]> git.jsancho.org Git - lugaru.git/commitdiff
Merge with p/lugaru
authorAlexander Monakov <amonakov@gmail.com>
Thu, 19 May 2011 07:11:43 +0000 (11:11 +0400)
committerAlexander Monakov <amonakov@gmail.com>
Thu, 19 May 2011 07:11:43 +0000 (11:11 +0400)
69 files changed:
CMakeLists.txt
Dependencies/libjpeg/jconfig.h
Source/Account.cpp [new file with mode: 0644]
Source/Account.h [new file with mode: 0644]
Source/Animation.cpp [new file with mode: 0644]
Source/Animation.def [new file with mode: 0644]
Source/Animation.h [new file with mode: 0644]
Source/Awards.cpp [new file with mode: 0644]
Source/Awards.def [new file with mode: 0644]
Source/Awards.h [new file with mode: 0644]
Source/Bonuses.def [new file with mode: 0644]
Source/Constants.h [deleted file]
Source/Game.cpp [new file with mode: 0644]
Source/Game.h
Source/GameDraw.cpp
Source/GameInitDispose.cpp
Source/GameTick.cpp
Source/Globals.cpp
Source/Input.cpp [new file with mode: 0644]
Source/Input.h [new file with mode: 0644]
Source/LinkedList.h [deleted file]
Source/MacCompatibility.h
Source/Models.cpp
Source/Models.h
Source/Objects.cpp
Source/Objects.h
Source/OpenGL_Windows.cpp
Source/Person.cpp
Source/Person.h
Source/Pointer.h [deleted file]
Source/Random.c [deleted file]
Source/Random.h
Source/Settings.cpp
Source/Skeleton.cpp
Source/Skeleton.h
Source/Skybox.cpp
Source/Skybox.h
Source/Sounds.cpp [new file with mode: 0644]
Source/Sounds.def [new file with mode: 0644]
Source/Sounds.h [new file with mode: 0644]
Source/Sprite.cpp [new file with mode: 0644]
Source/Sprite.h [new file with mode: 0644]
Source/Sprites.cpp [deleted file]
Source/Sprites.h [deleted file]
Source/TGALoader.cpp
Source/TGALoader.h
Source/Terrain.cpp
Source/Text.cpp
Source/Text.h
Source/Weapons.cpp
Source/Weapons.h
Source/WinDefs.cpp
Source/WinDefs.h
Source/WinInput.cpp [deleted file]
Source/WinInput.h [deleted file]
Source/gamegl.h
Source/glstubs.h
Source/mmgr.cpp [deleted file]
Source/mmgr.h [deleted file]
Source/nommgr.h [deleted file]
Source/nsp_network.c [deleted file]
Source/openal_wrapper.cpp
Source/openal_wrapper.h
Source/pack.c
Source/pack_private.c [deleted file]
Source/pack_private.h [deleted file]
Source/unpack.c
Source/unpack_private.c [deleted file]
Source/unpack_private.h [deleted file]

index 766bd3768640f4d3152b7458b5168d6b8a442499..4775a5ec9eeb1a6d75139967d163090259844df7 100644 (file)
@@ -52,6 +52,8 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
 
 set(LUGARU_SRCS
        ${SRCDIR}/Frustum.cpp
+       ${SRCDIR}/Account.cpp
+       ${SRCDIR}/Game.cpp
        ${SRCDIR}/GameDraw.cpp
        ${SRCDIR}/GameInitDispose.cpp
        ${SRCDIR}/GameTick.cpp
@@ -60,60 +62,58 @@ set(LUGARU_SRCS
        ${SRCDIR}/Models.cpp
        ${SRCDIR}/Objects.cpp
        ${SRCDIR}/pack.c
-       ${SRCDIR}/pack_private.c
        ${SRCDIR}/Person.cpp
        ${SRCDIR}/private.c
        ${SRCDIR}/Quaternions.cpp
-       ${SRCDIR}/Random.c
        ${SRCDIR}/Skeleton.cpp
        ${SRCDIR}/Skybox.cpp
-       ${SRCDIR}/Sprites.cpp
+       ${SRCDIR}/Sprite.cpp
        ${SRCDIR}/Terrain.cpp
        ${SRCDIR}/Text.cpp
        ${SRCDIR}/TGALoader.cpp
        ${SRCDIR}/unpack.c
-       ${SRCDIR}/unpack_private.c
        ${SRCDIR}/Weapons.cpp
        ${SRCDIR}/OpenGL_Windows.cpp
        ${SRCDIR}/openal_wrapper.cpp
-       ${SRCDIR}/WinInput.cpp
+       ${SRCDIR}/Input.cpp
        ${SRCDIR}/Settings.cpp
        ${SRCDIR}/Stereo.cpp
+       ${SRCDIR}/Animation.cpp
+       ${SRCDIR}/Sounds.cpp
+       ${SRCDIR}/Awards.cpp
 )
 
 set(LUGARU_H
-       ${SRCDIR}/Constants.h
        ${SRCDIR}/Frustum.h
+       ${SRCDIR}/Account.h
        ${SRCDIR}/Game.h
        ${SRCDIR}/Lights.h
-       ${SRCDIR}/LinkedList.h
        ${SRCDIR}/Models.h
        ${SRCDIR}/Objects.h
        ${SRCDIR}/Person.h
        ${SRCDIR}/PhysicsMath.h
-       ${SRCDIR}/Pointer.h
        ${SRCDIR}/Quaternions.h
        ${SRCDIR}/Random.h
        ${SRCDIR}/Skeleton.h
        ${SRCDIR}/Skybox.h
-       ${SRCDIR}/Sprites.h
+       ${SRCDIR}/Sprite.h
        ${SRCDIR}/TGALoader.h
        ${SRCDIR}/Terrain.h
        ${SRCDIR}/Text.h
        ${SRCDIR}/Weapons.h
-       ${SRCDIR}/WinInput.h
+       ${SRCDIR}/Input.h
        ${SRCDIR}/alstubs.h
        ${SRCDIR}/binio.h
        ${SRCDIR}/openal_wrapper.h
        ${SRCDIR}/gamegl.h
        ${SRCDIR}/glstubs.h
-       ${SRCDIR}/mmgr.h
-       ${SRCDIR}/nommgr.h
-       ${SRCDIR}/pack_private.h
        ${SRCDIR}/private.h
-       ${SRCDIR}/unpack_private.h
        ${SRCDIR}/Settings.h
        ${SRCDIR}/Stereo.h
+       ${SRCDIR}/Animation.h
+       ${SRCDIR}/Animation.def
+       ${SRCDIR}/Sounds.h
+       ${SRCDIR}/Sounds.def
 )
 
 if(UNIX)
@@ -496,7 +496,7 @@ include_directories(
     ${CMAKE_SOURCE_DIR}/Source
 )
 
-set(LUGARU_LIBS ${OPENAL_LIBRARY} ${PNG_LIBRARY} ${JPEG_LIBRARY} ${ZLIB_LIBRARIES} ${SDL_LIBRARY} ${GLU_LIBRARY} ${OPENGL_LIBRARY} ${VORBISFILE_LIBRARY} ${OGG_LIBRARY} ${PLATFORM_LIBS})
+set(LUGARU_LIBS ${OPENAL_LIBRARY} ${PNG_LIBRARY} ${JPEG_LIBRARY} ${ZLIB_LIBRARIES} ${SDL_LIBRARY} ${OPENGL_glu_LIBRARY} ${VORBISFILE_LIBRARY} ${OGG_LIBRARY} ${PLATFORM_LIBS})
 
 
 if(WIN32)
index 434f1ece1752737abbb50dbc31c786ecd5dbcb89..3700728843f7294e054fcc763803c59022e17fac 100644 (file)
@@ -4,10 +4,6 @@
 /* #define NEED_BSD_STRINGS -- causes fail on Win32 */
 #define NEED_SYS_TYPES_H
 
-#ifdef JPEG_INTERNALS
-#define INLINE inline
-#endif /* JPEG_INTERNALS */
-
 #ifdef JPEG_CJPEG_DJPEG
 #define BMP_SUPPORTED          /* BMP image file format */
 #define GIF_SUPPORTED          /* GIF image file format */
@@ -16,9 +12,3 @@
 #define TARGA_SUPPORTED                /* Targa image file format */
 #endif /* JPEG_CJPEG_DJPEG */
 
-#ifdef _MSC_VER
-#ifndef INLINE
-#define INLINE __inline__
-#endif
-#endif
-
diff --git a/Source/Account.cpp b/Source/Account.cpp
new file mode 100644 (file)
index 0000000..d601c4a
--- /dev/null
@@ -0,0 +1,221 @@
+/*
+Copyright (C) 2003, 2010 - Wolfire Games
+Copyright (C) 2010 - MCMic
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#include "Account.h"
+#include "binio.h"
+#include <fstream>
+#include "MacCompatibility.h"
+#include "string.h"
+
+using namespace std;
+
+extern bool debugmode;
+
+vector<Account*> Account::accounts = vector<Account*>();
+
+Account::Account(string n) {
+       name = string(n);
+       difficulty = 0;
+       progress = 0;
+       points = 0;
+       memset(highscore, 0, sizeof(highscore));
+       memset(fasttime, 0, sizeof(fasttime));
+       memset(unlocked, 0, sizeof(unlocked));
+       campaignhighscore = 0;
+       campaignfasttime = 0;
+       campaignscore = 0;
+       campaigntime = 0;
+       campaignchoicesmade = 0;
+       memset(campaignchoices, 0, sizeof(campaignchoices));
+}
+
+Account* Account::add(string name) {
+       accounts.push_back(new Account(name));
+       return accounts.back();
+}
+
+Account* Account::get(int i) {
+       if(i<accounts.size()) {
+               return accounts[i];
+       } else
+               return NULL;
+}
+
+void Account::destroy(int i) {
+       accounts.erase(accounts.begin()+i);
+}
+Account* Account::destroy(Account* a) {
+       for(int i=0; i<accounts.size(); i++) {
+               if(accounts[i]==a) {
+                       accounts.erase(accounts.begin()+i);
+                       return NULL;
+               }
+       }
+       printf("Unexpected error : User %s not found %d\n",a->getName(),a);
+       return accounts.front();
+}
+
+int Account::getDifficulty() {
+       return difficulty;
+}
+
+void Account::endGame() {
+       campaignchoicesmade=0;
+       campaignscore=0;
+       campaigntime=0;
+}
+
+void Account::winCampaignLevel(int choice, float score, float time) {
+       campaignchoices[campaignchoicesmade++] = choice;
+       setCampaignScore(campaignscore+score);
+       campaigntime = time;
+}
+
+void Account::winLevel(int level, float score, float time) {
+       if(!debugmode) {
+               if(score>highscore[level])
+                       highscore[level]=score;
+               if(time<fasttime[level]||fasttime[level]==0)
+                       fasttime[level]=time;
+       }
+       if(progress<level+1)
+               progress=level+1;
+}
+
+Account* Account::loadFile(string filename) {
+       FILE *tfile;
+       int numaccounts;
+       int accountactive;
+       int j;
+       
+       tfile=fopen(ConvertFileName(filename.c_str()), "rb" );
+       
+       if(tfile)
+       {
+               funpackf(tfile, "Bi", &numaccounts);
+               funpackf(tfile, "Bi", &accountactive);
+               printf("number of accounts %d\n",numaccounts);
+               for(int i=0;i<numaccounts;i++)
+               {
+                       printf("loading account %d/%d\n",i,numaccounts);
+                       Account* acc = new Account();
+                       funpackf(tfile, "Bf", &(acc->campaigntime));
+                       funpackf(tfile, "Bf", &(acc->campaignscore));
+                       funpackf(tfile, "Bf", &(acc->campaignfasttime));
+                       funpackf(tfile, "Bf", &(acc->campaignhighscore));
+                       funpackf(tfile, "Bi", &(acc->difficulty));
+                       funpackf(tfile, "Bi", &(acc->progress));
+                       funpackf(tfile, "Bi", &(acc->campaignchoicesmade));
+                       for(j=0;j<acc->campaignchoicesmade;j++)
+                       {
+                               funpackf(tfile, "Bi", &(acc->campaignchoices[j]));
+                               if (acc->campaignchoices[j] >= 10)
+                               {
+                                       acc->campaignchoices[j] = 0;
+                               }
+                       }
+                       funpackf(tfile, "Bf", &(acc->points));
+                       for(j=0;j<50;j++)
+                       {
+                               funpackf(tfile, "Bf", &(acc->highscore[j]));
+                               funpackf(tfile, "Bf", &(acc->fasttime[j]));
+                       }
+                       for(j=0;j<60;j++)
+                       {
+                               funpackf(tfile, "Bb",  &(acc->unlocked[j]));
+                       }
+                       int temp;
+                       char ctemp;
+                       funpackf(tfile, "Bi",  &temp);
+                       for(j=0;j<temp;j++)
+                       {
+                               funpackf(tfile, "Bb",  &ctemp);
+                               acc->name.append(1,ctemp);
+                       }
+                       if(!strcmp(acc->name.c_str(),""))
+                               acc->name="Lugaru Player"; // no empty player name security.
+                       accounts.push_back(acc);
+               }
+
+               fclose(tfile);
+               return get(accountactive);
+       } else {
+               printf("filenotfound\n");
+               return NULL;
+       }
+}
+
+void Account::saveFile(string filename, Account* accountactive) {
+       FILE *tfile;
+       int numaccounts;
+       int j;
+       
+       tfile=fopen(ConvertFileName(filename.c_str(), "wb"), "wb" );
+       if(tfile)
+       {
+               printf("writing %d accounts :\n",getNbAccounts());
+               fpackf(tfile, "Bi", getNbAccounts());
+               fpackf(tfile, "Bi", indice(accountactive));
+               
+               for(int i=0;i<getNbAccounts();i++)
+               {
+                       Account* a = Account::get(i);
+                       printf("writing account %d/%d (%s)\n",i+1,getNbAccounts(),a->getName());
+                       fpackf(tfile, "Bf", a->campaigntime);
+                       fpackf(tfile, "Bf", a->campaignscore);
+                       fpackf(tfile, "Bf", a->campaignfasttime);
+                       fpackf(tfile, "Bf", a->campaignhighscore);
+                       fpackf(tfile, "Bi", a->difficulty);
+                       fpackf(tfile, "Bi", a->progress);
+                       fpackf(tfile, "Bi", a->campaignchoicesmade);
+                       for(j=0;j<a->campaignchoicesmade;j++)
+                       {
+                               fpackf(tfile, "Bi", a->campaignchoices[j]);
+                       }
+                       fpackf(tfile, "Bf", a->points);
+                       for(j=0;j<50;j++)
+                       {
+                               fpackf(tfile, "Bf", a->highscore[j]);
+                               fpackf(tfile, "Bf", a->fasttime[j]);
+                       }
+                       for(j=0;j<60;j++)
+                       {
+                               fpackf(tfile, "Bb",  a->unlocked[j]);
+                       }
+                       fpackf(tfile, "Bi",  a->name.size());
+                       for(j=0;j<a->name.size();j++)
+                       {
+                               fpackf(tfile, "Bb",  a->name[j]);
+                       }
+               }
+
+               fclose(tfile);
+       }
+}
+
+int Account::indice(Account* a) {
+       for(int i=0; i < accounts.size(); i++) {
+               if(accounts[i]==a)
+                       return i;
+       }
+       return -1;
+}
diff --git a/Source/Account.h b/Source/Account.h
new file mode 100644 (file)
index 0000000..3cf94dd
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+Copyright (C) 2003, 2010 - Wolfire Games
+Copyright (C) 2010 - MCMic
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifndef _Account_H_
+#define _Account_H_
+
+#include <vector>
+#include <string>
+#include <fstream>
+
+
+class Account {
+       public:
+               static void destroy(int i);
+               static Account* destroy(Account* a);
+               static Account* add(std::string name);
+               static Account* get(int i);
+               static Account* loadFile(std::string filename);
+               static void saveFile(std::string filename, Account* accountactive);
+               static int indice(Account* a);
+               
+               void endGame();
+               void winCampaignLevel(int choice, float score, float time);
+               void winLevel(int level, float score, float time);
+               
+               // getter and setters
+               int getDifficulty();
+               void setDifficulty(int i) { difficulty = i; };
+               const char* getName() { return name.c_str(); };
+               float getCampaignScore() { return campaignscore; };
+               int getCampaignChoicesMade() { return campaignchoicesmade; };
+               int getCampaignChoice(int i) { return campaignchoices[i]; };
+               void setCampaignScore(int s) {
+                       campaignscore=s;
+                       if(s>campaignhighscore)
+                               campaignhighscore=s;
+               };
+               void setCampaignFinalTime(float t) {
+                               campaigntime = t;
+                               if((t<campaignfasttime) || (campaignfasttime==0) && (t!=0))
+                                       campaignfasttime = t;
+               };
+               float getCampaignFasttime() { return campaignfasttime; };
+               void resetFasttime() { campaignfasttime = 0; };
+               float getCampaignHighScore() { return campaignhighscore; };
+               float getHighScore(int i) { return highscore[i]; };
+               float getFastTime(int i) { return fasttime[i]; };
+               int getProgress() { return progress; };
+               
+               static int getNbAccounts() { return accounts.size(); };
+       private:
+               Account(std::string n="");
+               int difficulty;
+               int progress;
+               float points;
+               float highscore[50];
+               float fasttime[50];
+               bool unlocked[60];
+               std::string name;
+               float campaignhighscore;
+               float campaignfasttime;
+               float campaignscore;
+               float campaigntime;
+               int campaignchoicesmade;
+               int campaignchoices[5000]; // should really disappear. I'd use a vector or something like that.
+       
+       //statics
+               static std::vector<Account*> accounts;
+};
+
+#endif
diff --git a/Source/Animation.cpp b/Source/Animation.cpp
new file mode 100644 (file)
index 0000000..4e5a65f
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#include "Skeleton.h"
+#include "Animation.h"
+
+struct animation_data_elt
+{
+  const char *filename;
+  int height;
+  int attack;
+};
+
+static animation_data_elt animation_data[animation_count] = {
+#define DECLARE_ANIM(id, file, height, attack, ...) {file, height, attack},
+#include "Animation.def"
+#undef DECLARE_ANIM
+};
+
+void loadAllAnimations()
+{
+  for (int i = 0; i < loadable_anim_end; i++)
+    {
+      animation_data_elt *e = animation_data + i;
+      animation[i].Load(e->filename, e->height, e->attack);
+    }
+}
diff --git a/Source/Animation.def b/Source/Animation.def
new file mode 100644 (file)
index 0000000..30f2450
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifdef DECLARE_ANIM_BIT
+DECLARE_ANIM_BIT(ab_idle)
+DECLARE_ANIM_BIT(ab_sit)
+DECLARE_ANIM_BIT(ab_sleep)
+DECLARE_ANIM_BIT(ab_crouch)
+DECLARE_ANIM_BIT(ab_run)
+DECLARE_ANIM_BIT(ab_stop)
+DECLARE_ANIM_BIT(ab_land)
+DECLARE_ANIM_BIT(ab_landhard)
+DECLARE_ANIM_BIT(ab_flip)
+DECLARE_ANIM_BIT(ab_walljump)
+#endif
+
+#ifdef DECLARE_ANIM
+DECLARE_ANIM(runanim, "Run", middleheight, neutral, ab_run)
+DECLARE_ANIM(bounceidleanim, "Idle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(stopanim, "Stop", middleheight, neutral, ab_stop)
+DECLARE_ANIM(jumpupanim, "JumpUp", highheight, neutral, 0)
+DECLARE_ANIM(jumpdownanim, "JumpDown", highheight, neutral, 0)
+DECLARE_ANIM(landanim, "Landing", lowheight, neutral, ab_land)
+DECLARE_ANIM(landhardanim, "Landhard", lowheight, neutral, ab_landhard)
+DECLARE_ANIM(climbanim, "Climb", lowheight, neutral, 0)
+DECLARE_ANIM(hanganim, "Hangon", lowheight, neutral, 0)
+DECLARE_ANIM(spinkickanim, "SpinKick", middleheight, normalattack, 0)
+DECLARE_ANIM(getupfromfrontanim, "GetUpFromFront", lowheight, neutral, 0)
+DECLARE_ANIM(getupfrombackanim, "GetUpFromBack", lowheight, neutral, 0)
+DECLARE_ANIM(crouchanim, "Crouch", lowheight, neutral, ab_crouch)
+DECLARE_ANIM(sneakanim, "Sneak", lowheight, neutral, 0)
+DECLARE_ANIM(rollanim, "Roll", lowheight, neutral, 0)
+DECLARE_ANIM(flipanim, "Flip", highheight, neutral, ab_flip)
+DECLARE_ANIM(frontflipanim, "Flip", highheight, neutral, ab_flip)
+DECLARE_ANIM(spinkickreversedanim, "SpinKickCaught", middleheight, reversed, 0)
+DECLARE_ANIM(spinkickreversalanim, "SpinKickCatch", middleheight, reversal, 0)
+DECLARE_ANIM(lowkickanim, "lowkick", middleheight, normalattack, 0)
+DECLARE_ANIM(sweepanim, "sweep", lowheight, normalattack, 0)
+DECLARE_ANIM(sweepreversedanim, "SweepCaught", lowheight, reversed, 0)
+DECLARE_ANIM(sweepreversalanim, "SweepCatch", middleheight, reversal, 0)
+DECLARE_ANIM(rabbitkickanim, "RabbitKick", middleheight, normalattack, 0)
+DECLARE_ANIM(rabbitkickreversedanim, "RabbitKickCaught", middleheight, reversed, 0)
+DECLARE_ANIM(rabbitkickreversalanim, "RabbitKickCatch", lowheight, reversal, 0)
+DECLARE_ANIM(upunchanim, "Upunch", middleheight, normalattack, 0)
+DECLARE_ANIM(staggerbackhighanim, "Staggerbackhigh", middleheight, neutral, 0)
+DECLARE_ANIM(upunchreversedanim, "UpunchCaught", middleheight, reversed, 0)
+DECLARE_ANIM(upunchreversalanim, "UpunchCatch", middleheight, reversal, 0)
+DECLARE_ANIM(hurtidleanim, "Hurtidle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(backhandspringanim, "Backhandspring", middleheight, neutral, 0)
+DECLARE_ANIM(fightidleanim, "Fightidle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(walkanim, "Walk", middleheight, neutral, 0)
+DECLARE_ANIM(fightsidestep, "Fightsidestep", middleheight, neutral, ab_idle)
+DECLARE_ANIM(killanim, "Kill", middleheight, normalattack, 0)
+DECLARE_ANIM(sneakattackanim, "Sneakattack", middleheight, reversal, 0)
+DECLARE_ANIM(sneakattackedanim, "Sneakattacked", middleheight, reversed, 0)
+DECLARE_ANIM(drawrightanim, "drawright", middleheight, neutral, 0)
+DECLARE_ANIM(knifeslashstartanim, "slashstart", middleheight, normalattack, 0)
+DECLARE_ANIM(crouchdrawrightanim, "crouchdrawright", lowheight, neutral, 0)
+DECLARE_ANIM(crouchstabanim, "crouchstab", lowheight, normalattack, 0)
+DECLARE_ANIM(knifefollowanim, "slashfollow", middleheight, reversal, 0)
+DECLARE_ANIM(knifefollowedanim, "slashfollowed", middleheight, reversed, 0)
+DECLARE_ANIM(knifethrowanim, "knifethrow", middleheight, normalattack, 0)
+DECLARE_ANIM(removeknifeanim, "removeknife", middleheight, neutral, 0)
+DECLARE_ANIM(crouchremoveknifeanim, "crouchremoveknife", lowheight, neutral, 0)
+DECLARE_ANIM(jumpreversedanim, "JumpCaught", middleheight, reversed, 0)
+DECLARE_ANIM(jumpreversalanim, "JumpCatch", middleheight, reversal, 0)
+DECLARE_ANIM(staggerbackhardanim, "Staggerbackhard", middleheight, neutral, 0)
+DECLARE_ANIM(dropkickanim, "Dropkick", middleheight, normalattack, 0)
+DECLARE_ANIM(winduppunchanim, "Winduppunch", middleheight, normalattack, 0)
+DECLARE_ANIM(winduppunchblockedanim, "Winduppunchblocked", middleheight, normalattack, 0)
+DECLARE_ANIM(blockhighleftanim, "Blockhighleft", middleheight, normalattack, 0)
+DECLARE_ANIM(blockhighleftstrikeanim, "Blockhighleftstrike", middleheight, normalattack, 0)
+DECLARE_ANIM(backflipanim, "Backflip", highheight, neutral, ab_flip)
+DECLARE_ANIM(walljumpbackanim, "Walljumpback", highheight, neutral, ab_walljump)
+DECLARE_ANIM(walljumpfrontanim, "Walljumpfront", highheight, neutral, ab_walljump)
+DECLARE_ANIM(rightflipanim, "Rightflip", highheight, neutral, ab_flip)
+DECLARE_ANIM(walljumprightanim, "Walljumpright", highheight, neutral, ab_walljump)
+DECLARE_ANIM(leftflipanim, "Leftflip", highheight, neutral, ab_flip)
+DECLARE_ANIM(walljumpleftanim, "Walljumpleft", highheight, neutral, ab_walljump)
+DECLARE_ANIM(walljumprightkickanim, "Walljumprightkick", highheight, neutral, ab_flip)
+DECLARE_ANIM(walljumpleftkickanim, "Walljumpleftkick", highheight, neutral, ab_flip)
+DECLARE_ANIM(knifefightidleanim, "Knifefightidle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(knifesneakattackanim, "Knifesneakattack", middleheight, reversal, 0)
+DECLARE_ANIM(knifesneakattackedanim, "Knifesneakattacked", middleheight, reversed, 0)
+DECLARE_ANIM(swordfightidleanim, "swordfightidle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(drawleftanim, "drawleft", middleheight, neutral, 0)
+DECLARE_ANIM(swordslashanim, "swordslash", middleheight, normalattack, 0)
+DECLARE_ANIM(swordgroundstabanim, "swordgroundstab", lowheight, normalattack, 0)
+DECLARE_ANIM(dodgebackanim, "dodgeback", middleheight, neutral, 0)
+DECLARE_ANIM(swordsneakattackanim, "Swordsneakattack", middleheight, reversal, 0)
+DECLARE_ANIM(swordsneakattackedanim, "Swordsneakattacked", middleheight, reversed, 0)
+DECLARE_ANIM(swordslashreversedanim, "swordslashCaught", middleheight, reversed, 0)
+DECLARE_ANIM(swordslashreversalanim, "swordslashCatch", middleheight, reversal, 0)
+DECLARE_ANIM(knifeslashreversedanim, "knifeslashCaught", middleheight, reversed, 0)
+DECLARE_ANIM(knifeslashreversalanim, "knifeslashCatch", middleheight, reversal, 0)
+DECLARE_ANIM(swordfightidlebothanim, "swordfightidleboth", middleheight, neutral, ab_idle)
+DECLARE_ANIM(swordslashparryanim, "sworduprightparry", middleheight, normalattack, 0)
+DECLARE_ANIM(swordslashparriedanim, "swordslashparried", middleheight, normalattack, 0)
+DECLARE_ANIM(wolfidle, "Wolfidle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(wolfcrouchanim, "Wolfcrouch", lowheight, neutral, ab_crouch)
+DECLARE_ANIM(wolflandanim, "Wolflanding", lowheight, neutral, ab_land)
+DECLARE_ANIM(wolflandhardanim, "Wolflandhard", lowheight, neutral, ab_landhard)
+DECLARE_ANIM(wolfrunanim, "Wolfrun", middleheight, neutral, ab_run)
+DECLARE_ANIM(wolfrunninganim, "Wolfrunning", middleheight, neutral, ab_run)
+DECLARE_ANIM(rabbitrunninganim, "Rabbitrunning", middleheight, neutral, ab_run)
+DECLARE_ANIM(wolfstopanim, "Wolfstop", middleheight, neutral, ab_stop)
+DECLARE_ANIM(rabbittackleanim, "Rabbittackle", middleheight, neutral, 0)
+DECLARE_ANIM(rabbittacklinganim, "Rabbittackling", middleheight, reversal, 0)
+DECLARE_ANIM(rabbittackledbackanim, "Rabbittackledback", middleheight, reversed, 0)
+DECLARE_ANIM(rabbittackledfrontanim, "Rabbittackledfront", middleheight, reversed, 0)
+DECLARE_ANIM(wolfslapanim, "Wolfslap", middleheight, normalattack, 0)
+DECLARE_ANIM(staffhitanim, "StaffHit", middleheight, normalattack, 0)
+DECLARE_ANIM(staffgroundsmashanim, "StaffGroundSmash", lowheight, normalattack, 0)
+DECLARE_ANIM(staffspinhitanim, "Spinwhack", middleheight, normalattack, 0)
+DECLARE_ANIM(staffhitreversedanim, "StaffHitCaught", middleheight, reversed, 0)
+DECLARE_ANIM(staffhitreversalanim, "StaffHitCatch", middleheight, reversal, 0)
+DECLARE_ANIM(staffspinhitreversedanim, "SpinWhackCaught", middleheight, reversed, 0)
+DECLARE_ANIM(staffspinhitreversalanim, "SpinWhackCatch", middleheight, reversal, 0)
+DECLARE_ANIM(sitanim, "Sit", lowheight, neutral, ab_idle | ab_sit)
+DECLARE_ANIM(sleepanim, "Sleep", lowheight, neutral, ab_idle | ab_sleep)
+DECLARE_ANIM(talkidleanim, "TalkIdle", middleheight, neutral, ab_idle)
+DECLARE_ANIM(sitwallanim, "Dying", lowheight, neutral, ab_sit)
+DECLARE_ANIM(dead1anim, "Dead1", lowheight, neutral, ab_sleep)
+DECLARE_ANIM(dead2anim, "Dead2", lowheight, neutral, ab_sleep)
+DECLARE_ANIM(dead3anim, "Dead3", lowheight, neutral, ab_sleep)
+DECLARE_ANIM(dead4anim, "Dead4", lowheight, neutral, ab_sleep)
+
+DECLARE_ANIM(loadable_anim_end, "", 0, 0, 0)
+
+/* Not implemented.  */
+DECLARE_ANIM(rabbittacklereversal, "", 0, 0, 0)
+DECLARE_ANIM(rabbittacklereversed, "", 0, 0, 0)
+DECLARE_ANIM(sworddisarmanim, "", 0, 0, 0)
+DECLARE_ANIM(swordslashleftanim, "", 0, 0, 0)
+DECLARE_ANIM(swordslashrightanim, "", 0, 0, 0)
+DECLARE_ANIM(swordstabanim, "", 0, 0, 0)
+DECLARE_ANIM(wolfbashanim, "", 0, 0, 0)
+DECLARE_ANIM(wolfclawanim, "", 0, 0, 0)
+DECLARE_ANIM(wolffightidle, "", 0, 0, 0)
+DECLARE_ANIM(wolfhurtidle, "", 0, 0, 0)
+DECLARE_ANIM(wolfsneakanim, "", 0, 0, 0)
+DECLARE_ANIM(wolfswordidle, "", 0, 0, 0)
+DECLARE_ANIM(wolftackleanim, "", 0, 0, 0)
+DECLARE_ANIM(wolftackledbacanim, "", 0, 0, 0)
+DECLARE_ANIM(wolftackledfrontanim, "", 0, 0, 0)
+DECLARE_ANIM(wolftacklereversal, "", 0, 0, 0)
+DECLARE_ANIM(wolftacklereversed, "", 0, 0, 0)
+DECLARE_ANIM(wolftacklinganim, "", 0, 0, 0)
+
+DECLARE_ANIM(tempanim, "", 0, 0, 0)
+#endif
diff --git a/Source/Animation.h b/Source/Animation.h
new file mode 100644 (file)
index 0000000..668cac3
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifndef ANIMATION_H
+#define        ANIMATION_H
+
+enum anim_attack_type {
+  neutral, normalattack, reversed, reversal
+};
+
+enum anim_height_type {
+  lowheight, middleheight, highheight
+};
+
+
+enum animation_types {
+#define DECLARE_ANIM(id, ...) id,
+#include "Animation.def"
+#undef DECLARE_ANIM
+animation_count
+};
+
+enum animation_bit_offsets {
+#define DECLARE_ANIM_BIT(bit) o_##bit,
+#include "Animation.def"
+#undef DECLARE_ANIM_BIT
+animation_bit_count
+};
+
+enum animation_bits_def {
+#define DECLARE_ANIM_BIT(bit) bit = 1 << o_##bit,
+#include "Animation.def"
+#undef DECLARE_ANIM_BIT
+};
+
+static const int animation_bits[animation_count] = {
+#define DECLARE_ANIM(id, name, height, type, bits) bits,
+#include "Animation.def"
+#undef DECLARE_ANIM
+};
+
+extern Animation animation[animation_count];
+
+extern void loadAllAnimations();
+#endif
diff --git a/Source/Awards.cpp b/Source/Awards.cpp
new file mode 100644 (file)
index 0000000..cbfe381
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#include "Awards.h"
+#include "Person.h"
+#include "Game.h"
+
+int bonus;
+float bonusvalue;
+float bonustotal;
+float startbonustotal;
+float bonustime;
+float bonusnum[100];
+
+static const int bonus_values[bonus_count] = {
+#define DECLARE_BONUS(id, name, value, ...) value,
+#include "Bonuses.def"
+#undef DECLARE_BONUS
+};
+
+void
+award_bonus(int playerid, int bonusid, int alt_value)
+{
+  if (playerid != 0)
+    return;
+  bonus = bonusid;
+  bonustime = 0;
+  bonusvalue = alt_value ? alt_value : bonus_values[bonusid];
+}
+
+// FIXME: make these per-player
+float damagetaken;
+int numfalls;
+int numflipfail;
+int numseen;
+int numresponded;
+int numstaffattack;
+int numswordattack;
+int numknifeattack;
+int numunarmedattack;
+int numescaped;
+int numflipped;
+int numwallflipped;
+int numthrowkill;
+int numafterkill;
+int numreversals;
+int numattacks;
+int maxalarmed;
+
+int award_awards(int *awards)
+{
+  int numawards = 0, i;
+  if(damagetaken==0&&player[0].bloodloss==0){
+    awards[numawards]=awardflawless;
+    numawards++;
+  }
+  bool alldead = true;
+  for(i=1;i<numplayers;i++){
+    if(player[i].dead!=2)alldead=0;
+  }
+  if(alldead){
+    awards[numawards]=awardalldead;
+    numawards++;
+  }
+  alldead=1;
+  for(i=1;i<numplayers;i++){
+    if(player[i].dead!=1)alldead=0;
+  }
+  if(alldead){
+    awards[numawards]=awardnodead;
+    numawards++;
+  }
+  if(numresponded==0&&!numthrowkill){
+    awards[numawards]=awardstealth;
+    numawards++;
+  }
+  if(numattacks==numstaffattack&&numattacks>0){
+    awards[numawards]=awardbojutsu;
+    numawards++;
+  }
+  if(numattacks==numswordattack&&numattacks>0){
+    awards[numawards]=awardswordsman;
+    numawards++;
+  }
+  if(numattacks==numknifeattack&&numattacks>0){
+    awards[numawards]=awardknifefighter;
+    numawards++;
+  }
+  if(numattacks==numunarmedattack&&numthrowkill==0&&weapons.numweapons>0){
+    awards[numawards]=awardkungfu;
+    numawards++;
+  }
+  if(numescaped>0){
+    awards[numawards]=awardevasion;
+    numawards++;
+  }
+  if(numflipfail==0&&numflipped+numwallflipped*2>20){
+    awards[numawards]=awardacrobat;
+    numawards++;
+  }
+  if(numthrowkill==numplayers-1){
+    awards[numawards]=awardlongrange;
+    numawards++;
+  }
+  alldead=1;
+  for(i=1;i<numplayers;i++){
+    if(player[i].dead!=2)alldead=0;
+  }
+  if(numafterkill>0&&alldead){
+    awards[numawards]=awardbrutal;
+    numawards++;
+  }
+  if(numreversals>((float)numattacks)*.8&&numreversals>3){
+    awards[numawards]=awardaikido;
+    numawards++;
+  }
+  if(maxalarmed==1&&numplayers>2){
+    awards[numawards]=awardstrategy;
+    numawards++;
+  }
+  if(numflipfail>3){
+    awards[numawards]=awardklutz;
+    numawards++;
+  }
+  return numawards;
+}
diff --git a/Source/Awards.def b/Source/Awards.def
new file mode 100644 (file)
index 0000000..f2bfe22
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+DECLARE_AWARD(awardklutz, "Suicidal")
+DECLARE_AWARD(awardflawless, "Flawless!")
+DECLARE_AWARD(awardalldead, "Take no prisoners")
+DECLARE_AWARD(awardnodead, "Merciful")
+DECLARE_AWARD(awardstealth, "One with the shadows!")
+DECLARE_AWARD(awardswordsman, "Swordsman")
+DECLARE_AWARD(awardkungfu, "Unarmed!")
+DECLARE_AWARD(awardknifefighter, "Knife fighter")
+DECLARE_AWARD(awardcoward, "Coward")
+DECLARE_AWARD(awardevasion, "Escape artist")
+DECLARE_AWARD(awardacrobat, "Gymnast")
+DECLARE_AWARD(awardlongrange, "Blade slinger")
+DECLARE_AWARD(awardbrutal, "Brutal")
+DECLARE_AWARD(awardhyper, "Hyper")
+DECLARE_AWARD(awardaikido, "Aikido master!")
+DECLARE_AWARD(awardrambo, "Rambo")
+DECLARE_AWARD(awardfast, "Fast")
+DECLARE_AWARD(awardrealfast, "Real fast")
+DECLARE_AWARD(awarddamnfast, "Damn fast")
+DECLARE_AWARD(awardstrategy, "Divide and conquer")
+DECLARE_AWARD(awardbojutsu, "Bojutsu")
diff --git a/Source/Awards.h b/Source/Awards.h
new file mode 100644 (file)
index 0000000..83b61c0
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifndef AWARDS_H
+#define AWARDS_H
+
+enum bonus_types {
+#define DECLARE_BONUS(id, ...) id,
+#include "Bonuses.def"
+#undef DECLARE_BONUS
+bonus_count
+};
+
+static const char *bonus_names[bonus_count] = {
+#define DECLARE_BONUS(id, name, ...) name,
+#include "Bonuses.def"
+#undef DECLARE_BONUS
+};
+
+extern int bonus;
+extern float bonusvalue;
+extern float bonustotal;
+extern float bonustime;
+extern float startbonustotal;
+extern float bonusnum[100];
+
+extern void award_bonus(int playerid, int bonusid, int alt_value = 0);
+
+enum award_types {
+#define DECLARE_AWARD(id, name) id,
+#include "Awards.def"
+#undef DECLARE_AWARD
+award_count
+};
+
+static const char *award_names[award_count] = {
+#define DECLARE_AWARD(id, name) name,
+#include "Awards.def"
+#undef DECLARE_AWARD
+};
+
+extern int award_awards(int *);
+
+extern float damagetaken;
+extern int numfalls;
+extern int numflipfail;
+extern int numseen;
+extern int numresponded;
+extern int numstaffattack;
+extern int numswordattack;
+extern int numknifeattack;
+extern int numunarmedattack;
+extern int numescaped;
+extern int numflipped;
+extern int numwallflipped;
+extern int numthrowkill;
+extern int numafterkill;
+extern int numreversals;
+extern int numattacks;
+extern int maxalarmed;
+#endif
+
diff --git a/Source/Bonuses.def b/Source/Bonuses.def
new file mode 100644 (file)
index 0000000..1604f24
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+DECLARE_BONUS(nobonus, "", 0)
+DECLARE_BONUS(tracheotomy, "Tracheotomy!", 100)
+DECLARE_BONUS(backstab, "Backstabber!", 100)
+DECLARE_BONUS(spinecrusher, "Spinecrusher!", 100)
+DECLARE_BONUS(ninja, "Ninja Bonus!", 60)
+DECLARE_BONUS(style, "Style Bonus!", 150)
+DECLARE_BONUS(cannon, "Leg Cannon!", 100)
+DECLARE_BONUS(aimbonus, "Nice Aim!", 150)
+DECLARE_BONUS(deepimpact, "Heavy Impact!", 50)
+DECLARE_BONUS(touchofdeath, "Touch of Death!", 150)
+DECLARE_BONUS(swordreversebonus, "Sword Disarm!", 100)
+DECLARE_BONUS(staffreversebonus, "Staff Disarm!", 100)
+DECLARE_BONUS(reverseko, "Reversal KO!", 100)
+// The following five should be kept in that order
+DECLARE_BONUS(solidhit, "Solid Hit!", 10)
+DECLARE_BONUS(twoxcombo, "2X Combo!", 20)
+DECLARE_BONUS(threexcombo, "3X Combo!", 40)
+DECLARE_BONUS(fourxcombo, "4X COMBO!", 80)
+DECLARE_BONUS(megacombo, "MEGA COMBO!", 160)
+DECLARE_BONUS(Reversal, "Reversal!", 60)
+DECLARE_BONUS(Stabbonus, "Punctured!", 40)
+DECLARE_BONUS(Slicebonus, "Sliced!", 10)
+DECLARE_BONUS(Bullseyebonus, "Bullseye!", 30)
+DECLARE_BONUS(Slashbonus, "Slashed!", 40)
+DECLARE_BONUS(Wolfbonus, "WOLF SLAYER!", 300)
+DECLARE_BONUS(FinishedBonus, "SLAIN!", 200)
+DECLARE_BONUS(TackleBonus, "Tackle!", 5)
+DECLARE_BONUS(AboveBonus, "Death from Above!", 50)
diff --git a/Source/Constants.h b/Source/Constants.h
deleted file mode 100644 (file)
index 6769328..0000000
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#ifndef _CONSTANTS_H_
-#define _CONSTANTS_H_
-
-// cat src/Constants.h | sed -e 's/#define/const int/' -e 's/ [0-9]*$/ =&;/'
-// chew on that --Jookia
-
-const int awardklutz = 0;
-const int awardflawless = 1;
-const int awardalldead = 2;
-const int awardnodead = 3;
-const int awardstealth = 4;
-const int awardswordsman = 5;
-const int awardkungfu = 6;
-const int awardknifefighter = 7;
-const int awardcoward = 8;
-const int awardevasion = 9;
-const int awardacrobat = 10;
-const int awardlongrange = 11;
-const int awardbrutal = 12;
-const int awardhyper = 13;
-const int awardaikido = 14;
-const int awardrambo = 15;
-const int awardfast = 16;
-const int awardrealfast = 17;
-const int awarddamnfast = 18;
-const int awardstrategy = 19;
-const int awardbojutsu = 20;
-
-const int mapkilleveryone = 0;
-const int mapgosomewhere = 1;
-const int mapkillsomeone = 2;
-const int mapkillmost = 3;
-
-enum pathtypes {wpkeepwalking, wppause};
-
-static const char *pathtypenames[] = {"keepwalking", "pause"};
-
-enum editortypes {typeactive, typesitting, typesittingwall, typesleeping,
-                 typedead1, typedead2, typedead3, typedead4};
-
-static const char *editortypenames[] = {
-  "active", "sitting", "sitting wall", "sleeping",
-  "dead1", "dead2", "dead3", "dead4"
-};
-
-const int tracheotomy = 1;
-const int backstab = 2;
-const int spinecrusher = 3;
-const int ninja = 4;
-const int style = 5;
-const int cannon = 6;
-const int aimbonus = 7;
-const int deepimpact = 8;
-const int touchofdeath = 9;
-const int swordreversebonus = 10;
-const int staffreversebonus = 11;
-const int reverseko = 12;
-const int solidhit = 13;
-const int twoxcombo = 14;
-const int threexcombo = 15;
-const int fourxcombo = 16;
-const int megacombo = 17;
-const int Reversal = 18;
-const int Stabbonus = 19;
-const int Slicebonus = 20;
-const int Bullseyebonus = 21;
-const int Slashbonus = 22;
-const int Wolfbonus = 23;
-const int FinishedBonus = 24;
-const int TackleBonus = 25;
-const int AboveBonus = 26;
-
-const int boneconnect = 0;
-const int constraint = 1;
-const int muscle = 2;
-
-const int head = 0; // DO NOT CONFLICT WITH ZLIB's variable head
-const int neck = 1;
-const int leftshoulder = 2;
-const int leftelbow = 3;
-const int leftwrist = 4;
-const int lefthand = 5;
-const int rightshoulder = 6;
-const int rightelbow = 7;
-const int rightwrist = 8;
-const int righthand = 9;
-const int abdomen = 10;
-const int lefthip = 11;
-const int righthip = 12;
-const int groin = 13;
-const int leftknee = 14;
-const int leftankle = 15;
-const int leftfoot = 16;
-const int rightknee = 17;
-const int rightankle = 18;
-const int rightfoot = 19;
-
-const int max_joints = 50;
-const int max_frames = 50;
-const int max_muscles = 100;
-
-const int animation_count = 140;
-
-const int runanim = 0;
-const int bounceidleanim = 1;
-const int stopanim = 2;
-const int jumpupanim = 3;
-const int jumpdownanim = 4;
-const int landanim = 5;
-const int climbanim = 6;
-const int hanganim = 7;
-const int spinkickanim = 8;
-const int tempanim = 9;
-const int getupfromfrontanim = 10;
-const int getupfrombackanim = 11;
-const int crouchanim = 12;
-const int sneakanim = 13;
-const int rollanim = 14;
-const int flipanim = 15;
-const int spinkickreversedanim = 16;
-const int spinkickreversalanim = 17;
-const int lowkickanim = 18;
-const int sweepanim = 19;
-const int sweepreversedanim = 20;
-const int sweepreversalanim = 21;
-const int rabbitkickanim = 22;
-const int rabbitkickreversedanim = 23;
-const int rabbitkickreversalanim = 24;
-const int upunchanim = 25;
-const int staggerbackhighanim = 26;
-const int upunchreversedanim = 27;
-const int upunchreversalanim = 28;
-const int hurtidleanim = 29;
-const int backhandspringanim = 30;
-const int fightidleanim = 31;
-const int walkanim = 32;
-const int fightsidestep = 33;
-const int killanim = 34;
-const int sneakattackanim = 35;
-const int sneakattackedanim = 36;
-const int drawrightanim = 37;
-const int knifeslashstartanim = 38;
-const int crouchstabanim = 39;
-const int crouchdrawrightanim = 40;
-const int knifefollowanim = 41;
-const int knifefollowedanim = 42;
-const int knifethrowanim = 43;
-const int removeknifeanim = 44;
-const int crouchremoveknifeanim = 45;
-const int jumpreversedanim = 46;
-const int jumpreversalanim = 47;
-const int landhardanim = 48;
-const int staggerbackhardanim = 49;
-const int dropkickanim = 50;
-const int winduppunchanim = 51;
-const int winduppunchblockedanim = 52;
-const int blockhighleftanim = 53;
-const int blockhighleftstrikeanim = 54;
-const int walljumpfrontanim = 55;
-const int walljumpbackanim = 56;
-const int walljumpleftanim = 57;
-const int walljumprightanim = 58;
-const int backflipanim = 59;
-const int leftflipanim = 60;
-const int rightflipanim = 61;
-const int walljumprightkickanim = 62;
-const int walljumpleftkickanim = 63;
-const int knifefightidleanim = 64;
-const int knifesneakattackanim = 65;
-const int knifesneakattackedanim = 66;
-const int swordstabanim = 67;
-const int swordslashleftanim = 68;
-const int swordslashrightanim = 69;
-const int swordfightidleanim = 70;
-const int swordsneakattackanim = 71;
-const int swordsneakattackedanim = 72;
-const int drawleftanim = 73;
-const int swordslashanim = 74;
-const int swordgroundstabanim = 75;
-const int dodgebackanim = 76;
-const int swordslashreversedanim = 77;
-const int swordslashreversalanim = 78;
-const int knifeslashreversedanim = 79;
-const int knifeslashreversalanim = 80;
-const int swordfightidlebothanim = 81;
-const int swordslashparryanim = 82;
-const int sworddisarmanim = 83;
-const int swordslashparriedanim = 84;
-const int wolfidle = 85;
-const int wolffightidle = 86;
-const int wolfswordidle = 87;
-const int wolfhurtidle = 88;
-const int wolfcrouchanim = 89;
-const int wolfsneakanim = 90;
-const int wolfrunanim = 91;
-const int wolfstopanim = 92;
-const int wolfclawanim = 93;
-const int wolflandanim = 94;
-const int wolflandhardanim = 95;
-const int wolfrunninganim = 96;
-const int rabbitrunninganim = 97;
-const int frontflipanim = 98;
-const int rabbittackleanim = 99;
-const int rabbittacklinganim = 100;
-const int rabbittackledfrontanim = 101;
-const int rabbittackledbackanim = 102;
-const int rabbittacklereversal = 103;
-const int rabbittacklereversed = 104;
-const int wolftackleanim = 105;
-const int wolftacklinganim = 106;
-const int wolftackledfrontanim = 107;
-const int wolftackledbacanim = 108;
-const int wolftacklereversal = 109;
-const int wolftacklereversed = 110;
-const int wolfslapanim = 111;
-const int wolfbashanim = 112;
-const int staffhitanim = 113;
-const int staffgroundsmashanim = 114;
-const int staffspinhitanim = 115;
-const int staffhitreversedanim = 116;
-const int staffhitreversalanim = 117;
-const int staffspinhitreversedanim = 118;
-const int staffspinhitreversalanim = 119;
-const int sleepanim = 120;
-const int sitanim = 121;
-const int talkidleanim = 122;
-const int sitwallanim = 123;
-const int dead1anim = 124;
-const int dead2anim = 125;
-const int dead3anim = 126;
-const int dead4anim = 127;
-
-const int max_dialogues = 20;
-const int max_dialoguelength = 20;
-
-const int max_model_vertex = 3000;             // maximum number of vertexs
-const int max_textured_triangle = 3000;                // maximum number of texture-filled triangles in a model
-
-const int stream_music1desert = 0;
-const int stream_music1grass = 1;
-const int stream_music1snow = 2;
-const int stream_music2 = 3;
-const int stream_music3 = 4;
-const int stream_music4 = 5;
-const int stream_menumusic = 6;
-const int stream_desertambient = 7;
-const int stream_firesound = 8;
-const int stream_wind = 9;
-
-//const int music1desert = 0;
-//const int music1grass = 1;
-//const int music1snow = 2;
-//const int music2 = 3;
-//const int music3 = 4;
-//const int music4 = 5;
-//const int menumusic = 6;
-//const int desertambient = 7;
-//const int firesound = 8;
-//const int wind = 9;
-const int footstepsound = 10;
-const int footstepsound2 = 11;
-const int footstepsound3 = 12;
-const int footstepsound4 = 13;
-const int jumpsound = 14;
-const int landsound = 15;
-const int whooshsound = 16;
-const int hawksound = 17;
-const int landsound1 = 18;
-const int landsound2 = 19;
-const int breaksound = 20;
-const int lowwhooshsound = 21;
-const int heavyimpactsound = 22;
-const int firestartsound = 23;
-const int fireendsound = 24;
-const int breaksound2 = 25;
-const int knifedrawsound = 26;
-const int knifesheathesound = 27;
-const int knifeswishsound = 28;
-const int knifeslicesound = 29;
-const int skidsound = 30;
-const int snowskidsound = 31;
-const int bushrustle = 32;
-const int midwhooshsound = 33;
-const int highwhooshsound = 34;
-const int movewhooshsound = 35;
-const int thudsound = 36;
-const int whooshhitsound = 37;
-const int clank1sound = 38;
-const int clank2sound = 39;
-const int clank3sound = 40;
-const int clank4sound = 41;
-const int consolefailsound = 42;
-const int consolesuccesssound = 43;
-const int swordslicesound = 44;
-const int metalhitsound = 45;
-const int clawslicesound = 46;
-const int splattersound = 47;
-const int growlsound = 48;
-const int growl2sound = 49;
-const int barksound = 50;
-const int snarlsound = 51;
-const int snarl2sound = 52;
-const int barkgrowlsound = 53;
-const int bark2sound = 54;
-const int bark3sound = 55;
-const int rabbitattacksound = 56;
-const int rabbitattack2sound = 57;
-const int rabbitattack3sound = 58;
-const int rabbitattack4sound = 59;
-const int rabbitpainsound = 60;
-const int rabbitpain1sound = 61;
-const int rabbitpain2sound = 62;
-const int rabbitchitter = 63;
-const int rabbitchitter2 = 64;
-const int fleshstabsound = 65;
-const int fleshstabremovesound = 66;
-const int swordstaffsound = 67;
-const int staffbodysound = 68;
-const int staffheadsound = 69;
-const int alarmsound = 70;
-const int staffbreaksound = 71;
-
-const int normalmode = 0;
-const int motionblurmode = 1;
-const int radialzoommode = 2;
-const int realmotionblurmode = 3;
-const int doublevisionmode = 4;
-const int glowmode = 5;
-
-const int maxplayers = 10;
-#endif
diff --git a/Source/Game.cpp b/Source/Game.cpp
new file mode 100644 (file)
index 0000000..c3c846d
--- /dev/null
@@ -0,0 +1,375 @@
+#include "Game.h"
+#include "openal_wrapper.h"
+#include "SDL_thread.h"
+
+extern int mainmenu;
+
+int numdialogues;
+int numdialogueboxes[max_dialogues];
+int dialoguetype[max_dialogues];
+int dialogueboxlocation[max_dialogues][max_dialoguelength];
+float dialogueboxcolor[max_dialogues][max_dialoguelength][3];
+int dialogueboxsound[max_dialogues][max_dialoguelength];
+char dialoguetext[max_dialogues][max_dialoguelength][128];
+char dialoguename[max_dialogues][max_dialoguelength][64];
+XYZ dialoguecamera[max_dialogues][max_dialoguelength];
+XYZ participantlocation[max_dialogues][10];
+int participantfocus[max_dialogues][max_dialoguelength];
+int participantaction[max_dialogues][max_dialoguelength];
+float participantrotation[max_dialogues][10];
+XYZ participantfacing[max_dialogues][max_dialoguelength][10];
+float dialoguecamerarotation[max_dialogues][max_dialoguelength];
+float dialoguecamerarotation2[max_dialogues][max_dialoguelength];
+int indialogue;
+int whichdialogue;
+int directing;
+float dialoguetime;
+int dialoguegonethrough[20];
+
+Game::Game()
+{
+       terraintexture = 0;
+       terraintexture2 = 0;
+       terraintexture3 = 0;
+       screentexture = 0;
+       screentexture2 = 0;
+       logotexture = 0;
+       loadscreentexture = 0;
+       Maparrowtexture = 0;
+       Mapboxtexture = 0;
+       Mapcircletexture = 0;
+       cursortexture = 0;
+
+       memset(Mainmenuitems, 0, sizeof(Mainmenuitems));
+
+       nummenuitems = 0;
+
+       memset(startx, 0, sizeof(startx));
+       memset(starty, 0, sizeof(starty));
+       memset(endx, 0, sizeof(endx));
+       memset(endy, 0, sizeof(endy));
+
+       memset(selectedlong, 0, sizeof(selectedlong));
+       memset(offsetx, 0, sizeof(offsetx));
+       memset(offsety, 0, sizeof(offsety));
+       memset(movex, 0, sizeof(movex));
+       memset(movey, 0, sizeof(movey));
+       memset(endy, 0, sizeof(endy));
+
+       transition = 0;
+       anim = 0;
+       selected = 0;
+       loaddistrib = 0;
+       keyselect = 0;
+       indemo = 0;
+
+       won = 0;
+
+       entername = 0;
+
+       memset(menustring, 0, sizeof(menustring));
+       memset(registrationname, 0, sizeof(registrationname));
+       registrationnumber = 0;
+
+       newdetail = 0;
+       newscreenwidth = 0;
+       newscreenheight = 0;
+
+       gameon = 0;
+       deltah = 0,deltav = 0;
+       mousecoordh = 0,mousecoordv = 0;
+       oldmousecoordh = 0,oldmousecoordv = 0;
+       rotation = 0,rotation2 = 0;
+
+//     SkyBox skybox;
+
+       cameramode = 0;
+       cameratogglekeydown = 0;
+       chattogglekeydown = 0;
+       olddrawmode = 0;
+       drawmode = 0;
+       drawmodetogglekeydown = 0;
+       explodetogglekeydown = 0;
+       detailtogglekeydown = 0;
+       firstload = 0;
+       oldbutton = 0;
+
+       leveltime = 0;
+       loadtime = 0;
+
+//     Model hawk;
+
+//     XYZ hawkcoords;
+//     XYZ realhawkcoords;
+
+       hawktexture = 0;
+       hawkrotation = 0;
+       hawkcalldelay = 0;
+/*
+       Model eye;
+       Model iris;
+       Model cornea;
+*/
+       stealthloading = 0;
+
+       campaignnumlevels = 0;
+
+       memset(campaignmapname, 0, sizeof(campaignmapname));
+       memset(campaigndescription, 0, sizeof(campaigndescription));
+       memset(campaignchoosenext, 0, sizeof(campaignchoosenext));
+       memset(campaignnumnext, 0, sizeof(campaignnumnext));
+       memset(campaignnextlevel, 0, sizeof(campaignnextlevel));
+       int campaignchoicesmade;
+       memset(campaignchoices, 0, sizeof(campaignchoices));
+       memset(campaignlocationx, 0, sizeof(campaignlocationx));
+       memset(campaignlocationy, 0, sizeof(campaignlocationy));
+       memset(campaignlocationy, 0, sizeof(campaignlocationy));
+
+       campaignchoicenum = 0;
+
+       memset(campaignchoicewhich, 0, sizeof(campaignchoicewhich));
+
+       whichchoice = 0;
+
+       numlevelspassed = 0;
+
+       memset(levelorder, 0, sizeof(levelorder));
+       memset(levelvisible, 0, sizeof(levelvisible));
+       memset(levelhighlight, 0, sizeof(levelhighlight));
+
+       minimap = 0;
+
+       musictype = 0,oldmusictype = 0,oldoldmusictype = 0;
+       realthreat = 0;
+
+//     Model rabbit;
+//     XYZ rabbitcoords;
+
+//     XYZ mapcenter;
+       mapradius = 0;
+
+//     Text text;
+       fps = 0;
+
+//     XYZ cameraloc;
+       cameradist = 0;
+
+       envtogglekeydown = 0;
+       slomotogglekeydown = 0;
+       texturesizetogglekeydown = 0;
+       freezetogglekeydown = 0;
+       drawtoggle = 0;
+
+       editorenabled = 0;
+       editortype = 0;
+       editorsize = 0;
+       editorrotation = 0;
+       editorrotation2 = 0;
+
+       brightness = 0;
+
+       quit = 0;
+       tryquit = 0;
+
+//     XYZ pathpoint[30];
+       numpathpoints = 0;
+       memset(numpathpointconnect, 0, sizeof(numpathpointconnect));
+       memset(pathpointconnect, 0, sizeof(pathpointconnect));
+       pathpointselected = 0;
+
+       endgame = 0;
+       scoreadded = 0;
+       numchallengelevels = 0;
+
+       console = 0;
+       archiveselected = 0;
+
+       memset(consoletext, 0, sizeof(consoletext));
+       memset(consolechars, 0, sizeof(consolechars));
+       chatting = 0;
+       memset(displaytext, 0, sizeof(displaytext));
+       memset(displaychars, 0, sizeof(displaychars));
+       memset(displaytime, 0, sizeof(displaytime));
+       displayblinkdelay = 0;
+       displayblink = 0;
+       displayselected = 0;
+       consolekeydown = 0;
+       consoletogglekeydown = 0;
+       consoleblinkdelay = 0;
+       consoleblink = 0;
+       consoleselected = 0;
+//     memset(togglekey, 0, sizeof(togglekey));
+//     memset(togglekeydelay, 0, sizeof(togglekeydelay));
+       autocam = 0;
+
+       crouchkey = 0,jumpkey = 0,forwardkey = 0,chatkey = 0,backkey = 0,leftkey = 0,rightkey = 0,drawkey = 0,throwkey = 0,attackkey = 0;
+       oldattackkey = 0;
+
+       loading = 0;
+       talkdelay = 0;
+
+       numboundaries = 0;
+//     XYZ boundary[360];
+
+       whichlevel = 0;
+       oldenvironment = 0;
+       targetlevel = 0;
+       changedelay = 0;
+
+       memset(musicvolume, 0, sizeof(musicvolume));
+       memset(oldmusicvolume, 0, sizeof(oldmusicvolume));
+       musicselected = 0;
+       change = 0;
+       
+//------------
+
+       waiting = false;
+       mainmenu = 0;
+       
+       accountactive = NULL;
+}
+
+typedef struct {
+       Game* game;
+       void (Game::*method)();
+} params_thread;
+
+void Game::fireSound(int sound) {
+       emit_sound_at(sound);
+}
+
+void Game::inputText(char* str, int* charselected, int* nb_chars) {
+       SDL_Event evenement;
+       int i;
+       
+       if(!waiting) {
+               waiting=true;
+               SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,SDL_DEFAULT_REPEAT_INTERVAL);
+               SDL_EnableUNICODE(true);
+       }
+
+       SDL_PollEvent(&evenement);
+       
+       switch(evenement.type) {
+               case SDL_KEYDOWN:
+                       if(evenement.key.keysym.sym == SDLK_ESCAPE) {
+                               for(i=0;i<255;i++){
+                                       str[i]=' ';
+                               }
+                               *nb_chars=0;
+                               *charselected=0;
+                               waiting=false;
+                       } else if(evenement.key.keysym.sym==SDLK_BACKSPACE){
+                               if((*charselected)!=0) {
+                                       for(i=(*charselected)-1;i<255;i++){
+                                               str[i]=str[i+1];
+                                       }
+                                       str[255]=' ';
+                                       (*charselected)--;
+                                       (*nb_chars)--;
+                               }
+                       } else if(evenement.key.keysym.sym==SDLK_DELETE){
+                               for(i=(*charselected);i<255;i++){
+                                       str[i]=str[i+1];
+                               }
+                               str[255]=' ';
+                               (*nb_chars)--;
+                       } else if(evenement.key.keysym.sym==SDLK_LEFT){
+                               if((*charselected)!=0)
+                                       (*charselected)--;
+                       } else if(evenement.key.keysym.sym==SDLK_RIGHT){
+                               if((*charselected)<(*nb_chars))
+                                       (*charselected)++;
+                       } else if(evenement.key.keysym.sym==SDLK_RETURN) {
+                               waiting=false;
+                       } else if((evenement.key.keysym.unicode<127)&&((*nb_chars)<60)&&(evenement.key.keysym.sym!=SDLK_LSHIFT)&&(evenement.key.keysym.sym!=SDLK_RSHIFT)) {
+                               for(i=255;i>=(*charselected)+1;i--){
+                                       str[i]=str[i-1];
+                               }
+                               str[*charselected]=evenement.key.keysym.unicode;
+                               (*charselected)++;
+                               (*nb_chars)++;
+                       }
+               break;
+       }
+       
+       if(!waiting) {
+               SDL_EnableKeyRepeat(0,0); // disable key repeat
+               SDL_EnableUNICODE(false);
+       }
+}
+
+void Game::setKeySelected() {
+       waiting=true;
+       params_thread* data = new params_thread;
+    data->game = this;
+    data->method = &Game::setKeySelected_thread;
+    printf("launch thread\n");
+       SDL_Thread* thread = SDL_CreateThread(Game::thread, data);
+    if ( thread == NULL ) {
+        fprintf(stderr, "Unable to create thread: %s\n", SDL_GetError());
+               waiting=false;
+        return;
+    }
+}
+
+void Game::setKeySelected_thread() {
+       int keycode=-1;
+       SDL_Event evenement;
+       while(keycode==-1) {
+               SDL_WaitEvent(&evenement);
+               switch(evenement.type) {
+                       case SDL_KEYDOWN:
+                               keycode = evenement.key.keysym.sym;
+                       break;
+                       case SDL_MOUSEBUTTONDOWN:
+                               keycode = SDLK_LAST+evenement.button.button;
+                       break;
+                       default:
+                       break;
+               }
+       }
+       if(keycode != SDLK_ESCAPE) {
+               fireSound();
+               switch(keyselect) {
+                       case 0: forwardkey=keycode;
+                       break;
+                       case 1: backkey=keycode;
+                       break;
+                       case 2: leftkey=keycode;
+                       break;
+                       case 3: rightkey=keycode;
+                       break;
+                       case 4: crouchkey=keycode;
+                       break;
+                       case 5: jumpkey=keycode;
+                       break;
+                       case 6: drawkey=keycode;
+                       break;
+                       case 7: throwkey=keycode;
+                       break;
+                       case 8: attackkey=keycode;
+                       break;
+                       default:
+                       break;
+               }
+       }
+       keyselect=-1;
+       waiting=false;
+}
+
+int Game::thread(void *data) {
+       params_thread* pt = (params_thread*)data;
+    if(pt) {
+        (pt->game->*(pt->method))();
+    }
+}
+
+void Game::DrawGL() {
+       if ( stereomode == stereoNone ) {
+               DrawGLScene(stereoCenter);
+       } else {
+               DrawGLScene(stereoLeft);
+               DrawGLScene(stereoRight);
+       }
+}
index 1297fbdc4f6c016076c7bdbe308e563b2a53b5d7..63bb0a6468bfcbf60863b6055005c8ab0a90edd4 100644 (file)
@@ -40,20 +40,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "TGALoader.h"
 
-#if !PLATFORM_MACOSX
-#include "WinInput.h"
-#else
-#include "Macinput.h"
-#endif
-
 #include "Terrain.h"
 #include "Skybox.h"
 #include "Skeleton.h"
 #include "Models.h"
 #include "Lights.h"
 #include "Person.h"
-#include "Constants.h"
-#include "Sprites.h"
+#include "Sprite.h"
 //#include <agl.h>
 #include "Text.h"
 #include "Objects.h"
@@ -63,238 +56,249 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include <fstream>
 #include "gamegl.h"
 #include "Stereo.h"
+#include "Account.h"
+#include "Sounds.h"
 
 extern GLuint rabbittexture;
 
 class Game
 {
-public:
-
-       typedef std::map<std::string, GLuint> TextureList;
-       typedef std::map<GLuint, std::string> GLTextureList;
-       typedef TextureList::iterator TexIter;
-       static TextureList textures;
-
-       GLuint terraintexture;
-       GLuint terraintexture2;
-       GLuint terraintexture3;
-       GLuint screentexture;
-       GLuint screentexture2;
-       GLuint logotexture;
-       GLuint loadscreentexture;
-       GLuint Maparrowtexture;
-       GLuint Mapboxtexture;
-       GLuint Mapcircletexture;
-       GLuint cursortexture;
-       GLuint Mainmenuitems[10];
-
-       int nummenuitems;
-       int startx[100];
-       int starty[100];
-       int endx[100];
-       int endy[100];
-       float selectedlong[100];
-       float offsetx[100];
-       float offsety[100];
-       float movex[100];
-       float movey[100];
-       float transition;
-       int anim;
-       int selected;
-       int loaddistrib;
-       int keyselect;
-       int indemo;
-
-       bool won;
-
-       bool entername;
-
-       char menustring[100][256];
-       char registrationname[256];
-       float registrationnumber;
-
-       int newdetail;
-       int newscreenwidth;
-       int newscreenheight;
-
-       bool gameon;
-       float deltah,deltav;
-       int mousecoordh,mousecoordv;
-       int oldmousecoordh,oldmousecoordv;
-       float rotation,rotation2;
-       SkyBox skybox;
-       bool cameramode;
-       bool cameratogglekeydown;
-       bool chattogglekeydown;
-       int olddrawmode;
-       int drawmode;
-       bool drawmodetogglekeydown;
-       bool explodetogglekeydown;
-       bool detailtogglekeydown;
-       bool firstload;
-       bool oldbutton;
-
-       float leveltime;
-       float loadtime;
-
-       Model hawk;
-       XYZ hawkcoords;
-       XYZ realhawkcoords;
-       GLuint hawktexture;
-       float hawkrotation;
-       float hawkcalldelay;
-
-       Model eye;
-       Model iris;
-       Model cornea;
-
-       bool stealthloading;
-
-       int campaignnumlevels;
-       char campaignmapname[50][256];
-       char campaigndescription[50][256];
-       int campaignchoosenext[50];
-       int campaignnumnext[50];
-       int campaignnextlevel[50][10];
-       int campaignchoicesmade;
-       int campaignchoices[5000];
-       int campaignlocationx[50];
-       int campaignlocationy[50];
-       int campaignchoicenum;
-       int campaignchoicewhich[10];
-       int whichchoice;
-
-       int numlevelspassed;
-       int levelorder[5000];
-       int levelvisible[50];
-       int levelhighlight[50];
-
-       bool minimap;
-
-       int musictype,oldmusictype,oldoldmusictype;
-       bool realthreat;
-
-       Model rabbit;
-       XYZ rabbitcoords;
-
-       XYZ mapcenter;
-       float mapradius;
-
-       Text text;
-       float fps;
-
-       XYZ cameraloc;
-       float cameradist;
-
-       bool envtogglekeydown;
-       bool slomotogglekeydown;
-       bool texturesizetogglekeydown;
-       bool freezetogglekeydown;
-       int drawtoggle;
-
-       bool editorenabled;
-       int editortype;
-       float editorsize;
-       float editorrotation;
-       float editorrotation2;
-
-       float brightness;
-
-       int quit;
-       int tryquit;
-
-       XYZ pathpoint[30];
-       int numpathpoints;
-       int numpathpointconnect[30];
-       int pathpointconnect[30][30];
-       int pathpointselected;
-
-       int endgame;
-       bool scoreadded;
-       int numchallengelevels;
-
-       bool console;
-       int archiveselected;
-       char consoletext[15][256];
-       int consolechars[15];
-       bool chatting;
-       char displaytext[15][256];
-       int displaychars[15];
-       float displaytime[15];
-       float displayblinkdelay;
-       bool displayblink;
-       int displayselected;
-       bool consolekeydown;
-       bool consoletogglekeydown;
-       float consoleblinkdelay;
-       bool consoleblink;
-       int consoleselected;
-       int togglekey[140];
-       float togglekeydelay[140];
-       bool registernow;
-       bool autocam;
-
-       unsigned short crouchkey,jumpkey,forwardkey,chatkey,backkey,leftkey,rightkey,drawkey,throwkey,attackkey;
-       bool oldattackkey;
-
-       long long MD5_string (char *string);
-       static void LoadTexture(const char *fileName, GLuint *textureid,int mipmap, bool hasalpha);
-       static void LoadTextureSave(const char *fileName, GLuint *textureid,int mipmap,GLubyte *array, int *skinsize);
-       void LoadSave(const char *fileName, GLuint *textureid,bool mipmap,GLubyte *array, int *skinsize);
-       bool AddClothes(const char *fileName, GLuint *textureid,bool mipmap,GLubyte *array, int *skinsize);
-       void InitGame();
-       void LoadStuff();
-       void LoadingScreen();
-       void FadeLoadingScreen(float howmuch);
-       void Dispose();
-       int DrawGLScene(StereoSide side);
-       void Tick();
-       void TickOnce();
-       void TickOnceAfter();
-       void SetUpLighting();
-       void Loadlevel(int which);
-       void Loadlevel(char *name);
-       void LoadSounds();
-       void Setenvironment(int which);
-       GLvoid ReSizeGLScene(float fov, float near);
-       int findPathDist(int start,int end);
-       int checkcollide(XYZ startpoint, XYZ endpoint);
-       int checkcollide(XYZ startpoint, XYZ endpoint, int what);
-       int loading;
-       float talkdelay;
-
-       int numboundaries;
-       XYZ boundary[360];
-
-       int whichlevel;
-       int oldenvironment;
-       int targetlevel;
-       float changedelay;
-
-       float musicvolume[4];
-       float oldmusicvolume[4];
-       int musicselected;
-       int change;
-       Game();
-       ~Game() {
-               for(int i=0;i<10;i++){
-                       if(Mainmenuitems[i])glDeleteTextures( 1, &Mainmenuitems[i] );
+       public:
+               typedef std::map<std::string, GLuint> TextureList;
+               typedef std::map<GLuint, std::string> GLTextureList;
+               typedef TextureList::iterator TexIter;
+               static TextureList textures;
+
+               GLuint terraintexture;
+               GLuint terraintexture2;
+               GLuint terraintexture3;
+               GLuint screentexture;
+               GLuint screentexture2;
+               GLuint logotexture;
+               GLuint loadscreentexture;
+               GLuint Maparrowtexture;
+               GLuint Mapboxtexture;
+               GLuint Mapcircletexture;
+               GLuint cursortexture;
+               GLuint Mainmenuitems[10];
+
+               int nummenuitems;
+               int startx[100];
+               int starty[100];
+               int endx[100];
+               int endy[100];
+               float selectedlong[100];
+               float offsetx[100];
+               float offsety[100];
+               float movex[100];
+               float movey[100];
+               float transition;
+               int anim;
+               int selected;
+               int keyselect;
+               int loaddistrib;
+               int indemo;
+
+               bool won;
+
+               bool entername;
+
+               char menustring[100][256];
+               char registrationname[256];
+               float registrationnumber;
+
+               int newdetail;
+               int newscreenwidth;
+               int newscreenheight;
+
+               bool gameon;
+               float deltah,deltav;
+               int mousecoordh,mousecoordv;
+               int oldmousecoordh,oldmousecoordv;
+               float rotation,rotation2;
+               SkyBox skybox;
+               bool cameramode;
+               bool cameratogglekeydown;
+               bool chattogglekeydown;
+               int olddrawmode;
+               int drawmode;
+               bool drawmodetogglekeydown;
+               bool explodetogglekeydown;
+               bool detailtogglekeydown;
+               bool firstload;
+               bool oldbutton;
+
+               float leveltime;
+               float loadtime;
+
+               Model hawk;
+               XYZ hawkcoords;
+               XYZ realhawkcoords;
+               GLuint hawktexture;
+               float hawkrotation;
+               float hawkcalldelay;
+
+               Model eye;
+               Model iris;
+               Model cornea;
+
+               bool stealthloading;
+
+               int campaignnumlevels;
+               char campaignmapname[50][256];
+               char campaigndescription[50][256];
+               int campaignchoosenext[50];
+               int campaignnumnext[50];
+               int campaignnextlevel[50][10];
+               int campaignchoicesmade;
+               int campaignchoices[5000];
+               int campaignlocationx[50];
+               int campaignlocationy[50];
+               int campaignchoicenum;
+               int campaignchoicewhich[10];
+               int whichchoice;
+
+               int numlevelspassed;
+               int levelorder[5000];
+               int levelvisible[50];
+               int levelhighlight[50];
+
+               bool minimap;
+
+               int musictype,oldmusictype,oldoldmusictype;
+               bool realthreat;
+
+               Model rabbit;
+               XYZ rabbitcoords;
+
+               XYZ mapcenter;
+               float mapradius;
+
+               Text text;
+               float fps;
+
+               XYZ cameraloc;
+               float cameradist;
+
+               bool envtogglekeydown;
+               bool slomotogglekeydown;
+               bool texturesizetogglekeydown;
+               bool freezetogglekeydown;
+               int drawtoggle;
+
+               bool editorenabled;
+               int editortype;
+               float editorsize;
+               float editorrotation;
+               float editorrotation2;
+
+               float brightness;
+
+               int quit;
+               int tryquit;
+
+               XYZ pathpoint[30];
+               int numpathpoints;
+               int numpathpointconnect[30];
+               int pathpointconnect[30][30];
+               int pathpointselected;
+
+               int endgame;
+               bool scoreadded;
+               int numchallengelevels;
+
+               bool console;
+               int archiveselected;
+               char consoletext[15][256];
+               int consolechars[15];
+               bool chatting;
+               char displaytext[15][256];
+               int displaychars[15];
+               float displaytime[15];
+               float displayblinkdelay;
+               bool displayblink;
+               int displayselected;
+               bool consolekeydown;
+               bool consoletogglekeydown;
+               float consoleblinkdelay;
+               bool consoleblink;
+               int consoleselected;
+               //int togglekey[140];
+               //float togglekeydelay[140];
+               bool autocam;
+
+               unsigned short crouchkey,jumpkey,forwardkey,chatkey,backkey,leftkey,rightkey,drawkey,throwkey,attackkey;
+               bool oldattackkey;
+
+               static void LoadTexture(const char *fileName, GLuint *textureid,int mipmap, bool hasalpha);
+               static void LoadTextureSave(const char *fileName, GLuint *textureid,int mipmap,GLubyte *array, int *skinsize);
+               void LoadSave(const char *fileName, GLuint *textureid,bool mipmap,GLubyte *array, int *skinsize);
+               bool AddClothes(const char *fileName, GLuint *textureid,bool mipmap,GLubyte *array, int *skinsize);
+               void InitGame();
+               void LoadStuff();
+               void LoadingScreen();
+               void FadeLoadingScreen(float howmuch);
+               void Dispose();
+               int DrawGLScene(StereoSide side);
+               void DrawGL();
+               void Tick();
+               void TickOnce();
+               void TickOnceAfter();
+               void SetUpLighting();
+               void Loadlevel(int which);
+               void Loadlevel(const char *name);
+               void Setenvironment(int which);
+               GLvoid ReSizeGLScene(float fov, float near);
+               int findPathDist(int start,int end);
+               int checkcollide(XYZ startpoint, XYZ endpoint);
+               int checkcollide(XYZ startpoint, XYZ endpoint, int what);
+               int loading;
+               float talkdelay;
+               
+               void fireSound(int sound=fireendsound);
+               void setKeySelected();
+
+               int numboundaries;
+               XYZ boundary[360];
+
+               int whichlevel;
+               int oldenvironment;
+               int targetlevel;
+               float changedelay;
+
+               float musicvolume[4];
+               float oldmusicvolume[4];
+               int musicselected;
+               int change;
+               Game();
+               ~Game() {
+                       for(int i=0;i<10;i++){
+                               if(Mainmenuitems[i])glDeleteTextures( 1, &Mainmenuitems[i] );
+                       }
+                       glDeleteTextures( 1, &cursortexture );
+                       glDeleteTextures( 1, &Maparrowtexture );
+                       glDeleteTextures( 1, &Mapboxtexture );
+                       glDeleteTextures( 1, &Mapcircletexture );
+                       glDeleteTextures( 1, &terraintexture );
+                       glDeleteTextures( 1, &terraintexture2 );
+                       if(screentexture>0)glDeleteTextures( 1, &screentexture );
+                       if(screentexture2>0)glDeleteTextures( 1, &screentexture2 );
+                       glDeleteTextures( 1, &hawktexture );
+                       glDeleteTextures( 1, &logotexture );
+                       glDeleteTextures( 1, &loadscreentexture );
+
+                       Dispose();
                }
-               glDeleteTextures( 1, &cursortexture );
-               glDeleteTextures( 1, &Maparrowtexture );
-               glDeleteTextures( 1, &Mapboxtexture );
-               glDeleteTextures( 1, &Mapcircletexture );
-               glDeleteTextures( 1, &terraintexture );
-               glDeleteTextures( 1, &terraintexture2 );
-               if(screentexture>0)glDeleteTextures( 1, &screentexture );
-               if(screentexture2>0)glDeleteTextures( 1, &screentexture2 );
-               glDeleteTextures( 1, &hawktexture );
-               glDeleteTextures( 1, &logotexture );
-               glDeleteTextures( 1, &loadscreentexture );
-
-               Dispose();
-       }
-
+               bool isWaiting() { return waiting; };
+       private:
+               void setKeySelected_thread();
+               static int thread(void *data);
+               void inputText(char* str, int* charselected, int* nb_chars);
+               void flash();
+               bool waiting;
+               bool mainmenutogglekeydown;
+               //int mainmenu;
+               Account* accountactive;
 };
 
 #ifndef __forceinline
@@ -305,20 +309,55 @@ public:
 
 static __forceinline void swap_gl_buffers(void)
 {
-
     SDL_GL_SwapBuffers();
-
 }
 
-#ifdef __GNUC__
-#define LONGLONGCONST(x) (x##ll)
-#else
-#define LONGLONGCONST(x) (x)
-#endif
-
 extern "C" { void UndefinedSymbolToExposeStubbedCode(void); }
 //#define STUBBED(x) UndefinedSymbolToExposeStubbedCode();
 #define STUBBED(x) { static bool seen = false; if (!seen) { seen = true; fprintf(stderr, "STUBBED: %s at %s:%d\n", x, __FILE__, __LINE__); } }
 //#define STUBBED(x)
 
+extern int numplayers;
+
+extern int numdialogues;
+const int max_dialogues = 20;
+const int max_dialoguelength = 20;
+extern int numdialogueboxes[max_dialogues];
+extern int dialoguetype[max_dialogues];
+extern int dialogueboxlocation[max_dialogues][max_dialoguelength];
+extern float dialogueboxcolor[max_dialogues][max_dialoguelength][3];
+extern int dialogueboxsound[max_dialogues][max_dialoguelength];
+extern char dialoguetext[max_dialogues][max_dialoguelength][128];
+extern char dialoguename[max_dialogues][max_dialoguelength][64];
+extern XYZ dialoguecamera[max_dialogues][max_dialoguelength];
+extern XYZ participantlocation[max_dialogues][10];
+extern int participantfocus[max_dialogues][max_dialoguelength];
+extern int participantaction[max_dialogues][max_dialoguelength];
+extern float participantrotation[max_dialogues][10];
+extern XYZ participantfacing[max_dialogues][max_dialoguelength][10];
+extern float dialoguecamerarotation[max_dialogues][max_dialoguelength];
+extern float dialoguecamerarotation2[max_dialogues][max_dialoguelength];
+extern int indialogue;
+extern int whichdialogue;
+extern int directing;
+extern float dialoguetime;
+extern int dialoguegonethrough[20];
+
+enum maptypes {
+  mapkilleveryone, mapgosomewhere,
+  mapkillsomeone, mapkillmost // These two are unused
+};
+
+enum pathtypes {wpkeepwalking, wppause};
+
+static const char *pathtypenames[] = {"keepwalking", "pause"};
+
+enum editortypes {typeactive, typesitting, typesittingwall, typesleeping,
+                 typedead1, typedead2, typedead3, typedead4};
+
+static const char *editortypenames[] = {
+  "active", "sitting", "sitting wall", "sleeping",
+  "dead1", "dead2", "dead3", "dead4"
+};
+
 #endif
index 039df019d220a28189bd057da65770d8f6873e30..3d4b9f782391ac38ffb7796fa238f6307464e5c1 100644 (file)
@@ -21,6 +21,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "Game.h"
 #include "openal_wrapper.h"
+#include "Input.h"
+#include "Awards.h"
 
 using namespace std;
 
@@ -29,7 +31,7 @@ extern int environment;
 extern float texscale;
 extern Light light;
 extern Terrain terrain;
-extern Sprites sprites;
+//extern Sprites sprites;
 extern float multiplier;
 extern float sps;
 extern float viewdistance;
@@ -43,8 +45,6 @@ extern int detail;
 extern float usermousesensitivity;
 extern bool osx;
 extern float camerashake;
-extern Weapons weapons;
-extern Person player[maxplayers];
 extern int slomo;
 extern float slomodelay;
 extern bool ismotionblur;
@@ -52,7 +52,6 @@ extern float woozy;
 extern float blackout;
 extern bool damageeffects;
 extern float volume;
-extern int numplayers;
 extern bool texttoggle;
 extern float blurness;
 extern float targetblurness;
@@ -72,7 +71,6 @@ extern bool midweird;
 extern bool proportionweird;
 extern bool vertexweird[6];
 extern bool velocityblur;
-extern bool buttons[3];
 extern bool debugmode;
 extern int mainmenu;
 extern int oldmainmenu;
@@ -83,13 +81,6 @@ extern bool decals;
 //extern int texdetail;
 extern float texdetail;
 extern bool musictoggle;
-extern int bonus;
-extern float bonusvalue;
-extern float bonustotal;
-extern float bonustime;
-extern int oldbonus;
-extern float startbonustotal;
-extern float bonusnum[100];
 extern int tutoriallevel;
 extern float smoketex;
 extern float tutorialstagetime;
@@ -97,7 +88,6 @@ extern float tutorialmaxtime;
 extern int tutorialstage;
 extern bool againbonus;
 extern float damagedealt;
-extern float damagetaken;
 extern bool invertmouse;
 
 extern int numhotspots;
@@ -107,34 +97,7 @@ extern XYZ hotspot[40];
 extern int hotspottype[40];
 extern float hotspotsize[40];
 extern char hotspottext[40][256];
-extern int currenthotspot;
-
-extern int numaccounts;
-extern int accountactive;
-extern int accountdifficulty[10];
-extern int accountprogress[10];
-extern float accountpoints[10];
-extern float accounthighscore[10][50];
-extern float accountfasttime[10][50];
-extern bool accountunlocked[10][60];
-extern char accountname[10][256];
-
-extern int numfalls;
-extern int numflipfail;
-extern int numseen;
-extern int numstaffattack;
-extern int numswordattack;
-extern int numknifeattack;
-extern int numunarmedattack;
-extern int numescaped;
-extern int numflipped;
-extern int numwallflipped;
-extern int numthrowkill;
-extern int numafterkill;
-extern int numreversals;
-extern int numattacks;
-extern int maxalarmed;
-extern int numresponded;
+extern int currenthotspot;;
 
 extern bool campaign;
 extern bool winfreeze;
@@ -143,76 +106,23 @@ extern float menupulse;
 
 extern bool gamestart;
 
-extern int numdialogues;
-extern int numdialogueboxes[max_dialogues];
-extern int dialoguetype[max_dialogues];
-extern int dialogueboxlocation[max_dialogues][max_dialoguelength];
-extern float dialogueboxcolor[max_dialogues][max_dialoguelength][3];
-extern int dialogueboxsound[max_dialogues][max_dialoguelength];
-extern char dialoguetext[max_dialogues][max_dialoguelength][128];
-extern char dialoguename[max_dialogues][max_dialoguelength][64];
-extern XYZ dialoguecamera[max_dialogues][max_dialoguelength];
-extern XYZ participantlocation[max_dialogues][10];
-extern int participantfocus[max_dialogues][max_dialoguelength];
-extern int participantaction[max_dialogues][max_dialoguelength];
-extern float participantrotation[max_dialogues][10];
-extern XYZ participantfacing[max_dialogues][max_dialoguelength][10];
-extern float dialoguecamerarotation[max_dialogues][max_dialoguelength];
-extern float dialoguecamerarotation2[max_dialogues][max_dialoguelength];
-extern int indialogue;
-extern int whichdialogue;
-extern int directing;
-extern float dialoguetime;
-extern int dialoguegonethrough[20];
-
-extern int accountcampaignchoicesmade[10];
-extern int accountcampaignchoices[10][5000];
-
-extern float accountcampaignhighscore[10];
-extern float accountcampaignfasttime[10];
-extern float accountcampaignscore[10];
-extern float accountcampaigntime[10];
-
 extern bool gamestarted;
 
 extern bool showdamagebar;
 
-extern OPENAL_SAMPLE   *samp[100];
-extern int channels[100];
-extern "C"     void PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-
-/*********************> DrawGLScene() <*****/
-long long Game::MD5_string (char *string){
-       char temp[256]="";
-       char temp2[256]="";
-       long long num=90814;
-
-       sprintf (temp, "%s",string);
-
-       int i=0;
-       while (i<256&&temp[i]!='\0'){
-               if(temp[i]%3==0)num+=temp[i]*124;
-               else if(temp[i]%3==1)num-=temp[i]*temp[i];
-               else num*=temp[i];
-               i++;
-       }
-
-       num=longlongabs(num);
-       if(num==0)num+=1452;
-
-       while(num<LONGLONGCONST(5000000000000000)){
-               num*=1.85421521;
-       }
-
-       while(num>LONGLONGCONST(9900000000000000)){
-               num/=1.235421521;
-       }
-
-       return num;
-
-       //return 1111111111111111;
+enum drawmodes {
+  normalmode, motionblurmode, radialzoommode,
+  realmotionblurmode, doublevisionmode, glowmode,
+};
+
+void Game::flash() { // shouldn't be that way, these should be attributes and Person class should not change rendering.
+       flashr=1;
+       flashg=0;
+       flashb=0;
+       flashamount=1;
+       flashdelay=1;
 }
-
+/*********************> DrawGLScene() <*****/
 int Game::DrawGLScene(StereoSide side)
 {      
        static float texcoordwidth,texcoordheight;
@@ -304,16 +214,15 @@ int Game::DrawGLScene(StereoSide side)
 
                if(winfreeze||mainmenu)drawmode=normalmode;
 
-               //drawmode=glowmode;
+#if PLATFORM_MACOSX
                if(drawmode==glowmode){
                        RGBColor color2;
                        color2.red=0;
                        color2.green=0;
                        color2.blue=0;
-#if PLATFORM_MACOSX
                        DSpContext_FadeGamma(NULL,200,&color2);
-#endif
                }
+#endif
 
                if(drawtoggle!=2)drawtoggle=1-drawtoggle;
 
@@ -333,20 +242,18 @@ int Game::DrawGLScene(StereoSide side)
                glDrawBuffer(GL_BACK);
                glReadBuffer(GL_BACK);
 
-               /*if(environment==desertenvironment)glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, (float)(abs(Random()%100))/50 );
-               else glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0);
-               */
                if(abs(blurness-targetblurness)<multiplier*10||abs(blurness-targetblurness)>2){
                        blurness=targetblurness;
                        targetblurness=(float)(abs(Random()%100))/40;
                }
-               if(blurness<targetblurness)blurness+=multiplier*5;
-               if(blurness>targetblurness)blurness-=multiplier*5;
+               if(blurness<targetblurness) 
+                       blurness+=multiplier*5;
+               else
+                       blurness-=multiplier*5;
 
                //glFinish();
                static XYZ terrainlight;
                static float distance;
-               //if(drawmode==normalmode)ReSizeGLScene(90,.1);
                if(drawmode==normalmode)ReSizeGLScene(90,.1f);
                if(drawmode!=normalmode)glViewport(0,0,texviewwidth,texviewheight);     
                glDepthFunc(GL_LEQUAL);
@@ -370,7 +277,6 @@ int Game::DrawGLScene(StereoSide side)
                        glRotatef(rotation+sin(woozy)*(player[0].damage/player[0].damagetolerance)*5,0,1,0);
                }
                if(cameramode||freeze||winfreeze){
-                       //glRotatef(float(Random()%100)/10*camerashake/*+(woozy*woozy)/10*/,0,0,1);
                        glRotatef(rotation2,1,0,0);
                        glRotatef(rotation,0,1,0);
                }
@@ -378,8 +284,6 @@ int Game::DrawGLScene(StereoSide side)
                if(environment==desertenvironment){
                        glRotatef((float)(abs(Random()%100))/3000-1,1,0,0);
                        glRotatef((float)(abs(Random()%100))/3000-1,0,1,0);
-                       //glRotatef(blurness/40-1,1,0,0);
-                       //glRotatef(blurness/40-1,0,1,0);
                }
                SetUpLight(&light,0);
                glPushMatrix();
@@ -410,19 +314,18 @@ int Game::DrawGLScene(StereoSide side)
                                                                opacity=.2+.2*sin(smoketex*6+i)-player[k].skeleton.joints[i].position.y*player[k].scale/5-(player[k].coords.y-terrain.getHeight(player[k].coords.x,player[k].coords.z))/10;
                                                        }
                                                        terrain.MakeDecal(shadowdecal,point,size,opacity,rotation);
-                                                       if(terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz])
-                                                               for(l=0;l<terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz];l++){
-                                                                       j=terrain.patchobjects[player[k].whichpatchx][player[k].whichpatchz][l];
-                                                                       if(objects.position[j].y<player[k].coords.y||objects.type[j]==tunneltype||objects.type[j]==weirdtype){
-                                                                               point=DoRotation(DoRotation(player[k].skeleton.joints[i].position,0,player[k].rotation,0)*player[k].scale+player[k].coords-objects.position[j],0,-objects.rotation[j],0);
-                                                                               size=.4f;
-                                                                               opacity=.4f;
-                                                                               if(k!=0&&tutoriallevel==1){
-                                                                                       opacity=.2+.2*sin(smoketex*6+i);
-                                                                               }
-                                                                               objects.model[j].MakeDecal(shadowdecal,&point,&size,&opacity,&rotation);
+                                                       for(l=0;l<terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz];l++){
+                                                               j=terrain.patchobjects[player[k].whichpatchx][player[k].whichpatchz][l];
+                                                               if(objects.position[j].y<player[k].coords.y||objects.type[j]==tunneltype||objects.type[j]==weirdtype){
+                                                                       point=DoRotation(DoRotation(player[k].skeleton.joints[i].position,0,player[k].rotation,0)*player[k].scale+player[k].coords-objects.position[j],0,-objects.rotation[j],0);
+                                                                       size=.4f;
+                                                                       opacity=.4f;
+                                                                       if(k!=0&&tutoriallevel==1){
+                                                                               opacity=.2+.2*sin(smoketex*6+i);
                                                                        }
+                                                                       objects.model[j].MakeDecal(shadowdecal,&point,&size,&opacity,&rotation);
                                                                }
+                                                       }
                                                }
                                        }
                                        if((player[k].skeleton.free||player[k].howactive>=typesleeping)&&player[k].playerdetail)
@@ -437,20 +340,19 @@ int Game::DrawGLScene(StereoSide side)
                                                                                opacity=.2+.2*sin(smoketex*6+i)-player[k].skeleton.joints[i].position.y*player[k].scale/5-(player[k].coords.y-terrain.getHeight(player[k].coords.x,player[k].coords.z))/10;
                                                                        }
                                                                        terrain.MakeDecal(shadowdecal,point,size,opacity*.7,rotation);
-                                                                       if(terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz])
-                                                                               for(l=0;l<terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz];l++){
-                                                                                       j=terrain.patchobjects[player[k].whichpatchx][player[k].whichpatchz][l];
-                                                                                       if(objects.position[j].y<player[k].coords.y||objects.type[j]==tunneltype||objects.type[j]==weirdtype){
-                                                                                               if(player[k].skeleton.free)point=DoRotation(player[k].skeleton.joints[i].position*player[k].scale+player[k].coords-objects.position[j],0,-objects.rotation[j],0);
-                                                                                               else point=DoRotation(DoRotation(player[k].skeleton.joints[i].position,0,player[k].rotation,0)*player[k].scale+player[k].coords-objects.position[j],0,-objects.rotation[j],0);
-                                                                                               size=.4f;
-                                                                                               opacity=.4f;
-                                                                                               if(k!=0&&tutoriallevel==1){
-                                                                                                       opacity=.2+.2*sin(smoketex*6+i);
-                                                                                               }
-                                                                                               objects.model[j].MakeDecal(shadowdecal,&point,&size,&opacity,&rotation);
+                                                                       for(l=0;l<terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz];l++){
+                                                                               j=terrain.patchobjects[player[k].whichpatchx][player[k].whichpatchz][l];
+                                                                               if(objects.position[j].y<player[k].coords.y||objects.type[j]==tunneltype||objects.type[j]==weirdtype){
+                                                                                       if(player[k].skeleton.free)point=DoRotation(player[k].skeleton.joints[i].position*player[k].scale+player[k].coords-objects.position[j],0,-objects.rotation[j],0);
+                                                                                       else point=DoRotation(DoRotation(player[k].skeleton.joints[i].position,0,player[k].rotation,0)*player[k].scale+player[k].coords-objects.position[j],0,-objects.rotation[j],0);
+                                                                                       size=.4f;
+                                                                                       opacity=.4f;
+                                                                                       if(k!=0&&tutoriallevel==1){
+                                                                                               opacity=.2+.2*sin(smoketex*6+i);
                                                                                        }
+                                                                                       objects.model[j].MakeDecal(shadowdecal,&point,&size,&opacity,&rotation);
                                                                                }
+                                                                       }
                                                                }
                                                        }
 
@@ -461,14 +363,13 @@ int Game::DrawGLScene(StereoSide side)
                                                                        size=.7;
                                                                        opacity=.4-(player[k].coords.y-terrain.getHeight(player[k].coords.x,player[k].coords.z))/5;
                                                                        terrain.MakeDecal(shadowdecal,point,size,opacity*.7,rotation);
-                                                                       if(terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz])
-                                                                               for(l=0;l<terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz];l++){
-                                                                                       j=terrain.patchobjects[player[k].whichpatchx][player[k].whichpatchz][l];
-                                                                                       point=DoRotation(player[k].coords-objects.position[j],0,-objects.rotation[j],0);
-                                                                                       size=.7;
-                                                                                       opacity=.4f;
-                                                                                       objects.model[j].MakeDecal(shadowdecal,&point,&size,&opacity,&rotation);
-                                                                               }
+                                                                       for(l=0;l<terrain.patchobjectnum[player[k].whichpatchx][player[k].whichpatchz];l++){
+                                                                               j=terrain.patchobjects[player[k].whichpatchx][player[k].whichpatchz][l];
+                                                                               point=DoRotation(player[k].coords-objects.position[j],0,-objects.rotation[j],0);
+                                                                               size=.7;
+                                                                               opacity=.4f;
+                                                                               objects.model[j].MakeDecal(shadowdecal,&point,&size,&opacity,&rotation);
+                                                                       }
                                                                }
                }
 
@@ -567,29 +468,6 @@ int Game::DrawGLScene(StereoSide side)
                }
                glPopMatrix();
 
-               //if(cellophane){
-               /*glEnable(GL_CULL_FACE);
-               glCullFace(GL_FRONT);
-               glDepthMask(1);
-               for(k=0;k<numplayers;k++){
-               glEnable(GL_BLEND);
-               glEnable(GL_LIGHTING);
-               terrainlight=terrain.getLighting(player[k].coords.x,player[k].coords.z);
-               distance=findDistancefast(&viewer,&player[k].coords);
-               distance=(viewdistance*viewdistance-(distance-(viewdistance*viewdistance*fadestart))*(1/(1-fadestart)))/viewdistance/viewdistance;
-               glColor4f(terrainlight.x,terrainlight.y,terrainlight.z,distance);
-               if(distance>=1)glDisable(GL_BLEND);
-               if(distance>0){
-               checkpoint=DoRotation(player[k].skeleton.joints[abs(Random()%player[k].skeleton.num_joints)].position,0,player[k].rotation,0)*player[k].scale+player[k].coords;
-               checkpoint.y+=1;
-               if(checkcollide(viewer,checkpoint)){
-               player[k].occluded+=1;
-               }
-               else player[k].occluded=0;
-               if(player[k].occluded<25)player[k].DrawSkeleton();
-               }
-               }*/
-
                glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
                glEnable(GL_CULL_FACE);
                glCullFace(GL_FRONT);
@@ -617,7 +495,6 @@ int Game::DrawGLScene(StereoSide side)
                                }
                        }
                }
-               //}
 
                glPushMatrix();
                glEnable(GL_TEXTURE_2D);
@@ -632,7 +509,7 @@ int Game::DrawGLScene(StereoSide side)
 
                glDepthMask(0);
 
-               sprites.Draw();
+               Sprite::Draw();
 
                if(editorenabled){
                        glEnable(GL_BLEND);
@@ -682,38 +559,16 @@ int Game::DrawGLScene(StereoSide side)
 
                        if(!tutoriallevel)
                                if(bonus>0&&bonustime<1&&!winfreeze&&indialogue==-1/*bonustime<4*/){
-                                       if(bonus==tracheotomy)sprintf (string, "Tracheotomy!");
-                                       else if(bonus==backstab)sprintf (string, "Backstabber!");
-                                       else if(bonus==spinecrusher)sprintf (string, "Spinecrusher!");
-                                       else if(bonus==ninja)sprintf (string, "Ninja Bonus!");
-                                       else if(bonus==style)sprintf (string, "Style Bonus!");
-                                       else if(bonus==cannon)sprintf (string, "Leg Cannon!");
-                                       else if(bonus==aimbonus)sprintf (string, "Nice Aim!");
-                                       else if(bonus==deepimpact)sprintf (string, "Heavy Impact!");
-                                       else if(bonus==touchofdeath)sprintf (string, "Touch of Death!");
-                                       else if(bonus==swordreversebonus)sprintf (string, "Sword Disarm!");
-                                       else if(bonus==staffreversebonus)sprintf (string, "Staff Disarm!");
-                                       else if(bonus==reverseko)sprintf (string, "Reversal KO!");
-                                       else if(bonus==solidhit)sprintf (string, "Solid Hit!");
-                                       else if(bonus==twoxcombo)sprintf (string, "2X Combo!");
-                                       else if(bonus==threexcombo)sprintf (string, "3X Combo!");
-                                       else if(bonus==fourxcombo)sprintf (string, "4X COMBO!");
-                                       else if(bonus==megacombo)sprintf (string, "MEGA COMBO!");
-                                       else if(bonus==Reversal)sprintf (string, "Reversal!");
-                                       else if(bonus==Stabbonus)sprintf (string, "Punctured!");
-                                       else if(bonus==Slicebonus)sprintf (string, "Sliced!");
-                                       else if(bonus==Bullseyebonus)sprintf (string, "Bullseye!");
-                                       else if(bonus==Slashbonus)sprintf (string, "Slashed!");
-                                       else if(bonus==Wolfbonus)sprintf (string, "WOLF SLAYER!");
-                                       else if(bonus==FinishedBonus)sprintf (string, "SLAIN!");
-                                       else if(bonus==TackleBonus)sprintf (string, "Tackle!");
-                                       else if(bonus==AboveBonus)sprintf (string, "Death from Above!");
-                                       else sprintf (string, "Excellent!");
+                                       const char *bonus_name;
+                                       if (bonus < bonus_count)
+                                         bonus_name = bonus_names[bonus];
+                                       else
+                                         bonus_name = "Excellent!"; // When does this happen?
 
                                        glColor4f(0,0,0,1-bonustime);
-                                       text.glPrintOutline(1024/2-10*strlen(string)-4,768/16-4+768*4/5,string,1,2.5,1024,768);
+                                       text.glPrintOutline(1024/2-10*strlen(bonus_name)-4,768/16-4+768*4/5,bonus_name,1,2.5,1024,768);
                                        glColor4f(1,0,0,1-bonustime);
-                                       text.glPrint(1024/2-10*strlen(string),768/16+768*4/5,string,1,2,1024,768);
+                                       text.glPrint(1024/2-10*strlen(bonus_name),768/16+768*4/5,bonus_name,1,2,1024,768);
 
                                        sprintf (string, "%d",(int)bonusvalue);
                                        glColor4f(0,0,0,1-bonustime);
@@ -752,22 +607,22 @@ int Game::DrawGLScene(StereoSide side)
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==4){
-                                               sprintf (string, "Try using the %s, %s, %s and %s keys to move around.",KeyToChar(forwardkey),KeyToChar(leftkey),KeyToChar(backkey),KeyToChar(rightkey));
+                                               sprintf (string, "Try using the %s, %s, %s and %s keys to move around.",Input::keyToChar(forwardkey),Input::keyToChar(leftkey),Input::keyToChar(backkey),Input::keyToChar(rightkey));
                                                sprintf (string2, "All movement is relative to the camera.");
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==5){
-                                               sprintf (string, "Please press %s to jump.",KeyToChar(jumpkey));
+                                               sprintf (string, "Please press %s to jump.",Input::keyToChar(jumpkey));
                                                sprintf (string2, "You can hold it longer to jump higher.");
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==6){
-                                               sprintf (string, "You can press %s to crouch.",KeyToChar(crouchkey));
+                                               sprintf (string, "You can press %s to crouch.",Input::keyToChar(crouchkey));
                                                sprintf (string2, "You can jump higher from a crouching position.");
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==7){
-                                               sprintf (string, "While running, you can press %s to roll.",KeyToChar(crouchkey));
+                                               sprintf (string, "While running, you can press %s to roll.",Input::keyToChar(crouchkey));
                                                sprintf (string2, " ");
                                                sprintf (string3, " ");
                                        }
@@ -787,12 +642,12 @@ int Game::DrawGLScene(StereoSide side)
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==11){
-                                               sprintf (string, "When you jump at a wall, you can hold %s again",KeyToChar(jumpkey));
+                                               sprintf (string, "When you jump at a wall, you can hold %s again",Input::keyToChar(jumpkey));
                                                sprintf (string2, "during impact to perform a walljump.");
                                                sprintf (string3, "Be sure to use the movement keys to press against the wall");
                                        }
                                        if(tutorialstage==12){
-                                               sprintf (string, "While in the air, you can press crouch to flip.",KeyToChar(jumpkey));
+                                               sprintf (string, "While in the air, you can press crouch to flip.",Input::keyToChar(jumpkey));
                                                sprintf (string2, "Walljumps and flips confuse enemies and give you more control.");
                                                sprintf (string3, " ");
                                        }
@@ -807,8 +662,8 @@ int Game::DrawGLScene(StereoSide side)
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==15){
-                                               if(attackkey==MAC_MOUSEBUTTON1)sprintf (string, "Click to attack when you are near an enemy.");
-                                               else sprintf (string, "Press %s to attack when you are near an enemy.",KeyToChar(attackkey));
+                                               if(attackkey==MOUSEBUTTON1)sprintf (string, "Click to attack when you are near an enemy.");
+                                               else sprintf (string, "Press %s to attack when you are near an enemy.",Input::keyToChar(attackkey));
                                                sprintf (string2, "You can punch by standing still near an enemy and attacking.");
                                                sprintf (string3, " ");
                                        }
@@ -834,9 +689,9 @@ int Game::DrawGLScene(StereoSide side)
                                        }
                                        if(tutorialstage==20){
                                                sprintf (string, "Your most powerful individual attack is the rabbit kick.");
-                                               if(attackkey==MAC_MOUSEBUTTON1)sprintf (string2, "Run at the enemy while holding the mouse button, and press");
-                                               else sprintf (string2, "Run at the enemy while holding %s, and press", KeyToChar(attackkey));
-                                               sprintf (string3, "the jump key (%s) to attack.",KeyToChar(jumpkey));
+                                               if(attackkey==MOUSEBUTTON1)sprintf (string2, "Run at the enemy while holding the mouse button, and press");
+                                               else sprintf (string2, "Run at the enemy while holding %s, and press", Input::keyToChar(attackkey));
+                                               sprintf (string3, "the jump key (%s) to attack.",Input::keyToChar(jumpkey));
                                        }
                                        if(tutorialstage==21){
                                                sprintf (string, "This attack is devastating if timed correctly.");
@@ -856,8 +711,8 @@ int Game::DrawGLScene(StereoSide side)
                                        }
                                        if(tutorialstage==24){
                                                sprintf (string, "You can tackle enemies by running at them animal-style");
-                                               if(attackkey==MAC_MOUSEBUTTON1)sprintf (string2, "and pressing jump (%s) or attack(mouse button).",KeyToChar(jumpkey));
-                                               else sprintf (string2, "and pressing jump (%s) or attack(%s).",KeyToChar(jumpkey),KeyToChar(attackkey));
+                                               if(attackkey==MOUSEBUTTON1)sprintf (string2, "and pressing jump (%s) or attack(mouse button).",Input::keyToChar(jumpkey));
+                                               else sprintf (string2, "and pressing jump (%s) or attack(%s).",Input::keyToChar(jumpkey),Input::keyToChar(attackkey));
                                                sprintf (string3, "This is especially useful when they are running away.");
                                        }
                                        if(tutorialstage==25){
@@ -878,7 +733,7 @@ int Game::DrawGLScene(StereoSide side)
                                        if(tutorialstage==28){
                                                sprintf (string, "If you attack, you will notice that the enemy now sometimes");
                                                sprintf (string2, "catches your attack and uses it against you. Hold");
-                                               sprintf (string3, "crouch (%s) after attacking to escape from reversals.",KeyToChar(crouchkey));
+                                               sprintf (string3, "crouch (%s) after attacking to escape from reversals.",Input::keyToChar(crouchkey));
                                        }
                                        if(tutorialstage==29){
                                                sprintf (string, "Try escaping from two more reversals in a row.");
@@ -891,7 +746,7 @@ int Game::DrawGLScene(StereoSide side)
                                                sprintf (string3, " ");
                                        }
                                        if(tutorialstage==31){
-                                               sprintf (string, "To reverse an attack, you must tap crouch (%s) during the",KeyToChar(crouchkey));
+                                               sprintf (string, "To reverse an attack, you must tap crouch (%s) during the",Input::keyToChar(crouchkey));
                                                sprintf (string2, "enemy's attack. You must also be close to the enemy;");
                                                sprintf (string3, "this is especially important against armed opponents.");
                                        }
@@ -937,11 +792,11 @@ int Game::DrawGLScene(StereoSide side)
                                        }
                                        if(tutorialstage==40){
                                                sprintf (string, "Stand, roll or handspring over the knife");
-                                               sprintf (string2, "while pressing %s to pick it up.",KeyToChar(throwkey));
+                                               sprintf (string2, "while pressing %s to pick it up.",Input::keyToChar(throwkey));
                                                sprintf (string3, "You can crouch and press the same key to drop it again.");
                                        }
                                        if(tutorialstage==41){
-                                               sprintf (string, "You can equip and unequip weapons using the %s key.",KeyToChar(drawkey));
+                                               sprintf (string, "You can equip and unequip weapons using the %s key.",Input::keyToChar(drawkey));
                                                sprintf (string2, "Sometimes it is best to keep them unequipped to");
                                                sprintf (string3, "prevent enemies from taking them. ");
                                        }
@@ -981,7 +836,7 @@ int Game::DrawGLScene(StereoSide side)
                                                sprintf (string3, "spin smash is slower and more powerful.");
                                        }
                                        if(tutorialstage==49){
-                                               sprintf (string, "When facing an enemy, you can throw the knife with %s.",KeyToChar(throwkey));
+                                               sprintf (string, "When facing an enemy, you can throw the knife with %s.",Input::keyToChar(throwkey));
                                                sprintf (string2, "It is possible to throw the knife while flipping,");
                                                sprintf (string3, "but it is very inaccurate.");
                                        }
@@ -1005,7 +860,7 @@ int Game::DrawGLScene(StereoSide side)
                                        text.glPrint(screenwidth/2-7.6*strlen(string2)*screenwidth/1024,screenheight/16+screenheight*4/5-20*screenwidth/1024,string2,1,1.5*screenwidth/1024,screenwidth,screenheight);
                                        text.glPrint(screenwidth/2-7.6*strlen(string3)*screenwidth/1024,screenheight/16+screenheight*4/5-40*screenwidth/1024,string3,1,1.5*screenwidth/1024,screenwidth,screenheight);
 
-                                       sprintf (string, "Press 'tab' to skip to the next item.",KeyToChar(jumpkey));
+                                       sprintf (string, "Press 'tab' to skip to the next item.",Input::keyToChar(jumpkey));
                                        sprintf (string2, "Press escape at any time to");
                                        sprintf (string3, "pause or exit the tutorial.");
 
@@ -1047,10 +902,9 @@ int Game::DrawGLScene(StereoSide side)
 
                                                        sprintf (string, "%s", hotspottext[closest]);
 
-                                                       int lastline;
-                                                       int line=0;
-                                                       bool done=0;
-                                                       lastline=0;
+                                                       int lastline = 0;
+                                                       int line = 0;
+                                                       bool done = false;
                                                        i=0;
                                                        while(!done){
                                                                if(string[i]=='\n'||string[i]>'z'||string[i]<' '||string[i]=='\0'){
@@ -1080,14 +934,6 @@ int Game::DrawGLScene(StereoSide side)
                                                        indialogue=0;
                                                        dialoguegonethrough[whichdialogue]++;
                                                        if(dialogueboxsound[whichdialogue][indialogue]!=0){
-                                                               static float gLoc[3];
-                                                               static float vel[3];
-                                                               gLoc[0]=player[participantfocus[whichdialogue][indialogue]].coords.x;
-                                                               gLoc[1]=player[participantfocus[whichdialogue][indialogue]].coords.y;
-                                                               gLoc[2]=player[participantfocus[whichdialogue][indialogue]].coords.z;
-                                                               vel[0]=0;
-                                                               vel[1]=0;
-                                                               vel[2]=0;
                                                                int whichsoundplay;
                                                                if(dialogueboxsound[whichdialogue][indialogue]==1)whichsoundplay=rabbitchitter;
                                                                if(dialogueboxsound[whichdialogue][indialogue]==2)whichsoundplay=rabbitchitter2;
@@ -1109,10 +955,7 @@ int Game::DrawGLScene(StereoSide side)
                                                                if(dialogueboxsound[whichdialogue][indialogue]==-2)whichsoundplay=firestartsound;
                                                                if(dialogueboxsound[whichdialogue][indialogue]==-3)whichsoundplay=consolesuccesssound;
                                                                if(dialogueboxsound[whichdialogue][indialogue]==-4)whichsoundplay=consolefailsound;
-                                                               PlaySoundEx( whichsoundplay, samp[whichsoundplay], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[whichsoundplay], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[whichsoundplay], 256);
-                                                               OPENAL_SetPaused(channels[whichsoundplay], false);
+                                                               emit_sound_at(whichsoundplay, player[participantfocus[whichdialogue][indialogue]].coords);
                                                        }
                                                }
                                        }
@@ -1162,11 +1005,9 @@ int Game::DrawGLScene(StereoSide side)
                                        if(dialogueboxlocation[whichdialogue][indialogue]==1)starty=screenheight/16+screenheight*4/5;
                                        if(dialogueboxlocation[whichdialogue][indialogue]==2)starty=screenheight*1/5-screenheight/16;
 
-//                                     char tempname[64];
                                        char tempname[264];
                                        bool goodchar;
                                        int tempnum=0;
-//                                     for(i=0;i<64;i++){
                                        for(i=0;i<264;i++){
                                                tempname[i]='\0';
                                        }
@@ -1175,10 +1016,10 @@ int Game::DrawGLScene(StereoSide side)
                                                tempname[tempnum]=dialoguename[whichdialogue][indialogue][i];
                                                goodchar=1;
                                                if(dialoguename[whichdialogue][indialogue][i]=='#'||dialoguename[whichdialogue][indialogue][i]=='\0')goodchar=0;
-                                               //if(tempnum>2)if(tempname[tempnum-2]=='e'&&tempname[tempnum-1]=='r')goodchar=0;
-                                               //if(tempnum>2)if(tempname[tempnum]=='r'&&tempname[0]=='a')goodchar=0;
-                                               if(goodchar)tempnum++;
-                                               else tempname[tempnum]='\0';
+                                               if(goodchar)
+                                                       tempnum++;
+                                               else
+                                                       tempname[tempnum]='\0';
                                        }
 
                                        sprintf (string, "%s: ", tempname);
@@ -1193,7 +1034,6 @@ int Game::DrawGLScene(StereoSide side)
                                        {
                                                glColor4f(0,0,0,tutorialopac);
                                                text.glPrintOutline(startx-2*7.6*strlen(string)*screenwidth/1024-4,starty-4,string,1,1.5*1.25*screenwidth/1024,screenwidth,screenheight);
-
                                        }
 
                                        tempnum=0;
@@ -1202,14 +1042,11 @@ int Game::DrawGLScene(StereoSide side)
                                                if(dialoguetext[whichdialogue][indialogue][i]!='#')tempnum++;
                                        }
 
-
                                        sprintf (string, "%s", tempname);
 
-
-                                       int lastline;
-                                       int line=0;
-                                       bool done=0;
-                                       lastline=0;
+                                       int lastline = 0;
+                                       int line = 0;
+                                       bool done = false;
                                        i=0;
                                        while(!done){
                                                if(string[i]=='\n'||string[i]>'z'||string[i]<' '||string[i]=='\0'){
@@ -1235,8 +1072,10 @@ int Game::DrawGLScene(StereoSide side)
 
                                if(!tutoriallevel&&!winfreeze&&indialogue==-1&&!mainmenu){
                                        if(campaign){
-                                               if(!scoreadded)sprintf (string, "Score: %d", (int)accountcampaignscore[accountactive]+(int)bonustotal);//(int)bonustotal);
-                                               if(scoreadded)sprintf (string, "Score: %d", (int)accountcampaignscore[accountactive]);//(int)bonustotal);
+                                               if(scoreadded)
+                                                       sprintf (string, "Score: %d", (int)accountactive->getCampaignScore());
+                                               else
+                                                       sprintf (string, "Score: %d", (int)accountactive->getCampaignScore()+(int)bonustotal);
                                        }
                                        if(!campaign)sprintf (string, "Score: %d", (int)bonustotal);
                                        glColor4f(0,0,0,1);
@@ -1340,8 +1179,10 @@ int Game::DrawGLScene(StereoSide side)
                                        text.glPrint(10,260,string,0,.8,1024,768);
 
 
-                                       if(editorenabled)sprintf (string, "Map editor enabled.");
-                                       if(!editorenabled)sprintf (string, "Map editor Disabled.");
+                                       if(editorenabled)
+                                               sprintf (string, "Map editor enabled.");
+                                       else
+                                               sprintf (string, "Map editor disabled.");
                                        text.glPrint(10,60,string,0,.8,1024,768);
                                        if(editorenabled){
                                                sprintf (string, "Object size: %f",editorsize);
@@ -1354,18 +1195,44 @@ int Game::DrawGLScene(StereoSide side)
                                                text.glPrint(10,105,string,0,.8,1024,768);
                                                sprintf (string, "Object type: %d",editortype);
                                                text.glPrint(10,120,string,0,.8,1024,768);
-                                               if(editortype==boxtype)sprintf (string, "(box)");
-                                               if(editortype==treetrunktype)sprintf (string, "(tree)");
-                                               if(editortype==walltype)sprintf (string, "(wall)");
-                                               if(editortype==weirdtype)sprintf (string, "(weird)");
-                                               if(editortype==spiketype)sprintf (string, "(spike)");
-                                               if(editortype==rocktype)sprintf (string, "(rock)");
-                                               if(editortype==bushtype)sprintf (string, "(bush)");
-                                               if(editortype==tunneltype)sprintf (string, "(tunnel)");
-                                               if(editortype==chimneytype)sprintf (string, "(chimney)");
-                                               if(editortype==platformtype)sprintf (string, "(platform)");
-                                               if(editortype==cooltype)sprintf (string, "(cool)");
-                                               if(editortype==firetype)sprintf (string, "(fire)");
+                                               switch(editortype) {
+                                                       case boxtype: 
+                                                               sprintf (string, "(box)");
+                                                               break;
+                                                       case treetrunktype: 
+                                                               sprintf (string, "(tree)");
+                                                               break;
+                                                       case walltype: 
+                                                               sprintf (string, "(wall)");
+                                                               break;
+                                                       case weirdtype: 
+                                                               sprintf (string, "(weird)");
+                                                               break;
+                                                       case spiketype: 
+                                                               sprintf (string, "(spike)");
+                                                               break;
+                                                       case rocktype: 
+                                                               sprintf (string, "(rock)");
+                                                               break;
+                                                       case bushtype: 
+                                                               sprintf (string, "(bush)");
+                                                               break;
+                                                       case tunneltype: 
+                                                               sprintf (string, "(tunnel)");
+                                                               break;
+                                                       case chimneytype: 
+                                                               sprintf (string, "(chimney)");
+                                                               break;
+                                                       case platformtype: 
+                                                               sprintf (string, "(platform)");
+                                                               break;
+                                                       case cooltype: 
+                                                               sprintf (string, "(cool)");
+                                                               break;
+                                                       case firetype: 
+                                                               sprintf (string, "(fire)");
+                                                               break;
+                                               }
                                                text.glPrint(130,120,string,0,.8,1024,768);
 
                                                sprintf (string, "Numplayers: %d",numplayers);
@@ -1373,17 +1240,8 @@ int Game::DrawGLScene(StereoSide side)
                                                sprintf (string, "Player %d: numwaypoints: %d",numplayers,player[numplayers-1].numwaypoints);
                                                text.glPrint(10,140,string,0,.8,1024,768);
                                        }
-                                       /*sprintf (string, "Coords are: %f %f %f",player[0].coords.x,player[0].coords.y,player[0].coords.z);
-                                       text.glPrint(10,200,string,0,.8,1024,768);*/
                                        sprintf (string, "Difficulty: %d",difficulty);
                                        text.glPrint(10,240,string,0,.8,1024,768);
-                                       /*
-                                       sprintf (string, "lasthotspot: %d",hotspottype[numhotspots-1]);
-                                       text.glPrint(10,240,string,0,.8,1024,768);
-                                       sprintf (string, "killhotspot: %d",killhotspot);
-                                       text.glPrint(10,220,string,0,.8,1024,768);
-                                       sprintf (string, "winhotspot: %d",winhotspot);
-                                       text.glPrint(10,200,string,0,.8,1024,768);*/
 
                                }
                }
@@ -1529,8 +1387,7 @@ int Game::DrawGLScene(StereoSide side)
                }
 
                if(minimap&&indialogue==-1){
-                       float mapviewdist;
-                       mapviewdist=20000;
+                       float mapviewdist = 20000;
 
                        glDisable(GL_DEPTH_TEST);
                        glColor3f (1.0, 1.0, 1.0); // no coloring
@@ -1555,19 +1412,17 @@ int Game::DrawGLScene(StereoSide side)
                        glEnable(GL_BLEND);
                        glColor4f(1,1,1,1);
                        glPushMatrix();
-                       float opac;
-                       opac=.7;
+                       float opac = .7;
                        XYZ center;
                        float radius;
                        float distcheck;
-                       center=0;
                        int numliveplayers=0;
+                       center = 0;
                        for(i=0;i<numplayers;i++){
-                               if(!player[i].dead)numliveplayers++;
+                               if(!player[i].dead) numliveplayers++;
                        }
 
-                       int numadd;
-                       numadd=0;
+                       int numadd = 0;
 
                        for(i=0;i<objects.numobjects;i++){
                                if(objects.type[i]==treetrunktype||objects.type[i]==boxtype){
@@ -1608,17 +1463,6 @@ int Game::DrawGLScene(StereoSide side)
                        glScalef(.25/radius*256*terrain.scale*.4,.25/radius*256*terrain.scale*.4,1);
                        glPushMatrix();
                        glScalef(1/(1/radius*256*terrain.scale*.4),1/(1/radius*256*terrain.scale*.4),1);
-                       /*float startx,starty,endx,endy;
-                       glBegin(GL_QUADS);
-                       glTexCoord2f(1-(center.x-radius)/terrain.scale/256,(center.z-radius)/terrain.scale/256);
-                       glVertex3f(-1,          -1,      0.0f);
-                       glTexCoord2f(1-(center.x+radius)/terrain.scale/256,(center.z-radius)/terrain.scale/256);
-                       glVertex3f(1,   -1,      0.0f);
-                       glTexCoord2f(1-(center.x+radius)/terrain.scale/256,(center.z+radius)/terrain.scale/256);
-                       glVertex3f(1,   1, 0.0f);
-                       glTexCoord2f(1-(center.x-radius)/terrain.scale/256,(center.z+radius)/terrain.scale/256);
-                       glVertex3f(-1,  1, 0.0f);
-                       glEnd();*/
                        glPopMatrix();
                        glRotatef(player[0].lookrotation*-1+180,0,0,1);
                        glTranslatef(-(center.x/terrain.scale/256*-2+1),(center.z/terrain.scale/256*-2+1),0);
@@ -1712,27 +1556,9 @@ int Game::DrawGLScene(StereoSide side)
                                        glTexCoord2f(0,1);
                                        glVertex3f(-1,  1, 0.0f);
                                        glEnd();
-                                       /*glBegin(GL_TRIANGLES);
-                                       glTexCoord2f(0,0);
-                                       glVertex3f(-1,          -1,      0.0f);
-                                       glTexCoord2f(1,0);
-                                       glVertex3f(1,   -1,      0.0f);
-                                       glTexCoord2f(1,1);
-                                       glVertex3f(0,   1, 0.0f);
-                                       glEnd();*/
                                        glPopMatrix();
                                }
                        }
-                       /*glBegin(GL_QUADS);
-                       glTexCoord2f(0,0);
-                       glVertex3f(-1,          -1,      0.0f);
-                       glTexCoord2f(1,0);
-                       glVertex3f(1,   -1,      0.0f);
-                       glTexCoord2f(1,1);
-                       glVertex3f(1,   1, 0.0f);
-                       glTexCoord2f(0,1);
-                       glVertex3f(-1,  1, 0.0f);
-                       glEnd();*/
                        glPopMatrix();
                        glDisable(GL_TEXTURE_2D);
                        glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
@@ -1745,12 +1571,6 @@ int Game::DrawGLScene(StereoSide side)
                        glDepthMask(1);
                }
 
-               /*if(loading){
-               loading=2;
-               drawmode=normalmode;
-               }*/
-
-
                if(loading&&!stealthloading&&(!campaign||player[0].dead)){
                        glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
                        glDisable(GL_CULL_FACE);
@@ -1788,47 +1608,6 @@ int Game::DrawGLScene(StereoSide side)
                        glColor3f (1.0, 1.0, 1.0); // no coloring
 
                        glEnable(GL_TEXTURE_2D);
-                       /*glBindTexture( GL_TEXTURE_2D, logotexture);
-                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
-                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
-                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
-                       glDisable(GL_CULL_FACE);
-                       glDisable(GL_LIGHTING);
-                       glDepthMask(0);
-                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                       glPushMatrix();                                                                         // Store The Projection Matrix
-                       glLoadIdentity();                                                                       // Reset The Projection Matrix
-                       glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
-                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                       glPushMatrix();                                                                         // Store The Modelview Matrix
-                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                       glScalef((float)screenwidth/2,(float)screenwidth/2,1);
-                       glTranslatef(1.8,1.25,0);
-                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       glEnable(GL_BLEND);
-                       glColor4f(1,1,1,1);
-                       glPushMatrix();
-                       glScalef(.25,.25,.25);
-                       glBegin(GL_QUADS);
-                       glTexCoord2f(0,0);
-                       glVertex3f(-1,          -1,      0.0f);
-                       glTexCoord2f(1,0);
-                       glVertex3f(1,   -1,      0.0f);
-                       glTexCoord2f(1,1);
-                       glVertex3f(1,   1, 0.0f);
-                       glTexCoord2f(0,1);
-                       glVertex3f(-1,  1, 0.0f);
-                       glEnd();
-                       glPopMatrix();
-                       glDisable(GL_TEXTURE_2D);
-                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                       glPopMatrix();                                                                          // Restore The Old Projection Matrix
-                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                       glPopMatrix();                                                                          // Restore The Old Projection Matrix
-                       glEnable(GL_DEPTH_TEST);                                                        // Enables Depth Testing
-                       glEnable(GL_CULL_FACE);
-                       glDisable(GL_BLEND);
-                       glDepthMask(1);*/
 
                        //Minimap
 
@@ -1880,183 +1659,39 @@ int Game::DrawGLScene(StereoSide side)
                        glColor3f (1.0, 1.0, 1.0); // no coloring
 
                        glEnable(GL_TEXTURE_2D);
-                       /*glBindTexture( GL_TEXTURE_2D, logotexture);
-                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
-                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
-                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
-                       glDisable(GL_CULL_FACE);
-                       glDisable(GL_LIGHTING);
-                       glDepthMask(0);
-                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                       glPushMatrix();                                                                         // Store The Projection Matrix
-                       glLoadIdentity();                                                                       // Reset The Projection Matrix
-                       glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
-                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                       glPushMatrix();                                                                         // Store The Modelview Matrix
-                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                       glScalef((float)screenwidth/2,(float)screenwidth/2,1);
-                       glTranslatef(1.8,1.25,0);
-                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       glEnable(GL_BLEND);
+
+                       //Win Screen Won Victory
+
+                       glEnable(GL_TEXTURE_2D);
                        glColor4f(1,1,1,1);
-                       glPushMatrix();
-                       glScalef(.25,.25,.25);
-                       glBegin(GL_QUADS);
-                       glTexCoord2f(0,0);
-                       glVertex3f(-1,          -1,      0.0f);
-                       glTexCoord2f(1,0);
-                       glVertex3f(1,   -1,      0.0f);
-                       glTexCoord2f(1,1);
-                       glVertex3f(1,   1, 0.0f);
-                       glTexCoord2f(0,1);
-                       glVertex3f(-1,  1, 0.0f);
-                       glEnd();
-                       glPopMatrix();
-                       glDisable(GL_TEXTURE_2D);
-                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                       glPopMatrix();                                                                          // Restore The Old Projection Matrix
-                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                       glPopMatrix();                                                                          // Restore The Old Projection Matrix
-                       glEnable(GL_DEPTH_TEST);                                                        // Enables Depth Testing
-                       glEnable(GL_CULL_FACE);
-                       glDisable(GL_BLEND);
-                       glDepthMask(1);*/
+                       sprintf (string, "Level Cleared!");
+                       text.glPrintOutlined(1024/2-strlen(string)*10,768*7/8,string,1,2,1024,768);
 
-                       //Awards
-                       int numawards;
-                       int awards[30];
-                       numawards=0;
+                       sprintf (string, "Score:     %d",(int)(bonustotal-startbonustotal));
+                       text.glPrintOutlined(1024/30,768*6/8,string,1,2,1024,768);
 
-                       if(damagetaken==0&&player[0].bloodloss==0){
-                               awards[numawards]=awardflawless;
-                               numawards++;
-                       }
-                       bool alldead;
-                       alldead=1;
-                       if(numplayers>1)
-                               for(i=1;i<numplayers;i++){              
-                                       if(player[i].dead!=2)alldead=0;
-                               }
-                               if(alldead){
-                                       awards[numawards]=awardalldead;
-                                       numawards++;
-                               }
-                               alldead=1;
-                               if(numplayers>1)
-                                       for(i=1;i<numplayers;i++){              
-                                               if(player[i].dead!=1)alldead=0;
-                                       }
-                                       if(alldead){
-                                               awards[numawards]=awardnodead;
-                                               numawards++;
-                                       }
-                                       if(numresponded==0&&!numthrowkill){
-                                               awards[numawards]=awardstealth;
-                                               numawards++;
-                                       }
-                                       if(numattacks==numstaffattack&&numattacks>0){
-                                               awards[numawards]=awardbojutsu;
-                                               numawards++;
-                                       }
-                                       if(numattacks==numswordattack&&numattacks>0){
-                                               awards[numawards]=awardswordsman;
-                                               numawards++;
-                                       }
-                                       if(numattacks==numknifeattack&&numattacks>0){
-                                               awards[numawards]=awardknifefighter;
-                                               numawards++;
-                                       }
-                                       if(numattacks==numunarmedattack&&numthrowkill==0&&weapons.numweapons>0){
-                                               awards[numawards]=awardkungfu;
-                                               numawards++;
-                                       }
-                                       if(numescaped>0){
-                                               awards[numawards]=awardevasion;
-                                               numawards++;
-                                       }
-                                       if(numflipfail==0&&numflipped+numwallflipped*2>20){
-                                               awards[numawards]=awardacrobat;
-                                               numawards++;
-                                       }
-                                       if(numthrowkill==numplayers-1){
-                                               awards[numawards]=awardlongrange;
-                                               numawards++;
-                                       }
-                                       alldead=1;
-                                       if(numplayers>1)
-                                               for(i=1;i<numplayers;i++){              
-                                                       if(player[i].dead!=2)alldead=0;
-                                               }
-                                               if(numafterkill>0&&alldead){
-                                                       awards[numawards]=awardbrutal;
-                                                       numawards++;
-                                               }
-                                               if(numreversals>((float)numattacks)*.8&&numreversals>3){
-                                                       awards[numawards]=awardaikido;
-                                                       numawards++;
-                                               }
-                                               if(maxalarmed==1&&numplayers>2){
-                                                       awards[numawards]=awardstrategy;
-                                                       numawards++;
-                                               }
-                                               if(numflipfail>3){
-                                                       awards[numawards]=awardklutz;
-                                                       numawards++;
-                                               }
+                       if(campaign)
+                               sprintf (string, "Press Escape or Space to continue");
+                       else
+                               sprintf (string, "Press Escape to return to menu or Space to continue");
+                       text.glPrintOutlined(640/2-strlen(string)*5,480*1/16,string,1,1,640,480);
 
+                       char temp[255];
 
-                                               //Win Screen Won Victory
+                       for(i=0;i<255;i++)string[i]='\0';
+                       sprintf (temp, "Time:      %d:",(int)(((int)leveltime-(int)(leveltime)%60)/60));
+                       strcat(string,temp);
+                       if((int)(leveltime)%60<10)strcat(string,"0");
+                       sprintf (temp, "%d",(int)(leveltime)%60);
+                       strcat(string,temp);
+                       text.glPrintOutlined(1024/30,768*6/8-40,string,1,2,1024,768);
 
-                                               glEnable(GL_TEXTURE_2D);
-                                               glColor4f(1,1,1,1);
-                                               sprintf (string, "Level Cleared!");
-                                               text.glPrintOutlined(1024/2-strlen(string)*10,768*7/8,string,1,2,1024,768);
-
-                                               sprintf (string, "Score:     %d",(int)(bonustotal-startbonustotal));
-                                               text.glPrintOutlined(1024/30,768*6/8,string,1,2,1024,768);
-
-                                               if(!campaign)sprintf (string, "Press Escape to return to menu or Space to continue");
-                                               if(campaign)sprintf (string, "Press Escape or Space to continue");
-                                               text.glPrintOutlined(640/2-strlen(string)*5,480*1/16,string,1,1,640,480);
-
-                                               char temp[255];
-
-                                               for(i=0;i<255;i++)string[i]='\0';
-                                               sprintf (temp, "Time:      %d:",(int)(((int)leveltime-(int)(leveltime)%60)/60));
-                                               strcat(string,temp);
-                                               if((int)(leveltime)%60<10)strcat(string,"0");
-                                               sprintf (temp, "%d",(int)(leveltime)%60);
-                                               strcat(string,temp);
-                                               text.glPrintOutlined(1024/30,768*6/8-40,string,1,2,1024,768);
-
-                                               for(i=0;i<numawards;i++){
-                                                       if(i<6){
-                                                               if(awards[i]==awardklutz)sprintf (string, "Suicidal");
-                                                               if(awards[i]==awardflawless)sprintf (string, "Flawless!");
-                                                               if(awards[i]==awardalldead)sprintf (string, "Take no prisoners");
-                                                               if(awards[i]==awardnodead)sprintf (string, "Merciful");
-                                                               if(awards[i]==awardstealth)sprintf (string, "One with the shadows!");
-                                                               if(awards[i]==awardswordsman)sprintf (string, "Swordsman");
-                                                               if(awards[i]==awardkungfu)sprintf (string, "Unarmed!");
-                                                               if(awards[i]==awardknifefighter)sprintf (string, "Knife fighter");
-                                                               if(awards[i]==awardcoward)sprintf (string, "Coward");
-                                                               if(awards[i]==awardevasion)sprintf (string, "Escape artist");
-                                                               if(awards[i]==awardacrobat)sprintf (string, "Gymnast");
-                                                               if(awards[i]==awardlongrange)sprintf (string, "Blade slinger");
-                                                               if(awards[i]==awardbrutal)sprintf (string, "Brutal");
-                                                               if(awards[i]==awardhyper)sprintf (string, "Hyper");
-                                                               if(awards[i]==awardaikido)sprintf (string, "Aikido master!");
-                                                               if(awards[i]==awardrambo)sprintf (string, "Rambo");
-                                                               if(awards[i]==awardfast)sprintf (string, "Fast");
-                                                               if(awards[i]==awardrealfast)sprintf (string, "Real fast");
-                                                               if(awards[i]==awarddamnfast)sprintf (string, "Damn fast");
-                                                               if(awards[i]==awardstrategy)sprintf (string, "Divide and conquer");
-                                                               if(awards[i]==awardbojutsu)sprintf (string, "Bojutsu");
-                                                               text.glPrintOutlined(1024/30,768*6/8-90-40*i,string,1,2,1024,768);
-                                                       }
-                                               }
+                       //Awards
+                       int awards[award_count];
+                       int numawards = award_awards(awards);
 
-                                               //drawmode=normalmode;
+                       for (i = 0; i < numawards && i < 6; i++)
+                         text.glPrintOutlined(1024/30,768*6/8-90-40*i,award_names[awards[i]],1,2,1024,768);
                }
 
                if(drawmode!=normalmode){
@@ -2108,8 +1743,6 @@ int Game::DrawGLScene(StereoSide side)
                        if(drawmode==motionblurmode){
                                glDrawBuffer(GL_FRONT);
                                glReadBuffer(GL_BACK);
-                               //myassert(glGetError() == GL_NO_ERROR);
-                               //glFlush();
                        }
                        glColor3f (1.0, 1.0, 1.0); // no coloring
 
@@ -2312,23 +1945,21 @@ int Game::DrawGLScene(StereoSide side)
                if(console){
                        glEnable(GL_TEXTURE_2D);
                        glColor4f(1,1,1,1);
-                       if(console){
-                               int offset;
-                               offset=0;
-                               if(consoleselected>=60)offset=consoleselected-60;
-                               sprintf (string, " ]");
-                               text.glPrint(10,30,string,0,1,1024,768);
-                               if(consoleblink){
-                                       sprintf (string, "_");
-                                       text.glPrint(30+(float)(consoleselected)*10-offset*10,30,string,0,1,1024,768);
-                               }
-                               for(i=0;i<15;i++){
-                                       for(j=0;j<consolechars[i];j++){
-                                               glColor4f(1,1,1,1-(float)(i)/16);
-                                               if(j<consolechars[i]){
-                                                       sprintf (string, "%c",consoletext[i][j]);
-                                                       text.glPrint(30+j*10-offset*10,30+i*20,string,0,1,1024,768);
-                                               }
+                       int offset = 0;
+                       if(consoleselected>=60)
+                               offset=consoleselected-60;
+                       sprintf (string, " ]");
+                       text.glPrint(10,30,string,0,1,1024,768);
+                       if(consoleblink){
+                               sprintf (string, "_");
+                               text.glPrint(30+(float)(consoleselected)*10-offset*10,30,string,0,1,1024,768);
+                       }
+                       for(i=0;i<15;i++){
+                               for(j=0;j<consolechars[i];j++){
+                                       glColor4f(1,1,1,1-(float)(i)/16);
+                                       if(j<consolechars[i]){
+                                               sprintf (string, "%c",consoletext[i][j]);
+                                               text.glPrint(30+j*10-offset*10,30+i*20,string,0,1,1024,768);
                                        }
                                }
                        }
@@ -2356,29 +1987,15 @@ int Game::DrawGLScene(StereoSide side)
                        if(mainmenu==1){
                                LoadTexture(":Data:Textures:Newgame.png",&Mainmenuitems[1],0,0);
                                LoadTexture(":Data:Textures:Quit.png",&Mainmenuitems[3],0,0);
-                               /*if(oldmainmenu==1||oldmainmenu==0){
-                               LoadTexture(":Data:Textures:World.png",&Mainmenuitems[7],0,0);
-                               LoadTexture(":Data:Textures:Options.png",&Mainmenuitems[2],0,0);
-                               LoadTexture(":Data:Textures:Lugaru.png",&Mainmenuitems[0],0,0);
-                               loaddistrib=0;
-                               }*/
                        }
                        if(mainmenu==2){
                                LoadTexture(":Data:Textures:Resume.png",&Mainmenuitems[1],0,0);
                                LoadTexture(":Data:Textures:Endgame.png",&Mainmenuitems[3],0,0);
-                               /*if(oldmainmenu==2||oldmainmenu==0){
-                               LoadTexture(":Data:Textures:World.png",&Mainmenuitems[7],0,0);
-                               LoadTexture(":Data:Textures:Options.png",&Mainmenuitems[2],0,0);
-                               LoadTexture(":Data:Textures:Lugaru.png",&Mainmenuitems[0],0,0);
-                               loaddistrib=0;
-                               }*/
                        }
                }
                if(lastcheck>.5||oldmainmenu!=mainmenu){
                        if(mainmenu==5){
                                ifstream ipstream(ConvertFileName(":Data:Campaigns:main.txt"));
-                               //campaignnumlevels=0;
-                               //accountcampaignchoicesmade[accountactive]=0;
                                ipstream.ignore(256,':');
                                ipstream >> campaignnumlevels;
                                for(i=0;i<campaignnumlevels;i++){
@@ -2395,18 +2012,15 @@ int Game::DrawGLScene(StereoSide side)
                                        ipstream >> campaignchoosenext[i];
                                        ipstream.ignore(256,':');
                                        ipstream >> campaignnumnext[i];
-                                       if(campaignnumnext[i])
-                                               for(j=0;j<campaignnumnext[i];j++){
-                                                       ipstream.ignore(256,':');
-                                                       ipstream >> campaignnextlevel[i][j];
-                                                       campaignnextlevel[i][j]-=1;
-                                               }
-                                               ipstream.ignore(256,':');
-                                               ipstream >> campaignlocationx[i];
-                                               //campaignlocationx[i]-=30;
+                                       for(j=0;j<campaignnumnext[i];j++){
                                                ipstream.ignore(256,':');
-                                               ipstream >> campaignlocationy[i];
-                                               //campaignlocationy[i]+=30;
+                                               ipstream >> campaignnextlevel[i][j];
+                                               campaignnextlevel[i][j]-=1;
+                                       }
+                                       ipstream.ignore(256,':');
+                                       ipstream >> campaignlocationx[i];
+                                       ipstream.ignore(256,':');
+                                       ipstream >> campaignlocationy[i];
                                }
                                ipstream.close();
 
@@ -2417,37 +2031,26 @@ int Game::DrawGLScene(StereoSide side)
 
                                levelorder[0]=0;
                                levelvisible[0]=1;
-                               if(accountcampaignchoicesmade[accountactive])
-                                       for(i=0;i<accountcampaignchoicesmade[accountactive];i++){
-                                               levelorder[i+1]=campaignnextlevel[levelorder[i]][accountcampaignchoices[accountactive][i]];
-                                               levelvisible[levelorder[i+1]]=1;
-                                       }
-                                       int whichlevelstart;
-                                       whichlevelstart=accountcampaignchoicesmade[accountactive]-1;
-                                       if(whichlevelstart<0){
-                                               accountcampaignscore[accountactive]=0;
-                                               accountcampaignfasttime[accountactive]=0;
-                                               campaignchoicenum=1;
-                                               campaignchoicewhich[0]=0;
-                                       }
-                                       else
-                                       {
-                                               campaignchoicenum=campaignnumnext[levelorder[whichlevelstart]];
-                                               if(campaignchoicenum==0){
-                                                       if(accountcampaignscore[accountactive]>accountcampaignhighscore[accountactive])accountcampaignhighscore[accountactive]=accountcampaignscore[accountactive];
-                                                       if(accountcampaignfasttime[accountactive]==0||accountcampaigntime[accountactive]<accountcampaignfasttime[accountactive])accountcampaignfasttime[accountactive]=accountcampaigntime[accountactive];              
-                                               }
-                                               if(campaignchoicenum)
-                                                       for(i=0;i<campaignchoicenum;i++){
-                                                               campaignchoicewhich[i]=campaignnextlevel[levelorder[whichlevelstart]][i];
-                                                               levelvisible[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
-                                                               levelhighlight[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
-                                                       }
+                               for(i=0;i<accountactive->getCampaignChoicesMade();i++){
+                                       levelorder[i+1]=campaignnextlevel[levelorder[i]][accountactive->getCampaignChoice(i)];
+                                       levelvisible[levelorder[i+1]]=1;
+                               }
+                               int whichlevelstart = accountactive->getCampaignChoicesMade()-1;
+                               if(whichlevelstart<0){
+                                       accountactive->setCampaignScore(0);
+                                       accountactive->resetFasttime();
+                                       campaignchoicenum=1;
+                                       campaignchoicewhich[0]=0;
+                               }
+                               else
+                               {
+                                       campaignchoicenum=campaignnumnext[levelorder[whichlevelstart]];
+                                       for(i=0;i<campaignchoicenum;i++){
+                                               campaignchoicewhich[i]=campaignnextlevel[levelorder[whichlevelstart]][i];
+                                               levelvisible[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
+                                               levelhighlight[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
                                        }
-                                       /*levelorder[0]=0;
-                                       levelorder[1]=1;
-                                       levelorder[2]=2;
-                                       levelorder[3]=3;*/
+                               }
                        }
                }
                if(mainmenu==5){
@@ -2456,9 +2059,9 @@ int Game::DrawGLScene(StereoSide side)
 
                texdetail=temptexdetail;
 
-               /*if(mainmenu!=0)*/oldmainmenu=mainmenu;
+               oldmainmenu=mainmenu;
 
-               if(mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==8||mainmenu==9||mainmenu==10||mainmenu==119||mainmenu==13||mainmenu==17||mainmenu==18){
+               if(mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==8||mainmenu==9||mainmenu==10||mainmenu==119||mainmenu==18){
                        glClear(GL_DEPTH_BUFFER_BIT);
                        glEnable(GL_ALPHA_TEST);
                        glAlphaFunc(GL_GREATER, 0.001f);
@@ -2650,7 +2253,7 @@ int Game::DrawGLScene(StereoSide side)
 
                        if(mainmenu==4){                        
                                nummenuitems=10;
-                               if(keyselect!=0)sprintf (menustring[0], "Forwards: %s",KeyToChar(forwardkey));
+                               if(keyselect!=0)sprintf (menustring[0], "Forwards: %s",Input::keyToChar(forwardkey));
                                else sprintf (menustring[0], "Forwards: _");
                                startx[0]=10;
                                starty[0]=400;
@@ -2659,7 +2262,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[0]=0;
                                movey[0]=0;
 
-                               if(keyselect!=1)sprintf (menustring[1], "Back: %s",KeyToChar(backkey));
+                               if(keyselect!=1)sprintf (menustring[1], "Back: %s",Input::keyToChar(backkey));
                                else sprintf (menustring[1], "Back: _");
                                startx[1]=10+40;
                                starty[1]=360;
@@ -2668,7 +2271,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[1]=0;
                                movey[1]=0;
 
-                               if(keyselect!=2)sprintf (menustring[2], "Left: %s",KeyToChar(leftkey));
+                               if(keyselect!=2)sprintf (menustring[2], "Left: %s",Input::keyToChar(leftkey));
                                else sprintf (menustring[2], "Left: _");
                                startx[2]=10+40;
                                starty[2]=320;
@@ -2677,7 +2280,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[2]=0;
                                movey[2]=0;
 
-                               if(keyselect!=3)sprintf (menustring[3], "Right: %s",KeyToChar(rightkey));
+                               if(keyselect!=3)sprintf (menustring[3], "Right: %s",Input::keyToChar(rightkey));
                                else sprintf (menustring[3], "Right: _");
                                startx[3]=10+30;
                                starty[3]=280;
@@ -2686,7 +2289,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[3]=0;
                                movey[3]=0;
 
-                               if(keyselect!=4)sprintf (menustring[4], "Crouch: %s",KeyToChar(crouchkey));
+                               if(keyselect!=4)sprintf (menustring[4], "Crouch: %s",Input::keyToChar(crouchkey));
                                else sprintf (menustring[4], "Crouch: _");
                                startx[4]=10+20;
                                starty[4]=240;
@@ -2695,7 +2298,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[4]=0;
                                movey[4]=0;
 
-                               if(keyselect!=5)sprintf (menustring[5], "Jump: %s",KeyToChar(jumpkey));
+                               if(keyselect!=5)sprintf (menustring[5], "Jump: %s",Input::keyToChar(jumpkey));
                                else sprintf (menustring[5], "Jump: _");
                                startx[5]=10+40;
                                starty[5]=200;
@@ -2704,7 +2307,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[5]=0;
                                movey[5]=0;
 
-                               if(keyselect!=6)sprintf (menustring[6], "Draw: %s",KeyToChar(drawkey));
+                               if(keyselect!=6)sprintf (menustring[6], "Draw: %s",Input::keyToChar(drawkey));
                                else sprintf (menustring[6], "Draw: _");
                                startx[6]=10+40;
                                starty[6]=160;
@@ -2713,7 +2316,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[6]=0;
                                movey[6]=0;
 
-                               if(keyselect!=7)sprintf (menustring[7], "Throw: %s",KeyToChar(throwkey));
+                               if(keyselect!=7)sprintf (menustring[7], "Throw: %s",Input::keyToChar(throwkey));
                                else sprintf (menustring[7], "Throw: _");
                                startx[7]=10+30;
                                starty[7]=120;
@@ -2722,7 +2325,7 @@ int Game::DrawGLScene(StereoSide side)
                                movex[7]=0;
                                movey[7]=0;
 
-                               if(keyselect!=8)sprintf (menustring[8], "Attack: %s",KeyToChar(attackkey));
+                               if(keyselect!=8)sprintf (menustring[8], "Attack: %s",Input::keyToChar(attackkey));
                                else sprintf (menustring[8], "Attack: _");
                                startx[8]=10+20;
                                starty[8]=80;
@@ -2742,9 +2345,9 @@ int Game::DrawGLScene(StereoSide side)
                                movey[9]=0;
                        }
                        if(mainmenu==5){                        
-                               nummenuitems=7+accountcampaignchoicesmade[accountactive]+campaignchoicenum;
+                               nummenuitems=7+accountactive->getCampaignChoicesMade()+campaignchoicenum;
 
-                               sprintf (menustring[0], "%s",accountname[accountactive]);
+                               sprintf (menustring[0], "%s",accountactive->getName());
                                startx[0]=5;
                                starty[0]=400;
                                endx[0]=startx[0]+strlen(menustring[0])*10;
@@ -2802,8 +2405,8 @@ int Game::DrawGLScene(StereoSide side)
                                movex[6]=0;
                                movey[6]=0;
 
-                               if(accountcampaignchoicesmade[accountactive])
-                                       for(i=0;i<accountcampaignchoicesmade[accountactive];i++){
+                               if(accountactive->getCampaignChoicesMade())
+                                       for(i=0;i<accountactive->getCampaignChoicesMade();i++){
                                                sprintf (menustring[7+i], "%s", campaigndescription[levelorder[i]]);
                                                startx[7+i]=30+120+campaignlocationx[levelorder[i]]*400/512;
                                                starty[7+i]=30+30+(512-campaignlocationy[levelorder[i]])*400/512;
@@ -2814,10 +2417,10 @@ int Game::DrawGLScene(StereoSide side)
                                        }
 
                                        if(campaignchoicenum>0)
-                                               for(i=accountcampaignchoicesmade[accountactive];i<accountcampaignchoicesmade[accountactive]+campaignchoicenum;i++){
+                                               for(i=accountactive->getCampaignChoicesMade();i<accountactive->getCampaignChoicesMade()+campaignchoicenum;i++){
                                                        sprintf (menustring[7+i], "%s", campaigndescription[levelorder[i]]);
-                                                       startx[7+i]=30+120+campaignlocationx[campaignchoicewhich[i-(accountcampaignchoicesmade[accountactive])]]*400/512;
-                                                       starty[7+i]=30+30+(512-campaignlocationy[campaignchoicewhich[i-(accountcampaignchoicesmade[accountactive])]])*400/512;
+                                                       startx[7+i]=30+120+campaignlocationx[campaignchoicewhich[i-(accountactive->getCampaignChoicesMade())]]*400/512;
+                                                       starty[7+i]=30+30+(512-campaignlocationy[campaignchoicewhich[i-(accountactive->getCampaignChoicesMade())]])*400/512;
                                                        endx[7+i]=startx[7+i]+10;
                                                        endy[7+i]=starty[7+i]+10;
                                                        movex[7+i]=0;
@@ -2917,12 +2520,12 @@ int Game::DrawGLScene(StereoSide side)
                                movey[5]=0;
                        }
 
-                       if(mainmenu==7){                        
-                               nummenuitems=numaccounts+2;
+                       if(mainmenu==7){        
+                               nummenuitems=Account::getNbAccounts()+2;
 
                                int num;
 
-                               if(numaccounts<8)
+                               if(Account::getNbAccounts()<8)
                                        sprintf (menustring[0], "New User");
                                else
                                        sprintf (menustring[0], "No More Users");
@@ -2933,30 +2536,30 @@ int Game::DrawGLScene(StereoSide side)
                                movex[0]=0;
                                movey[0]=0;
 
-                               if(entername)startx[0]+=10;
+                               if(entername)
+                                       startx[0]+=10;
 
 
                                num=1;
-                               if(numaccounts)
-                                       for(i=0;i<numaccounts;i++){
-                                               sprintf (menustring[num], "%s",accountname[i]);
-                                               startx[num]=10;
-                                               starty[num]=360-20-20*num;
-                                               endx[num]=startx[num]+strlen(menustring[num])*10;
-                                               endy[num]=starty[num]+20;
-                                               movex[num]=0;
-                                               movey[num]=0;
-
-                                               num++;
-                                       }
-
-                                       sprintf (menustring[num], "Back");
+                               for(i=0;i<Account::getNbAccounts();i++){
+                                       sprintf (menustring[num], "%s",Account::get(i)->getName());
                                        startx[num]=10;
+                                       starty[num]=360-20-20*num;
                                        endx[num]=startx[num]+strlen(menustring[num])*10;
-                                       starty[num]=10;
                                        endy[num]=starty[num]+20;
                                        movex[num]=0;
                                        movey[num]=0;
+
+                                       num++;
+                               }
+
+                               sprintf (menustring[num], "Back");
+                               startx[num]=10;
+                               endx[num]=startx[num]+strlen(menustring[num])*10;
+                               starty[num]=10;
+                               endy[num]=starty[num]+20;
+                               movex[num]=0;
+                               movey[num]=0;
                        }
                        if(mainmenu==8){                        
                                nummenuitems=3;
@@ -2998,14 +2601,14 @@ int Game::DrawGLScene(StereoSide side)
                                        strcpy(menustring[j],temp);
                                        for(i=0;i<17;i++)if(menustring[j][i]=='\0')menustring[j][i]=' ';
                                        menustring[j][17]='\0';
-                                       sprintf (temp, "%d",(int)accounthighscore[accountactive][j]);
+                                       sprintf (temp, "%d",(int)accountactive->getHighScore(j));
                                        strcat(menustring[j],temp);
                                        for(i=18;i<32;i++)if(menustring[j][i]=='\0')menustring[j][i]=' ';
                                        menustring[j][32]='\0';
-                                       sprintf (temp, "%d:",(int)(((int)accountfasttime[accountactive][j]-(int)(accountfasttime[accountactive][j])%60)/60));
+                                       sprintf (temp, "%d:",(int)(((int)accountactive->getFastTime(j)-(int)(accountactive->getFastTime(j))%60)/60));
                                        strcat(menustring[j],temp);
-                                       if((int)(accountfasttime[accountactive][j])%60<10)strcat(menustring[j],"0");
-                                       sprintf (temp, "%d",(int)(accountfasttime[accountactive][j])%60);
+                                       if((int)(accountactive->getFastTime(j))%60<10)strcat(menustring[j],"0");
+                                       sprintf (temp, "%d",(int)(accountactive->getFastTime(j))%60);
                                        strcat(menustring[j],temp);
 
                                        startx[j]=10;
@@ -3034,51 +2637,6 @@ int Game::DrawGLScene(StereoSide side)
 
                                //numchallengelevels=tempncl;
 
-                       }
-                       if(mainmenu==11){                       
-                               nummenuitems=2+numchallengelevels;
-                               char temp[255];
-
-                               for(j=0;j<numchallengelevels;j++){
-                                       for(i=0;i<255;i++)menustring[j][i]='\0';
-                                       sprintf (temp, "Level %d",j+1);
-                                       strcpy(menustring[j],temp);
-                                       for(i=0;i<17;i++)if(menustring[j][i]=='\0')menustring[j][i]=' ';
-                                       menustring[j][17]='\0';
-                                       sprintf (temp, "%d",(int)accounthighscore[accountactive][j]);
-                                       strcat(menustring[j],temp);
-                                       for(i=18;i<32;i++)if(menustring[j][i]=='\0')menustring[j][i]=' ';
-                                       menustring[j][32]='\0';
-                                       sprintf (temp, "%d:",(int)(((int)accountfasttime[accountactive][j]-(int)(accountfasttime[accountactive][j])%60)/60));
-                                       strcat(menustring[j],temp);
-                                       if((int)(accountfasttime[accountactive][j])%60<10)strcat(menustring[j],"0");
-                                       sprintf (temp, "%d",(int)(accountfasttime[accountactive][j])%60);
-                                       strcat(menustring[j],temp);
-
-                                       startx[j]=10;
-                                       starty[j]=360-j*40;
-                                       endx[j]=startx[j]+strlen(menustring[j])*10;
-                                       endy[j]=starty[j]+20;
-                                       movex[j]=0;
-                                       movey[j]=0;
-                               }
-
-                               sprintf (menustring[numchallengelevels], "Back");
-                               startx[numchallengelevels]=10;
-                               endx[numchallengelevels]=startx[numchallengelevels]+strlen(menustring[numchallengelevels])*10;
-                               starty[numchallengelevels]=10;
-                               endy[numchallengelevels]=starty[numchallengelevels]+20;
-                               movex[numchallengelevels]=0;
-                               movey[numchallengelevels]=0;
-
-                               sprintf (menustring[numchallengelevels+1], "             High Score      Best Time");
-                               startx[numchallengelevels+1]=10;
-                               starty[numchallengelevels+1]=400;
-                               endx[numchallengelevels+1]=startx[numchallengelevels+1]+strlen(menustring[numchallengelevels+1])*10;
-                               endy[numchallengelevels+1]=starty[numchallengelevels+1]+20;
-                               movex[numchallengelevels+1]=0;
-                               movey[numchallengelevels+1]=0;
-
                        }
                        if(mainmenu==10){                       
                                nummenuitems=6;
@@ -3121,7 +2679,7 @@ int Game::DrawGLScene(StereoSide side)
                                strcpy(menustring[4],temp);
                                for(i=0;i<20;i++)if(menustring[4][i]=='\0')menustring[4][i]=' ';
                                menustring[4][20]='\0';
-                               sprintf (temp, "%d",(int)accountcampaignscore[accountactive]);
+                               sprintf (temp, "%d",(int)accountactive->getCampaignScore());
                                strcat(menustring[4],temp);
                                startx[4]=190;
                                endx[4]=startx[4]+strlen(menustring[4])*10;
@@ -3149,7 +2707,7 @@ int Game::DrawGLScene(StereoSide side)
                                strcpy(menustring[5],temp);
                                for(i=0;i<20;i++)if(menustring[5][i]=='\0')menustring[5][i]=' ';
                                menustring[5][20]='\0';
-                               sprintf (temp, "%d",(int)accountcampaignhighscore[accountactive]);
+                               sprintf (temp, "%d",(int)accountactive->getCampaignHighScore());
                                strcat(menustring[5],temp);
                                startx[5]=190;
                                endx[5]=startx[5]+strlen(menustring[5])*10;
@@ -3163,7 +2721,7 @@ int Game::DrawGLScene(StereoSide side)
                                strcpy(menustring[7],temp);
                                for(i=0;i<20;i++)if(menustring[7][i]=='\0')menustring[7][i]=' ';
                                menustring[7][20]='\0';
-                               sprintf (temp, "%d",(int)accountcampaignfasttime[accountactive]);
+                               sprintf (temp, "%d",(int)accountactive->getCampaignFasttime());
                                strcat(menustring[7],temp);
                                startx[7]=200;
                                endx[7]=startx[7]+strlen(menustring[7])*10;
@@ -3208,26 +2766,6 @@ int Game::DrawGLScene(StereoSide side)
                        }
                }
 
-               if(mainmenu==13){       
-                       nummenuitems=2;
-                       char temp[255];
-
-                       sprintf (menustring[0], "Please enter your name:");
-                       startx[0]=50;
-                       starty[0]=250;
-                       endx[0]=startx[0]+strlen(menustring[0])*10;
-                       endy[0]=starty[0]+20;
-                       movex[0]=0;
-                       movey[0]=0;
-
-                       sprintf (menustring[1], "Please enter your name:");
-                       startx[1]=290;
-                       starty[1]=250;
-                       endx[1]=startx[1]+strlen(menustring[1])*10;
-                       endy[1]=starty[1]+20;
-                       movex[1]=0;
-                       movey[1]=0;
-               }
                if(mainmenu==1||mainmenu==2){
                        nummenuitems=7;
                        startx[0]=150;
@@ -3395,173 +2933,329 @@ int Game::DrawGLScene(StereoSide side)
                                }
                        }
 
-                       if(mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==8||mainmenu==9||mainmenu==10||mainmenu==11||mainmenu==13||mainmenu==17||mainmenu==18)
-                               for(i=0;i<nummenuitems;i++){
-                                       if((mousecoordh/screenwidth*640)>startx[i]&&(mousecoordh/screenwidth*640)<endx[i]&&480-(mousecoordv/screenheight*480)>starty[i]&&480-(mousecoordv/screenheight*480)<endy[i]){
-                                               if(mainmenu!=5)selected=i;
-                                               if(mainmenu==5&&(i!=0&&i!=6))selected=i;
-                                               if(mainmenu==9&&(i!=numchallengelevels+1))selected=i;
-                                               if(mainmenu==11&&(i!=numchallengelevels+1))selected=i;
-                                       }
+               if(mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==8||mainmenu==9||mainmenu==10||mainmenu==18)
+                       for(i=0;i<nummenuitems;i++){
+                               if((mousecoordh/screenwidth*640)>startx[i]&&(mousecoordh/screenwidth*640)<endx[i]&&480-(mousecoordv/screenheight*480)>starty[i]&&480-(mousecoordv/screenheight*480)<endy[i]){
+                                       if(mainmenu!=5)selected=i;
+                                       if(mainmenu==5&&(i!=0&&i!=6))selected=i;
+                                       if(mainmenu==9&&(i!=numchallengelevels+1))selected=i; // seem useless, if mainmenu==9 then mainmenu!=5, so selected==i.
                                }
+                       }
 
-                               if(nummenuitems>0)
-                                       for(i=0;i<nummenuitems;i++){
-                                               if(selected==i)selectedlong[i]+=multiplier*5;
-                                               if(selectedlong[i]>1)selectedlong[i]=1;
-                                               if(selected!=i)selectedlong[i]-=multiplier*5;
-                                               if(selectedlong[i]<0)selectedlong[i]=0; 
-                                               //if(i>=4)selectedlong[i]=.3;           
-                                               if(i>=4&&(mainmenu==1||mainmenu==2))selectedlong[i]=0;  
-                                       }
-
-                                       if(nummenuitems>0)
-                                               for(i=0;i<nummenuitems;i++){
-                                                       offsetx[i]=(startx[i]+endx[i])/2-(mousecoordh/screenwidth*640);
-                                                       offsety[i]=(starty[i]+endy[i])/2-(480-(mousecoordv/screenheight*480));
-                                                       offsetx[i]*=.06f;
-                                                       offsety[i]*=.06f;
-                                                       offsetx[i]=0;
-                                                       offsety[i]=0;
-                                                       if(i>=4&&(mainmenu==1||mainmenu==2)){
-                                                               offsetx[i]=(startx[i]+endx[i]+movex[i]*transition)/2-(640+190)/2;
-                                                               offsety[i]=(starty[i]+endy[i]+movey[i]*transition)/2-(336+150)/2;
-                                                               offsetx[i]*=.06f;
-                                                               offsety[i]*=.06f;
-                                                       }
-                                               }
+               for(i=0;i<nummenuitems;i++){
+                       if(selected==i) {
+                               selectedlong[i]+=multiplier*5;
+                               if(selectedlong[i]>1) selectedlong[i]=1;
+                       } else {
+                               selectedlong[i]-=multiplier*5;
+                               if(selectedlong[i]<0) selectedlong[i]=0;        
+                       }
+                       offsetx[i]=(startx[i]+endx[i])/2-(mousecoordh/screenwidth*640);
+                       offsety[i]=(starty[i]+endy[i])/2-(480-(mousecoordv/screenheight*480));
+                       offsetx[i]*=.06f;
+                       offsety[i]*=.06f;
+                       offsetx[i]=0;
+                       offsety[i]=0;
+                       if(i>=4&&(mainmenu==1||mainmenu==2)){
+                               selectedlong[i]=0;
+                               offsetx[i]=(startx[i]+endx[i]+movex[i]*transition)/2-(640+190)/2;
+                               offsety[i]=(starty[i]+endy[i]+movey[i]*transition)/2-(336+150)/2;
+                               offsetx[i]*=.06f;
+                               offsety[i]*=.06f;
+                       }
+               }
 
-                                               if(mainmenu==1||mainmenu==2){
-                                                       glClear(GL_DEPTH_BUFFER_BIT);
-                                                       glEnable(GL_ALPHA_TEST);
-                                                       glAlphaFunc(GL_GREATER, 0.001f);
-                                                       glEnable(GL_TEXTURE_2D);
-                                                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
-                                                       glDisable(GL_CULL_FACE);
-                                                       glDisable(GL_LIGHTING);
-                                                       glDepthMask(0);
-                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                       glPushMatrix();                                                                         // Store The Projection Matrix
-                                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                                               glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
-                                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                               glPushMatrix();                                                                         // Store The Modelview Matrix
-                                                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                                                       glTranslatef(screenwidth/2,screenheight/2,0);
-                                                                       glPushMatrix();
-                                                                               glScalef((float)screenwidth/2,(float)screenheight/2,1);
-                                                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                                                                               glDisable(GL_BLEND);
-                                                                               glColor4f(0,0,0,1.0);
-                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
-                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
-                                                                               glDisable(GL_TEXTURE_2D);
-                                                                               glPushMatrix();
-                                                                                       //glScalef(.25,.25,.25);
-                                                                                       glBegin(GL_QUADS);
-                                                                                       glTexCoord2f(0,0);
-                                                                                       glVertex3f(-1,          -1,      0.0f);
-                                                                                       glTexCoord2f(1,0);
-                                                                                       glVertex3f(1,   -1,      0.0f);
-                                                                                       glTexCoord2f(1,1);
-                                                                                       glVertex3f(1,   1, 0.0f);
-                                                                                       glTexCoord2f(0,1);
-                                                                                       glVertex3f(-1,  1, 0.0f);
-                                                                                       glEnd();
-                                                                               glPopMatrix();
-                                                                               glEnable(GL_BLEND);
-                                                                               glColor4f(0.4,0.4,0.4,1.0);
-                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
-                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
-                                                                               glEnable(GL_TEXTURE_2D);
-                                                                               glBindTexture( GL_TEXTURE_2D, Mainmenuitems[4]);
-                                                                               glPushMatrix();
-                                                                                       //glScalef(.25,.25,.25);
-                                                                                       glBegin(GL_QUADS);
-                                                                                       glTexCoord2f(0,0);
-                                                                                       glVertex3f(-1,          -1,      0.0f);
-                                                                                       glTexCoord2f(1,0);
-                                                                                       glVertex3f(1,   -1,      0.0f);
-                                                                                       glTexCoord2f(1,1);
-                                                                                       glVertex3f(1,   1, 0.0f);
-                                                                                       glTexCoord2f(0,1);
-                                                                                       glVertex3f(-1,  1, 0.0f);
-                                                                                       glEnd();
-                                                                               glPopMatrix();
-                                                                       glPopMatrix();
-                                                               glPopMatrix();
-                                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                       glPopMatrix();
+               if(mainmenu==1||mainmenu==2){
+                       glClear(GL_DEPTH_BUFFER_BIT);
+                       glEnable(GL_ALPHA_TEST);
+                       glAlphaFunc(GL_GREATER, 0.001f);
+                       glEnable(GL_TEXTURE_2D);
+                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
+                       glDisable(GL_CULL_FACE);
+                       glDisable(GL_LIGHTING);
+                       glDepthMask(0);
+                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                       glPushMatrix();                                                                         // Store The Projection Matrix
+                               glLoadIdentity();                                                                       // Reset The Projection Matrix
+                               glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
+                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                               glPushMatrix();                                                                         // Store The Modelview Matrix
+                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
+                                       glTranslatef(screenwidth/2,screenheight/2,0);
+                                       glPushMatrix();
+                                               glScalef((float)screenwidth/2,(float)screenheight/2,1);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                               glDisable(GL_BLEND);
+                                               glColor4f(0,0,0,1.0);
+                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
+                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
+                                               glDisable(GL_TEXTURE_2D);
+                                               glPushMatrix();
+                                                       //glScalef(.25,.25,.25);
+                                                       glBegin(GL_QUADS);
+                                                       glTexCoord2f(0,0);
+                                                       glVertex3f(-1,          -1,      0.0f);
+                                                       glTexCoord2f(1,0);
+                                                       glVertex3f(1,   -1,      0.0f);
+                                                       glTexCoord2f(1,1);
+                                                       glVertex3f(1,   1, 0.0f);
+                                                       glTexCoord2f(0,1);
+                                                       glVertex3f(-1,  1, 0.0f);
+                                                       glEnd();
+                                               glPopMatrix();
+                                               glEnable(GL_BLEND);
+                                               glColor4f(0.4,0.4,0.4,1.0);
+                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
+                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
+                                               glEnable(GL_TEXTURE_2D);
+                                               glBindTexture( GL_TEXTURE_2D, Mainmenuitems[4]);
+                                               glPushMatrix();
+                                                       //glScalef(.25,.25,.25);
+                                                       glBegin(GL_QUADS);
+                                                       glTexCoord2f(0,0);
+                                                       glVertex3f(-1,          -1,      0.0f);
+                                                       glTexCoord2f(1,0);
+                                                       glVertex3f(1,   -1,      0.0f);
+                                                       glTexCoord2f(1,1);
+                                                       glVertex3f(1,   1, 0.0f);
+                                                       glTexCoord2f(0,1);
+                                                       glVertex3f(-1,  1, 0.0f);
+                                                       glEnd();
+                                               glPopMatrix();
+                                       glPopMatrix();
+                               glPopMatrix();
+                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                       glPopMatrix();
 
-                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                       glPushMatrix();                                                                         // Store The Projection Matrix
-                                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                                               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
-                                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                               glPushMatrix();                                                                         // Store The Modelview Matrix
-                                                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                                                       glPushMatrix();
-                                                                               glDisable(GL_TEXTURE_2D);
-                                                                               glColor4f(1,0,0,1);
-                                                                               /*glPushMatrix();
-                                                                               glBegin(GL_QUADS);
-                                                                               glTexCoord2f(0,0);
-                                                                               if(anim!=1)glVertex3f(190,      150,     0.0f);
-                                                                               if(anim==1)glVertex3f(190+movex[4]*transition,  150,     0.0f);
-                                                                               glTexCoord2f(1,0);
-                                                                               glVertex3f(640, 150,     0.0f);
-                                                                               glTexCoord2f(1,1);
-                                                                               glVertex3f(640, 336, 0.0f);
-                                                                               glTexCoord2f(0,1);
-                                                                               if(anim!=1)glVertex3f(190, 336, 0.0f);
-                                                                               if(anim==1)glVertex3f(190+movex[4]*transition, 336,      0.0f);
-                                                                               glEnd();
-                                                                               glPopMatrix();*/
-                                                                       glPopMatrix();
-                                                               glPopMatrix();
-                                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                       glPopMatrix();
-                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                       glPushMatrix();                                                                         // Store The Projection Matrix
+                               glLoadIdentity();                                                                       // Reset The Projection Matrix
+                               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
+                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                               glPushMatrix();                                                                         // Store The Modelview Matrix
+                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
+                                       glPushMatrix();
+                                               glDisable(GL_TEXTURE_2D);
+                                               glColor4f(1,0,0,1);
+                                       glPopMatrix();
+                               glPopMatrix();
+                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                       glPopMatrix();
+                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
 
-                                               }
+               }
 
-                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                               glPushMatrix();                                                                         // Store The Projection Matrix
-                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
+               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+               glPushMatrix();                                                                         // Store The Projection Matrix
+               glLoadIdentity();                                                                       // Reset The Projection Matrix
+               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
+               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+               glPushMatrix();                                                                         // Store The Modelview Matrix
+               glLoadIdentity();                                                               // Reset The Modelview Matrix
+               glEnable(GL_TEXTURE_2D);
+               for(j=0;j<nummenuitems;j++)
+               {
+                       if(j<=3||(mainmenu!=1&&mainmenu!=2))
+                       {
+                               //glDisable(GL_BLEND);
+                               glEnable(GL_ALPHA_TEST);
+                               glEnable(GL_BLEND);
+                               //glDisable(GL_ALPHA_TEST);
+                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                               if(mainmenu==1||mainmenu==2)
+                               {
+                                       glColor4f(1,1,1,1);
+                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+                                       glBindTexture( GL_TEXTURE_2D, Mainmenuitems[j]);
+                                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
+                                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                       glPushMatrix();
+                                               glBegin(GL_QUADS);
+                                               glTexCoord2f(0,0);
+                                               glVertex3f(startx[j]+movex[j]*transition,       starty[j]+movey[j]*transition,   0.0f);
+                                               glTexCoord2f(1,0);
+                                               glVertex3f(endx[j]+movex[j]*transition,         starty[j]+movey[j]*transition,   0.0f);
+                                               glTexCoord2f(1,1);
+                                               glVertex3f(endx[j]+movex[j]*transition,         endy[j]+movey[j]*transition, 0.0f);
+                                               glTexCoord2f(0,1);
+                                               glVertex3f(startx[j]+movex[j]*transition,       endy[j]+movey[j]*transition, 0.0f);
+                                               glEnd();
+                                       glPopMatrix();
+                                       glEnable(GL_BLEND);
+                                       //glDisable(GL_ALPHA_TEST);
+                                       if(j<4)glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+                                       for(i=0;i<10;i++)
+                                       {
+                                               if(1-((float)i)/10-(1-selectedlong[j])>0)
+                                               {
+                                                       glColor4f(1,1,1,(1-((float)i)/10-(1-selectedlong[j]))*.25);
+                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                                       glPushMatrix();
+                                                               glBegin(GL_QUADS);
+                                                               glTexCoord2f(0,0);
+                                                               glVertex3f(startx[j]-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,        starty[j]-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,    0.0f);
+                                                               glTexCoord2f(1,0);
+                                                               glVertex3f(endx[j]+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,  starty[j]-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,    0.0f);
+                                                               glTexCoord2f(1,1);
+                                                               glVertex3f(endx[j]+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,  endy[j]+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
+                                                               glTexCoord2f(0,1);
+                                                               glVertex3f(startx[j]-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition, endy[j]+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
+                                                               glEnd();
+                                                       glPopMatrix();
+                                               }
+                                       }
+                               }
+                               if(mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==8||mainmenu==9||mainmenu==10||mainmenu==18)
+                               {
+                                       if(mainmenu!=5||j<6)
+                                       {
+                                               glColor4f(1,0,0,1);
+                                               if(mainmenu==9&&j>accountactive->getProgress()&&j<numchallengelevels)glColor4f(0.5,0,0,1);
                                                glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                               glPushMatrix();                                                                         // Store The Modelview Matrix
-                                               glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                               glEnable(GL_TEXTURE_2D);
-                                               if(nummenuitems>0)
+                                               glPushMatrix();
+                                                       if(mainmenu!=7||j!=0||!entername)
+                                                               text.glPrint(startx[j],starty[j],menustring[j],0,1,640,480);
+                                                       else
+                                                       {
+                                                               if(displayblink){
+                                                                       sprintf (string, "_");
+                                                                       text.glPrint(startx[j]+(float)(displayselected)*10,starty[j],string,0,1,640,480);
+                                                               }
+                                                               for(l=0;l<displaychars[0];l++){
+                                                                       sprintf (string, "%c",displaytext[0][l]);
+                                                                       text.glPrint(startx[j]+l*10,starty[j],string,0,1,640,480);
+                                                               }
+                                                       }
+                                               glPopMatrix();
+                                               glEnable(GL_BLEND);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+                                               for(i=0;i<15;i++)
                                                {
-                                                       for(j=0;j<nummenuitems;j++)
+                                                       if(1-((float)i)/15-(1-selectedlong[j])>0)
                                                        {
-                                                               if(j<=3||(mainmenu!=1&&mainmenu!=2))
-                                                               {
-                                                                       //glDisable(GL_BLEND);
-                                                                       glEnable(GL_ALPHA_TEST);
-                                                                       glEnable(GL_BLEND);
-                                                                       //glDisable(GL_ALPHA_TEST);
-                                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                                                                       if(mainmenu==1||mainmenu==2)
+                                                               glColor4f(1,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
+                                                               if(mainmenu==9&&j>accountactive->getProgress()&&j<numchallengelevels)glColor4f(0.5,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
+                                                               if(mainmenu==11&&j>accountactive->getProgress()&&j<numchallengelevels)glColor4f(0.5,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
+                                                               if(mainmenu==3)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4-((/*1*/+((float)i)/70)*strlen(menustring[j]))*3,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==4)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==5)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==6)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==7&&(j!=0||!entername)) text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==8)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==9)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==10)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                               if(mainmenu==18)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4,starty[j]+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
+                                                       }
+                                               }
+                                       }
+                                       else
+                                       {
+                                               glClear(GL_DEPTH_BUFFER_BIT);
+                                               glEnable(GL_ALPHA_TEST);
+                                               glAlphaFunc(GL_GREATER, 0.001f);
+                                               glEnable(GL_TEXTURE_2D);
+                                               glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
+                                               glDisable(GL_CULL_FACE);
+                                               glDisable(GL_LIGHTING);
+                                               if(j==6)glColor4f(1,1,1,1);
+                                               else glColor4f(1,0,0,1);
+
+                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                                               glPushMatrix();                                                                         // Store The Projection Matrix
+                                                       glLoadIdentity();                                                                       // Reset The Projection Matrix
+                                                       glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
+                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                                       glPushMatrix();                                                                         // Store The Modelview Matrix
+                                                               glLoadIdentity();                                                               // Reset The Modelview Matrix
+                                                               glPushMatrix();
+
+                                                                       //Draw world, draw map
+                                                                       glTranslatef(2,-5,0);
+
+                                                                       if(j>6&&j<nummenuitems-1)
+                                                                       {
+                                                                               XYZ linestart,lineend,offset;
+                                                                               XYZ fac;
+                                                                               float startsize;
+                                                                               float endsize;
+                                                                               linestart=0;
+                                                                               lineend=0;
+                                                                               offset=0;
+                                                                               //float linestartx,lineendx,linestarty,lineendy,offsetx,offsety;
+                                                                               linestart.x=(startx[j]+endx[j])/2;
+                                                                               linestart.y=(starty[j]+endy[j])/2;
+                                                                               if(j>=6+accountactive->getCampaignChoicesMade()){
+                                                                                       linestart.x=(startx[6+accountactive->getCampaignChoicesMade()]+endx[6+accountactive->getCampaignChoicesMade()])/2;
+                                                                                       linestart.y=(starty[6+accountactive->getCampaignChoicesMade()]+endy[6+accountactive->getCampaignChoicesMade()])/2;
+                                                                               }
+                                                                               lineend.x=(startx[j+1]+endx[j+1])/2;
+                                                                               lineend.y=(starty[j+1]+endy[j+1])/2;
+                                                                               offset=lineend-linestart;
+                                                                               fac=offset;
+                                                                               Normalise(&fac);
+                                                                               offset=DoRotation(offset,0,0,90);
+                                                                               Normalise(&offset);
+                                                                               glDisable(GL_TEXTURE_2D);                                                       
+
+                                                                               if(j<6+accountactive->getCampaignChoicesMade()){
+                                                                                       glColor4f(0.5,0,0,1);
+                                                                                       endsize=.5;
+                                                                               } else {
+                                                                                       glColor4f(1,0,0,1);
+                                                                                       endsize=1;
+                                                                               }
+                                                                               startsize=.5;
+
+                                                                               linestart+=fac*4*startsize;
+                                                                               lineend-=fac*4*endsize;
+
+                                                                               if(!(j>7+accountactive->getCampaignChoicesMade()+campaignchoicenum)){
+                                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                                                                       glPushMatrix();
+                                                                                               glBegin(GL_QUADS);
+                                                                                               glTexCoord2f(0,0);
+                                                                                               glVertex3f(linestart.x-offset.x*startsize,      linestart.y-offset.y*startsize,          0.0f);
+                                                                                               glTexCoord2f(1,0);
+                                                                                               glVertex3f(linestart.x+offset.x*startsize,      linestart.y+offset.y*startsize,          0.0f);
+                                                                                               glTexCoord2f(1,1);
+                                                                                               glVertex3f(lineend.x+offset.x*endsize,          lineend.y+offset.y*endsize, 0.0f);
+                                                                                               glTexCoord2f(0,1);
+                                                                                               glVertex3f(lineend.x-offset.x*endsize,          lineend.y-offset.y*endsize, 0.0f);
+                                                                                               glEnd();
+                                                                                       glPopMatrix();
+                                                                               }
+                                                                               glEnable(GL_TEXTURE_2D);
+                                                                       }
+
+
+                                                                       if(j==6)glBindTexture( GL_TEXTURE_2D, Mainmenuitems[7]);
+                                                                       else glBindTexture( GL_TEXTURE_2D, Mapcircletexture);
+                                                                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
+                                                                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
+                                                                       if(j-7<accountactive->getCampaignChoicesMade())glColor4f(0.5,0,0,1);
+                                                                       if(j-7>=accountactive->getCampaignChoicesMade())glColor4f(1,0,0,1);
+                                                                       if(j==6)glColor4f(1,1,1,1);
+                                                                       XYZ midpoint;
+                                                                       float itemsize;
+                                                                       itemsize=abs(startx[j]-endx[j])/2;
+                                                                       midpoint=0;
+                                                                       midpoint.x=(startx[j]+endx[j])/2;
+                                                                       midpoint.y=(starty[j]+endy[j])/2;
+                                                                       if(j>6&&(j-7<accountactive->getCampaignChoicesMade()))itemsize*=.5;
+                                                                       if(!(j-7>accountactive->getCampaignChoicesMade()+campaignchoicenum))
                                                                        {
-                                                                               glColor4f(1,1,1,1);
-                                                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE);
-                                                                               glBindTexture( GL_TEXTURE_2D, Mainmenuitems[j]);
-                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
-                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
                                                                                glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
                                                                                glPushMatrix();
                                                                                        glBegin(GL_QUADS);
                                                                                        glTexCoord2f(0,0);
-                                                                                       glVertex3f(startx[j]+movex[j]*transition,       starty[j]+movey[j]*transition,   0.0f);
+                                                                                       glVertex3f(midpoint.x-itemsize+movex[j]*transition,     midpoint.y-itemsize+movey[j]*transition,         0.0f);
                                                                                        glTexCoord2f(1,0);
-                                                                                       glVertex3f(endx[j]+movex[j]*transition,         starty[j]+movey[j]*transition,   0.0f);
+                                                                                       glVertex3f(midpoint.x+itemsize+movex[j]*transition,             midpoint.y-itemsize+movey[j]*transition,         0.0f);
                                                                                        glTexCoord2f(1,1);
-                                                                                       glVertex3f(endx[j]+movex[j]*transition,         endy[j]+movey[j]*transition, 0.0f);
+                                                                                       glVertex3f(midpoint.x+itemsize+movex[j]*transition,             midpoint.y+itemsize+movey[j]*transition, 0.0f);
                                                                                        glTexCoord2f(0,1);
-                                                                                       glVertex3f(startx[j]+movex[j]*transition,       endy[j]+movey[j]*transition, 0.0f);
+                                                                                       glVertex3f(midpoint.x-itemsize+movex[j]*transition,     midpoint.y+itemsize+movey[j]*transition, 0.0f);
                                                                                        glEnd();
                                                                                glPopMatrix();
                                                                                glEnable(GL_BLEND);
@@ -3571,372 +3265,154 @@ int Game::DrawGLScene(StereoSide side)
                                                                                {
                                                                                        if(1-((float)i)/10-(1-selectedlong[j])>0)
                                                                                        {
-                                                                                               glColor4f(1,1,1,(1-((float)i)/10-(1-selectedlong[j]))*.25);
+                                                                                               glColor4f(1,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
                                                                                                glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
                                                                                                glPushMatrix();
                                                                                                        glBegin(GL_QUADS);
                                                                                                        glTexCoord2f(0,0);
-                                                                                                       glVertex3f(startx[j]-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,        starty[j]-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,    0.0f);
+                                                                                                       glVertex3f(midpoint.x-itemsize-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,      midpoint.y-itemsize-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,          0.0f);
                                                                                                        glTexCoord2f(1,0);
-                                                                                                       glVertex3f(endx[j]+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,  starty[j]-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,    0.0f);
+                                                                                                       glVertex3f(midpoint.x+itemsize+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,      midpoint.y-itemsize-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,          0.0f);
                                                                                                        glTexCoord2f(1,1);
-                                                                                                       glVertex3f(endx[j]+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,  endy[j]+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
+                                                                                                       glVertex3f(midpoint.x+itemsize+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,      midpoint.y+itemsize+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
                                                                                                        glTexCoord2f(0,1);
-                                                                                                       glVertex3f(startx[j]-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition, endy[j]+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
+                                                                                                       glVertex3f(midpoint.x-itemsize-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition, midpoint.y+itemsize+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
                                                                                                        glEnd();
                                                                                                glPopMatrix();
                                                                                        }
                                                                                }
                                                                        }
-                                                                       if(mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==8||mainmenu==9||mainmenu==10||mainmenu==11||mainmenu==13||mainmenu==17||mainmenu==18)
-                                                                       {
-                                                                               if(mainmenu!=5||j<6)
-                                                                               {
-                                                                                       glColor4f(1,0,0,1);
-                                                                                       if(mainmenu==9&&j>accountprogress[accountactive]&&j<numchallengelevels)glColor4f(0.5,0,0,1);
-                                                                                       if(mainmenu==11&&j>accountprogress[accountactive]&&j<numchallengelevels)glColor4f(0.5,0,0,1);
-                                                                                       //if(1-((float)i)/10-(1-selectedlong[j])>0){
-                                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                                       glPushMatrix();
-                                                                                               if(mainmenu!=7||j!=0||!entername)text.glPrint(startx[j],starty[j],menustring[j],0,1,640,480);
-                                                                                               else
-                                                                                               {
-                                                                                                       if(displayblink){
-                                                                                                               sprintf (string, "_");
-                                                                                                               text.glPrint(startx[j]+(float)(displayselected)*10,starty[j],string,0,1,640,480);
-                                                                                                       }
-                                                                                                       k=0;
-                                                                                                       for(l=0;l<displaychars[k];l++){
-                                                                                                               if(l<displaychars[k]){
-                                                                                                                       sprintf (string, "%c",displaytext[k][l]);
-                                                                                                                       text.glPrint(startx[j]+l*10,starty[j],string,0,1,640,480);
-                                                                                                               }
-                                                                                                       }
-                                                                                               }
-                                                                                       glPopMatrix();
-                                                                                       /*}
-                                                                                       else{
-                                                                                       glPushMatrix();
-                                                                                       sprintf (string, "Hooo!");
-                                                                                       text.glPrint(startx[0],starty[0],string,0,1,640,480);
-                                                                                       glPopMatrix();
-                                                                                       }*/
-                                                                                       glEnable(GL_BLEND);
-                                                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE);
-                                                                                       for(i=0;i<15;i++)
-                                                                                       {
-                                                                                               if(1-((float)i)/15-(1-selectedlong[j])>0)
-                                                                                               {
-                                                                                                       glColor4f(1,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
-                                                                                                       if(mainmenu==9&&j>accountprogress[accountactive]&&j<numchallengelevels)glColor4f(0.5,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
-                                                                                                       if(mainmenu==11&&j>accountprogress[accountactive]&&j<numchallengelevels)glColor4f(0.5,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
-                                                                                                       if(mainmenu==3)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4-((/*1*/+((float)i)/70)*strlen(menustring[j]))*3,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==4)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==5)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==6)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==7&&(j!=0||!entername))text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==8)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==9)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==11)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==10)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==17)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==13&&j!=1)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       if(mainmenu==18)text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4/*-((((float)i)/70)*strlen(menustring[j]))*3*/,starty[j]/*-i*1/2*/+offsety[j]*((float)i)/4,menustring[j],0,1+((float)i)/70,640,480);
-                                                                                                       /*else{
-                                                                                                       if(displayblink){
-                                                                                                       sprintf (string, "_");
-                                                                                                       text.glPrint(startx[j]-((float)i)+offsetx[j]*((float)i)/4+(float)(displayselected)*10*(1+((float)i)/70),starty[j]+offsety[j]*((float)i)/4,string,0,1+((float)i)/70,640,480);
-                                                                                                       }
-                                                                                                       k=0;
-                                                                                                       for(l=0;l<displaychars[k];l++){
-                                                                                                       if(l<displaychars[k]){
-                                                                                                       sprintf (string, "%c",displaytext[k][l]);
-                                                                                                       text.glPrint(startx[j]-((float)k)+offsetx[j]*((float)k)/4+l*10*(1+((float)i)/70),starty[j]+offsety[j]*((float)i)/4,string,0,1+((float)i)/70,640,480);
-                                                                                                       }
-                                                                                                       }
-                                                                                                       }*/
-                                                                                               }
-                                                                                       }
-                                                                               }
-                                                                               else
-                                                                               {
-                                                                                       glClear(GL_DEPTH_BUFFER_BIT);
-                                                                                       glEnable(GL_ALPHA_TEST);
-                                                                                       glAlphaFunc(GL_GREATER, 0.001f);
-                                                                                       glEnable(GL_TEXTURE_2D);
-                                                                                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
-                                                                                       glDisable(GL_CULL_FACE);
-                                                                                       glDisable(GL_LIGHTING);
-                                                                                       if(j==6)glColor4f(1,1,1,1);
-                                                                                       else glColor4f(1,0,0,1);
-
-                                                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                                                       glPushMatrix();                                                                         // Store The Projection Matrix
-                                                                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                                                                               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
-                                                                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                                               glPushMatrix();                                                                         // Store The Modelview Matrix
-                                                                                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                                                                                       glPushMatrix();
-
-                                                                                                               //Draw world, draw map
-                                                                                                               glTranslatef(2,-5,0);
-
-                                                                                                               if(j>6&&j<nummenuitems-1)
-                                                                                                               {
-                                                                                                                       XYZ linestart,lineend,offset;
-                                                                                                                       XYZ fac;
-                                                                                                                       float startsize;
-                                                                                                                       float endsize;
-                                                                                                                       linestart=0;
-                                                                                                                       lineend=0;
-                                                                                                                       offset=0;
-                                                                                                                       //float linestartx,lineendx,linestarty,lineendy,offsetx,offsety;
-                                                                                                                       linestart.x=(startx[j]+endx[j])/2;
-                                                                                                                       linestart.y=(starty[j]+endy[j])/2;
-                                                                                                                       if(j>=6+accountcampaignchoicesmade[accountactive]){
-                                                                                                                               linestart.x=(startx[6+accountcampaignchoicesmade[accountactive]]+endx[6+accountcampaignchoicesmade[accountactive]])/2;
-                                                                                                                               linestart.y=(starty[6+accountcampaignchoicesmade[accountactive]]+endy[6+accountcampaignchoicesmade[accountactive]])/2;
-                                                                                                                       }
-                                                                                                                       lineend.x=(startx[j+1]+endx[j+1])/2;
-                                                                                                                       lineend.y=(starty[j+1]+endy[j+1])/2;
-                                                                                                                       offset=lineend-linestart;
-                                                                                                                       fac=offset;
-                                                                                                                       Normalise(&fac);
-                                                                                                                       offset=DoRotation(offset,0,0,90);
-                                                                                                                       Normalise(&offset);
-                                                                                                                       glDisable(GL_TEXTURE_2D);                                                       
-
-                                                                                                                       if(j<6+accountcampaignchoicesmade[accountactive]){
-                                                                                                                               glColor4f(0.5,0,0,1);
-                                                                                                                               startsize=.5;
-                                                                                                                               endsize=.5;
-                                                                                                                       }
-                                                                                                                       if(j>=6+accountcampaignchoicesmade[accountactive]){
-                                                                                                                               glColor4f(1,0,0,1);
-                                                                                                                               endsize=1;
-                                                                                                                               startsize=.5;
-                                                                                                                       }
-
-                                                                                                                       linestart+=fac*4*startsize;
-                                                                                                                       lineend-=fac*4*endsize;
-
-                                                                                                                       if(!(j>7+accountcampaignchoicesmade[accountactive]+campaignchoicenum)){
-                                                                                                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                                                                               glPushMatrix();
-                                                                                                                                       glBegin(GL_QUADS);
-                                                                                                                                       glTexCoord2f(0,0);
-                                                                                                                                       glVertex3f(linestart.x-offset.x*startsize,      linestart.y-offset.y*startsize,          0.0f);
-                                                                                                                                       glTexCoord2f(1,0);
-                                                                                                                                       glVertex3f(linestart.x+offset.x*startsize,      linestart.y+offset.y*startsize,          0.0f);
-                                                                                                                                       glTexCoord2f(1,1);
-                                                                                                                                       glVertex3f(lineend.x+offset.x*endsize,          lineend.y+offset.y*endsize, 0.0f);
-                                                                                                                                       glTexCoord2f(0,1);
-                                                                                                                                       glVertex3f(lineend.x-offset.x*endsize,          lineend.y-offset.y*endsize, 0.0f);
-                                                                                                                                       glEnd();
-                                                                                                                               glPopMatrix();
-                                                                                                                       }
-                                                                                                                       glEnable(GL_TEXTURE_2D);
-                                                                                                               }
-
-
-                                                                                                               if(j==6)glBindTexture( GL_TEXTURE_2D, Mainmenuitems[7]);
-                                                                                                               else glBindTexture( GL_TEXTURE_2D, Mapcircletexture);
-                                                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
-                                                                                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
-                                                                                                               if(j-7<accountcampaignchoicesmade[accountactive])glColor4f(0.5,0,0,1);
-                                                                                                               if(j-7>=accountcampaignchoicesmade[accountactive])glColor4f(1,0,0,1);
-                                                                                                               if(j==6)glColor4f(1,1,1,1);
-                                                                                                               XYZ midpoint;
-                                                                                                               float itemsize;
-                                                                                                               itemsize=abs(startx[j]-endx[j])/2;
-                                                                                                               midpoint=0;
-                                                                                                               midpoint.x=(startx[j]+endx[j])/2;
-                                                                                                               midpoint.y=(starty[j]+endy[j])/2;
-                                                                                                               if(j>6&&(j-7<accountcampaignchoicesmade[accountactive]))itemsize*=.5;
-                                                                                                               if(!(j-7>accountcampaignchoicesmade[accountactive]+campaignchoicenum))
-                                                                                                               {
-                                                                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                                                                       glPushMatrix();
-                                                                                                                               glBegin(GL_QUADS);
-                                                                                                                               glTexCoord2f(0,0);
-                                                                                                                               glVertex3f(midpoint.x-itemsize+movex[j]*transition,     midpoint.y-itemsize+movey[j]*transition,         0.0f);
-                                                                                                                               glTexCoord2f(1,0);
-                                                                                                                               glVertex3f(midpoint.x+itemsize+movex[j]*transition,             midpoint.y-itemsize+movey[j]*transition,         0.0f);
-                                                                                                                               glTexCoord2f(1,1);
-                                                                                                                               glVertex3f(midpoint.x+itemsize+movex[j]*transition,             midpoint.y+itemsize+movey[j]*transition, 0.0f);
-                                                                                                                               glTexCoord2f(0,1);
-                                                                                                                               glVertex3f(midpoint.x-itemsize+movex[j]*transition,     midpoint.y+itemsize+movey[j]*transition, 0.0f);
-                                                                                                                               glEnd();
-                                                                                                                       glPopMatrix();
-                                                                                                                       glEnable(GL_BLEND);
-                                                                                                                       //glDisable(GL_ALPHA_TEST);
-                                                                                                                       if(j<4)glBlendFunc(GL_SRC_ALPHA,GL_ONE);
-                                                                                                                       for(i=0;i<10;i++)
-                                                                                                                       {
-                                                                                                                               if(1-((float)i)/10-(1-selectedlong[j])>0)
-                                                                                                                               {
-                                                                                                                                       glColor4f(1,0,0,(1-((float)i)/10-(1-selectedlong[j]))*.25);
-                                                                                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                                                                                       glPushMatrix();
-                                                                                                                                               glBegin(GL_QUADS);
-                                                                                                                                               glTexCoord2f(0,0);
-                                                                                                                                               glVertex3f(midpoint.x-itemsize-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,      midpoint.y-itemsize-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,          0.0f);
-                                                                                                                                               glTexCoord2f(1,0);
-                                                                                                                                               glVertex3f(midpoint.x+itemsize+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,      midpoint.y-itemsize-((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition,          0.0f);
-                                                                                                                                               glTexCoord2f(1,1);
-                                                                                                                                               glVertex3f(midpoint.x+itemsize+((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition,      midpoint.y+itemsize+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
-                                                                                                                                               glTexCoord2f(0,1);
-                                                                                                                                               glVertex3f(midpoint.x-itemsize-((float)i)*1/2+offsetx[j]*((float)i)/2+movex[j]*transition, midpoint.y+itemsize+((float)i)*1/2+offsety[j]*((float)i)/2+movey[j]*transition, 0.0f);
-                                                                                                                                               glEnd();
-                                                                                                                                       glPopMatrix();
-                                                                                                                               }
-                                                                                                                       }
-                                                                                                               }
-                                                                                                       glPopMatrix();
-                                                                                               glPopMatrix();
-                                                                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                                                       glPopMatrix();
-                                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                                               glPopMatrix();
+                                                       glPopMatrix();
+                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                                               glPopMatrix();
+                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
 
-                                                                                       if(j-7>=accountcampaignchoicesmade[accountactive]){
-                                                                                               //glColor4f(0,0,0,1);
-                                                                                               //text.glPrintOutline(startx[j]+10-1.5,starty[j]-4-1.5,menustring[j],0,0.6*1.25,640,480);
-                                                                                               //glColor4f(1,0,0,1);
-                                                                                               //text.glPrint(startx[j]+10,starty[j]-4,menustring[j],0,0.6,640,480);
-                                                                                               text.glPrintOutlined(0.9,0,0,startx[j]+10,starty[j]-4,menustring[j],0,0.6,640,480);
-                                                                                               glDisable(GL_DEPTH_TEST);
-                                                                                       }
-                                                                               }
-                                                                       }
-                                                               }
-                                                       }
+                                               if(j-7>=accountactive->getCampaignChoicesMade()){
+                                                       text.glPrintOutlined(0.9,0,0,startx[j]+10,starty[j]-4,menustring[j],0,0.6,640,480);
+                                                       glDisable(GL_DEPTH_TEST);
                                                }
-                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                               glPopMatrix();
+                                       }
+                               }
+                       }
+               }
+               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+               glPopMatrix();
+               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+               glPopMatrix();
+
+                       if(mainmenu==1||mainmenu==2)
+                               if(transition<.1||transition>.9){
+                                       glClear(GL_DEPTH_BUFFER_BIT);
+                                       glEnable(GL_ALPHA_TEST);
+                                       glAlphaFunc(GL_GREATER, 0.001f);
+                                       glEnable(GL_TEXTURE_2D);
+                                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
+                                       glDisable(GL_CULL_FACE);
+                                       glDisable(GL_LIGHTING);
+                                       glDepthMask(0);
+                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                                       glPushMatrix();                                                                         // Store The Projection Matrix
+                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
+                                               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
                                                glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                               glPushMatrix();                                                                         // Store The Modelview Matrix
+                                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
+                                                       glPushMatrix();
+                                                               glDisable(GL_TEXTURE_2D);
+                                                               if(transition<.1)
+                                                                       glColor4f(1,0,0,1-(transition*10));
+                                                               if(transition>.9)
+                                                                       glColor4f(1,0,0,1-((1-transition)*10));
+                                                       glPopMatrix();
                                                glPopMatrix();
+                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                                       glPopMatrix();
+                               }
 
-                                                       if(mainmenu==1||mainmenu==2)
-                                                               if(transition<.1||transition>.9){
-                                                                       glClear(GL_DEPTH_BUFFER_BIT);
-                                                                       glEnable(GL_ALPHA_TEST);
-                                                                       glAlphaFunc(GL_GREATER, 0.001f);
-                                                                       glEnable(GL_TEXTURE_2D);
-                                                                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
-                                                                       glDisable(GL_CULL_FACE);
-                                                                       glDisable(GL_LIGHTING);
-                                                                       glDepthMask(0);
-                                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                                       glPushMatrix();                                                                         // Store The Projection Matrix
-                                                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                                                               glOrtho(0,640,0,480,-100,100);                                          // Set Up An Ortho Screen
-                                                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                               glPushMatrix();                                                                         // Store The Modelview Matrix
-                                                                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                                                                       glPushMatrix();
-                                                                                               glDisable(GL_TEXTURE_2D);
-                                                                                               if(transition<.1)glColor4f(1,0,0,1-(transition*10));
-                                                                                               if(transition>.9)glColor4f(1,0,0,1-((1-transition)*10));
-                                                                                               /*glPushMatrix();
-                                                                                               glBegin(GL_QUADS);
-                                                                                               glTexCoord2f(0,0);
-                                                                                               glVertex3f(190, 150,     0.0f);
-                                                                                               glTexCoord2f(1,0);
-                                                                                               glVertex3f(640, 150,     0.0f);
-                                                                                               glTexCoord2f(1,1);
-                                                                                               glVertex3f(640, 336, 0.0f);
-                                                                                               glTexCoord2f(0,1);
-                                                                                               glVertex3f(190, 336, 0.0f);
-                                                                                               glEnd();
-                                                                                               glPopMatrix();*/
-                                                                                       glPopMatrix();
-                                                                               glPopMatrix();
-                                                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                                       glPopMatrix();
-                                                               }
-
-                                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                               glPushMatrix();                                                                         // Store The Projection Matrix
-                                                                       glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                                                       glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
-                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                       glPushMatrix();                                                                         // Store The Modelview Matrix
-                                                                               glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                                                               glTranslatef(screenwidth/2,screenheight/2,0);
-                                                                               glPushMatrix();
-                                                                                       glScalef((float)screenwidth/2,(float)screenheight/2,1);
-                                                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                                                                                       glEnable(GL_BLEND);
-                                                                                       glEnable(GL_TEXTURE_2D);
-                                                                                       glColor4f(1,1,1,1);
-                                                                                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
-                                                                                       glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
-                                                                               glPopMatrix();
-                                                                               glPushMatrix();
-                                                                                       glTranslatef(mousecoordh-screenwidth/2,mousecoordv*-1+screenheight/2,0);
-                                                                                       glScalef((float)screenwidth/64,(float)screenwidth/64,1);
-                                                                                       glTranslatef(1,-1,0);
-                                                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                                                                                       glColor4f(1,1,1,1);
-                                                                                       glBindTexture( GL_TEXTURE_2D, cursortexture);
-                                                                                       glPushMatrix();
-                                                                                               //glScalef(.25,.25,.25);
-                                                                                               glBegin(GL_QUADS);
-                                                                                               glTexCoord2f(0,0);
-                                                                                               glVertex3f(-1,          -1,      0.0f);
-                                                                                               glTexCoord2f(1,0);
-                                                                                               glVertex3f(1,   -1,      0.0f);
-                                                                                               glTexCoord2f(1,1);
-                                                                                               glVertex3f(1,   1, 0.0f);
-                                                                                               glTexCoord2f(0,1);
-                                                                                               glVertex3f(-1,  1, 0.0f);
-                                                                                               glEnd();
-                                                                                       glPopMatrix();
-                                                                               glPopMatrix();
-                                                                       glPopMatrix();
-                                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                               glPopMatrix();
+                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                       glPushMatrix();                                                                         // Store The Projection Matrix
+                               glLoadIdentity();                                                                       // Reset The Projection Matrix
+                               glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
+                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                               glPushMatrix();                                                                         // Store The Modelview Matrix
+                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
+                                       glTranslatef(screenwidth/2,screenheight/2,0);
+                                       glPushMatrix();
+                                               glScalef((float)screenwidth/2,(float)screenheight/2,1);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                               glEnable(GL_BLEND);
+                                               glEnable(GL_TEXTURE_2D);
+                                               glColor4f(1,1,1,1);
+                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
+                                               glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
+                                       glPopMatrix();
+                                       if(!waiting) { // hide the cursor while waiting for a key
+                                               glPushMatrix();
+                                                       glTranslatef(mousecoordh-screenwidth/2,mousecoordv*-1+screenheight/2,0);
+                                                       glScalef((float)screenwidth/64,(float)screenwidth/64,1);
+                                                       glTranslatef(1,-1,0);
+                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                                       glColor4f(1,1,1,1);
+                                                       glBindTexture( GL_TEXTURE_2D, cursortexture);
+                                                       glPushMatrix();
+                                                               //glScalef(.25,.25,.25);
+                                                               glBegin(GL_QUADS);
+                                                               glTexCoord2f(0,0);
+                                                               glVertex3f(-1,          -1,      0.0f);
+                                                               glTexCoord2f(1,0);
+                                                               glVertex3f(1,   -1,      0.0f);
+                                                               glTexCoord2f(1,1);
+                                                               glVertex3f(1,   1, 0.0f);
+                                                               glTexCoord2f(0,1);
+                                                               glVertex3f(-1,  1, 0.0f);
+                                                               glEnd();
+                                                       glPopMatrix();
+                                               glPopMatrix();
+                                       }
+                               glPopMatrix();
+                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                       glPopMatrix();
 
 
-                                                               if(flashamount>0)
-                                                               {
-                                                                       //printf("Flash amount: %f, delay %i\n", flashamount, flashdelay);
-                                                                       if(flashamount>1)flashamount=1;
-                                                                       if(flashdelay<=0)flashamount-=multiplier;
-                                                                       flashdelay--;
-                                                                       if(flashamount<0)flashamount=0;
-                                                                       glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
-                                                                       glDisable(GL_CULL_FACE);
-                                                                       glDisable(GL_LIGHTING);
-                                                                       glDisable(GL_TEXTURE_2D);
-                                                                       glDepthMask(0);
-                                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                                       glPushMatrix();                                                                         // Store The Projection Matrix
-                                                                               glLoadIdentity();                                                                       // Reset The Projection Matrix
-                                                                               glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
-                                                                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                               glPushMatrix();                                                                         // Store The Modelview Matrix
-                                                                                       glLoadIdentity();                                                               // Reset The Modelview Matrix
-                                                                                       glScalef(screenwidth,screenheight,1);
-                                                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                                                                                       glEnable(GL_BLEND);
-                                                                                       glColor4f(flashr,flashg,flashb,flashamount);
-                                                                                       glBegin(GL_QUADS);
-                                                                                       glVertex3f(0,           0,       0.0f);
-                                                                                       glVertex3f(256, 0,       0.0f);
-                                                                                       glVertex3f(256, 256, 0.0f);
-                                                                                       glVertex3f(0,   256, 0.0f);
-                                                                                       glEnd();
-                                                                                       glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
-                                                                               glPopMatrix();                                                                          // Restore The Old Projection Matrix
-                                                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-                                                                       glPopMatrix();                                                                          // Restore The Old Projection Matrix
-                                                                       glEnable(GL_DEPTH_TEST);                                                        // Enables Depth Testing
-                                                                       glEnable(GL_CULL_FACE);
-                                                                       glDisable(GL_BLEND);
-                                                                       glDepthMask(1);
-                                                               }       
+                       if(flashamount>0)
+                       {
+                               //printf("Flash amount: %f, delay %i\n", flashamount, flashdelay);
+                               if(flashamount>1)flashamount=1;
+                               if(flashdelay<=0)flashamount-=multiplier;
+                               flashdelay--;
+                               if(flashamount<0)flashamount=0;
+                               glDisable(GL_DEPTH_TEST);                                                       // Disables Depth Testing
+                               glDisable(GL_CULL_FACE);
+                               glDisable(GL_LIGHTING);
+                               glDisable(GL_TEXTURE_2D);
+                               glDepthMask(0);
+                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                               glPushMatrix();                                                                         // Store The Projection Matrix
+                                       glLoadIdentity();                                                                       // Reset The Projection Matrix
+                                       glOrtho(0,screenwidth,0,screenheight,-100,100);                                         // Set Up An Ortho Screen
+                                       glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                                       glPushMatrix();                                                                         // Store The Modelview Matrix
+                                               glLoadIdentity();                                                               // Reset The Modelview Matrix
+                                               glScalef(screenwidth,screenheight,1);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                               glEnable(GL_BLEND);
+                                               glColor4f(flashr,flashg,flashb,flashamount);
+                                               glBegin(GL_QUADS);
+                                               glVertex3f(0,           0,       0.0f);
+                                               glVertex3f(256, 0,       0.0f);
+                                               glVertex3f(256, 256, 0.0f);
+                                               glVertex3f(0,   256, 0.0f);
+                                               glEnd();
+                                               glMatrixMode(GL_PROJECTION);                                            // Select The Projection Matrix
+                                       glPopMatrix();                                                                          // Restore The Old Projection Matrix
+                               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+                               glPopMatrix();                                                                          // Restore The Old Projection Matrix
+                               glEnable(GL_DEPTH_TEST);                                                        // Enables Depth Testing
+                               glEnable(GL_CULL_FACE);
+                               glDisable(GL_BLEND);
+                               glDepthMask(1);
+                       }
        }
 
        if(freeze||winfreeze||(mainmenu&&gameon)||(!gameon&&gamestarted)||(!gameon&&gamestarted)){
@@ -3944,7 +3420,6 @@ int Game::DrawGLScene(StereoSide side)
                multiplier=0;
        }
 
-
        //glFlush();
        if ( side == stereoRight || side == stereoCenter ) {
                if(drawmode!=motionblurmode||mainmenu){
index 3a3689fb16a7f1e93dbfc45e4d681a167db390b4..db565c2faf9d995705484362096a8a4b6f8a359a 100644 (file)
@@ -21,6 +21,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "Game.h"
 #include "openal_wrapper.h"
+#include "Animation.h"
 
 extern float screenwidth,screenheight;
 extern float viewdistance;
@@ -31,17 +32,13 @@ extern float fadestart;
 extern float texscale;
 extern float gravity;
 extern Light light;
-extern Animation animation[animation_count];
 extern Skeleton testskeleton;
 extern int numsounds;
-extern OPENAL_SAMPLE   *samp[100];
-extern int channels[100];
 extern Terrain terrain;
-extern Sprites sprites;
+//extern Sprites sprites;
 extern int kTextureSize;
 extern float texdetail;
 extern float realtexdetail;
-extern float terraindetail;
 extern float volume;
 extern Objects objects;
 extern int detail;
@@ -52,9 +49,6 @@ extern bool ismotionblur;
 extern bool trilinear;
 extern bool osx;
 extern bool musictoggle;
-extern Weapons weapons;
-extern Person player[maxplayers];
-extern int numplayers;
 extern int environment;
 extern bool ambientsound;
 extern float multiplier;
@@ -75,19 +69,8 @@ extern int whichjointendarray[26];
 extern int difficulty;
 extern float tintr,tintg,tintb;
 extern float slomospeed;
-extern char mapname[256];
 extern bool gamestarted;
 
-extern int numaccounts;
-extern int accountactive;
-extern int accountdifficulty[10];
-extern int accountprogress[10];
-extern float accountpoints[10];
-extern float accounthighscore[10][50];
-extern float accountfasttime[10][50];
-extern bool accountunlocked[10][60];
-extern char accountname[10][256];
-
 extern int numdialogues;
 extern int numdialogueboxes[20];
 extern int dialoguetype[20];
@@ -111,11 +94,6 @@ extern float accountcampaigntime[10];
 extern int accountcampaignchoicesmade[10];
 extern int accountcampaignchoices[10][5000];
 
-extern OPENAL_STREAM * strm[20];
-
-extern "C"     void PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-
 void LOG(const std::string &fmt, ...)
 {
     // !!! FIXME: write me.
@@ -131,59 +109,11 @@ void Game::Dispose()
        LOGFUNC;
 
        if(endgame==2){
-               accountcampaignchoicesmade[accountactive]=0;
-               accountcampaignscore[accountactive]=0;
-               accountcampaigntime[accountactive]=0;
+               accountactive->endGame();
                endgame=0;
        }
 
-
-       sprintf (mapname, ":Data:Users");
-
-       FILE                    *tfile;
-       tfile=fopen( ConvertFileName(mapname, "wb"), "wb" );
-       if (tfile)
-       {
-               fpackf(tfile, "Bi", numaccounts);
-               fpackf(tfile, "Bi", accountactive);
-               if(numaccounts>0)
-               {
-                       for(i=0;i<numaccounts;i++)
-                       {
-                               fpackf(tfile, "Bf", accountcampaigntime[i]);
-                               fpackf(tfile, "Bf", accountcampaignscore[i]);
-                               fpackf(tfile, "Bf", accountcampaignfasttime[i]);
-                               fpackf(tfile, "Bf", accountcampaignhighscore[i]);
-                               fpackf(tfile, "Bi", accountdifficulty[i]);
-                               fpackf(tfile, "Bi", accountprogress[i]);
-                               fpackf(tfile, "Bi", accountcampaignchoicesmade[i]);
-                               for(j=0;j<accountcampaignchoicesmade[i];j++)
-                               {
-                                       fpackf(tfile, "Bi", accountcampaignchoices[i][j]);
-                               }
-                               fpackf(tfile, "Bf", accountpoints[i]);
-                               for(j=0;j<50;j++)
-                               {
-                                       fpackf(tfile, "Bf", accounthighscore[i][j]);
-                                       fpackf(tfile, "Bf", accountfasttime[i][j]);
-                               }
-                               for(j=0;j<60;j++)
-                               {
-                                       fpackf(tfile, "Bb",  accountunlocked[i][j]);
-                               }
-                               fpackf(tfile, "Bi",  strlen(accountname[i]));
-                               if(strlen(accountname[i])>0)
-                               {
-                                       for(j=0;j<(int)strlen(accountname[i]);j++)
-                                       {
-                                               fpackf(tfile, "Bb",  accountname[i][j]);
-                                       }
-                               }
-                       }
-               }
-
-               fclose(tfile);
-       }
+       Account::saveFile(":Data:Users", accountactive);
 
        TexIter it = textures.begin();
        for (; it != textures.end(); ++it)
@@ -200,19 +130,12 @@ void Game::Dispose()
 // this is causing problems on Linux, but we'll force an _exit() a little
 //  later in the shutdown process.  --ryan.
 #if !PLATFORM_LINUX
-#define streamcount 20
-#define samplecount 100
 
-       for (i=0; i < samplecount; ++i)
+       for (i=0; i < sounds_count; ++i)
        {
                OPENAL_Sample_Free(samp[i]);
        }
 
-       for (i=0; i < streamcount; ++i)
-       {
-               OPENAL_Stream_Close(strm[i]);
-       }
-
        OPENAL_Close();
        if (texture.data)
        {
@@ -223,202 +146,6 @@ void Game::Dispose()
 }
 
 
-//void Game::LoadSounds();
-void Game::LoadSounds()
-{
-       LOGFUNC;
-
-       LOG(std::string("Loading sounds..."));
-
-       OPENAL_3D_SetDopplerFactor(0);
-
-       OPENAL_SetSFXMasterVolume((int)(volume*255));
-
-       samp[footstepsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow1.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[footstepsound], 4.0f, 1000.0f);
-
-       samp[footstepsound2] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[footstepsound2], 4.0f, 1000.0f);
-
-       samp[footstepsound3] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepstone1.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[footstepsound3], 4.0f, 1000.0f);
-
-       samp[footstepsound4] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepstone2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[footstepsound4], 4.0f, 1000.0f);
-
-       samp[landsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:land.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[landsound], 4.0f, 1000.0f);
-
-       samp[jumpsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:jump.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[jumpsound], 4.0f, 1000.0f);
-
-       samp[hawksound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:hawk.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[hawksound], 40.0f, 10000.0f);
-
-       samp[whooshsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:whoosh.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[whooshsound], 4.0f, 1000.0f);
-       OPENAL_Sample_SetMode(samp[whooshsound], OPENAL_LOOP_NORMAL);
-
-       samp[landsound1] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:land1.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[landsound1], 4.0f, 1000.0f);
-
-
-
-       samp[landsound2] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:land2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[landsound2], 4.0f, 1000.0f);
-
-       samp[breaksound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:broken.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[breaksound], 8.0f, 2000.0f);
-
-       samp[lowwhooshsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:Lowwhoosh.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[lowwhooshsound], 8.0f, 2000.0f);
-
-       samp[midwhooshsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:midwhoosh.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[midwhooshsound], 8.0f, 2000.0f);
-
-       samp[highwhooshsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:highwhoosh.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[highwhooshsound], 8.0f, 2000.0f);
-
-       samp[movewhooshsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:movewhoosh.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[movewhooshsound], 8.0f, 2000.0f);
-
-       samp[heavyimpactsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:heavyimpact.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[heavyimpactsound], 8.0f, 2000.0f);
-
-       samp[whooshhitsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:Whooshhit.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[whooshhitsound], 8.0f, 2000.0f);
-
-       samp[thudsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:thud.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[thudsound], 8.0f, 2000.0f);
-
-       samp[alarmsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:alarm.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[alarmsound], 8.0f, 2000.0f);
-
-       samp[breaksound2] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:break.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[breaksound2], 8.0f, 2000.0f);
-
-       samp[knifedrawsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:knifedraw.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[knifedrawsound], 8.0f, 2000.0f);
-
-       samp[knifesheathesound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:knifesheathe.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[knifesheathesound], 8.0f, 2000.0f);
-
-       samp[fleshstabsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:Fleshstab.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[fleshstabsound], 8.0f, 2000.0f);
-
-       samp[fleshstabremovesound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:Fleshstabremove.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[fleshstabremovesound], 8.0f, 2000.0f);
-
-       samp[knifeswishsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:knifeswish.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[knifeswishsound], 8.0f, 2000.0f);
-
-       samp[knifeslicesound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:knifeslice.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[knifeslicesound], 8.0f, 2000.0f);
-
-       samp[swordslicesound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:swordslice.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[swordslicesound], 8.0f, 2000.0f);
-
-       samp[skidsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:skid.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[skidsound], 8.0f, 2000.0f);
-
-       samp[snowskidsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:snowskid.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[snowskidsound], 8.0f, 2000.0f);
-
-       samp[bushrustle] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:bushrustle.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[bushrustle], 4.0f, 1000.0f);
-
-       samp[clank1sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:clank1.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[clank1sound], 8.0f, 2000.0f);
-
-       samp[clank2sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:clank2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[clank2sound], 8.0f, 2000.0f);
-
-       samp[clank3sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:clank3.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[clank3sound], 8.0f, 2000.0f);
-
-       samp[clank4sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:clank4.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[clank4sound], 8.0f, 2000.0f);
-
-       samp[consolesuccesssound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:consolesuccess.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[consolesuccesssound], 4.0f, 1000.0f);
-
-       samp[consolefailsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:consolefail.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[consolefailsound], 4.0f, 1000.0f);
-
-       samp[metalhitsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:MetalHit.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[metalhitsound], 8.0f, 2000.0f);
-
-       samp[clawslicesound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:clawslice.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[clawslicesound], 8.0f, 2000.0f);
-
-       samp[splattersound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:splatter.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[splattersound], 8.0f, 2000.0f);
-
-       samp[growlsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:Growl.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[growlsound], 1000.0f, 2000.0f);
-
-       samp[growl2sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:Growl2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[growl2sound], 1000.0f, 2000.0f);
-
-       samp[barksound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:bark.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[barksound], 1000.0f, 2000.0f);
-
-       samp[bark2sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:bark2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[bark2sound], 1000.0f, 2000.0f);
-
-       samp[bark3sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:bark3.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[bark3sound], 1000.0f, 2000.0f);
-
-       samp[snarlsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:snarl.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[snarlsound], 1000.0f, 2000.0f);
-
-
-       samp[snarl2sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:snarl2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[snarl2sound], 1000.0f, 2000.0f);
-
-       samp[barkgrowlsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:barkgrowl.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[barkgrowlsound], 1000.0f, 2000.0f);
-
-       samp[rabbitattacksound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitattack.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitattacksound], 1000.0f, 2000.0f);
-
-       samp[rabbitattack2sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitattack2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitattack2sound], 1000.0f, 2000.0f);
-
-       samp[rabbitattack3sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitattack3.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitattack3sound], 1000.0f, 2000.0f);
-
-       samp[rabbitattack4sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitattack4.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitattack4sound], 1000.0f, 2000.0f);
-
-       samp[rabbitpainsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitpain.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitpainsound], 1000.0f, 2000.0f);
-
-       samp[rabbitpain1sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitpain2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitpain1sound], 1000.0f, 2000.0f);
-
-       /*samp[rabbitpain2sound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitpain2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitpain2sound], 1000.0f, 2000.0f);
-       */
-       samp[rabbitchitter] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitchitter.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitchitter], 1000.0f, 2000.0f);
-
-       samp[rabbitchitter2] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:rabbitchitter2.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[rabbitchitter2], 1000.0f, 2000.0f);
-
-       samp[swordstaffsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:swordstaff.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[swordstaffsound], 8.0f, 2000.0f);
-
-       samp[staffbodysound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:staffbody.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[staffbodysound], 8.0f, 2000.0f);
-
-       samp[staffheadsound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:staffhead.ogg"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[staffheadsound], 8.0f, 2000.0f);
-
-       samp[staffbreaksound] = OPENAL_Sample_LoadEx(OPENAL_FREE, ConvertFileName(":Data:Sounds:staffbreak.wav"), OPENAL_HW3D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[staffbreaksound], 8.0f, 2000.0f);
-}
-
 void Game::LoadTexture(const char *fileName, GLuint *textureid,int mipmap, bool hasalpha)
 {
        GLuint          type;
@@ -451,7 +178,8 @@ void Game::LoadTexture(const char *fileName, GLuint *textureid,int mipmap, bool
 
                glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
 
-               if(!*textureid)glGenTextures( 1, textureid );
+               if(!*textureid)
+                       glGenTextures( 1, textureid );
                glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
 
                glBindTexture( GL_TEXTURE_2D, *textureid);
@@ -459,20 +187,9 @@ void Game::LoadTexture(const char *fileName, GLuint *textureid,int mipmap, bool
                if(trilinear)if(mipmap)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
                if(!trilinear)if(mipmap)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
                if(!mipmap)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-
-               //glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.sizeX, texture.sizeY, 0,
-               //          GL_BGRA_EXT, GL_UNSIGNED_INT_8_8_8_8_REV, texture.data);
-
-               //gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, GL_BGRA_EXT, GL_UNSIGNED_INT_8_8_8_8_REV, texture.data );
-
+               
                gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-//             textures.insert(std::make_pair(fname, *textureid));
        }
-//     else
-//     {
-//             *textureid = it->second;
-//     }
 }
 
 void Game::LoadTextureSave(const char *fileName, GLuint *textureid,int mipmap,GLubyte *array, int *skinsize)
@@ -996,73 +713,7 @@ void Game::InitGame()
 
        numchallengelevels=14;
 
-       /*char tempstring[256];
-       sprintf (tempstring, "%s", registrationname);
-       long num1;
-       long num2;
-       long num3;
-       long num4;
-       long long longnum;
-       longnum = MD5_string ( tempstring);
-       //longnum = 1111111111111111;
-       num1 = longnum/100000000;
-       num2 = longnum%100000000;
-       sprintf (tempstring, "%d-%d-%d-%d", num1/10000, num1%10000, num2/10000, num2%10000);
-       */
-
-       FILE                    *tfile;
-
-       accountactive=-1;
-
-       sprintf (mapname, ":Data:Users");
-       tfile=fopen( ConvertFileName(mapname), "rb" );
-       if(tfile)
-       {
-               funpackf(tfile, "Bi", &numaccounts);
-               funpackf(tfile, "Bi", &accountactive);
-               if(numaccounts>0)
-               {
-                       for(i=0;i<numaccounts;i++)
-                       {
-                               funpackf(tfile, "Bf", &accountcampaigntime[i]);
-                               funpackf(tfile, "Bf", &accountcampaignscore[i]);
-                               funpackf(tfile, "Bf", &accountcampaignfasttime[i]);
-                               funpackf(tfile, "Bf", &accountcampaignhighscore[i]);
-                               funpackf(tfile, "Bi", &accountdifficulty[i]);
-                               funpackf(tfile, "Bi", &accountprogress[i]);
-                               funpackf(tfile, "Bi", &accountcampaignchoicesmade[i]);
-                               for(j=0;j<accountcampaignchoicesmade[i];j++)
-                               {
-                                       funpackf(tfile, "Bi", &accountcampaignchoices[i][j]);
-                                       if (accountcampaignchoices[i][j] >= 10)
-                                       {
-                                               accountcampaignchoices[i][j] = 0;
-                                       }
-                               }
-                               funpackf(tfile, "Bf", &accountpoints[i]);
-                               for(j=0;j<50;j++)
-                               {
-                                       funpackf(tfile, "Bf", &accounthighscore[i][j]);
-                                       funpackf(tfile, "Bf", &accountfasttime[i][j]);
-                               }
-                               for(j=0;j<60;j++)
-                               {
-                                       funpackf(tfile, "Bb",  &accountunlocked[i][j]);
-                               }
-                               int temp;
-                               funpackf(tfile, "Bi",  &temp);
-                               if(temp>0)
-                               {
-                                       for(j=0;j<temp;j++)
-                                       {
-                                               funpackf(tfile, "Bb",  &accountname[i][j]);
-                                       }
-                               }
-                       }
-               }
-
-               fclose(tfile);
-       }
+       accountactive=Account::loadFile(":Data:Users");
 
        tintr=1;
        tintg=1;
@@ -1162,26 +813,12 @@ void Game::InitGame()
 
        if(detail==2){
                texdetail=1;
-               terraindetail=1;
        }
        if(detail==1){
                texdetail=2;
-               terraindetail=1;
        }
        if(detail==0){
                texdetail=4;
-               terraindetail=1;
-               //terraindetail=2;
-       }
-
-       for (int it = 0; it < 100; ++it)
-       {
-               channels[it] = -1;
-               samp[it] = NULL;
-       }
-       for (int it = 0; it < 20; ++it)
-       {
-               strm[it] = NULL;
        }
 
        LOG("Initializing sound system...");
@@ -1222,71 +859,10 @@ void Game::InitGame()
     #endif
 
        OPENAL_SetSFXMasterVolume((int)(volume*255));
+       loadAllSounds();
 
-       strm[stream_music3] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:music3.mp3"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=0;}
-//     OPENAL_Sample_SetMinMaxDistance(strm[stream_music3], 4.0f, 1000.0f);
-       OPENAL_Stream_SetMode(strm[stream_music3], OPENAL_LOOP_NORMAL);
-
-       if(musictoggle){
-//             PlaySoundEx( stream_music3, strm[stream_music3], NULL, true);
-               PlayStreamEx(stream_music3, strm[stream_music3], 0, true);
-               OPENAL_SetPaused(channels[stream_music3], false);
-               OPENAL_SetVolume(channels[stream_music3], 256);
-       }
-
-       FadeLoadingScreen(20);
-
-       if(ambientsound){
-               strm[stream_wind] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:wind.mp3"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-//             OPENAL_Sample_SetMinMaxDistance(strm[stream_wind], 4.0f, 1000.0f);
-               OPENAL_Stream_SetMode(strm[stream_wind], OPENAL_LOOP_NORMAL);
-
-               FadeLoadingScreen(30);
-
-               strm[stream_desertambient] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:desertambient.mp3"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-//             OPENAL_Sample_SetMinMaxDistance(strm[stream_desertambient], 4.0f, 1000.0f);
-               OPENAL_Stream_SetMode(strm[stream_desertambient], OPENAL_LOOP_NORMAL);
-       }
-
-       FadeLoadingScreen(40);
-
-       samp[firestartsound] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:firestart.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-       strm[stream_firesound] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:fire.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-//     OPENAL_Sample_SetMinMaxDistance(strm[stream_firesound], 8.0f, 2000.0f);
-       OPENAL_Stream_SetMode(strm[stream_firesound], OPENAL_LOOP_NORMAL);
-
-       FadeLoadingScreen(50);
-
-       samp[fireendsound] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:fireend.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=5;}
-       OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-       //if(musictoggle){
-       strm[stream_music1grass] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:music1grass.mp3"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=1;}
-//     OPENAL_Sample_SetMinMaxDistance(strm[stream_music1grass], 4.0f, 1000.0f);
-       OPENAL_Stream_SetMode(strm[stream_music1grass], OPENAL_LOOP_NORMAL);
-
-       strm[stream_music1snow] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:music1snow.mp3"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=2;}
-//     OPENAL_Sample_SetMinMaxDistance(strm[stream_music1snow], 4.0f, 1000.0f);
-       OPENAL_Stream_SetMode(strm[stream_music1snow], OPENAL_LOOP_NORMAL);
-
-       FadeLoadingScreen(60);
-
-       strm[stream_music1desert] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:music1desert.mp3"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=3;}
-//     OPENAL_Sample_SetMinMaxDistance(strm[stream_music1desert], 4.0f, 1000.0f);
-       OPENAL_Stream_SetMode(strm[stream_music1desert], OPENAL_LOOP_NORMAL);
-
-       FadeLoadingScreen(80);
-       strm[stream_music2] = OPENAL_Stream_Open(ConvertFileName(":Data:Sounds:music2.ogg"), OPENAL_2D, 0, 0); if(visibleloading){LoadingScreen(); loadscreencolor=4;}
-//     OPENAL_Sample_SetMinMaxDistance(strm[stream_music2], 4.0f, 1000.0f);
-       OPENAL_Stream_SetMode(strm[stream_music2], OPENAL_LOOP_NORMAL);
-
-       //}
-
-
-       FadeLoadingScreen(90);
-
+       if(musictoggle)
+         emit_stream_np(stream_music3);
 
        LoadTexture(":Data:Textures:Cursor.png",&cursortexture,0,1);
 
@@ -1321,25 +897,6 @@ void Game::InitGame()
        newdetail=detail;
        newscreenwidth=screenwidth;
        newscreenheight=screenheight;
-
-
-
-       /*
-       float gLoc[3]={0,0,0};
-       float vel[3]={0,0,0};
-       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-       PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-       OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-       OPENAL_SetVolume(channels[firestartsound], 256);
-       OPENAL_SetPaused(channels[firestartsound], false);
-       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-       flashr=1;
-       flashg=0;
-       flashb=0;
-       flashamount=1;
-       flashdelay=1;
-       */
 }
 
 
@@ -1354,11 +911,6 @@ void Game::LoadStuff()
 
        visibleloading=1;
 
-       /*musicvolume[3]=512;
-       PlaySoundEx( music4, samp[music4], NULL, true);
-       OPENAL_SetPaused(channels[music4], false);
-       OPENAL_SetVolume(channels[music4], 512);
-       */
        loadtime=0;
 
        stillloading=1;
@@ -1397,16 +949,12 @@ void Game::LoadStuff()
 
        if(detail==2){
                texdetail=1;
-               terraindetail=1;
        }
        if(detail==1){
                texdetail=2;
-               terraindetail=1;
        }
        if(detail==0){
                texdetail=4;
-               terraindetail=1;
-               //terraindetail=2;
        }
 
        realtexdetail=texdetail;
@@ -1481,19 +1029,19 @@ void Game::LoadStuff()
 
        LoadTexture(":Data:Textures:bodyprint.png",&terrain.bodyprinttexture,0,1);
 
-       /*LoadTexture(":Data:Textures:cloud.png",&sprites.cloudtexture,1);
+       /*LoadTexture(":Data:Textures:cloud.png",&Sprite::cloudtexture,1);
 
-       LoadTexture(":Data:Textures:cloudimpact.png",&sprites.cloudimpacttexture,1);
+       LoadTexture(":Data:Textures:cloudimpact.png",&Sprite::cloudimpacttexture,1);
 
-       LoadTexture(":Data:Textures:bloodparticle.png",&sprites.bloodtexture,1);
+       LoadTexture(":Data:Textures:bloodparticle.png",&Sprite::bloodtexture,1);
 
-       LoadTexture(":Data:Textures:snowflake.png",&sprites.snowflaketexture,1);
+       LoadTexture(":Data:Textures:snowflake.png",&Sprite::snowflaketexture,1);
 
-       LoadTexture(":Data:Textures:flame.png",&sprites.flametexture,1);
+       LoadTexture(":Data:Textures:flame.png",&Sprite::flametexture,1);
 
-       LoadTexture(":Data:Textures:smoke.png",&sprites.smoketexture,1);
+       LoadTexture(":Data:Textures:smoke.png",&Sprite::smoketexture,1);
        //texdetail=temptexdetail;
-       LoadTexture(":Data:Textures:shine.png",&sprites.shinetexture,1);*/
+       LoadTexture(":Data:Textures:shine.png",&Sprite::shinetexture,1);*/
 
 
 
@@ -1505,17 +1053,17 @@ void Game::LoadStuff()
        //LoadTexture(":Data:Textures:box.jpg",&objects.boxtextureptr,1,0);
 
 
-       LoadTexture(":Data:Textures:cloud.png",&sprites.cloudtexture,1,1);
-       LoadTexture(":Data:Textures:cloudimpact.png",&sprites.cloudimpacttexture,1,1);
-       LoadTexture(":Data:Textures:bloodparticle.png",&sprites.bloodtexture,1,1);
-       LoadTexture(":Data:Textures:snowflake.png",&sprites.snowflaketexture,1,1);
-       LoadTexture(":Data:Textures:flame.png",&sprites.flametexture,1,1);
-       LoadTexture(":Data:Textures:bloodflame.png",&sprites.bloodflametexture,1,1);
-       LoadTexture(":Data:Textures:smoke.png",&sprites.smoketexture,1,1);
-       LoadTexture(":Data:Textures:shine.png",&sprites.shinetexture,1,0);
-       LoadTexture(":Data:Textures:splinter.png",&sprites.splintertexture,1,1);
-       LoadTexture(":Data:Textures:leaf.png",&sprites.leaftexture,1,1);
-       LoadTexture(":Data:Textures:tooth.png",&sprites.toothtexture,1,1);
+       LoadTexture(":Data:Textures:cloud.png",&Sprite::cloudtexture,1,1);
+       LoadTexture(":Data:Textures:cloudimpact.png",&Sprite::cloudimpacttexture,1,1);
+       LoadTexture(":Data:Textures:bloodparticle.png",&Sprite::bloodtexture,1,1);
+       LoadTexture(":Data:Textures:snowflake.png",&Sprite::snowflaketexture,1,1);
+       LoadTexture(":Data:Textures:flame.png",&Sprite::flametexture,1,1);
+       LoadTexture(":Data:Textures:bloodflame.png",&Sprite::bloodflametexture,1,1);
+       LoadTexture(":Data:Textures:smoke.png",&Sprite::smoketexture,1,1);
+       LoadTexture(":Data:Textures:shine.png",&Sprite::shinetexture,1,0);
+       LoadTexture(":Data:Textures:splinter.png",&Sprite::splintertexture,1,1);
+       LoadTexture(":Data:Textures:leaf.png",&Sprite::leaftexture,1,1);
+       LoadTexture(":Data:Textures:tooth.png",&Sprite::toothtexture,1,1);
 
        rotation=0;
        rotation2=0;
@@ -1554,7 +1102,7 @@ void Game::LoadStuff()
        gravity=-10;
 
        texscale=.2/megascale/viewdistdetail;
-       terrain.scale=3*megascale*terraindetail*viewdistdetail;
+       terrain.scale=3*megascale*viewdistdetail;
 
        viewer.x=terrain.size/2*terrain.scale;
        viewer.z=terrain.size/2*terrain.scale;
@@ -1597,126 +1145,7 @@ void Game::LoadStuff()
        rabbitcoords=player[0].coords;
        rabbitcoords.y=terrain.getHeight(rabbitcoords.x,rabbitcoords.z);
 
-       animation[runanim].Load((char *)":Data:Animations:Run",middleheight,neutral);
-
-       animation[bounceidleanim].Load((char *)":Data:Animations:Idle",middleheight,neutral);
-       animation[stopanim].Load((char *)":Data:Animations:Stop",middleheight,neutral);
-
-       animation[jumpupanim].Load((char *)":Data:Animations:JumpUp",highheight,neutral);
-       animation[jumpdownanim].Load((char *)":Data:Animations:JumpDown",highheight,neutral);
-
-       animation[landanim].Load((char *)":Data:Animations:Landing",lowheight,neutral);
-       animation[landhardanim].Load((char *)":Data:Animations:Landhard",lowheight,neutral);
-       animation[climbanim].Load((char *)":Data:Animations:Climb",lowheight,neutral);
-       animation[hanganim].Load((char *)":Data:Animations:Hangon",lowheight,neutral);
-       animation[spinkickanim].Load((char *)":Data:Animations:SpinKick",middleheight,normalattack);
-
-       animation[getupfromfrontanim].Load((char *)":Data:Animations:GetUpFromFront",lowheight,neutral);
-       animation[getupfrombackanim].Load((char *)":Data:Animations:GetUpFromBack",lowheight,neutral);
-       animation[crouchanim].Load((char *)":Data:Animations:Crouch",lowheight,neutral);
-       animation[sneakanim].Load((char *)":Data:Animations:Sneak",lowheight,neutral);
-       animation[rollanim].Load((char *)":Data:Animations:Roll",lowheight,neutral);
-       animation[flipanim].Load((char *)":Data:Animations:Flip",highheight,neutral);
-       animation[frontflipanim].Load((char *)":Data:Animations:Flip",highheight,neutral);
-       animation[spinkickreversedanim].Load((char *)":Data:Animations:SpinKickCaught",middleheight,reversed);
-
-       animation[spinkickreversalanim].Load((char *)":Data:Animations:SpinKickCatch",middleheight,reversal);
-       animation[lowkickanim].Load((char *)":Data:Animations:lowkick",middleheight,normalattack);
-       animation[sweepanim].Load((char *)":Data:Animations:sweep",lowheight,normalattack);
-       animation[sweepreversedanim].Load((char *)":Data:Animations:SweepCaught",lowheight,reversed);
-       animation[sweepreversalanim].Load((char *)":Data:Animations:SweepCatch",middleheight,reversal);
-       animation[rabbitkickanim].Load((char *)":Data:Animations:RabbitKick",middleheight,normalattack);
-       animation[rabbitkickreversedanim].Load((char *)":Data:Animations:RabbitKickCaught",middleheight,reversed);
-       animation[rabbitkickreversalanim].Load((char *)":Data:Animations:RabbitKickCatch",lowheight,reversal);
-       animation[upunchanim].Load((char *)":Data:Animations:Upunch",middleheight,normalattack);
-       animation[staggerbackhighanim].Load((char *)":Data:Animations:Staggerbackhigh",middleheight,neutral);
-       animation[upunchreversedanim].Load((char *)":Data:Animations:UpunchCaught",middleheight,reversed);
-
-       animation[upunchreversalanim].Load((char *)":Data:Animations:UpunchCatch",middleheight,reversal);
-       animation[hurtidleanim].Load((char *)":Data:Animations:Hurtidle",middleheight,neutral);
-       animation[backhandspringanim].Load((char *)":Data:Animations:Backhandspring",middleheight,neutral);
-       animation[fightidleanim].Load((char *)":Data:Animations:Fightidle",middleheight,neutral);
-       animation[walkanim].Load((char *)":Data:Animations:Walk",middleheight,neutral);
-
-       animation[fightsidestep].Load((char *)":Data:Animations:Fightsidestep",middleheight,neutral);
-       animation[killanim].Load((char *)":Data:Animations:Kill",middleheight,normalattack);
-       animation[sneakattackanim].Load((char *)":Data:Animations:Sneakattack",middleheight,reversal);
-       animation[sneakattackedanim].Load((char *)":Data:Animations:Sneakattacked",middleheight,reversed);
-       animation[drawrightanim].Load((char *)":Data:Animations:drawright",middleheight,neutral);
-       animation[knifeslashstartanim].Load((char *)":Data:Animations:slashstart",middleheight,normalattack);
-       animation[crouchdrawrightanim].Load((char *)":Data:Animations:crouchdrawright",lowheight,neutral);
-       animation[crouchstabanim].Load((char *)":Data:Animations:crouchstab",lowheight,normalattack);
-
-       animation[knifefollowanim].Load((char *)":Data:Animations:slashfollow",middleheight,reversal);
-       animation[knifefollowedanim].Load((char *)":Data:Animations:slashfollowed",middleheight,reversed);
-       animation[knifethrowanim].Load((char *)":Data:Animations:knifethrow",middleheight,normalattack);
-       animation[removeknifeanim].Load((char *)":Data:Animations:removeknife",middleheight,neutral);
-       animation[crouchremoveknifeanim].Load((char *)":Data:Animations:crouchremoveknife",lowheight,neutral);
-       animation[jumpreversedanim].Load((char *)":Data:Animations:JumpCaught",middleheight,reversed);
-       animation[jumpreversalanim].Load((char *)":Data:Animations:JumpCatch",middleheight,reversal);
-       animation[staggerbackhardanim].Load((char *)":Data:Animations:Staggerbackhard",middleheight,neutral);
-
-       animation[dropkickanim].Load((char *)":Data:Animations:Dropkick",middleheight,normalattack);
-       animation[winduppunchanim].Load((char *)":Data:Animations:Winduppunch",middleheight,normalattack);
-       animation[winduppunchblockedanim].Load((char *)":Data:Animations:Winduppunchblocked",middleheight,normalattack);
-       animation[blockhighleftanim].Load((char *)":Data:Animations:Blockhighleft",middleheight,normalattack);
-       animation[blockhighleftstrikeanim].Load((char *)":Data:Animations:Blockhighleftstrike",middleheight,normalattack);
-       animation[backflipanim].Load((char *)":Data:Animations:Backflip",highheight,neutral);
-       animation[walljumpbackanim].Load((char *)":Data:Animations:Walljumpback",highheight,neutral);
-       animation[walljumpfrontanim].Load((char *)":Data:Animations:Walljumpfront",highheight,neutral);
-       animation[rightflipanim].Load((char *)":Data:Animations:Rightflip",highheight,neutral);
-       animation[walljumprightanim].Load((char *)":Data:Animations:Walljumpright",highheight,neutral);
-       animation[leftflipanim].Load((char *)":Data:Animations:Leftflip",highheight,neutral);
-       animation[walljumpleftanim].Load((char *)":Data:Animations:Walljumpleft",highheight,neutral);
-       animation[walljumprightkickanim].Load((char *)":Data:Animations:Walljumprightkick",highheight,neutral);
-       animation[walljumpleftkickanim].Load((char *)":Data:Animations:Walljumpleftkick",highheight,neutral);
-       animation[knifefightidleanim].Load((char *)":Data:Animations:Knifefightidle",middleheight,neutral);
-       animation[knifesneakattackanim].Load((char *)":Data:Animations:Knifesneakattack",middleheight,reversal);
-       animation[knifesneakattackedanim].Load((char *)":Data:Animations:Knifesneakattacked",middleheight,reversed);
-       animation[swordfightidleanim].Load((char *)":Data:Animations:swordfightidle",middleheight,neutral);
-       animation[drawleftanim].Load((char *)":Data:Animations:drawleft",middleheight,neutral);
-       animation[swordslashanim].Load((char *)":Data:Animations:swordslash",middleheight,normalattack);
-       animation[swordgroundstabanim].Load((char *)":Data:Animations:swordgroundstab",lowheight,normalattack);
-       animation[dodgebackanim].Load((char *)":Data:Animations:dodgeback",middleheight,neutral);
-       animation[swordsneakattackanim].Load((char *)":Data:Animations:Swordsneakattack",middleheight,reversal);
-       animation[swordsneakattackedanim].Load((char *)":Data:Animations:Swordsneakattacked",middleheight,reversed);
-       animation[swordslashreversedanim].Load((char *)":Data:Animations:swordslashCaught",middleheight,reversed);
-       animation[swordslashreversalanim].Load((char *)":Data:Animations:swordslashCatch",middleheight,reversal);
-       animation[knifeslashreversedanim].Load((char *)":Data:Animations:knifeslashCaught",middleheight,reversed);
-       animation[knifeslashreversalanim].Load((char *)":Data:Animations:knifeslashCatch",middleheight,reversal);
-       animation[swordfightidlebothanim].Load((char *)":Data:Animations:swordfightidleboth",middleheight,neutral);
-       animation[swordslashparryanim].Load((char *)":Data:Animations:sworduprightparry",middleheight,normalattack);
-       animation[swordslashparriedanim].Load((char *)":Data:Animations:swordslashparried",middleheight,normalattack);
-       animation[wolfidle].Load((char *)":Data:Animations:Wolfidle",middleheight,neutral);
-       animation[wolfcrouchanim].Load((char *)":Data:Animations:Wolfcrouch",lowheight,neutral);
-       animation[wolflandanim].Load((char *)":Data:Animations:Wolflanding",lowheight,neutral);
-       animation[wolflandhardanim].Load((char *)":Data:Animations:Wolflandhard",lowheight,neutral);
-       animation[wolfrunanim].Load((char *)":Data:Animations:Wolfrun",middleheight,neutral);
-       animation[wolfrunninganim].Load((char *)":Data:Animations:Wolfrunning",middleheight,neutral);
-       animation[rabbitrunninganim].Load((char *)":Data:Animations:Rabbitrunning",middleheight,neutral);
-       animation[wolfstopanim].Load((char *)":Data:Animations:Wolfstop",middleheight,neutral);
-       animation[rabbittackleanim].Load((char *)":Data:Animations:Rabbittackle",middleheight,neutral);
-       animation[rabbittacklinganim].Load((char *)":Data:Animations:Rabbittackling",middleheight,reversal);
-       animation[rabbittackledbackanim].Load((char *)":Data:Animations:Rabbittackledback",middleheight,reversed);
-       animation[rabbittackledfrontanim].Load((char *)":Data:Animations:Rabbittackledfront",middleheight,reversed);
-       animation[wolfslapanim].Load((char *)":Data:Animations:Wolfslap",middleheight,normalattack);
-       animation[staffhitanim].Load((char *)":Data:Animations:StaffHit",middleheight,normalattack);
-       animation[staffgroundsmashanim].Load((char *)":Data:Animations:StaffGroundSmash",lowheight,normalattack);
-       animation[staffspinhitanim].Load((char *)":Data:Animations:Spinwhack",middleheight,normalattack);
-       animation[staffhitreversedanim].Load((char *)":Data:Animations:StaffHitCaught",middleheight,reversed);
-       animation[staffhitreversalanim].Load((char *)":Data:Animations:StaffHitCatch",middleheight,reversal);
-       animation[staffspinhitreversedanim].Load((char *)":Data:Animations:SpinWhackCaught",middleheight,reversed);
-       animation[staffspinhitreversalanim].Load((char *)":Data:Animations:SpinWhackCatch",middleheight,reversal);
-
-       animation[sitanim].Load((char *)":Data:Animations:Sit",lowheight,neutral);
-       animation[sleepanim].Load((char *)":Data:Animations:Sleep",lowheight,neutral);
-       animation[talkidleanim].Load((char *)":Data:Animations:TalkIdle",middleheight,neutral);
-
-       animation[sitwallanim].Load((char *)":Data:Animations:Dying",lowheight,neutral);
-       animation[dead1anim].Load((char *)":Data:Animations:Dead1",lowheight,neutral);
-       animation[dead2anim].Load((char *)":Data:Animations:Dead2",lowheight,neutral);
-       animation[dead3anim].Load((char *)":Data:Animations:Dead3",lowheight,neutral);
-       animation[dead4anim].Load((char *)":Data:Animations:Dead4",lowheight,neutral);
+       loadAllAnimations();
        //Fix knife stab, too lazy to do it manually
        XYZ moveamount;
        moveamount=0;
@@ -1805,23 +1234,9 @@ void Game::LoadStuff()
 
                glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 0, 0, kTextureSize, kTextureSize, 0);
        }
-       //}
-
-       LoadSounds();
 
-       /*PlaySoundEx( consolesuccesssound, samp[consolesuccesssound], NULL, true);
-       OPENAL_SetVolume(channels[consolesuccesssound], 256);
-       OPENAL_SetPaused(channels[consolesuccesssound], false);
-       */
        if(targetlevel!=7){
-               float gLoc[3]={0,0,0};
-               float vel[3]={0,0,0};
-               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-               OPENAL_SetVolume(channels[fireendsound], 256);
-               OPENAL_SetPaused(channels[fireendsound], false);
-               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
+               emit_sound_at(fireendsound);
        }
 
        stillloading=0;
@@ -1831,200 +1246,3 @@ void Game::LoadStuff()
        visibleloading=0;
 }
 
-Game::Game()
-{
-       terraintexture = 0;
-       terraintexture2 = 0;
-       terraintexture3 = 0;
-       screentexture = 0;
-       screentexture2 = 0;
-       logotexture = 0;
-       loadscreentexture = 0;
-       Maparrowtexture = 0;
-       Mapboxtexture = 0;
-       Mapcircletexture = 0;
-       cursortexture = 0;
-
-       memset(Mainmenuitems, 0, sizeof(Mainmenuitems));
-
-       nummenuitems = 0;
-
-       memset(startx, 0, sizeof(startx));
-       memset(starty, 0, sizeof(starty));
-       memset(endx, 0, sizeof(endx));
-       memset(endy, 0, sizeof(endy));
-
-       memset(selectedlong, 0, sizeof(selectedlong));
-       memset(offsetx, 0, sizeof(offsetx));
-       memset(offsety, 0, sizeof(offsety));
-       memset(movex, 0, sizeof(movex));
-       memset(movey, 0, sizeof(movey));
-       memset(endy, 0, sizeof(endy));
-
-       transition = 0;
-       anim = 0;
-       selected = 0;
-       loaddistrib = 0;
-       keyselect = 0;
-       indemo = 0;
-
-       won = 0;
-
-       entername = 0;
-
-       memset(menustring, 0, sizeof(menustring));
-       memset(registrationname, 0, sizeof(registrationname));
-       registrationnumber = 0;
-
-       newdetail = 0;
-       newscreenwidth = 0;
-       newscreenheight = 0;
-
-       gameon = 0;
-       deltah = 0,deltav = 0;
-       mousecoordh = 0,mousecoordv = 0;
-       oldmousecoordh = 0,oldmousecoordv = 0;
-       rotation = 0,rotation2 = 0;
-
-//     SkyBox skybox;
-
-       cameramode = 0;
-       cameratogglekeydown = 0;
-       chattogglekeydown = 0;
-       olddrawmode = 0;
-       drawmode = 0;
-       drawmodetogglekeydown = 0;
-       explodetogglekeydown = 0;
-       detailtogglekeydown = 0;
-       firstload = 0;
-       oldbutton = 0;
-
-       leveltime = 0;
-       loadtime = 0;
-
-//     Model hawk;
-
-//     XYZ hawkcoords;
-//     XYZ realhawkcoords;
-
-       hawktexture = 0;
-       hawkrotation = 0;
-       hawkcalldelay = 0;
-/*
-       Model eye;
-       Model iris;
-       Model cornea;
-*/
-       stealthloading = 0;
-
-       campaignnumlevels = 0;
-
-       memset(campaignmapname, 0, sizeof(campaignmapname));
-       memset(campaigndescription, 0, sizeof(campaigndescription));
-       memset(campaignchoosenext, 0, sizeof(campaignchoosenext));
-       memset(campaignnumnext, 0, sizeof(campaignnumnext));
-       memset(campaignnextlevel, 0, sizeof(campaignnextlevel));
-       int campaignchoicesmade;
-       memset(campaignchoices, 0, sizeof(campaignchoices));
-       memset(campaignlocationx, 0, sizeof(campaignlocationx));
-       memset(campaignlocationy, 0, sizeof(campaignlocationy));
-       memset(campaignlocationy, 0, sizeof(campaignlocationy));
-
-       campaignchoicenum = 0;
-
-       memset(campaignchoicewhich, 0, sizeof(campaignchoicewhich));
-
-       whichchoice = 0;
-
-       numlevelspassed = 0;
-
-       memset(levelorder, 0, sizeof(levelorder));
-       memset(levelvisible, 0, sizeof(levelvisible));
-       memset(levelhighlight, 0, sizeof(levelhighlight));
-
-       minimap = 0;
-
-       musictype = 0,oldmusictype = 0,oldoldmusictype = 0;
-       realthreat = 0;
-
-//     Model rabbit;
-//     XYZ rabbitcoords;
-
-//     XYZ mapcenter;
-       mapradius = 0;
-
-//     Text text;
-       fps = 0;
-
-//     XYZ cameraloc;
-       cameradist = 0;
-
-       envtogglekeydown = 0;
-       slomotogglekeydown = 0;
-       texturesizetogglekeydown = 0;
-       freezetogglekeydown = 0;
-       drawtoggle = 0;
-
-       editorenabled = 0;
-       editortype = 0;
-       editorsize = 0;
-       editorrotation = 0;
-       editorrotation2 = 0;
-
-       brightness = 0;
-
-       quit = 0;
-       tryquit = 0;
-
-//     XYZ pathpoint[30];
-       numpathpoints = 0;
-       memset(numpathpointconnect, 0, sizeof(numpathpointconnect));
-       memset(pathpointconnect, 0, sizeof(pathpointconnect));
-       pathpointselected = 0;
-
-       endgame = 0;
-       scoreadded = 0;
-       numchallengelevels = 0;
-
-       console = 0;
-       archiveselected = 0;
-
-       memset(consoletext, 0, sizeof(consoletext));
-       memset(consolechars, 0, sizeof(consolechars));
-       chatting = 0;
-       memset(displaytext, 0, sizeof(displaytext));
-       memset(displaychars, 0, sizeof(displaychars));
-       memset(displaytime, 0, sizeof(displaytime));
-       displayblinkdelay = 0;
-       displayblink = 0;
-       displayselected = 0;
-       consolekeydown = 0;
-       consoletogglekeydown = 0;
-       consoleblinkdelay = 0;
-       consoleblink = 0;
-       consoleselected = 0;
-       memset(togglekey, 0, sizeof(togglekey));
-       memset(togglekeydelay, 0, sizeof(togglekeydelay));
-       registernow = 0;
-       autocam = 0;
-
-       crouchkey = 0,jumpkey = 0,forwardkey = 0,chatkey = 0,backkey = 0,leftkey = 0,rightkey = 0,drawkey = 0,throwkey = 0,attackkey = 0;
-       oldattackkey = 0;
-
-       loading = 0;
-       talkdelay = 0;
-
-       numboundaries = 0;
-//     XYZ boundary[360];
-
-       whichlevel = 0;
-       oldenvironment = 0;
-       targetlevel = 0;
-       changedelay = 0;
-
-       memset(musicvolume, 0, sizeof(musicvolume));
-       memset(oldmusicvolume, 0, sizeof(oldmusicvolume));
-       musicselected = 0;
-       change = 0;
-}
-
index 8138608f19f01a8c7e85a23631300f4138587ed4..58a3bde7c19f1def242f24b06a1f1499db0a8298 100644 (file)
@@ -27,10 +27,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include <direct.h>
 #endif
 
+#include <limits>
 #include <ctime>
 #include "Game.h"
 #include "openal_wrapper.h"
 #include "Settings.h"
+#include "Input.h"
+#include "Animation.h"
+#include "Awards.h"
 
 using namespace std;
 
@@ -46,9 +50,6 @@ extern XYZ viewer;
 extern int environment;
 extern float texscale;
 extern Terrain terrain;
-extern OPENAL_SAMPLE   *samp[100];
-extern int channels[100];
-extern Sprites sprites;
 extern int kTextureSize;
 extern float screenwidth,screenheight;
 extern float gravity;
@@ -59,21 +60,16 @@ extern int slomo;
 extern float slomodelay;
 extern bool floatjump;
 extern float volume;
-extern Animation animation[animation_count];
 extern Light light;
 extern float texdetail;
 extern GLubyte bloodText[512*512*3];
 extern GLubyte wolfbloodText[512*512*3];
-extern float terraindetail;
 extern float camerashake;
 extern float woozy;
 extern float blackout;
 extern bool cellophane;
 extern bool musictoggle;
 extern int difficulty;
-extern Weapons weapons;
-extern Person player[maxplayers];
-extern int numplayers;
 extern int bloodtoggle;
 extern bool invertmouse;
 extern float windvar;
@@ -87,9 +83,7 @@ extern bool autoslomo;
 extern bool keyboardfrozen;
 extern int netdatanew;
 extern bool loadingstuff;
-extern char mapname[256];
 extern XYZ windvector;
-extern bool buttons[3];
 extern bool debugmode;
 static int music1;
 extern int mainmenu;
@@ -113,17 +107,9 @@ extern bool texttoggle;
 extern bool alwaysblur;
 extern float gamespeed;
 extern bool decals;
-extern bool vblsync;
 extern bool immediate;
 extern bool velocityblur;
-extern int bonus;
-extern int oldbonus;
-extern float bonusvalue;
-extern float bonustotal;
-extern float bonustime;
-extern float startbonustotal;
 extern float tintr,tintg,tintb;
-extern float bonusnum[100];
 extern bool skyboxtexture;
 extern float skyboxr;
 extern float skyboxg;
@@ -145,11 +131,9 @@ extern bool reversaltrain;
 extern bool canattack;
 extern bool cananger;
 extern float damagedealt;
-extern float damagetaken;
 extern int maptype;
 extern int editoractive;
 extern int editorpathtype;
-extern bool oldbuttons[3];
 
 extern float hostiletime;
 
@@ -168,70 +152,13 @@ extern int currenthotspot;
 extern int kBitsPerPixel;
 extern int hostile;
 
-extern int numaccounts;
-extern int accountactive;
-extern int accountdifficulty[10];
-extern int accountprogress[10];
-extern float accountpoints[10];
-extern float accounthighscore[10][50];
-extern float accountfasttime[10][50];
-extern bool accountunlocked[10][60];
-extern char accountname[10][256];
-
 extern bool stillloading;
 extern bool winfreeze;
 
-extern int numfalls;
-extern int numflipfail;
-extern int numseen;
-extern int numstaffattack;
-extern int numswordattack;
-extern int numknifeattack;
-extern int numunarmedattack;
-extern int numescaped;
-extern int numflipped;
-extern int numwallflipped;
-extern int numthrowkill;
-extern int numafterkill;
-extern int numreversals;
-extern int numattacks;
-extern int maxalarmed;
-extern int numresponded;
-
-extern int numdialogues;
-extern int numdialogueboxes[max_dialogues];
-extern int dialoguetype[max_dialogues];
-extern int dialogueboxlocation[max_dialogues][max_dialoguelength];
-extern float dialogueboxcolor[max_dialogues][max_dialoguelength][3];
-extern int dialogueboxsound[max_dialogues][max_dialoguelength];
-extern char dialoguetext[max_dialogues][max_dialoguelength][128];
-extern char dialoguename[max_dialogues][max_dialoguelength][64];
-extern XYZ dialoguecamera[max_dialogues][max_dialoguelength];
-extern XYZ participantlocation[max_dialogues][10];
-extern int participantfocus[max_dialogues][max_dialoguelength];
-extern int participantaction[max_dialogues][max_dialoguelength];
-extern float participantrotation[max_dialogues][10];
-extern XYZ participantfacing[max_dialogues][max_dialoguelength][10];
-extern float dialoguecamerarotation[max_dialogues][max_dialoguelength];
-extern float dialoguecamerarotation2[max_dialogues][max_dialoguelength];
-extern int indialogue;
-extern int whichdialogue;
-extern int directing;
-extern float dialoguetime;
-extern int dialoguegonethrough[20];
-
 extern bool campaign;
 
 extern float oldgamespeed;
 
-extern float accountcampaignhighscore[10];
-extern float accountcampaignfasttime[10];
-extern float accountcampaignscore[10];
-extern float accountcampaigntime[10];
-
-extern int accountcampaignchoicesmade[10];
-extern int accountcampaignchoices[10][5000];
-
 static const char *rabbitskin[] = {
 ":Data:Textures:Fur3.jpg",
 ":Data:Textures:Fur.jpg",
@@ -262,11 +189,6 @@ static bool stripfx(const char *str, const char *pfx)
   return !strncasecmp(str, pfx, strlen(pfx));
 }
 
-extern OPENAL_STREAM * strm[20];
-extern "C"     void PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-
-
 static const char *cmd_names[] = {
 #define DECLARE_COMMAND(cmd) #cmd " ",
 #include "ConsoleCmds.h"
@@ -292,9 +214,7 @@ static void ch_quit(Game *game, const char *args)
 
 static void ch_map(Game *game, const char *args)
 {
-  char buf[64];
-  snprintf(buf, 63, ":Data:Maps:%s", args);
-  game->Loadlevel(buf);
+  game->Loadlevel(args);
   game->whichlevel = -2;
   campaign = 0;
 }
@@ -333,142 +253,131 @@ static void ch_save(Game *game, const char *args)
   fpackf(tfile, "Bi Bi", player[0].whichskin, player[0].creature);
 
   fpackf(tfile, "Bi", numdialogues);
-  if(numdialogues)
-    for(k=0;k<numdialogues;k++){
-      fpackf(tfile, "Bi", numdialogueboxes[k]);
-      fpackf(tfile, "Bi", dialoguetype[k]);
-      for(l=0;l<10;l++){
-       fpackf(tfile, "Bf Bf Bf", participantlocation[k][l].x, participantlocation[k][l].y, participantlocation[k][l].z);
-       fpackf(tfile, "Bf", participantrotation[k][l]);
-      }
-      if(numdialogueboxes)
-       for(l=0;l<numdialogueboxes[k];l++){
-         fpackf(tfile, "Bi", dialogueboxlocation[k][l]);
-         fpackf(tfile, "Bf", dialogueboxcolor[k][l][0]);
-         fpackf(tfile, "Bf", dialogueboxcolor[k][l][1]);
-         fpackf(tfile, "Bf", dialogueboxcolor[k][l][2]);
-         fpackf(tfile, "Bi", dialogueboxsound[k][l]);
-
-         templength=strlen(dialoguetext[k][l]);
-         fpackf(tfile, "Bi",(templength));
-         for(m=0;m<templength;m++){
-           fpackf(tfile, "Bb", dialoguetext[k][l][m]);
-           if(dialoguetext[k][l][m]=='\0')break;
-         }
+       for(k=0;k<numdialogues;k++){
+               fpackf(tfile, "Bi", numdialogueboxes[k]);
+               fpackf(tfile, "Bi", dialoguetype[k]);
+               for(l=0;l<10;l++){
+                       fpackf(tfile, "Bf Bf Bf", participantlocation[k][l].x, participantlocation[k][l].y, participantlocation[k][l].z);
+                       fpackf(tfile, "Bf", participantrotation[k][l]);
+               }
+               for(l=0;l<numdialogueboxes[k];l++){
+                       fpackf(tfile, "Bi", dialogueboxlocation[k][l]);
+                       fpackf(tfile, "Bf", dialogueboxcolor[k][l][0]);
+                       fpackf(tfile, "Bf", dialogueboxcolor[k][l][1]);
+                       fpackf(tfile, "Bf", dialogueboxcolor[k][l][2]);
+                       fpackf(tfile, "Bi", dialogueboxsound[k][l]);
+
+                       templength=strlen(dialoguetext[k][l]);
+                       fpackf(tfile, "Bi",(templength));
+                       for(m=0;m<templength;m++){
+                               fpackf(tfile, "Bb", dialoguetext[k][l][m]);
+                               if(dialoguetext[k][l][m]=='\0')break;
+                       }
 
-         templength=strlen(dialoguename[k][l]);
-         fpackf(tfile, "Bi",templength);
-         for(m=0;m<templength;m++){
-           fpackf(tfile, "Bb", dialoguename[k][l][m]);
-           if(dialoguename[k][l][m]=='\0')break;
-         }
+                       templength=strlen(dialoguename[k][l]);
+                       fpackf(tfile, "Bi",templength);
+                       for(m=0;m<templength;m++){
+                               fpackf(tfile, "Bb", dialoguename[k][l][m]);
+                               if(dialoguename[k][l][m]=='\0')break;
+                       }
 
-         fpackf(tfile, "Bf Bf Bf", dialoguecamera[k][l].x, dialoguecamera[k][l].y, dialoguecamera[k][l].z);
-         fpackf(tfile, "Bi", participantfocus[k][l]);
-         fpackf(tfile, "Bi", participantaction[k][l]);
+                       fpackf(tfile, "Bf Bf Bf", dialoguecamera[k][l].x, dialoguecamera[k][l].y, dialoguecamera[k][l].z);
+                       fpackf(tfile, "Bi", participantfocus[k][l]);
+                       fpackf(tfile, "Bi", participantaction[k][l]);
 
-         for(m=0;m<10;m++)
-           fpackf(tfile, "Bf Bf Bf", participantfacing[k][l][m].x, participantfacing[k][l][m].y, participantfacing[k][l][m].z);
+                       for(m=0;m<10;m++)
+                               fpackf(tfile, "Bf Bf Bf", participantfacing[k][l][m].x, participantfacing[k][l][m].y, participantfacing[k][l][m].z);
 
-         fpackf(tfile, "Bf Bf",dialoguecamerarotation[k][l],dialoguecamerarotation2[k][l]);
+                       fpackf(tfile, "Bf Bf",dialoguecamerarotation[k][l],dialoguecamerarotation2[k][l]);
+               }
        }
-    }
 
-  if(player[0].numclothes)
-    for(k=0;k<player[0].numclothes;k++){
-      templength=strlen(player[0].clothes[k]);
-      fpackf(tfile, "Bi", templength);
-      for(l=0;l<templength;l++)
-       fpackf(tfile, "Bb", player[0].clothes[k][l]);
-      fpackf(tfile, "Bf Bf Bf", player[0].clothestintr[k], player[0].clothestintg[k], player[0].clothestintb[k]);
-    }
+       for(k=0;k<player[0].numclothes;k++){
+               templength=strlen(player[0].clothes[k]);
+               fpackf(tfile, "Bi", templength);
+               for(l=0;l<templength;l++)
+                       fpackf(tfile, "Bb", player[0].clothes[k][l]);
+               fpackf(tfile, "Bf Bf Bf", player[0].clothestintr[k], player[0].clothestintg[k], player[0].clothestintb[k]);
+       }
 
   fpackf(tfile, "Bi", environment);
 
   fpackf(tfile, "Bi", objects.numobjects);
 
-  if(objects.numobjects)
     for(k=0;k<objects.numobjects;k++){
       fpackf(tfile, "Bi Bf Bf Bf Bf Bf Bf", objects.type[k], objects.rotation[k], objects.rotation2[k], objects.position[k].x, objects.position[k].y, objects.position[k].z, objects.scale[k]);
     }
 
   fpackf(tfile, "Bi", numhotspots);
-  if(numhotspots)
-    for(i=0;i<numhotspots;i++){
-      fpackf(tfile, "Bi Bf Bf Bf Bf", hotspottype[i],hotspotsize[i],hotspot[i].x,hotspot[i].y,hotspot[i].z);
-      templength=strlen(hotspottext[i]);
-      fpackf(tfile, "Bi",templength);
-      for(l=0;l<templength;l++)
-       fpackf(tfile, "Bb", hotspottext[i][l]);
-    }
+       for(i=0;i<numhotspots;i++){
+               fpackf(tfile, "Bi Bf Bf Bf Bf", hotspottype[i],hotspotsize[i],hotspot[i].x,hotspot[i].y,hotspot[i].z);
+               templength=strlen(hotspottext[i]);
+               fpackf(tfile, "Bi",templength);
+               for(l=0;l<templength;l++)
+                       fpackf(tfile, "Bb", hotspottext[i][l]);
+       }
 
   fpackf(tfile, "Bi", numplayers);
-  if(numplayers>1&&numplayers<maxplayers)
+  if(numplayers<maxplayers)
     for(j=1;j<numplayers;j++){
-      fpackf(tfile, "Bi Bi Bf Bf Bf Bi Bi Bf Bb Bf", player[j].whichskin, player[j].creature, player[j].coords.x, player[j].coords.y, player[j].coords.z, player[j].num_weapons, player[j].howactive, player[j].scale, player[j].immobile, player[j].rotation);
-      if(player[j].num_weapons>0&&player[j].num_weapons<5)
-       for(k=0;k<player[j].num_weapons;k++){
-         fpackf(tfile, "Bi", weapons.type[player[j].weaponids[k]]);
-       }
-      if(player[j].numwaypoints<30){
-       fpackf(tfile, "Bi", player[j].numwaypoints);
-       for(k=0;k<player[j].numwaypoints;k++){
-         fpackf(tfile, "Bf", player[j].waypoints[k].x);
-         fpackf(tfile, "Bf", player[j].waypoints[k].y);
-         fpackf(tfile, "Bf", player[j].waypoints[k].z);
-         fpackf(tfile, "Bi", player[j].waypointtype[k]);
-       }
-       fpackf(tfile, "Bi", player[j].waypoint);
-      }
-      else{
-       player[j].numwaypoints=0;
-       player[j].waypoint=0;
-       fpackf(tfile, "Bi Bi Bi", player[j].numwaypoints, player[j].waypoint, player[j].waypoint);
-      }
-
-      fpackf(tfile, "Bf Bf Bf", player[j].armorhead, player[j].armorhigh, player[j].armorlow);
-      fpackf(tfile, "Bf Bf Bf", player[j].protectionhead, player[j].protectionhigh, player[j].protectionlow);
-      fpackf(tfile, "Bf Bf Bf", player[j].metalhead, player[j].metalhigh, player[j].metallow);
-      fpackf(tfile, "Bf Bf", player[j].power, player[j].speedmult);
-
-      if(player[j].creature==wolftype){
-       headprop=player[j].proportionhead.x/1.1;
-       bodyprop=player[j].proportionbody.x/1.1;
-       armprop=player[j].proportionarms.x/1.1;
-       legprop=player[j].proportionlegs.x/1.1;
-      }
-
-      if(player[j].creature==rabbittype){
-       headprop=player[j].proportionhead.x/1.2;
-       bodyprop=player[j].proportionbody.x/1.05;
-       armprop=player[j].proportionarms.x/1.00;
-       legprop=player[j].proportionlegs.x/1.1;
-      }
-
-      fpackf(tfile, "Bf Bf Bf Bf", headprop, bodyprop, armprop, legprop);
+               fpackf(tfile, "Bi Bi Bf Bf Bf Bi Bi Bf Bb Bf", player[j].whichskin, player[j].creature, player[j].coords.x, player[j].coords.y, player[j].coords.z, player[j].num_weapons, player[j].howactive, player[j].scale, player[j].immobile, player[j].rotation);
+               if(player[j].num_weapons<5)
+                       for(k=0;k<player[j].num_weapons;k++){
+                               fpackf(tfile, "Bi", weapons.type[player[j].weaponids[k]]);
+                       }
+               if(player[j].numwaypoints<30){
+                       fpackf(tfile, "Bi", player[j].numwaypoints);
+                       for(k=0;k<player[j].numwaypoints;k++){
+                               fpackf(tfile, "Bf", player[j].waypoints[k].x);
+                               fpackf(tfile, "Bf", player[j].waypoints[k].y);
+                               fpackf(tfile, "Bf", player[j].waypoints[k].z);
+                               fpackf(tfile, "Bi", player[j].waypointtype[k]);
+                       }
+                       fpackf(tfile, "Bi", player[j].waypoint);
+               } else {
+                       player[j].numwaypoints=0;
+                       player[j].waypoint=0;
+                       fpackf(tfile, "Bi Bi Bi", player[j].numwaypoints, player[j].waypoint, player[j].waypoint);
+               }
 
+               fpackf(tfile, "Bf Bf Bf", player[j].armorhead, player[j].armorhigh, player[j].armorlow);
+               fpackf(tfile, "Bf Bf Bf", player[j].protectionhead, player[j].protectionhigh, player[j].protectionlow);
+               fpackf(tfile, "Bf Bf Bf", player[j].metalhead, player[j].metalhigh, player[j].metallow);
+               fpackf(tfile, "Bf Bf", player[j].power, player[j].speedmult);
+
+               if(player[j].creature==wolftype) {
+                       headprop=player[j].proportionhead.x/1.1;
+                       bodyprop=player[j].proportionbody.x/1.1;
+                       armprop=player[j].proportionarms.x/1.1;
+                       legprop=player[j].proportionlegs.x/1.1;
+               } else if(player[j].creature==rabbittype){
+                       headprop=player[j].proportionhead.x/1.2;
+                       bodyprop=player[j].proportionbody.x/1.05;
+                       armprop=player[j].proportionarms.x/1.00;
+                       legprop=player[j].proportionlegs.x/1.1;
+               }
 
+               fpackf(tfile, "Bf Bf Bf Bf", headprop, bodyprop, armprop, legprop);
 
-      fpackf(tfile, "Bi", player[j].numclothes);
-      if(player[j].numclothes)
-       for(k=0;k<player[j].numclothes;k++){
-         int templength;
-         templength=strlen(player[j].clothes[k]);
-         fpackf(tfile, "Bi", templength);
-         for(l=0;l<templength;l++)
-           fpackf(tfile, "Bb", player[j].clothes[k][l]);
-         fpackf(tfile, "Bf Bf Bf", player[j].clothestintr[k], player[j].clothestintg[k], player[j].clothestintb[k]);
-       }
+               fpackf(tfile, "Bi", player[j].numclothes);
+               if(player[j].numclothes)
+                       for(k=0;k<player[j].numclothes;k++){
+                               int templength;
+                               templength=strlen(player[j].clothes[k]);
+                               fpackf(tfile, "Bi", templength);
+                               for(l=0;l<templength;l++)
+                                       fpackf(tfile, "Bb", player[j].clothes[k][l]);
+                               fpackf(tfile, "Bf Bf Bf", player[j].clothestintr[k], player[j].clothestintg[k], player[j].clothestintb[k]);
+                       }
     }
 
   fpackf(tfile, "Bi", game->numpathpoints);
-  if(game->numpathpoints)
-    for(j=0;j<game->numpathpoints;j++){
-      fpackf(tfile, "Bf Bf Bf Bi", game->pathpoint[j].x, game->pathpoint[j].y, game->pathpoint[j].z, game->numpathpointconnect[j]);
-      for(k=0;k<game->numpathpointconnect[j];k++){
-       fpackf(tfile, "Bi", game->pathpointconnect[j][k]);
-      }
-    }
+       for(j=0;j<game->numpathpoints;j++){
+               fpackf(tfile, "Bf Bf Bf Bi", game->pathpoint[j].x, game->pathpoint[j].y, game->pathpoint[j].z, game->numpathpointconnect[j]);
+               for(k=0;k<game->numpathpointconnect[j];k++){
+                       fpackf(tfile, "Bi", game->pathpointconnect[j][k]);
+               }
+       }
 
   fpackf(tfile, "Bf Bf Bf Bf", game->mapcenter.x, game->mapcenter.y, game->mapcenter.z, game->mapradius);
 
@@ -523,7 +432,7 @@ static void ch_size(Game *game, const char *args)
 static int find_closest()
 {
   int closest = 0;
-  float closestdist = 1.0/0.0;
+  float closestdist = std::numeric_limits<float>::max();
 
   for (int i = 1; i < numplayers; i++) {
     float distance;
@@ -555,9 +464,7 @@ static void set_proportion(int pnum, const char *args)
     player[pnum].proportionbody=1.1*bodyprop;
     player[pnum].proportionarms=1.1*armprop;
     player[pnum].proportionlegs=1.1*legprop;
-  }
-
-  if(player[pnum].creature==rabbittype){
+  } else if(player[pnum].creature==rabbittype){
     player[pnum].proportionhead=1.2*headprop;
     player[pnum].proportionbody=1.05*bodyprop;
     player[pnum].proportionarms=1.00*armprop;
@@ -672,7 +579,7 @@ static void set_clothes(int pnum, Game *game, const char *args)
   if (!game->AddClothes(buf,0,1,&player[pnum].skeleton.skinText[pnum],&player[pnum].skeleton.skinsize))
     return;
 
-  player[pnum].DoMipmaps(5,0,0,player[pnum].skeleton.skinsize,player[pnum].skeleton.skinsize);
+  player[pnum].DoMipmaps();
   strcpy(player[pnum].clothes[player[pnum].numclothes],buf);
   player[pnum].clothestintr[player[pnum].numclothes]=tintr;
   player[pnum].clothestintg[player[pnum].numclothes]=tintg;
@@ -829,23 +736,21 @@ static void ch_notindemo(Game *game, const char *args)
 static void ch_type(Game *game, const char *args)
 {
   int i, n = sizeof(editortypenames) / sizeof(editortypenames[0]);
-  for (i = 0; i < n; i++)
-    if (stripfx(args, editortypenames[i]))
-      {
-       editoractive = i;
-       break;
-      }
+       for (i = 0; i < n; i++)
+               if (stripfx(args, editortypenames[i])) {
+                       editoractive = i;
+                       break;
+               }
 }
 
 static void ch_path(Game *game, const char *args)
 {
   int i, n = sizeof(pathtypenames) / sizeof(pathtypenames[0]);
   for (i = 0; i < n; i++)
-    if (stripfx(args, pathtypenames[i]))
-      {
-       editorpathtype = i;
-       break;
-      }
+    if (stripfx(args, pathtypenames[i])) {
+               editorpathtype = i;
+               break;
+    }
 }
 
 static void ch_hs(Game *game, const char *args)
@@ -1014,9 +919,7 @@ static void ch_default(Game *game, const char *args)
     player[0].proportionbody=1.1;
     player[0].proportionarms=1.1;
     player[0].proportionlegs=1.1;
-  }
-
-  if(player[0].creature==rabbittype){
+  } else if(player[0].creature==rabbittype){
     player[0].proportionhead=1.2;
     player[0].proportionbody=1.05;
     player[0].proportionarms=1.00;
@@ -1054,20 +957,12 @@ static void ch_play(Game *game, const char *args)
   directing=0;
   indialogue=0;
 
-  float gLoc[3];
-  float vel[3];
   XYZ temppos;
   temppos=player[participantfocus[whichdialogue][indialogue]].coords;
   temppos=temppos-viewer;
   Normalise(&temppos);
   temppos+=viewer;
 
-  gLoc[0]=temppos.x;
-  gLoc[1]=temppos.y;
-  gLoc[2]=temppos.z;
-  vel[0]=0;
-  vel[1]=0;
-  vel[2]=0;
   int whichsoundplay;
   whichsoundplay=rabbitchitter;
   if(dialogueboxsound[whichdialogue][indialogue]==2)whichsoundplay=rabbitchitter2;
@@ -1089,10 +984,7 @@ static void ch_play(Game *game, const char *args)
   if(dialogueboxsound[whichdialogue][indialogue]==-2)whichsoundplay=firestartsound;
   if(dialogueboxsound[whichdialogue][indialogue]==-3)whichsoundplay=consolesuccesssound;
   if(dialogueboxsound[whichdialogue][indialogue]==-4)whichsoundplay=consolefailsound;
-  PlaySoundEx( whichsoundplay, samp[whichsoundplay], NULL, true);
-  OPENAL_3D_SetAttributes(channels[whichsoundplay], gLoc, vel);
-  OPENAL_SetVolume(channels[whichsoundplay], 256);
-  OPENAL_SetPaused(channels[whichsoundplay], false);
+  emit_sound_at(whichsoundplay, temppos);
 }
 
 static void ch_mapkilleveryone(Game *game, const char *args)
@@ -1181,24 +1073,11 @@ static void cmd_dispatch(Game *game, const char *cmd)
        cmd_handlers[i](game, cmd + strlen(cmd_names[i]));
        break;
       }
-  if (i < n_cmds)
-    {
-      PlaySoundEx(consolesuccesssound, samp[consolesuccesssound], NULL, true);
-      OPENAL_SetVolume(channels[consolesuccesssound], 256);
-      OPENAL_SetPaused(channels[consolesuccesssound], false);
-    }
-  else
-    {
-      PlaySoundEx(consolefailsound, samp[consolefailsound], NULL, true);
-      OPENAL_SetVolume(channels[consolefailsound], 256);
-      OPENAL_SetPaused(channels[consolefailsound], false);
-    }
+  emit_sound_np(i < n_cmds ? consolesuccesssound : consolefailsound);
 }
 
-
-
 /********************> Tick() <*****/
-extern void ScreenShot(const char * fname);
+extern bool save_image(const char * fname);
 void Screenshot        (void)
 {
        char temp[1024];
@@ -1211,193 +1090,8 @@ void Screenshot (void)
        #else
        mkdir("Screenshots", S_IRWXU);
        #endif
-
-       ScreenShot(temp/*"Screenshots\\Screenshot.png"*/);
-
-       /*FSSpec                                MAC_file;
-       GraphicsExportComponent QT_exporter;
-       OSErr                           MAC_error_code;
-       CGrafPtr                        MAC_currentPort;
-       GDHandle                        MAC_currentDevice;
-       unsigned char*          MAC_pixels;
-       Rect                            MAC_picture_rectangle;
-       GWorldPtr                       MAC_offscreen_graphics_port;
-
-       static int numscreenshots=0;
-
-       // Make an FSSpec
-       static char buf[256];
-       if(numscreenshots==0){
-       buf[0]=26;
-       buf[1]=':';
-       buf[2]='S';
-       buf[3]='c';
-       buf[4]='r';
-       buf[5]='e';
-       buf[6]='e';
-       buf[7]='n';
-       buf[8]='s';
-       buf[9]='h';
-       buf[10]='o';
-       buf[11]='t';
-       buf[12]='s';
-       buf[13]=':';
-       buf[14]='S';
-       buf[15]='c';
-       buf[16]='r';
-       buf[17]='e';
-       buf[18]='e';
-       buf[19]='n';
-       buf[20]='s';
-       buf[21]='h';
-       buf[22]='o';
-       buf[23]='t';
-       buf[24]='0';
-       buf[25]='0';
-       buf[26]='0';
-       }
-
-       FInfo *fndrInfo;
-       FSMakeFSSpec(0, 0, (unsigned char*)buf, &MAC_file);
-       while(!FSpGetFInfo (&MAC_file, fndrInfo)){
-       FSMakeFSSpec(0, 0, (unsigned char*)buf, &MAC_file);
-       if(!FSpGetFInfo (&MAC_file, fndrInfo)){
-       numscreenshots++;
-       buf[26]++;
-       if(buf[26]==':'){
-       buf[26]='0';
-       buf[25]++;
-       if(buf[25]==':'){
-       buf[25]='0';
-       buf[24]++;
-       if(buf[24]==':'){
-       buf[24]='9';
-       buf[25]='9';
-       buf[26]='9';
-       }
-       }
-       }
-       }
-       }
-
-
-       // Get the GWorld
-       GWorldPtr                       MAC_gWorld = (CGrafPtr) FrontWindow();
-       //assert(MAC_gWorld != NULL);
-
-       // Allocate memory for loading image
-       MAC_pixels = new unsigned char[(int)(screenheight * screenwidth * 4)];
-       if (MAC_pixels == NULL) {
-       //UTIL_Error("Could not create Texture data.");
-       return;
-       }
-
-       // Get GWorld
-       ::GetGWorld(&MAC_currentPort, &MAC_currentDevice);
-
-       // Make a picture Rectangle
-       MAC_picture_rectangle.left = 0;
-       MAC_picture_rectangle.right = screenwidth;
-       MAC_picture_rectangle.top = 0;
-       MAC_picture_rectangle.bottom = screenheight;
-
-       // Create new offscreen GWorld
-       MAC_error_code = ::QTNewGWorldFromPtr (&MAC_offscreen_graphics_port, k32ARGBPixelFormat, &MAC_picture_rectangle, NULL, NULL, 0, (char *) MAC_pixels, screenwidth * 4);
-       if (MAC_error_code)     {
-       ::SetGWorld(MAC_currentPort, MAC_currentDevice);
-       delete MAC_pixels;
-       //UTIL_Error("Could not create offscreen GWorld. ");
-       return;
-
-       }
-
-       // Copy OpenGL Context to new GWorld
-       glReadBuffer(GL_FRONT);
-       glReadPixels(0,0,screenwidth,screenheight,GL_RGBA,GL_UNSIGNED_BYTE,MAC_pixels);
-
-       // Swizzle texture
-       for (unsigned long byte = 0; byte < screenheight * screenwidth * 4; byte+=4) {
-       unsigned char temp = MAC_pixels[byte+0];
-       MAC_pixels[byte+0] = MAC_pixels[byte+3];
-       MAC_pixels[byte+3] = MAC_pixels[byte+2];
-       MAC_pixels[byte+2] = MAC_pixels[byte+1];
-       MAC_pixels[byte+1] = temp;
-       }
-
-       // Flip the image  :(   This could probably be optimized
-       int vert;
-       int src_index;
-       int dst_index;
-       unsigned char temp;
-       for (int horz = 0; horz < screenwidth; ++horz)
-       for (vert = 0; vert < screenheight / 2; ++vert) {
-       src_index = (screenwidth * vert + horz) * 4;
-       dst_index = (screenwidth * (screenheight - vert - 1) + horz) * 4;
-
-       temp=MAC_pixels[src_index+0];
-       MAC_pixels[src_index+0]=MAC_pixels[dst_index+0];
-       MAC_pixels[dst_index+0]=temp;
-
-       temp=MAC_pixels[src_index+1];
-       MAC_pixels[src_index+1]=MAC_pixels[dst_index+1];
-       MAC_pixels[dst_index+1]=temp;
-
-       temp=MAC_pixels[src_index+2];
-       MAC_pixels[src_index+2]=MAC_pixels[dst_index+2];
-       MAC_pixels[dst_index+2]=temp;
-
-       temp=MAC_pixels[src_index+3];
-       MAC_pixels[src_index+3]=MAC_pixels[dst_index+3];
-       MAC_pixels[dst_index+3]=temp;
-       }
-
-
-
-       // Export the Gworld
-       MAC_error_code =  OpenADefaultComponent(GraphicsExporterComponentType, kQTFileTypeBMP, &QT_exporter);
-       if (MAC_error_code) {
-       //UTIL_Warning("Unable to export screenshot.");
-       ::SetGWorld(MAC_currentPort, MAC_currentDevice);
-       ::DisposeGWorld(MAC_offscreen_graphics_port);
-       delete MAC_pixels;
-       return;
-       }
-
-       MAC_error_code =  GraphicsExportSetInputGWorld(QT_exporter,MAC_offscreen_graphics_port);
-       if (MAC_error_code) {
-       ::CloseComponent(QT_exporter);
-       ::SetGWorld(MAC_currentPort, MAC_currentDevice);
-       ::DisposeGWorld(MAC_offscreen_graphics_port);
-       delete MAC_pixels;
-       //UTIL_Warning("Unable to export screenshot.");
-       return;
-       }
-
-       MAC_error_code = GraphicsExportSetOutputFile(QT_exporter,&MAC_file);
-       if (MAC_error_code) {
-       ::CloseComponent(QT_exporter);
-       ::SetGWorld(MAC_currentPort, MAC_currentDevice);
-       ::DisposeGWorld(MAC_offscreen_graphics_port);
-       delete MAC_pixels;
-       //UTIL_Warning("Unable to export screenshot.");
-       return;
-       }
-
-       MAC_error_code = GraphicsExportDoExport(QT_exporter,NULL);
-       if (MAC_error_code) {
-       ::CloseComponent(QT_exporter);
-       ::SetGWorld(MAC_currentPort, MAC_currentDevice);
-       ::DisposeGWorld(MAC_offscreen_graphics_port);
-       delete MAC_pixels;
-       //UTIL_Warning("Unable to export screenshot.");
-       return;
-       }
-
-       ::CloseComponent(QT_exporter);
-       ::SetGWorld(MAC_currentPort, MAC_currentDevice);
-       ::DisposeGWorld(MAC_offscreen_graphics_port);
-
-       delete MAC_pixels;*/
+       
+       save_image(temp);
 }
 
 
@@ -1594,47 +1288,29 @@ void    Game::Setenvironment(int which)
 
        float temptexdetail;
        environment=which;
-/*
-       OPENAL_SetPaused(channels[music1snow], true);
-       OPENAL_SetPaused(channels[music1grass], true);
-       OPENAL_SetPaused(channels[music1desert], true);
-       OPENAL_SetPaused(channels[wind], true);
-       OPENAL_SetPaused(channels[desertambient], true);
-*/
-       OPENAL_SetPaused(channels[stream_music1snow], true);
-       OPENAL_SetPaused(channels[stream_music1grass], true);
-       OPENAL_SetPaused(channels[stream_music1desert], true);
-       OPENAL_SetPaused(channels[stream_wind], true);
-       OPENAL_SetPaused(channels[stream_desertambient], true);
+
+       pause_sound(stream_music1snow);
+       pause_sound(stream_music1grass);
+       pause_sound(stream_music1desert);
+       pause_sound(stream_wind);
+       pause_sound(stream_desertambient);
 
 
        if(environment==snowyenvironment){
                windvector=0;
                windvector.z=3;
-               if(ambientsound){
-                       //PlaySoundEx( wind, samp[wind], NULL, true);
-                       PlayStreamEx(stream_wind, strm[stream_wind], 0, true);
-                       OPENAL_SetPaused(channels[stream_wind], false);
-                       OPENAL_SetVolume(channels[stream_wind], 256);
-               }
+               if(ambientsound)
+                 emit_stream_np(stream_wind);
 
                LoadTexture(":Data:Textures:snowtree.png",&objects.treetextureptr,0,1);
                LoadTexture(":Data:Textures:bushsnow.png",&objects.bushtextureptr,0,1);
                LoadTexture(":Data:Textures:bouldersnow.jpg",&objects.rocktextureptr,1,0);
                LoadTexture(":Data:Textures:snowbox.jpg",&objects.boxtextureptr,1,0);
 
-               OPENAL_Sample_Free(samp[footstepsound]);
-               OPENAL_Sample_Free(samp[footstepsound2]);
-               OPENAL_Sample_Free(samp[footstepsound3]);
-               OPENAL_Sample_Free(samp[footstepsound4]);
-               samp[footstepsound] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow1.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound2] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow2.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound3] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepstone1.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound4] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepstone2.ogg"), OPENAL_HW3D, 0, 0);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound2], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound3], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound4], 4.0f, 1000.0f);
+               footstepsound = footstepsn1;
+               footstepsound2 = footstepsn2;
+               footstepsound3 = footstepst1;
+               footstepsound4 = footstepst2;
 
                LoadTexture(":Data:Textures:snow.jpg",&terraintexture,1,0);
 
@@ -1652,9 +1328,7 @@ void      Game::Setenvironment(int which)
                        ":Data:Textures:Skybox(snow):Back.jpg",
                        ":Data:Textures:Skybox(snow):Right.jpg",
                        ":Data:Textures:Skybox(snow):Up.jpg",
-                       ":Data:Textures:Skybox(snow):Down.jpg",
-                       ":Data:Textures:Skybox(snow):Cloud.jpg",
-                       ":Data:Textures:Skybox(snow):Reflect.jpg");
+                       ":Data:Textures:Skybox(snow):Down.jpg");
 
 
 
@@ -1670,25 +1344,13 @@ void    Game::Setenvironment(int which)
                LoadTexture(":Data:Textures:desertbox.jpg",&objects.boxtextureptr,1,0);
 
 
-               if(ambientsound){
-                       //PlaySoundEx( desertambient, samp[desertambient], NULL, true);
-                       PlayStreamEx( stream_desertambient, strm[stream_desertambient], NULL, true);
-                       OPENAL_SetPaused(channels[stream_desertambient], false);
-                       OPENAL_SetVolume(channels[stream_desertambient], 256);
-               }
+               if(ambientsound)
+                 emit_stream_np(stream_desertambient);
 
-               OPENAL_Sample_Free(samp[footstepsound]);
-               OPENAL_Sample_Free(samp[footstepsound2]);
-               OPENAL_Sample_Free(samp[footstepsound3]);
-               OPENAL_Sample_Free(samp[footstepsound4]);
-               samp[footstepsound] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow1.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound2] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow2.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound3] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow1.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound4] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepsnow2.ogg"), OPENAL_HW3D, 0, 0);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound2], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound3], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound4], 4.0f, 1000.0f);
+               footstepsound = footstepsn1;
+               footstepsound2 = footstepsn2;
+               footstepsound3 = footstepsn1;
+               footstepsound4 = footstepsn2;
 
                LoadTexture(":Data:Textures:sand.jpg",&terraintexture,1,0);
 
@@ -1705,9 +1367,7 @@ void      Game::Setenvironment(int which)
                        ":Data:Textures:Skybox(sand):Back.jpg",
                        ":Data:Textures:Skybox(sand):Right.jpg",
                        ":Data:Textures:Skybox(sand):Up.jpg",
-                       ":Data:Textures:Skybox(sand):Down.jpg",
-                       ":Data:Textures:Skybox(sand):Cloud.jpg",
-                       ":Data:Textures:Skybox(sand):Reflect.jpg");
+                       ":Data:Textures:Skybox(sand):Down.jpg");
 
 
 
@@ -1722,24 +1382,13 @@ void    Game::Setenvironment(int which)
                LoadTexture(":Data:Textures:boulder.jpg",&objects.rocktextureptr,1,0);
                LoadTexture(":Data:Textures:grassbox.jpg",&objects.boxtextureptr,1,0);
 
-               if(ambientsound){
-                       PlayStreamEx( stream_wind, strm[stream_wind], NULL, true);
-                       OPENAL_SetPaused(channels[stream_wind], false);
-                       OPENAL_SetVolume(channels[stream_wind], 100);
-               }
+               if(ambientsound)
+                 emit_stream_np(stream_wind, 100.);
 
-               OPENAL_Sample_Free(samp[footstepsound]);
-               OPENAL_Sample_Free(samp[footstepsound2]);
-               OPENAL_Sample_Free(samp[footstepsound3]);
-               OPENAL_Sample_Free(samp[footstepsound4]);
-               samp[footstepsound] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepgrass1.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound2] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepgrass2.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound3] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepstone1.ogg"), OPENAL_HW3D, 0, 0);
-               samp[footstepsound4] = OPENAL_Sample_Load(OPENAL_FREE, ConvertFileName(":Data:Sounds:footstepstone2.ogg"), OPENAL_HW3D, 0, 0);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound2], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound3], 4.0f, 1000.0f);
-               OPENAL_Sample_SetMinMaxDistance(samp[footstepsound4], 4.0f, 1000.0f);
+               footstepsound = footstepgr1;
+               footstepsound2 = footstepgr2;
+               footstepsound3 = footstepst1;
+               footstepsound4 = footstepst2;
 
                LoadTexture(":Data:Textures:grassdirt.jpg",&terraintexture,1,0);
 
@@ -1756,9 +1405,7 @@ void      Game::Setenvironment(int which)
                        ":Data:Textures:Skybox(grass):Back.jpg",
                        ":Data:Textures:Skybox(grass):Right.jpg",
                        ":Data:Textures:Skybox(grass):Up.jpg",
-                       ":Data:Textures:Skybox(grass):Down.jpg",
-                       ":Data:Textures:Skybox(grass):Cloud.jpg",
-                       ":Data:Textures:Skybox(grass):Reflect.jpg");
+                       ":Data:Textures:Skybox(grass):Down.jpg");
 
 
 
@@ -1774,55 +1421,31 @@ void    Game::Setenvironment(int which)
 
 void   Game::Loadlevel(int which){
        stealthloading=0;
-
-       if(which==0)Loadlevel((char *)":Data:Maps:map1");
-       else if(which==1)Loadlevel((char *)":Data:Maps:map2");
-       else if(which==2)Loadlevel((char *)":Data:Maps:map3");
-       else if(which==3)Loadlevel((char *)":Data:Maps:map4");
-       else if(which==4)Loadlevel((char *)":Data:Maps:map5");
-       else if(which==5)Loadlevel((char *)":Data:Maps:map6");
-       else if(which==6)Loadlevel((char *)":Data:Maps:map7");
-       else if(which==7)Loadlevel((char *)":Data:Maps:map8");
-       else if(which==8)Loadlevel((char *)":Data:Maps:map9");
-       else if(which==9)Loadlevel((char *)":Data:Maps:map10");
-       else if(which==10)Loadlevel((char *)":Data:Maps:map11");
-       else if(which==11)Loadlevel((char *)":Data:Maps:map12");
-       else if(which==12)Loadlevel((char *)":Data:Maps:map13");
-       else if(which==13)Loadlevel((char *)":Data:Maps:map14");
-       else if(which==14)Loadlevel((char *)":Data:Maps:map15");
-       else if(which==15)Loadlevel((char *)":Data:Maps:map16");
-       else if(which==-1){tutoriallevel=-1;Loadlevel((char *)":Data:Maps:tutorial");}
-       else Loadlevel((char *)":Data:Maps:mapsave");
-
        whichlevel=which;
-}
-
-/*char * Game::MD5_string (unsigned char *string){
-char temp[50];
-char temp2[100];
-
-strcpy(temp2,(const char *)string);
-strcat((char *)temp2,(const char *)"Lugaru");
-sprintf (temp, "%d",strlen((char *)temp2));
-strcat((char *)temp2,temp);
-
-MD5 context;
-unsigned int len = strlen ( (char *)temp2);
-
-context.update   ((unsigned char *)temp2, len);
-context.finalize ();
-
-return context.hex_digest();
-}*/
-
 
+       if (which == -1)
+         {
+           tutoriallevel = -1;
+           Loadlevel("tutorial");
+         }
+       else if (which >= 0 && which <= 15)
+         {
+           char buf[32];
+           snprintf(buf, 32, "map%d", which + 1);
+           Loadlevel(buf);
+         }
+       else
+         Loadlevel("mapsave");
+}
 
-void   Game::Loadlevel(char *name){
+void   Game::Loadlevel(const char *name){
        int i,j,k,l,m;
        static int oldlevel;
        int templength;
        float lamefloat;
        int lameint;
+       static const char *pfx = ":Data:Maps:";
+       char *buf;
 
        float headprop,legprop,armprop,bodyprop;
 
@@ -1851,18 +1474,20 @@ void    Game::Loadlevel(char *name){
        if(!firstload){
                oldlevel=50;
        }
-       OPENAL_SetPaused(channels[whooshsound], true);
-       OPENAL_SetPaused(channels[stream_firesound], true);
+       pause_sound(whooshsound);
+       pause_sound(stream_firesound);
 
        // Change the map filename into something that is os specific
-       char *FixedFN = ConvertFileName(name);
+       buf = (char*) alloca(strlen(pfx) + strlen(name) + 1);
+       sprintf(buf, "%s%s", pfx, name);
+       const char *FixedFN = ConvertFileName(buf);
 
        int mapvers;
        FILE                    *tfile;
        tfile=fopen( FixedFN, "rb" );
        if(tfile)
        {
-               OPENAL_SetPaused(channels[stream_firesound], true);
+               pause_sound(stream_firesound);
 
 
                scoreadded=0;
@@ -1873,7 +1498,7 @@ void      Game::Loadlevel(char *name){
                won=0;
 
                //campaign=0;
-               animation[bounceidleanim].Load((char *)":Data:Animations:Idle",middleheight,neutral);
+               animation[bounceidleanim].Load((char *)"Idle",middleheight,neutral);
 
                numdialogues=0;
 
@@ -1888,7 +1513,7 @@ void      Game::Loadlevel(char *name){
                damagedealt=0;
                damagetaken=0;
 
-               if(accountactive!=-1)difficulty=accountdifficulty[accountactive];
+               if(accountactive)difficulty=accountactive->getDifficulty();
 
                if(difficulty!=2)minimap=1;
                else minimap=0;
@@ -1933,9 +1558,7 @@ void      Game::Loadlevel(char *name){
                changedelay=0;
                if(console)
                {
-                       PlaySoundEx( consolesuccesssound, samp[consolesuccesssound], NULL, true);
-                       OPENAL_SetVolume(channels[consolesuccesssound], 256);
-                       OPENAL_SetPaused(channels[consolesuccesssound], false);
+                       emit_sound_np(consolesuccesssound);
                        freeze=0;
                        console=0;
                }
@@ -1943,7 +1566,7 @@ void      Game::Loadlevel(char *name){
                if(!stealthloading)
                {
                        terrain.numdecals=0;
-                       sprites.numsprites=0;
+                       Sprite::deleteSprites();
                        for(i=0;i<objects.numobjects;i++)
                        {
                                objects.model[i].numdecals=0;
@@ -2029,21 +1652,6 @@ void     Game::Loadlevel(char *name){
                        player[0].creature=rabbittype;
                }
 
-               for(i=0;i<max_dialogues;i++)
-               {
-                       for(j=0;j<max_dialoguelength;j++)
-                       {
-                               for(k=0;k<128;k++)
-                               {
-                                       dialoguetext[i][j][k]='\0';
-                               }
-                               for(k=0;k<64;k++)
-                               {
-                                       dialoguename[i][j][k]='\0';
-                               }
-                       }
-               }
-
                player[0].lastattack=-1;
                player[0].lastattack2=-1;
                player[0].lastattack3=-1;
@@ -2080,6 +1688,7 @@ void      Game::Loadlevel(char *name){
                                                                funpackf(tfile, "Bb", &dialoguetext[k][l][m]);
                                                                if(dialoguetext[k][l][m]=='\0')break;
                                                        }
+                                                       dialoguetext[k][l][m] = 0;
 
                                                        funpackf(tfile, "Bi",&templength);
                                                        if(templength>64||templength<=0)templength=64;
@@ -2089,6 +1698,7 @@ void      Game::Loadlevel(char *name){
                                                                        break;
                                                                }
                                                        }
+                                                       dialoguename[k][l][m] = 0;
                                                        funpackf(tfile, "Bf Bf Bf", &dialoguecamera[k][l].x, &dialoguecamera[k][l].y, &dialoguecamera[k][l].z);
                                                        funpackf(tfile, "Bi", &participantfocus[k][l]);
                                                        funpackf(tfile, "Bi", &participantaction[k][l]);
@@ -2368,7 +1978,7 @@ void      Game::Loadlevel(char *name){
                                        tintb=player[i].clothestintb[j];
                                        AddClothes((char *)player[i].clothes[j],0,1,&player[i].skeleton.skinText[0],&player[i].skeleton.skinsize);
                                }
-                               player[i].DoMipmaps(5,0,0,player[i].skeleton.skinsize,player[i].skeleton.skinsize);
+                               player[i].DoMipmaps();
                        }
 
                        player[i].currentanimation=bounceidleanim;
@@ -2439,7 +2049,7 @@ void      Game::Loadlevel(char *name){
                                player[i].proportionlegs.z=0;
                        }
 
-                       player[i].tempanimation.Load((char *)":Data:Animations:Tempanim",0,0);
+                       player[i].tempanimation.Load((char *)"Tempanim",0,0);
 
                        player[i].headmorphness=0;
                        player[i].targetheadmorphness=1;
@@ -2532,62 +2142,30 @@ void    Game::Loadlevel(char *name){
                        weapons.position[i]=-1000;
                        weapons.tippoint[i]=-1000;
                }
-
-/*             for(i=0;i<32;i++){
-                       //if(i<16||i>20)
-                       OPENAL_StopSound(i);
-               }
-*/
+               
                LOG("Starting background music...");
 
                OPENAL_StopSound(OPENAL_ALL);
                if(environment==snowyenvironment)
                {
                        if(ambientsound)
-                       {
-                               PlayStreamEx(stream_wind, strm[stream_wind], NULL, true);
-                               OPENAL_SetPaused(channels[stream_wind], false);
-                               OPENAL_SetVolume(channels[stream_wind], 256);
-                       }
+                         emit_stream_np(stream_wind);
                }
                else if(environment==desertenvironment)
                {
                        if(ambientsound)
-                       {
-                               //PlaySoundEx(desertambient,
-                               //      samp[desertambient], NULL, true);
-                               PlayStreamEx(stream_desertambient,
-                                       strm[stream_desertambient], NULL, true);
-                               OPENAL_SetPaused(channels[stream_desertambient], false);
-                               OPENAL_SetVolume(channels[stream_desertambient], 256);
-                       }
+                         emit_stream_np(stream_desertambient);
                }
                else if(environment==grassyenvironment)
                {
                        if(ambientsound)
-                       {
-                               //PlaySoundEx(wind, samp[wind], NULL, true);
-                               PlayStreamEx(stream_wind, strm[stream_wind], NULL, true);
-                               OPENAL_SetPaused(channels[stream_wind], false);
-                               OPENAL_SetVolume(channels[stream_wind], 100);
-                       }
+                         emit_stream_np(stream_wind, 100.);
                }
                oldmusicvolume[0]=0;
                oldmusicvolume[1]=0;
                oldmusicvolume[2]=0;
                oldmusicvolume[3]=0;
 
-
-               /*LoadTexture(":Data:Textures:cloud.png",&sprites.cloudtexture,1,1);
-               LoadTexture(":Data:Textures:cloudimpact.png",&sprites.cloudimpacttexture,1,1);
-               LoadTexture(":Data:Textures:bloodparticle.png",&sprites.bloodtexture,1,1);
-               LoadTexture(":Data:Textures:snowflake.png",&sprites.snowflaketexture,1,1);
-               LoadTexture(":Data:Textures:flame.png",&sprites.flametexture,1,1);
-               LoadTexture(":Data:Textures:bloodflame.png",&sprites.bloodflametexture,1,1);
-               LoadTexture(":Data:Textures:smoke.png",&sprites.smoketexture,1,1);
-               LoadTexture(":Data:Textures:shine.png",&sprites.shinetexture,1,0);
-               */
-
                if(!firstload)
                {
                        firstload=1;
@@ -2621,16 +2199,10 @@ void    Game::Tick()
                displaytime[i]+=multiplier;
        }
 
-       static unsigned char    theKeyMap[16];
-       GetKeys( theKeyMap );
-
        keyboardfrozen=0;
 
-
-       static bool mainmenutogglekeydown;
-
-       if (IsKeyDown(theKeyMap, MAC_F6_KEY) && !freezetogglekeydown) {
-               if (IsKeyDown(theKeyMap, MAC_SHIFT_KEY)) {
+       if (Input::isKeyDown(SDLK_F6) && !freezetogglekeydown) {
+               if (Input::isKeyDown(SDLK_LSHIFT)) {
                        stereoreverse=true;
                } else {
                        stereoreverse=false;
@@ -2644,8 +2216,8 @@ void      Game::Tick()
                freezetogglekeydown=1;
        }
 
-       if (IsKeyDown(theKeyMap, MAC_F7_KEY)) {
-               if (IsKeyDown(theKeyMap, MAC_SHIFT_KEY)) {
+       if (Input::isKeyDown(SDLK_F7)) {
+               if (Input::isKeyDown(SDLK_LSHIFT)) {
                        stereoseparation -= 0.001;
                } else {
                        stereoseparation -= 0.010;
@@ -2654,8 +2226,8 @@ void      Game::Tick()
                printf("Stereo decreased increased to %f\n", stereoseparation);
        }
 
-       if (IsKeyDown(theKeyMap, MAC_F8_KEY)) {
-               if (IsKeyDown(theKeyMap, MAC_SHIFT_KEY)) {
+       if (Input::isKeyDown(SDLK_F8)) {
+               if (Input::isKeyDown(SDLK_LSHIFT)) {
                        stereoseparation += 0.001;
                } else {
                        stereoseparation += 0.010;
@@ -2667,140 +2239,34 @@ void   Game::Tick()
 
        if(!console){
                if(mainmenu&&endgame==1)mainmenu=10;
-               if(IsKeyDown(theKeyMap, MAC_ESCAPE_KEY)&&!mainmenutogglekeydown&&(mainmenu==7&&entername)){
-                       for(j=0;j<255;j++){
-                               displaytext[0][j]=' ';
-                       }
-                       displaychars[0]=0;
-                       displayselected=0;
-                       entername=0;
-                       mainmenutogglekeydown=1;
-               }
-               if((IsKeyDown(theKeyMap, MAC_ESCAPE_KEY)||(mainmenu==0&&((IsKeyDown(theKeyMap, jumpkey)||IsKeyDown(theKeyMap, MAC_SPACE_KEY)||(campaign)))&&!oldjumpkeydown&&campaign&&winfreeze))&&!mainmenutogglekeydown&&(!mainmenu||gameon||mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||(mainmenu==7&&!entername)||mainmenu==9||mainmenu==11||mainmenu==13||mainmenu==17||mainmenu==10)){
+               if( (Input::isKeyDown(SDLK_ESCAPE)||(mainmenu==0&&((Input::isKeyDown(jumpkey)||Input::isKeyDown(SDLK_SPACE)||(campaign)))&&!oldjumpkeydown&&campaign&&winfreeze))
+                   && !mainmenutogglekeydown
+                   && (!mainmenu||gameon||mainmenu==3||mainmenu==4||mainmenu==5||mainmenu==6||(mainmenu==7&&!entername)||mainmenu==9||mainmenu==10)
+                 ) { // go back
                        selected=-1;
                        if(mainmenu==1||mainmenu==2||mainmenu==0){
                                if(mainmenu==0&&!winfreeze)mainmenu=2;
                                else if(mainmenu==0&&winfreeze&&(campaignchoosenext[campaignchoicewhich[whichchoice]])==1)mainmenu=100;
                                else if(mainmenu==0&&winfreeze){
-                                       /*      if(campaignchoosenext[campaignchoicewhich[whichchoice]]==2)
-                                       stealthloading=1;
-                                       else stealthloading=0;
-
-                                       if(!stealthloading){
-                                       float gLoc[3]={0,0,0};
-                                       float vel[3]={0,0,0};
-                                       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                       PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                       OPENAL_SetVolume(channels[firestartsound], 256);
-                                       OPENAL_SetPaused(channels[firestartsound], false);
-                                       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                       flashr=1;
-                                       flashg=0;
-                                       flashb=0;
-                                       flashamount=1;
-                                       flashdelay=1;
-                                       }
-
-                                       startbonustotal=0;
-
-                                       for(i=0;i<campaignnumlevels;i++){
-                                       levelvisible[i]=0;
-                                       levelhighlight[i]=0;
-                                       }
-
-                                       levelorder[0]=0;
-                                       levelvisible[0]=1;
-                                       if(accountcampaignchoicesmade[accountactive])
-                                       for(i=0;i<accountcampaignchoicesmade[accountactive];i++){
-                                       levelorder[i+1]=campaignnextlevel[levelorder[i]][accountcampaignchoices[accountactive][i]];
-                                       levelvisible[levelorder[i+1]]=1;
-                                       }
-                                       int whichlevelstart;
-                                       whichlevelstart=accountcampaignchoicesmade[accountactive]-1;
-                                       if(whichlevelstart<0){
-                                       campaignchoicenum=1;
-                                       campaignchoicewhich[0]=0;
-                                       }
-                                       else
-                                       {
-                                       campaignchoicenum=campaignnumnext[levelorder[whichlevelstart]];
-                                       if(campaignchoicenum)
-                                       for(i=0;i<campaignchoicenum;i++){
-                                       campaignchoicewhich[i]=campaignnextlevel[levelorder[whichlevelstart]][i];
-                                       levelvisible[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
-                                       levelhighlight[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
-                                       }
-                                       }
-
-                                       loading=2;
-                                       loadtime=0;
-                                       targetlevel=7;
-                                       if(firstload)TickOnceAfter();
-                                       if(!firstload)LoadStuff();
-                                       //else {
-                                       for(i=0;i<255;i++){
-                                       mapname[i]='\0';
-                                       }
-                                       mapname[0]=':';
-                                       mapname[1]='D';
-                                       mapname[2]='a';
-                                       mapname[3]='t';
-                                       mapname[4]='a';
-                                       mapname[5]=':';
-                                       mapname[6]='M';
-                                       mapname[7]='a';
-                                       mapname[8]='p';
-                                       mapname[9]='s';
-                                       mapname[10]=':';
-
-                                       //accountcampaignchoices[accountactive][accountcampaignchoicesmade[accountactive]]=whichchoice;
-                                       //accountcampaignchoicesmade[accountactive]++;
-
-
-                                       strcat(mapname,campaignmapname[campaignchoicewhich[0]]);
-                                       whichchoice=0;
-                                       visibleloading=1;
-                                       stillloading=1;
-                                       Loadlevel(mapname);
-                                       campaign=1;
-                                       mainmenu=0;
-                                       gameon=1;
-                                       OPENAL_SetPaused(channels[music3], true);
-
-                                       stealthloading=0;*/
+                                       
                                }
                                else if(mainmenu==1||mainmenu==2)mainmenu=0;
                                if(mainmenu&&musictoggle){
                                        if(mainmenu==1||mainmenu==2||mainmenu==100){
                                                OPENAL_SetFrequency(OPENAL_ALL, 0.001);
-                                               PlayStreamEx( stream_music3, strm[stream_music3], NULL, true);
-                                               OPENAL_SetPaused(channels[stream_music3], false);
-                                               OPENAL_SetVolume(channels[stream_music3], 256);
-                                               OPENAL_SetPaused(channels[music1], true);
+                                               emit_stream_np(stream_music3);
+                                               pause_sound(music1);
                                        }
                                }
                                if(!mainmenu){
-                                       OPENAL_SetPaused(channels[stream_music3], true);
-                                       OPENAL_SetPaused(channels[music1], false);
+                                       pause_sound(stream_music3);
+                                       resume_stream(music1);
                                }
                        }
                        if(mainmenu==3){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                               fireSound();
+
+                               flash();
 
                                if(newdetail>2)newdetail=detail;
                                if(newdetail<0)newdetail=detail;
@@ -2809,21 +2275,10 @@ void    Game::Tick()
 
                                SaveSettings(*this);
                        }
-                       if(mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==9||mainmenu==13||mainmenu==10||mainmenu==11||mainmenu==100){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(mainmenu==4||mainmenu==5||mainmenu==6||mainmenu==7||mainmenu==9||mainmenu==10||mainmenu==100){
+                               fireSound();
+
+                               flash();
                        }
                        if(mainmenu==3&&gameon)mainmenu=2;
                        if(mainmenu==3&&!gameon)mainmenu=1;
@@ -2833,8 +2288,6 @@ void      Game::Tick()
                        if(mainmenu==6)mainmenu=5;
                        if(mainmenu==7)mainmenu=1;
                        if(mainmenu==9)mainmenu=5;
-                       if(mainmenu==11)mainmenu=5;
-                       if(mainmenu==13)mainmenu=12;
                        if(mainmenu==10)mainmenu=5;
                        if(mainmenu==100){
                                mainmenu=5;
@@ -2843,95 +2296,52 @@ void    Game::Tick()
                        }
                        mainmenutogglekeydown=1;
                }
-               if(!IsKeyDown(theKeyMap, MAC_ESCAPE_KEY)){
+               if(!Input::isKeyDown(SDLK_ESCAPE)){
                        mainmenutogglekeydown=0;
                }
        }
 
-       /*static bool minimaptogglekeydown;
-       if(IsKeyDown(theKeyMap, MAC_TAB_KEY)&&!minimaptogglekeydown){
-       minimap=1-minimap;
-       minimaptogglekeydown=1;
-       }
-       if(!IsKeyDown(theKeyMap, MAC_TAB_KEY)){
-       minimaptogglekeydown=0;
-       }
-       */
-
        static bool minimaptogglekeydown;
-       if(IsKeyDown(theKeyMap, MAC_TAB_KEY)&&!minimaptogglekeydown&&tutoriallevel){
+       if(Input::isKeyDown(SDLK_TAB)&&!minimaptogglekeydown&&tutoriallevel){
                if(tutorialstage!=51)
                        tutorialstagetime=tutorialmaxtime;
-               PlaySoundEx( consolefailsound, samp[consolefailsound], NULL, true);
-               OPENAL_SetVolume(channels[consolefailsound], 128);
-               OPENAL_SetPaused(channels[consolefailsound], false);
+               emit_sound_np(consolefailsound, 128.);
                minimaptogglekeydown=1;
        }
-       if(!IsKeyDown(theKeyMap, MAC_TAB_KEY)){
+       if(!Input::isKeyDown(SDLK_TAB)){
                minimaptogglekeydown=0;
        }
 
        if(mainmenu){
                //menu buttons
                if(mainmenu==1||mainmenu==2){
-                       if(Button()&&!oldbutton&&selected==1){
+                       if(Input::Button()&&!oldbutton&&selected==1){
                                if(!gameon){
-                                       float gLoc[3]={0,0,0};
-                                       float vel[3]={0,0,0};
-                                       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                       PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                       OPENAL_SetVolume(channels[firestartsound], 256);
-                                       OPENAL_SetPaused(channels[firestartsound], false);
-                                       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                       flashr=1;
-                                       flashg=0;
-                                       flashb=0;
-                                       flashamount=1;
-                                       flashdelay=1;
+                                       fireSound(firestartsound);
 
-                                       //new game
-                                       if(accountactive!=-1)mainmenu=5;
-                                       else mainmenu=7;
-                                       /*
-                                       startbonustotal=0;
+                                       flash();
 
-                                       loading=2;
-                                       loadtime=0;
-                                       if(firstload)TickOnceAfter();
-                                       if(!firstload)LoadStuff();
-                                       else {
-                                       Loadlevel(0);
+                                       //new game
+                                       if(accountactive) {
+                                               mainmenu=5;
+                                       } else {
+                                               mainmenu=7;
                                        }
-                                       mainmenu=0;
-                                       gameon=1;
-                                       OPENAL_SetPaused(channels[music3], true);       */
+                                       selected=-1;
                                }
                                else
                                {
                                        //resume
                                        mainmenu=0;
-                                       OPENAL_SetPaused(channels[stream_music3], true);
-                                       OPENAL_SetPaused(channels[music1], false);
+                                       pause_sound(stream_music3);
+                                       resume_stream(music1);
                                }
                        }
 
-                       if(Button()&&!oldbutton&&selected==2){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==2){
+                               fireSound();
+
+                               flash();
 
                                //options
 
@@ -2945,26 +2355,15 @@ void    Game::Tick()
                                if(newscreenheight<0)newscreenheight=screenheight;
                        }
 
-                       if(Button()&&!oldbutton&&selected==3){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==3){
+                               fireSound();
+
+                               flash();
 
                                if(!gameon){
                                        //quit
                                        tryquit=1;
-                                       OPENAL_SetPaused(channels[stream_music3], true);
+                                       pause_sound(stream_music3);
                                }
                                else{
                                        //end game
@@ -2972,22 +2371,12 @@ void    Game::Tick()
                                        mainmenu=1;
                                }
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
-
                if(mainmenu==3){
-                       if(Button()&&!oldbutton&&selected!=-1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
+                       if(Input::Button()&&!oldbutton&&selected!=-1){
+                               fireSound();
                        }
-                       if(Button()&&!oldbutton&&selected==0){
+                       if(Input::Button()&&!oldbutton&&selected==0){
                        
                                extern SDL_Rect **resolutions;
                                bool isCustomResolution = true;
@@ -3035,31 +2424,31 @@ void    Game::Tick()
 
                                
                        }
-                       if(Button()&&!oldbutton&&selected==1){
+                       if(Input::Button()&&!oldbutton&&selected==1){
                                newdetail++;
                                if(newdetail>2)newdetail=0;
                        }
-                       if(Button()&&!oldbutton&&selected==2){
+                       if(Input::Button()&&!oldbutton&&selected==2){
                                bloodtoggle++;
                                if(bloodtoggle>2)bloodtoggle=0;
                        }
-                       if(Button()&&!oldbutton&&selected==3){
+                       if(Input::Button()&&!oldbutton&&selected==3){
                                difficulty++;
                                if(difficulty>2)difficulty=0;
                        }
-                       if(Button()&&!oldbutton&&selected==4){
+                       if(Input::Button()&&!oldbutton&&selected==4){
                                ismotionblur=1-ismotionblur;
                        }
-                       if(Button()&&!oldbutton&&selected==5){
+                       if(Input::Button()&&!oldbutton&&selected==5){
                                decals=1-decals;
                        }
-                       if(Button()&&!oldbutton&&selected==6){
+                       if(Input::Button()&&!oldbutton&&selected==6){
                                musictoggle=1-musictoggle;
 
                                if(!musictoggle){
-                                       OPENAL_SetPaused(channels[music1], true);
-                                       OPENAL_SetPaused(channels[stream_music2], true);
-                                       OPENAL_SetPaused(channels[stream_music3], true);
+                                       pause_sound(music1);
+                                       pause_sound(stream_music2);
+                                       pause_sound(stream_music3);
 
                                        for(i=0;i<4;i++){
                                                oldmusicvolume[i]=0;
@@ -3067,74 +2456,46 @@ void    Game::Tick()
                                        }
                                }
 
-                               if(musictoggle){
-                                       PlayStreamEx( stream_music3, strm[stream_music3], NULL, true);
-                                       OPENAL_SetPaused(channels[stream_music3], false);
-                                       OPENAL_SetVolume(channels[stream_music3], 256);
-                               }
+                               if(musictoggle)
+                                 emit_stream_np(stream_music3);
                        }
-                       if(Button()&&!oldbutton&&selected==9){
+                       if(Input::Button()&&!oldbutton&&selected==9){
                                invertmouse=1-invertmouse;
                        }
-                       if(Button()&&!oldbutton&&selected==10){
+                       if(Input::Button()&&!oldbutton&&selected==10){
                                usermousesensitivity+=.2;
                                if(usermousesensitivity>2)usermousesensitivity=.2;
                        }
-                       if(Button()&&!oldbutton&&selected==11){
+                       if(Input::Button()&&!oldbutton&&selected==11){
                                volume+=.1f;
                                if(volume>1.0001f)volume=0;
                                OPENAL_SetSFXMasterVolume((int)(volume*255));
                        }
-                       if(Button()&&!oldbutton&&selected==7){
-                               /*float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
+                       if(Input::Button()&&!oldbutton&&selected==7){
+                               /*fireSound();
                                */
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                               flash();
 
                                //options
 
                                mainmenu=4;
+                               selected=-1;
                                keyselect=-1;
                        }
-                       if(Button() && !oldbutton && selected == 12) {
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button() && !oldbutton && selected == 12) {
+                               flash();
                                
                                newstereomode = stereomode;
                                mainmenu=18;
-                               keyselect = -1;
+                               keyselect=-1;
                        }
-                       if(Button() && !oldbutton && selected == 13) {
+                       if(Input::Button() && !oldbutton && selected == 13) {
                                showdamagebar=!showdamagebar;
                        }
-                       if(Button()&&!oldbutton&&selected==8){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==8){
+                               fireSound();
+
+                               flash();
 
                                if(newdetail>2)newdetail=detail;
                                if(newdetail<0)newdetail=detail;
@@ -3146,112 +2507,40 @@ void   Game::Tick()
                                if(mainmenu==3&&gameon)mainmenu=2;
                                if(mainmenu==3&&!gameon)mainmenu=1;
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
                if(mainmenu==4){
-                       if(Button()&&!oldbutton&&selected!=-1&&keyselect==-1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-                       }
-                       if(Button()&&!oldbutton&&selected<9&&keyselect==-1){
-                               keyselect=selected;
-                               oldbuttons[0]=1;
-                               oldbuttons[1]=1;
-                               oldbuttons[2]=1;
-                       }
-                       if(keyselect!=-1){
-                               for(i=0;i<3;i++)
-                                       if(!buttons[i]&&!oldbutton&&!Button())oldbuttons[i]=0;
-                               for(i=0;i<140;i++){
-                                       if((IsKeyDown(theKeyMap, i)||(buttons[0]&&!oldbuttons[0]&&!oldbutton)||(buttons[1]&&!oldbuttons[1]&&!oldbutton))&&keyselect!=-1){
-                                               if(i!=MAC_ESCAPE_KEY&&(strcmp(KeyToChar(i),"unknown")||(buttons[0]&&!oldbuttons[0]&&!oldbutton)||(buttons[1]&&!oldbuttons[1]&&!oldbutton))){
-                                                       float gLoc[3]={0,0,0};
-                                                       float vel[3]={0,0,0};
-                                                       OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                                                       PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[fireendsound], 256);
-                                                       OPENAL_SetPaused(channels[fireendsound], false);
-                                                       OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                                                       int keynum;
-                                                       keynum=i;
-                                                       if(buttons[0]&&!oldbuttons[0])keynum=MAC_MOUSEBUTTON1;
-                                                       if(buttons[1]&&!oldbuttons[1])keynum=MAC_MOUSEBUTTON2;
-
-
-
-                                                       if(keyselect==0)forwardkey=keynum;
-                                                       if(keyselect==1)backkey=keynum;
-                                                       if(keyselect==2)leftkey=keynum;
-                                                       if(keyselect==3)rightkey=keynum;
-                                                       if(keyselect==4)crouchkey=keynum;
-                                                       if(keyselect==5)jumpkey=keynum;
-                                                       if(keyselect==6)drawkey=keynum;
-                                                       if(keyselect==7)throwkey=keynum;
-                                                       if(keyselect==8)attackkey=keynum;
-                                                       keyselect=-1;
-                                               }
-                                       }
-                               }}
-                       if(Button()&&!oldbutton&&selected==9){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
-
-                               mainmenu=3;
-
-                               if(newdetail>2)newdetail=detail;
-                               if(newdetail<0)newdetail=detail;
-                               if(newscreenwidth>3000)newscreenwidth=screenwidth;
-                               if(newscreenwidth<0)newscreenwidth=screenwidth;
-                               if(newscreenheight>3000)newscreenheight=screenheight;
-                               if(newscreenheight<0)newscreenheight=screenheight;
+                       if(Input::Button()&&!oldbutton&&selected!=-1&&!waiting){
+                               fireSound();
+                               if(selected<9&&keyselect==-1)
+                                       keyselect=selected;
+                               if(keyselect!=-1)
+                                       setKeySelected();
+                               if(selected==9){
+                                       flash();
+
+                                       mainmenu=3;
+
+                                       if(newdetail>2)newdetail=detail;
+                                       if(newdetail<0)newdetail=detail;
+                                       if(newscreenwidth>3000)newscreenwidth=screenwidth;
+                                       if(newscreenwidth<0)newscreenwidth=screenwidth;
+                                       if(newscreenheight>3000)newscreenheight=screenheight;
+                                       if(newscreenheight<0)newscreenheight=screenheight;
+                               }
                        }
                }
 
                if(mainmenu==5){
 
                        if(endgame==2){
-                               accountcampaignchoicesmade[accountactive]=0;
-                               accountcampaignscore[accountactive]=0;
-                               accountcampaigntime[accountactive]=0;
+                               accountactive->endGame();
                                endgame=0;
                        }
 
-                       if(Button()&&!oldbutton&&selected==1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==1){
+                               fireSound();
+
+                               flash();
 
                                startbonustotal=0;
 
@@ -3266,204 +2555,65 @@ void   Game::Tick()
 
                                mainmenu=0;
                                gameon=1;
-                               OPENAL_SetPaused(channels[stream_music3], true);
+                               pause_sound(stream_music3);
                        }
-                       if(Button()&&!oldbutton&&selected-7>=accountcampaignchoicesmade[accountactive]){//selected>=7&&(selected-7<=campaignnumchoices)){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&(selected-7>=accountactive->getCampaignChoicesMade())){
+                               fireSound();
+
+                               flash();
 
                                startbonustotal=0;
 
                                loading=2;
                                loadtime=0;
                                targetlevel=7;
-                               if(firstload)TickOnceAfter();
-                               if(!firstload)LoadStuff();
-                               //else {
-                               for(i=0;i<255;i++){
-                                       mapname[i]='\0';
-                               }
-                               mapname[0]=':';
-                               mapname[1]='D';
-                               mapname[2]='a';
-                               mapname[3]='t';
-                               mapname[4]='a';
-                               mapname[5]=':';
-                               mapname[6]='M';
-                               mapname[7]='a';
-                               mapname[8]='p';
-                               mapname[9]='s';
-                               mapname[10]=':';
-                               strcat(mapname,campaignmapname[campaignchoicewhich[selected-7-accountcampaignchoicesmade[accountactive]]]);
-                               whichchoice=selected-7-accountcampaignchoicesmade[accountactive];
+                               if(firstload) TickOnceAfter();
+                               else LoadStuff();
+                               whichchoice=selected-7-accountactive->getCampaignChoicesMade();
                                visibleloading=1;
                                stillloading=1;
-                               Loadlevel(mapname);
+                               Loadlevel(campaignmapname[campaignchoicewhich[selected-7-accountactive->getCampaignChoicesMade()]]);
                                //Loadlevel(campaignmapname[levelorder[selected-7]]);
-                               //}
                                campaign=1;
                                mainmenu=0;
                                gameon=1;
-                               OPENAL_SetPaused(channels[stream_music3], true);
+                               pause_sound(stream_music3);
                        }
-                       if(Button()&&!oldbutton&&selected==4){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==4){
+                               fireSound();
+
+                               flash();
 
                                if(mainmenu==5&&gameon)mainmenu=2;
                                if(mainmenu==5&&!gameon)mainmenu=1;
                        }
-                       if(Button()&&!oldbutton&&selected==5){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==5){
+                               fireSound();
+
+                               flash();
 
                                mainmenu=7;
                        }
-                       if(Button()&&!oldbutton&&selected==3){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==3){
+                               fireSound();
+
+                               flash();
 
                                mainmenu=6;
                        }
-                       if(Button()&&!oldbutton&&selected==2){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==2){
+                               fireSound();
+
+                               flash();
 
                                mainmenu=9;
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
-               if(mainmenu==9){
-                       if(Button()&&!oldbutton&&selected<numchallengelevels&&selected>=0&&selected<=accountprogress[accountactive]){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+               else if(mainmenu==9){
+                       if(Input::Button()&&!oldbutton&&selected<numchallengelevels&&selected>=0&&selected<=accountactive->getProgress()){
+                               fireSound();
 
-                               startbonustotal=0;
-
-                               loading=2;
-                               loadtime=0;
-                               targetlevel=selected;
-                               if(firstload)TickOnceAfter();
-                               if(!firstload)LoadStuff();
-                               else {
-                                       Loadlevel(selected);
-                               }
-                               campaign=0;
-
-                               mainmenu=0;
-                               gameon=1;
-                               OPENAL_SetPaused(channels[stream_music3], true);
-                       }
-                       if(Button()&&!oldbutton&&selected==numchallengelevels){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
-
-                               mainmenu=5;
-                       }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
-               }
-               if(mainmenu==11){
-                       if(Button()&&!oldbutton&&selected<numchallengelevels&&selected>=0&&selected<=accountprogress[accountactive]){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                               flash();
 
                                startbonustotal=0;
 
@@ -3479,215 +2629,82 @@ void   Game::Tick()
 
                                mainmenu=0;
                                gameon=1;
-                               OPENAL_SetPaused(channels[stream_music3], true);
+                               pause_sound(stream_music3);
                        }
-                       if(Button()&&!oldbutton&&selected==numchallengelevels){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==numchallengelevels){
+                               fireSound();
+
+                               flash();
 
                                mainmenu=5;
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
                if(mainmenu==10){
                        endgame=2;
-                       if(Button()&&!oldbutton&&selected==3){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==3){
+                               fireSound();
+
+                               flash();
 
                                mainmenu=5;
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
 
                if(mainmenu==6){
-                       if(Button()&&!oldbutton&&selected!=-1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-                       }
-                       if(Button()&&!oldbutton&&selected==1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
-
-                               for(i=accountactive;i<numaccounts-1;i++){
-                                       accountdifficulty[i]=accountdifficulty[i+1];
-                                       accountcampaignchoicesmade[i]=accountcampaignchoicesmade[i+1];
-                                       for(j=0;j<accountcampaignchoicesmade[i+1];j++){
-                                               accountcampaignchoices[i][j]=accountcampaignchoices[i+1][j];
-                                       }
-                                       accountpoints[i]=accountpoints[i+1];
-                                       for(j=0;j<50;j++){
-                                               accounthighscore[i][j]=accounthighscore[i+1][j];
-                                               accountfasttime[i][j]=accountfasttime[i+1][j];
+                       if(Input::Button()&&!oldbutton) {
+                               if(selected>-1){
+                                       fireSound();
+                                       if(selected==1) {
+                                               flash();
+                                               accountactive = Account::destroy(accountactive);
+                                               mainmenu=7;
+                                       } else if(selected==2) {
+                                               flash();
+                                               mainmenu=5;
                                        }
-                                       for(j=0;j<60;j++){
-                                               accountunlocked[i][j]=accountunlocked[i+1][j];
-                                       }
-                                       for(j=0;j<256;j++){
-                                               accountname[i][j]=accountname[i+1][j];
-                                       }
-                                       accountcampaignhighscore[i]=accountcampaignhighscore[i+1];
-                                       accountprogress[i]=accountprogress[i+1];
-                                       accountcampaignfasttime[i]=accountcampaignfasttime[i+1];
-                                       accountcampaignscore[i]=accountcampaignscore[i+1];
-                                       accountcampaigntime[i]=accountcampaigntime[i+1];
                                }
-
-                               numaccounts--;
-                               accountactive=-1;
-
-
-                               mainmenu=7;
-                       }
-                       if(Button()&&!oldbutton&&selected==2){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
-
-                               mainmenu=5;
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
                if(mainmenu==7){
-                       if(Button()&&!oldbutton&&selected!=-1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-                       }
-                       if(Button()&&!oldbutton&&selected==0&&numaccounts<8){
-                               entername=1;
-                       }
-                       if(Button()&&!oldbutton&&selected>0&&selected<numaccounts+1){
-                               accountactive=selected-1;
-                               mainmenu=5;
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
-                       }
-                       if(Button()&&!oldbutton&&selected==numaccounts+1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
-
-                               mainmenu=1;
-
-                               for(j=0;j<255;j++){
-                                       displaytext[0][j]=' ';
+                       if(Input::Button()&&!oldbutton) {
+                               if(selected!=-1){
+                                       fireSound();
+                                       if(selected==0&&Account::getNbAccounts()<8){
+                                               entername=1;
+                                       } else if (selected<Account::getNbAccounts()+1) {
+                                               accountactive=Account::get(selected-1);
+                                               mainmenu=5;
+                                               flash();
+                                       } else if (selected==Account::getNbAccounts()+1) {
+                                               flash();
+
+                                               mainmenu=1;
+
+                                               for(j=0;j<255;j++){
+                                                       displaytext[0][j]=' ';
+                                               }
+                                               displaychars[0]=0;
+                                               displayselected=0;
+                                               entername=0;
+                                       }
                                }
-                               displaychars[0]=0;
-                               displayselected=0;
-                               entername=0;
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
                if(mainmenu==8){
-                       if(Button()&&!oldbutton&&selected!=-1){
-                               float gLoc[3]={0,0,0};
-                               float vel[3]={0,0,0};
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[firestartsound], 256);
-                               OPENAL_SetPaused(channels[firestartsound], false);
-                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                               if(selected==0)accountdifficulty[accountactive]=0;
-                               if(selected==1)accountdifficulty[accountactive]=1;
-                               if(selected==2)accountdifficulty[accountactive]=2;
+                       if(Input::Button()&&!oldbutton&&selected>-1){
+                               fireSound();
+
+                               if(selected<=2)
+                                       accountactive->setDifficulty(selected);
 
                                mainmenu=5;
 
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                               flash();
 
                        }
-                       if(Button())oldbutton=1;
-                       else oldbutton=0;
                }
-               if (mainmenu==18) {
-                       if(Button()&&!oldbutton) {
-                               printf("Button %i pressed\n", selected);
-                       }
-                       
-                       if(Button()&&!oldbutton&&selected==0) {
+               if (mainmenu==18) {                     
+                       if(Input::Button()&&!oldbutton&&selected==0) {
                                newstereomode = (StereoMode)(newstereomode + 1);
                                while(!CanInitStereo(newstereomode)) {
                                        printf("Failed to initialize mode %s (%i)\n", StereoModeName(newstereomode), newstereomode);
@@ -3698,39 +2715,32 @@ void    Game::Tick()
                                }
                        }
                        
-                       if(buttons[0]&&!oldbutton&&selected==1) {
+                       if(Input::isKeyDown(MOUSEBUTTON1)&&!oldbutton&&selected==1) {
                                stereoseparation+=0.001;
                        }
-                       if(buttons[1]&&!oldbutton&&selected==1) {
+                       if(Input::isKeyDown(MOUSEBUTTON2)&&!oldbutton&&selected==1) {
                                stereoseparation-=0.001;
                        }
 
-                       if(Button()&&!oldbutton&&selected==2) {
+                       if(Input::Button()&&!oldbutton&&selected==2) {
                                stereoreverse =! stereoreverse;
                        }
                        
-                       if(Button()&&!oldbutton&&selected==3) {
-                               flashr=1;
-                               flashg=0;
-                               flashb=0;
-                               flashamount=1;
-                               flashdelay=1;
+                       if(Input::Button()&&!oldbutton&&selected==3) {
+                               flash();
 
                                stereomode = newstereomode;
                                InitStereo(stereomode);
                                
                                mainmenu=3;
                        }
-                       
-                       if(Button() || buttons[1])oldbutton=1;
-                       else oldbutton=0;
                }
 
 
-               if(Button()||buttons[1])oldbutton=1;
+               if(Input::Button()||Input::isKeyDown(MOUSEBUTTON2))oldbutton=1;
                else oldbutton=0;
 
-               if(IsKeyDown(theKeyMap, MAC_Q_KEY)&&IsKeyDown(theKeyMap, MAC_COMMAND_KEY)){
+               if(Input::isKeyDown(SDLK_q)&&Input::isKeyDown(SDLK_LMETA)){
                        tryquit=1;
                        if(mainmenu==3){
                                if(newdetail>2)newdetail=detail;
@@ -3753,130 +2763,30 @@ void   Game::Tick()
                }
                OPENAL_SetFrequency(channels[stream_music3], 22050);
 
-               if(entername){
-                       for(i=0;i<140;i++){
-                               if(IsKeyDown(theKeyMap, i)){
-                                       togglekeydelay[i]+=multiplier;
-                                       if(togglekeydelay[i]>.4){
-                                               togglekey[i]=0;
-                                               togglekeydelay[i]=.36;
-                                       }
-                                       if(!togglekey[i]){
-                                               if(KeyToSingleChar(i)!='\0'&&displaychars[0]<60){
-                                                       for(j=255;j>=displayselected+1;j--){
-                                                               displaytext[0][j]=displaytext[0][j-1];
-                                                       }
-                                                       displaytext[0][displayselected]=KeyToSingleChar(i);
-                                                       if(IsKeyDown(theKeyMap, MAC_SHIFT_KEY))displaytext[0][displayselected]=Shift(displaytext[0][displayselected]);
-                                                       displayselected++;
-                                                       displaychars[0]++;
-                                               }
-                                               if(i==MAC_DELETE_KEY&&displayselected!=0){
-                                                       for(j=displayselected-1;j<255;j++){
-                                                               displaytext[0][j]=displaytext[0][j+1];
-                                                       }
-                                                       displaytext[0][255]=' ';
-                                                       displayselected--;
-                                                       displaychars[0]--;
-                                               }
-                                               if(i==MAC_ARROW_LEFT_KEY&&displayselected!=0){
-                                                       displayselected--;
-                                               }
-                                               if(i==MAC_ARROW_RIGHT_KEY&&displayselected<displaychars[0]){
-                                                       displayselected++;
-                                               }
-                                               if(i==MAC_RETURN_KEY&&entername){
-                                                       if(displaychars[0]){
-                                                               numaccounts++;
-                                                               strcpy(accountname[numaccounts-1],displaytext[0]);
-                                                               accountactive=numaccounts-1;
-                                                               accountdifficulty[accountactive]=1;
-                                                               accountprogress[accountactive]=0;
-                                                               accountpoints[accountactive]=0;
-                                                               accountcampaigntime[accountactive]=0;
-                                                               accountcampaignscore[accountactive]=0;
-                                                               accountcampaignfasttime[accountactive]=0;
-                                                               accountcampaignhighscore[accountactive]=0;
-                                                               for(j=0;j<50;j++){
-                                                                       accounthighscore[accountactive][j]=0;
-                                                                       accountfasttime[accountactive][j]=0;
-                                                               }
-                                                               for(j=0;j<60;j++){
-                                                                       accountunlocked[accountactive][j]=0;
-                                                               }
-                                                               accountcampaignchoicesmade[accountactive]=0;
+               if(entername) {
+                       inputText(displaytext[0],&displayselected,&displaychars[0]);
+                       if(!waiting) { // the input as finished
+                               if(displaychars[0]){ // with enter
+                                       accountactive = Account::add(string(displaytext[0]));
 
-                                                               for(j=0;j<255;j++){
-                                                                       displaytext[0][j]=' ';
-                                                               }
-                                                               displaychars[0]=0;
-                                                               displayselected=0;
-                                                               entername=0;
-
-                                                               mainmenu=8;
-
-                                                               flashr=1;
-                                                               flashg=0;
-                                                               flashb=0;
-                                                               flashamount=1;
-                                                               flashdelay=1;
-
-                                                               float gLoc[3]={0,0,0};
-                                                               float vel[3]={0,0,0};
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[firestartsound], 256);
-                                                               OPENAL_SetPaused(channels[firestartsound], false);
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                                               for(j=0;j<255;j++){
-                                                                       displaytext[0][j]=' ';
-                                                               }
-                                                               displaychars[0]=0;
-
-
-                                                               displayselected=0;
-                                                       }}
-
-                                               if(i==MAC_RETURN_KEY&&mainmenu==13){
-                                                       if(displaychars[0]){
-                                                               sprintf (registrationname, "%s", displaytext[0]);
-                                                               if(displaychars[0]<254)registrationname[displaychars[0]]='\0';
-
-                                                               mainmenu=5;
-                        
-                                                               flashr=1;
-                                                               flashg=0;
-                                                               flashb=0;
-                                                               flashamount=1;
-                                                               flashdelay=1;
-
-                                                               float gLoc[3]={0,0,0};
-                                                               float vel[3]={0,0,0};
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[firestartsound], 256);
-                                                               OPENAL_SetPaused(channels[firestartsound], false);
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                                               for(j=0;j<255;j++){
-                                                                       displaytext[0][j]=' ';
-                                                               }
-                                                               displaychars[0]=0;
-                        
-                                                               displayselected=0;
-                                                       }}
+                                       mainmenu=8;
+
+                                       flash();
+
+                                       fireSound(firestartsound);
+
+                                       for(i=0;i<255;i++){
+                                               displaytext[0][i]=' ';
                                        }
-                                       togglekey[i]=1;
-                               }
-                               else {
-                                       togglekey[i]=0;
-                                       togglekeydelay[i]=0;
+                                       displaychars[0]=0;
+
+                                       displayselected=0;
+                               } else { // with escape or empty
+                                       mainmenutogglekeydown=1;
                                }
+                               entername=0;
                        }
-
+                       
                        displayblinkdelay-=multiplier;
                        if(displayblinkdelay<=0){
                                displayblinkdelay=.3;
@@ -3889,80 +2799,33 @@ void    Game::Tick()
                if(hostile==1)hostiletime+=multiplier;
                else hostiletime=0;
                if(!winfreeze)leveltime+=multiplier;
-               if(IsKeyDown(theKeyMap, MAC_ESCAPE_KEY)){
+               if(Input::isKeyDown(SDLK_ESCAPE)){
                        chatting=0;
                        console=0;
                        freeze=0;
                        displaychars[0]=0;
                }
 
-               if(IsKeyDown(theKeyMap, chatkey)&&!chattogglekeydown&&!console&&!chatting&&debugmode){
+               if(Input::isKeyDown(chatkey)&&!chattogglekeydown&&!console&&!chatting&&debugmode){
                        chatting=1;
                        chattogglekeydown=1;
-                       togglekey[chatkey]=1;
-                       togglekeydelay[chatkey]=-20;
                }
 
-               if(!IsKeyDown(theKeyMap, chatkey)){
+               if(!Input::isKeyDown(chatkey)){
                        chattogglekeydown=0;
                }
 
                if(chatting){
-                       for(i=0;i<140;i++){
-                               if(IsKeyDown(theKeyMap, i)){
-                                       togglekeydelay[i]+=multiplier;
-                                       if(togglekeydelay[i]>.4){
-                                               togglekey[i]=0;
-                                               togglekeydelay[i]=.36;
+                       inputText(displaytext[0],&displayselected,&displaychars[0]);
+                       if(!waiting) {
+                               if(displaychars[0]){
+                                       for(int j=0;j<255;j++){
+                                               displaytext[0][j]=' ';
                                        }
-                                       if(!togglekey[i]){
-                                               if(KeyToSingleChar(i)!='\0'&&displaychars[0]<60){
-                                                       for(j=255;j>=displayselected+1;j--){
-                                                               displaytext[0][j]=displaytext[0][j-1];
-                                                       }
-                                                       displaytext[0][displayselected]=KeyToSingleChar(i);
-                                                       if(IsKeyDown(theKeyMap, MAC_SHIFT_KEY))displaytext[0][displayselected]=Shift(displaytext[0][displayselected]);
-                                                       displayselected++;
-                                                       displaychars[0]++;
-                                               }
-                                               if(i==MAC_DELETE_KEY&&displayselected!=0){
-                                                       for(j=displayselected-1;j<255;j++){
-                                                               displaytext[0][j]=displaytext[0][j+1];
-                                                       }
-                                                       displaytext[0][255]=' ';
-                                                       displayselected--;
-                                                       displaychars[0]--;
-                                               }
-                                               if(i==MAC_ARROW_LEFT_KEY&&displayselected!=0){
-                                                       displayselected--;
-                                               }
-                                               if(i==MAC_ARROW_RIGHT_KEY&&displayselected<displaychars[0]){
-                                                       displayselected++;
-                                               }
-                                               if(i==MAC_RETURN_KEY){
-                                                       if(displaychars[0]){
-                                                               /*for(j=0;j<displaychars[0];j++){
-                                                               talkname[j]=displaytext[0][j];
-                                                               }
-                                                               talkname[displaychars[0]]='\0';
-                                                               sprintf (chatname, "%s: %s",playerName,talkname);
-                                                               //NetworkSendInformation(chatname);
-                                                               */
-                                                               for(j=0;j<255;j++){
-                                                                       displaytext[0][j]=' ';
-                                                               }
-                                                               displaychars[0]=0;
-                                                               displayselected=0;
-                                                               chatting=0;
-                                                       }
-                                               }
-                                       }
-                                       togglekey[i]=1;
-                               }
-                               else {
-                                       togglekey[i]=0;
-                                       togglekeydelay[i]=0;
-                               }
+                                       displaychars[0]=0;
+                                       displayselected=0;
+                               }       
+                               chatting=0;             
                        }
 
                        displayblinkdelay-=multiplier;
@@ -3974,7 +2837,7 @@ void      Game::Tick()
 
                if(chatting)keyboardfrozen=1;
 
-               if(IsKeyDown(theKeyMap, MAC_V_KEY)&&!freezetogglekeydown&&debugmode){
+               if(Input::isKeyDown(SDLK_v)&&!freezetogglekeydown&&debugmode){
                        freeze=1-freeze;
                        if(freeze){
                                OPENAL_SetFrequency(OPENAL_ALL, 0.001);
@@ -3982,105 +2845,45 @@ void   Game::Tick()
                        freezetogglekeydown=1;
                }
 
-               if(!IsKeyDown(theKeyMap, MAC_V_KEY)&&!IsKeyDown(theKeyMap, MAC_F1_KEY)){
+               if(!Input::isKeyDown(SDLK_v)&&!Input::isKeyDown(SDLK_F1)){
                        freezetogglekeydown=0;
                }
 
-               if(IsKeyDown(theKeyMap, MAC_TILDE_KEY)&&!consoletogglekeydown&&debugmode){
+               if(Input::isKeyDown(SDLK_BACKQUOTE)&&!consoletogglekeydown&&debugmode){
                        console=1-console;
-                       if(!console)freeze=0;
                        if(console){
                                OPENAL_SetFrequency(OPENAL_ALL, 0.001);
+                       } else {
+                               freeze=0;
+                               waiting=false;
                        }
                        consoletogglekeydown=1;
                }
 
-               if(!IsKeyDown(theKeyMap, MAC_TILDE_KEY)){
+               if(!Input::isKeyDown(SDLK_BACKQUOTE)){
                        consoletogglekeydown=0;
                }
 
                if(console)freeze=1;
 
-               if(console&&!IsKeyDown(theKeyMap,MAC_COMMAND_KEY)){
-                       for(i=0;i<140;i++){
-                               if(IsKeyDown(theKeyMap, i)){
-                                       togglekeydelay[i]+=multiplier;
-                                       if(togglekeydelay[i]>.4){
-                                               togglekey[i]=0;
-                                               togglekeydelay[i]=.36;
-                                       }
-                                       if(!togglekey[i]){
-                                               if(KeyToSingleChar(i)!='\0'&&consolechars[0]<255){
-                                                       for(j=255;j>=consoleselected+1;j--){
-                                                               consoletext[0][j]=consoletext[0][j-1];
-                                                       }
-                                                       consoletext[0][consoleselected]=KeyToSingleChar(i);
-                                                       if(IsKeyDown(theKeyMap, MAC_SHIFT_KEY))consoletext[0][consoleselected]=Shift(consoletext[0][consoleselected]);
-                                                       consoleselected++;
-                                                       consolechars[0]++;
-                                               }
-                                               else if(i==MAC_ENTER_KEY){
-                                                       for(j=255;j>=consoleselected+1;j--){
-                                                               consoletext[0][j]=consoletext[0][j-1];
-                                                       }
-                                                       consoletext[0][consoleselected]='\n';
-                                                       consoleselected++;
-                                                       consolechars[0]++;
-                                               }
-                                               if(i==MAC_DELETE_KEY&&consoleselected!=0){
-                                                       for(j=consoleselected-1;j<255;j++){
-                                                               consoletext[0][j]=consoletext[0][j+1];
-                                                       }
-                                                       consoletext[0][255]=' ';
-                                                       consoleselected--;
-                                                       consolechars[0]--;
-                                               }
-                                               if(i==MAC_ARROW_UP_KEY){
-                                                       if(archiveselected<14)archiveselected++;
-                                                       for(j=0;j<255;j++){
-                                                               consolechars[0]=consolechars[archiveselected];
-                                                               consoletext[0][j]=consoletext[archiveselected][j];
-                                                               consoleselected=consolechars[0];
-                                                       }
-                                               }
-                                               if(i==MAC_ARROW_DOWN_KEY){
-                                                       if(archiveselected>0)archiveselected--;
-                                                       for(j=0;j<255;j++){
-                                                               consolechars[0]=consolechars[archiveselected];
-                                                               consoletext[0][j]=consoletext[archiveselected][j];
-                                                               consoleselected=consolechars[0];
-                                                       }
-                                               }
-                                               if(i==MAC_ARROW_LEFT_KEY&&consoleselected!=0){
-                                                       consoleselected--;
-                                               }
-                                               if(i==MAC_ARROW_RIGHT_KEY&&consoleselected<consolechars[0]){
-                                                       consoleselected++;
-                                               }
-                                               if(i==MAC_RETURN_KEY){
-                                                       archiveselected=0;
-                                                       cmd_dispatch(this, consoletext[0]);
-
-                                                       if(consolechars[0]>0){
-                                                               for(k=14;k>=1;k--){
-                                                                       for(j=0;j<255;j++){
-                                                                               consoletext[k][j]=consoletext[k-1][j];
-                                                                       }
-                                                                       consolechars[k]=consolechars[k-1];
-                                                               }
-                                                               for(j=0;j<255;j++){
-                                                                       consoletext[0][j]=' ';
-                                                               }
-                                                               consolechars[0]=0;
-                                                               consoleselected=0;
-                                                       }
+               if(console&&!Input::isKeyDown(SDLK_LMETA)){
+                       inputText(consoletext[0],&consoleselected,&consolechars[0]);
+                       if(!waiting) {
+                               archiveselected=0;
+                               cmd_dispatch(this, consoletext[0]);
+                               if(consolechars[0]>0){
+
+                                       for(k=14;k>=1;k--){
+                                               for(j=0;j<255;j++){
+                                                       consoletext[k][j]=consoletext[k-1][j];
                                                }
+                                               consolechars[k]=consolechars[k-1];
                                        }
-                                       togglekey[i]=1;
-                               }
-                               else {
-                                       togglekey[i]=0;
-                                       togglekeydelay[i]=0;
+                                       for(j=0;j<255;j++){
+                                               consoletext[0][j]=' ';
+                                       }
+                                       consolechars[0]=0;
+                                       consoleselected=0;
                                }
                        }
 
@@ -4091,7 +2894,7 @@ void      Game::Tick()
                        }
                }
 
-               if(IsKeyDown(theKeyMap, MAC_Q_KEY)&&IsKeyDown(theKeyMap, MAC_COMMAND_KEY)){
+               if(Input::isKeyDown(SDLK_q)&&Input::isKeyDown(SDLK_LMETA)){
                        tryquit=1;
                        if(mainmenu==3){
                                if(newdetail>2)newdetail=detail;
@@ -4106,27 +2909,25 @@ void    Game::Tick()
                static int oldwinfreeze;
                if(winfreeze&&!oldwinfreeze){
                        OPENAL_SetFrequency(OPENAL_ALL, 0.001);
-                       PlaySoundEx( consolesuccesssound, samp[consolesuccesssound], NULL, true);
-                       OPENAL_SetVolume(channels[consolesuccesssound], 256);
-                       OPENAL_SetPaused(channels[consolesuccesssound], false);
+                       emit_sound_np(consolesuccesssound);
                }
                if(winfreeze==0)oldwinfreeze=winfreeze;
                else oldwinfreeze++;
 
-               if((IsKeyDown(theKeyMap, jumpkey)||IsKeyDown(theKeyMap, MAC_SPACE_KEY))&&!oldjumpkeydown&&!campaign){
+               if((Input::isKeyDown(jumpkey)||Input::isKeyDown(SDLK_SPACE))&&!oldjumpkeydown&&!campaign){
                        if(winfreeze)winfreeze=0;
                        oldjumpkeydown=1;
                }
-               if((IsKeyDown(theKeyMap, MAC_ESCAPE_KEY))&&!campaign&&gameon){
+               if((Input::isKeyDown(SDLK_ESCAPE))&&!campaign&&gameon){
                        if(winfreeze){
                                mainmenu=9;
                                gameon=0;
                        }
                }
-               if((IsKeyDown(theKeyMap, jumpkey)||IsKeyDown(theKeyMap, MAC_SPACE_KEY))){
+               if((Input::isKeyDown(jumpkey)||Input::isKeyDown(SDLK_SPACE))){
                        oldjumpkeydown=1;
                }
-               if(!IsKeyDown(theKeyMap, jumpkey)&&!IsKeyDown(theKeyMap, MAC_SPACE_KEY))oldjumpkeydown=0;
+               if(!Input::isKeyDown(jumpkey)&&!Input::isKeyDown(SDLK_SPACE))oldjumpkeydown=0;
 
                if(!freeze&&!winfreeze&&!(mainmenu&&gameon)&&(gameon||!gamestarted)){
 
@@ -4164,7 +2965,7 @@ void      Game::Tick()
                                                        realdialoguetype=dialoguetype[i];
                                                        special=0;
                                                }
-                                               if((!hostile||(dialoguetype[i]>40&&dialoguetype[i]<50))&&realdialoguetype<numplayers&&realdialoguetype>0&&(dialoguegonethrough[i]==0||!special)&&(special||(IsKeyDown(theKeyMap, attackkey)&&!oldbuttondialogue))){
+                                               if((!hostile||(dialoguetype[i]>40&&dialoguetype[i]<50))&&realdialoguetype<numplayers&&realdialoguetype>0&&(dialoguegonethrough[i]==0||!special)&&(special||(Input::isKeyDown(attackkey)&&!oldbuttondialogue))){
                                                        if(findDistancefast(&player[0].coords,&player[realdialoguetype].coords)<6||player[realdialoguetype].howactive>=typedead1||(dialoguetype[i]>40&&dialoguetype[i]<50)){
                                                                whichdialogue=i;
                                                                for(j=0;j<numdialogueboxes[whichdialogue];j++){
@@ -4180,19 +2981,12 @@ void    Game::Tick()
                                                                dialoguetime=0;
                                                                dialoguegonethrough[i]++;
                                                                if(dialogueboxsound[whichdialogue][indialogue]!=0){
-                                                                       static float gLoc[3];
-                                                                       static float vel[3];
                                                                        XYZ temppos;
                                                                        temppos=player[participantfocus[whichdialogue][indialogue]].coords;
                                                                        temppos=temppos-viewer;
                                                                        Normalise(&temppos);
                                                                        temppos+=viewer;
 
-                                                                       gLoc[0]=temppos.x;
-                                                                       gLoc[1]=temppos.y;
-                                                                       gLoc[2]=temppos.z;vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
                                                                        int whichsoundplay;
                                                                        if(dialogueboxsound[whichdialogue][indialogue]==1)whichsoundplay=rabbitchitter;
                                                                        if(dialogueboxsound[whichdialogue][indialogue]==2)whichsoundplay=rabbitchitter2;
@@ -4214,12 +3008,9 @@ void     Game::Tick()
                                                                        if(dialogueboxsound[whichdialogue][indialogue]==-2)whichsoundplay=firestartsound;
                                                                        if(dialogueboxsound[whichdialogue][indialogue]==-3)whichsoundplay=consolesuccesssound;
                                                                        if(dialogueboxsound[whichdialogue][indialogue]==-4)whichsoundplay=consolefailsound;
-                                                                       PlaySoundEx( whichsoundplay, samp[whichsoundplay], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[whichsoundplay], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[whichsoundplay], 256);
-                                                                       OPENAL_SetPaused(channels[whichsoundplay], false);
+                                                                       emit_sound_at(whichsoundplay, temppos);
                                                                }
-                                                               if(IsKeyDown(theKeyMap, attackkey))oldbuttondialogue=1;
+                                                               if(Input::isKeyDown(attackkey))oldbuttondialogue=1;
                                                        }
                                                }
                                        }
@@ -4243,7 +3034,7 @@ void      Game::Tick()
                                                                hotspotsprite=DoRotation(hotspotsprite,0,0,Random()%360);
                                                                hotspotsprite=DoRotation(hotspotsprite,0,Random()%360,0);
                                                                hotspotsprite+=hotspot[i];
-                                                               sprites.MakeSprite(breathsprite, hotspotsprite, hotspotsprite*0, 1,0.5,0, 7, 0.4);
+                                                               Sprite::MakeSprite(breathsprite, hotspotsprite, hotspotsprite*0, 1,0.5,0, 7, 0.4);
                                                                hotspotvisual[i]+=0.1/hotspotsize[i]/hotspotsize[i]/hotspotsize[i];
                                                        }
                                                }
@@ -4266,44 +3057,31 @@ void    Game::Tick()
                                                }
                                                if(tutorialstage==1){
                                                        tutorialmaxtime=5;
-                                               }
-                                               if(tutorialstage==2){
+                                               } else if(tutorialstage==2){
                                                        tutorialmaxtime=2;
-                                               }
-                                               if(tutorialstage==3){
+                                               } else if(tutorialstage==3){
                                                        tutorialmaxtime=600;
-                                               }
-                                               if(tutorialstage==4){
+                                               } else if(tutorialstage==4){
                                                        tutorialmaxtime=1000;
-                                               }
-                                               if(tutorialstage==5){
+                                               } else if(tutorialstage==5){
                                                        tutorialmaxtime=600;
-                                               }
-                                               if(tutorialstage==6){
+                                               } else if(tutorialstage==6){
                                                        tutorialmaxtime=600;
-                                               }
-                                               if(tutorialstage==7){
+                                               } else if(tutorialstage==7){
                                                        tutorialmaxtime=600;
-                                               }
-                                               if(tutorialstage==8){
+                                               } else if(tutorialstage==8){
                                                        tutorialmaxtime=600;
-                                               }
-                                               if(tutorialstage==9){
+                                               } else if(tutorialstage==9){
                                                        tutorialmaxtime=600;
-                                               }
-                                               if(tutorialstage==10){
+                                               } else if(tutorialstage==10){
                                                        tutorialmaxtime=2;
-                                               }
-                                               if(tutorialstage==11){
+                                               } else if(tutorialstage==11){
                                                        tutorialmaxtime=1000;
-                                               }
-                                               if(tutorialstage==12){
+                                               } else if(tutorialstage==12){
                                                        tutorialmaxtime=1000;
-                                               }
-                                               if(tutorialstage==13){
+                                               } else if(tutorialstage==13){
                                                        tutorialmaxtime=2;
-                                               }
-                                               if(tutorialstage==14){
+                                               } else if(tutorialstage==14){
                                                        tutorialmaxtime=3;
 
                                                        XYZ temp,temp2;
@@ -4317,18 +3095,7 @@ void     Game::Tick()
 
                                                        player[1].coords=(temp+temp2)/2;
 
-                                                       float gLoc[3];
-                                                       float vel[3];
-                                                       gLoc[0]=player[1].coords.x;
-                                                       gLoc[1]=player[1].coords.y;
-                                                       gLoc[2]=player[1].coords.z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[fireendsound], 256);
-                                                       OPENAL_SetPaused(channels[fireendsound], false);
+                                                       emit_sound_at(fireendsound, player[1].coords);
 
                                                        for(i=0;i<player[1].skeleton.num_joints;i++){
                                                                if(Random()%2==0){
@@ -4336,111 +3103,86 @@ void   Game::Tick()
                                                                        if(player[1].skeleton.free)temp2=player[1].skeleton.joints[i].velocity*player[1].scale/2;
                                                                        if(!player[1].skeleton.free)temp=DoRotation(DoRotation(DoRotation(player[1].skeleton.joints[i].position,0,0,player[1].tilt),player[1].tilt2,0,0),0,player[1].rotation,0)*player[1].scale+player[1].coords;
                                                                        if(player[1].skeleton.free)temp=player[1].skeleton.joints[i].position*player[1].scale+player[1].coords;
-                                                                       sprites.MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
+                                                                       Sprite::MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
                                                                }
                                                        }
 
-                                               }
-                                               if(tutorialstage==15){
+                                               } else if(tutorialstage==15){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==16){
+                                               } else if(tutorialstage==16){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==17){
+                                               } else if(tutorialstage==17){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==18){
+                                               } else if(tutorialstage==18){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==19){
+                                               } else if(tutorialstage==19){
                                                        tutorialstage=20;
                                                        //tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==20){
+                                               } else if(tutorialstage==20){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==21){
+                                               } else if(tutorialstage==21){
                                                        tutorialmaxtime=500;
                                                        if(bonus==cannon){
                                                                bonus=Slicebonus;
                                                                againbonus=1;
                                                        }
                                                        else againbonus=0;
-                                               }
-                                               if(tutorialstage==22){
+                                               } else if(tutorialstage==22){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==23){
+                                               } else if(tutorialstage==23){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==24){
+                                               } else if(tutorialstage==24){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==25){
+                                               } else if(tutorialstage==25){
                                                        tutorialmaxtime=500;
-                                               }
-                                               if(tutorialstage==26){
+                                               } else if(tutorialstage==26){
                                                        tutorialmaxtime=2;
-                                               }
-                                               if(tutorialstage==27){
+                                               } else if(tutorialstage==27){
                                                        tutorialmaxtime=4;
                                                        reversaltrain=1;
                                                        cananger=1;
                                                        player[1].aitype=attacktypecutoff;
-                                               }
-                                               if(tutorialstage==28){
+                                               } else if(tutorialstage==28){
                                                        tutorialmaxtime=400;
-                                               }
-                                               if(tutorialstage==29){
+                                               } else if(tutorialstage==29){
                                                        tutorialmaxtime=400;
                                                        player[0].escapednum=0;
-                                               }
-                                               if(tutorialstage==30){
+                                               } else if(tutorialstage==30){
                                                        tutorialmaxtime=4;
                                                        reversaltrain=0;
                                                        cananger=0;
                                                        player[1].aitype=passivetype;
-                                               }
-                                               if(tutorialstage==31){
+                                               } else if(tutorialstage==31){
                                                        tutorialmaxtime=13;
-                                               }
-                                               if(tutorialstage==32){
+                                               } else if(tutorialstage==32){
                                                        tutorialmaxtime=8;
-                                               }
-                                               if(tutorialstage==33){
+                                               } else if(tutorialstage==33){
                                                        tutorialmaxtime=400;
                                                        cananger=1;
                                                        canattack=1;
                                                        player[1].aitype=attacktypecutoff;
-                                               }
-                                               if(tutorialstage==34){
+                                               } else if(tutorialstage==34){
                                                        tutorialmaxtime=400;
-                                               }
-                                               if(tutorialstage==35){
+                                               } else if(tutorialstage==35){
                                                        tutorialmaxtime=400;
-                                               }
-                                               if(tutorialstage==36){
+                                               } else if(tutorialstage==36){
                                                        tutorialmaxtime=2;
                                                        reversaltrain=0;
                                                        cananger=0;
                                                        player[1].aitype=passivetype;
-                                               }
-                                               if(tutorialstage==37){
+                                               } else if(tutorialstage==37){
                                                        damagedealt=0;
                                                        damagetaken=0;
                                                        tutorialmaxtime=50;
                                                        cananger=1;
                                                        canattack=1;
                                                        player[1].aitype=attacktypecutoff;
-                                               }
-                                               if(tutorialstage==38){
+                                               } else if(tutorialstage==38){
                                                        tutorialmaxtime=4;
                                                        canattack=0;
                                                        cananger=0;
                                                        player[1].aitype=passivetype;
-                                               }
-                                               if(tutorialstage==39){
+                                               } else if(tutorialstage==39){
                                                        XYZ temp,temp2;
 
                                                        temp.x=1011;
@@ -4469,20 +3211,15 @@ void    Game::Tick()
                                                        weapons.physics[weapons.numweapons]=1;
 
                                                        weapons.numweapons++;
-                                               }
-                                               if(tutorialstage==40){
+                                               } else if(tutorialstage==40){
                                                        tutorialmaxtime=300;
-                                               }
-                                               if(tutorialstage==41){
+                                               } else if(tutorialstage==41){
                                                        tutorialmaxtime=300;
-                                               }
-                                               if(tutorialstage==42){
+                                               } else if(tutorialstage==42){
                                                        tutorialmaxtime=8;
-                                               }
-                                               if(tutorialstage==43){
+                                               } else if(tutorialstage==43){
                                                        tutorialmaxtime=300;
-                                               }
-                                               if(tutorialstage==44){
+                                               } else if(tutorialstage==44){
                                                        weapons.owner[0]=1;
                                                        player[0].weaponactive=-1;
                                                        player[0].num_weapons=0;
@@ -4495,8 +3232,7 @@ void      Game::Tick()
                                                        player[1].aitype=attacktypecutoff;
 
                                                        tutorialmaxtime=300;
-                                               }
-                                               if(tutorialstage==45){
+                                               } else if(tutorialstage==45){
                                                        weapons.owner[0]=1;
                                                        player[0].weaponactive=-1;
                                                        player[0].num_weapons=0;
@@ -4505,8 +3241,7 @@ void      Game::Tick()
                                                        player[1].weaponids[0]=0;
 
                                                        tutorialmaxtime=300;
-                                               }
-                                               if(tutorialstage==46){
+                                               } else if(tutorialstage==46){
                                                        weapons.owner[0]=1;
                                                        player[0].weaponactive=-1;
                                                        player[0].num_weapons=0;
@@ -4517,9 +3252,7 @@ void      Game::Tick()
                                                        weapons.type[0]=sword;
 
                                                        tutorialmaxtime=300;
-                                               }
-
-                                               if(tutorialstage==47){
+                                               } else if(tutorialstage==47){
                                                        tutorialmaxtime=10;
 
                                                        XYZ temp,temp2;
@@ -4558,8 +3291,7 @@ void      Game::Tick()
                                                        player[1].weaponids[0]=0;
 
                                                        weapons.numweapons++;
-                                               }
-                                               if(tutorialstage==48){
+                                               } else if(tutorialstage==48){
                                                        canattack=0;
                                                        cananger=0;
                                                        player[1].aitype=passivetype;
@@ -4579,8 +3311,7 @@ void      Game::Tick()
                                                        else weapons.type[0]=staff;
 
                                                        weapons.numweapons++;
-                                               }
-                                               if(tutorialstage==49){
+                                               } else if(tutorialstage==49){
                                                        canattack=0;
                                                        cananger=0;
                                                        player[1].aitype=passivetype;
@@ -4601,23 +3332,11 @@ void    Game::Tick()
                                                        weapons.type[0]=knife;
 
                                                        weapons.numweapons++;
-                                               }
-                                               if(tutorialstage==50){
+                                               } else if(tutorialstage==50){
                                                        tutorialmaxtime=8;
 
                                                        XYZ temp,temp2;
-                                                       float gLoc[3];
-                                                       float vel[3];
-                                                       gLoc[0]=player[1].coords.x;
-                                                       gLoc[1]=player[1].coords.y;
-                                                       gLoc[2]=player[1].coords.z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[fireendsound], 256);
-                                                       OPENAL_SetPaused(channels[fireendsound], false);
+                                                       emit_sound_at(fireendsound, player[1].coords);
 
                                                        for(i=0;i<player[1].skeleton.num_joints;i++){
                                                                if(Random()%2==0){
@@ -4625,7 +3344,7 @@ void      Game::Tick()
                                                                        if(player[1].skeleton.free)temp2=player[1].skeleton.joints[i].velocity*player[1].scale/2;
                                                                        if(!player[1].skeleton.free)temp=DoRotation(DoRotation(DoRotation(player[1].skeleton.joints[i].position,0,0,player[1].tilt),player[1].tilt2,0,0),0,player[1].rotation,0)*player[1].scale+player[1].coords;
                                                                        if(player[1].skeleton.free)temp=player[1].skeleton.joints[i].position*player[1].scale+player[1].coords;
-                                                                       sprites.MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
+                                                                       Sprite::MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
                                                                }
                                                        }
 
@@ -4643,8 +3362,7 @@ void      Game::Tick()
                                                        weapons.freetime[0]=0;
                                                        weapons.firstfree[0]=1;
                                                        weapons.physics[0]=1;
-                                               }
-                                               if(tutorialstage==51){
+                                               } else if(tutorialstage==51){
                                                        tutorialmaxtime=80000;
                                                }
                                                if(tutorialstage<=51)tutorialstagetime=0;
@@ -4762,9 +3480,7 @@ void      Game::Tick()
 
 
                                                if(tutorialstagetime==tutorialmaxtime-3){
-                                                       PlaySoundEx( consolesuccesssound, samp[consolesuccesssound], NULL, true);
-                                                       OPENAL_SetVolume(channels[consolesuccesssound], 256);
-                                                       OPENAL_SetPaused(channels[consolesuccesssound], false);
+                                                       emit_sound_np(consolesuccesssound);
                                                }
 
                                                if(tutorialsuccess>=1){
@@ -4782,16 +3498,12 @@ void    Game::Tick()
 
                                        if(tutoriallevel!=1){
                                                if(bonustime==0&&bonus!=solidhit&&bonus!=spinecrusher&&bonus!=tracheotomy&&bonus!=backstab&&bonusvalue>10){
-                                                       PlaySoundEx( consolesuccesssound, samp[consolesuccesssound], NULL, true);
-                                                       OPENAL_SetVolume(channels[consolesuccesssound], 256);
-                                                       OPENAL_SetPaused(channels[consolesuccesssound], false);
+                                                       emit_sound_np(consolesuccesssound);
                                                }
                                        }
                                        else
                                                if(bonustime==0){
-                                                       PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                       OPENAL_SetVolume(channels[fireendsound], 256);
-                                                       OPENAL_SetPaused(channels[fireendsound], false);
+                                                       emit_sound_np(fireendsound);
                                                }
                                                if(bonustime==0){
                                                        if(bonus!=solidhit&&bonus!=twoxcombo&&bonus!=threexcombo&&bonus!=fourxcombo&&bonus!=megacombo)bonusnum[bonus]++;
@@ -4814,7 +3526,7 @@ void      Game::Tick()
                                                                footpoint.y+=((float)abs(Random()%1200))/100-6;
                                                                footpoint.x+=((float)abs(Random()%1200))/100-6;
                                                                footpoint.z+=((float)abs(Random()%1200))/100-6;
-                                                               sprites.MakeSprite(snowsprite, footpoint,footvel, 1,1,1, .1, 1);
+                                                               Sprite::MakeSprite(snowsprite, footpoint,footvel, 1,1,1, .1, 1);
                                                        }
                                                }
                                                for(k=0;k<numplayers;k++){
@@ -4897,19 +3609,8 @@ void     Game::Tick()
                                                                                                                        player[k].target=0;
                                                                                                                        player[k].targetanimation=walljumpleftanim;
                                                                                                                        player[k].targetframe=0;
-                                                                                                                       float gLoc[3];
-                                                                                                                       float vel[3];
-                                                                                                                       gLoc[0]=player[k].coords.x;
-                                                                                                                       gLoc[1]=player[k].coords.y;
-                                                                                                                       gLoc[2]=player[k].coords.z;
-                                                                                                                       vel[0]=0;
-                                                                                                                       vel[1]=0;
-                                                                                                                       vel[2]=0;
-                                                                                                                       PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                                                                                                                       OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                                                                                                                       OPENAL_SetVolume(channels[movewhooshsound], 256);
-                                                                                                                       OPENAL_SetPaused(channels[movewhooshsound], false);
-                                                                                                                       if(k==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                                                                       emit_sound_at(movewhooshsound, player[k].coords);
+                                                                                                                       if(k==0)pause_sound(whooshsound);
 
                                                                                                                        lowpointtarget=DoRotation(objects.model[i].facenormals[whichhit],0,objects.rotation[i],0);
                                                                                                                        player[k].rotation=-asin(0-lowpointtarget.x);
@@ -4928,19 +3629,8 @@ void     Game::Tick()
                                                                                                                                player[k].target=0;
                                                                                                                                player[k].targetanimation=walljumprightanim;
                                                                                                                                player[k].targetframe=0;
-                                                                                                                               float gLoc[3];
-                                                                                                                               float vel[3];
-                                                                                                                               gLoc[0]=player[k].coords.x;
-                                                                                                                               gLoc[1]=player[k].coords.y;
-                                                                                                                               gLoc[2]=player[k].coords.z;
-                                                                                                                               vel[0]=0;
-                                                                                                                               vel[1]=0;
-                                                                                                                               vel[2]=0;
-                                                                                                                               PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                                                                                                                               OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                                                                                                                               OPENAL_SetVolume(channels[movewhooshsound], 256);
-                                                                                                                               OPENAL_SetPaused(channels[movewhooshsound], false);
-                                                                                                                               if(k==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                                                                               emit_sound_at(movewhooshsound, player[k].coords);
+                                                                                                                               if(k==0)pause_sound(whooshsound);
 
                                                                                                                                lowpointtarget=DoRotation(objects.model[i].facenormals[whichhit],0,objects.rotation[i],0);
                                                                                                                                player[k].rotation=-asin(0-lowpointtarget.x);
@@ -4959,19 +3649,8 @@ void     Game::Tick()
                                                                                                                                        player[k].target=0;
                                                                                                                                        player[k].targetanimation=walljumpbackanim;
                                                                                                                                        player[k].targetframe=0;
-                                                                                                                                       float gLoc[3];
-                                                                                                                                       float vel[3];
-                                                                                                                                       gLoc[0]=player[k].coords.x;
-                                                                                                                                       gLoc[1]=player[k].coords.y;
-                                                                                                                                       gLoc[2]=player[k].coords.z;
-                                                                                                                                       vel[0]=0;
-                                                                                                                                       vel[1]=0;
-                                                                                                                                       vel[2]=0;
-                                                                                                                                       PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                                                                                                                                       OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                                                                                                                                       OPENAL_SetVolume(channels[movewhooshsound], 256);
-                                                                                                                                       OPENAL_SetPaused(channels[movewhooshsound], false);
-                                                                                                                                       if(k==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                                                                                       emit_sound_at(movewhooshsound, player[k].coords);
+                                                                                                                                       if(k==0)pause_sound(whooshsound);
 
                                                                                                                                        lowpointtarget=DoRotation(objects.model[i].facenormals[whichhit],0,objects.rotation[i],0);
                                                                                                                                        player[k].rotation=-asin(0-lowpointtarget.x);
@@ -4990,19 +3669,8 @@ void     Game::Tick()
                                                                                                                                                player[k].target=0;
                                                                                                                                                player[k].targetanimation=walljumpfrontanim;
                                                                                                                                                player[k].targetframe=0;
-                                                                                                                                               float gLoc[3];
-                                                                                                                                               float vel[3];
-                                                                                                                                               gLoc[0]=player[k].coords.x;
-                                                                                                                                               gLoc[1]=player[k].coords.y;
-                                                                                                                                               gLoc[2]=player[k].coords.z;
-                                                                                                                                               vel[0]=0;
-                                                                                                                                               vel[1]=0;
-                                                                                                                                               vel[2]=0;
-                                                                                                                                               PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                                                                                                                                               OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                                                                                                                                               OPENAL_SetVolume(channels[movewhooshsound], 256);
-                                                                                                                                               OPENAL_SetPaused(channels[movewhooshsound], false);
-                                                                                                                                               if(k==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                                                                                               emit_sound_at(movewhooshsound, player[k].coords);
+                                                                                                                                               if(k==0)pause_sound(whooshsound);
 
                                                                                                                                                lowpointtarget=DoRotation(objects.model[i].facenormals[whichhit],0,objects.rotation[i],0);
                                                                                                                                                player[k].rotation=-asin(0-lowpointtarget.x);
@@ -5037,25 +3705,14 @@ void    Game::Tick()
                                                                                                                player[k].onterrain=1;
 
                                                                                                                if(player[k].id==0){
-                                                                                                                       OPENAL_SetPaused(channels[whooshsound], true);
+                                                                                                                       pause_sound(whooshsound);
                                                                                                                        OPENAL_SetVolume(channels[whooshsound], 0);
                                                                                                                }
 
                                                                                                                if((player[k].targetanimation==jumpdownanim||player[k].isFlip())&&!player[k].wasLanding()){
                                                                                                                        if(player[k].isFlip())player[k].jumppower=-4;
                                                                                                                        player[k].targetanimation=player[k].getLanding();
-                                                                                                                       float gLoc[3];
-                                                                                                                       float vel[3];
-                                                                                                                       gLoc[0]=player[k].coords.x;
-                                                                                                                       gLoc[1]=player[k].coords.y;
-                                                                                                                       gLoc[2]=player[k].coords.z;
-                                                                                                                       vel[0]=player[k].velocity.x;
-                                                                                                                       vel[1]=player[k].velocity.y;
-                                                                                                                       vel[2]=player[k].velocity.z;
-                                                                                                                       PlaySoundEx( landsound, samp[landsound], NULL, true);
-                                                                                                                       OPENAL_3D_SetAttributes(channels[landsound], gLoc, vel);
-                                                                                                                       OPENAL_SetVolume(channels[landsound], 128);
-                                                                                                                       OPENAL_SetPaused(channels[landsound], false);
+                                                                                                                       emit_sound_at(landsound, player[k].coords, 128.);
                                                                                                                        if(k==0){
                                                                                                                                envsound[numenvsounds]=player[k].coords;
                                                                                                                                envsoundvol[numenvsounds]=16;
@@ -5153,20 +3810,9 @@ void     Game::Tick()
 
                                                                                                                                                                                                        if(j>10||!player[k].isRun()){
                                                                                                                                                                                                                if(player[k].targetanimation==jumpdownanim||player[k].targetanimation==jumpupanim){
-                                                                                                                                                                                                                       if(k==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                                                                                                                                                                       if(k==0)pause_sound(whooshsound);
                                                                                                                                                                                                                }
-                                                                                                                                                                                                               float gLoc[3];
-                                                                                                                                                                                                               float vel[3];
-                                                                                                                                                                                                               gLoc[0]=player[k].coords.x;
-                                                                                                                                                                                                               gLoc[1]=player[k].coords.y;
-                                                                                                                                                                                                               gLoc[2]=player[k].coords.z;
-                                                                                                                                                                                                               vel[0]=player[k].velocity.x;
-                                                                                                                                                                                                               vel[1]=player[k].velocity.y;
-                                                                                                                                                                                                               vel[2]=player[k].velocity.z;
-                                                                                                                                                                                                               PlaySoundEx( jumpsound, samp[jumpsound], NULL, true);
-                                                                                                                                                                                                               OPENAL_3D_SetAttributes(channels[jumpsound], gLoc, vel);
-                                                                                                                                                                                                               OPENAL_SetVolume(channels[jumpsound], 128);
-                                                                                                                                                                                                               OPENAL_SetPaused(channels[jumpsound], false);
+                                                                                                                                                                                                               emit_sound_at(jumpsound, player[k].coords, 128.);
 
                                                                                                                                                                                                                lowpointtarget=DoRotation(objects.model[i].facenormals[whichhit],0,objects.rotation[i],0);
                                                                                                                                                                                                                player[k].rotation=-asin(0-lowpointtarget.x);
@@ -5216,20 +3862,8 @@ void     Game::Tick()
                                                                                                                player[k].targetframe=0;
                                                                                                                player[k].target=0;
 
-                                                                                                               float gLoc[3];
-                                                                                                               float vel[3];
-                                                                                                               gLoc[0]=player[k].coords.x;
-                                                                                                               gLoc[1]=player[k].coords.y;
-                                                                                                               gLoc[2]=player[k].coords.z;
-                                                                                                               vel[0]=player[k].velocity.x;
-                                                                                                               vel[1]=player[k].velocity.y;
-                                                                                                               vel[2]=player[k].velocity.z;
-                                                                                                               if(k==0){
-                                                                                                                       PlaySoundEx( whooshsound, samp[whooshsound], NULL, true);
-                                                                                                                       OPENAL_3D_SetAttributes(channels[whooshsound], gLoc, vel);
-                                                                                                                       OPENAL_SetVolume(channels[whooshsound], 128);
-                                                                                                                       OPENAL_SetPaused(channels[whooshsound], false);
-                                                                                                               }
+                                                                                                               if(!k)
+                                                                                                                 emit_sound_at(whooshsound, player[k].coords, 128.);
                                                                                                        }
                                                                                                        player[k].velocity.y+=gravity;
                                                                                                }
@@ -5242,14 +3876,14 @@ void    Game::Tick()
                                                static XYZ oldviewer;
 
                                                if(indialogue==-1){
-                                                       player[0].forwardkeydown=IsKeyDown(theKeyMap, forwardkey);
-                                                       player[0].leftkeydown=IsKeyDown(theKeyMap, leftkey);
-                                                       player[0].backkeydown=IsKeyDown(theKeyMap, backkey);
-                                                       player[0].rightkeydown=IsKeyDown(theKeyMap, rightkey);
-                                                       player[0].jumpkeydown=IsKeyDown(theKeyMap, jumpkey);
-                                                       player[0].crouchkeydown=IsKeyDown(theKeyMap, crouchkey);
-                                                       player[0].drawkeydown=IsKeyDown(theKeyMap, drawkey);
-                                                       player[0].throwkeydown=IsKeyDown(theKeyMap, throwkey);
+                                                       player[0].forwardkeydown=Input::isKeyDown(forwardkey);
+                                                       player[0].leftkeydown=Input::isKeyDown(leftkey);
+                                                       player[0].backkeydown=Input::isKeyDown(backkey);
+                                                       player[0].rightkeydown=Input::isKeyDown(rightkey);
+                                                       player[0].jumpkeydown=Input::isKeyDown(jumpkey);
+                                                       player[0].crouchkeydown=Input::isKeyDown(crouchkey);
+                                                       player[0].drawkeydown=Input::isKeyDown(drawkey);
+                                                       player[0].throwkeydown=Input::isKeyDown(throwkey);
                                                }
                                                else
                                                {
@@ -5281,27 +3915,27 @@ void    Game::Tick()
 
                                                                flatfacing=DoRotation(flatfacing,0,-rotation,0);
 
-                                                               if(IsKeyDown(theKeyMap, forwardkey))viewer+=facing*multiplier*4;
-                                                               if(IsKeyDown(theKeyMap, backkey))viewer-=facing*multiplier*4;
-                                                               if(IsKeyDown(theKeyMap, leftkey))viewer+=DoRotation(flatfacing*multiplier,0,90,0)*4;
-                                                               if(IsKeyDown(theKeyMap, rightkey))viewer+=DoRotation(flatfacing*multiplier,0,-90,0)*4;
-                                                               if(IsKeyDown(theKeyMap, jumpkey))viewer.y+=multiplier*4;
-                                                               if(IsKeyDown(theKeyMap, crouchkey))viewer.y-=multiplier*4;
-                                                               if(!endkeydown&&(IsKeyDown(theKeyMap, MAC_1_KEY)||IsKeyDown(theKeyMap, MAC_2_KEY)||IsKeyDown(theKeyMap, MAC_3_KEY)||IsKeyDown(theKeyMap, MAC_4_KEY)||IsKeyDown(theKeyMap, MAC_5_KEY)
-                                                                       ||IsKeyDown(theKeyMap, MAC_6_KEY)||IsKeyDown(theKeyMap, MAC_7_KEY)||IsKeyDown(theKeyMap, MAC_8_KEY)||IsKeyDown(theKeyMap, MAC_9_KEY)||IsKeyDown(theKeyMap, MAC_0_KEY)
-                                                                       ||IsKeyDown(theKeyMap, MAC_MINUS_KEY))){
+                                                               if(Input::isKeyDown(forwardkey))viewer+=facing*multiplier*4;
+                                                               if(Input::isKeyDown(backkey))viewer-=facing*multiplier*4;
+                                                               if(Input::isKeyDown(leftkey))viewer+=DoRotation(flatfacing*multiplier,0,90,0)*4;
+                                                               if(Input::isKeyDown(rightkey))viewer+=DoRotation(flatfacing*multiplier,0,-90,0)*4;
+                                                               if(Input::isKeyDown(jumpkey))viewer.y+=multiplier*4;
+                                                               if(Input::isKeyDown(crouchkey))viewer.y-=multiplier*4;
+                                                               if(!endkeydown&&(Input::isKeyDown(SDLK_1)||Input::isKeyDown(SDLK_2)||Input::isKeyDown(SDLK_3)||Input::isKeyDown(SDLK_4)||Input::isKeyDown(SDLK_5)
+                                                                       ||Input::isKeyDown(SDLK_6)||Input::isKeyDown(SDLK_7)||Input::isKeyDown(SDLK_8)||Input::isKeyDown(SDLK_9)||Input::isKeyDown(SDLK_0)
+                                                                       ||Input::isKeyDown(SDLK_MINUS))){
                                                                                int whichend;
-                                                                               if(IsKeyDown(theKeyMap, MAC_1_KEY))whichend=1;
-                                                                               if(IsKeyDown(theKeyMap, MAC_2_KEY))whichend=2;
-                                                                               if(IsKeyDown(theKeyMap, MAC_3_KEY))whichend=3;
-                                                                               if(IsKeyDown(theKeyMap, MAC_4_KEY))whichend=4;
-                                                                               if(IsKeyDown(theKeyMap, MAC_5_KEY))whichend=5;
-                                                                               if(IsKeyDown(theKeyMap, MAC_6_KEY))whichend=6;
-                                                                               if(IsKeyDown(theKeyMap, MAC_7_KEY))whichend=7;
-                                                                               if(IsKeyDown(theKeyMap, MAC_8_KEY))whichend=8;
-                                                                               if(IsKeyDown(theKeyMap, MAC_9_KEY))whichend=9;
-                                                                               if(IsKeyDown(theKeyMap, MAC_0_KEY))whichend=0;
-                                                                               if(IsKeyDown(theKeyMap, MAC_MINUS_KEY))whichend=-1;
+                                                                               if(Input::isKeyDown(SDLK_1))whichend=1;
+                                                                               if(Input::isKeyDown(SDLK_2))whichend=2;
+                                                                               if(Input::isKeyDown(SDLK_3))whichend=3;
+                                                                               if(Input::isKeyDown(SDLK_4))whichend=4;
+                                                                               if(Input::isKeyDown(SDLK_5))whichend=5;
+                                                                               if(Input::isKeyDown(SDLK_6))whichend=6;
+                                                                               if(Input::isKeyDown(SDLK_7))whichend=7;
+                                                                               if(Input::isKeyDown(SDLK_8))whichend=8;
+                                                                               if(Input::isKeyDown(SDLK_9))whichend=9;
+                                                                               if(Input::isKeyDown(SDLK_0))whichend=0;
+                                                                               if(Input::isKeyDown(SDLK_MINUS))whichend=-1;
                                                                                if(whichend!=-1){
                                                                                        participantfocus[whichdialogue][indialogue]=whichend;
                                                                                        participantlocation[whichdialogue][whichend]=player[whichend].coords;
@@ -5321,19 +3955,12 @@ void    Game::Tick()
                                                                                indialogue++;
                                                                                if(indialogue<numdialogueboxes[whichdialogue]){
                                                                                        if(dialogueboxsound[whichdialogue][indialogue]!=0){
-                                                                                               static float gLoc[3];
-                                                                                               static float vel[3];
                                                                                                XYZ temppos;
                                                                                                temppos=player[participantfocus[whichdialogue][indialogue]].coords;
                                                                                                temppos=temppos-viewer;
                                                                                                Normalise(&temppos);
                                                                                                temppos+=viewer;
 
-                                                                                               gLoc[0]=temppos.x;
-                                                                                               gLoc[1]=temppos.y;
-                                                                                               gLoc[2]=temppos.z;vel[0]=0;
-                                                                                               vel[1]=0;
-                                                                                               vel[2]=0;
                                                                                                int whichsoundplay;
                                                                                                if(dialogueboxsound[whichdialogue][indialogue]==1)whichsoundplay=rabbitchitter;
                                                                                                if(dialogueboxsound[whichdialogue][indialogue]==2)whichsoundplay=rabbitchitter2;
@@ -5355,10 +3982,7 @@ void     Game::Tick()
                                                                                                if(dialogueboxsound[whichdialogue][indialogue]==-2)whichsoundplay=firestartsound;
                                                                                                if(dialogueboxsound[whichdialogue][indialogue]==-3)whichsoundplay=consolesuccesssound;
                                                                                                if(dialogueboxsound[whichdialogue][indialogue]==-4)whichsoundplay=consolefailsound;
-                                                                                               PlaySoundEx( whichsoundplay, samp[whichsoundplay], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[whichsoundplay], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[whichsoundplay], 256);
-                                                                                               OPENAL_SetPaused(channels[whichsoundplay], false);
+                                                                                               emit_sound_at(whichsoundplay, temppos);
                                                                                        }
                                                                                }
 
@@ -5368,25 +3992,25 @@ void    Game::Tick()
 
                                                                                endkeydown=1;
                                                                        }
-                                                                       if((IsKeyDown(theKeyMap, MAC_NUMPAD_1_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_2_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_3_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_4_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_5_KEY)
-                                                                               ||IsKeyDown(theKeyMap, MAC_NUMPAD_6_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_7_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_8_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_9_KEY)||IsKeyDown(theKeyMap, MAC_NUMPAD_0_KEY)
+                                                                       if((Input::isKeyDown(SDLK_KP1)||Input::isKeyDown(SDLK_KP2)||Input::isKeyDown(SDLK_KP3)||Input::isKeyDown(SDLK_KP4)||Input::isKeyDown(SDLK_KP5)
+                                                                               ||Input::isKeyDown(SDLK_KP6)||Input::isKeyDown(SDLK_KP7)||Input::isKeyDown(SDLK_KP8)||Input::isKeyDown(SDLK_KP9)||Input::isKeyDown(SDLK_KP0)
                                                                                )){
                                                                                        int whichend;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_1_KEY))whichend=1;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_2_KEY))whichend=2;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_3_KEY))whichend=3;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_4_KEY))whichend=4;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_5_KEY))whichend=5;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_6_KEY))whichend=6;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_7_KEY))whichend=7;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_8_KEY))whichend=8;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_9_KEY))whichend=9;
-                                                                                       if(IsKeyDown(theKeyMap, MAC_NUMPAD_0_KEY))whichend=0;
+                                                                                       if(Input::isKeyDown(SDLK_KP1))whichend=1;
+                                                                                       if(Input::isKeyDown(SDLK_KP2))whichend=2;
+                                                                                       if(Input::isKeyDown(SDLK_KP3))whichend=3;
+                                                                                       if(Input::isKeyDown(SDLK_KP4))whichend=4;
+                                                                                       if(Input::isKeyDown(SDLK_KP5))whichend=5;
+                                                                                       if(Input::isKeyDown(SDLK_KP6))whichend=6;
+                                                                                       if(Input::isKeyDown(SDLK_KP7))whichend=7;
+                                                                                       if(Input::isKeyDown(SDLK_KP8))whichend=8;
+                                                                                       if(Input::isKeyDown(SDLK_KP9))whichend=9;
+                                                                                       if(Input::isKeyDown(SDLK_KP0))whichend=0;
                                                                                        participantfacing[whichdialogue][indialogue][whichend]=facing;
                                                                                }
-                                                                               if(!IsKeyDown(theKeyMap, MAC_1_KEY)&&!IsKeyDown(theKeyMap, MAC_2_KEY)&&!IsKeyDown(theKeyMap, MAC_3_KEY)&&!IsKeyDown(theKeyMap, MAC_4_KEY)&&!IsKeyDown(theKeyMap, MAC_5_KEY)
-                                                                                       &&!IsKeyDown(theKeyMap, MAC_6_KEY)&&!IsKeyDown(theKeyMap, MAC_7_KEY)&&!IsKeyDown(theKeyMap, MAC_8_KEY)&&!IsKeyDown(theKeyMap, MAC_9_KEY)&&!IsKeyDown(theKeyMap, MAC_0_KEY)
-                                                                                       &&!IsKeyDown(theKeyMap, MAC_MINUS_KEY)){
+                                                                               if(!Input::isKeyDown(SDLK_1)&&!Input::isKeyDown(SDLK_2)&&!Input::isKeyDown(SDLK_3)&&!Input::isKeyDown(SDLK_4)&&!Input::isKeyDown(SDLK_5)
+                                                                                       &&!Input::isKeyDown(SDLK_6)&&!Input::isKeyDown(SDLK_7)&&!Input::isKeyDown(SDLK_8)&&!Input::isKeyDown(SDLK_9)&&!Input::isKeyDown(SDLK_0)
+                                                                                       &&!Input::isKeyDown(SDLK_MINUS)){
                                                                                                endkeydown=0;
                                                                                        }
                                                                                        if(indialogue>=numdialogueboxes[whichdialogue]){
@@ -5396,7 +4020,7 @@ void      Game::Tick()
                                                                                        }
                                                        }
                                                        if(!directing){
-                                                               OPENAL_SetPaused(channels[whooshsound], true);
+                                                               pause_sound(whooshsound);
                                                                viewer=dialoguecamera[whichdialogue][indialogue];
                                                                if(viewer.y<terrain.getHeight(viewer.x,viewer.z)+.1){
                                                                        viewer.y=terrain.getHeight(viewer.x,viewer.z)+.1;
@@ -5404,26 +4028,19 @@ void    Game::Tick()
                                                                rotation=dialoguecamerarotation[whichdialogue][indialogue];
                                                                rotation2=dialoguecamerarotation2[whichdialogue][indialogue];
                                                                if(dialoguetime>0.5)
-                                                                       if((!endkeydown&&(IsKeyDown(theKeyMap, MAC_1_KEY)||IsKeyDown(theKeyMap, MAC_2_KEY)||IsKeyDown(theKeyMap, MAC_3_KEY)||IsKeyDown(theKeyMap, MAC_4_KEY)||IsKeyDown(theKeyMap, MAC_5_KEY)
-                                                                               ||IsKeyDown(theKeyMap, MAC_6_KEY)||IsKeyDown(theKeyMap, MAC_7_KEY)||IsKeyDown(theKeyMap, MAC_8_KEY)||IsKeyDown(theKeyMap, MAC_9_KEY)||IsKeyDown(theKeyMap, MAC_0_KEY)
-                                                                               ||IsKeyDown(theKeyMap, MAC_MINUS_KEY)))||(IsKeyDown(theKeyMap, attackkey)&&!oldbuttondialogue)){
+                                                                       if((!endkeydown&&(Input::isKeyDown(SDLK_1)||Input::isKeyDown(SDLK_2)||Input::isKeyDown(SDLK_3)||Input::isKeyDown(SDLK_4)||Input::isKeyDown(SDLK_5)
+                                                                               ||Input::isKeyDown(SDLK_6)||Input::isKeyDown(SDLK_7)||Input::isKeyDown(SDLK_8)||Input::isKeyDown(SDLK_9)||Input::isKeyDown(SDLK_0)
+                                                                               ||Input::isKeyDown(SDLK_MINUS)))||(Input::isKeyDown(attackkey)&&!oldbuttondialogue)){
                                                                                        indialogue++;
                                                                                        endkeydown=1;
                                                                                        if(indialogue<numdialogueboxes[whichdialogue]){
                                                                                                if(dialogueboxsound[whichdialogue][indialogue]!=0){
-                                                                                                       static float gLoc[3];
-                                                                                                       static float vel[3];
                                                                                                        XYZ temppos;
                                                                                                        temppos=player[participantfocus[whichdialogue][indialogue]].coords;
                                                                                                        temppos=temppos-viewer;
                                                                                                        Normalise(&temppos);
                                                                                                        temppos+=viewer;
 
-                                                                                                       gLoc[0]=temppos.x;
-                                                                                                       gLoc[1]=temppos.y;
-                                                                                                       gLoc[2]=temppos.z;vel[0]=0;
-                                                                                                       vel[1]=0;
-                                                                                                       vel[2]=0;
                                                                                                        int whichsoundplay;
                                                                                                        if(dialogueboxsound[whichdialogue][indialogue]==1)whichsoundplay=rabbitchitter;
                                                                                                        if(dialogueboxsound[whichdialogue][indialogue]==2)whichsoundplay=rabbitchitter2;
@@ -5447,10 +4064,7 @@ void     Game::Tick()
                                                                                                        if(dialogueboxsound[whichdialogue][indialogue]==-4)whichsoundplay=consolefailsound;
                                                                                                        if(dialogueboxsound[whichdialogue][indialogue]==-6)whichsoundplay=alarmsound;
                                                                                                        if(dialogueboxsound[whichdialogue][indialogue]!=-5){
-                                                                                                               PlaySoundEx( whichsoundplay, samp[whichsoundplay], NULL, true);
-                                                                                                               OPENAL_3D_SetAttributes(channels[whichsoundplay], gLoc, vel);
-                                                                                                               OPENAL_SetVolume(channels[whichsoundplay], 256);
-                                                                                                               OPENAL_SetPaused(channels[whichsoundplay], false);
+                                                                                                               emit_sound_at(whichsoundplay, temppos);
                                                                                                        }
                                                                                                        if(dialogueboxsound[whichdialogue][indialogue]==-5){
                                                                                                                hotspot[numhotspots]=player[0].coords;
@@ -5471,9 +4085,9 @@ void      Game::Tick()
                                                                                                }
                                                                                        }
                                                                                }
-                                                                               if(!IsKeyDown(theKeyMap, MAC_1_KEY)&&!IsKeyDown(theKeyMap, MAC_2_KEY)&&!IsKeyDown(theKeyMap, MAC_3_KEY)&&!IsKeyDown(theKeyMap, MAC_4_KEY)&&!IsKeyDown(theKeyMap, MAC_5_KEY)
-                                                                                       &&!IsKeyDown(theKeyMap, MAC_6_KEY)&&!IsKeyDown(theKeyMap, MAC_7_KEY)&&!IsKeyDown(theKeyMap, MAC_8_KEY)&&!IsKeyDown(theKeyMap, MAC_9_KEY)&&!IsKeyDown(theKeyMap, MAC_0_KEY)
-                                                                                       &&!IsKeyDown(theKeyMap, MAC_MINUS_KEY)){
+                                                                               if(!Input::isKeyDown(SDLK_1)&&!Input::isKeyDown(SDLK_2)&&!Input::isKeyDown(SDLK_3)&&!Input::isKeyDown(SDLK_4)&&!Input::isKeyDown(SDLK_5)
+                                                                                       &&!Input::isKeyDown(SDLK_6)&&!Input::isKeyDown(SDLK_7)&&!Input::isKeyDown(SDLK_8)&&!Input::isKeyDown(SDLK_9)&&!Input::isKeyDown(SDLK_0)
+                                                                                       &&!Input::isKeyDown(SDLK_MINUS)){
                                                                                                endkeydown=0;
                                                                                        }
                                                                                        if(indialogue>=numdialogueboxes[whichdialogue]){
@@ -5496,120 +4110,11 @@ void   Game::Tick()
                                                        }
                                                }
 
-                                               if(!IsKeyDown(theKeyMap, attackkey))oldbuttondialogue=0;
+                                               if(!Input::isKeyDown(attackkey))oldbuttondialogue=0;
                                                else oldbuttondialogue=1;
 
                                                static float keyrefreshdelay=0,bigrefreshdelay=0;
 
-                                               //Net updates
-
-                                               /*keyrefreshdelay-=multiplier;
-                                               bigrefreshdelay-=multiplier;
-
-                                               if(keyrefreshdelay<=0){
-                                               static int concat[4];
-
-                                               concat[0]=player[0].forwardkeydown;
-                                               concat[0]=concat[0]*2+player[0].forwardstogglekeydown;
-                                               concat[0]=concat[0]*2+player[0].rightkeydown;
-                                               concat[0]=concat[0]*2+player[0].leftkeydown;
-                                               concat[0]=concat[0]*2+player[0].backkeydown;
-                                               concat[0]=concat[0]*2+player[0].jumpkeydown;
-                                               concat[0]=concat[0]*2+player[0].jumptogglekeydown;
-                                               concat[0]=concat[0]*2+player[0].crouchkeydown;
-
-                                               concat[1]=player[0].crouchtogglekeydown;
-                                               concat[1]=concat[1]*2+player[0].drawkeydown;
-                                               concat[1]=concat[1]*2+player[0].drawtogglekeydown;
-                                               concat[1]=concat[1]*2+player[0].throwkeydown;
-                                               concat[1]=concat[1]*2+player[0].throwtogglekeydown;
-                                               concat[1]=concat[1]*2+player[0].attackkeydown;
-
-                                               //concat[2]=(char)((int)(rotation/2)%180);
-
-                                               //concat[3]=(char)((int)(rotation2/2)%180);
-
-                                               chatname[0]=concat[0]-128;
-                                               chatname[1]=concat[1]-128;
-                                               //chatname[2]=concat[2]-128;
-                                               //chatname[3]=concat[3]-128;
-                                               int temppoint=2;
-                                               memcpy(chatname+temppoint,&rotation,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&rotation2,sizeof(float));
-                                               temppoint+=sizeof(float);
-
-                                               chatname[temppoint]='\0';
-
-                                               //if(!ishost)NetworkSendPlayerMessage( chatname, kMessageType_Keys );
-                                               //if(ishost)NetworkSendPlayerRelayMessage( chatname, kMessageType_Keys );
-                                               //keyrefreshdelay=.01;
-                                               keyrefreshdelay=.03;
-                                               }
-
-                                               if(bigrefreshdelay<=0){
-                                               for(i=0;i<1;i++){
-                                               /*int temppoint=0;
-                                               memcpy(chatname+temppoint,&i,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].coords.x,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].coords.y,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].coords.z,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].damage,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].target,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].targetanimation,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].currentanimation,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].velocity.x,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].velocity.y,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].velocity.z,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].targetframe,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].currentframe,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].rotation,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].targetrotation,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].bloodloss,sizeof(float));
-                                               temppoint+=sizeof(float);
-                                               memcpy(chatname+temppoint,&player[i].weaponactive,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].num_weapons,sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].weaponids[0],sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].weaponids[1],sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].weaponids[2],sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               memcpy(chatname+temppoint,&player[i].weaponids[3],sizeof(int));
-                                               temppoint+=sizeof(int);
-                                               chatname[temppoint]='\0';
-
-                                               sprintf (chatname, "%d %f %f %f %f %f %d %d %f %f %f %d %d %f %f %f",i,player[i].coords.x,player[i].coords.y,player[i].coords.z,player[i].damage,player[i].target, player[i].targetanimation, player[i].currentanimation, player[i].velocity.x, player[i].velocity.y, player[i].velocity.z, player[i].targetframe, player[i].currentframe, player[i].rotation, player[i].targetrotation);
-                                               //if(ishost)NetworkSendPlayerRelayMessage( chatname, kMessageType_PlayerState );
-                                               //else NetworkSendPlayerMessage( chatname, kMessageType_PlayerState );
-
-                                               sprintf (chatname, "%d %f %d %d %d %d %d %d %d %d %f",i,player[i].bloodloss, player[i].weaponactive, player[i].num_weapons, player[i].weaponids[0], player[i].weaponids[1], player[i].weaponids[2], player[i].weaponids[3],player[i].dead,player[i].skeleton.free,player[i].permanentdamage);
-
-                                               //if(ishost)NetworkSendPlayerRelayMessage( chatname, kMessageType_PlayerStateMisc );
-                                               //else NetworkSendPlayerMessage( chatname, kMessageType_PlayerStateMisc );
-                                               }
-                                               //bigrefreshdelay=.02;
-                                               bigrefreshdelay=.1;
-                                               }
-                                               }*/
-
                                                if(!player[0].jumpkeydown){
                                                        player[0].jumptogglekeydown=0;
                                                }
@@ -5617,7 +4122,6 @@ void      Game::Tick()
 
 
                                                dialoguetime+=multiplier;
-                                               skybox.cloudmove+=multiplier;
                                                hawkrotation+=multiplier*25;
                                                realhawkcoords=0;
                                                realhawkcoords.x=25;
@@ -5626,38 +4130,22 @@ void    Game::Tick()
 
                                                if(hawkcalldelay<=0)
                                                {
-                                                       static float gLoc[3];
-                                                       static float vel[3];
-                                                       gLoc[0]=realhawkcoords.x;
-                                                       gLoc[1]=realhawkcoords.y;
-                                                       gLoc[2]=realhawkcoords.z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( hawksound, samp[hawksound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[hawksound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[hawksound], 128);
-                                                       OPENAL_SetPaused(channels[hawksound], false);
+                                                       emit_sound_at(hawksound, realhawkcoords);
 
                                                        hawkcalldelay=16+abs(Random()%8);
                                                }
                                                static float temptexdetail;
 
 
-                                               if(IsKeyDown(theKeyMap, MAC_H_KEY)&&debugmode){
+                                               if(Input::isKeyDown(SDLK_h)&&debugmode){
                                                        player[0].damagetolerance=200000;
                                                        player[0].damage=0;
                                                        player[0].burnt=0;
                                                        player[0].permanentdamage=0;
                                                        player[0].superpermanentdamage=0;
-                                                       /*
-                                                       int whichchar;
-                                                       whichchar = abs(Random()%7);
-                                                       registrationname[whichchar]+=1;
-                                                       */
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_J_KEY)&&!envtogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_j)&&!envtogglekeydown&&debugmode){
                                                        environment++;
                                                        if(environment>2)environment=0;
                                                        Setenvironment(environment);
@@ -5666,20 +4154,20 @@ void    Game::Tick()
                                                }
 
 
-                                               if(!IsKeyDown(theKeyMap, MAC_J_KEY)){
+                                               if(!Input::isKeyDown(SDLK_j)){
                                                        envtogglekeydown=0;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_C_KEY)&&!cameratogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_c)&&!cameratogglekeydown&&debugmode){
                                                        cameramode=1-cameramode;
                                                        cameratogglekeydown=1;
                                                }
 
-                                               if(!IsKeyDown(theKeyMap, MAC_C_KEY)){
+                                               if(!Input::isKeyDown(SDLK_c)){
                                                        cameratogglekeydown=0;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_X_KEY)&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!detailtogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_x)&&!Input::isKeyDown(SDLK_LSHIFT)&&!detailtogglekeydown&&debugmode){
                                                        if(player[0].num_weapons>0){
                                                                if(weapons.type[player[0].weaponids[0]]==sword)weapons.type[player[0].weaponids[0]]=staff;
                                                                else if(weapons.type[player[0].weaponids[0]]==staff)weapons.type[player[0].weaponids[0]]=knife;
@@ -5701,20 +4189,10 @@ void    Game::Tick()
                                                                        weapons.length[player[0].weaponids[0]]=.25;
                                                                }
                                                        }
-
-                                                       /*for(i=0;i<objects.numobjects;i++){
-                                                       if(objects.type[i]==treeleavestype){
-                                                       for(j=0;j<objects.numobjects;j++){
-                                                       if(objects.type[j]==treetrunktype)
-                                                       if(findDistancefast(&objects.position[i],&objects.position[j])<.5)
-                                                       objects.scale[i]=objects.scale[j];
-                                                       }
-                                                       }
-                                                       }*/
                                                        detailtogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_X_KEY)&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!detailtogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_x)&&Input::isKeyDown(SDLK_LSHIFT)&&!detailtogglekeydown&&debugmode){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -5771,7 +4249,7 @@ void      Game::Tick()
                                                                detailtogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_U_KEY)&&debugmode){
+                                               if(Input::isKeyDown(SDLK_u)&&debugmode){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -5789,7 +4267,7 @@ void      Game::Tick()
                                                }
 
 
-                                               if(IsKeyDown(theKeyMap, MAC_O_KEY)&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&debugmode){
+                                               if(Input::isKeyDown(SDLK_o)&&!Input::isKeyDown(SDLK_LSHIFT)&&debugmode){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -5801,7 +4279,7 @@ void      Game::Tick()
                                                                                closest=i;
                                                                        }
                                                                }
-                                                               if(IsKeyDown(theKeyMap, MAC_CONTROL_KEY))closest=0;
+                                                               if(Input::isKeyDown(SDLK_LCTRL))closest=0;
 
                                                                if(closest!=-1){
                                                                        player[closest].whichskin++;
@@ -5819,13 +4297,13 @@ void    Game::Tick()
                                                                                tintb=player[closest].clothestintb[i];
                                                                                AddClothes((char *)player[closest].clothes[i],0,1,&player[closest].skeleton.skinText[0],&player[closest].skeleton.skinsize);
                                                                        }
-                                                                       player[closest].DoMipmaps(5,0,0,player[closest].skeleton.skinsize,player[closest].skeleton.skinsize);
+                                                                       player[closest].DoMipmaps();
                                                                }
 
                                                                detailtogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_O_KEY)&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&debugmode){
+                                               if(Input::isKeyDown(SDLK_o)&&Input::isKeyDown(SDLK_LSHIFT)&&debugmode){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -5906,18 +4384,18 @@ void    Game::Tick()
                                                                detailtogglekeydown=1;
                                                }
 
-                                               if(!IsKeyDown(theKeyMap, MAC_X_KEY)){
+                                               if(!Input::isKeyDown(SDLK_x)){
                                                        detailtogglekeydown=0;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_B_KEY)&&!slomotogglekeydown&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&debugmode){
+                                               if(Input::isKeyDown(SDLK_b)&&!slomotogglekeydown&&!Input::isKeyDown(SDLK_LSHIFT)&&debugmode){
                                                        slomo=1-slomo;
                                                        slomodelay=1000;
                                                        slomotogglekeydown=1;
                                                }
 
 
-                                               if(((IsKeyDown(theKeyMap, MAC_I_KEY)&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY))/*||buttons[1]*/)&&!explodetogglekeydown&&debugmode){
+                                               if(((Input::isKeyDown(SDLK_i)&&!Input::isKeyDown(SDLK_LSHIFT)))&&!explodetogglekeydown&&debugmode){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -5947,29 +4425,14 @@ void    Game::Tick()
                                                                                flatvelocity2.z+=(float)(abs(Random()%100)-50)/10;
                                                                                headspurtdirection=player[closest].skeleton.joints[player[closest].skeleton.jointlabels[head]].position-player[closest].skeleton.joints[player[closest].skeleton.jointlabels[neck]].position;
                                                                                Normalise(&headspurtdirection);
-                                                                               sprites.MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, .6, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, .6, 1);
                                                                                flatvelocity2+=headspurtdirection*8;
-                                                                               sprites.MakeSprite(bloodsprite, flatfacing2,flatvelocity2/2, 1,1,1, .16, 1);
+                                                                               Sprite::MakeSprite(bloodsprite, flatfacing2,flatvelocity2/2, 1,1,1, .16, 1);
                                                                        }
-                                                                       sprites.MakeSprite(cloudsprite, flatfacing2,flatvelocity2*0, .6,0,0, 1, .5);
-
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=blah.x;
-                                                                       gLoc[1]=blah.y;
-                                                                       gLoc[2]=blah.z;
-                                                                       vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
-                                                                       PlaySoundEx( splattersound, samp[splattersound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[splattersound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[splattersound], 256);
-                                                                       OPENAL_SetPaused(channels[splattersound], false);
-
-                                                                       PlaySoundEx( breaksound2, samp[breaksound2], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[breaksound2], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[breaksound2], 100);
-                                                                       OPENAL_SetPaused(channels[breaksound2], false);
+                                                                       Sprite::MakeSprite(cloudsprite, flatfacing2,flatvelocity2*0, .6,0,0, 1, .5);
+
+                                                                       emit_sound_at(splattersound, blah);
+                                                                       emit_sound_at(breaksound2, blah, 100.);
 
                                                                        if(player[closest].skeleton.free==2)player[closest].skeleton.free=0;
                                                                        player[closest].RagDoll(0);
@@ -5983,7 +4446,7 @@ void      Game::Tick()
                                                                explodetogglekeydown=1;
                                                }
 
-                                               if(((IsKeyDown(theKeyMap, MAC_I_KEY)&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY))/*||buttons[2]*/)&&!explodetogglekeydown&&debugmode){
+                                               if(((Input::isKeyDown(SDLK_i)&&Input::isKeyDown(SDLK_LSHIFT)))&&!explodetogglekeydown&&debugmode){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -6001,24 +4464,9 @@ void     Game::Tick()
                                                                }
 
                                                                if(closest!=-1){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=blah.x;
-                                                                       gLoc[1]=blah.y;
-                                                                       gLoc[2]=blah.z;
-                                                                       vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
-
-                                                                       PlaySoundEx( splattersound, samp[splattersound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[splattersound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[splattersound], 256);
-                                                                       OPENAL_SetPaused(channels[splattersound], false);
-
-                                                                       PlaySoundEx( breaksound2, samp[breaksound2], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[breaksound2], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[breaksound2], 600);
-                                                                       OPENAL_SetPaused(channels[breaksound2], false);
+                                                                       emit_sound_at(splattersound, blah);
+
+                                                                       emit_sound_at(breaksound2, blah);
 
                                                                        for(i=0;i<player[closest].skeleton.num_joints; i++){
                                                                                if(!player[closest].skeleton.free)flatvelocity2=player[closest].velocity;
@@ -6028,9 +4476,9 @@ void      Game::Tick()
                                                                                flatvelocity2.x+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.y+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.z+=(float)(abs(Random()%100)-50)/10;
-                                                                               sprites.MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, 3, 1);
-                                                                               sprites.MakeSprite(bloodsprite, flatfacing2,flatvelocity2, 1,1,1, .3, 1);
-                                                                               sprites.MakeSprite(cloudsprite, flatfacing2,flatvelocity2*0, .6,0,0, 1, .5);
+                                                                               Sprite::MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, 3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite, flatfacing2,flatvelocity2, 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(cloudsprite, flatfacing2,flatvelocity2*0, .6,0,0, 1, .5);
                                                                        }
 
                                                                        for(i=0;i<player[closest].skeleton.num_joints; i++){
@@ -6041,8 +4489,8 @@ void      Game::Tick()
                                                                                flatvelocity2.x+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.y+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.z+=(float)(abs(Random()%100)-50)/10;
-                                                                               sprites.MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, 3, 1);
-                                                                               sprites.MakeSprite(bloodsprite, flatfacing2,flatvelocity2, 1,1,1, .4, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, 3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite, flatfacing2,flatvelocity2, 1,1,1, .4, 1);
                                                                        }
 
                                                                        for(i=0;i<player[closest].skeleton.num_joints; i++){
@@ -6053,8 +4501,8 @@ void      Game::Tick()
                                                                                flatvelocity2.x+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.y+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.z+=(float)(abs(Random()%100)-50)/10;
-                                                                               sprites.MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2*2, 1,1,1, 3, 1);
-                                                                               sprites.MakeSprite(bloodsprite, flatfacing2,flatvelocity2*2, 1,1,1, .4, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2*2, 1,1,1, 3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite, flatfacing2,flatvelocity2*2, 1,1,1, .4, 1);
                                                                        }
 
                                                                        for(i=0;i<player[closest].skeleton.num_joints; i++){
@@ -6065,8 +4513,8 @@ void      Game::Tick()
                                                                                flatvelocity2.x+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.y+=(float)(abs(Random()%100)-50)/10;
                                                                                flatvelocity2.z+=(float)(abs(Random()%100)-50)/10;
-                                                                               sprites.MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2*2, 1,1,1, 3, 1);
-                                                                               sprites.MakeSprite(bloodsprite, flatfacing2,flatvelocity2*2, 1,1,1, .4, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2*2, 1,1,1, 3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite, flatfacing2,flatvelocity2*2, 1,1,1, .4, 1);
                                                                        }
 
                                                                        XYZ temppos;
@@ -6102,99 +4550,28 @@ void    Game::Tick()
                                                                explodetogglekeydown=1;
                                                }
 
-                                               if(!IsKeyDown(theKeyMap, MAC_I_KEY)){
+                                               if(!Input::isKeyDown(SDLK_i)){
                                                        explodetogglekeydown=0;
                                                }
 
-                                               /*
-                                               if(IsKeyDown(theKeyMap, MAC_S_KEY)&&IsKeyDown(theKeyMap, MAC_COMMAND_KEY)&&!slomotogglekeydown){
-                                               FILE                    *tfile;
-                                               //tfile=fopen( ":Data:Maps:mapsave", "wb" );
-                                               if(whichlevel==0)tfile=fopen( ":Data:Maps:map1", "wb" );
-                                               else if(whichlevel==1)tfile=fopen( ":Data:Maps:map2", "wb" );
-                                               else if(whichlevel==2)tfile=fopen( ":Data:Maps:map3", "wb" );
-                                               else if(whichlevel==3)tfile=fopen( ":Data:Maps:map4", "wb" );
-                                               else if(whichlevel==4)tfile=fopen( ":Data:Maps:map5", "wb" );
-                                               else tfile=fopen( ":Data:Maps:mapsave", "wb" );
-
-                                               fwrite( &player[0].coords, 1, sizeof(XYZ), tfile );
-                                               fwrite( &player[0].rotation, 1, sizeof(float), tfile );
-                                               fwrite( &player[0].targetrotation, 1, sizeof(float), tfile );
-                                               fwrite( &player[0].num_weapons, 1, sizeof(int), tfile );
-                                               for(j=0;j<player[0].num_weapons;j++){
-                                               fwrite( &weapons.type[player[0].weaponids[j]], 1, sizeof(int), tfile );
-                                               }
-                                               fwrite( &environment, 1, sizeof(int), tfile );
-
-                                               fwrite( &objects.numobjects, 1, sizeof(int), tfile );
-                                               fwrite( &objects.type, 1, sizeof(int)*objects.numobjects, tfile );
-                                               fwrite( &objects.rotation, 1, sizeof(float)*objects.numobjects, tfile );
-                                               fwrite( &objects.position, 1, sizeof(XYZ)*objects.numobjects, tfile );
-                                               fwrite( &objects.scale, 1, sizeof(float)*objects.numobjects, tfile );
-
-                                               fwrite( &numplayers, 1, sizeof(int), tfile );
-                                               if(numplayers>1&&numplayers<maxplayers)
-                                               for(i=1;i<numplayers;i++){
-                                               fwrite( &player[i].coords, 1, sizeof(XYZ), tfile );
-                                               fwrite( &player[i].num_weapons, 1, sizeof(int), tfile );
-                                               for(j=0;j<player[i].num_weapons;j++){
-                                               fwrite( &weapons.type[player[i].weaponids[j]], 1, sizeof(int), tfile );
-                                               }
-                                               if(player[i].numwaypoints<30){
-                                               fwrite( &player[i].numwaypoints, 1, sizeof(int), tfile );
-                                               fwrite( &player[i].waypoints, 1, sizeof(XYZ)*player[i].numwaypoints, tfile );
-                                               fwrite( &player[i].waypoint, 1, sizeof(int), tfile );
-                                               //fwrite( &player[i].jumppath, 1, sizeof(bool), tfile );
-                                               }
-                                               else{
-                                               player[i].numwaypoints=0;
-                                               player[i].waypoint=0;
-                                               fwrite( &player[i].numwaypoints, 1, sizeof(int), tfile );
-                                               fwrite( &player[i].waypoint, 1, sizeof(int), tfile );
-                                               fwrite( &player[i].waypoint, 1, sizeof(int), tfile );
-                                               }
-                                               }
-
-                                               fclose(tfile);
-
-                                               slomotogglekeydown=1;
-                                               }*/
-
-                                               if(!IsKeyDown(theKeyMap, MAC_B_KEY)&&!IsKeyDown(theKeyMap, MAC_F_KEY)&&!IsKeyDown(theKeyMap, MAC_K_KEY)&&!IsKeyDown(theKeyMap, MAC_S_KEY)){
+                                               if(!Input::isKeyDown(SDLK_b)&&!Input::isKeyDown(SDLK_f)&&!Input::isKeyDown(SDLK_k)&&!Input::isKeyDown(SDLK_s)){
                                                        slomotogglekeydown=0;
                                                }
 
 
-                                               if(IsKeyDown(theKeyMap, MAC_F_KEY)&&!slomotogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_f)&&!slomotogglekeydown&&debugmode){
                                                        player[0].onfire=1-player[0].onfire;
                                                        if(player[0].onfire){
                                                                player[0].CatchFire();
                                                        }
                                                        if(!player[0].onfire){
-                                                               float gLoc[3];
-                                                               float vel[3];
-                                                               gLoc[0]=player[0].coords.x;
-                                                               gLoc[1]=player[0].coords.y;
-                                                               gLoc[2]=player[0].coords.z;
-                                                               vel[0]=0;
-                                                               vel[1]=0;
-                                                               vel[2]=0;
-                                                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[fireendsound], 256);
-                                                               OPENAL_SetPaused(channels[fireendsound], false);
-                                                               OPENAL_SetPaused(channels[stream_firesound], true);
+                                                               emit_sound_at(fireendsound, player[0].coords);
+                                                               pause_sound(stream_firesound);
                                                        }
                                                        slomotogglekeydown=1;
                                                }
-                                               /*
-                                               if(IsKeyDown(theKeyMap, MAC_L_KEY)){
-                                               if(player[0].bleeding<=0)
-                                               player[0].DoBlood(1,255);
-                                               }*/
 
-
-                                               if(IsKeyDown(theKeyMap, MAC_DELETE_KEY)&&editorenabled&&!drawmodetogglekeydown&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)){
+                                               if(Input::isKeyDown(SDLK_DELETE)&&editorenabled&&!drawmodetogglekeydown&&Input::isKeyDown(SDLK_LSHIFT)){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -6214,7 +4591,7 @@ void      Game::Tick()
                                                                drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_DELETE_KEY)&&editorenabled&&!drawmodetogglekeydown&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_DELETE)&&editorenabled&&!drawmodetogglekeydown&&Input::isKeyDown(SDLK_LCTRL)){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -6232,7 +4609,7 @@ void      Game::Tick()
                                                                drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_M_KEY)&&!drawmodetogglekeydown&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&editorenabled&&debugmode){
+                                               if(Input::isKeyDown(SDLK_m)&&!drawmodetogglekeydown&&!Input::isKeyDown(SDLK_LSHIFT)&&editorenabled&&debugmode){
                                                        //drawmode++;
                                                        //if(drawmode>2)drawmode=0;
                                                        if(objects.numobjects<max_objects-1){
@@ -6257,7 +4634,7 @@ void      Game::Tick()
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_P_KEY)&&!drawmodetogglekeydown&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)&&editorenabled){
+                                               if(Input::isKeyDown(SDLK_p)&&!drawmodetogglekeydown&&!Input::isKeyDown(SDLK_LSHIFT)&&!Input::isKeyDown(SDLK_LCTRL)&&editorenabled){
                                                        if(numplayers<maxplayers-1){
                                                                player[numplayers].scale=.2*5*player[0].scale;
                                                                player[numplayers].creature=rabbittype;
@@ -6349,7 +4726,7 @@ void      Game::Tick()
                                                                        player[numplayers].proportionlegs.z=0;
                                                                }
 
-                                                               player[numplayers].tempanimation.Load((char *)":Data:Animations:Tempanim",0,0);
+                                                               player[numplayers].tempanimation.Load((char *)"Tempanim",0,0);
 
                                                                player[numplayers].damagetolerance=200;
 
@@ -6378,7 +4755,7 @@ void      Game::Tick()
                                                                                AddClothes((char *)player[numplayers].clothes[i],0,1,&player[numplayers].skeleton.skinText[0],&player[numplayers].skeleton.skinsize);
                                                                        }
                                                                        if(player[numplayers].numclothes){
-                                                                               player[numplayers].DoMipmaps(5,0,0,player[numplayers].skeleton.skinsize,player[numplayers].skeleton.skinsize);
+                                                                               player[numplayers].DoMipmaps();
                                                                        }
 
                                                                        player[numplayers].power=player[0].power;
@@ -6405,7 +4782,7 @@ void      Game::Tick()
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_P_KEY)&&!drawmodetogglekeydown&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&editorenabled){
+                                               if(Input::isKeyDown(SDLK_p)&&!drawmodetogglekeydown&&Input::isKeyDown(SDLK_LSHIFT)&&editorenabled){
                                                        if(player[numplayers-1].numwaypoints<90){
                                                                player[numplayers-1].waypoints[player[numplayers-1].numwaypoints]=player[0].coords;
                                                                player[numplayers-1].waypointtype[player[numplayers-1].numwaypoints]=editorpathtype;
@@ -6414,7 +4791,7 @@ void      Game::Tick()
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_P_KEY)&&!drawmodetogglekeydown&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)&&editorenabled){
+                                               if(Input::isKeyDown(SDLK_p)&&!drawmodetogglekeydown&&Input::isKeyDown(SDLK_LCTRL)&&editorenabled){
                                                        if(numpathpoints<30){
                                                                bool connected,alreadyconnected;
                                                                connected=0;
@@ -6446,17 +4823,18 @@ void    Game::Tick()
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_PERIOD_KEY)&&!drawmodetogglekeydown&&editorenabled){
+                                               if(Input::isKeyDown(SDLK_PERIOD)&&!drawmodetogglekeydown&&editorenabled){
                                                        pathpointselected++;
                                                        if(pathpointselected>=numpathpoints)pathpointselected=-1;
                                                        drawmodetogglekeydown=1;
                                                }
-                                               if(IsKeyDown(theKeyMap, MAC_COMMA_KEY)&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!drawmodetogglekeydown&&editorenabled){
+                                               if(Input::isKeyDown(SDLK_COMMA)&&!Input::isKeyDown(SDLK_LSHIFT)&&!drawmodetogglekeydown&&editorenabled){
                                                        pathpointselected--;
-                                                       if(pathpointselected<=-2)pathpointselected=numpathpoints-1;
+                                                       if(pathpointselected<=-2)
+                                                               pathpointselected=numpathpoints-1;
                                                        drawmodetogglekeydown=1;
                                                }
-                                               if(IsKeyDown(theKeyMap, MAC_COMMA_KEY)&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!drawmodetogglekeydown&&editorenabled){
+                                               if(Input::isKeyDown(SDLK_COMMA)&&Input::isKeyDown(SDLK_LSHIFT)&&!drawmodetogglekeydown&&editorenabled){
                                                        if(pathpointselected!=-1){
                                                                numpathpoints--;
                                                                pathpoint[pathpointselected]=pathpoint[numpathpoints];
@@ -6480,96 +4858,74 @@ void    Game::Tick()
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_M_KEY)&&!drawmodetogglekeydown&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&debugmode){
+                                               if(Input::isKeyDown(SDLK_m)&&!drawmodetogglekeydown&&Input::isKeyDown(SDLK_LSHIFT)&&debugmode){
                                                        editorenabled=1-editorenabled;
                                                        if(editorenabled){
                                                                player[0].damagetolerance=100000;
-                                                               player[0].damage=0;
-                                                               player[0].superpermanentdamage=0;
-                                                               player[0].bloodloss=0;
-                                                               player[0].deathbleeding=0;
-                                                       }
-                                                       if(!editorenabled){
+                                                       } else {
                                                                player[0].damagetolerance=200;
-                                                               player[0].damage=0;
-                                                               player[0].permanentdamage=0;
-                                                               player[0].superpermanentdamage=0;
-                                                               player[0].bloodloss=0;
-                                                               player[0].deathbleeding=0;
                                                        }
+                                                       player[0].damage=0; // these lines were in both if and else, but I think they would better fit in the if
+                                                       player[0].permanentdamage=0;
+                                                       player[0].superpermanentdamage=0;
+                                                       player[0].bloodloss=0;
+                                                       player[0].deathbleeding=0;
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_LEFT_KEY)&&!drawmodetogglekeydown&&editorenabled&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_LEFT)&&!drawmodetogglekeydown&&editorenabled&&Input::isKeyDown(SDLK_LSHIFT)&&!Input::isKeyDown(SDLK_LCTRL)){
                                                        editortype--;
                                                        if(editortype==treeleavestype||editortype==10)editortype--;
                                                        if(editortype<0)editortype=firetype;
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_RIGHT_KEY)&&!drawmodetogglekeydown&&editorenabled&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_RIGHT)&&!drawmodetogglekeydown&&editorenabled&&Input::isKeyDown(SDLK_LSHIFT)&&!Input::isKeyDown(SDLK_LCTRL)){
                                                        editortype++;
                                                        if(editortype==treeleavestype||editortype==10)editortype++;
                                                        if(editortype>firetype)editortype=0;
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_LEFT_KEY)&&editorenabled&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_LEFT)&&editorenabled&&!Input::isKeyDown(SDLK_LSHIFT)&&!Input::isKeyDown(SDLK_LCTRL)){
                                                        editorrotation-=multiplier*100;
                                                        if(editorrotation<-.01)editorrotation=-.01;
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_RIGHT_KEY)&&editorenabled&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_RIGHT)&&editorenabled&&!Input::isKeyDown(SDLK_LSHIFT)&&!Input::isKeyDown(SDLK_LCTRL)){
                                                        editorrotation+=multiplier*100;
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_UP_KEY)&&editorenabled&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_UP)&&editorenabled&&!Input::isKeyDown(SDLK_LCTRL)){
                                                        editorsize+=multiplier;
                                                        drawmodetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_DOWN_KEY)&&editorenabled&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_DOWN)&&editorenabled&&!Input::isKeyDown(SDLK_LCTRL)){
                                                        editorsize-=multiplier;
                                                        if(editorsize<.1)editorsize=.1;
                                                        drawmodetogglekeydown=1;
                                                }
 
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_LEFT_KEY)&&!drawmodetogglekeydown&&editorenabled&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_LEFT)&&!drawmodetogglekeydown&&editorenabled&&Input::isKeyDown(SDLK_LSHIFT)&&Input::isKeyDown(SDLK_LCTRL)){
                                                        mapradius-=multiplier*10;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_RIGHT_KEY)&&!drawmodetogglekeydown&&editorenabled&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_RIGHT)&&!drawmodetogglekeydown&&editorenabled&&Input::isKeyDown(SDLK_LSHIFT)&&Input::isKeyDown(SDLK_LCTRL)){
                                                        mapradius+=multiplier*10;
                                                }
-                                               /*
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_LEFT_KEY)&&editorenabled&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
-                                               mapcenter.x+=multiplier*20;
-                                               }
-
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_RIGHT_KEY)&&editorenabled&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
-                                               mapcenter.x-=multiplier*20;
-                                               }
-
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_UP_KEY)&&editorenabled&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
-                                               mapcenter.z+=multiplier*20;
-                                               }
-
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_DOWN_KEY)&&editorenabled&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
-                                               mapcenter.z-=multiplier*20;
-                                               }
-                                               */
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_UP_KEY)&&editorenabled&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_UP)&&editorenabled&&Input::isKeyDown(SDLK_LCTRL)){
                                                        editorrotation2+=multiplier*100;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_ARROW_DOWN_KEY)&&editorenabled&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)){
+                                               if(Input::isKeyDown(SDLK_DOWN)&&editorenabled&&Input::isKeyDown(SDLK_LCTRL)){
                                                        editorrotation2-=multiplier*100;
                                                        if(editorrotation2<-.01)editorrotation2=-.01;
                                                }
-                                               if(IsKeyDown(theKeyMap, MAC_DELETE_KEY)&&editorenabled&&objects.numobjects&&!drawmodetogglekeydown&&!IsKeyDown(theKeyMap, MAC_SHIFT_KEY)){
+                                               if(Input::isKeyDown(SDLK_DELETE)&&editorenabled&&objects.numobjects&&!drawmodetogglekeydown&&!Input::isKeyDown(SDLK_LSHIFT)){
                                                        int closest=-1;
                                                        float closestdist=-1;
                                                        float distance;
@@ -6585,34 +4941,22 @@ void    Game::Tick()
                                                }
 
 
-                                               if(!IsKeyDown(theKeyMap, MAC_M_KEY)&&!IsKeyDown(theKeyMap, MAC_ARROW_LEFT_KEY)&&!IsKeyDown(theKeyMap, MAC_COMMA_KEY)&&!IsKeyDown(theKeyMap, MAC_PERIOD_KEY)&&!IsKeyDown(theKeyMap, MAC_ARROW_RIGHT_KEY)&&!IsKeyDown(theKeyMap, MAC_DELETE_KEY)&&!IsKeyDown(theKeyMap, MAC_P_KEY)){
+                                               if(!Input::isKeyDown(SDLK_m)&&!Input::isKeyDown(SDLK_LEFT)&&!Input::isKeyDown(SDLK_COMMA)&&!Input::isKeyDown(SDLK_PERIOD)&&!Input::isKeyDown(SDLK_RIGHT)&&!Input::isKeyDown(SDLK_DELETE)&&!Input::isKeyDown(SDLK_p)){
                                                        drawmodetogglekeydown=0;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_N_KEY)&&!IsKeyDown(theKeyMap, MAC_CONTROL_KEY)&&!texturesizetogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_n)&&!Input::isKeyDown(SDLK_LCTRL)&&!texturesizetogglekeydown&&debugmode){
                                                        //if(!player[0].skeleton.free)player[0].damage+=500;
                                                        player[0].RagDoll(0);
                                                        //player[0].spurt=1;
                                                        //player[0].DoDamage(1000);
 
-                                                       float gLoc[3];
-                                                       float vel[3];
-                                                       gLoc[0]=player[0].coords.x;
-                                                       gLoc[1]=player[0].coords.y;
-                                                       gLoc[2]=player[0].coords.z;
-                                                       vel[0]=player[0].velocity.x;
-                                                       vel[1]=player[0].velocity.y;
-                                                       vel[2]=player[0].velocity.z;
-                                                       PlaySoundEx( whooshsound, samp[whooshsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[whooshsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[whooshsound], 128);
-                                                       OPENAL_SetPaused(channels[whooshsound], false);
-                                                       //OPENAL_SetPaused(channels[whooshsound], true);
+                                                       emit_sound_at(whooshsound, player[0].coords, 128.);
 
                                                        texturesizetogglekeydown=1;
                                                }
 
-                                               if(IsKeyDown(theKeyMap, MAC_N_KEY)&&IsKeyDown(theKeyMap, MAC_CONTROL_KEY)&&!texturesizetogglekeydown&&debugmode){
+                                               if(Input::isKeyDown(SDLK_n)&&Input::isKeyDown(SDLK_LCTRL)&&!texturesizetogglekeydown&&debugmode){
 
                                                        int closest=-1;
                                                        float closestdist=-1;
@@ -6630,13 +4974,13 @@ void    Game::Tick()
                                                //Attack
                                                static bool playerrealattackkeydown=0;
 
-                                               if(!buttons[0])oldbutton=0;
-                                               if(!IsKeyDown(theKeyMap, attackkey))oldattackkey=0;
+                                               if(!Input::isKeyDown(MOUSEBUTTON1)&&!Input::isKeyDown(MOUSEBUTTON2))oldbutton=0;
+                                               if(!Input::isKeyDown(attackkey))oldattackkey=0;
                                                if(oldattackkey)player[0].attackkeydown=0;
                                                if(oldattackkey)playerrealattackkeydown=0;
-                                               if(!oldattackkey)playerrealattackkeydown=IsKeyDown(theKeyMap, attackkey);
-                                               if((player[0].parriedrecently<=0||player[0].weaponactive==-1)&&(!oldattackkey||(realthreat&&player[0].lastattack!=swordslashanim&&player[0].lastattack!=knifeslashstartanim&&player[0].lastattack!=staffhitanim&&player[0].lastattack!=staffspinhitanim)))player[0].attackkeydown=IsKeyDown(theKeyMap, attackkey);
-                                               if(IsKeyDown(theKeyMap, attackkey)&&!oldattackkey&&!player[0].backkeydown){
+                                               if(!oldattackkey)playerrealattackkeydown=Input::isKeyDown(attackkey);
+                                               if((player[0].parriedrecently<=0||player[0].weaponactive==-1)&&(!oldattackkey||(realthreat&&player[0].lastattack!=swordslashanim&&player[0].lastattack!=knifeslashstartanim&&player[0].lastattack!=staffhitanim&&player[0].lastattack!=staffspinhitanim)))player[0].attackkeydown=Input::isKeyDown(attackkey);
+                                               if(Input::isKeyDown(attackkey)&&!oldattackkey&&!player[0].backkeydown){
                                                        for(k=0;k<numplayers;k++){
                                                                if((player[k].targetanimation==swordslashanim||player[k].targetanimation==staffhitanim||player[k].targetanimation==staffspinhitanim)&&player[0].currentanimation!=dodgebackanim&&!player[k].skeleton.free)
                                                                        player[k].Reverse();
@@ -7018,35 +5362,20 @@ void    Game::Tick()
                                                                                                                                                                                                                if(((((findLengthfast(&rotatetarget)>150&&(i!=0&&k!=0))||(findLengthfast(&rotatetarget)>50&&player[0].rabbitkickragdoll/*currentanimation==rabbitkickanim*/&&(i==0||k==0)))&&normaldotproduct(rotatetarget,player[k].coords-player[i].coords)>0)&&((i==0||k==0)||((player[i].skeleton.oldfree==1&&k!=0&&animation[player[k].currentanimation].attack==neutral)||(player[k].skeleton.oldfree==1&&i!=0&&animation[player[i].currentanimation].attack==neutral)||(player[i].isFlip()&&!player[i].skeleton.oldfree&&(i==0||k==0))||(player[k].isFlip()&&!player[k].skeleton.oldfree&&(i==0||k==0))||(i==0||k==0))))||((player[i].targetanimation==jumpupanim||player[i].targetanimation==jumpdownanim||player[i].isFlip())&&(player[k].targetanimation==jumpupanim||player[k].targetanimation==jumpdownanim||player[k].isFlip())&&(i==0||k==0)&&(!player[i].skeleton.oldfree&&!player[k].skeleton.oldfree))){
                                                                                                                                                                                                                        //If hit by body
                                                                                                                                                                                                                        if((i!=0||player[i].skeleton.free)&&(k!=0||player[k].skeleton.free)||(animation[player[i].targetanimation].height==highheight&&animation[player[k].targetanimation].height==highheight)){
-                                                                                                                                                                                                                               static float gLoc[3];
-                                                                                                                                                                                                                               static float vel[3];
-                                                                                                                                                                                                                               gLoc[0]=player[i].coords.x;
-                                                                                                                                                                                                                               gLoc[1]=player[i].coords.y;
-                                                                                                                                                                                                                               gLoc[2]=player[i].coords.z;
-                                                                                                                                                                                                                               vel[0]=player[i].velocity.x;
-                                                                                                                                                                                                                               vel[1]=player[i].velocity.y;
-                                                                                                                                                                                                                               vel[2]=player[i].velocity.z;
                                                                                                                                                                                                                                if(tutoriallevel!=1){
-                                                                                                                                                                                                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                                                                                                                                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                                                                                                                                                                       OPENAL_SetVolume(channels[heavyimpactsound], 256);
-                                                                                                                                                                                                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                                                                                                                                                                       emit_sound_at(heavyimpactsound, player[i].coords);
                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                //player[i].velocity=player[k].velocity;
                                                                                                                                                                                                                                //player[k].velocity=player[i].velocity;
 
                                                                                                                                                                                                                                player[i].RagDoll(0);
                                                                                                                                                                                                                                if(player[i].damage>player[i].damagetolerance-findLengthfast(&rotatetarget)/4&&!player[i].dead){
-                                                                                                                                                                                                                                       bonus=aimbonus;
-                                                                                                                                                                                                                                       bonustime=0;
-                                                                                                                                                                                                                                       bonusvalue=150;
+                                                                                                                                                                                                                                 award_bonus(0, aimbonus);
                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                player[i].DoDamage(findLengthfast(&rotatetarget)/4);
                                                                                                                                                                                                                                player[k].RagDoll(0);
                                                                                                                                                                                                                                if(player[k].damage>player[k].damagetolerance-findLengthfast(&rotatetarget)/4&&!player[k].dead){
-                                                                                                                                                                                                                                       bonus=aimbonus;
-                                                                                                                                                                                                                                       bonustime=0;
-                                                                                                                                                                                                                                       bonusvalue=150;
+                                                                                                                                                                                                                                 award_bonus(0, aimbonus); // Huh, again?
                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                player[k].DoDamage(findLengthfast(&rotatetarget)/4);
 
@@ -7112,11 +5441,7 @@ void     Game::Tick()
                                                                                                                                                                                                                                                player[i].DoDamage(20);
                                                                                                                                                                                                                                                player[i].RagDoll(0);
                                                                                                                                                                                                                                                player[k].lastcollide=1;
-                                                                                                                                                                                                                                               if(k==0){
-                                                                                                                                                                                                                                                       bonus=AboveBonus;
-                                                                                                                                                                                                                                                       bonustime=0;
-                                                                                                                                                                                                                                                       bonusvalue=50;
-                                                                                                                                                                                                                                               }
+                                                                                                                                                                                                                                               award_bonus(k, AboveBonus);
                                                                                                                                                                                                                                        }
                                                                                                                                                                                                                                        if(i==0&&k!=0&&player[i].targetanimation==jumpdownanim&&!player[k].isCrouch()&&player[k].targetanimation!=rollanim&&!player[i].skeleton.oldfree&&!player[i].skeleton.free&&player[i].lastcollide<=0&&player[i].velocity.y<-10){
                                                                                                                                                                                                                                                player[k].velocity=player[i].velocity;
@@ -7126,11 +5451,7 @@ void     Game::Tick()
                                                                                                                                                                                                                                                player[k].DoDamage(20);
                                                                                                                                                                                                                                                player[k].RagDoll(0);
                                                                                                                                                                                                                                                player[i].lastcollide=1;
-                                                                                                                                                                                                                                               if(i==0){
-                                                                                                                                                                                                                                                       bonus=AboveBonus;
-                                                                                                                                                                                                                                                       bonustime=0;
-                                                                                                                                                                                                                                                       bonusvalue=50;
-                                                                                                                                                                                                                                               }
+                                                                                                                                                                                                                                               award_bonus(i, AboveBonus);
                                                                                                                                                                                                                                        }
                                                                                                                                                                                                                                }
                                                                                                                                                                                                                        }
@@ -7222,78 +5543,7 @@ void     Game::Tick()
 
 
                                                        //pile
-                                                       /*
-                                                       XYZ tempdiff;
-                                                       XYZ tempoldpos;
-                                                       XYZ temp1,temp2;
-                                                       bool isgood;
-                                                       static float checkdelay;
-                                                       checkdelay-=multiplier;
-                                                       int m;
-                                                       static bool checkedcoll[maxplayers][maxplayers];
-                                                       static bool above[maxplayers];
-
-                                                       for(i=0;i<maxplayers;i++){
-                                                       for(j=0;j<maxplayers;j++){
-                                                       checkedcoll[i][j]=0;
-                                                       }
-                                                       }
-
-                                                       if(numplayers>1&&checkdelay<=0){
-                                                       checkdelay=.015;
-                                                       for(k=0;k<numplayers;k++){
-                                                       if(player[k].skeleton.free!=2)above[k]=-1;
-
-                                                       for(i=k;i<numplayers;i++){
-                                                       if(i==k)i++;
-                                                       if(i<numplayers)
-                                                       if(!checkedcoll[i][k]){
-                                                       checkedcoll[i][k]=1;
-                                                       checkedcoll[k][i]=1;
-                                                       if(player[i].skeleton.free&&player[k].skeleton.free)
-                                                       if(player[i].skeleton.free!=2||player[k].skeleton.free!=2)
-                                                       if(i!=k&&player[i].whichpatchx==player[k].whichpatchx&&player[i].whichpatchz==player[k].whichpatchz)
-                                                       if(player[i].coords.y>player[k].coords.y-3)
-                                                       if(player[i].coords.y<player[k].coords.y+3)
-                                                       if(player[i].coords.x>player[k].coords.x-3)
-                                                       if(player[i].coords.x<player[k].coords.x+3)
-                                                       if(player[i].coords.z>player[k].coords.z-3)
-                                                       if(player[i].coords.z<player[k].coords.z+3)
-                                                       if(findDistancefast(&player[i].coords,&player[k].coords)<3*((player[i].scale+player[k].scale)*2.5)*((player[i].scale+player[k].scale)*2.5)){
-                                                       int stuck,moving;
-                                                       if((player[i].skeleton.longdead>player[k].skeleton.longdead&&player[k].skeleton.free!=2)||player[i].skeleton.free==2){
-                                                       stuck=i;
-                                                       moving=k;
-                                                       }
-                                                       else
-                                                       {
-                                                       moving=i;
-                                                       stuck=k;
-                                                       }
-                                                       isgood=1;
-
-                                                       if(isgood){
-                                                       above[moving]=stuck;
-                                                       for(l=0;l<player[moving].skeleton.num_joints;l++){
-                                                       for(m=0;m<player[stuck].skeleton.num_joints;m++){
-                                                       while(findDistancefast(player[moving].skeleton.joints[l].position+player[moving].coords,player[stuck].skeleton.joints[m].position+player[stuck].coords)<.25)
-                                                       {
-                                                       player[moving].skeleton.joints[l].position.y+=.003;
-                                                       if(player[moving].skeleton.joints[l].velocity.y<-.05)player[moving].skeleton.joints[l].velocity.y+=.003/.015/2;
-
-                                                       }
-                                                       }
-                                                       }
-                                                       }
-                                                       }
-                                                       }
-                                                       }
-                                                       }
-                                                       }
-
-                                                       */
-
-                                                       if(!IsKeyDown(theKeyMap, MAC_N_KEY)){
+                                                       if(!Input::isKeyDown(SDLK_n)){
                                                                texturesizetogglekeydown=0;
                                                        }
 
@@ -7306,52 +5556,27 @@ void    Game::Tick()
                                                        }
 
                                                        static bool respawnkeydown;
-                                                       if(!editorenabled&&(whichlevel!=-2&&(IsKeyDown(theKeyMap, MAC_Z_KEY)&&IsKeyDown(theKeyMap, MAC_COMMAND_KEY)&&debugmode&&!editorenabled)||(IsKeyDown(theKeyMap, jumpkey)&&!respawnkeydown&&!oldattackkey&&player[0].dead))){
+                                                       if(!editorenabled&&(whichlevel!=-2&&(Input::isKeyDown(SDLK_z)&&Input::isKeyDown(SDLK_LMETA)&&debugmode&&!editorenabled)||(Input::isKeyDown(jumpkey)&&!respawnkeydown&&!oldattackkey&&player[0].dead))){
                                                                targetlevel=whichlevel;
                                                                loading=1;
                                                                leveltime=5;
                                                        }
-                                                       if(!IsKeyDown(theKeyMap, jumpkey))respawnkeydown=0;
-                                                       if(IsKeyDown(theKeyMap, jumpkey))respawnkeydown=1;
+                                                       if(!Input::isKeyDown(jumpkey))respawnkeydown=0;
+                                                       if(Input::isKeyDown(jumpkey))respawnkeydown=1;
 
 
 
 
-                                                       if(whichlevel!=-2&&IsKeyDown(theKeyMap, MAC_K_KEY)&&IsKeyDown(theKeyMap, MAC_SHIFT_KEY)&&!slomotogglekeydown&&debugmode&&!editorenabled){
+                                                       if(whichlevel!=-2&&Input::isKeyDown(SDLK_k)&&Input::isKeyDown(SDLK_LSHIFT)&&!slomotogglekeydown&&debugmode&&!editorenabled){
                                                                targetlevel++;
                                                                if(targetlevel>numchallengelevels-1)targetlevel=0;
                                                                loading=1;
                                                                leveltime=5;
                                                                slomotogglekeydown=1;
                                                        }
-
-                                                       /*
-                                                       if(IsKeyDown(theKeyMap, MAC_Z_KEY)){
-                                                       //Respawn
-                                                       OPENAL_SetPaused(channels[whooshsound], true);
-                                                       changedelay=0;
-                                                       for(k=0;k<numplayers;k++){
-                                                       player[k].dead=0;
-                                                       player[k].damage=0;
-                                                       player[k].permanentdamage=0;
-                                                       if(player[k].skeleton.free==2)player[k].skeleton.free=1;
-                                                       player[k].aitype=passivetype;
-                                                       }
-                                                       player[0].aitype=playercontrolled;
-                                                       }
-                                                       */
-
                                                        static bool movekey;
                                                        static bool connected;
-                                                       /*player[0].forwardkeydown=IsKeyDown(theKeyMap, MAC_W_KEY);
-                                                       player[0].leftkeydown=IsKeyDown(theKeyMap, MAC_A_KEY);
-                                                       player[0].backkeydown=IsKeyDown(theKeyMap, MAC_S_KEY);
-                                                       player[0].rightkeydown=IsKeyDown(theKeyMap, MAC_D_KEY);
-                                                       player[0].jumpkeydown=IsKeyDown(theKeyMap, MAC_SPACE_KEY);
-                                                       player[0].crouchkeydown=IsKeyDown(theKeyMap, MAC_SHIFT_KEY);*/
-
-                                                       //if(!player[0].crouchkeydown)player[0].crouchkeydown=IsKeyDown(theKeyMap, MAC_CONTROL_KEY);
-
+                                                       
                for(int i=0;i<numplayers;i++){
                                                                if(!player[i].skeleton.free){
                                                                        oldtargetrotation=player[i].targetrotation;
@@ -8042,21 +6267,6 @@ void     Game::Tick()
                                                                                                                                        else player[i].targetrotation-=90;
                                                                                                                                }
                                                                                                                        }
-                                                                                                                       /*if(findDistancefast(&player[i].coords,&weapons.position[player[i].ally])<3){
-                                                                                                                       if(abs(Random()%6)){
-                                                                                                                       player[i].crouchkeydown=1;
-                                                                                                                       if(!findDistancefast(&player[i].coords,&weapons.position[player[i].ally])<1){
-                                                                                                                       if(player[i].isRun()){
-                                                                                                                       player[i].targetframe=0;
-                                                                                                                       player[i].target=0;
-                                                                                                                       player[i].targetanimation=sneakanim;
-                                                                                                                       }
-                                                                                                                       }
-                                                                                                                       else player[i].forwardkeydown=0;
-                                                                                                                       }
-                                                                                                                       else player[i].crouchkeydown=0;
-                                                                                                                       }
-                                                                                                                       else player[i].crouchkeydown=0;*/
                                                                                                                }
 
                                                                                                                player[i].leftkeydown=0;
@@ -8198,21 +6408,9 @@ void     Game::Tick()
                                                                                                                                player[i].throwkeydown=0;
 
                                                                                                                                if(player[i].avoidcollided>.8&&!player[i].jumpkeydown&&player[i].collided<.8)player[i].targetrotation+=90*(player[i].whichdirection*2-1);
-                                                                                                                               /*for(j=0;j<numplayers;j++){
-                                                                                                                               if(player[j].victim->id==i&&(player[j].targetanimation==spinkickanim&&player[j].targetframe<3)){
-                                                                                                                               player[i].crouchkeydown=1;
-                                                                                                                               }
-                                                                                                                               }*/
                                                                                                                                if(Random()%2==0/*||player[0].weaponactive!=-1*/||player[i].weaponactive!=-1||player[i].creature==wolftype)player[i].attackkeydown=1;
                                                                                                                                else player[i].attackkeydown=0;
                                                                                                                                if((player[i].isRun())&&Random()%6&&findDistancefast(&player[i].coords,&player[0].coords)>7)player[i].attackkeydown=0;
-                                                                                                                               //if(player[i].attackkeydown&&findDistancefast(&player[i].coords,&player[0].coords)<3&&player[i].targetanimation!=runanim&&!player[0].skeleton.free)player[i].crouchkeydown=1;
-                                                                                                                               /*if(player[0].targetanimation==rabbitkickanim&&!player[0].skeleton.free){
-                                                                                                                               player[i].attackkeydown=0;
-                                                                                                                               if(player[i].isIdle())player[i].crouchkeydown=1;
-                                                                                                                               player[i].forwardkeydown=0;
-                                                                                                                               player[i].aiupdatedelay=.02;
-                                                                                                                               }*/
 
                                                                                                                                if(player[i].aitype!=playercontrolled&&(player[i].isIdle()||player[i].isCrouch()||player[i].isRun())){
                                                                                                                                        target=-2;
@@ -8392,20 +6590,8 @@ void     Game::Tick()
                                                                                                                                if((((weapons.velocity[j].x==0&&weapons.velocity[j].y==0&&weapons.velocity[j].z==0)||player[i].aitype==playercontrolled)&&weapons.owner[j]==-1)||(player[i].victim&&weapons.owner[j]==player[i].victim->id))
                                                                                                                                        if(findDistancefastflat(&player[i].coords,&weapons.position[j])<2&&player[i].weaponactive==-1){
                                                                                                                                                if(findDistancefast(&player[i].coords,&weapons.position[j])<1||player[i].victim){
-                                                                                                                                                       float gLoc[3];
-                                                                                                                                                       float vel[3];
-                                                                                                                                                       gLoc[0]=player[i].coords.x;
-                                                                                                                                                       gLoc[1]=player[i].coords.y;
-                                                                                                                                                       gLoc[2]=player[i].coords.z;
-                                                                                                                                                       vel[0]=player[i].velocity.x;
-                                                                                                                                                       vel[1]=player[i].velocity.y;
-                                                                                                                                                       vel[2]=player[i].velocity.z;
-                                                                                                                                                       if(weapons.type[j]!=staff){
-                                                                                                                                                               PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                                                                                                               OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                                                                                                               OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                                                                                                               OPENAL_SetPaused(channels[knifedrawsound], false);
-                                                                                                                                                       }
+                                                                                                                                                       if(weapons.type[j]!=staff)
+                                                                                                                                                         emit_sound_at(knifedrawsound, player[i].coords, 128.);
 
                                                                                                                                                        player[i].weaponactive=0;
                                                                                                                                                        weapons.owner[j]=player[i].id;
@@ -8439,20 +6625,8 @@ void     Game::Tick()
                                                                                                                                        if(player[i].weaponactive==-1)
                                                                                                                                                if((((weapons.velocity[k].x==0&&weapons.velocity[k].y==0&&weapons.velocity[k].z==0)||player[i].aitype==playercontrolled)&&weapons.owner[k]==-1)||(player[i].victim&&weapons.owner[k]==player[i].victim->id))
                                                                                                                                                        if(findDistancefastflat(&player[i].coords,&weapons.position[k])<3&&player[i].weaponactive==-1){
-                                                                                                                                                               float gLoc[3];
-                                                                                                                                                               float vel[3];
-                                                                                                                                                               gLoc[0]=player[i].coords.x;
-                                                                                                                                                               gLoc[1]=player[i].coords.y;
-                                                                                                                                                               gLoc[2]=player[i].coords.z;
-                                                                                                                                                               vel[0]=player[i].velocity.x;
-                                                                                                                                                               vel[1]=player[i].velocity.y;
-                                                                                                                                                               vel[2]=player[i].velocity.z;
-                                                                                                                                                               if(weapons.type[k]!=staff){
-                                                                                                                                                                       PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                                                                                                                       OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                                                                                                                       OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                                                                                                                       OPENAL_SetPaused(channels[knifedrawsound], false);
-                                                                                                                                                               }
+                                                                                                                                                               if(weapons.type[k]!=staff)
+                                                                                                                                                                 emit_sound_at(knifedrawsound, player[i].coords, 128.);
 
                                                                                                                                                                player[i].weaponactive=0;
                                                                                                                                                                weapons.owner[k]=player[i].id;
@@ -8492,14 +6666,6 @@ void     Game::Tick()
                                                                                                                                                player[i].hasvictim=1;
                                                                                                                                                int k = player[j].weaponids[0];
                                                                                                                                                if(player[i].hasvictim){
-                                                                                                                                                       float gLoc[3];
-                                                                                                                                                       float vel[3];
-                                                                                                                                                       gLoc[0]=player[i].coords.x;
-                                                                                                                                                       gLoc[1]=player[i].coords.y;
-                                                                                                                                                       gLoc[2]=player[i].coords.z;
-                                                                                                                                                       vel[0]=player[i].velocity.x;
-                                                                                                                                                       vel[1]=player[i].velocity.y;
-                                                                                                                                                       vel[2]=player[i].velocity.z;
                                                                                                                                                        bool fleshstuck;
                                                                                                                                                        fleshstuck=0;
                                                                                                                                                        if(player[i].victim->weaponstuck!=-1){
@@ -8508,19 +6674,11 @@ void    Game::Tick()
                                                                                                                                                                }
                                                                                                                                                        }
                                                                                                                                                        if(!fleshstuck){
-                                                                                                                                                               if(weapons.type[k]!=staff){
-                                                                                                                                                                       PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                                                                                                                       OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                                                                                                                       OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                                                                                                                       OPENAL_SetPaused(channels[knifedrawsound], false);
-                                                                                                                                                               }
-                                                                                                                                                       }
-                                                                                                                                                       if(fleshstuck){
-                                                                                                                                                               PlaySoundEx( fleshstabremovesound, samp[fleshstabremovesound], NULL, true);
-                                                                                                                                                               OPENAL_3D_SetAttributes(channels[fleshstabremovesound], gLoc, vel);
-                                                                                                                                                               OPENAL_SetVolume(channels[fleshstabremovesound], 128);
-                                                                                                                                                               OPENAL_SetPaused(channels[fleshstabremovesound], false);
+                                                                                                                                                               if(weapons.type[k]!=staff)
+                                                                                                                                                                 emit_sound_at(knifedrawsound, player[i].coords, 128.);
                                                                                                                                                        }
+                                                                                                                                                       if(fleshstuck)
+                                                                                                                                                         emit_sound_at(fleshstabremovesound, player[i].coords, 128.);
 
                                                                                                                                                        player[i].weaponactive=0;
                                                                                                                                                        if(weapons.owner[k]!=-1){
@@ -8545,7 +6703,7 @@ void      Game::Tick()
                                                                                                                                                                footpoint=weapons.position[k];
                                                                                                                                                                if(player[i].victim->weaponstuck!=-1){
                                                                                                                                                                        if(player[i].victim->weaponids[player[i].victim->weaponstuck]==k){
-                                                                                                                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
+                                                                                                                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
                                                                                                                                                                                weapons.bloody[k]=2;
                                                                                                                                                                                weapons.blooddrip[k]=5;
                                                                                                                                                                                player[i].victim->weaponstuck=-1;
@@ -8934,26 +7092,10 @@ void    Game::Tick()
                                                                                                                player[i].coords.y+=.2;
                                                                                                                player[i].jumppower-=1;
 
-                                                                                                               static float gLoc[3];
-                                                                                                               static float vel[3];
-                                                                                                               gLoc[0]=player[i].coords.x;
-                                                                                                               gLoc[1]=player[i].coords.y;
-                                                                                                               gLoc[2]=player[i].coords.z;
-                                                                                                               vel[0]=player[i].velocity.x;
-                                                                                                               vel[1]=player[i].velocity.y;
-                                                                                                               vel[2]=player[i].velocity.z;
-
-                                                                                                               if(i==0){
-                                                                                                                       PlaySoundEx( whooshsound, samp[whooshsound], NULL, true);
-                                                                                                                       OPENAL_3D_SetAttributes(channels[whooshsound], gLoc, vel);
-                                                                                                                       OPENAL_SetVolume(channels[whooshsound], 128);
-                                                                                                                       OPENAL_SetPaused(channels[whooshsound], false);
-                                                                                                               }
+                                                                                                               if (!i)
+                                                                                                                 emit_sound_at(whooshsound, player[i].coords, 128.);
 
-                                                                                                               PlaySoundEx( jumpsound, samp[jumpsound], NULL, true);
-                                                                                                               OPENAL_3D_SetAttributes(channels[jumpsound], gLoc, vel);
-                                                                                                               OPENAL_SetVolume(channels[jumpsound], 128);
-                                                                                                               OPENAL_SetPaused(channels[jumpsound], false);
+                                                                                                               emit_sound_at(jumpsound, player[i].coords, 128.);
                                                                                                }
                                                                                                if((player[i].isIdle())&&player[i].jumppower>1){
                                                                                                        player[i].targetanimation=player[i].getLanding();
@@ -9045,225 +7187,148 @@ void  Game::Tick()
 
                                                        for(k=0;k<numplayers;k++){
                                                                player[k].DoAnimations();
-                                                               player[k].whichpatchx=player[k].coords.x/(terrain.size/subdivision*terrain.scale*terraindetail);
-                                                               player[k].whichpatchz=player[k].coords.z/(terrain.size/subdivision*terrain.scale*terraindetail);
+                                                               player[k].whichpatchx=player[k].coords.x/(terrain.size/subdivision*terrain.scale);
+                                                               player[k].whichpatchz=player[k].coords.z/(terrain.size/subdivision*terrain.scale);
                                                        }
 
                                                        objects.DoStuff();
-                                                       /*
-                                                       player[0].righthandmorphstart=0;
-                                                       player[0].righthandmorphend=1;
-                                                       player[0].lefthandmorphstart=0;
-                                                       player[0].lefthandmorphend=1;
-                                                       player[0].headmorphstart=0;
-                                                       player[0].headmorphend=2;*/
-
-                                                       /*
-                                                       if(IsKeyDown( theKeyMap, MAC_P_KEY )){
-                                                       if(player[0].righthandmorphend!=1)player[0].righthandmorphness=0;
-                                                       player[0].righthandmorphend=1;
-                                                       player[0].targetrighthandmorphness=1;
-
-                                                       if(player[0].lefthandmorphend!=0)player[0].lefthandmorphness=0;
-                                                       player[0].lefthandmorphend=0;
-                                                       player[0].targetlefthandmorphness=1;
-
-                                                       if(player[0].headmorphend!=2)player[0].headmorphness=0;
-                                                       player[0].headmorphend=2;
-                                                       player[0].targetheadmorphness=1;
-                                                       }
-                                                       if(IsKeyDown( theKeyMap, MAC_L_KEY )){
-                                                       if(player[0].righthandmorphend!=0)player[0].righthandmorphness=0;
-                                                       player[0].righthandmorphend=0;
-                                                       player[0].targetrighthandmorphness=1;
-
-                                                       if(player[0].lefthandmorphend!=1)player[0].lefthandmorphness=0;
-                                                       player[0].lefthandmorphend=1;
-                                                       player[0].targetlefthandmorphness=1;
-
-                                                       if(player[0].headmorphend!=0)player[0].headmorphness=0;
-                                                       player[0].headmorphend=0;
-                                                       player[0].targetheadmorphness=1;
+                                                       
+                                                       for(j=numenvsounds-1;j>=0;j--){
+                                                               envsoundlife[j]-=multiplier;
+                                                               if(envsoundlife[j]<0){
+                                                                       numenvsounds--;
+                                                                       envsoundlife[j]=envsoundlife[numenvsounds];
+                                                                       envsound[j]=envsound[numenvsounds];
+                                                               }
                                                        }
-                                                       */
-                                                       if(numenvsounds!=0)
-                                                               for(j=numenvsounds-1;j>=0;j--){
-                                                                       envsoundlife[j]-=multiplier;
-                                                                       if(envsoundlife[j]<0){
-                                                                               numenvsounds--;
-                                                                               envsoundlife[j]=envsoundlife[numenvsounds];
-                                                                               envsound[j]=envsound[numenvsounds];
+                                                       if(slomo) OPENAL_SetFrequency(OPENAL_ALL, slomofreq);
+                                                       else OPENAL_SetFrequency(OPENAL_ALL, 22050);
+
+                                                       if(tutoriallevel==1){
+                                                               XYZ temp;
+                                                               XYZ temp2;
+                                                               XYZ temp3;
+                                                               XYZ oldtemp;
+                                                               XYZ oldtemp2;
+                                                               temp.x=1011;
+                                                               temp.y=84;
+                                                               temp.z=491;
+                                                               temp2.x=1025;
+                                                               temp2.y=75;
+                                                               temp2.z=447;
+                                                               temp3.x=1038;
+                                                               temp3.y=76;
+                                                               temp3.z=453;
+                                                               oldtemp=temp;
+                                                               oldtemp2=temp2;
+                                                               if(tutorialstage>=51)
+                                                                       if(findDistancefast(&temp,&player[0].coords)>=findDistancefast(&temp,&temp2)-1||findDistancefast(&temp3,&player[0].coords)<4){
+                                                                               OPENAL_StopSound(OPENAL_ALL);  // hack...OpenAL renderer isn't stopping music after tutorial goes to level menu...
+                                                                               OPENAL_SetFrequency(OPENAL_ALL, 0.001);
+
+                                                                               emit_stream_np(stream_music3);
+
+                                                                               gameon=0;
+                                                                               mainmenu=5;
+
+                                                                               fireSound();
+
+                                                                               flash();
                                                                        }
-                                                               }
-                                                               if(!slomo)OPENAL_SetFrequency(OPENAL_ALL, 22050);
-                                                               if(slomo)OPENAL_SetFrequency(OPENAL_ALL, slomofreq);
-
-                                                               if(tutoriallevel==1){
-                                                                       XYZ temp;
-                                                                       XYZ temp2;
-                                                                       XYZ temp3;
-                                                                       XYZ oldtemp;
-                                                                       XYZ oldtemp2;
-                                                                       temp.x=1011;
-                                                                       temp.y=84;
-                                                                       temp.z=491;
-                                                                       temp2.x=1025;
-                                                                       temp2.y=75;
-                                                                       temp2.z=447;
-                                                                       temp3.x=1038;
-                                                                       temp3.y=76;
-                                                                       temp3.z=453;
-                                                                       oldtemp=temp;
-                                                                       oldtemp2=temp2;
-                                                                       if(tutorialstage>=51)
+                                                                       if(tutorialstage<51)
                                                                                if(findDistancefast(&temp,&player[0].coords)>=findDistancefast(&temp,&temp2)-1||findDistancefast(&temp3,&player[0].coords)<4){
-                                                   OPENAL_StopSound(OPENAL_ALL);  // hack...OpenAL renderer isn't stopping music after tutorial goes to level menu...
-                                                                                       OPENAL_SetFrequency(OPENAL_ALL, 0.001);
-
-                                                                                       PlayStreamEx( stream_music3, strm[stream_music3], NULL, true);
-                                                                                       OPENAL_SetPaused(channels[stream_music3], false);
-                                                                                       OPENAL_SetVolume(channels[stream_music3], 256);
-
-                                                                                       gameon=0;
-                                                                                       mainmenu=5;
-
-                                                                                       float gLoc[3]={0,0,0};
-                                                                                       float vel[3]={0,0,0};
-                                                                                       OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                                                                                       PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[fireendsound], 256);
-                                                                                       OPENAL_SetPaused(channels[fireendsound], false);
-                                                                                       OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                                                                                       flashr=1;
-                                                                                       flashg=0;
-                                                                                       flashb=0;
-                                                                                       flashamount=1;
-                                                                                       flashdelay=1;
+                                                                                       emit_sound_at(fireendsound, player[0].coords);
+
+                                                                                       player[0].coords=(oldtemp+oldtemp2)/2;
+
+                                                                                       flash();
                                                                                }
-                                                                               if(tutorialstage<51)
-                                                                                       if(findDistancefast(&temp,&player[0].coords)>=findDistancefast(&temp,&temp2)-1||findDistancefast(&temp3,&player[0].coords)<4){
-                                                                                               float gLoc[3];
-                                                                                               float vel[3];
-                                                                                               gLoc[0]=player[0].coords.x;
-                                                                                               gLoc[1]=player[0].coords.y;
-                                                                                               gLoc[2]=player[0].coords.z;
-                                                                                               vel[0]=0;
-                                                                                               vel[1]=0;
-                                                                                               vel[2]=0;
-                                                                                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[fireendsound], 256);
-                                                                                               OPENAL_SetPaused(channels[fireendsound], false);
-
-                                                                                               player[0].coords=(oldtemp+oldtemp2)/2;
-
-                                                                                               flashr=1;
-                                                                                               flashg=1;
-                                                                                               flashb=1;
-                                                                                               flashamount=1;
-                                                                                               flashdelay=1;
-                                                                                       }
-                                                                                       if(tutorialstage>=14&&tutorialstage<50)
-                                                                                               if(findDistancefast(&temp,&player[1].coords)>=findDistancefast(&temp,&temp2)-1||findDistancefast(&temp3,&player[1].coords)<4){
-                                                                                                       float gLoc[3];
-                                                                                                       float vel[3];
-                                                                                                       gLoc[0]=player[1].coords.x;
-                                                                                                       gLoc[1]=player[1].coords.y;
-                                                                                                       gLoc[2]=player[1].coords.z;
-                                                                                                       vel[0]=0;
-                                                                                                       vel[1]=0;
-                                                                                                       vel[2]=0;
-                                                                                                       PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                                                                       OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                                                                       OPENAL_SetVolume(channels[fireendsound], 256);
-                                                                                                       OPENAL_SetPaused(channels[fireendsound], false);
-
-                                                                                                       for(int i=0;i<player[1].skeleton.num_joints;i++){
-                                                                                                               if(Random()%2==0){
-                                                                                                                       if(!player[1].skeleton.free)temp2=(player[1].coords-player[1].oldcoords)/multiplier/2;//velocity/2;
-                                                                                                                       if(player[1].skeleton.free)temp2=player[1].skeleton.joints[i].velocity*player[1].scale/2;
-                                                                                                                       if(!player[1].skeleton.free)temp=DoRotation(DoRotation(DoRotation(player[1].skeleton.joints[i].position,0,0,player[1].tilt),player[1].tilt2,0,0),0,player[1].rotation,0)*player[1].scale+player[1].coords;
-                                                                                                                       if(player[1].skeleton.free)temp=player[1].skeleton.joints[i].position*player[1].scale+player[1].coords;
-                                                                                                                       sprites.MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
-                                                                                                               }
+                                                                               if(tutorialstage>=14&&tutorialstage<50)
+                                                                                       if(findDistancefast(&temp,&player[1].coords)>=findDistancefast(&temp,&temp2)-1||findDistancefast(&temp3,&player[1].coords)<4){
+                                                                                               emit_sound_at(fireendsound, player[1].coords);
+
+                                                                                               for(int i=0;i<player[1].skeleton.num_joints;i++){
+                                                                                                       if(Random()%2==0){
+                                                                                                               if(!player[1].skeleton.free)temp2=(player[1].coords-player[1].oldcoords)/multiplier/2;//velocity/2;
+                                                                                                               if(player[1].skeleton.free)temp2=player[1].skeleton.joints[i].velocity*player[1].scale/2;
+                                                                                                               if(!player[1].skeleton.free)temp=DoRotation(DoRotation(DoRotation(player[1].skeleton.joints[i].position,0,0,player[1].tilt),player[1].tilt2,0,0),0,player[1].rotation,0)*player[1].scale+player[1].coords;
+                                                                                                               if(player[1].skeleton.free)temp=player[1].skeleton.joints[i].position*player[1].scale+player[1].coords;
+                                                                                                               Sprite::MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
                                                                                                        }
+                                                                                               }
 
-                                                                                                       player[1].coords=(oldtemp+oldtemp2)/2;
-                                                                                                       for(int i=0;i<player[1].skeleton.num_joints;i++){
-                                                                                                               player[1].skeleton.joints[i].velocity=0;
-                                                                                                               if(Random()%2==0){
-                                                                                                                       if(!player[1].skeleton.free)temp2=(player[1].coords-player[1].oldcoords)/multiplier/2;//velocity/2;
-                                                                                                                       if(player[1].skeleton.free)temp2=player[1].skeleton.joints[i].velocity*player[1].scale/2;
-                                                                                                                       if(!player[1].skeleton.free)temp=DoRotation(DoRotation(DoRotation(player[1].skeleton.joints[i].position,0,0,player[1].tilt),player[1].tilt2,0,0),0,player[1].rotation,0)*player[1].scale+player[1].coords;
-                                                                                                                       if(player[1].skeleton.free)temp=player[1].skeleton.joints[i].position*player[1].scale+player[1].coords;
-                                                                                                                       sprites.MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
-                                                                                                               }
+                                                                                               player[1].coords=(oldtemp+oldtemp2)/2;
+                                                                                               for(int i=0;i<player[1].skeleton.num_joints;i++){
+                                                                                                       player[1].skeleton.joints[i].velocity=0;
+                                                                                                       if(Random()%2==0){
+                                                                                                               if(!player[1].skeleton.free)temp2=(player[1].coords-player[1].oldcoords)/multiplier/2;//velocity/2;
+                                                                                                               if(player[1].skeleton.free)temp2=player[1].skeleton.joints[i].velocity*player[1].scale/2;
+                                                                                                               if(!player[1].skeleton.free)temp=DoRotation(DoRotation(DoRotation(player[1].skeleton.joints[i].position,0,0,player[1].tilt),player[1].tilt2,0,0),0,player[1].rotation,0)*player[1].scale+player[1].coords;
+                                                                                                               if(player[1].skeleton.free)temp=player[1].skeleton.joints[i].position*player[1].scale+player[1].coords;
+                                                                                                               Sprite::MakeSprite(breathsprite, temp,temp2, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
                                                                                                        }
                                                                                                }
-                                                               }
+                                                                                       }
+                                                       }
 
 
-                                                               //3d sound
-                                                               static float gLoc[3];
-                                                               gLoc[0]=viewer.x;
-                                                               gLoc[1]=viewer.y;
-                                                               gLoc[2]=viewer.z;
-                                                               static float vel[3];
-                                                               vel[0]=(viewer.x-oldviewer.x)/multiplier;
-                                                               vel[1]=(viewer.y-oldviewer.y)/multiplier;
-                                                               vel[2]=(viewer.z-oldviewer.z)/multiplier;
+                                                       //3d sound
+                                                       static float gLoc[3];
+                                                       gLoc[0]=viewer.x;
+                                                       gLoc[1]=viewer.y;
+                                                       gLoc[2]=viewer.z;
+                                                       static float vel[3];
+                                                       vel[0]=(viewer.x-oldviewer.x)/multiplier;
+                                                       vel[1]=(viewer.y-oldviewer.y)/multiplier;
+                                                       vel[2]=(viewer.z-oldviewer.z)/multiplier;
 
-                                                               //Set orientation with forward and up vectors
-                                                               static XYZ upvector;
-                                                               upvector=0;
-                                                               upvector.z=-1;
+                                                       //Set orientation with forward and up vectors
+                                                       static XYZ upvector;
+                                                       upvector=0;
+                                                       upvector.z=-1;
 
-                                                               upvector=DoRotation(upvector,-rotation2+90,0,0);
-                                                               upvector=DoRotation(upvector,0,0-rotation,0);
+                                                       upvector=DoRotation(upvector,-rotation2+90,0,0);
+                                                       upvector=DoRotation(upvector,0,0-rotation,0);
 
-                                                               facing=0;
-                                                               facing.z=-1;
+                                                       facing=0;
+                                                       facing.z=-1;
 
-                                                               facing=DoRotation(facing,-rotation2,0,0);
-                                                               facing=DoRotation(facing,0,0-rotation,0);
+                                                       facing=DoRotation(facing,-rotation2,0,0);
+                                                       facing=DoRotation(facing,0,0-rotation,0);
 
 
-                                                               static float ori[6];
-                                                               ori[0] = -facing.x;
-                                                               ori[1] = facing.y;
-                                                               ori[2] = -facing.z;
-                                                               ori[3] = -upvector.x;
-                                                               ori[4] = upvector.y;
-                                                               ori[5] = -upvector.z;
+                                                       static float ori[6];
+                                                       ori[0] = -facing.x;
+                                                       ori[1] = facing.y;
+                                                       ori[2] = -facing.z;
+                                                       ori[3] = -upvector.x;
+                                                       ori[4] = upvector.y;
+                                                       ori[5] = -upvector.z;
 
-                                                               OPENAL_3D_Listener_SetAttributes(&gLoc[0], &vel[0], ori[0], ori[1], ori[2], ori[3], ori[4], ori[5]);
-                                                               OPENAL_Update();
+                                                       OPENAL_3D_Listener_SetAttributes(&gLoc[0], &vel[0], ori[0], ori[1], ori[2], ori[3], ori[4], ori[5]);
+                                                       OPENAL_Update();
 
-                                                               oldviewer=viewer;
+                                                       oldviewer=viewer;
                }
        }
 
-       if(IsKeyDown(theKeyMap, MAC_F1_KEY)&&!freezetogglekeydown){
+       if(Input::isKeyDown(SDLK_F1)&&!freezetogglekeydown){
                Screenshot();
                freezetogglekeydown=1;
        }
 }
 
 void   Game::TickOnce(){
-       //if(!console){
-       if(!mainmenu)
-               if(directing||indialogue==-1){
+       if(mainmenu)
+               rotation+=multiplier*5;
+       else
+               if(directing||indialogue==-1) {
                        rotation+=deltah*.7;
                        if(!invertmouse)rotation2+=deltav*.7;
                        if(invertmouse)rotation2-=deltav*.7;
                        if(rotation2>90)rotation2=90;
                        if(rotation2<-70)rotation2=-70;
                }
-               if(mainmenu)rotation+=multiplier*5;
-      
-               //}
 }
 
 void   Game::TickOnceAfter(){
@@ -9319,17 +7384,7 @@ void     Game::TickOnceAfter(){
 
                if(musictoggle){
                        if(musictype!=oldmusictype&&musictype==stream_music2){
-                               static float gLoc[3];
-                               static float vel[3];
-                               gLoc[0]=cameraloc.x;
-                               gLoc[1]=cameraloc.y;
-                               gLoc[2]=cameraloc.z;
-                               vel[0]=0;
-                               vel[1]=0;
-                               vel[2]=0;
-                               PlaySoundEx( alarmsound, samp[alarmsound], NULL, true);
-                               OPENAL_SetVolume(channels[alarmsound], 512);
-                               OPENAL_SetPaused(channels[alarmsound], false);
+                               emit_sound_np(alarmsound);
 
                        }
                }
@@ -9341,14 +7396,6 @@ void     Game::TickOnceAfter(){
                else musicvolume[1]-=multiplier*450;
                if(musicselected==stream_music3)musicvolume[2]+=multiplier*450;
                else musicvolume[2]-=multiplier*450;
-               /*
-               if(musicselected==music1)musicvolume[0]+=multiplier*100;
-               else musicvolume[0]-=multiplier*450;
-               if(musicselected==music2)musicvolume[1]+=multiplier*150;
-               else if(player[0].dead)musicvolume[1]-=multiplier*450;
-               else musicvolume[1]-=multiplier*100;
-               if(musicselected==music3)musicvolume[2]+=multiplier*450;
-               else musicvolume[2]-=multiplier*450;*/
 
                for(i=0;i<3;i++){
                        if(musicvolume[i]<0)musicvolume[i]=0;
@@ -9358,40 +7405,20 @@ void    Game::TickOnceAfter(){
                if(musicvolume[2]>128&&!loading&&!mainmenu)musicvolume[2]=128;
 
                if(musictoggle){
-                       if(musicvolume[0]>0&&oldmusicvolume[0]<=0){
-                               PlayStreamEx( music1, strm[music1], NULL, true);
-                               OPENAL_SetPaused(channels[music1], false);
-                       }
-                       if(musicvolume[1]>0&&oldmusicvolume[1]<=0){
-                               PlayStreamEx( stream_music2, strm[stream_music2], NULL, true);
-                               OPENAL_SetPaused(channels[stream_music2], false);
-                       }
-                       if(musicvolume[2]>0&&oldmusicvolume[2]<=0){
-                               PlayStreamEx( stream_music3, strm[stream_music3], NULL, true);
-                               OPENAL_SetPaused(channels[stream_music3], false);
-                       }
-               }
-
-               if(!musictoggle){
-                       OPENAL_SetPaused(channels[music1], true);
-                       OPENAL_SetPaused(channels[stream_music2], true);
-                       OPENAL_SetPaused(channels[stream_music3], true);
-
-                       for(i=0;i<4;i++){
-                               oldmusicvolume[i]=0;
-                               musicvolume[i]=0;
-                       }
-               }
-
-               if(musictoggle){
+                       if(musicvolume[0]>0&&oldmusicvolume[0]<=0)
+                         emit_stream_np(music1, musicvolume[0]);
+                       if(musicvolume[1]>0&&oldmusicvolume[1]<=0)
+                         emit_stream_np(stream_music2, musicvolume[1]);
+                       if(musicvolume[2]>0&&oldmusicvolume[2]<=0)
+                         emit_stream_np(stream_music3, musicvolume[2]);
                        if(musicvolume[0]<=0&&oldmusicvolume[0]>0){
-                               OPENAL_SetPaused(channels[music1], true);
+                               pause_sound(music1);
                        }
                        if(musicvolume[1]<=0&&oldmusicvolume[1]>0){
-                               OPENAL_SetPaused(channels[stream_music2], true);
+                               pause_sound(stream_music2);
                        }
                        if(musicvolume[2]<=0&&oldmusicvolume[2]>0){
-                               OPENAL_SetPaused(channels[stream_music3], true);
+                               pause_sound(stream_music3);
                        }
 
                        if(musicvolume[0]!=oldmusicvolume[0]){
@@ -9407,334 +7434,243 @@ void  Game::TickOnceAfter(){
                        for(i=0;i<3;i++){
                                oldmusicvolume[i]=musicvolume[i];
                        }
+               } else {
+                       pause_sound(music1);
+                       pause_sound(stream_music2);
+                       pause_sound(stream_music3);
+
+                       for(i=0;i<4;i++){
+                               oldmusicvolume[i]=0;
+                               musicvolume[i]=0;
+                       }
                }
 
                killhotspot=2;
-               if(numhotspots)
-                       for(i=0;i<numhotspots;i++){
-                               if(hotspottype[i]>10&&hotspottype[i]<20){
-                                       if(player[hotspottype[i]-10].dead==0){
-                                               killhotspot=0;
-                                       }
-                                       else if(killhotspot==2)
-                                               killhotspot=1;
+               for(i=0;i<numhotspots;i++){
+                       if(hotspottype[i]>10&&hotspottype[i]<20){
+                               if(player[hotspottype[i]-10].dead==0){
+                                       killhotspot=0;
                                }
+                               else if(killhotspot==2)
+                                       killhotspot=1;
                        }
-                       if(killhotspot==2)killhotspot=0;
+               }
+               if(killhotspot==2)killhotspot=0;
 
 
-                       winhotspot=0;
-                       if(numhotspots)
-                               for(i=0;i<numhotspots;i++){
-                                       if(hotspottype[i]==-1){
-                                               if(findDistancefast(&player[0].coords,&hotspot[i])<hotspotsize[i])
-                                                       winhotspot=1;
-                                       }
-                               }
+               winhotspot=0;
+               for(i=0;i<numhotspots;i++){
+                       if(hotspottype[i]==-1){
+                               if(findDistancefast(&player[0].coords,&hotspot[i])<hotspotsize[i])
+                                       winhotspot=1;
+                       }
+               }
 
-                               int numalarmed=0;
-                               if(numplayers>1)
-                                       for(i=1;i<numplayers;i++){
-                                               if(!player[i].dead&&player[i].aitype==attacktypecutoff&&player[i].surprised<=0)numalarmed++;
-                                       }
-                                       if(numalarmed>maxalarmed)maxalarmed=numalarmed;
+               int numalarmed=0;
+               for(i=1;i<numplayers;i++){
+                       if(!player[i].dead&&player[i].aitype==attacktypecutoff&&player[i].surprised<=0)numalarmed++;
+               }
+               if(numalarmed>maxalarmed)maxalarmed=numalarmed;
 
-                                       if(changedelay<=0&&!loading&&!editorenabled&&gameon&&!tutoriallevel&&changedelay!=-999&&!won){
-                                               if(player[0].dead&&changedelay<=0){
-                                                       changedelay=1;
-                                                       targetlevel=whichlevel;
-                                               }
-                                               alldead=1;
-                                               if(numplayers>1)
-                                                       for(i=1;i<numplayers;i++){
-                                                               if(!player[i].dead&&player[i].howactive<typedead1)alldead=0;
-                                                       }
+               if(changedelay<=0&&!loading&&!editorenabled&&gameon&&!tutoriallevel&&changedelay!=-999&&!won){
+                       if(player[0].dead&&changedelay<=0){
+                               changedelay=1;
+                               targetlevel=whichlevel;
+                       }
+                       alldead=1;
+                       for(i=1;i<numplayers;i++){
+                               if(!player[i].dead&&player[i].howactive<typedead1)alldead=0;
+                       }
 
 
-                                                       if(alldead&&!player[0].dead&&maptype==mapkilleveryone){
-                                                               changedelay=1;
-                                                               targetlevel=whichlevel+1;
-                                                               if(targetlevel>numchallengelevels-1)targetlevel=0;
-                                                       }
-                                                       if(winhotspot||windialogue){
-                                                               changedelay=0.1;
-                                                               targetlevel=whichlevel+1;
-                                                               if(targetlevel>numchallengelevels-1)targetlevel=0;
-                                                       }
+                       if(alldead&&!player[0].dead&&maptype==mapkilleveryone){
+                               changedelay=1;
+                               targetlevel=whichlevel+1;
+                               if(targetlevel>numchallengelevels-1)targetlevel=0;
+                       }
+                       if(winhotspot||windialogue){
+                               changedelay=0.1;
+                               targetlevel=whichlevel+1;
+                               if(targetlevel>numchallengelevels-1)targetlevel=0;
+                       }
 
 
-                                                       if(killhotspot){
-                                                               changedelay=1;
-                                                               targetlevel=whichlevel+1;
-                                                               if(targetlevel>numchallengelevels-1)targetlevel=0;
-                                                       }
+                       if(killhotspot){
+                               changedelay=1;
+                               targetlevel=whichlevel+1;
+                               if(targetlevel>numchallengelevels-1)targetlevel=0;
+                       }
 
-                                                       if(changedelay>0&&!player[0].dead&&!won){
-                                                               //high scores, awards, win
-                                                               if(campaign){
-                                                                       won=1;
-                                                                       accountcampaignchoices[accountactive][accountcampaignchoicesmade[accountactive]]=whichchoice;
-                                                                       accountcampaignchoicesmade[accountactive]++;
-                                                                       accountcampaignscore[accountactive]+=bonustotal;
-                                                                       scoreadded=1;
-                                                                       accountcampaigntime[accountactive]+=leveltime;
-                                                                       if(accountcampaignscore[accountactive]>accountcampaignhighscore[accountactive])accountcampaignhighscore[accountactive]=accountcampaignscore[accountactive];
-
-                                                                       //if(accountprogress[accountactive]<whichlevel+1)accountprogress[accountactive]=whichlevel+1;
-                                                               }
-                                                               else
-                                                               {
-                                                                       won=1;
-                                                                       if(!debugmode){
-                                                                               if(bonustotal-startbonustotal>accounthighscore[accountactive][whichlevel])accounthighscore[accountactive][whichlevel]=bonustotal-startbonustotal;
-                                                                               if(accountfasttime[accountactive][whichlevel]==0||leveltime<accountfasttime[accountactive][whichlevel])accountfasttime[accountactive][whichlevel]=leveltime;
-                                                                       }
-                                                                       if(accountprogress[accountactive]<whichlevel+1)accountprogress[accountactive]=whichlevel+1;
+                       if(changedelay>0&&!player[0].dead&&!won){
+                               //high scores, awards, win
+                               if(campaign){
+                                       accountactive->winCampaignLevel(whichchoice, bonustotal, leveltime);
+                                       scoreadded=1;
+                               }
+                               else
+                               {
+                                       accountactive->winLevel(whichlevel,bonustotal-startbonustotal,leveltime);
+                               }
+                               won=1;
+                       }
+               }
 
-                                                               }
-                                                       }
+               if(!winfreeze){
+
+                       if(leveltime<1){
+                               loading=0;
+                               changedelay=.1;
+                               alldead=0;
+                               winhotspot=0;
+                               killhotspot=0;
+                       }
+
+                       if(!editorenabled&&gameon&&!mainmenu){
+                               if(changedelay!=-999)changedelay-=multiplier/7;
+                               if(player[0].dead)targetlevel=whichlevel;
+                               if(loading==2&&!campaign){
+                                       flash();
+
+                                       fireSound(firestartsound);
+
+                                       if(!player[0].dead&&targetlevel!=whichlevel){
+                                               startbonustotal=bonustotal;
                                        }
+                                       if(player[0].dead) Loadlevel(whichlevel);
+                                       else Loadlevel(targetlevel);
 
-                                       if(!winfreeze){
+                                       fireSound();
 
-                                               if(leveltime<1){
-                                                       loading=0;
-                                                       changedelay=.1;
-                                                       alldead=0;
-                                                       winhotspot=0;
-                                                       killhotspot=0;
-                                               }
+                                       loading=3;
+                               }
+                               if(loading==2&&targetlevel==whichlevel){
+                                       flash();
+                                       loadtime=0;
 
-                                               if(!editorenabled&&gameon&&!mainmenu){
-                                                       if(changedelay!=-999)changedelay-=multiplier/7;
-                                                       if(player[0].dead)targetlevel=whichlevel;
-                                                       if(loading==2&&!campaign){
-                                                               flashr=1;
-                                                               flashg=0;
-                                                               flashb=0;
-                                                               flashamount=1;
-                                                               flashdelay=1;
-                                                               loadtime=0;
-
-                                                               float gLoc[3]={0,0,0};
-                                                               float vel[3]={0,0,0};
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[firestartsound], 256);
-                                                               OPENAL_SetPaused(channels[firestartsound], false);
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                                               if(!player[0].dead&&targetlevel!=whichlevel){
-                                                                       startbonustotal=bonustotal;
-                                                               }
-                                                               if(!player[0].dead)Loadlevel(targetlevel);
-                                                               if(player[0].dead)Loadlevel(whichlevel);
+                                       fireSound(firestartsound);
 
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                                                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[fireendsound], 256);
-                                                               OPENAL_SetPaused(channels[fireendsound], false);
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
+                                       Loadlevel(campaignmapname[levelorder[accountactive->getCampaignChoicesMade()]]);
 
-                                                               loading=3;
-                                                       }
-                                                       if(loading==2&&targetlevel==whichlevel){
-                                                               flashr=1;
-                                                               flashg=0;
-                                                               flashb=0;
-                                                               flashamount=1;
-                                                               flashdelay=1;
-                                                               loadtime=0;
-
-                                                               float gLoc[3]={0,0,0};
-                                                               float vel[3]={0,0,0};
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[firestartsound], 256);
-                                                               OPENAL_SetPaused(channels[firestartsound], false);
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                                               for(i=0;i<255;i++){
-                                                                       mapname[i]='\0';
-                                                               }
-                                                               mapname[0]=':';
-                                                               mapname[1]='D';
-                                                               mapname[2]='a';
-                                                               mapname[3]='t';
-                                                               mapname[4]='a';
-                                                               mapname[5]=':';
-                                                               mapname[6]='M';
-                                                               mapname[7]='a';
-                                                               mapname[8]='p';
-                                                               mapname[9]='s';
-                                                               mapname[10]=':';
-                                                               strcat(mapname,campaignmapname[levelorder[accountcampaignchoicesmade[accountactive]]]);//[campaignchoicewhich[whichchoice]]);
-                                                               Loadlevel(mapname);
-
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 9999.0f, 99999.0f);
-                                                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[fireendsound], 256);
-                                                               OPENAL_SetPaused(channels[fireendsound], false);
-                                                               OPENAL_Sample_SetMinMaxDistance(samp[fireendsound], 8.0f, 2000.0f);
-
-                                                               loading=3;
-                                                       }
-                                                       if(changedelay<=-999&&whichlevel!=-2&&!loading&&(player[0].dead||(alldead&&maptype==mapkilleveryone)||(winhotspot)||(killhotspot))&&!winfreeze)loading=1;
-                                                       if((player[0].dead||(alldead&&maptype==mapkilleveryone)||(winhotspot)||(windialogue)||(killhotspot))&&changedelay<=0){
-                        {
-                                                                       if(whichlevel!=-2&&!loading&&!player[0].dead){
-                                                                               winfreeze=1;
-                                                                               changedelay=-999;
-                                                                       }
-                                                                       if(player[0].dead)loading=1;
-                                                               }
-                                                       }
+                                       fireSound();
+
+                                       loading=3;
+                               }
+                               if(changedelay<=-999&&whichlevel!=-2&&!loading&&(player[0].dead||(alldead&&maptype==mapkilleveryone)||(winhotspot)||(killhotspot))&&!winfreeze)loading=1;
+                               if((player[0].dead||(alldead&&maptype==mapkilleveryone)||(winhotspot)||(windialogue)||(killhotspot))&&changedelay<=0){
+                       {
+                                               if(whichlevel!=-2&&!loading&&!player[0].dead){
+                                                       winfreeze=1;
+                                                       changedelay=-999;
                                                }
+                                               if(player[0].dead)loading=1;
+                                       }
+                               }
+                       }
 
-                                               if(campaign)
-                                                       if(mainmenu==0&&winfreeze&&(campaignchoosenext[campaignchoicewhich[whichchoice]])==1){
-                                                               if(campaignnumnext[campaignchoicewhich[whichchoice]]==0){
-                                                                       endgame=1;
-                                                               }
-                                                       }
-                                                       else if(mainmenu==0&&winfreeze){
-                                                               if(campaignchoosenext[campaignchoicewhich[whichchoice]]==2)
-                                                                       stealthloading=1;
-                                                               else stealthloading=0;
-
-                                                               if(!stealthloading){
-                                                                       float gLoc[3]={0,0,0};
-                                                                       float vel[3]={0,0,0};
-                                                                       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 9999.0f, 99999.0f);
-                                                                       PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[firestartsound], 256);
-                                                                       OPENAL_SetPaused(channels[firestartsound], false);
-                                                                       OPENAL_Sample_SetMinMaxDistance(samp[firestartsound], 8.0f, 2000.0f);
-
-                                                                       flashr=1;
-                                                                       flashg=0;
-                                                                       flashb=0;
-                                                                       flashamount=1;
-                                                                       flashdelay=1;
-                                                               }
+                       if(campaign)
+                               if(mainmenu==0&&winfreeze&&(campaignchoosenext[campaignchoicewhich[whichchoice]])==1){
+                                       if(campaignnumnext[campaignchoicewhich[whichchoice]]==0){
+                                               endgame=1;
+                                       }
+                               }
+                               else if(mainmenu==0&&winfreeze){
+                                       if(campaignchoosenext[campaignchoicewhich[whichchoice]]==2)
+                                               stealthloading=1;
+                                       else stealthloading=0;
 
-                                                               startbonustotal=0;
-
-                                                               ifstream ipstream(ConvertFileName(":Data:Campaigns:main.txt"));
-                                                               //campaignnumlevels=0;
-                                                               //accountcampaignchoicesmade[accountactive]=0;
-                                                               ipstream.ignore(256,':');
-                                                               ipstream >> campaignnumlevels;
-                                                               for(i=0;i<campaignnumlevels;i++){
-                                                                       ipstream.ignore(256,':');
-                                                                       ipstream.ignore(256,':');
-                                                                       ipstream.ignore(256,' ');
-                                                                       ipstream >> campaignmapname[i];
-                                                                       ipstream.ignore(256,':');
-                                                                       ipstream >> campaigndescription[i];
-                                                                       for(j=0;j<256;j++){
-                                                                               if(campaigndescription[i][j]=='_')campaigndescription[i][j]=' ';
-                                                                       }
-                                                                       ipstream.ignore(256,':');
-                                                                       ipstream >> campaignchoosenext[i];
-                                                                       ipstream.ignore(256,':');
-                                                                       ipstream >> campaignnumnext[i];
-                                                                       if(campaignnumnext[i])
-                                                                               for(j=0;j<campaignnumnext[i];j++){
-                                                                                       ipstream.ignore(256,':');
-                                                                                       ipstream >> campaignnextlevel[i][j];
-                                                                                       campaignnextlevel[i][j]-=1;
-                                                                               }
-                                                                               ipstream.ignore(256,':');
-                                                                               ipstream >> campaignlocationx[i];
-                                                                               ipstream.ignore(256,':');
-                                                                               ipstream >> campaignlocationy[i];
-                                                               }
-                                                               ipstream.close();
+                                       if(!stealthloading){
+                                               float gLoc[3]={0,0,0};
+                                               float vel[3]={0,0,0};
+                                               fireSound(firestartsound);
 
-                                                               for(i=0;i<campaignnumlevels;i++){
-                                                                       levelvisible[i]=0;
-                                                                       levelhighlight[i]=0;
-                                                               }
+                                               flash();
+                                       }
 
+                                       startbonustotal=0;
 
-                                                               for(i=0;i<campaignnumlevels;i++){
-                                                                       levelvisible[i]=0;
-                                                                       levelhighlight[i]=0;
-                                                               }
+                                       ifstream ipstream(ConvertFileName(":Data:Campaigns:main.txt"));
+                                       ipstream.ignore(256,':');
+                                       ipstream >> campaignnumlevels;
+                                       for(i=0;i<campaignnumlevels;i++){
+                                               ipstream.ignore(256,':');
+                                               ipstream.ignore(256,':');
+                                               ipstream.ignore(256,' ');
+                                               ipstream >> campaignmapname[i];
+                                               ipstream.ignore(256,':');
+                                               ipstream >> campaigndescription[i];
+                                               for(j=0;j<256;j++){
+                                                       if(campaigndescription[i][j]=='_')campaigndescription[i][j]=' ';
+                                               }
+                                               ipstream.ignore(256,':');
+                                               ipstream >> campaignchoosenext[i];
+                                               ipstream.ignore(256,':');
+                                               ipstream >> campaignnumnext[i];
+                                               for(j=0;j<campaignnumnext[i];j++){
+                                                       ipstream.ignore(256,':');
+                                                       ipstream >> campaignnextlevel[i][j];
+                                                       campaignnextlevel[i][j]-=1;
+                                               }
+                                               ipstream.ignore(256,':');
+                                               ipstream >> campaignlocationx[i];
+                                               ipstream.ignore(256,':');
+                                               ipstream >> campaignlocationy[i];
+                                       }
+                                       ipstream.close();
 
-                                                               levelorder[0]=0;
-                                                               levelvisible[0]=1;
-                                                               if(accountcampaignchoicesmade[accountactive])
-                                                                       for(i=0;i<accountcampaignchoicesmade[accountactive];i++){
-                                                                               levelorder[i+1]=campaignnextlevel[levelorder[i]][accountcampaignchoices[accountactive][i]];
-                                                                               levelvisible[levelorder[i+1]]=1;
-                                                                       }
-                                                                       int whichlevelstart;
-                                                                       whichlevelstart=accountcampaignchoicesmade[accountactive]-1;
-                                                                       if(whichlevelstart<0){
-                                                                               campaignchoicenum=1;
-                                                                               campaignchoicewhich[0]=0;
-                                                                       }
-                                                                       else
-                                                                       {
-                                                                               campaignchoicenum=campaignnumnext[levelorder[whichlevelstart]];
-                                                                               if(campaignchoicenum)
-                                                                                       for(i=0;i<campaignchoicenum;i++){
-                                                                                               campaignchoicewhich[i]=campaignnextlevel[levelorder[whichlevelstart]][i];
-                                                                                               levelvisible[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
-                                                                                               levelhighlight[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
-                                                                                       }
-                                                                       }
+                                       for(i=0;i<campaignnumlevels;i++){
+                                               levelvisible[i]=0;
+                                               levelhighlight[i]=0;
+                                       }
 
-                                                                       loading=2;
-                                                                       loadtime=0;
-                                                                       targetlevel=7;
-                                                                       //if(firstload)TickOnceAfter();
-                                                                       if(!firstload)LoadStuff();
-                                                                       //else {
-                                                                       for(i=0;i<255;i++){
-                                                                               mapname[i]='\0';
-                                                                       }
-                                                                       mapname[0]=':';
-                                                                       mapname[1]='D';
-                                                                       mapname[2]='a';
-                                                                       mapname[3]='t';
-                                                                       mapname[4]='a';
-                                                                       mapname[5]=':';
-                                                                       mapname[6]='M';
-                                                                       mapname[7]='a';
-                                                                       mapname[8]='p';
-                                                                       mapname[9]='s';
-                                                                       mapname[10]=':';
-
-                                                                       //accountcampaignchoices[accountactive][accountcampaignchoicesmade[accountactive]]=whichchoice;
-                                                                       //accountcampaignchoicesmade[accountactive]++;
-
-
-                                                                       strcat(mapname,campaignmapname[campaignchoicewhich[0]]);
-                                                                       whichchoice=0;
-                                                                       visibleloading=1;
-                                                                       stillloading=1;
-                                                                       Loadlevel(mapname);
-                                                                       campaign=1;
-                                                                       mainmenu=0;
-                                                                       gameon=1;
-                                                                       OPENAL_SetPaused(channels[stream_music3], true);
-
-                                                                       stealthloading=0;
-                                                       }
 
-                                                       if(loading==3)loading=0;
+                                       for(i=0;i<campaignnumlevels;i++){
+                                               levelvisible[i]=0;
+                                               levelhighlight[i]=0;
+                                       }
 
+                                       levelorder[0]=0;
+                                       levelvisible[0]=1;
+                                       for(i=0;i<accountactive->getCampaignChoicesMade();i++){
+                                               levelorder[i+1]=campaignnextlevel[levelorder[i]][accountactive->getCampaignChoice(i)];
+                                               levelvisible[levelorder[i+1]]=1;
+                                       }
+                                       int whichlevelstart;
+                                       whichlevelstart=accountactive->getCampaignChoicesMade()-1;
+                                       if(whichlevelstart<0){
+                                               campaignchoicenum=1;
+                                               campaignchoicewhich[0]=0;
+                                       }
+                                       else
+                                       {
+                                               campaignchoicenum=campaignnumnext[levelorder[whichlevelstart]];
+                                               for(i=0;i<campaignchoicenum;i++){
+                                                       campaignchoicewhich[i]=campaignnextlevel[levelorder[whichlevelstart]][i];
+                                                       levelvisible[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
+                                                       levelhighlight[campaignnextlevel[levelorder[whichlevelstart]][i]]=1;
+                                               }
                                        }
 
-                                       oldmusictype=musictype;
+                                       loading=2;
+                                       loadtime=0;
+                                       targetlevel=7;
+                                       if(!firstload)LoadStuff();
+                                       whichchoice=0;
+                                       visibleloading=1;
+                                       stillloading=1;
+                                       Loadlevel(campaignmapname[campaignchoicewhich[0]]);
+                                       campaign=1;
+                                       mainmenu=0;
+                                       gameon=1;
+                                       pause_sound(stream_music3);
+
+                                       stealthloading=0;
+                               }
+
+                               if(loading==3)loading=0;
+
+                       }
+
+                       oldmusictype=musictype;
        }
 
        facing=0;
index eae0bd07f0590fbda565f78b41bd0c97c2a3068e..db533ec567e555804d512b9a1d45ef6cf8b87d64 100644 (file)
@@ -26,7 +26,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "Lights.h"
 #include "Skeleton.h"
 #include "Terrain.h"
-#include "Sprites.h"
+#include "Sprite.h"
 #include "Frustum.h"
 #include "Objects.h"
 #include "Weapons.h"
@@ -35,15 +35,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "openal_wrapper.h"
 #include "Stereo.h"
 
-#include "Constants.h"
+#include "Animation.h"
 
 bool visibleloading = 0;
-OPENAL_SAMPLE  *samp[100] = {0};
-OPENAL_STREAM * strm[20] = {0};
-int channels[100] = {0};
 
-float volume = 0;bool buttons[3] = {0};
-bool oldbuttons[3] = {0};
+float volume = 0;
 bool ismotionblur = 0;
 float usermousesensitivity = 0;
 bool floatjump = 0;
@@ -76,7 +72,6 @@ Animation animation[animation_count];
 Skeleton testskeleton;
 int numsounds = 0;
 Terrain terrain;
-Sprites sprites;
 float sps = 0;
 
 SDL_Surface *sdlscreen;
@@ -86,7 +81,6 @@ int detail = 0;
 FRUSTUM frustum;
 float texdetail = 0;
 float realtexdetail = 0;
-float terraindetail = 0;
 float playerdist = 0;
 Objects objects;
 int slomo = 0;
@@ -104,8 +98,6 @@ bool musictoggle = 0;
 bool trilinear;
 Weapons weapons;
 bool damageeffects = 0;
-//apvector<Person> player(maxplayers);
-Person player[maxplayers];
 int numplayers = 0;
 bool ambientsound = 0;
 bool mousejump = 0;
@@ -116,7 +108,6 @@ int flashdelay = 0;
 bool vblsync = 0;
 float motionbluramount = 0;
 bool keyboardfrozen = 0;
-char mapname[256] = {0};
 bool loadingstuff = 0;
 bool stillloading = 0;
 bool showpoints = 0;
@@ -130,7 +121,6 @@ short vRefNum = 0;
 long dirID = 0;
 int mainmenu = 0;
 int oldmainmenu = 0;
-GLubyte texturearray[512*512*3] = {0};
 int loadscreencolor = 0;
 int whichjointstartarray[26] = {0};
 int whichjointendarray[26] = {0};
@@ -148,28 +138,6 @@ int killhotspot = 0;
 
 float menupulse = 0;
 
-int numdialogues = 0;
-int numdialogueboxes[max_dialogues] = {0};
-int dialoguetype[max_dialogues] = {0};
-int dialogueboxlocation[max_dialogues][max_dialoguelength] = {0};
-float dialogueboxcolor[max_dialogues][max_dialoguelength][3] = {0};
-int dialogueboxsound[max_dialogues][max_dialoguelength] = {0};
-char dialoguetext[max_dialogues][max_dialoguelength][128] = {0};
-char dialoguename[max_dialogues][max_dialoguelength][64] = {0};
-XYZ dialoguecamera[max_dialogues][max_dialoguelength]; //l = {0};
-XYZ participantlocation[max_dialogues][10]; // = {0};
-int participantfocus[max_dialogues][max_dialoguelength] = {0};
-int participantaction[max_dialogues][max_dialoguelength] = {0};
-float participantrotation[max_dialogues][10] = {0};
-XYZ participantfacing[max_dialogues][max_dialoguelength][10]; // = {0};
-float dialoguecamerarotation[max_dialogues][max_dialoguelength] = {0};
-float dialoguecamerarotation2[max_dialogues][max_dialoguelength] = {0};
-int indialogue = 0;
-int whichdialogue = 0;
-int directing = 0;
-float dialoguetime = 0;
-int dialoguegonethrough[20] = {0};
-
 float smoketex = 0;
 
 float slomospeed = 0;
@@ -184,7 +152,6 @@ float tutorialsuccess = 0;
 bool againbonus = 0;
 
 float damagedealt = 0;
-float damagetaken = 0;
 
 int maptype = 0;
 
@@ -203,8 +170,6 @@ float skyboxlightr = 0;
 float skyboxlightg = 0;
 float skyboxlightb = 0;
 
-float bonusnum[100] = {0};
-
 int hostile = 0;
 float hostiletime = 0;
 
@@ -222,49 +187,11 @@ bool vertexweird[6] = {0};
 TGAImageRec texture;
 bool debugmode = 0;
 
-int oldbonus = 0;
-int bonus = 0;
-float bonusvalue = 0;
-float bonustotal = 0;
-float startbonustotal = 0;
-float bonustime = 0;
-
-int numaccounts = 0;
-int accountactive = 0;
-int accountdifficulty[10] = {0};
-int accountprogress[10] = {0};
-float accountpoints[10] = {0};
-float accounthighscore[10][50] = {0};
-float accountfasttime[10][50] = {0};
-bool accountunlocked[10][60] = {0};
-char accountname[10][256] = {0};
-float accountcampaignhighscore[10] = {0};
-float accountcampaignfasttime[10] = {0};
-float accountcampaignscore[10] = {0};
-float accountcampaigntime[10] = {0};
-int accountcampaignchoicesmade[10] = {0};int accountcampaignchoices[10][5000] = {0};
 bool won = 0;
 
 
 bool campaign = 0;
 
-int numfalls = 0;
-int numflipfail = 0;
-int numseen = 0;
-int numresponded = 0;
-int numstaffattack = 0;
-int numswordattack = 0;
-int numknifeattack = 0;
-int numunarmedattack = 0;
-int numescaped = 0;
-int numflipped = 0;
-int numwallflipped = 0;
-int numthrowkill = 0;
-int numafterkill = 0;
-int numreversals = 0;
-int numattacks = 0;
-int maxalarmed = 0;
-
 bool gamestarted = 0;
 
 //TextureList textures;
@@ -272,4 +199,4 @@ bool gamestarted = 0;
 StereoMode stereomode =  stereoNone;
 StereoMode newstereomode = stereoNone;
 float stereoseparation = 0.05;
-bool  stereoreverse = false;
\ No newline at end of file
+bool  stereoreverse = false;
diff --git a/Source/Input.cpp b/Source/Input.cpp
new file mode 100644 (file)
index 0000000..3cf1b1c
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+Copyright (C) 2003, 2010 - Wolfire Games
+Copyright (C) 2010 - MCMic
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+/**> HEADER FILES <**/
+#include "Input.h"
+
+extern bool keyboardfrozen;
+
+bool Input::isKeyDown(int k) {
+       if(keyboardfrozen)return 0; // vraiment utile? Ã  vérifier
+       Uint8 *keystate = SDL_GetKeyState(NULL);
+       if(k<SDLK_LAST)
+               return keystate[k];
+       else
+               return SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(k-SDLK_LAST);
+}
+
+const char* Input::keyToChar(unsigned short i) {
+       if(i<SDLK_LAST)
+               return SDL_GetKeyName(SDLKey(i));
+       else if(i==SDLK_LAST+SDL_BUTTON_LEFT)
+               return "mouse1";
+       else if(i==SDLK_LAST+SDL_BUTTON_RIGHT)
+               return "mouse2";
+       else if(i==SDLK_LAST+SDL_BUTTON_MIDDLE)
+               return "mouse3";
+       else
+               return "unknown";
+}
+
+unsigned short         Input::CharToKey(const char* which)
+{
+       for(unsigned short i=0;i<SDLK_LAST;i++) {
+               if(!strcasecmp(which,SDL_GetKeyName(SDLKey(i))))
+                       return i;
+       }
+       if(!strcasecmp(which,"mouse1")){
+               return MOUSEBUTTON1;
+       }
+       if(!strcasecmp(which,"mouse2")){
+               return MOUSEBUTTON2;
+       }
+       return SDLK_LAST;
+}
+
+Boolean Input::Button()
+{
+    return SDL_GetMouseState(NULL,NULL)&SDL_BUTTON(SDL_BUTTON_LEFT);
+}
diff --git a/Source/Input.h b/Source/Input.h
new file mode 100644 (file)
index 0000000..f78437c
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+Copyright (C) 2003, 2010 - Wolfire Games
+Copyright (C) 2010 - MCMic
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifndef _Input_H_
+#define _Input_H_
+
+/**> HEADER FILES <**/
+#include "SDL.h"
+#include "Game.h"
+
+/**> CONSTANT DECLARATIONS <**/
+#define MOUSEBUTTON1           SDLK_LAST+SDL_BUTTON_LEFT
+#define MOUSEBUTTON2           SDLK_LAST+SDL_BUTTON_RIGHT
+
+/**> FUNCTION PROTOTYPES <**/
+class Input {
+       public:
+               static bool isKeyDown(int k);
+               static const char* keyToChar(unsigned short which);
+               static void setKeyFor(Game* g);
+               static unsigned short   CharToKey(const char* which);
+               static Boolean Button();
+};
+
+#endif
diff --git a/Source/LinkedList.h b/Source/LinkedList.h
deleted file mode 100644 (file)
index 38dded3..0000000
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-/*
- * Copyright (c) 1999-2002 Apple Computer, Inc. All rights reserved.
- *
- * @APPLE_LICENSE_HEADER_START@
- * 
- * Portions Copyright (c) 1999-2002 Apple Computer, Inc.  All Rights
- * Reserved.  This file contains Original Code and/or Modifications of
- * Original Code as defined in and that are subject to the Apple Public
- * Source License Version 1.1 (the "License").  You may not use this file
- * except in compliance with the License.  Please obtain a copy of the
- * License at http://www.apple.com/publicsource and read it before using
- * this file.
- * 
- * The Original Code and all software distributed under the License are
- * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
- * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
- * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT.  Please see the
- * License for the specific language governing rights and limitations
- * under the License.
- * 
- * @APPLE_LICENSE_HEADER_END@
- *
- * Modified: $Date: 2002/04/27 20:52:48 $
- * Revision: $Id: LinkedList.h,v 1.3 2002/04/27 20:52:48 lane Exp $
- */
-
-
-/*
-       File:           LinkedList.h
-
-       Contains:
-
-*/
-
-#ifndef __LINKEDLIST__
-#define __LINKEDLIST__
-
-
-//we cant just use "macintosh_build" - the mac macho_build is designated as "posix_build" but may 
-//include open transport in some cases
-#ifndef __OPENTRANSPORT__
-//#if (!macintosh_build)
-
-#include <stddef.h>            //for OTGetLinkObject replacement
-
-#include "OPUtils.h"   //for true/false
-
-#if (windows_build)
-
-// ECF 010928 win32 syncronization routines for safe critical sections.  We can't simply use TryEnterCriticalSection()
-// to return a true/false value because it's not available in win95 and 98
-class OSCriticalSection
-{
-       public:
-               NMBoolean locked;
-               OSCriticalSection() {locked = false; InitializeCriticalSection(&theCriticalSection);}
-               ~OSCriticalSection() {DeleteCriticalSection(&theCriticalSection);}
-               NMBoolean       acquire()       {       if (locked == true) return false; //dont have to wait in this case      
-                                                               EnterCriticalSection(&theCriticalSection);
-                                                               if (locked) {LeaveCriticalSection(&theCriticalSection); return false;}
-                                                               else {locked = true; LeaveCriticalSection(&theCriticalSection); return true;}}
-               void    release()       {       EnterCriticalSection(&theCriticalSection);
-                                                               locked = false; LeaveCriticalSection(&theCriticalSection);}
-
-       CRITICAL_SECTION theCriticalSection;
-};
-#endif //windows_build
-
-#if (posix_build)
-#include <pthread.h>
-class OSCriticalSection
-{
-       public:
-               OSCriticalSection() {pthread_mutex_init(&theMutex,NULL);}
-               ~OSCriticalSection() {pthread_mutex_destroy(&theMutex);}
-               NMBoolean       acquire()       {       int error = pthread_mutex_trylock(&theMutex);
-                                                                       if (error) return false; else return true;}
-               void    release()       {       pthread_mutex_unlock(&theMutex);}
-
-               pthread_mutex_t theMutex;
-};
-
-#endif //(posix_build)
-
-/*     -------------------------------------------------------------------------
-       ** OTLIFO
-       **
-       ** These are functions to implement a LIFO list that is interrupt-safe.
-       ** The only function which is not is OTReverseList.  Normally, you create
-       ** a LIFO list, populate it at interrupt time, and then use OTLIFOStealList
-       ** to atomically remove the list, and OTReverseList to flip the list so that
-       ** it is a FIFO list, which tends to be more useful.
-       ------------------------------------------------------------------------- */
-
-       class OTLink;
-       class OTLIFO;
-
-       class OTLink
-       {
-               public:
-                       OTLink* fNext;
-                       void    Init()
-                                               { fNext = NULL; }
-       };
-
-       class OTLIFO
-       {
-               public:
-                       OSCriticalSection theLock;
-                       OTLink* fHead;
-               
-                       void    Init()  
-                                       { fHead = NULL; }
-               
-                       void    Enqueue(OTLink* link)
-                                                       { 
-                                                               while (true) {if (theLock.acquire()) break;}
-                                                               link->fNext = fHead;
-                                                               fHead = link;   
-                                                               theLock.release();              
-                                                       }
-                                       
-
-                       OTLink* Dequeue()
-                                                       {
-                                                               while (true) {if (theLock.acquire()) break;}                                            
-                                                               OTLink *origHead = fHead;
-                                                               fHead = fHead->fNext;
-                                                               theLock.release();                                                                      
-                                                               return origHead;
-                                                       }
-
-                                               
-                       OTLink* StealList()
-                                                       {       
-                                                               while (true) {if (theLock.acquire()) break;}
-                                                               OTLink *origHead = fHead;
-                                                               fHead = NULL;
-                                                               theLock.release();
-                                                               return origHead;
-                                                       }
-                                               
-                                               
-                       NMBoolean       IsEmpty()
-                                                       {
-                                                               return fHead == NULL;
-                                                       }
-       };
-
-/*     -------------------------------------------------------------------------
-       ** OTList
-       **
-       ** An OTList is a non-interrupt-safe list, but has more features than the
-       ** OTLIFO list. It is a standard singly-linked list.
-       ------------------------------------------------------------------------- */
-
-       typedef struct OTList   OTList;
-
-               typedef NMBoolean (*OTListSearchProcPtr)(const void* ref, OTLink* linkToCheck);
-               //
-               // Remove the last link from the list
-               //
-       extern OTLink*          OTRemoveLast(OTList* pList);
-               //
-               // Return the first link from the list
-               //
-       extern OTLink*          OTGetFirst(OTList* pList);
-               //
-               // Return the last link from the list
-               //
-       extern OTLink*          OTGetLast(OTList* pList);
-               //
-               // Return true if the link is present in the list
-               //
-       extern NMBoolean                OTIsInList(OTList* pList, OTLink* link);
-               //
-               // Find a link in the list which matches the search criteria
-               // established by the search proc and the refPtr.  This is done
-               // by calling the search proc, passing it the refPtr and each
-               // link in the list, until the search proc returns true.
-               // NULL is returned if the search proc never returned true.
-               //
-       extern OTLink*          OTFindLink(OTList* pList, OTListSearchProcPtr proc, const void* refPtr);
-               //
-               // Remove the specified link from the list, returning true if it was found
-               //
-       extern NMBoolean                OTRemoveLink(OTList*, OTLink*);
-               //
-               // Similar to OTFindLink, but it also removes it from the list.
-               //
-       extern OTLink*          OTFindAndRemoveLink(OTList* pList, OTListSearchProcPtr proc, const void* refPtr);
-               //
-               // Return the "index"th link in the list
-               //
-       extern OTLink*          OTGetIndexedLink(OTList* pList, size_t index);
-
-       struct OTList
-       {
-               OTLink*         fHead;
-               
-               void            Init()  
-                                               { fHead = NULL; }
-               
-               NMBoolean               IsEmpty()
-                                               { return fHead == NULL; }
-                                               
-               void            AddFirst(OTLink* link)
-                                                       { 
-                                                               link->fNext = fHead;
-                                                               fHead = link;                   
-                                                       }
-
-               void            AddLast(OTLink* link)
-                                                       {
-                                                               if (fHead == NULL)
-                                                                       fHead = link->fNext;
-                                                               else
-                                                               {
-                                                                       OTLink *current = fHead;
-                                                                       
-                                                                       while (current->fNext != NULL)
-                                                                               current = current->fNext;
-                                                                               
-                                                                       current->fNext = link;
-                                                               }
-                                                               
-                                                               
-                                                               link->fNext = fHead;
-                                                               fHead = link;                   
-                                                       }
-
-               
-               OTLink*         GetFirst()
-                                               { return OTGetFirst(this); }
-               
-               OTLink*         GetLast()
-                                               { return OTGetLast(this); }
-               
-               OTLink*         RemoveFirst()
-                                                       {
-                                                               OTLink *origHead = fHead;
-                                                               fHead = fHead->fNext;
-                                                               return origHead;
-                                                       }
-                                                               
-               OTLink*         RemoveLast()
-                                               { return OTRemoveLast(this); }
-                                               
-               NMBoolean               IsInList(OTLink* link)
-                                               { return OTIsInList(this, link); }
-                                               
-               OTLink*         FindLink(OTListSearchProcPtr proc, const void* ref)
-                                               { return OTFindLink(this, proc, ref); }
-                                               
-               NMBoolean               RemoveLink(OTLink* link)
-                                               { return OTRemoveLink(this, link); }
-                                               
-               OTLink*         RemoveLink(OTListSearchProcPtr proc, const void* ref)
-                                               { return OTFindAndRemoveLink(this, proc, ref); }
-                                               
-               OTLink*         GetIndexedLink(size_t index)
-                                               { return OTGetIndexedLink(this, index); }
-       };
-       
-       
-//FIXME!!  this is a recursive function and will crash and burn on large lists
-static OTLink* OTReverseList(OTLink *headRef)
-{
-       OTLink  *first;
-       OTLink  *rest;
-
-       if (headRef == NULL) return NULL;
-       
-       first = headRef;
-       rest = (OTLink *) first->fNext;
-       
-       if (rest == NULL) return headRef;
-       
-       rest = OTReverseList(rest);
-       
-       first->fNext->fNext = first;
-       first->fNext = NULL;
-       
-       return rest;
-}
-       
-
-       #define OTGetLinkObject(link, struc, field)     \
-               ((struc*)((char*)(link) - offsetof(struc, field)))
-
-#endif //!macintosh_build
-#endif /* __LINKEDLIST__ */
-
-
index 3a99c52a052925f9dfc90c7036950365f5aca3ee..e9b2905f714219e2b6d98ac65311450913a442a6 100644 (file)
@@ -111,27 +111,7 @@ inline bool isnormal( double x)
 char* ConvertFileName( const char* orgfilename, const char *mode = "rb" );
 
 #define fopen( a, b) fopen(ConvertFileName(a, b), b)
-/*
-inline float abs( float f)
-{
-if (f < 0)
-return -f;
-return f;
-}
 
-inline double abs( double f)
-{
-if (f < 0)
-return -f;
-return f;
-}
-*/
-__forceinline long long longlongabs( long long f)
-{
-       if (f < 0)
-               return -f;
-       return f;
-}
 #endif
 #endif
 
index e573423ba9eb674cc49b743c26a267cfe217fcd3..e51bcfb786c7ce81c2406a1fa2926ae41b6829e1 100644 (file)
@@ -21,7 +21,6 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "Game.h"
 #include "Models.h"
-//#include "altivec.h"
 
 extern float multiplier;
 extern float viewdistance;
@@ -33,25 +32,6 @@ extern int loadscreencolor;
 
 extern Game * pgame;
 extern bool visibleloading;
-//Functions
-void *allocate_aligned(size_t pointer_size, size_t byte_alignment)
-{
-       uintptr_t pointer = (uintptr_t)malloc(pointer_size + byte_alignment + 1);
-       uintptr_t aligned_pointer = (pointer + byte_alignment + 1);
-       aligned_pointer -= (aligned_pointer % byte_alignment);
-       *(uint8_t *)(aligned_pointer - 1) = (aligned_pointer - pointer);
-       return (void *)aligned_pointer;
-}
-
-void free_aligned(void *aligned_pointer)
-{
-       free((uint8_t *)(aligned_pointer) - *((uint8_t *)(aligned_pointer) - 1));
-}
-
-void dealloc(void* param){
-       free(param);
-       param=0;
-}
 
 int Model::LineCheck(XYZ *p1,XYZ *p2, XYZ *p, XYZ *move, float *rotate)
 {
@@ -443,13 +423,6 @@ bool Model::loadnotex(const char *filename )
        funpackf(tfile, "Bs Bs", &vertexNum, &TriangleNum);
 
        // read the model data
-       /*if(owner)dealloc(owner);
-       if(possible)dealloc(possible);
-       if(vertex)dealloc(vertex);
-       if(normals)dealloc(normals);
-       if(facenormals)dealloc(facenormals);
-       if(Triangles)dealloc(Triangles);
-       if(vArray)dealloc(vArray);*/
        deallocate();
 
        numpossible=0;
@@ -528,13 +501,6 @@ bool Model::load(const char *filename,bool texture )
        funpackf(tfile, "Bs Bs", &vertexNum, &TriangleNum);
 
        // read the model data
-       /*if(owner)dealloc(owner);
-       if(possible)dealloc(possible);
-       if(vertex)dealloc(vertex);
-       if(normals)dealloc(normals);
-       if(facenormals)dealloc(facenormals);
-       if(Triangles)dealloc(Triangles);
-       if(vArray)dealloc(vArray);*/
        deallocate();
 
        numpossible=0;
@@ -616,13 +582,6 @@ bool Model::loaddecal(const char *filename,bool texture )
 
        // read the model data
 
-       /*if(owner)dealloc(owner);
-       if(possible)dealloc(possible);
-       if(vertex)dealloc(vertex);
-       if(normals)dealloc(normals);
-       if(facenormals)dealloc(facenormals);
-       if(Triangles)dealloc(Triangles);
-       if(vArray)dealloc(vArray);*/
        deallocate();
 
        numpossible=0;
@@ -722,13 +681,6 @@ bool Model::loadraw(char *filename )
        funpackf(tfile, "Bs Bs", &vertexNum, &TriangleNum);
 
        // read the model data
-       /*if(owner)dealloc(owner);
-       if(possible)dealloc(possible);
-       if(vertex)dealloc(vertex);
-       if(normals)dealloc(normals);
-       if(facenormals)dealloc(facenormals);
-       if(Triangles)dealloc(Triangles);
-       if(vArray)dealloc(vArray);*/
        deallocate();
 
        numpossible=0;
@@ -1447,25 +1399,25 @@ void Model::deallocate()
 {
        int i = 0, j = 0;
 
-       if(owner)dealloc(owner);
+       if(owner)free(owner);
        owner = 0;
 
-       if(possible)dealloc(possible);
+       if(possible)free(possible);
        possible = 0;
 
-       if(vertex)dealloc(vertex);
+       if(vertex)free(vertex);
        vertex = 0;
 
-       if(normals)dealloc(normals);
+       if(normals)free(normals);
        normals = 0;
 
-       if(facenormals)dealloc(facenormals);
+       if(facenormals)free(facenormals);
        facenormals = 0;
 
-       if(Triangles)dealloc(Triangles);
+       if(Triangles)free(Triangles);
        Triangles = 0;
 
-       if(vArray)dealloc(vArray);
+       if(vArray)free(vArray);
        vArray = 0;
 
 
@@ -1476,11 +1428,11 @@ void Model::deallocate()
                {
                        for(j=0;j<3;j++)
                        {
-                               dealloc(decaltexcoords[i][j]);
+                               free(decaltexcoords[i][j]);
                        }
-                       dealloc(decaltexcoords[i]);
+                       free(decaltexcoords[i]);
                }
-               dealloc(decaltexcoords);
+               free(decaltexcoords);
        }
        decaltexcoords = 0;
 
@@ -1489,26 +1441,26 @@ void Model::deallocate()
        {
                for(i=0;i<max_model_decals;i++)
                {
-                       dealloc(decalvertex[i]);
+                       free(decalvertex[i]);
                }
-               dealloc(decalvertex);
+               free(decalvertex);
        }
        decalvertex = 0;
 
 
-       dealloc(decaltype);
+       free(decaltype);
        decaltype = 0;
 
-       dealloc(decalopacity);
+       free(decalopacity);
        decalopacity = 0;
 
-       dealloc(decalrotation);
+       free(decalrotation);
        decalrotation = 0;
 
-       dealloc(decalalivetime);
+       free(decalalivetime);
        decalalivetime = 0;
 
-       dealloc(decalposition);
+       free(decalposition);
        decalposition = 0;
 
 };
index 297b6e1a7f8a2eda1617dc571cc5441e4a4c522c..caad18ed653699c7b1c6436153dafe2ae99a6401 100644 (file)
@@ -32,7 +32,6 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include <string.h>
 #include <vector>
 
-#include "Constants.h"
 #include "Terrain.h"
 #include "binio.h"
 #include "Quaternions.h"
index d67044eee0923ea543436805384068352c0cf457..a01fc1193598d379c0cc390c5fc7d7d53372ffec 100644 (file)
@@ -31,14 +31,12 @@ extern float multiplier;
 extern float gravity;
 extern FRUSTUM frustum;
 extern Terrain terrain;
-extern float terraindetail;
 extern bool foliage;
 extern int detail;
 extern float blurness;
 extern float windvar;
 extern float playerdist;
 extern bool skyboxtexture;
-extern Sprites sprites;
 
 //Functions
 
@@ -68,8 +66,8 @@ void Objects::SphereCheckPossible(XYZ *p1,float radius)
        static int whichpatchx;
        static int whichpatchz;
 
-       whichpatchx=p1->x/(terrain.size/subdivision*terrain.scale*terraindetail);
-       whichpatchz=p1->z/(terrain.size/subdivision*terrain.scale*terraindetail);
+       whichpatchx=p1->x/(terrain.size/subdivision*terrain.scale);
+       whichpatchz=p1->z/(terrain.size/subdivision*terrain.scale);
 
        if(whichpatchx>=0&&whichpatchz>=0&&whichpatchx<subdivision&&whichpatchz<subdivision)
                if(terrain.patchobjectnum[whichpatchx][whichpatchz]>0&&terrain.patchobjectnum[whichpatchx][whichpatchz]<500)
@@ -664,7 +662,7 @@ void Objects::DoStuff()
        XYZ spawnpoint;
        for(int i=0;i<numobjects;i++){
                /*if(type[i]==firetype){
-               sprites.MakeSprite(weaponshinesprite, position[i],position[i]*0, 1,1,1, 5, 1);
+               Sprite::MakeSprite(weaponshinesprite, position[i],position[i]*0, 1,1,1, 5, 1);
                }*/
 
                if(type[i]==firetype)onfire[i]=1;
@@ -680,7 +678,7 @@ void Objects::DoStuff()
                                        spawnpoint.z=0;
                                        spawnpoint=DoRotation(spawnpoint,0,Random()%360,0);
                                        spawnpoint+=position[i];
-                                       sprites.MakeSprite(flamesprite, spawnpoint,spawnpoint*0, 1,1,1, (.6+(float)abs(Random()%100)/200-.25)*5*scale[i], 1);
+                                       Sprite::MakeSprite(flamesprite, spawnpoint,spawnpoint*0, 1,1,1, (.6+(float)abs(Random()%100)/200-.25)*5*scale[i], 1);
                                }
                                if(type[i]==treeleavestype){
                                        spawnpoint.x=((float)(Random()%100))/80*scale[i];
@@ -688,7 +686,7 @@ void Objects::DoStuff()
                                        spawnpoint.z=0;
                                        spawnpoint=DoRotation(spawnpoint,0,Random()%360,0);
                                        spawnpoint+=position[i];
-                                       sprites.MakeSprite(flamesprite, spawnpoint,spawnpoint*0, 1,1,1, (.6+(float)abs(Random()%100)/200-.25)*6, 1);
+                                       Sprite::MakeSprite(flamesprite, spawnpoint,spawnpoint*0, 1,1,1, (.6+(float)abs(Random()%100)/200-.25)*6, 1);
                                }
                        }
 
@@ -714,8 +712,8 @@ void Objects::DoShadows()
                                        terrainpoint=position[i]+DoRotation(model[i].vertex[j]+model[i].normals[j]*.1,0,rotation[i],0);
                                        //terrainpoint.y+=model[i].boundingsphereradius;
                                        shadowed[i]=0;
-                                       patchx=terrainpoint.x/(terrain.size/subdivision*terrain.scale*terraindetail);
-                                       patchz=terrainpoint.z/(terrain.size/subdivision*terrain.scale*terraindetail);
+                                       patchx=terrainpoint.x/(terrain.size/subdivision*terrain.scale);
+                                       patchz=terrainpoint.z/(terrain.size/subdivision*terrain.scale);
                                        if(patchx>=0&&patchz>=0&&patchx<subdivision&&patchz<subdivision)
                                                if(terrain.patchobjectnum[patchx][patchz])
                                                        for(k=0;k<terrain.patchobjectnum[patchx][patchz];k++){
index a3319ef6dd9dead41fd9cf92b9426b97b6b1b8c6..400d6b3064e4f300b744dd134d50fef0de96d26d 100644 (file)
@@ -30,7 +30,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "Lights.h"
 #include "Models.h"
 #include "Terrain.h"
-#include "Sprites.h"
+#include "Sprite.h"
 #include <vector>
 //
 // Model Structures
index 618ef4742d4218bfbb9ff5571775816b46fd8c7b..23a5f1a407b58f56b6df81c3c2a07d55ef929491 100644 (file)
@@ -48,35 +48,21 @@ extern "C" {
 static bool load_image(const char * fname, TGAImageRec & tex);
 static bool load_png(const char * fname, TGAImageRec & tex);
 static bool load_jpg(const char * fname, TGAImageRec & tex);
-static bool save_image(const char * fname);
+bool save_image(const char * fname);
 static bool save_png(const char * fname);
 
 
 #include "openal_wrapper.h"
 
-// ADDED GWC
-#ifdef _MSC_VER
-#pragma comment(lib, "opengl32.lib")
-#pragma comment(lib, "glu32.lib")
-#pragma comment(lib, "glaux.lib")
-#endif
-
-extern bool buttons[3];
 extern float multiplier;
 extern float sps;
 extern float realmultiplier;
 extern int slomo;
 extern bool cellophane;
-// MODIFIED GWC
-//extern int terraindetail;
-//extern int texdetail;
-extern float terraindetail;
 extern float texdetail;
 
 extern bool osx;
-extern int numplayers;
 extern bool freeze;
-extern Person player[maxplayers];
 extern bool stillloading;
 extern int mainmenu;
 /*extern*/ bool gameFocused;
@@ -102,8 +88,6 @@ extern float slomofreq;
 
 using namespace std;
 
-
-
 SDL_Rect **resolutions = NULL;
 static SDL_Rect rect_1024_768 = { 0, 0, 1024, 768 };
 static SDL_Rect rect_800_600  = { 0, 0, 800,  600 };
@@ -115,39 +99,14 @@ static SDL_Rect *hardcoded_resolutions[] = {
     NULL
 };
 
-
-
-unsigned int resolutionDepths[8][2] = {0};
-
-bool selectDetail(int & width, int & height, int & bpp, int & detail);
-int closestResolution(int width, int height);
-int resolutionID(int width, int height);
-
-void ReportError (char * strError);
-
-void SetupDSpFullScreen();
-void ShutdownDSp();
-
 void DrawGL(Game & game);
 
-void CreateGLWindow (void);
 Boolean SetUp (Game & game);
-void DoKey (SInt8 theKey, SInt8 theCode);
 void DoUpdate (Game & game);
 
-void DoEvent (void);
 void CleanUp (void);
 
-
 // statics/globals (internal only) ------------------------------------------
-#ifndef WIN32
-typedef struct tagPOINT { 
-  int x;
-  int y;
-} POINT, *PPOINT; 
-#endif
-
-
 
 #ifdef _MSC_VER
 #pragma warning(push)
@@ -192,53 +151,17 @@ static void GLAPIENTRY glDeleteTextures_doNothing(GLsizei n, const GLuint *textu
     // no-op.
 }
 
-
-
-void sdlGetCursorPos(POINT *pt)
-{
-    int x, y;
-    SDL_GetMouseState(&x, &y);
-    pt->x = x;
-    pt->y = y;
-}
-#define GetCursorPos(x) sdlGetCursorPos(x)
-#define SetCursorPos(x, y) SDL_WarpMouse(x, y)
-#define ScreenToClient(x, pt)
-#define ClientToScreen(x, pt)
 #ifdef MessageBox
 #undef MessageBox
 #endif
 #define MessageBox(hwnd,text,title,flags) STUBBED("msgbox")
 
-
-Point delta;
-
-static bool g_button, fullscreen = true;
-
-
 // Menu defs
-enum 
-{
-       kFileQuit = 1
-};
-
-enum 
-{
-       kForegroundSleep = 10,
-       kBackgroundSleep = 10000
-};
-
 
 int kContextWidth;
 int kContextHeight;
 
-const RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
-
-GLuint gFontList;
-char gcstrMode [256] = "";
-
-UInt32 gSleepTime = kForegroundSleep;
-Boolean gDone = false, gfFrontProcess = true;
+Boolean gDone = false;
 
 Game * pgame = 0;
 
@@ -261,190 +184,12 @@ bool cmdline(const char *cmd)
     return false;
 }
 
-
-// --------------------------------------------------------------------------
-
-void ReportError (char * strError)
-{
-#ifdef _MSC_VER  // !!! FIXME.  --ryan.
-       throw std::exception( strError);
-#endif
-
-       /*      char errMsgCStr [256];
-       Str255 strErr;
-
-       sprintf (errMsgCStr, "%s", strError); 
-
-       // out as debug string
-       CToPStr (strErr, errMsgCStr);
-       DebugStr (strErr);
-       */
-}
-
-void SetupDSpFullScreen ()
-{
-}
-
-
-void ShutdownDSp ()
-{
-}
-
-
 //-----------------------------------------------------------------------------------------------------------------------
 
 // OpenGL Drawing
 
-void DrawGL (Game & game)
-{
-       if ( stereomode == stereoNone ) {
-               game.DrawGLScene(stereoCenter);
-       } else {
-               game.DrawGLScene(stereoLeft);
-               game.DrawGLScene(stereoRight);
-       }
-}
-
-
-static KeyMap g_theKeys;
-
-void SetKey( int key)
-{
-    g_theKeys[ key >> 3] |= (1 << (key & 7));
-}
-
-void ClearKey( int key)
-{
-    g_theKeys[ key >> 3] &= (0xff ^ (1 << (key & 7)));
-}
-
-void GetKeys(  unsigned char theKeys[16])
-{
-    memcpy( theKeys, &g_theKeys, 16);
-}
-
-Boolean Button()
-{
-    return g_button;
-}
-
-
-#define MAX_SDLKEYS SDLK_LAST
-static unsigned short KeyTable[MAX_SDLKEYS];
-
-static void initSDLKeyTable(void)
-{
-    memset(KeyTable, 0xFF, sizeof (KeyTable));
-    KeyTable[SDLK_BACKSPACE] = MAC_DELETE_KEY;
-    KeyTable[SDLK_TAB] = MAC_TAB_KEY;
-    KeyTable[SDLK_RETURN] = MAC_RETURN_KEY;
-    KeyTable[SDLK_ESCAPE] = MAC_ESCAPE_KEY;
-    KeyTable[SDLK_SPACE] = MAC_SPACE_KEY;
-    KeyTable[SDLK_PAGEUP] = MAC_PAGE_UP_KEY;
-    KeyTable[SDLK_PAGEDOWN] = MAC_PAGE_DOWN_KEY;
-    KeyTable[SDLK_END] = MAC_END_KEY;
-    KeyTable[SDLK_HOME] = MAC_HOME_KEY;
-    KeyTable[SDLK_LEFT] = MAC_ARROW_LEFT_KEY;
-    KeyTable[SDLK_UP] = MAC_ARROW_UP_KEY;
-    KeyTable[SDLK_RIGHT] = MAC_ARROW_RIGHT_KEY;
-    KeyTable[SDLK_DOWN] = MAC_ARROW_DOWN_KEY;
-    KeyTable[SDLK_INSERT] = MAC_INSERT_KEY;
-    KeyTable[SDLK_DELETE] = MAC_DEL_KEY;
-    KeyTable[SDLK_0] = MAC_0_KEY;
-    KeyTable[SDLK_1] = MAC_1_KEY;
-    KeyTable[SDLK_2] = MAC_2_KEY;
-    KeyTable[SDLK_3] = MAC_3_KEY;
-    KeyTable[SDLK_4] = MAC_4_KEY;
-    KeyTable[SDLK_5] = MAC_5_KEY;
-    KeyTable[SDLK_6] = MAC_6_KEY;
-    KeyTable[SDLK_7] = MAC_7_KEY;
-    KeyTable[SDLK_8] = MAC_8_KEY;
-    KeyTable[SDLK_9] = MAC_9_KEY;
-    KeyTable[SDLK_a] = MAC_A_KEY;
-    KeyTable[SDLK_b] = MAC_B_KEY;
-    KeyTable[SDLK_c] = MAC_C_KEY;
-    KeyTable[SDLK_d] = MAC_D_KEY;
-    KeyTable[SDLK_e] = MAC_E_KEY;
-    KeyTable[SDLK_f] = MAC_F_KEY;
-    KeyTable[SDLK_g] = MAC_G_KEY;
-    KeyTable[SDLK_h] = MAC_H_KEY;
-    KeyTable[SDLK_i] = MAC_I_KEY;
-    KeyTable[SDLK_j] = MAC_J_KEY;
-    KeyTable[SDLK_k] = MAC_K_KEY;
-    KeyTable[SDLK_l] = MAC_L_KEY;
-    KeyTable[SDLK_m] = MAC_M_KEY;
-    KeyTable[SDLK_n] = MAC_N_KEY;
-    KeyTable[SDLK_o] = MAC_O_KEY;
-    KeyTable[SDLK_p] = MAC_P_KEY;
-    KeyTable[SDLK_q] = MAC_Q_KEY;
-    KeyTable[SDLK_r] = MAC_R_KEY;
-    KeyTable[SDLK_s] = MAC_S_KEY;
-    KeyTable[SDLK_t] = MAC_T_KEY;
-    KeyTable[SDLK_u] = MAC_U_KEY;
-    KeyTable[SDLK_v] = MAC_V_KEY;
-    KeyTable[SDLK_w] = MAC_W_KEY;
-    KeyTable[SDLK_x] = MAC_X_KEY;
-    KeyTable[SDLK_y] = MAC_Y_KEY;
-    KeyTable[SDLK_z] = MAC_Z_KEY;
-    KeyTable[SDLK_KP0] = MAC_NUMPAD_0_KEY;
-    KeyTable[SDLK_KP1] = MAC_NUMPAD_1_KEY;
-    KeyTable[SDLK_KP2] = MAC_NUMPAD_2_KEY;
-    KeyTable[SDLK_KP3] = MAC_NUMPAD_3_KEY;
-    KeyTable[SDLK_KP4] = MAC_NUMPAD_4_KEY;
-    KeyTable[SDLK_KP5] = MAC_NUMPAD_5_KEY;
-    KeyTable[SDLK_KP6] = MAC_NUMPAD_6_KEY;
-    KeyTable[SDLK_KP7] = MAC_NUMPAD_7_KEY;
-    KeyTable[SDLK_KP8] = MAC_NUMPAD_8_KEY;
-    KeyTable[SDLK_KP9] = MAC_NUMPAD_9_KEY;
-    KeyTable[SDLK_KP_MULTIPLY] = MAC_NUMPAD_ASTERISK_KEY;
-    KeyTable[SDLK_KP_PLUS] = MAC_NUMPAD_PLUS_KEY;
-    KeyTable[SDLK_KP_ENTER] = MAC_NUMPAD_ENTER_KEY;
-    KeyTable[SDLK_KP_MINUS] = MAC_NUMPAD_MINUS_KEY;
-    KeyTable[SDLK_KP_PERIOD] = MAC_NUMPAD_PERIOD_KEY;
-    KeyTable[SDLK_KP_DIVIDE] = MAC_NUMPAD_SLASH_KEY;
-    KeyTable[SDLK_F1] = MAC_F1_KEY;
-    KeyTable[SDLK_F2] = MAC_F2_KEY;
-    KeyTable[SDLK_F3] = MAC_F3_KEY;
-    KeyTable[SDLK_F4] = MAC_F4_KEY;
-    KeyTable[SDLK_F5] = MAC_F5_KEY;
-    KeyTable[SDLK_F6] = MAC_F6_KEY;
-    KeyTable[SDLK_F7] = MAC_F7_KEY;
-    KeyTable[SDLK_F8] = MAC_F8_KEY;
-    KeyTable[SDLK_F9] = MAC_F9_KEY;
-    KeyTable[SDLK_F10] = MAC_F10_KEY;
-    KeyTable[SDLK_F11] = MAC_F11_KEY;
-    KeyTable[SDLK_F12] = MAC_F12_KEY;
-    KeyTable[SDLK_SEMICOLON] = MAC_SEMICOLON_KEY;
-    KeyTable[SDLK_PLUS] = MAC_PLUS_KEY;
-    KeyTable[SDLK_COMMA] = MAC_COMMA_KEY;
-    KeyTable[SDLK_MINUS] = MAC_MINUS_KEY;
-    KeyTable[SDLK_PERIOD] = MAC_PERIOD_KEY;
-    KeyTable[SDLK_SLASH] = MAC_SLASH_KEY;
-    KeyTable[SDLK_BACKQUOTE] = MAC_TILDE_KEY;
-    KeyTable[SDLK_LEFTBRACKET] = MAC_LEFTBRACKET_KEY;
-    KeyTable[SDLK_BACKSLASH] = MAC_BACKSLASH_KEY;
-    KeyTable[SDLK_RIGHTBRACKET] = MAC_RIGHTBRACKET_KEY;
-    KeyTable[SDLK_QUOTE] = MAC_APOSTROPHE_KEY;
-}
-
-static inline int clamp_sdl_mouse_button(Uint8 button)
-{
-    if (button == 2)   // right mouse button is button 3 in SDL.
-        button = 3;
-    else if (button == 3)
-        button = 2;
-
-    if ((button >= 1) && (button <= 3))
-        return button - 1;
-    return -1;
-}
-
 static void sdlEventProc(const SDL_Event &e, Game &game)
 {
-    int val;
-    bool skipkey = false;
-    SDLMod mod;
-
     switch(e.type)
        {
         case SDL_MOUSEMOTION:
@@ -452,93 +197,14 @@ static void sdlEventProc(const SDL_Event &e, Game &game)
             game.deltav += e.motion.yrel;
             return;
 
-               case SDL_MOUSEBUTTONDOWN:
-                       {
-                val = clamp_sdl_mouse_button(e.button.button);
-                if ((val >= 0) && (val <= 2))
-                {
-                    if (val == 0)
-                                   g_button = true;
-                               buttons[val] = true;
-                }
-                       }
-                       return;
-
-               case SDL_MOUSEBUTTONUP:
-                       {
-                val = clamp_sdl_mouse_button(e.button.button);
-                if ((val >= 0) && (val <= 2))
-                {
-                    if (val == 0)
-                                   g_button = false;
-                               buttons[val] = false;
-                }
-                       }
-            return;
-
         case SDL_KEYDOWN:
-            if (e.key.keysym.sym == SDLK_g)
-            {
-                if (e.key.keysym.mod & KMOD_CTRL)
-                {
-                    skipkey = true;
-                    SDL_GrabMode mode = SDL_GRAB_ON;
-                    if ((SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) == 0)
-                    {
-                        mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
-                        mode = (mode==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON;
-                    }
-                    SDL_WM_GrabInput(mode);
-                }
-            }
-
-            else if (e.key.keysym.sym == SDLK_RETURN)
-            {
-                if (e.key.keysym.mod & KMOD_ALT)
-                {
-                    skipkey = true;
-                    SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
-                }
-            }
-
-            if ((!skipkey) && (e.key.keysym.sym < SDLK_LAST))
-            {
-                if (KeyTable[e.key.keysym.sym] != 0xffff)
-                    SetKey(KeyTable[e.key.keysym.sym]);
+            if ((e.key.keysym.sym == SDLK_g) &&
+                               (e.key.keysym.mod & KMOD_CTRL) &&
+                               !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN) ) {
+                               SDL_WM_GrabInput( ((SDL_WM_GrabInput(SDL_GRAB_QUERY)==SDL_GRAB_ON) ? SDL_GRAB_OFF:SDL_GRAB_ON) );
+                       } else if ( (e.key.keysym.sym == SDLK_RETURN) && (e.key.keysym.mod & KMOD_ALT) ) {
+                               SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
             }
-
-            mod = SDL_GetModState();
-            if (mod & KMOD_CTRL)
-                SetKey(MAC_CONTROL_KEY);
-            if (mod & KMOD_ALT)
-                SetKey(MAC_OPTION_KEY);
-            if (mod & KMOD_META)
-                SetKey(MAC_COMMAND_KEY);
-            if (mod & KMOD_SHIFT)
-                SetKey(MAC_SHIFT_KEY);
-            if (mod & KMOD_CAPS)
-                SetKey(MAC_CAPS_LOCK_KEY);
-
-            return;
-
-        case SDL_KEYUP:
-            if (e.key.keysym.sym < SDLK_LAST)
-            {
-                if (KeyTable[e.key.keysym.sym] != 0xffff)
-                    ClearKey(KeyTable[e.key.keysym.sym]);
-            }
-
-            mod = SDL_GetModState();
-            if ((mod & KMOD_CTRL) == 0)
-                ClearKey(MAC_CONTROL_KEY);
-            if ((mod & KMOD_ALT) == 0)
-                ClearKey(MAC_OPTION_KEY);
-            if ((mod & KMOD_META) == 0)
-                ClearKey(MAC_COMMAND_KEY);
-            if ((mod & KMOD_SHIFT) == 0)
-                ClearKey(MAC_SHIFT_KEY);
-            if ((mod & KMOD_CAPS) == 0)
-                ClearKey(MAC_CAPS_LOCK_KEY);
             return;
     }
 }
@@ -554,20 +220,21 @@ Boolean SetUp (Game & game)
 
        LOGFUNC;
 
-       randSeed = UpTime().lo;
-
        osx = 0;
        cellophane=0;
        texdetail=4;
-       terraindetail=2;
        slomospeed=0.25;
        slomofreq=8012;
        numplayers=1;
        
        DefaultSettings(game);
 
-       selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
-
+    if (!SDL_WasInit(SDL_INIT_VIDEO))
+        if (SDL_Init(SDL_INIT_VIDEO) == -1)
+        {
+            fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
+            return false;
+        }
        if(!LoadSettings(game)) {
                fprintf(stderr, "Failed to load config, creating default\n");
                SaveSettings(game);
@@ -576,63 +243,48 @@ Boolean SetUp (Game & game)
                kBitsPerPixel=16;
        }
 
+       if (SDL_GL_LoadLibrary(NULL) == -1)
+       {
+               fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
+               SDL_Quit();
+               return false;
+       }
 
-       selectDetail(kContextWidth, kContextHeight, kBitsPerPixel, detail);
-
-       SetupDSpFullScreen();
-
-
-    if (!SDL_WasInit(SDL_INIT_VIDEO))
-    {
-        if (SDL_Init(SDL_INIT_VIDEO) == -1)
-        {
-            fprintf(stderr, "SDL_Init() failed: %s\n", SDL_GetError());
-            return false;
-        }
-
-        if (SDL_GL_LoadLibrary(NULL) == -1)
-        {
-            fprintf(stderr, "SDL_GL_LoadLibrary() failed: %s\n", SDL_GetError());
-            SDL_Quit();
-            return false;
-        }
-
-        SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
-        if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
-            res = hardcoded_resolutions;
+       SDL_Rect **res = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_OPENGL);
+       if ( (res == NULL) || (res == ((SDL_Rect **)-1)) || (res[0] == NULL) || (res[0]->w < 640) || (res[0]->h < 480) )
+               res = hardcoded_resolutions;
 
-        // reverse list (it was sorted biggest to smallest by SDL)...
-        int count;
-        for (count = 0; res[count]; count++)
-        {
-            if ((res[count]->w < 640) || (res[count]->h < 480))
-                break;   // sane lower limit.
-        }
+       // reverse list (it was sorted biggest to smallest by SDL)...
+       int count;
+       for (count = 0; res[count]; count++)
+       {
+               if ((res[count]->w < 640) || (res[count]->h < 480))
+                       break;   // sane lower limit.
+       }
 
-        static SDL_Rect *resolutions_block = NULL;
-        resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
-        resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
-        if ((resolutions_block == NULL) || (resolutions == NULL))
-        {
-            SDL_Quit();
-            fprintf(stderr, "Out of memory!\n");
-            return false;
-        }
+       static SDL_Rect *resolutions_block = NULL;
+       resolutions_block = (SDL_Rect*) realloc(resolutions_block, sizeof (SDL_Rect) * count);
+       resolutions = (SDL_Rect**) realloc(resolutions, sizeof (SDL_Rect *) * (count + 1));
+       if ((resolutions_block == NULL) || (resolutions == NULL))
+       {
+               SDL_Quit();
+               fprintf(stderr, "Out of memory!\n");
+               return false;
+       }
 
-        resolutions[count--] = NULL;
-        for (int i = 0; count >= 0; i++, count--)
-        {
-            memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
-            resolutions[count] = &resolutions_block[count];
-        }
+       resolutions[count--] = NULL;
+       for (int i = 0; count >= 0; i++, count--)
+       {
+               memcpy(&resolutions_block[count], res[i], sizeof (SDL_Rect));
+               resolutions[count] = &resolutions_block[count];
+       }
 
-        if (cmdline("showresolutions"))
-        {
-            printf("Resolutions we think are okay:\n");
-            for (int i = 0; resolutions[i]; i++)
-                printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
-        }
-    }
+       if (cmdline("showresolutions"))
+       {
+               printf("Resolutions we think are okay:\n");
+               for (int i = 0; resolutions[i]; i++)
+                       printf("  %d x %d\n", (int) resolutions[i]->w, (int) resolutions[i]->h);
+       }
 
     Uint32 sdlflags = SDL_OPENGL;
     if (!cmdline("windowed"))
@@ -644,6 +296,9 @@ Boolean SetUp (Game & game)
 
     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
     SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 1);
+#if SDL_VERSION_ATLEAST(1, 2, 10)
+    SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vblsync);
+#endif
     
     if (SDL_SetVideoMode(kContextWidth, kContextHeight, 0, sdlflags) == NULL)
     {
@@ -750,7 +405,7 @@ Boolean SetUp (Game & game)
 static void DoMouse(Game & game)
 {
 
-       if(mainmenu||(abs(game.deltah)<10*realmultiplier*1000&&abs(game.deltav)<10*realmultiplier*1000))
+       if(mainmenu|| ( (abs(game.deltah)<10*realmultiplier*1000) && (abs(game.deltav)<10*realmultiplier*1000) ))
        {
                game.deltah *= usermousesensitivity;
                game.deltav *= usermousesensitivity;
@@ -768,19 +423,6 @@ static void DoMouse(Game & game)
 
 }
 
-
-
-// --------------------------------------------------------------------------
-
-void DoKey (SInt8 theKey, SInt8 theCode)
-{
-       // do nothing
-}
-
-// --------------------------------------------------------------------------
-
-
-
 void DoFrameRate (int update)
 {      
        static long frames = 0;
@@ -796,9 +438,9 @@ void DoFrameRate (int update)
                deltaTime /= 1000.0;
 
        multiplier=deltaTime;
-       if(multiplier<.001)multiplier=.001;
-       if(multiplier>10)multiplier=10;
-       if(update)frametime = currTime; // reset for next time interval
+       if(multiplier<.001) multiplier=.001;
+       if(multiplier>10) multiplier=10;
+       if(update) frametime = currTime;        // reset for next time interval
 
        deltaTime = (float) AbsoluteDeltaToDuration (currTime, time);
 
@@ -830,7 +472,6 @@ void DoUpdate (Game & game)
 
        count = multiplier*sps;
        if(count<2)count=2;
-       //if(count>10)count=10;
 
        realmultiplier=multiplier;
        multiplier*=gamespeed;
@@ -838,9 +479,7 @@ void DoUpdate (Game & game)
        if(difficulty==0)multiplier*=.8;
 
        if(game.loading==4)multiplier*=.00001;
-       //multiplier*.9;
        if(slomo&&!mainmenu)multiplier*=slomospeed;
-       //if(freeze)multiplier*=0.00001;
        oldmult=multiplier;
        multiplier/=(float)count;
 
@@ -889,7 +528,7 @@ void DoUpdate (Game & game)
                num_channels = 0;
        }
 */
-       DrawGL (game);
+       game.DrawGL();
 }
 
 // --------------------------------------------------------------------------
@@ -899,11 +538,6 @@ void CleanUp (void)
 {
        LOGFUNC;
 
-//     game.Dispose();
-
-
-
-
     SDL_Quit();
     #define GL_FUNC(ret,fn,params,call,rt) p##fn = NULL;
     #include "glstubs.h"
@@ -922,29 +556,6 @@ static bool IsFocused()
 }
 
 
-static void launch_web_browser(const char *url)
-{
-#ifdef WIN32
-    ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL);
-
-#elif (defined(__APPLE__) && defined(__MACH__))
-    const char *fmt = "open '%s'";
-    const size_t len = strlen(fmt) + strlen(url) + 16;
-    char *buf = new char[len];
-    snprintf(buf, len, fmt, url);
-    system(buf);
-    delete[] buf;
-
-#elif PLATFORM_LINUX
-    const char *fmt = "PATH=$PATH:. xdg-open '%s'";
-    const size_t len = strlen(fmt) + strlen(url) + 16;
-    char *buf = new char[len];
-    snprintf(buf, len, fmt, url);
-    system(buf);
-    delete[] buf;
-#endif
-}
-
 
 #ifndef WIN32
 // (code lifted from physfs: http://icculus.org/physfs/ ... zlib license.)
@@ -1062,13 +673,8 @@ int main(int argc, char **argv)
 
        LOGFUNC;
 
-       memset( &g_theKeys, 0, sizeof( KeyMap));
-
-    initSDLKeyTable();
-
        try
        {
-               bool regnow = false;
                {
                        Game game;
                        pgame = &game;
@@ -1092,17 +698,18 @@ int main(int argc, char **argv)
                                        game.deltah = 0;
                                        game.deltav = 0;
                                        SDL_Event e;
-                                       // message pump
-                                       while( SDL_PollEvent( &e ) )
-                                       {
-                                               if( e.type == SDL_QUIT )
+                                       if(!game.isWaiting()) {
+                                               // message pump
+                                               while( SDL_PollEvent( &e ) )
                                                {
-                                                       gDone=true;
-                                                       break;
+                                                       if( e.type == SDL_QUIT )
+                                                       {
+                                                               gDone=true;
+                                                               break;
+                                                       }
+                                                       sdlEventProc(e, game);
                                                }
-                                               sdlEventProc(e, game);
                                        }
-                               
 
                                        // game
                                        DoUpdate(game);
@@ -1126,26 +733,11 @@ int main(int argc, char **argv)
                                }
                        }
 
-                       regnow = game.registernow;
                }
                pgame = 0;
 
                CleanUp ();
-//             if(game.registernow){
-               if(regnow)
-               {
-            #if (defined(__APPLE__) && defined(__MACH__))
-            launch_web_browser("http://www.wolfire.com/purchase/lugaru/mac");
-            #elif PLATFORM_LINUX
-            launch_web_browser("http://www.wolfire.com/purchase/lugaru/linux");
-            #else
-            launch_web_browser("http://www.wolfire.com/purchase/lugaru/pc");
-            #endif
-               }
 
-        #if PLATFORM_LINUX  // (this may not be necessary any more.)
-        _exit(0);  // !!! FIXME: hack...crashes on exit!
-        #endif
                return 0;
        }
        catch (const std::exception& error)
@@ -1167,100 +759,21 @@ int main(int argc, char **argv)
 
 
 
-       // --------------------------------------------------------------------------
-
-
-
-       bool selectDetail(int & width, int & height, int & bpp, int & detail)
-       {
-               bool res = true;
-
-               // currently with SDL, we just use whatever is requested
-               //  and don't care.  --ryan.
-               
-
-               return res;
-       }
-
-       extern int channels[100];
-       extern OPENAL_SAMPLE * samp[100];
-       extern OPENAL_STREAM * strm[20];
-
-       extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
-       {
-               const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
-               if (currSample && currSample == samp[chan])
-               {
-                       if (OPENAL_GetPaused(channels[chan]))
-                       {
-                               OPENAL_StopSound(channels[chan]);
-                               channels[chan] = OPENAL_FREE;
-                       }
-                       else if (OPENAL_IsPlaying(channels[chan]))
-                       {
-                               int loop_mode = OPENAL_GetLoopMode(channels[chan]);
-                               if (loop_mode & OPENAL_LOOP_OFF)
-                               {
-                                       channels[chan] = OPENAL_FREE;
-                               }
-                       }
-               }
-               else
-               {
-                       channels[chan] = OPENAL_FREE;
-               }
-
-               channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
-               if (channels[chan] < 0)
-               {
-                       channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
-               }
-       }
-
-       extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
-       {
-               const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
-               if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
-               {
-                               OPENAL_StopSound(channels[chan]);
-                               OPENAL_Stream_Stop(sptr);
-               }
-               else
-               {
-                       OPENAL_Stream_Stop(sptr);
-                       channels[chan] = OPENAL_FREE;
-               }
-
-               channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
-               if (channels[chan] < 0)
-               {
-                       channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
-               }
-       }
-
-
-       bool LoadImage(const char * fname, TGAImageRec & tex)
-       {
-               bool res = true;
+// --------------------------------------------------------------------------
 
-               if ( tex.data == NULL )
-               {
-                       return false;
-               }
 
-       
-        res = load_image(fname, tex);
-    
-
-               return res;
-       }
+bool LoadImage(const char * fname, TGAImageRec & tex)
+{
+       if ( tex.data == NULL )
+               return false;
+       else
+               return load_image(fname, tex);
+}
 
-       void ScreenShot(const char * fname)
-       {
-  
-        save_image(fname);
-  
-       }
+void ScreenShot(const char * fname)
+{
+       
+}
 
 
 
@@ -1428,7 +941,7 @@ png_done:
 }
 
 
-static bool save_image(const char *file_name)
+bool save_image(const char *file_name)
 {
     const char *ptr = strrchr((char *)file_name, '.');
     if (ptr)
index 6a1def9bf91bff686c2d975bb43dd22f7e63a386..47212bd59ac3eee01265620103cc9898e86e4f63 100644 (file)
@@ -22,15 +22,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 /**> HEADER FILES <**/
 #include "Person.h"
 #include "openal_wrapper.h"
+#include "Animation.h"
+#include "Sounds.h"
+#include "Awards.h"
+#include "Game.h"
 
 extern float multiplier;
-extern Animation animation[animation_count];
-extern OPENAL_SAMPLE   *samp[100];
-extern int channels[100];
 extern Terrain terrain;
 extern float gravity;
 extern int environment;
-extern Sprites sprites;
 extern int detail;
 extern FRUSTUM frustum;
 extern XYZ viewer;
@@ -48,15 +48,11 @@ extern bool osx;
 extern bool autoslomo;
 extern float camerashake;
 extern float woozy;
-extern float terraindetail;
 extern float viewdistance;
 extern float blackout;
 extern int difficulty;
-extern Weapons weapons;
 extern bool decals;
 extern float fadestart;
-extern Person player[maxplayers];
-extern int numplayers;
 extern bool freeze;
 extern bool winfreeze;
 extern float flashamount,flashr,flashg,flashb;
@@ -69,15 +65,10 @@ extern bool tiltweird;
 extern bool midweird;
 extern bool proportionweird;
 extern bool vertexweird[6];
-extern GLubyte texturearray[512*512*3];
 extern XYZ envsound[30];
 extern float envsoundvol[30];
 extern float envsoundlife[30];
 extern int numenvsounds;
-extern int bonus;
-extern float bonusvalue;
-extern float bonustotal;
-extern float bonustime;
 extern int tutoriallevel;
 extern float smoketex;
 extern int tutorialstage;
@@ -85,112 +76,74 @@ extern bool reversaltrain;
 extern bool canattack;
 extern bool cananger;
 extern float damagedealt;
-extern float damagetaken;
 extern int hostile;
 extern float hostiletime;
 
-extern int mainmenu;
-
-extern int numfalls;
-extern int numflipfail;
-extern int numseen;
-extern int numswordattack;
-extern int numknifeattack;
-extern int numunarmedattack;
-extern int numescaped;
-extern int numflipped;
-extern int numwallflipped;
-extern int numthrowkill;
-extern int numafterkill;
-extern int numreversals;
-extern int numattacks;
-extern int maxalarmed;
 extern int indialogue;
 
 extern bool gamestarted;
 
-extern OPENAL_STREAM * strm[20];
-extern "C"     void PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
-
-void Person::CheckKick(){
-       static XYZ relative;
-       static int i;
-
-       float damagemult=1*power;
-       if(creature==wolftype)damagemult=2.5*power;
-       damagemult*=power;
-
-       if(hasvictim)
-               if(targetanimation==rabbitkickanim&&victim&&victim!=this&&currentframe>=2&&currentanimation==rabbitkickanim){
-                       if(findDistancefast(&coords,&victim->coords)<1.2){
-                               if(!victim->skeleton.free){
-                                       relative=velocity;
-                                       Normalise(&relative);
-                                       relative=coords+relative*1;
-                                       if(animation[victim->targetanimation].height!=lowheight){
-                                               victim->spurt=1;
-                                               DoBlood(.2,250);
-                                               float gLoc[3];
-                                               float vel[3];
-                                               gLoc[0]=victim->coords.x;
-                                               gLoc[1]=victim->coords.y;
-                                               gLoc[2]=victim->coords.z;
-                                               vel[0]=velocity.x;
-                                               vel[1]=velocity.y;
-                                               vel[2]=velocity.z;
-                                               if(tutoriallevel!=1){
-                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
-                                               }
-                                               victim->RagDoll(0);
-                                               relative=velocity;
-                                               relative.y=0;
-                                               Normalise(&relative);
-                                               for(i=0;i<victim->skeleton.num_joints;i++){
-                                                       victim->skeleton.joints[i].velocity+=relative*120*damagemult;
-                                               }
-                                               victim->Puff(neck);
-                                               victim->DoDamage(100*damagemult/victim->protectionhigh);
-                                               if(id==0)camerashake+=.4;
+Person player[maxplayers];
 
-                                               target=0;
-                                               currentframe=3;
-                                               targetanimation=backflipanim;
-                                               targetframe=4;
-                                               velocity=facing*-10;
-                                               velocity.y=5;
-                                               skeleton.free=0;
-                                               if(id==0)OPENAL_SetPaused(channels[whooshsound], false);
-
-                                               //if(victim->damage>victim->damagetolerance){
-                                               if(id==0){
-                                                       bonus=cannon;
-                                                       bonustime=0;
-                                                       bonusvalue=100;
-                                               }
-                                               //}
-                                       }
-                                       else if (victim->isCrouch()){
-                                               targetanimation=rabbitkickreversedanim;
-                                               currentanimation=rabbitkickreversedanim;
-                                               victim->currentanimation=rabbitkickreversalanim;
-                                               victim->targetanimation=rabbitkickreversalanim;
-                                               targettilt2=0;
-                                               currentframe=0;
-                                               targetframe=1;
-                                               target=0;
-                                               velocity=0;
-                                               victim->oldcoords=victim->coords;
-                                               coords=victim->coords;
-                                               victim->targetrotation=targetrotation;
-                                               victim->victim=this;
-                                       }
-                               }
-                       }
-               }
+void Person::CheckKick()
+{
+  if (!(hasvictim
+       && (targetanimation == rabbitkickanim
+           && victim
+           && victim != this
+           && currentframe >= 2
+           && currentanimation == rabbitkickanim)
+       && (findDistancefast(&coords,&victim->coords) < 1.2)
+       && (!victim->skeleton.free)))
+    return;
+
+  if (animation[victim->targetanimation].height!=lowheight)
+    {
+      float damagemult = (creature == wolftype ? 2.5 : 1.) * power * power;
+      XYZ relative = velocity;
+      relative.y=0;
+      Normalise(&relative);
+
+      victim->spurt=1;
+      DoBlood(.2,250);
+      if(tutoriallevel!=1)
+       emit_sound_at(heavyimpactsound, victim->coords);
+      victim->RagDoll(0);
+      for(int i=0;i<victim->skeleton.num_joints;i++){
+       victim->skeleton.joints[i].velocity+=relative*120*damagemult;
+      }
+      victim->Puff(neck);
+      victim->DoDamage(100*damagemult/victim->protectionhigh);
+      if(id==0)camerashake+=.4;
+
+      target=0;
+      currentframe=3;
+      targetanimation=backflipanim;
+      targetframe=4;
+      velocity=facing*-10;
+      velocity.y=5;
+      skeleton.free=0;
+      if(id==0)
+       resume_stream(whooshsound);
+
+      award_bonus(id, cannon);
+    }
+  else if (victim->isCrouch())
+    {
+      targetanimation=rabbitkickreversedanim;
+      currentanimation=rabbitkickreversedanim;
+      victim->currentanimation=rabbitkickreversalanim;
+      victim->targetanimation=rabbitkickreversalanim;
+      targettilt2=0;
+      currentframe=0;
+      targetframe=1;
+      target=0;
+      velocity=0;
+      victim->oldcoords=victim->coords;
+      coords=victim->coords;
+      victim->targetrotation=targetrotation;
+      victim->victim=this;
+    }
 }
 
 void Person::CatchFire(){
@@ -202,62 +155,20 @@ void Person::CatchFire(){
                if(skeleton.free)flatvelocity=skeleton.joints[howmany].velocity;
                if(!skeleton.free)flatfacing=DoRotation(DoRotation(DoRotation(skeleton.joints[howmany].position,0,0,tilt),tilt2,0,0),0,rotation,0)*scale+coords;
                if(skeleton.free)flatfacing=skeleton.joints[howmany].position*scale+coords;
-               sprites.MakeSprite(flamesprite, flatfacing,flatvelocity, 1,1,1, 2, 1);
+               Sprite::MakeSprite(flamesprite, flatfacing,flatvelocity, 1,1,1, 2, 1);
        }
 
        onfiredelay=0.5;
 
-       float gLoc[3];
-       float vel[3];
-       gLoc[0]=coords.x;
-       gLoc[1]=coords.y;
-       gLoc[2]=coords.z;
-       vel[0]=0;
-       vel[1]=0;
-       vel[2]=0;
-       PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-       OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-       OPENAL_SetVolume(channels[firestartsound], 256);
-       OPENAL_SetPaused(channels[firestartsound], false);
-
-       vel[0]=velocity.x;
-       vel[1]=velocity.y;
-       vel[2]=velocity.z;
-       //PlaySoundEx( firesound, samp[firesound], NULL, true);
-       PlayStreamEx( stream_firesound, strm[stream_firesound], NULL, true);
-       OPENAL_3D_SetAttributes(channels[stream_firesound], gLoc, vel);
-       OPENAL_SetVolume(channels[stream_firesound], 256);
-       OPENAL_SetPaused(channels[stream_firesound], false);
+       emit_sound_at(firestartsound, coords);
+
+       emit_stream_at(stream_firesound, coords);
 
        flamedelay=0;
 
        onfire=1;
 }
 
-bool Person::isIdle(){
-       if(targetanimation==sleepanim||targetanimation==sitanim||targetanimation==talkidleanim||targetanimation==hurtidleanim||targetanimation==bounceidleanim||targetanimation==talkidleanim||targetanimation==fightidleanim||targetanimation==knifefightidleanim||targetanimation==swordfightidleanim||targetanimation==swordfightidlebothanim||targetanimation==fightsidestep||targetanimation==wolfidle)return 1;
-       else return 0;
-}
-
-bool Person::isSitting(){
-       if(targetanimation==sitanim)return 1;
-       if(targetanimation==sitwallanim)return 1;
-       else return 0;
-}
-
-bool Person::isSleeping(){
-       if(targetanimation==sleepanim)return 1;
-       if(targetanimation==dead1anim)return 1;
-       if(targetanimation==dead2anim)return 1;
-       if(targetanimation==dead3anim)return 1;
-       if(targetanimation==dead4anim)return 1;
-       else return 0;
-}
-
-bool Person::wasIdle(){
-       if(currentanimation==sleepanim||currentanimation==talkidleanim||currentanimation==sitanim||currentanimation==hurtidleanim||currentanimation==bounceidleanim||currentanimation==fightidleanim||currentanimation==swordfightidleanim||currentanimation==swordfightidlebothanim||currentanimation==knifefightidleanim||currentanimation==fightsidestep||currentanimation==wolfidle)return 1;
-       else return 0;
-}
 int Person::getIdle(){
        if(indialogue!=-1&&howactive==typeactive&&creature==rabbittype)return talkidleanim;
        if(hasvictim&&victim!=this/*||(id==0&&attackkeydown)*/)if(/*(id==0&&attackkeydown)||*/(!victim->dead&&victim->aitype!=passivetype&&victim->aitype!=searchtype&&aitype!=passivetype&&aitype!=searchtype&&victim->id<numplayers)){
@@ -286,32 +197,12 @@ int Person::getIdle(){
        return 0;
 }
 
-bool Person::isCrouch(){
-       if(targetanimation==crouchanim||targetanimation==wolfcrouchanim)return 1;
-       else return 0;
-}
-
-
-bool Person::wasCrouch(){
-       if(currentanimation==crouchanim||currentanimation==wolfcrouchanim)return 1;
-       else return 0;
-}
 int Person::getCrouch(){
        if(creature==rabbittype)return crouchanim;
        if(creature==wolftype)return wolfcrouchanim;
        return 0;
 }
 
-bool Person::isRun(){
-       if(targetanimation==runanim||targetanimation==wolfrunanim||targetanimation==wolfrunninganim||targetanimation==rabbitrunninganim)return 1;
-       else return 0;
-}
-
-
-bool Person::wasRun(){
-       if(currentanimation==runanim||currentanimation==wolfrunanim||currentanimation==wolfrunninganim||currentanimation==rabbitrunninganim)return 1;
-       else return 0;
-}
 int Person::getRun(){
        if(creature==rabbittype&&(!superruntoggle||weaponactive!=-1))return runanim;
        if(creature==wolftype&&(!superruntoggle))return wolfrunanim;
@@ -321,99 +212,31 @@ int Person::getRun(){
        return 0;
 }
 
-bool Person::isStop(){
-       if(targetanimation==stopanim||targetanimation==wolfstopanim)return 1;
-       else return 0;
-}
-
-
-bool Person::wasStop(){
-       if(currentanimation==stopanim||currentanimation==wolfstopanim)return 1;
-       else return 0;
-}
 int Person::getStop(){
        if(creature==rabbittype)return stopanim;
        if(creature==wolftype)return wolfstopanim;
        return 0;
 }
 
-
-bool Person::isLanding(){
-       if(targetanimation==landanim||targetanimation==wolflandanim)return 1;
-       else return 0;
-}
-
-
-bool Person::wasLanding(){
-       if(currentanimation==landanim||currentanimation==wolflandanim)return 1;
-       else return 0;
-}
 int Person::getLanding(){
        if(creature==rabbittype)return landanim;
        if(creature==wolftype)return wolflandanim;
        return 0;
 }
 
-
-bool Person::isLandhard(){
-       if(targetanimation==landhardanim||targetanimation==wolflandhardanim)return 1;
-       else return 0;
-}
-
-
-bool Person::wasLandhard(){
-       if(currentanimation==landhardanim||currentanimation==wolflandhardanim)return 1;
-       else return 0;
-}
 int Person::getLandhard(){
        if(creature==rabbittype)return landhardanim;
        if(creature==wolftype)return wolflandhardanim;
        return 0;
 }
 
-
-bool Person::isFlip(){
-       if(targetanimation==flipanim||targetanimation==frontflipanim||targetanimation==backflipanim||targetanimation==rightflipanim||targetanimation==leftflipanim||targetanimation==walljumprightkickanim||targetanimation==walljumpleftkickanim)return 1;
-       else return 0;
-}
-
-bool Person::wasFlip(){
-       if(currentanimation==flipanim||currentanimation==frontflipanim||currentanimation==backflipanim||currentanimation==rightflipanim||currentanimation==leftflipanim||currentanimation==walljumprightkickanim||currentanimation==walljumpleftkickanim)return 1;
-       else return 0;
-}
-
-bool Person::isWallJump(){
-       if(targetanimation==walljumpfrontanim||targetanimation==walljumpbackanim||targetanimation==walljumpleftanim||targetanimation==walljumprightanim)return 1;
-       else return 0;
-}
-
-void SolidHitBonus();
-void SolidHitBonus(){
-       if(bonustime<1.5&&(bonus==fourxcombo||bonus==megacombo)){
-               bonus=megacombo;
-               bonustime=0;
-               bonusvalue=160;
-       }
-       else if(bonustime<1.5&&bonus==threexcombo){
-               bonus=fourxcombo;
-               bonustime=0;
-               bonusvalue=80;
-       }
-       else if(bonustime<1.5&&bonus==twoxcombo){
-               bonus=threexcombo;
-               bonustime=0;
-               bonusvalue=40;
-       }
-       else if(bonustime<1.5&&bonus==solidhit){
-               bonus=twoxcombo;
-               bonustime=0;
-               bonusvalue=20;
-       }
-       else {
-               bonus=solidhit;
-               bonustime=0;
-               bonusvalue=10;
-       }
+static void
+SolidHitBonus(int playerid)
+{
+  if (bonustime < 1.5 && bonus >= solidhit && bonus <= megacombo)
+    award_bonus(playerid, bonus == megacombo ? bonus : bonus + 1);
+  else
+    award_bonus(playerid, solidhit);
 }
 
 void Person::DoBlood(float howmuch,int which){
@@ -435,36 +258,33 @@ void Person::DoBlood(float howmuch,int which){
                                if(skeleton.free)bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[head]].velocity,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
                                if(!skeleton.free)bloodvel+=DoRotation(velocity,((float)(Random()%100))/4,((float)(Random()%100))/4,0)*scale;
                                if(skeleton.free){
-                                       sprites.MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                       sprites.MakeSprite(bloodflamesprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .3, 1);
+                                       Sprite::MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                       Sprite::MakeSprite(bloodflamesprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .3, 1);
                                }
                                if(!skeleton.free){
-                                       sprites.MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                       sprites.MakeSprite(bloodflamesprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .3, 1);
+                                       Sprite::MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                       Sprite::MakeSprite(bloodflamesprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .3, 1);
                                }
                        }
                        if(Random()%2==0)
                                for(int i=0;i<3;i++){
                                        if(Random()%2!=0){
                                                bloodvel=0;
-                                               if(!skeleton.free){
+                                               if(skeleton.free) {
+                                                       bloodvel-=DoRotation(skeleton.forward*10*scale,((float)(Random()%100))/4,((float)(Random()%100))/4,0);
+                                                       bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[head]].velocity,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
+                                               } else {
                                                        bloodvel.z=10;
                                                        bloodvel=DoRotation(bloodvel,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
+                                                       bloodvel+=DoRotation(velocity,((float)(Random()%100))/4,((float)(Random()%100))/4,0)*scale;
                                                }
-                                               if(skeleton.free){
-                                                       bloodvel-=DoRotation(skeleton.forward*10*scale,((float)(Random()%100))/4,((float)(Random()%100))/4,0);
-                                               }
-                                               if(skeleton.free)bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[head]].velocity,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
-                                               if(!skeleton.free)bloodvel+=DoRotation(velocity,((float)(Random()%100))/4,((float)(Random()%100))/4,0)*scale;
                                                bloodvel*=.2;
                                                if(skeleton.free){
-                                                       sprites.MakeSprite(splintersprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                                       sprites.special[sprites.numsprites-1]=3;
-                                               }
-                                               if(!skeleton.free){
-                                                       sprites.MakeSprite(splintersprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                                       sprites.special[sprites.numsprites-1]=3;
+                                                       Sprite::MakeSprite(splintersprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                               } else {
+                                                       Sprite::MakeSprite(splintersprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
                                                }
+                                               Sprite::setLastSpriteSpecial(3);
                                        }
                                }
                }
@@ -478,16 +298,16 @@ void Person::DoBlood(float howmuch,int which){
                                        bleedxint=abs(Random()%512);
                                        bleedyint=abs(Random()%512);
                                }
-                               if(creature==wolftype)
-                                       while(wolfbloodText[bleedxint*512*3+bleedyint*3+0]>which+4||wolfbloodText[bleedxint*512*3+bleedyint*3+0]<which-4||bleedxint<10||bleedyint<10||bleedxint>500||bleedyint>500){
-                                               bleedxint=abs(Random()%512);
-                                               bleedyint=abs(Random()%512);
-                                       }
-                                       bleedy=bleedxint;
-                                       bleedx=bleedyint;
-                                       bleedy/=realtexdetail;
-                                       bleedx/=realtexdetail;
-                                       direction=abs(Random()%2)*2-1;
+                       if(creature==wolftype)
+                               while(wolfbloodText[bleedxint*512*3+bleedyint*3+0]>which+4||wolfbloodText[bleedxint*512*3+bleedyint*3+0]<which-4||bleedxint<10||bleedyint<10||bleedxint>500||bleedyint>500){
+                                       bleedxint=abs(Random()%512);
+                                       bleedyint=abs(Random()%512);
+                               }
+                       bleedy=bleedxint;
+                       bleedx=bleedyint;
+                       bleedy/=realtexdetail;
+                       bleedx/=realtexdetail;
+                       direction=abs(Random()%2)*2-1;
                }
 
        }
@@ -502,14 +322,6 @@ void Person::DoBloodBig(float howmuch,int which){
        if(tutoriallevel!=1||id==0)
                if(aitype!=playercontrolled&&howmuch>0){
                        int whichsound=-1;
-                       float gLoc[3];
-                       float vel[3];
-                       gLoc[0]=coords.x;
-                       gLoc[1]=coords.y;
-                       gLoc[2]=coords.z;
-                       vel[0]=velocity.x;
-                       vel[1]=velocity.y;
-                       vel[2]=velocity.z;
 
                        if(creature==wolftype){
                                int i=abs(Random()%2);
@@ -531,12 +343,8 @@ void Person::DoBloodBig(float howmuch,int which){
                                //if(i==2)whichsound=rabbitpain2sound;
                        }
 
-                       if(whichsound!=-1){
-                               PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[whichsound], 512);
-                               OPENAL_SetPaused(channels[whichsound], false);
-                       }
+                       if(whichsound!=-1)
+                         emit_sound_at(whichsound, coords);
                }
 
                if(id==0&&howmuch>0){
@@ -562,12 +370,12 @@ void Person::DoBloodBig(float howmuch,int which){
                                        if(skeleton.free)bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[head]].velocity,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
                                        if(!skeleton.free)bloodvel+=DoRotation(velocity,((float)(Random()%100))/4,((float)(Random()%100))/4,0)*scale;
                                        if(skeleton.free){
-                                               sprites.MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                               sprites.MakeSprite(bloodflamesprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .3, 1);
+                                               Sprite::MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                               Sprite::MakeSprite(bloodflamesprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .3, 1);
                                        }
                                        if(!skeleton.free){
-                                               sprites.MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                               sprites.MakeSprite(bloodflamesprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .3, 1);
+                                               Sprite::MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                               Sprite::MakeSprite(bloodflamesprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .3, 1);
                                        }
                                }
                        }
@@ -667,8 +475,7 @@ void Person::DoBloodBig(float howmuch,int which){
                                                                }
                                                        }
                                                        glBindTexture(GL_TEXTURE_2D,skeleton.drawmodel.textureptr);
-                                                       if(detail!=2||osx)DoMipmaps(5,0,0,skeleton.skinsize,skeleton.skinsize);
-                                                       else DoMipmaps(0,startx/realtexdetail,endx/realtexdetail,starty/realtexdetail,endy/realtexdetail);
+                                                       DoMipmaps();
 
                                                        bleedxint=0;
                                                        bleedyint=0;
@@ -789,12 +596,12 @@ bool Person::DoBloodBigWhere(float howmuch,int which, XYZ where){
                                        if(skeleton.free)bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[head]].velocity,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
                                        if(!skeleton.free)bloodvel+=DoRotation(velocity,((float)(Random()%100))/4,((float)(Random()%100))/4,0)*scale;
                                        if(skeleton.free){
-                                               sprites.MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                               sprites.MakeSprite(bloodflamesprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .3, 1);
+                                               Sprite::MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                               Sprite::MakeSprite(bloodflamesprite, skeleton.joints[skeleton.jointlabels[head]].position*scale+coords,bloodvel, 1,1,1, .3, 1);
                                        }
                                        if(!skeleton.free){
-                                               sprites.MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
-                                               sprites.MakeSprite(bloodflamesprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .3, 1);
+                                               Sprite::MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                               Sprite::MakeSprite(bloodflamesprite, DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .3, 1);
                                        }
                                }
                        }
@@ -896,8 +703,7 @@ bool Person::DoBloodBigWhere(float howmuch,int which, XYZ where){
                                                                }
                                                        }
                                                        glBindTexture(GL_TEXTURE_2D,skeleton.drawmodel.textureptr);
-                                                       if(detail!=2||osx)DoMipmaps(5,0,0,skeleton.skinsize,skeleton.skinsize);
-                                                       else DoMipmaps(0,startx/realtexdetail,endx/realtexdetail,starty/realtexdetail,endy/realtexdetail);
+                                                       DoMipmaps();
 
                                                        bleedy=(1+coordsy)*512;
                                                        bleedx=coordsx*512;
@@ -927,427 +733,326 @@ bool Person::DoBloodBigWhere(float howmuch,int which, XYZ where){
 }
 
 
-void Person::DoMipmaps(int howmanylevels,float startx, float endx, float starty, float endy){
-       int i,j,k;
-       static float temp;
-       static int bytesPerPixel=3;
-       static int newsize,totalsize,rowsize,bigstep,smallstep,sum;
-       static int newstartx,newstarty,newendx,newendy;
-       static int newnewstartx,newnewstarty,newnewendx,newnewendy;
-       static int which;
-       static float sizemult;
-       /*
-       for(i=0;i<skeleton.skinsize*skeleton.skinsize*bytesPerPixel;i++){
-       texture[i]=skeleton.skinText[i];
-       }
-       */
-       if((!osx||howmanylevels)){
-
-               if(startx<0)startx=0;
-               if(starty<0)starty=0;
-               if(endx>skeleton.skinsize-1)endx=skeleton.skinsize-1;
-               if(endy>skeleton.skinsize-1)endy=skeleton.skinsize-1;
-               if((endx>startx&&endy>starty)||howmanylevels){
-
-                       newstartx=startx;
-                       newstarty=starty;
-                       newendx=endx;
-                       newendy=endy;
-
-                       for(i=startx;i<endx;i++){
-                               for(j=starty;j<endy;j++){
-                                       texturearray[(i-newstartx)*(newendy-newstarty)*3+(j-newstarty)*3+0]=skeleton.skinText[i*skeleton.skinsize*3+j*3+0];
-                                       texturearray[(i-newstartx)*(newendy-newstarty)*3+(j-newstarty)*3+1]=skeleton.skinText[i*skeleton.skinsize*3+j*3+1];
-                                       texturearray[(i-newstartx)*(newendy-newstarty)*3+(j-newstarty)*3+2]=skeleton.skinText[i*skeleton.skinsize*3+j*3+2];
-                               }
-                       }
-
-                       glBindTexture(GL_TEXTURE_2D,skeleton.drawmodel.textureptr);
-
-                       if(!howmanylevels){
-                               if(!osx)glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
-                               glTexSubImage2D(GL_TEXTURE_2D,0,starty,startx,endy-starty,endx-startx,GL_RGB,GL_UNSIGNED_BYTE,texturearray);
-                               if(!osx)glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
-                       }
-
-                       newsize=skeleton.skinsize;
 
-                       if(howmanylevels)
-                               gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGB, skeleton.skinsize, skeleton.skinsize, GL_RGB, GL_UNSIGNED_BYTE, &skeleton.skinText[0] );
-               }
-               /*for(j=1;j<=howmanylevels;j++){
-               if(j==1)texpointer=&skeleton.skinText[0];
-               else texpointer=&texture[0];
-
-               totalsize=int( newsize*newsize*bytesPerPixel);
-               rowsize=int( newsize*bytesPerPixel );
-               bigstep=bytesPerPixel*newsize*2;
-               smallstep=bytesPerPixel*2;
-
-               which=0;
-
-
-
-               glTexSubImage2D(GL_TEXTURE_2D,j,0,0,newsize/2,newsize/2,GL_RGB,GL_UNSIGNED_BYTE,texture);
-               newsize/=2;
-               }*/
+void Person::Reverse()
+{
+  if (!((victim->aitype == playercontrolled
+        || hostiletime > 1
+        || staggerdelay <= 0)
+       && victim->targetanimation != jumpupanim
+       && victim->targetanimation != jumpdownanim
+       && (tutoriallevel != 1 || cananger)
+       && hostile))
+    return;
+
+  if (normaldotproduct (victim->facing, victim->coords-coords) > 0
+      && (victim->id != 0 || difficulty >= 2)
+      && (creature != wolftype || victim->creature == wolftype))
+    return;
+
+  if(targetanimation==sweepanim){
+    targetanimation=sweepreversedanim;
+    currentanimation=sweepreversedanim;
+    victim->currentanimation=sweepreversalanim;
+    victim->targetanimation=sweepreversalanim;
+  }
+  if(targetanimation==spinkickanim){
+    targetanimation=spinkickreversedanim;
+    currentanimation=spinkickreversedanim;
+    victim->currentanimation=spinkickreversalanim;
+    victim->targetanimation=spinkickreversalanim;
+  }
+  if(targetanimation==upunchanim||targetanimation==rabbittacklinganim){
+    if(targetanimation==rabbittacklinganim){
+      currentframe=6;
+      targetframe=7;
+      victim->currentframe=6;
+      victim->targetframe=7;
+    }
+    targetanimation=upunchreversedanim;
+    currentanimation=upunchreversedanim;
+    victim->currentanimation=upunchreversalanim;
+    victim->targetanimation=upunchreversalanim;
+  }
+  if(targetanimation==staffhitanim&&findDistancefast(&victim->coords,&coords)<2&&((victim->id==0&&victim->crouchkeydown)||Random()%4==0)){
+    if(victim->weaponactive!=-1){
+      victim->throwtogglekeydown=1;
+      weapons.owner[victim->weaponids[0]]=-1;
+      weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
+      if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
+      weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
+      weapons.missed[victim->weaponids[0]]=1;
+      weapons.freetime[victim->weaponids[0]]=0;
+      weapons.firstfree[victim->weaponids[0]]=1;
+      weapons.physics[victim->weaponids[0]]=1;
+      victim->num_weapons--;
+      if(victim->num_weapons){
+       victim->weaponids[0]=victim->weaponids[victim->num_weapons];
+       if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
+      }
+
+      victim->weaponactive=-1;
+      for(int j=0;j<numplayers;j++){
+       player[j].wentforweapon=0;
+      }
+    }
+
+    targetanimation=staffhitreversedanim;
+    currentanimation=staffhitreversedanim;
+    victim->currentanimation=staffhitreversalanim;
+    victim->targetanimation=staffhitreversalanim;
+  }
+  if(targetanimation==staffspinhitanim&&findDistancefast(&victim->coords,&coords)<2&&((victim->id==0&&victim->crouchkeydown)||Random()%2==0)){
+    if(victim->weaponactive!=-1){
+      victim->throwtogglekeydown=1;
+      weapons.owner[victim->weaponids[0]]=-1;
+      weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
+      if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
+      weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
+      weapons.missed[victim->weaponids[0]]=1;
+      weapons.freetime[victim->weaponids[0]]=0;
+      weapons.firstfree[victim->weaponids[0]]=1;
+      weapons.physics[victim->weaponids[0]]=1;
+      victim->num_weapons--;
+      if(victim->num_weapons){
+       victim->weaponids[0]=victim->weaponids[victim->num_weapons];
+       if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
+      }
+
+      victim->weaponactive=-1;
+      for(int j=0;j<numplayers;j++){
+       player[j].wentforweapon=0;
+      }
+    }
+    targetanimation=staffspinhitreversedanim;
+    currentanimation=staffspinhitreversedanim;
+    victim->currentanimation=staffspinhitreversalanim;
+    victim->targetanimation=staffspinhitreversalanim;
+  }
+  if(targetanimation==swordslashanim&&findDistancefast(&victim->coords,&coords)<2&&((victim->id==0&&victim->crouchkeydown)||Random()%4==0)){
+    if(victim->weaponactive!=-1){
+      victim->throwtogglekeydown=1;
+      weapons.owner[victim->weaponids[0]]=-1;
+      weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
+      if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
+      weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
+      weapons.missed[victim->weaponids[0]]=1;
+      weapons.freetime[victim->weaponids[0]]=0;
+      weapons.firstfree[victim->weaponids[0]]=1;
+      weapons.physics[victim->weaponids[0]]=1;
+      victim->num_weapons--;
+      if(victim->num_weapons){
+       victim->weaponids[0]=victim->weaponids[victim->num_weapons];
+       if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
+      }
+
+      victim->weaponactive=-1;
+      for(int j=0;j<numplayers;j++){
+       player[j].wentforweapon=0;
+      }
+    }
+    targetanimation=swordslashreversedanim;
+    currentanimation=swordslashreversedanim;
+    victim->currentanimation=swordslashreversalanim;
+    victim->targetanimation=swordslashreversalanim;
+  }
+  if(targetanimation==knifeslashstartanim&&findDistancefast(&victim->coords,&coords)<2&&(victim->id==0||Random()%4==0)){
+    if(victim->weaponactive!=-1){
+      victim->throwtogglekeydown=1;
+      weapons.owner[victim->weaponids[0]]=-1;
+      weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
+      if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
+      weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
+      weapons.missed[victim->weaponids[0]]=1;
+      weapons.freetime[victim->weaponids[0]]=0;
+      weapons.firstfree[victim->weaponids[0]]=1;
+      weapons.physics[victim->weaponids[0]]=1;
+      victim->num_weapons--;
+      if(victim->num_weapons){
+       victim->weaponids[0]=victim->weaponids[victim->num_weapons];
+       if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
+      }
+
+      victim->weaponactive=-1;
+      for(int j=0;j<numplayers;j++){
+       player[j].wentforweapon=0;
+      }
+    }
+    targetanimation=knifeslashreversedanim;
+    currentanimation=knifeslashreversedanim;
+    victim->currentanimation=knifeslashreversalanim;
+    victim->targetanimation=knifeslashreversalanim;
+  }
+  if(targetanimation!=knifeslashstartanim&&targetanimation!=staffhitanim&&targetanimation!=staffspinhitanim&&targetanimation!=winduppunchanim&&targetanimation!=wolfslapanim&&targetanimation!=swordslashanim&&targetanimation!=swordslashanim){
+    victim->targettilt2=targettilt2;
+    victim->currentframe=currentframe;
+    victim->targetframe=targetframe;
+    victim->target=target;
+    victim->velocity=0;
+    victim->oldcoords=victim->coords;
+    victim->coords=coords;
+    victim->targetrotation=targetrotation;
+    victim->rotation=targetrotation;
+    victim->victim=this;
+  }
+  if(targetanimation==winduppunchanim){
+    targetanimation=winduppunchblockedanim;
+    victim->targetanimation=blockhighleftanim;
+    victim->targetframe=1;
+    victim->target=.5;
+    victim->victim=this;
+    victim->targetrotation=targetrotation+180;
+  }
+  if(targetanimation==wolfslapanim){
+    targetanimation=winduppunchblockedanim;
+    victim->targetanimation=blockhighleftanim;
+    victim->targetframe=1;
+    victim->target=.5;
+    victim->victim=this;
+    victim->targetrotation=targetrotation+180;
+  }
+  if((targetanimation==swordslashanim||targetanimation==staffhitanim||targetanimation==staffspinhitanim)&&victim->weaponactive!=-1){
+    targetanimation=swordslashparriedanim;
+    parriedrecently=.4;
+    victim->parriedrecently=0;
+    victim->targetanimation=swordslashparryanim;
+    victim->targetframe=1;
+    victim->target=.5;
+    victim->victim=this;
+    victim->targetrotation=targetrotation+180;
+
+    if(abs(Random()%20)==0||weapons.type[victim->weaponids[victim->weaponactive]]==knife){
+      if(victim->weaponactive!=-1){
+       if(weapons.type[victim->weaponids[0]]==staff||weapons.type[weaponids[0]]==staff){
+         if(weapons.type[victim->weaponids[0]]==staff)weapons.damage[victim->weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
+         if(weapons.type[weaponids[0]]==staff)weapons.damage[weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
+         emit_sound_at(swordstaffsound, victim->coords);
        }
-}
-
-
-void Person::Reverse(){
-       if(victim->aitype==playercontrolled||hostiletime>1)
-               if(victim->targetanimation!=jumpupanim&&victim->targetanimation!=jumpdownanim&&((tutoriallevel!=1||cananger)&&hostile)){
-                       if(normaldotproduct(victim->facing,victim->coords-coords)>0&&!(victim->id==0&&difficulty<2)&&(creature!=wolftype||victim->creature==wolftype))return;
-                       if(victim->aitype!=playercontrolled&&staggerdelay>0)return;
-                       if(targetanimation==sweepanim){
-                               targetanimation=sweepreversedanim;
-                               currentanimation=sweepreversedanim;
-                               victim->currentanimation=sweepreversalanim;
-                               victim->targetanimation=sweepreversalanim;
-                       }
-                       if(targetanimation==spinkickanim){
-                               targetanimation=spinkickreversedanim;
-                               currentanimation=spinkickreversedanim;
-                               victim->currentanimation=spinkickreversalanim;
-                               victim->targetanimation=spinkickreversalanim;
-                       }
-                       if(targetanimation==upunchanim||targetanimation==rabbittacklinganim){
-                               if(targetanimation==rabbittacklinganim){
-                                       currentframe=6;
-                                       targetframe=7;
-                                       victim->currentframe=6;
-                                       victim->targetframe=7;
-                               }
-                               targetanimation=upunchreversedanim;
-                               currentanimation=upunchreversedanim;
-                               victim->currentanimation=upunchreversalanim;
-                               victim->targetanimation=upunchreversalanim;
-                       }
-                       if(targetanimation==staffhitanim&&findDistancefast(&victim->coords,&coords)<2&&((victim->id==0&&victim->crouchkeydown)||Random()%4==0)){
-                               if(victim->weaponactive!=-1){
-                                       victim->throwtogglekeydown=1;
-                                       weapons.owner[victim->weaponids[0]]=-1;
-                                       weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
-                                       if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
-                                       weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
-                                       weapons.missed[victim->weaponids[0]]=1;
-                                       weapons.freetime[victim->weaponids[0]]=0;
-                                       weapons.firstfree[victim->weaponids[0]]=1;
-                                       weapons.physics[victim->weaponids[0]]=1;
-                                       victim->num_weapons--;
-                                       if(victim->num_weapons){
-                                               victim->weaponids[0]=victim->weaponids[victim->num_weapons];
-                                               if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
-                                }
-
-                                       victim->weaponactive=-1;
-                                       for(int j=0;j<numplayers;j++){
-                                               player[j].wentforweapon=0;
-                                }
-                               }
-
-                               targetanimation=staffhitreversedanim;
-                               currentanimation=staffhitreversedanim;
-                               victim->currentanimation=staffhitreversalanim;
-                               victim->targetanimation=staffhitreversalanim;
-                       }
-                       if(targetanimation==staffspinhitanim&&findDistancefast(&victim->coords,&coords)<2&&((victim->id==0&&victim->crouchkeydown)||Random()%2==0)){
-                               if(victim->weaponactive!=-1){
-                                       victim->throwtogglekeydown=1;
-                                       weapons.owner[victim->weaponids[0]]=-1;
-                                       weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
-                                       if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
-                                       weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
-                                       weapons.missed[victim->weaponids[0]]=1;
-                                       weapons.freetime[victim->weaponids[0]]=0;
-                                       weapons.firstfree[victim->weaponids[0]]=1;
-                                       weapons.physics[victim->weaponids[0]]=1;
-                                       victim->num_weapons--;
-                                       if(victim->num_weapons){
-                                               victim->weaponids[0]=victim->weaponids[victim->num_weapons];
-                                               if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
-                                }
-
-                                       victim->weaponactive=-1;
-                                       for(int j=0;j<numplayers;j++){
-                                               player[j].wentforweapon=0;
-                                }
-                               }
-                               targetanimation=staffspinhitreversedanim;
-                               currentanimation=staffspinhitreversedanim;
-                               victim->currentanimation=staffspinhitreversalanim;
-                               victim->targetanimation=staffspinhitreversalanim;
-                       }
-                       if(targetanimation==swordslashanim&&findDistancefast(&victim->coords,&coords)<2&&((victim->id==0&&victim->crouchkeydown)||Random()%4==0)){
-                               if(victim->weaponactive!=-1){
-                                       victim->throwtogglekeydown=1;
-                                       weapons.owner[victim->weaponids[0]]=-1;
-                                       weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
-                                       if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
-                                       weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
-                                       weapons.missed[victim->weaponids[0]]=1;
-                                       weapons.freetime[victim->weaponids[0]]=0;
-                                       weapons.firstfree[victim->weaponids[0]]=1;
-                                       weapons.physics[victim->weaponids[0]]=1;
-                                       victim->num_weapons--;
-                                       if(victim->num_weapons){
-                                               victim->weaponids[0]=victim->weaponids[victim->num_weapons];
-                                               if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
-                                }
-
-                                       victim->weaponactive=-1;
-                                       for(int j=0;j<numplayers;j++){
-                                               player[j].wentforweapon=0;
-                                }
-                               }
-                               targetanimation=swordslashreversedanim;
-                               currentanimation=swordslashreversedanim;
-                               victim->currentanimation=swordslashreversalanim;
-                               victim->targetanimation=swordslashreversalanim;
-                       }
-                       if(targetanimation==knifeslashstartanim&&findDistancefast(&victim->coords,&coords)<2&&(victim->id==0||Random()%4==0)){
-                               if(victim->weaponactive!=-1){
-                                       victim->throwtogglekeydown=1;
-                                       weapons.owner[victim->weaponids[0]]=-1;
-                                       weapons.velocity[victim->weaponids[0]]=victim->velocity*.2;
-                                       if(weapons.velocity[victim->weaponids[0]].x==0)weapons.velocity[victim->weaponids[0]].x=.1;
-                                       weapons.tipvelocity[victim->weaponids[0]]=weapons.velocity[victim->weaponids[0]];
-                                       weapons.missed[victim->weaponids[0]]=1;
-                                       weapons.freetime[victim->weaponids[0]]=0;
-                                       weapons.firstfree[victim->weaponids[0]]=1;
-                                       weapons.physics[victim->weaponids[0]]=1;
-                                       victim->num_weapons--;
-                                       if(victim->num_weapons){
-                                               victim->weaponids[0]=victim->weaponids[victim->num_weapons];
-                                               if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
-                                }
-
-                                       victim->weaponactive=-1;
-                                       for(int j=0;j<numplayers;j++){
-                                               player[j].wentforweapon=0;
-                                }
-                               }
-                               targetanimation=knifeslashreversedanim;
-                               currentanimation=knifeslashreversedanim;
-                               victim->currentanimation=knifeslashreversalanim;
-                               victim->targetanimation=knifeslashreversalanim;
-                       }
-                       if(targetanimation!=knifeslashstartanim&&targetanimation!=staffhitanim&&targetanimation!=staffspinhitanim&&targetanimation!=winduppunchanim&&targetanimation!=wolfslapanim&&targetanimation!=swordslashanim&&targetanimation!=swordslashanim){
-                               victim->targettilt2=targettilt2;
-                               victim->currentframe=currentframe;
-                               victim->targetframe=targetframe;
-                               victim->target=target;
-                               victim->velocity=0;
-                               victim->oldcoords=victim->coords;
-                               victim->coords=coords;
-                               victim->targetrotation=targetrotation;
-                               victim->rotation=targetrotation;
-                               victim->victim=this;
-                       }
-                       if(targetanimation==winduppunchanim){
-                               targetanimation=winduppunchblockedanim;
-                               victim->targetanimation=blockhighleftanim;
-                               victim->targetframe=1;
-                               victim->target=.5;
-                               victim->victim=this;
-                               victim->targetrotation=targetrotation+180;
-                       }
-                       if(targetanimation==wolfslapanim){
-                               targetanimation=winduppunchblockedanim;
-                               victim->targetanimation=blockhighleftanim;
-                               victim->targetframe=1;
-                               victim->target=.5;
-                               victim->victim=this;
-                               victim->targetrotation=targetrotation+180;
-                       }
-                       if((targetanimation==swordslashanim||targetanimation==staffhitanim||targetanimation==staffspinhitanim)&&victim->weaponactive!=-1){
-                               targetanimation=swordslashparriedanim;
-                               parriedrecently=.4;
-                               victim->parriedrecently=0;
-                               victim->targetanimation=swordslashparryanim;
-                               victim->targetframe=1;
-                               victim->target=.5;
-                               victim->victim=this;
-                               victim->targetrotation=targetrotation+180;
-
-                               if(abs(Random()%20)==0||weapons.type[victim->weaponids[victim->weaponactive]]==knife){
-                                       float gLoc[3];
-                                       float vel[3];
-                                       gLoc[0]=victim->coords.x;
-                                       gLoc[1]=victim->coords.y;
-                                       gLoc[2]=victim->coords.z;
-                                       vel[0]=velocity.x;
-                                       vel[1]=velocity.y;
-                                       vel[2]=velocity.z;
-                                       if(victim->weaponactive!=-1){
-                                               if(weapons.type[victim->weaponids[0]]==staff||weapons.type[weaponids[0]]==staff){
-                                                       if(weapons.type[victim->weaponids[0]]==staff)weapons.damage[victim->weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
-                                                       if(weapons.type[weaponids[0]]==staff)weapons.damage[weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
-
-                                                       PlaySoundEx( swordstaffsound, samp[swordstaffsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[swordstaffsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[swordstaffsound], 512);
-                                                       OPENAL_SetPaused(channels[swordstaffsound], false);
-                                               }
-                                               else{
-                                                       PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[metalhitsound], 512);
-                                                       OPENAL_SetPaused(channels[metalhitsound], false);
-                                               }
-                                       }
-                                       XYZ aim;
-                                       victim->Puff(righthand);
-                                       victim->target=0;
-                                       victim->targetframe=0;
-                                       victim->targetanimation=staggerbackhighanim;
-                                       victim->targetrotation=targetrotation+180;
-                                       victim->target=0;
-                                       weapons.owner[victim->weaponids[0]]=-1;
-                                       aim=DoRotation(facing,0,90,0)*21;
-                                       aim.y+=7;
-                                       weapons.velocity[victim->weaponids[0]]=aim*-.2;
-                                       weapons.tipvelocity[victim->weaponids[0]]=aim;
-                                       weapons.missed[victim->weaponids[0]]=1;
-                                       weapons.hitsomething[victim->weaponids[0]]=0;
-                                       weapons.freetime[victim->weaponids[0]]=0;
-                                       weapons.firstfree[victim->weaponids[0]]=1;
-                                       weapons.physics[victim->weaponids[0]]=1;
-                                       victim->num_weapons--;
-                                       if(victim->num_weapons){
-                                               victim->weaponids[0]=victim->weaponids[num_weapons];
-                                               if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
-                                }
-                                       victim->weaponactive=-1;
-                                       for(int i=0;i<numplayers;i++){
-                                               player[i].wentforweapon=0;
-                                }
-
-
-
-
-
-                                       /*PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                       OPENAL_SetVolume(channels[metalhitsound], 512);
-                                       OPENAL_SetPaused(channels[metalhitsound], false);*/
-                               }
-
-                               if(abs(Random()%20)==0){
-                                       float gLoc[3];
-                                       float vel[3];
-                                       gLoc[0]=coords.x;
-                                       gLoc[1]=coords.y;
-                                       gLoc[2]=coords.z;
-                                       vel[0]=velocity.x;
-                                       vel[1]=velocity.y;
-                                       vel[2]=velocity.z;
-                                       if(weaponactive!=-1){
-                                               if(weapons.type[victim->weaponids[0]]==staff||weapons.type[weaponids[0]]==staff){
-                                                       if(weapons.type[victim->weaponids[0]]==staff)weapons.damage[victim->weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
-                                                       if(weapons.type[weaponids[0]]==staff)weapons.damage[weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
-
-                                                       PlaySoundEx( swordstaffsound, samp[swordstaffsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[swordstaffsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[swordstaffsound], 512);
-                                                       OPENAL_SetPaused(channels[swordstaffsound], false);
-                                               }
-                                               else{
-                                                       PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[metalhitsound], 512);
-                                                       OPENAL_SetPaused(channels[metalhitsound], false);
-                                               }
-                                       }
-
-                                       XYZ aim;
-                                       Puff(righthand);
-                                       target=0;
-                                       targetframe=0;
-                                       targetanimation=staggerbackhighanim;
-                                       targetrotation=targetrotation+180;
-                                       target=0;
-                                       weapons.owner[weaponids[0]]=-1;
-                                       aim=DoRotation(facing,0,90,0)*21;
-                                       aim.y+=7;
-                                       weapons.velocity[weaponids[0]]=aim*-.2;
-                                       weapons.tipvelocity[weaponids[0]]=aim;
-                                       weapons.hitsomething[weaponids[0]]=0;
-                                       weapons.missed[weaponids[0]]=1;
-                                       weapons.freetime[weaponids[0]]=0;
-                                       weapons.firstfree[weaponids[0]]=1;
-                                       weapons.physics[weaponids[0]]=1;
-                                       num_weapons--;
-                                       if(num_weapons){
-                                               weaponids[0]=weaponids[num_weapons];
-                                               if(weaponstuck==num_weapons)weaponstuck=0;
-                                }
-                                       weaponactive=-1;
-                                       for(int i=0;i<numplayers;i++){
-                                               player[i].wentforweapon=0;
-                                }
-
-
-                                       /*PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                       OPENAL_SetVolume(channels[metalhitsound], 512);
-                                       OPENAL_SetPaused(channels[metalhitsound], false);*/
-                               }
-                       }
-                       if(hasvictim)
-                               if(targetanimation==knifeslashstartanim||targetanimation==swordslashanim||targetanimation==staffhitanim||targetanimation==staffspinhitanim){
-                                       if((targetanimation!=staffhitanim&&targetanimation!=staffspinhitanim)||findDistancefast(&coords,&victim->coords)>.2){
-                                               //victim->targetanimation=sweepanim;
-                                               victim->targetanimation=dodgebackanim;
-                                               victim->targetframe=0;
-                                               victim->target=0;
-                                               //victim->velocity=0;
-
-                                               XYZ rotatetarget;
-                                               rotatetarget=coords-victim->coords;
-                                               Normalise(&rotatetarget);
-                                               victim->targetrotation=-asin(0-rotatetarget.x);
-                                               victim->targetrotation*=360/6.28;
-                                               if(rotatetarget.z<0)victim->targetrotation=180-victim->targetrotation;
-
-                                               victim->targettilt2=-asin(rotatetarget.y)*360/6.28;//*-70;
-
-                                               victim->lastattack3=victim->lastattack2;
-                                               victim->lastattack2=victim->lastattack;
-                                               victim->lastattack=victim->targetanimation;
-                                       }
-                                       else
-                                       {
-                                               victim->targetanimation=sweepanim;
-                                               victim->targetframe=0;
-                                               victim->target=0;
-
-                                               XYZ rotatetarget;
-                                               rotatetarget=coords-victim->coords;
-                                               Normalise(&rotatetarget);
-                                               victim->targetrotation=-asin(0-rotatetarget.x);
-                                               victim->targetrotation*=360/6.28;
-                                               if(rotatetarget.z<0)victim->targetrotation=180-victim->targetrotation;
-
-                                               victim->targettilt2=-asin(rotatetarget.y)*360/6.28;//*-70;
-
-                                               victim->lastattack3=victim->lastattack2;
-                                               victim->lastattack2=victim->lastattack;
-                                               victim->lastattack=victim->targetanimation;
-                                       }
-                               }
+       else{
+         emit_sound_at(metalhitsound, victim->coords);
+       }
+      }
+      XYZ aim;
+      victim->Puff(righthand);
+      victim->target=0;
+      victim->targetframe=0;
+      victim->targetanimation=staggerbackhighanim;
+      victim->targetrotation=targetrotation+180;
+      victim->target=0;
+      weapons.owner[victim->weaponids[0]]=-1;
+      aim=DoRotation(facing,0,90,0)*21;
+      aim.y+=7;
+      weapons.velocity[victim->weaponids[0]]=aim*-.2;
+      weapons.tipvelocity[victim->weaponids[0]]=aim;
+      weapons.missed[victim->weaponids[0]]=1;
+      weapons.hitsomething[victim->weaponids[0]]=0;
+      weapons.freetime[victim->weaponids[0]]=0;
+      weapons.firstfree[victim->weaponids[0]]=1;
+      weapons.physics[victim->weaponids[0]]=1;
+      victim->num_weapons--;
+      if(victim->num_weapons){
+       victim->weaponids[0]=victim->weaponids[num_weapons];
+       if(victim->weaponstuck==victim->num_weapons)victim->weaponstuck=0;
+      }
+      victim->weaponactive=-1;
+      for(int i=0;i<numplayers;i++){
+       player[i].wentforweapon=0;
+      }
+    }
+
+    if(abs(Random()%20)==0){
+      if(weaponactive!=-1){
+       if(weapons.type[victim->weaponids[0]]==staff||weapons.type[weaponids[0]]==staff){
+         if(weapons.type[victim->weaponids[0]]==staff)weapons.damage[victim->weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
+         if(weapons.type[weaponids[0]]==staff)weapons.damage[weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
+
+         emit_sound_at(swordstaffsound, coords);
+       }
+       else{
+         emit_sound_at(metalhitsound, coords);
+       }
+      }
+
+      XYZ aim;
+      Puff(righthand);
+      target=0;
+      targetframe=0;
+      targetanimation=staggerbackhighanim;
+      targetrotation=targetrotation+180;
+      target=0;
+      weapons.owner[weaponids[0]]=-1;
+      aim=DoRotation(facing,0,90,0)*21;
+      aim.y+=7;
+      weapons.velocity[weaponids[0]]=aim*-.2;
+      weapons.tipvelocity[weaponids[0]]=aim;
+      weapons.hitsomething[weaponids[0]]=0;
+      weapons.missed[weaponids[0]]=1;
+      weapons.freetime[weaponids[0]]=0;
+      weapons.firstfree[weaponids[0]]=1;
+      weapons.physics[weaponids[0]]=1;
+      num_weapons--;
+      if(num_weapons){
+       weaponids[0]=weaponids[num_weapons];
+       if(weaponstuck==num_weapons)weaponstuck=0;
+      }
+      weaponactive=-1;
+      for(int i=0;i<numplayers;i++){
+       player[i].wentforweapon=0;
+      }
+
+
+    }
+  }
+  if(hasvictim)
+    if(targetanimation==knifeslashstartanim||targetanimation==swordslashanim||targetanimation==staffhitanim||targetanimation==staffspinhitanim){
+      if((targetanimation!=staffhitanim&&targetanimation!=staffspinhitanim)||findDistancefast(&coords,&victim->coords)>.2){
+       victim->targetanimation=dodgebackanim;
+       victim->targetframe=0;
+       victim->target=0;
+
+       XYZ rotatetarget;
+       rotatetarget=coords-victim->coords;
+       Normalise(&rotatetarget);
+       victim->targetrotation=-asin(0-rotatetarget.x);
+       victim->targetrotation*=360/6.28;
+       if(rotatetarget.z<0)victim->targetrotation=180-victim->targetrotation;
+
+       victim->targettilt2=-asin(rotatetarget.y)*360/6.28;//*-70;
+
+       victim->lastattack3=victim->lastattack2;
+       victim->lastattack2=victim->lastattack;
+       victim->lastattack=victim->targetanimation;
+      }
+      else
+       {
+         victim->targetanimation=sweepanim;
+         victim->targetframe=0;
+         victim->target=0;
+
+         XYZ rotatetarget;
+         rotatetarget=coords-victim->coords;
+         Normalise(&rotatetarget);
+         victim->targetrotation=-asin(0-rotatetarget.x);
+         victim->targetrotation*=360/6.28;
+         if(rotatetarget.z<0)victim->targetrotation=180-victim->targetrotation;
+
+         victim->targettilt2=-asin(rotatetarget.y)*360/6.28;//*-70;
+
+         victim->lastattack3=victim->lastattack2;
+         victim->lastattack2=victim->lastattack;
+         victim->lastattack=victim->targetanimation;
+       }
+    }
 
-                               velocity=0;
-                               victim->velocity=0;
+  velocity=0;
+  victim->velocity=0;
 
-                               if(aitype!=playercontrolled)feint=0;
-                               if(aitype!=playercontrolled&&Random()%3==0&&escapednum<2&&difficulty==2)feint=1;
-                               if(aitype!=playercontrolled&&Random()%5==0&&escapednum<2&&difficulty==1)feint=1;
-                               if(aitype!=playercontrolled&&Random()%10==0&&escapednum<2&&difficulty==0)feint=1;
+  if(aitype!=playercontrolled)feint=0;
+  if(aitype!=playercontrolled&&Random()%3==0&&escapednum<2&&difficulty==2)feint=1;
+  if(aitype!=playercontrolled&&Random()%5==0&&escapednum<2&&difficulty==1)feint=1;
+  if(aitype!=playercontrolled&&Random()%10==0&&escapednum<2&&difficulty==0)feint=1;
 
-                               if(victim->id==0&&animation[victim->targetanimation].attack==reversal)numreversals++;
-               }
+  if(victim->id==0&&animation[victim->targetanimation].attack==reversal)numreversals++;
 }
 
 void Person::DoDamage(float howmuch){
@@ -1385,23 +1090,12 @@ void Person::DoDamage(float howmuch){
                        flatvelocity2.x+=(float)(abs(Random()%100)-50)/10;
                        flatvelocity2.y+=(float)(abs(Random()%100)-50)/10;
                        flatvelocity2.z+=(float)(abs(Random()%100)-50)/10;
-                       sprites.MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, 3, 1);
-                       sprites.MakeSprite(bloodsprite, flatfacing2,flatvelocity2, 1,1,1, .4, 1);
-                       sprites.MakeSprite(cloudsprite, flatfacing2,flatvelocity2*0, .6,0,0, 1, .5);
+                       Sprite::MakeSprite(bloodflamesprite, flatfacing2,flatvelocity2, 1,1,1, 3, 1);
+                       Sprite::MakeSprite(bloodsprite, flatfacing2,flatvelocity2, 1,1,1, .4, 1);
+                       Sprite::MakeSprite(cloudsprite, flatfacing2,flatvelocity2*0, .6,0,0, 1, .5);
                }
 
-               float gLoc[3];
-               float vel[3];
-               gLoc[0]=coords.x;
-               gLoc[1]=coords.y;
-               gLoc[2]=coords.z;
-               vel[0]=0;
-               vel[1]=0;
-               vel[2]=0;
-               PlaySoundEx( splattersound, samp[splattersound], NULL, true);
-               OPENAL_3D_SetAttributes(channels[splattersound], gLoc, vel);
-               OPENAL_SetVolume(channels[splattersound], 256);
-               OPENAL_SetPaused(channels[splattersound], false);
+               emit_sound_at(splattersound, coords);
 
                skeleton.free=2;
                DoDamage(10000);
@@ -1411,9 +1105,7 @@ void Person::DoDamage(float howmuch){
                slomodelay=.2;
                }*/
                if(!dead&&creature==wolftype){
-                       bonus=Wolfbonus;
-                       bonustime=0;
-                       bonusvalue=300;
+                 award_bonus(0, Wolfbonus);
                }
                dead=2;
                coords=20;
@@ -1422,14 +1114,6 @@ void Person::DoDamage(float howmuch){
        if(tutoriallevel!=1||id==0)
                if(speechdelay<=0&&!dead&&aitype!=playercontrolled){
                        int whichsound=-1;
-                       float gLoc[3];
-                       float vel[3];
-                       gLoc[0]=coords.x;
-                       gLoc[1]=coords.y;
-                       gLoc[2]=coords.z;
-                       vel[0]=velocity.x;
-                       vel[1]=velocity.y;
-                       vel[2]=velocity.z;
 
                        if(creature==wolftype){
                                int i=abs(Random()%2);
@@ -1452,10 +1136,7 @@ void Person::DoDamage(float howmuch){
                        }
 
                        if(whichsound!=-1){
-                               PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[whichsound], 512);
-                               OPENAL_SetPaused(channels[whichsound], false);
+                               emit_sound_at(whichsound, coords);
                        }
                }
                speechdelay=.3;
@@ -1469,7 +1150,7 @@ void Person::DoHead(){
        static XYZ facing;
        static float lookspeed=500;
 
-       if(!freeze&&!winfreeze&&(!mainmenu||!gamestarted)){
+       if(!freeze&&!winfreeze){
 
                //head facing
                targetheadrotation=(float)((int)((0-rotation-targetheadrotation+180)*100)%36000)/100;
@@ -1642,8 +1323,8 @@ void Person::RagDoll(bool checkcollision){
                                skeleton.joints[j].position-=average;
                        }
 
-                       whichpatchx=coords.x/(terrain.size/subdivision*terrain.scale*terraindetail);
-                       whichpatchz=coords.z/(terrain.size/subdivision*terrain.scale*terraindetail);
+                       whichpatchx=coords.x/(terrain.size/subdivision*terrain.scale);
+                       whichpatchz=coords.z/(terrain.size/subdivision*terrain.scale);
                        if(terrain.patchobjectnum[whichpatchx][whichpatchz])
                                for(l=0;l<terrain.patchobjectnum[whichpatchx][whichpatchz];l++){
                                        i=terrain.patchobjects[whichpatchx][whichpatchz][l];
@@ -1707,7 +1388,7 @@ void Person::FootLand(int which, float opacity){
                        if(which==0)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[leftfoot]].position,0,rotation,0)*scale+coords;
                        if(which==1)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[rightfoot]].position,0,rotation,0)*scale+coords;
                        //footpoint.y=coords.y;
-                       if(findDistancefast(&footpoint,&viewer))sprites.MakeSprite(cloudsprite, footpoint,footvel, 1,1,1, .5, .2*opacity);
+                       if(findDistancefast(&footpoint,&viewer))Sprite::MakeSprite(cloudsprite, footpoint,footvel, 1,1,1, .5, .2*opacity);
                }
                else if(environment==snowyenvironment&&onterrain&&terrain.getOpacity(coords.x,coords.z)<.2){
                        footvel=velocity/5;
@@ -1716,7 +1397,7 @@ void Person::FootLand(int which, float opacity){
                        if(which==1)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[rightfoot]].position,0,rotation,0)*scale+coords;
                        footpoint.y=terrain.getHeight(footpoint.x,footpoint.z);
                        terrainlight=terrain.getLighting(footpoint.x,footpoint.z);
-                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, footpoint,footvel*.6, terrainlight.x,terrainlight.y,terrainlight.z, .5, .7*opacity);
+                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, footpoint,footvel*.6, terrainlight.x,terrainlight.y,terrainlight.z, .5, .7*opacity);
                        if(opacity>=1||detail==2)if(detail==2)if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)terrain.MakeDecal(footprintdecal,footpoint,.2,1*opacity,rotation);
                }
                else if(environment==grassyenvironment&&onterrain&&terrain.getOpacity(coords.x,coords.z)<.2){
@@ -1726,7 +1407,7 @@ void Person::FootLand(int which, float opacity){
                        if(which==1)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[rightfoot]].position,0,rotation,0)*scale+coords;
                        footpoint.y=terrain.getHeight(footpoint.x,footpoint.z);
                        terrainlight=terrain.getLighting(footpoint.x,footpoint.z);
-                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, footpoint,footvel*.6, terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5*opacity);
+                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, footpoint,footvel*.6, terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5*opacity);
                }
                else if(environment==desertenvironment&&onterrain&&terrain.getOpacity(coords.x,coords.z)<.2){
                        footvel=velocity/5;
@@ -1735,7 +1416,7 @@ void Person::FootLand(int which, float opacity){
                        if(which==1)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[rightfoot]].position,0,rotation,0)*scale+coords;
                        footpoint.y=terrain.getHeight(footpoint.x,footpoint.z);
                        terrainlight=terrain.getLighting(footpoint.x,footpoint.z);
-                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, footpoint,footvel*.6, terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7*opacity);
+                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, footpoint,footvel*.6, terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7*opacity);
                        if(opacity>=1||detail==2)if(detail==2)if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)terrain.MakeDecal(footprintdecal,footpoint,.2,.25*opacity,rotation);
                }
                else if(isLanding()||targetanimation==jumpupanim||isLandhard())
@@ -1745,7 +1426,7 @@ void Person::FootLand(int which, float opacity){
                        if(which==0)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[leftfoot]].position,0,rotation,0)*scale+coords;
                        if(which==1)footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[rightfoot]].position,0,rotation,0)*scale+coords;
                        //footpoint.y=coords.y;
-                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, footpoint,footvel*.6, 1,1,1, .5, .2*opacity);
+                       if(findDistancefast(&footpoint,&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, footpoint,footvel*.6, 1,1,1, .5, .2*opacity);
                }
 }
 
@@ -1754,179 +1435,10 @@ void Person::Puff(int whichlabel){
 
        footvel=0;
        footpoint=DoRotation(skeleton.joints[skeleton.jointlabels[whichlabel]].position,0,rotation,0)*scale+coords;
-       sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,1,1, .9, .3);
+       Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,1,1, .9, .3);
 }
 
 
-/*
-HitStruct      Person::BulletCollideWithPlayer(XYZ start, XYZ end){
-float damage=20;
-XYZ tempbulletloc[2];
-XYZ collisionpoint;
-XYZ sparkpos;
-GLfloat M[16];
-int collide;
-float howfar;
-XYZ average;
-XYZ facing;
-int howmany;
-float distancemax;
-HitStruct hitstruct;
-hitstruct.collision=0;
-//Make bounding sphere
-average=0;
-howmany=0;
-for(int j=0;j<skeleton.num_joints;j++){
-average.x=average.x+skeleton.joints[j].position.x;
-average.y=average.y+skeleton.joints[j].position.y;
-average.z=average.z+skeleton.joints[j].position.z;
-howmany++;
-}
-average=average/howmany;
-distancemax=0;
-for(int j=0;j<skeleton.num_joints;j++){
-if(findDistancefast(average,skeleton.joints[j].position)>distancemax){
-distancemax=findDistancefast(average,skeleton.joints[j].position);
-}
-}
-distancemax=fast_sqrt(distancemax);
-//Collide with player
-if(skeleton.free<1){
-start=start-coords;
-end=end-coords;
-if(rotation)start=DoRotation(start,0,-rotation,0);
-if(rotation)end=DoRotation(end,0,-rotation,0);
-}
-tempbulletloc[0]=start;
-tempbulletloc[1]=end;
-if(sphere_line_intersection(tempbulletloc[0].x,tempbulletloc[0].y,tempbulletloc[0].z,
-tempbulletloc[1].x,tempbulletloc[1].y,tempbulletloc[1].z,
-average.x, average.y, average.z, distancemax)){
-for(int j=0;j<skeleton.num_joints;j++){
-if(skeleton.joints[j].hasparent&&skeleton.joints[j].visible){
-tempbulletloc[0]=start;
-tempbulletloc[1]=end;
-glPushMatrix();
-glLoadIdentity();
-glScalef(1,1/skeleton.joints[j].length,1);
-glRotatef(skeleton.joints[j].rotate2-90,0,0,1);
-glRotatef(skeleton.joints[j].rotate1-90,0,1,0);
-glTranslatef(  (-(skeleton.joints[j].position.x+skeleton.joints[j].parent->position.x)/2),
-(-(skeleton.joints[j].position.y+skeleton.joints[j].parent->position.y)/2),
-(-(skeleton.joints[j].position.z+skeleton.joints[j].parent->position.z)/2));
-glTranslatef(tempbulletloc[0].x,tempbulletloc[0].y,tempbulletloc[0].z);
-glGetFloatv(GL_MODELVIEW_MATRIX,M);
-tempbulletloc[0].x=M[12];
-tempbulletloc[0].y=M[13];
-tempbulletloc[0].z=M[14];
-glPopMatrix();
-glPushMatrix();
-glLoadIdentity();
-glScalef(1,1/skeleton.joints[j].length,1);
-glRotatef(skeleton.joints[j].rotate2-90,0,0,1);
-glRotatef(skeleton.joints[j].rotate1-90,0,1,0);
-glTranslatef(  (-(skeleton.joints[j].position.x+skeleton.joints[j].parent->position.x)/2),
-(-(skeleton.joints[j].position.y+skeleton.joints[j].parent->position.y)/2),
-(-(skeleton.joints[j].position.z+skeleton.joints[j].parent->position.z)/2));
-glTranslatef(tempbulletloc[1].x,tempbulletloc[1].y,tempbulletloc[1].z);
-glGetFloatv(GL_MODELVIEW_MATRIX,M);
-tempbulletloc[1].x=M[12];
-tempbulletloc[1].y=M[13];
-tempbulletloc[1].z=M[14];
-glPopMatrix();
-collide=skeletonmodels[skeleton.joints[j].modelnum].LineCheck(tempbulletloc[0],tempbulletloc[1],&collisionpoint);
-if(collide!=-1)
-{
-glPushMatrix();
-glLoadIdentity();
-glTranslatef(  (skeleton.joints[j].position.x+skeleton.joints[j].parent->position.x)/2,
-(skeleton.joints[j].position.y+skeleton.joints[j].parent->position.y)/2,
-(skeleton.joints[j].position.z+skeleton.joints[j].parent->position.z)/2);
-glRotatef(-skeleton.joints[j].rotate1+90,0,1,0);
-glRotatef(-skeleton.joints[j].rotate2+90,0,0,1);
-glScalef(1,skeleton.joints[j].length,1);
-glTranslatef(collisionpoint.x,collisionpoint.y,collisionpoint.z);
-glGetFloatv(GL_MODELVIEW_MATRIX,M);
-collisionpoint.x=M[12];
-collisionpoint.y=M[13];
-collisionpoint.z=M[14];
-glPopMatrix();
-hitstruct.collision=1;
-hitstruct.hitlocation=collisionpoint;
-hitstruct.joint1=&skeleton.joints[j];
-hitstruct.joint2=skeleton.joints[j].parent;
-}
-}
-}
-for(int j=0;j<skeleton.num_muscles;j++){
-if(skeleton.muscles[j].visible){
-tempbulletloc[0]=start;
-tempbulletloc[1]=end;
-glPushMatrix();
-glLoadIdentity();
-glScalef(1,1/skeleton.muscles[j].length,1);
-glRotatef(skeleton.muscles[j].rotate3,0,1,0);
-glRotatef(skeleton.muscles[j].rotate2-90,0,0,1);
-glRotatef(skeleton.muscles[j].rotate1-90,0,1,0);
-glTranslatef(  (-(skeleton.muscles[j].parent1->position.x+skeleton.muscles[j].parent2->position.x)/2),
-(-(skeleton.muscles[j].parent1->position.y+skeleton.muscles[j].parent2->position.y)/2),
-(-(skeleton.muscles[j].parent1->position.z+skeleton.muscles[j].parent2->position.z)/2));
-
-glTranslatef(tempbulletloc[0].x,tempbulletloc[0].y,tempbulletloc[0].z);
-glGetFloatv(GL_MODELVIEW_MATRIX,M);
-tempbulletloc[0].x=M[12];
-tempbulletloc[0].y=M[13];
-tempbulletloc[0].z=M[14];
-glPopMatrix();
-glPushMatrix();
-glLoadIdentity();
-glScalef(1,1/skeleton.muscles[j].length,1);
-glRotatef(skeleton.muscles[j].rotate3,0,1,0);
-glRotatef(skeleton.muscles[j].rotate2-90,0,0,1);
-glRotatef(skeleton.muscles[j].rotate1-90,0,1,0);
-
-glTranslatef(  (-(skeleton.muscles[j].parent1->position.x+skeleton.muscles[j].parent2->position.x)/2),
-(-(skeleton.muscles[j].parent1->position.y+skeleton.muscles[j].parent2->position.y)/2),
-(-(skeleton.muscles[j].parent1->position.z+skeleton.muscles[j].parent2->position.z)/2));
-glTranslatef(tempbulletloc[1].x,tempbulletloc[1].y,tempbulletloc[1].z);
-glGetFloatv(GL_MODELVIEW_MATRIX,M);
-tempbulletloc[1].x=M[12];
-tempbulletloc[1].y=M[13];
-tempbulletloc[1].z=M[14];
-glPopMatrix();
-collide=skeletonmodels[skeleton.muscles[j].parent1->modelnum].LineCheck(tempbulletloc[0],tempbulletloc[1],&collisionpoint);
-if(collide!=-1)
-{
-glPushMatrix();
-glLoadIdentity();
-glTranslatef(  (skeleton.muscles[j].parent1->position.x+skeleton.muscles[j].parent2->position.x)/2,
-(skeleton.muscles[j].parent1->position.y+skeleton.muscles[j].parent2->position.y)/2,
-(skeleton.muscles[j].parent1->position.z+skeleton.muscles[j].parent2->position.z)/2);
-glRotatef(-skeleton.muscles[j].rotate1+90,0,1,0);
-glRotatef(-skeleton.muscles[j].rotate2+90,0,0,1);
-glRotatef(-skeleton.muscles[j].rotate3,0,1,0);
-glScalef(1,findDistance(skeleton.muscles[j].parent1->position,skeleton.muscles[j].parent2->position),1);
-glTranslatef(collisionpoint.x,collisionpoint.y,collisionpoint.z);
-glGetFloatv(GL_MODELVIEW_MATRIX,M);
-collisionpoint.x=M[12];
-collisionpoint.y=M[13];
-collisionpoint.z=M[14];
-glPopMatrix();
-hitstruct.collision=1;
-hitstruct.hitlocation=collisionpoint;
-hitstruct.joint1=skeleton.muscles[j].parent1;
-hitstruct.joint2=skeleton.muscles[j].parent2;
-}
-}
-}
-}
-if(skeleton.free<1){
-if(rotation)hitstruct.hitlocation=DoRotation(hitstruct.hitlocation,0,rotation,0);
-hitstruct.hitlocation=hitstruct.hitlocation+coords;
-}
-return hitstruct;
-}
-*/
 void   Person::DoAnimations(){
        if(!skeleton.free){
                int i = 0;
@@ -1989,19 +1501,8 @@ void     Person::DoAnimations(){
                if(target>=1){
                        if(targetanimation==rollanim&&targetframe==3&&onfire){
                                onfire=0;
-                               float gLoc[3];
-                               float vel[3];
-                               gLoc[0]=coords.x;
-                               gLoc[1]=coords.y;
-                               gLoc[2]=coords.z;
-                               vel[0]=0;
-                               vel[1]=0;
-                               vel[2]=0;
-                               PlaySoundEx( fireendsound, samp[fireendsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[fireendsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[fireendsound], 256);
-                               OPENAL_SetPaused(channels[fireendsound], false);
-                               OPENAL_SetPaused(channels[stream_firesound], true);
+                               emit_sound_at(fireendsound, coords);
+                               pause_sound(stream_firesound);
                                deathbleeding=0;
                        }
 
@@ -2019,27 +1520,12 @@ void    Person::DoAnimations(){
                                        //victim->DoDamage(30);
                                        if(creature==wolftype){
                                                DoBloodBig(0,255);
-                                               float gLoc[3];
-                                               float vel[3];
-                                               gLoc[0]=victim->coords.x;
-                                               gLoc[1]=victim->coords.y;
-                                               gLoc[2]=victim->coords.z;
-                                               vel[0]=velocity.x;
-                                               vel[1]=velocity.y;
-                                               vel[2]=velocity.z;
-                                               PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                               OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                               OPENAL_SetVolume(channels[clawslicesound], 128);
-                                               OPENAL_SetPaused(channels[clawslicesound], false);
+                                               emit_sound_at(clawslicesound, victim->coords);
                                                victim->spurt=1;
                                                victim->DoBloodBig(1/victim->armorhead,210);
                                        }
-                                       if(id==0){
-                                               bonus=TackleBonus;
-                                               bonustime=0;
-                                               bonusvalue=5;
-                                               if(victim->aitype==gethelptype)bonusvalue=50;
-                                       }
+                                       award_bonus(id, TackleBonus,
+                                                   victim->aitype == gethelptype ? 50 : 0);
                                }
                        }
 
@@ -2049,34 +1535,10 @@ void    Person::DoAnimations(){
                                        else if(weaponactive==0)weaponactive=-1;
 
                                        if(weaponactive==-1){
-                                               float gLoc[3];
-                                               float vel[3];
-                                               gLoc[0]=coords.x;
-                                               gLoc[1]=coords.y;
-                                               gLoc[2]=coords.z;
-                                               vel[0]=velocity.x;
-                                               vel[1]=velocity.y;
-                                               vel[2]=velocity.z;
-
-                                               PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                               OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                               OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                               OPENAL_SetPaused(channels[knifesheathesound], false);
+                                               emit_sound_at(knifesheathesound, coords);
                                        }
                                        if(weaponactive!=-1){
-                                               float gLoc[3];
-                                               float vel[3];
-                                               gLoc[0]=coords.x;
-                                               gLoc[1]=coords.y;
-                                               gLoc[2]=coords.z;
-                                               vel[0]=velocity.x;
-                                               vel[1]=velocity.y;
-                                               vel[2]=velocity.z;
-
-                                               PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                               OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                               OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                               OPENAL_SetPaused(channels[knifedrawsound], false);
+                                               emit_sound_at(knifedrawsound, coords, 128);
                                        }
                                }
                                drawtogglekeydown=1;
@@ -2085,14 +1547,6 @@ void     Person::DoAnimations(){
                        if(tutoriallevel!=1||id==0)
                                if((animation[targetanimation].label[targetframe]&&(animation[targetanimation].label[targetframe]<5||animation[targetanimation].label[targetframe]==8))/*||(targetanimation==rollanim&&targetframe==animation[rollanim].numframes-1)*/){
                                        int whichsound;
-                                       float gLoc[3];
-                                       float vel[3];
-                                       gLoc[0]=coords.x;
-                                       gLoc[1]=coords.y;
-                                       gLoc[2]=coords.z;
-                                       vel[0]=velocity.x;
-                                       vel[1]=velocity.y;
-                                       vel[2]=velocity.z;
                                        if(onterrain){
                                                if(terrain.getOpacity(coords.x,coords.z)<.2){
                                                        if(animation[targetanimation].label[targetframe]==1)whichsound=footstepsound;
@@ -2126,12 +1580,7 @@ void     Person::DoAnimations(){
                                        else if(animation[targetanimation].label[targetframe]==4)whichsound=knifeswishsound;
                                        if(animation[targetanimation].label[targetframe]==8&&tutoriallevel!=1)whichsound=landsound2;
 
-                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                       if(whichsound!=knifeswishsound)OPENAL_SetVolume(channels[whichsound], 128);
-                                       if(whichsound!=knifeswishsound&&(targetanimation==staffhitanim||targetanimation==staffgroundsmashanim||targetanimation==staffspinhitanim))OPENAL_SetVolume(channels[whichsound], 256);
-                                       if(whichsound==knifeswishsound)OPENAL_SetVolume(channels[whichsound], 512);
-                                       OPENAL_SetPaused(channels[whichsound], false);
+                                       emit_sound_at(whichsound, coords, 256.);
 
                                        if(id==0)
                                                if(whichsound==footstepsound||whichsound==footstepsound2||whichsound==footstepsound3||whichsound==footstepsound4){
@@ -2144,10 +1593,7 @@ void     Person::DoAnimations(){
 
                                                if(animation[targetanimation].label[targetframe]==3){
                                                        whichsound--;
-                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[whichsound], 128);
-                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                       emit_sound_at(whichsound, coords, 128.);
                                                }
                                }
 
@@ -2157,14 +1603,6 @@ void     Person::DoAnimations(){
                                                if(targetanimation!=crouchstabanim&&targetanimation!=swordgroundstabanim&&targetanimation!=staffgroundsmashanim)
                                                        if((animation[targetanimation].label[targetframe]&&(animation[targetanimation].label[targetframe]<5||animation[targetanimation].label[targetframe]==8))/*||(targetanimation==rollanim&&targetframe==animation[rollanim].numframes-1)*/){
                                                                int whichsound=-1;
-                                                               float gLoc[3];
-                                                               float vel[3];
-                                                               gLoc[0]=coords.x;
-                                                               gLoc[1]=coords.y;
-                                                               gLoc[2]=coords.z;
-                                                               vel[0]=velocity.x;
-                                                               vel[1]=velocity.y;
-                                                               vel[2]=velocity.z;
                                                                if(animation[targetanimation].label[targetframe]==4&&aitype!=playercontrolled){
                                                                        if(animation[targetanimation].attack!=neutral){
                                                                                i=abs(Random()%4);
@@ -2188,10 +1626,7 @@ void     Person::DoAnimations(){
                                                                //if(animation[targetanimation].label[targetframe]==8)whichsound=landsound2;
 
                                                                if(whichsound!=-1){
-                                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[whichsound], 512);
-                                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                                       emit_sound_at(whichsound, coords);
                                                                }
                                                        }
 
@@ -2214,18 +1649,7 @@ void     Person::DoAnimations(){
                                                                                if(findDistancefastflat(&coords,&weapons.position[i])<4&&weaponactive==-1){
                                                                                        if(findDistancefast(&coords,&weapons.position[i])>=1){
                                                                                                if(weapons.type[i]!=staff){
-                                                                                                       float gLoc[3];
-                                                                                                       float vel[3];
-                                                                                                       gLoc[0]=coords.x;
-                                                                                                       gLoc[1]=coords.y;
-                                                                                                       gLoc[2]=coords.z;
-                                                                                                       vel[0]=velocity.x;
-                                                                                                       vel[1]=velocity.y;
-                                                                                                       vel[2]=velocity.z;
-                                                                                                       PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                                                       OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                                                       OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                                                       OPENAL_SetPaused(channels[knifedrawsound], false);
+                                                                                                       emit_sound_at(knifedrawsound, coords, 128.);
                                                                                                }
 
                                                                                                weaponactive=0;
@@ -2251,14 +1675,6 @@ void     Person::DoAnimations(){
                                                                        if((/*weapons.velocity[i].x==0&&weapons.velocity[i].y==0&&weapons.velocity[i].z==0&&*/weapons.owner[i]==-1)||(hasvictim&&weapons.owner[i]==victim->id&&victim->skeleton.free))
                                                                                if(willwork&&findDistancefastflat(&coords,&weapons.position[i])<3&&weaponactive==-1){
                                                                                        if(findDistancefast(&coords,&weapons.position[i])<1||hasvictim){
-                                                                                               float gLoc[3];
-                                                                                               float vel[3];
-                                                                                               gLoc[0]=coords.x;
-                                                                                               gLoc[1]=coords.y;
-                                                                                               gLoc[2]=coords.z;
-                                                                                               vel[0]=velocity.x;
-                                                                                               vel[1]=velocity.y;
-                                                                                               vel[2]=velocity.z;
                                                                                                bool fleshstuck=0;
                                                                                                if(weapons.owner[i]!=-1)
                                                                                                        if(victim->weaponstuck!=-1){
@@ -2268,17 +1684,11 @@ void    Person::DoAnimations(){
                                                                                                        }
                                                                                                        if(!fleshstuck){
                                                                                                                if(weapons.type[i]!=staff){
-                                                                                                                       PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                                                                       OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                                                                       OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                                                                       OPENAL_SetPaused(channels[knifedrawsound], false);
+                                                                                                                       emit_sound_at(knifedrawsound, coords, 128.);
                                                                                                                }
                                                                                                        }
                                                                                                        if(fleshstuck){
-                                                                                                               PlaySoundEx( fleshstabremovesound, samp[fleshstabremovesound], NULL, true);
-                                                                                                               OPENAL_3D_SetAttributes(channels[fleshstabremovesound], gLoc, vel);
-                                                                                                               OPENAL_SetVolume(channels[fleshstabremovesound], 128);
-                                                                                                               OPENAL_SetPaused(channels[fleshstabremovesound], false);
+                                                                                                               emit_sound_at(fleshstabremovesound, coords, 128.);
                                                                                                        }
                                                                                                        weaponactive=0;
                                                                                                        if(weapons.owner[i]!=-1){
@@ -2306,7 +1716,7 @@ void      Person::DoAnimations(){
                                                                                                                footpoint=weapons.position[i];
                                                                                                                if(victim->weaponstuck!=-1){
                                                                                                                        if(victim->weaponids[victim->weaponstuck]==i){
-                                                                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
+                                                                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
                                                                                                                                weapons.bloody[i]=2;
                                                                                                                                weapons.blooddrip[i]=5;
                                                                                                                                victim->weaponstuck=-1;
@@ -2346,34 +1756,10 @@ void    Person::DoAnimations(){
                                                                        }
                                                                }
                                                                if(weaponactive==-1){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-
-                                                                       PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                                                       OPENAL_SetPaused(channels[knifesheathesound], false);
+                                                                       emit_sound_at(knifesheathesound, coords, 128.);
                                                                }
                                                                if(weaponactive!=-1){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-
-                                                                       PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                       OPENAL_SetPaused(channels[knifedrawsound], false);
+                                                                       emit_sound_at(knifedrawsound, coords, 128.);
                                                                }
                                                        }
 
@@ -2398,19 +1784,7 @@ void     Person::DoAnimations(){
                                                                if((targetanimation==rabbitrunninganim||targetanimation==wolfrunninganim)&&id==0){
                                                                        targetanimation=rabbittackleanim;
                                                                        targetframe=0;
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-
-                                                                       PlaySoundEx( jumpsound, samp[jumpsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[jumpsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[jumpsound], 128);
-                                                                       OPENAL_SetPaused(channels[jumpsound], false);
+                                                                       emit_sound_at(jumpsound, coords);
                                                                }
 
                                                                float closestdist;
@@ -2446,19 +1820,7 @@ void     Person::DoAnimations(){
                                                                                        if(rotatetarget.z<0)targetrotation=180-targetrotation;
                                                                                }
                                                                                if(targetanimation!=rabbitrunninganim){
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       gLoc[0]=coords.x;
-                                                                                       gLoc[1]=coords.y;
-                                                                                       gLoc[2]=coords.z;
-                                                                                       vel[0]=velocity.x;
-                                                                                       vel[1]=velocity.y;
-                                                                                       vel[2]=velocity.z;
-
-                                                                                       PlaySoundEx( jumpsound, samp[jumpsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[jumpsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[jumpsound], 128);
-                                                                                       OPENAL_SetPaused(channels[jumpsound], false);
+                                                                                       emit_sound_at(jumpsound, coords, 128.);
                                                                                }
                                                                        }
                                                        }
@@ -2478,25 +1840,11 @@ void    Person::DoAnimations(){
                                                                                        DoBlood(.2,250);
                                                                                        if(creature==wolftype)DoBloodBig(0,250);
                                                                                }
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                       emit_sound_at(heavyimpactsound, victim->coords, 128.);
                                                                                }
                                                                                if(creature==wolftype){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2/victim->armorhead,175);
                                                                                }
@@ -2514,9 +1862,7 @@ void      Person::DoAnimations(){
                                                                                victim->Puff(head);
                                                                                victim->DoDamage(damagemult*100/victim->protectionhead);
 
-                                                                               if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               SolidHitBonus(id);
                                                                        }
                                                                }
 
@@ -2528,23 +1874,9 @@ void     Person::DoAnimations(){
                                                                                        victim->spurt=1;
                                                                                        if(creature==wolftype)DoBloodBig(0,235);
                                                                                }
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               PlaySoundEx( whooshhitsound, samp[whooshhitsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[whooshhitsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[whooshhitsound], 512);
-                                                                               OPENAL_SetPaused(channels[whooshhitsound], false);
+                                                                               emit_sound_at(whooshhitsound, victim->coords);
                                                                                if(creature==wolftype){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2,175);
                                                                                }
@@ -2572,25 +1904,11 @@ void    Person::DoAnimations(){
                                                                                if(id==0)camerashake+=.4;
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,250);
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[heavyimpactsound], 160);
-                                                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                       emit_sound_at(heavyimpactsound, victim->coords, 160.);
                                                                                }
                                                                                if(creature==wolftype){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2/victim->armorhead,175);
                                                                                }
@@ -2608,16 +1926,10 @@ void    Person::DoAnimations(){
                                                                                victim->Puff(head);
                                                                                victim->DoDamage(damagemult*150/victim->protectionhead);
 
-                                                                               if(victim->damage>victim->damagetolerance){
-                                                                                       if(id==0){
-                                                                                               bonus=style;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=150;
-                                                                                       }
-                                                                               }
-                                                                               else if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               if(victim->damage>victim->damagetolerance)
+                                                                                 award_bonus(id, style);
+                                                                               else
+                                                                                 SolidHitBonus(id);
                                                                        }
                                                                }
 
@@ -2627,25 +1939,11 @@ void    Person::DoAnimations(){
                                                                                if(id==0)camerashake+=.4;
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,250);
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[heavyimpactsound], 160);
-                                                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                       emit_sound_at(heavyimpactsound, victim->coords, 160.);
                                                                                }
                                                                                if(creature==wolftype){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2/victim->armorhead,175);
                                                                                }
@@ -2663,16 +1961,10 @@ void    Person::DoAnimations(){
                                                                                victim->Puff(head);
                                                                                victim->DoDamage(damagemult*150/victim->protectionhead);
 
-                                                                               if(victim->damage>victim->damagetolerance){
-                                                                                       if(id==0){
-                                                                                               bonus=style;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=150;
-                                                                                       }
-                                                                               }
-                                                                               else if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               if(victim->damage>victim->damagetolerance)
+                                                                                 award_bonus(id, style);
+                                                                               else
+                                                                                 SolidHitBonus(id);
                                                                        }
                                                                }
 
@@ -2684,18 +1976,7 @@ void     Person::DoAnimations(){
                                                                                        victim->spurt=1;
                                                                                        DoBlood(.2,235);
                                                                                }
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               PlaySoundEx( whooshhitsound, samp[whooshhitsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[whooshhitsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[whooshhitsound], 512);
-                                                                               OPENAL_SetPaused(channels[whooshhitsound], false);
+                                                                               emit_sound_at(whooshhitsound, victim->coords);
                                                                                victim->RagDoll(0);
                                                                                XYZ relative;
                                                                                relative=victim->coords-coords;
@@ -2715,23 +1996,7 @@ void     Person::DoAnimations(){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*3&&victim->dead){
                                                                                escapednum=0;
                                                                                if(id==0)camerashake+=.2;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               /*PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[landsound2], 128);
-                                                                               OPENAL_SetPaused(channels[landsound2], false);
-                                                                               */
-                                                                               PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[movewhooshsound], 128);
-                                                                               OPENAL_SetPaused(channels[movewhooshsound], false);
+                                                                               emit_sound_at(whooshhitsound, victim->coords, 128.);
 
                                                                                victim->skeleton.longdead=0;
                                                                                victim->skeleton.free=1;
@@ -2764,19 +2029,8 @@ void     Person::DoAnimations(){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*9&&victim->dead){
                                                                                escapednum=0;
                                                                                if(id==0)camerashake+=.4;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=coords.x;
-                                                                               gLoc[1]=coords.y;
-                                                                               gLoc[2]=coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                       emit_sound_at(heavyimpactsound, coords, 128.);
                                                                                }
                                                                                XYZ relative;
                                                                                relative=victim->coords-coords;
@@ -2799,19 +2053,8 @@ void     Person::DoAnimations(){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*9&&victim->skeleton.free){
                                                                                escapednum=0;
                                                                                if(id==0)camerashake+=.4;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=coords.x;
-                                                                               gLoc[1]=coords.y;
-                                                                               gLoc[2]=coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( thudsound, samp[thudsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[thudsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[thudsound], 400);
-                                                                                       OPENAL_SetPaused(channels[thudsound], false);
+                                                                                       emit_sound_at(thudsound, coords);
                                                                                }
 
                                                                                victim->skeleton.longdead=0;
@@ -2832,9 +2075,8 @@ void      Person::DoAnimations(){
                                                                                for(i=0;i<victim->skeleton.num_joints;i++){
                                                                                        victim->skeleton.joints[i].velocity+=relative*damagemult*20;
                                                                                }
-                                                                               if(id==0&&!victim->dead){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               if(!victim->dead)
+                                                                                 SolidHitBonus(id);
 
                                                                                victim->Puff(abdomen);
                                                                                victim->DoDamage(damagemult*20/victim->protectionhigh);
@@ -2847,26 +2089,14 @@ void    Person::DoAnimations(){
                                                                }
 
                                                                if((targetanimation==crouchstabanim||targetanimation==swordgroundstabanim)&&animation[targetanimation].label[currentframe]==5){
-                                                                       // if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*9){
                                                                        //if(id==0)camerashake+=.4;
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
 
                                                                        if(hasvictim)
                                                                                if(!victim->skeleton.free)hasvictim=0;
 
                                                                        if(!hasvictim){
                                                                                terrain.MakeDecal(blooddecalfast,(weapons.tippoint[weaponids[weaponactive]]*.8+weapons.position[weaponids[weaponactive]]*.2),.08,.6,Random()%360);
-                                                                               PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                                                               OPENAL_SetPaused(channels[knifesheathesound], false);
+                                                                               emit_sound_at(knifesheathesound, coords, 128.);
                                                                        }
 
                                                                        if(victim&&hasvictim){
@@ -2912,11 +2142,8 @@ void     Person::DoAnimations(){
                                                                                        if(whichtri!=-1){
                                                                                                if(victim->dead!=2){
                                                                                                        victim->DoDamage(abs((victim->damagetolerance-victim->permanentdamage)*2));
-                                                                                                       if(id==0&&!victim->dead){
-                                                                                                               bonus=FinishedBonus;
-                                                                                                               bonustime=0;
-                                                                                                               bonusvalue=200;
-                                                                                                       }
+                                                                                                       if (!victim->dead)
+                                                                                                         award_bonus(id, FinishedBonus);
                                                                                                }
                                                                                                if(bloodtoggle)weapons.bloody[weaponids[weaponactive]]=2;
 
@@ -2929,10 +2156,7 @@ void     Person::DoAnimations(){
                                                                                                        victim->skeleton.joints[i].locked=0;
                                                                                                        //victim->skeleton.joints[i].velocity=0;
                                                                                                }
-                                                                                               PlaySoundEx( fleshstabsound, samp[fleshstabsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[fleshstabsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[fleshstabsound], 128);
-                                                                                               OPENAL_SetPaused(channels[fleshstabsound], false);
+                                                                                               emit_sound_at(fleshstabsound, coords, 128);
 
                                                                                        }
                                                                                        if(whichtri!=-1||weapons.bloody[weaponids[weaponactive]]){
@@ -2941,40 +2165,21 @@ void    Person::DoAnimations(){
                                                                                        }
                                                                                        if(whichtri==-1){
                                                                                                hasvictim=0;
-                                                                                               PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                                                                               OPENAL_SetPaused(channels[knifesheathesound], false);
+                                                                                               emit_sound_at(knifesheathesound, coords, 128.);
                                                                                        }
                                                                                }
                                                                        }
                                                                }
 
                                                                if((targetanimation==crouchstabanim||targetanimation==swordgroundstabanim)&&animation[targetanimation].label[currentframe]==6){
-                                                                       // if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*9){
-                                                                       //if(id==0)camerashake+=.4;
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
                                                                        if(!hasvictim){
-                                                                               PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                               OPENAL_SetPaused(channels[knifedrawsound], false);
+                                                                               emit_sound_at(knifedrawsound, coords, 128);
                                                                        }
 
                                                                        if(victim&&hasvictim){
                                                                                XYZ footvel,footpoint;
 
-                                                                               PlaySoundEx( fleshstabremovesound, samp[fleshstabremovesound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[fleshstabremovesound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[fleshstabremovesound], 128);
-                                                                               OPENAL_SetPaused(channels[fleshstabremovesound], false);
+                                                                               emit_sound_at(fleshstabremovesound, coords, 128.);
 
                                                                                footvel=0;
                                                                                footpoint=(weapons.tippoint[weaponids[weaponactive]]*.8+weapons.position[weaponids[weaponactive]]*.2);
@@ -3043,7 +2248,7 @@ void      Person::DoAnimations(){
                                                                                                relative.y=10;
                                                                                                Normalise(&relative);
                                                                                                //victim->Puff(abdomen);
-                                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
+                                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
 
                                                                                                if(victim->bloodloss<victim->damagetolerance){
                                                                                                        victim->bloodloss+=1000;
@@ -3068,33 +2273,10 @@ void    Person::DoAnimations(){
                                                                                        victim->spurt=1;
                                                                                        DoBlood(.2,235);
                                                                                }
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               //if(!victim->isIdle()||victim->damage>victim->damagetolerance-60){
-                                                                               if(1==1){
-                                                                                       if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                                               OPENAL_SetPaused(channels[heavyimpactsound], false);
-                                                                                       }
-                                                                               }
-                                                                               else {
-                                                                                       if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[landsound2], 256);
-                                                                                               OPENAL_SetPaused(channels[landsound2], false);
-                                                                                       }
+                                                                               if(tutoriallevel!=1){
+                                                                                 emit_sound_at(heavyimpactsound, victim->coords, 128);
                                                                                }
 
-                                                                               //if(!victim->isIdle()||victim->damage>victim->damagetolerance-60)
                                                                                victim->RagDoll(0);
                                                                                XYZ relative;
                                                                                relative=victim->coords-coords;
@@ -3115,9 +2297,7 @@ void      Person::DoAnimations(){
                                                                                victim->Puff(abdomen);
                                                                                victim->DoDamage(damagemult*60/victim->protectionhigh);
 
-                                                                               if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               SolidHitBonus(id);
                                                                        }
                                                                }
 
@@ -3126,37 +2306,19 @@ void    Person::DoAnimations(){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*2){
                                                                                escapednum=0;
                                                                                if(id==0)camerashake+=.4;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               //if(!victim->isIdle()||victim->damage>victim->damagetolerance-60){
                                                                                if(victim->damage<=victim->damagetolerance-60&&normaldotproduct(victim->facing,victim->coords-coords)<(scale*5)*(scale*5)*0&&animation[victim->targetanimation].height!=lowheight){
                                                                                        if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( thudsound, samp[thudsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[thudsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[thudsound], 512);
-                                                                                               OPENAL_SetPaused(channels[thudsound], false);
+                                                                                               emit_sound_at(thudsound, victim->coords);
                                                                                        }
                                                                                }
                                                                                else if(victim->damage<=victim->damagetolerance-60&&normaldotproduct(victim->facing,victim->coords-coords)<(scale*5)*(scale*5)*0&&animation[victim->targetanimation].height==lowheight){
                                                                                        if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( whooshhitsound, samp[whooshhitsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[whooshhitsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[whooshhitsound], 512);
-                                                                                               OPENAL_SetPaused(channels[whooshhitsound], false);
+                                                                                               emit_sound_at(whooshhitsound, victim->coords);
                                                                                        }
                                                                                }
                                                                                else {
                                                                                        if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[heavyimpactsound], 256);
-                                                                                               OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                               emit_sound_at(heavyimpactsound, victim->coords);
                                                                                        }
                                                                                }
 
@@ -3182,28 +2344,14 @@ void    Person::DoAnimations(){
                                                                                victim->Puff(abdomen);
                                                                                victim->DoDamage(damagemult*60/victim->protectionhigh);
 
-                                                                               if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               SolidHitBonus(id);
                                                                        }
                                                                }
 
                                                                if(targetanimation==blockhighleftanim&&animation[targetanimation].label[currentframe]==5){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*4){
                                                                                if(victim->id==0)camerashake+=.4;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-
-                                                                               PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[landsound2], 256);
-                                                                               OPENAL_SetPaused(channels[landsound2], false);
+                                                                               emit_sound_at(landsound2, victim->coords);
 
                                                                                Puff(righthand);
                                                                        }
@@ -3212,30 +2360,16 @@ void    Person::DoAnimations(){
                                                                if(targetanimation==swordslashparryanim&&animation[targetanimation].label[currentframe]==5){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*4){
                                                                                if(victim->id==0)camerashake+=.4;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
 
                                                                                if(weaponactive!=-1){
                                                                                        if(weapons.type[victim->weaponids[0]]==staff||weapons.type[weaponids[0]]==staff){
                                                                                                if(weapons.type[victim->weaponids[0]]==staff)weapons.damage[victim->weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
                                                                                                if(weapons.type[weaponids[0]]==staff)weapons.damage[weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
 
-                                                                                               PlaySoundEx( swordstaffsound, samp[swordstaffsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[swordstaffsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[swordstaffsound], 512);
-                                                                                               OPENAL_SetPaused(channels[swordstaffsound], false);
+                                                                                               emit_sound_at(swordstaffsound, victim->coords);
                                                                                        }
                                                                                        else{
-                                                                                               PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[metalhitsound], 512);
-                                                                                               OPENAL_SetPaused(channels[metalhitsound], false);
+                                                                                               emit_sound_at(metalhitsound, victim->coords);
                                                                                        }
                                                                                }
 
@@ -3272,28 +2406,11 @@ void    Person::DoAnimations(){
                                                                        if(hasvictim)
                                                                                if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*4.5&&/*animation[victim->targetanimation].height!=lowheight&&*/victim->targetanimation!=dodgebackanim&&victim->targetanimation!=rollanim){
                                                                                        escapednum=0;
-                                                                                       //if(Random()%2){
                                                                                        if(tutoriallevel!=1)victim->DoBloodBig(1.5/victim->armorhigh,225);
-                                                                                       //}
 
-                                                                                       if(id==0){
-                                                                                               bonus=Slicebonus;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=10;
-                                                                                       }
+                                                                                       award_bonus(id, Slicebonus);
                                                                                        if(tutoriallevel!=1){
-                                                                                               float gLoc[3];
-                                                                                               float vel[3];
-                                                                                               gLoc[0]=victim->coords.x;
-                                                                                               gLoc[1]=victim->coords.y;
-                                                                                               gLoc[2]=victim->coords.z;
-                                                                                               vel[0]=velocity.x;
-                                                                                               vel[1]=velocity.y;
-                                                                                               vel[2]=velocity.z;
-                                                                                               PlaySoundEx( knifeslicesound, samp[knifeslicesound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[knifeslicesound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[knifeslicesound], 512);
-                                                                                               OPENAL_SetPaused(channels[knifeslicesound], false);
+                                                                                               emit_sound_at(knifeslicesound, victim->coords);
                                                                                        }
                                                                                        //victim->skeleton.joints[victim->skeleton.jointlabels[abdomen]].velocity+=relative*damagemult*200;
                                                                                        if(animation[victim->targetanimation].attack&&(victim->aitype!=playercontrolled||victim->targetanimation==knifeslashstartanim)&&(victim->creature==rabbittype||victim->deathbleeding<=0)){
@@ -3320,16 +2437,16 @@ void    Person::DoAnimations(){
                                                                                                footpoint=DoRotation((victim->skeleton.joints[victim->skeleton.jointlabels[abdomen]].position+victim->skeleton.joints[victim->skeleton.jointlabels[neck]].position)/2,0,victim->rotation,0)*victim->scale+victim->coords;
                                                                                        }
                                                                                        if(tutoriallevel!=1){
-                                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .6, .3);
+                                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .6, .3);
                                                                                                footvel=DoRotation(facing,0,90,0)*.8;
                                                                                                //footvel.y-=.3;
-                                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .2, 1);
-                                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .2, 1);
+                                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .2, 1);
+                                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .2, 1);
                                                                                        }
                                                                                        if(tutoriallevel==1){
-                                                                                               sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,1,1, .6, .3);
+                                                                                               Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,1,1, .6, .3);
                                                                                        }
                                                                                        victim->DoDamage(damagemult*0);
                                                                                }
@@ -3337,40 +2454,21 @@ void    Person::DoAnimations(){
                                                                if(targetanimation==swordslashanim&&animation[targetanimation].label[currentframe]==5&&victim->targetanimation!=rollanim){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*6.5&&victim->targetanimation!=dodgebackanim){
                                                                                if(victim->weaponactive==-1||normaldotproduct(victim->facing,victim->coords-coords)>0||(Random()%2==0)){
-                                                                                       if(id==0){
-                                                                                               bonus=Slashbonus;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=40;
-                                                                                       }
+                                                                                       award_bonus(id, Slashbonus);
                                                                                        escapednum=0;
                                                                                        if(tutoriallevel!=1){
                                                                                                if(normaldotproduct(victim->facing,victim->coords-coords)<0)victim->DoBloodBig(2/victim->armorhigh,190);
                                                                                                else victim->DoBloodBig(2/victim->armorhigh,185);
                                                                                                victim->deathbleeding=1;
-                                                                                               float gLoc[3];
-                                                                                               float vel[3];
-                                                                                               gLoc[0]=victim->coords.x;
-                                                                                               gLoc[1]=victim->coords.y;
-                                                                                               gLoc[2]=victim->coords.z;
-                                                                                               vel[0]=velocity.x;
-                                                                                               vel[1]=velocity.y;
-                                                                                               vel[2]=velocity.z;
-                                                                                               PlaySoundEx( swordslicesound, samp[swordslicesound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[swordslicesound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[swordslicesound], 512);
-                                                                                               OPENAL_SetPaused(channels[swordslicesound], false);
+                                                                                               emit_sound_at(swordslicesound, victim->coords);
                                                                                        }
                                                                                        //victim->skeleton.joints[victim->skeleton.jointlabels[abdomen]].velocity+=relative*damagemult*200;
-                                                                                       //if(animation[victim->targetanimation].attack){
-                                                                                       //if(victim->creature==rabbittype){
                                                                                        if(tutoriallevel!=1){
                                                                                                victim->targetframe=0;
                                                                                                victim->targetanimation=staggerbackhardanim;
                                                                                                victim->targetrotation=targetrotation+180;
                                                                                                victim->target=0;
                                                                                        }
-                                                                                       //}
-                                                                                       //}
 
                                                                                        if(tutoriallevel!=1){
                                                                                                if(bloodtoggle&&!weapons.bloody[weaponids[weaponactive]])weapons.bloody[weaponids[weaponactive]]=1;
@@ -3390,41 +2488,25 @@ void    Person::DoAnimations(){
                                                                                                if(!skeleton.free){
                                                                                                        footpoint=DoRotation((victim->skeleton.joints[victim->skeleton.jointlabels[abdomen]].position+victim->skeleton.joints[victim->skeleton.jointlabels[neck]].position)/2,0,victim->rotation,0)*victim->scale+victim->coords;
                                                                                                }
-                                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
+                                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
                                                                                                footvel=DoRotation(facing,0,90,0)*.8;
                                                                                                footvel.y-=.3;
-                                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
-                                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
+                                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
+                                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
                                                                                        }
                                                                                }
                                                                                else {
-
-
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       gLoc[0]=victim->coords.x;
-                                                                                       gLoc[1]=victim->coords.y;
-                                                                                       gLoc[2]=victim->coords.z;
-                                                                                       vel[0]=velocity.x;
-                                                                                       vel[1]=velocity.y;
-                                                                                       vel[2]=velocity.z;
                                                                                        if(victim->weaponactive!=-1){
                                                                                                if(weapons.type[victim->weaponids[0]]==staff||weapons.type[weaponids[0]]==staff){
                                                                                                        if(weapons.type[victim->weaponids[0]]==staff)weapons.damage[victim->weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
                                                                                                        if(weapons.type[weaponids[0]]==staff)weapons.damage[weaponids[0]]+=.2+float(abs(Random()%100)-50)/250;
 
-                                                                                                       PlaySoundEx( swordstaffsound, samp[swordstaffsound], NULL, true);
-                                                                                                       OPENAL_3D_SetAttributes(channels[swordstaffsound], gLoc, vel);
-                                                                                                       OPENAL_SetVolume(channels[swordstaffsound], 512);
-                                                                                                       OPENAL_SetPaused(channels[swordstaffsound], false);
+                                                                                                       emit_sound_at(swordstaffsound, victim->coords);
                                                                                                }
                                                                                                else{
-                                                                                                       PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                                                                                       OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                                                                                       OPENAL_SetVolume(channels[metalhitsound], 512);
-                                                                                                       OPENAL_SetPaused(channels[metalhitsound], false);
+                                                                                                       emit_sound_at(metalhitsound, victim->coords);
                                                                                                }
                                                                                        }
 
@@ -3456,11 +2538,6 @@ void     Person::DoAnimations(){
                                                                                                player[i].wentforweapon=0;
                                                                                        }
 
-                                                                                       /*PlaySoundEx( metalhitsound, samp[metalhitsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[metalhitsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[metalhitsound], 512);
-                                                                                       OPENAL_SetPaused(channels[metalhitsound], false);*/
-
                                                                                }
                                                                        }
                                                                }
@@ -3474,18 +2551,7 @@ void     Person::DoAnimations(){
                                                                                        if(Random()%2||creature==wolftype){
                                                                                                victim->spurt=1;
                                                                                        }
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       gLoc[0]=victim->coords.x;
-                                                                                       gLoc[1]=victim->coords.y;
-                                                                                       gLoc[2]=victim->coords.z;
-                                                                                       vel[0]=velocity.x;
-                                                                                       vel[1]=velocity.y;
-                                                                                       vel[2]=velocity.z;
-                                                                                       PlaySoundEx( staffheadsound, samp[staffheadsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[staffheadsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[staffheadsound], 256);
-                                                                                       OPENAL_SetPaused(channels[staffheadsound], false);
+                                                                                       emit_sound_at(staffheadsound, victim->coords);
                                                                                }
                                                                                victim->RagDoll(0);
                                                                                XYZ relative;
@@ -3505,11 +2571,7 @@ void     Person::DoAnimations(){
                                                                                if(tutoriallevel!=1){
                                                                                        victim->DoDamage(damagemult*120/victim->protectionhigh);
 
-                                                                                       if(id==0){
-                                                                                               bonus=solidhit;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=30;
-                                                                                       }
+                                                                                       award_bonus(id, solidhit, 30);
                                                                                }
                                                                        }
                                                                }
@@ -3523,18 +2585,7 @@ void     Person::DoAnimations(){
                                                                                        if(Random()%2||creature==wolftype){
                                                                                                victim->spurt=1;
                                                                                        }
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       gLoc[0]=victim->coords.x;
-                                                                                       gLoc[1]=victim->coords.y;
-                                                                                       gLoc[2]=victim->coords.z;
-                                                                                       vel[0]=velocity.x;
-                                                                                       vel[1]=velocity.y;
-                                                                                       vel[2]=velocity.z;
-                                                                                       PlaySoundEx( staffheadsound, samp[staffheadsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[staffheadsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[staffheadsound], 256);
-                                                                                       OPENAL_SetPaused(channels[staffheadsound], false);
+                                                                                       emit_sound_at(staffheadsound, victim->coords);
                                                                                }
                                                                                victim->RagDoll(0);
                                                                                XYZ relative;
@@ -3551,11 +2602,7 @@ void     Person::DoAnimations(){
                                                                                victim->Puff(head);
                                                                                if(tutoriallevel!=1){victim->DoDamage(damagemult*350/victim->protectionhead);
 
-                                                                               if(id==0){
-                                                                                       bonus=solidhit;
-                                                                                       bonustime=0;
-                                                                                       bonusvalue=60;
-                                                                               }
+                                                                               award_bonus(id, solidhit, 60);
                                                                                }
                                                                        }
                                                                }
@@ -3569,18 +2616,7 @@ void     Person::DoAnimations(){
                                                                                        if(Random()%2||creature==wolftype){
                                                                                                victim->spurt=1;
                                                                                        }
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       gLoc[0]=victim->coords.x;
-                                                                                       gLoc[1]=victim->coords.y;
-                                                                                       gLoc[2]=victim->coords.z;
-                                                                                       vel[0]=velocity.x;
-                                                                                       vel[1]=velocity.y;
-                                                                                       vel[2]=velocity.z;
-                                                                                       PlaySoundEx( staffbodysound, samp[staffbodysound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[staffbodysound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[staffbodysound], 256);
-                                                                                       OPENAL_SetPaused(channels[staffbodysound], false);
+                                                                                       emit_sound_at(staffbodysound, victim->coords);
                                                                                }
                                                                                victim->skeleton.longdead=0;
                                                                                victim->skeleton.free=1;
@@ -3619,11 +2655,7 @@ void     Person::DoAnimations(){
                                                                                if(tutoriallevel!=1){victim->DoDamage(damagemult*100/victim->protectionhigh);
 
                                                                                if(!victim->dead){
-                                                                                       if(id==0){
-                                                                                               bonus=solidhit;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=40;
-                                                                                       }
+                                                                                 award_bonus(id, solidhit, 40);
                                                                                }
                                                                                }
                                                                        }
@@ -3633,22 +2665,12 @@ void    Person::DoAnimations(){
                                                                        if(findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*3&&animation[victim->targetanimation].height!=highheight){
                                                                                escapednum=0;
                                                                                if(id==0)camerashake+=.4;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                XYZ relative;
                                                                                relative=victim->coords-coords;
                                                                                relative.y=0;
                                                                                Normalise(&relative);
 
-                                                                               if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               SolidHitBonus(id);
 
                                                                                if(animation[victim->targetanimation].height==lowheight){
                                                                                        if(Random()%2){
@@ -3661,19 +2683,13 @@ void    Person::DoAnimations(){
                                                                                        }
                                                                                        victim->skeleton.joints[victim->skeleton.jointlabels[head]].velocity+=relative*damagemult*200;
                                                                                        if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                                               OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                               emit_sound_at(heavyimpactsound, victim->coords, 128.);
                                                                                        }
                                                                                        victim->Puff(head);
                                                                                        victim->DoDamage(damagemult*100/victim->protectionhead);
                                                                                        if(victim->howactive==typesleeping)victim->DoDamage(damagemult*150/victim->protectionhead);
                                                                                        if(creature==wolftype){
-                                                                                               PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                               OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                               emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                                victim->spurt=1;
                                                                                                victim->DoBloodBig(2/victim->armorhead,175);
                                                                                        }
@@ -3689,18 +2705,12 @@ void    Person::DoAnimations(){
                                                                                        victim->targetrotation=targetrotation+180;
                                                                                        victim->target=0;
                                                                                        if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[landsound2], 128);
-                                                                                               OPENAL_SetPaused(channels[landsound2], false);
+                                                                                               emit_sound_at(landsound2, victim->coords, 128.);
                                                                                        }
                                                                                        victim->Puff(abdomen);
                                                                                        victim->DoDamage(damagemult*30/victim->protectionhigh);
                                                                                        if(creature==wolftype){
-                                                                                               PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                               OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                               emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                                victim->spurt=1;
                                                                                                victim->DoBloodBig(2/victim->armorhigh,170);
                                                                                        }
@@ -3713,19 +2723,8 @@ void     Person::DoAnimations(){
                                                                        if(victim->targetanimation!=jumpupanim&&findDistancefast(&coords,&victim->coords)<(scale*5)*(scale*5)*3&&victim!=this){
                                                                                escapednum=0;
                                                                                if(id==0)camerashake+=.2;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[landsound2], 128);
-                                                                                       OPENAL_SetPaused(channels[landsound2], false);
+                                                                                       emit_sound_at(landsound2, victim->coords, 128.);
                                                                                }
                                                                                XYZ relative;
                                                                                relative=victim->coords-coords;
@@ -3764,18 +2763,13 @@ void    Person::DoAnimations(){
                                                                                        victim->targetrotation=targetrotation+180;
                                                                                        victim->target=0;
                                                                                        if(tutoriallevel!=1){
-                                                                                               PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[landsound2], 128);
-                                                                                               OPENAL_SetPaused(channels[landsound2], false);
+                                                                                               emit_sound_at(landsound2, victim->coords, 128.);
                                                                                        }
                                                                                        victim->Puff(abdomen);
                                                                                        victim->DoDamage(damagemult*30/victim->protectionlow);
                                                                                }
 
-                                                                               if(id==0){
-                                                                                       SolidHitBonus();
-                                                                               }
+                                                                               SolidHitBonus(id);
 
                                                                        }
                                                                }
@@ -3788,25 +2782,11 @@ void    Person::DoAnimations(){
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,230);
                                                                        }
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=victim->coords.x;
-                                                                       gLoc[1]=victim->coords.y;
-                                                                       gLoc[2]=victim->coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
                                                                        if(tutoriallevel!=1){
-                                                                               PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                               OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                               emit_sound_at(heavyimpactsound, victim->coords, 128.);
                                                                        }
                                                                        if(creature==wolftype){
-                                                                               PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                               OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                               emit_sound_at(clawslicesound, victim->coords, 128);
                                                                                victim->spurt=1;
                                                                                victim->DoBloodBig(2/victim->armorhigh,170);
                                                                        }
@@ -3824,11 +2804,7 @@ void     Person::DoAnimations(){
                                                                        victim->Puff(abdomen);
                                                                        victim->DoDamage(damagemult*150/victim->protectionhigh);
 
-                                                                       if(id==0){
-                                                                               bonus=Reversal;
-                                                                               bonustime=0;
-                                                                               bonusvalue=60;
-                                                                       }
+                                                                       award_bonus(id, Reversal);
                                                                }
 
                                                                if((targetanimation==swordslashreversalanim||targetanimation==knifeslashreversalanim||targetanimation==staffhitreversalanim||targetanimation==staffspinhitreversalanim)&&animation[targetanimation].label[currentframe]==5){
@@ -3858,18 +2834,7 @@ void     Person::DoAnimations(){
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,230);
                                                                        }
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=victim->coords.x;
-                                                                       gLoc[1]=victim->coords.y;
-                                                                       gLoc[2]=victim->coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-                                                                       PlaySoundEx( whooshhitsound, samp[whooshhitsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[whooshhitsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[whooshhitsound], 128);
-                                                                       OPENAL_SetPaused(channels[whooshhitsound], false);
+                                                                       emit_sound_at(whooshhitsound, victim->coords, 128.);
                                                                        victim->RagDoll(0);
                                                                        XYZ relative;
                                                                        relative=victim->coords-oldcoords;
@@ -3892,33 +2857,14 @@ void    Person::DoAnimations(){
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,230);
                                                                        }
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=victim->coords.x;
-                                                                       gLoc[1]=victim->coords.y;
-                                                                       gLoc[2]=victim->coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
 
-                                                                       if(id==0){
-                                                                               bonus=staffreversebonus;
-                                                                               bonustime=0;
-                                                                               bonusvalue=100;
-                                                                       }
+                                                                       award_bonus(id, staffreversebonus);
 
                                                                        if(tutoriallevel!=1){
-                                                                               PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                               OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                               emit_sound_at(heavyimpactsound, victim->coords, 128.);
                                                                        }
                                                                        victim->RagDoll(0);
-                                                                       if(id==0){
-                                                                               bonus=staffreversebonus;
-                                                                               bonustime=0;
-                                                                               bonusvalue=100;
-                                                                       }
+                                                                       award_bonus(id, staffreversebonus); // Huh, again?
 
                                                                        XYZ relative;
                                                                        relative=victim->coords-oldcoords;
@@ -3958,39 +2904,21 @@ void    Person::DoAnimations(){
                                                                        victim->Puff(abdomen);
                                                                        victim->DoDamage(damagemult*90/victim->protectionhigh);
 
-                                                                       if(id==0){
-                                                                               bonus=Reversal;
-                                                                               bonustime=0;
-                                                                               bonusvalue=60;
-                                                                       }
+                                                                       award_bonus(id, Reversal);
 
                                                                        bool doslice;
                                                                        doslice=0;
                                                                        if(weaponactive!=-1||creature==wolftype)doslice=1;
                                                                        if(creature==rabbittype&&weaponactive!=-1)if(weapons.type[weaponids[0]]==staff)doslice=0;
                                                                        if(doslice){
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(weaponactive!=-1){
                                                                                        victim->DoBloodBig(2/victim->armorhigh,225);
-                                                                                       PlaySoundEx( knifeslicesound, samp[knifeslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[knifeslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[knifeslicesound], 512);
-                                                                                       OPENAL_SetPaused(channels[knifeslicesound], false);
+                                                                                       emit_sound_at(knifeslicesound, victim->coords);
                                                                                        if(bloodtoggle&&!weapons.bloody[weaponids[weaponactive]])weapons.bloody[weaponids[weaponactive]]=1;
                                                                                        weapons.blooddrip[weaponids[weaponactive]]+=3;
                                                                                }
-                                                                               if(weaponactive==-1&&creature==wolftype){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                               if(weaponactive==-1&&creature==wolftype){;
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2/victim->armorhigh,175);
                                                                                }
@@ -4020,30 +2948,7 @@ void     Person::DoAnimations(){
                                                                        victim->skeleton.joints[victim->skeleton.jointlabels[rightelbow]].velocity*=.5-1;
                                                                        victim->skeleton.joints[victim->skeleton.jointlabels[rightshoulder]].velocity*=.7-1;
 
-                                                                       if(id==0){
-                                                                               bonus=swordreversebonus;
-                                                                               bonustime=0;
-                                                                               bonusvalue=100;
-                                                                       }
-                                                                       //victim->DoDamage(90);
-
-                                                                       /*if(weaponactive!=-1){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=victim->coords.x;
-                                                                       gLoc[1]=victim->coords.y;
-                                                                       gLoc[2]=victim->coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-                                                                       victim->DoBloodBig(2,225);
-                                                                       PlaySoundEx( knifeslicesound, samp[knifeslicesound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[knifeslicesound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[knifeslicesound], 512);
-                                                                       OPENAL_SetPaused(channels[knifeslicesound], false);
-                                                                       if(bloodtoggle&&!weapons.bloody[weaponids[weaponactive]])weapons.bloody[weaponids[weaponactive]]=1;
-                                                                       weapons.blooddrip[weaponids[weaponactive]]+=3;
-                                                                       }*/
+                                                                       award_bonus(id, swordreversebonus);
                                                                }
 
                                                                if(hasvictim&&targetanimation==knifeslashreversalanim&&animation[targetanimation].label[currentframe]==7){
@@ -4053,19 +2958,8 @@ void     Person::DoAnimations(){
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,230);
                                                                        }
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=victim->coords.x;
-                                                                       gLoc[1]=victim->coords.y;
-                                                                       gLoc[2]=victim->coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
                                                                        if(tutoriallevel!=1){
-                                                                               PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                               OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                               emit_sound_at(heavyimpactsound, victim->coords, 128.);
                                                                        }
                                                                        victim->RagDoll(0);
                                                                        XYZ relative;
@@ -4081,11 +2975,7 @@ void     Person::DoAnimations(){
                                                                        victim->Puff(abdomen);
                                                                        victim->DoDamage(damagemult*30/victim->protectionhigh);
 
-                                                                       if(id==0){
-                                                                               bonus=Reversal;
-                                                                               bonustime=0;
-                                                                               bonusvalue=60;
-                                                                       }
+                                                                       award_bonus(id, Reversal);
                                                                }
 
                                                                if(hasvictim&&targetanimation==sneakattackanim&&animation[targetanimation].label[currentframe]==7){
@@ -4108,38 +2998,20 @@ void    Person::DoAnimations(){
                                                                        if(weaponactive!=-1||creature==wolftype)doslice=1;
                                                                        if(creature==rabbittype&&weaponactive!=-1)if(weapons.type[weaponids[0]]==staff)doslice=0;
                                                                        if(doslice){
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
                                                                                if(weaponactive!=-1){
                                                                                        victim->DoBloodBig(200,225);
-                                                                                       PlaySoundEx( knifeslicesound, samp[knifeslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[knifeslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[knifeslicesound], 512);
-                                                                                       OPENAL_SetPaused(channels[knifeslicesound], false);
+                                                                                       emit_sound_at(knifeslicesound, victim->coords);
                                                                                        if(bloodtoggle)weapons.bloody[weaponids[weaponactive]]=2;
                                                                                        weapons.blooddrip[weaponids[weaponactive]]+=5;
                                                                                }
 
                                                                                if(creature==wolftype&&weaponactive==-1){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2,175);
                                                                                }
                                                                        }
-                                                                       if(id==0){
-                                                                               bonus=spinecrusher;
-                                                                               bonustime=0;
-                                                                               bonusvalue=100;
-                                                                       }
+                                                                       award_bonus(id, spinecrusher);
                                                                }
 
                                                                if(hasvictim&&(targetanimation==knifefollowanim||targetanimation==knifesneakattackanim)&&animation[targetanimation].label[currentframe]==5){
@@ -4153,57 +3025,36 @@ void    Person::DoAnimations(){
                                                                                        bloodvel.z=20;
                                                                                        bloodvel.y=5;
                                                                                        bloodvel=DoRotation(bloodvel,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
-                                                                                       sprites.MakeSprite(bloodsprite, DoRotation(skeleton.joints[skeleton.jointlabels[neck]].position,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
+                                                                                       Sprite::MakeSprite(bloodsprite, DoRotation(skeleton.joints[skeleton.jointlabels[neck]].position,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
                                                                                        */
                                                                                        XYZ footvel,footpoint;
                                                                                        footvel=0;
                                                                                        footpoint=weapons.tippoint[weaponids[0]];
-                                                                                       if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
+                                                                                       if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
                                                                                        footvel=(weapons.tippoint[weaponids[0]]-weapons.position[weaponids[0]]);
-                                                                                       sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                       sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                       sprites.MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
-                                                                                       sprites.MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
+                                                                                       Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                       Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                       Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
+                                                                                       Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
                                                                                        victim->DoBloodBig(200,195);
-                                                                                       if(id==0){
-                                                                                               bonus=tracheotomy;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=100;
-                                                                                       }
-
-                                                                                       //victim->neckspurtamount=5;
+                                                                                       award_bonus(id, tracheotomy);
                                                                                }
                                                                                if(targetanimation==knifefollowanim){
-                                                                                       if(id==0){
-                                                                                               bonus=Stabbonus;
-                                                                                               bonustime=0;
-                                                                                               bonusvalue=40;
-                                                                                       }
+                                                                                       award_bonus(id, Stabbonus);
                                                                                        XYZ footvel,footpoint;
                                                                                        footvel=0;
                                                                                        footpoint=weapons.tippoint[weaponids[0]];
-                                                                                       if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
+                                                                                       if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
                                                                                        footvel=(weapons.tippoint[weaponids[0]]-weapons.position[weaponids[0]])*-1;
-                                                                                       sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                       sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                                       sprites.MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .2, 1);
-                                                                                       sprites.MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .2, 1);
+                                                                                       Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                       Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                                       Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .2, 1);
+                                                                                       Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .2, 1);
 
                                                                                }
                                                                                victim->bloodloss+=10000;
                                                                                victim->velocity=0;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               PlaySoundEx( fleshstabsound, samp[fleshstabsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[fleshstabsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[fleshstabsound], 512);
-                                                                               OPENAL_SetPaused(channels[fleshstabsound], false);
+                                                                               emit_sound_at(fleshstabsound, victim->coords);
                                                                                if(bloodtoggle)weapons.bloody[weaponids[weaponactive]]=2;
                                                                                weapons.blooddrip[weaponids[weaponactive]]+=5;
                                                                        }
@@ -4222,68 +3073,42 @@ void    Person::DoAnimations(){
                                                                                }
                                                                        }
                                                                        if(weaponactive!=-1&&animation[victim->targetanimation].attack!=reversal){
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               PlaySoundEx( fleshstabremovesound, samp[fleshstabremovesound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[fleshstabremovesound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[fleshstabremovesound], 512);
-                                                                               OPENAL_SetPaused(channels[fleshstabremovesound], false);
+                                                                               emit_sound_at(fleshstabremovesound, victim->coords);
                                                                                if(bloodtoggle)weapons.bloody[weaponids[weaponactive]]=2;
                                                                                weapons.blooddrip[weaponids[weaponactive]]+=5;
 
                                                                                XYZ footvel,footpoint;
                                                                                footvel=0;
                                                                                footpoint=weapons.tippoint[weaponids[0]];
-                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
+                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
                                                                                footvel=(weapons.tippoint[weaponids[0]]-weapons.position[weaponids[0]])*-1;
-                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
-                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
                                                                        }
                                                                }
 
                                                                if(hasvictim&&(targetanimation==swordsneakattackanim)&&animation[targetanimation].label[currentframe]==5){
                                                                        if(weaponactive!=-1&&victim->bloodloss<victim->damagetolerance){
-                                                                               if(id==0){
-                                                                                       bonus=backstab;
-                                                                                       bonustime=0;
-                                                                                       bonusvalue=100;
-                                                                               }
+                                                                               award_bonus(id, backstab);
 
                                                                                escapednum=0;
 
                                                                                XYZ footvel,footpoint;
                                                                                footvel=0;
                                                                                footpoint=(weapons.tippoint[weaponids[0]]+weapons.position[weaponids[0]])/2;
-                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
+                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
                                                                                footvel=(weapons.tippoint[weaponids[0]]-weapons.position[weaponids[0]]);
-                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,DoRotation(footvel*5,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .3, 1);
-                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,DoRotation(footvel*5,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .3, 1);
                                                                                victim->DoBloodBig(200,180);
                                                                                victim->DoBloodBig(200,215);
                                                                                victim->bloodloss+=10000;
                                                                                victim->velocity=0;
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               PlaySoundEx( fleshstabsound, samp[fleshstabsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[fleshstabsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[fleshstabsound], 512);
-                                                                               OPENAL_SetPaused(channels[fleshstabsound], false);
+                                                                               emit_sound_at(fleshstabsound, victim->coords);
                                                                                if(bloodtoggle)weapons.bloody[weaponids[weaponactive]]=2;
                                                                                weapons.blooddrip[weaponids[weaponactive]]+=5;
                                                                        }
@@ -4296,30 +3121,19 @@ void    Person::DoAnimations(){
                                                                                victim->skeleton.joints[i].velocity=0;
                                                                        }
                                                                        if(weaponactive!=-1){
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=victim->coords.x;
-                                                                               gLoc[1]=victim->coords.y;
-                                                                               gLoc[2]=victim->coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-                                                                               PlaySoundEx( fleshstabremovesound, samp[fleshstabremovesound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[fleshstabremovesound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[fleshstabremovesound], 512);
-                                                                               OPENAL_SetPaused(channels[fleshstabremovesound], false);
+                                                                               emit_sound_at(fleshstabremovesound, victim->coords);
                                                                                if(bloodtoggle)weapons.bloody[weaponids[weaponactive]]=2;
                                                                                weapons.blooddrip[weaponids[weaponactive]]+=5;
 
                                                                                XYZ footvel,footpoint;
                                                                                footvel=0;
                                                                                footpoint=weapons.tippoint[weaponids[0]];
-                                                                               if(bloodtoggle)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
+                                                                               if(bloodtoggle)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .9, .3);
                                                                                footvel=(weapons.tippoint[weaponids[0]]-weapons.position[weaponids[0]])*-1;
-                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                               sprites.MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
-                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
-                                                                               sprites.MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*7,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                               Sprite::MakeSprite(bloodsprite,footpoint,DoRotation(footvel*3,(float)(Random()%20),(float)(Random()%20),0), 1,1,1, .05, .9);
+                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*5, 1,1,1, .3, 1);
+                                                                               Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*2, 1,1,1, .3, 1);
                                                                        }
                                                                }
 
@@ -4330,20 +3144,9 @@ void     Person::DoAnimations(){
                                                                                victim->spurt=1;
                                                                                DoBlood(.2,240);
                                                                        }
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=victim->coords.x;
-                                                                       gLoc[1]=victim->coords.y;
-                                                                       gLoc[2]=victim->coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
                                                                        if(weaponactive==-1){
                                                                                if(tutoriallevel!=1){
-                                                                                       PlaySoundEx( heavyimpactsound, samp[heavyimpactsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[heavyimpactsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[heavyimpactsound], 128);
-                                                                                       OPENAL_SetPaused(channels[heavyimpactsound], false);
+                                                                                       emit_sound_at(heavyimpactsound, victim->coords, 128.);
                                                                                }
                                                                        }
                                                                        bool doslice;
@@ -4353,28 +3156,18 @@ void    Person::DoAnimations(){
                                                                        if(doslice){
                                                                                if(weaponactive!=-1){
                                                                                        victim->DoBloodBig(2/victim->armorhead,225);
-                                                                                       PlaySoundEx( knifeslicesound, samp[knifeslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[knifeslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[knifeslicesound], 512);
-                                                                                       OPENAL_SetPaused(channels[knifeslicesound], false);
+                                                                                       emit_sound_at(knifeslicesound, victim->coords);
                                                                                        if(bloodtoggle&&!weapons.bloody[weaponids[weaponactive]])weapons.bloody[weaponids[weaponactive]]=1;
                                                                                        weapons.blooddrip[weaponids[weaponactive]]+=3;
                                                                                }
                                                                                if(weaponactive==-1&&creature==wolftype){
-                                                                                       PlaySoundEx( clawslicesound, samp[clawslicesound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[clawslicesound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[clawslicesound], 128);
-                                                                                       OPENAL_SetPaused(channels[clawslicesound], false);
+                                                                                       emit_sound_at(clawslicesound, victim->coords, 128.);
                                                                                        victim->spurt=1;
                                                                                        victim->DoBloodBig(2/victim->armorhead,175);
                                                                                }
                                                                        }
 
-                                                                       if(id==0){
-                                                                               bonus=Reversal;
-                                                                               bonustime=0;
-                                                                               bonusvalue=60;
-                                                                       }
+                                                                       award_bonus(id, Reversal);
 
                                                                        victim->Puff(neck);
 
@@ -4414,11 +3207,7 @@ void     Person::DoAnimations(){
 
                                                                if(hasvictim&&(targetanimation==spinkickreversalanim||targetanimation==sweepreversalanim||targetanimation==rabbitkickreversalanim||targetanimation==upunchreversalanim||targetanimation==jumpreversalanim||targetanimation==swordslashreversalanim||targetanimation==knifeslashreversalanim||targetanimation==rabbittacklereversal||targetanimation==wolftacklereversal||targetanimation==staffhitreversalanim||targetanimation==staffspinhitreversalanim))
                                                                        if(victim->damage>victim->damagetolerance&&bonus!=reverseko){
-                                                                               if(id==0){
-                                                                                       bonus=reverseko;
-                                                                                       bonustime=0;
-                                                                                       bonusvalue=100;
-                                                                               }
+                                                                         award_bonus(id, reverseko);
                                                                        }
                                                        }
 
@@ -4434,19 +3223,7 @@ void     Person::DoAnimations(){
                                                                if(currentanimation==rabbittackleanim||currentanimation==rabbittacklinganim){
                                                                        targetanimation=rollanim;
                                                                        targetframe=3;
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-
-                                                                       PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[movewhooshsound], 128);
-                                                                       OPENAL_SetPaused(channels[movewhooshsound], false);
+                                                                       emit_sound_at(movewhooshsound, coords, 128.);
                                                                }
                                                                if(currentanimation==staggerbackhighanim){
                                                                        targetanimation=getIdle();
@@ -4486,34 +3263,10 @@ void    Person::DoAnimations(){
                                                                        }
 
                                                                        if(weaponactive==-1){
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=coords.x;
-                                                                               gLoc[1]=coords.y;
-                                                                               gLoc[2]=coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-
-                                                                               PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                                                               OPENAL_SetPaused(channels[knifesheathesound], false);
+                                                                               emit_sound_at(knifesheathesound, coords, 128.);
                                                                        }
                                                                        if(weaponactive!=-1){
-                                                                               float gLoc[3];
-                                                                               float vel[3];
-                                                                               gLoc[0]=coords.x;
-                                                                               gLoc[1]=coords.y;
-                                                                               gLoc[2]=coords.z;
-                                                                               vel[0]=velocity.x;
-                                                                               vel[1]=velocity.y;
-                                                                               vel[2]=velocity.z;
-
-                                                                               PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                               OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                               OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                               OPENAL_SetPaused(channels[knifedrawsound], false);
+                                                                               emit_sound_at(knifedrawsound, coords, 128.);
                                                                        }
                                                                }
                                                                if(currentanimation==rollanim){
@@ -4588,7 +3341,8 @@ void      Person::DoAnimations(){
                                                                                targetframe=3;
                                                                                velocity=facing*-8;
                                                                                velocity.y=4;
-                                                                               if(id==0)OPENAL_SetPaused(channels[whooshsound], false);
+                                                                               if(id==0)
+                                                                                 resume_stream(whooshsound);
                                                                        }
                                                                        if(targetanimation==walljumprightanim){
                                                                                targetanimation=rightflipanim;
@@ -4606,7 +3360,8 @@ void      Person::DoAnimations(){
                                                                                velocity=facing*8;
                                                                                velocity.y=4;
                                                                        }
-                                                                       if(id==0)OPENAL_SetPaused(channels[whooshsound], false);
+                                                                       if(id==0)
+                                                                         resume_stream(whooshsound);
                                                                }
                                                                if(targetanimation==walljumpleftanim){
                                                                        if(attackkeydown){
@@ -4646,7 +3401,8 @@ void      Person::DoAnimations(){
                                                                                velocity=DoRotation(facing,0,-30,0)*-8;
                                                                                velocity.y=4;
                                                                        }
-                                                                       if(id==0)OPENAL_SetPaused(channels[whooshsound], false);
+                                                                       if(id==0)
+                                                                         resume_stream(whooshsound);
                                                                }
                                                                if(targetanimation==sneakattackanim){
                                                                        float ycoords=oldcoords.y;
@@ -4733,18 +3489,7 @@ void     Person::DoAnimations(){
                                                                        if(targetanimation==sweepreversedanim)targetrotation+=90;
                                                                        targetanimation=backhandspringanim;
                                                                        targetframe=2;
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-                                                                       PlaySoundEx( landsound, samp[landsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[landsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[landsound], 128);
-                                                                       OPENAL_SetPaused(channels[landsound], false);
+                                                                       emit_sound_at(landsound, coords, 128);
 
                                                                        if(currentanimation==upunchreversedanim||currentanimation==swordslashreversedanim){
                                                                                targetanimation=rollanim;
@@ -4804,13 +3549,13 @@ void    Person::DoAnimations(){
                                                                                //DoDamage(100);
                                                                                RagDoll(0);
                                                                                skeleton.spinny=0;
-                                                                               if(id!=0)SolidHitBonus();
+                                                                               SolidHitBonus(!id); // FIXME: tricky id
                                                                        }
                                                                        if(feint){
                                                                                escapednum++;
                                                                                targetanimation=rollanim;
                                                                                coords+=facing;
-                                                                               if(id==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                               if(id==0)pause_sound(whooshsound);
                                                                        }
                                                                        lastfeint=0;
                                                                }
@@ -4827,13 +3572,13 @@ void    Person::DoAnimations(){
                                                                                //DoDamage(100);
                                                                                RagDoll(0);
                                                                                skeleton.spinny=0;
-                                                                               if(id!=0)SolidHitBonus();
+                                                                               SolidHitBonus(!id); // FIXME: tricky id
                                                                        }
                                                                        if(feint){
                                                                                escapednum++;
                                                                                targetanimation=rollanim;
                                                                                coords+=facing*2;
-                                                                               if(id==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                                                               if(id==0)pause_sound(whooshsound);
                                                                        }
                                                                        lastfeint=0;
                                                                }
@@ -4976,14 +3721,12 @@ void    Person::DoAnimations(){
                }
 
                if(isLanding()&&landhard){
-                       //if(abs(velocity.y)>fast_sqrt(velocity.x*velocity.x*velocity.z*velocity.z)){
                        if(id==0)camerashake+=.4;
                        targetanimation=getLandhard();
                        targetframe=0;
                        target=0;
                        landhard=0;
                        transspeed=15;
-                       //}
                }
        }
        //skeleton.DoConstraints();
@@ -5054,12 +3797,6 @@ void     Person::DoStuff(){
                        targetanimation=getRun();
                        targetframe=0;
                }
-               /*static float toggledelay;
-               toggledelay-=multiplier;
-               if(toggledelay<0){
-               toggledelay=1;
-               if(Random()%3==0)superruntoggle=1-superruntoggle;
-               }*/
        }
        if(weaponactive==-1&&num_weapons>0){
                if(weapons.type[weaponids[0]]==staff){
@@ -5098,7 +3835,7 @@ void      Person::DoStuff(){
                if(skeleton.free)flatvelocity=skeleton.joints[howmany].velocity*scale/2;
                if(!skeleton.free)flatfacing=DoRotation(DoRotation(DoRotation(skeleton.joints[howmany].position,0,0,tilt),tilt2,0,0),0,rotation,0)*scale+coords;
                if(skeleton.free)flatfacing=skeleton.joints[howmany].position*scale+coords;
-               sprites.MakeSprite(flamesprite, flatfacing,flatvelocity, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
+               Sprite::MakeSprite(flamesprite, flatfacing,flatvelocity, 1,1,1, .6+(float)abs(Random()%100)/200-.25, 1);
        }
 
        while(flamedelay<0&&!onfire&&tutoriallevel==1&&id!=0){
@@ -5108,14 +3845,14 @@ void    Person::DoStuff(){
                if(skeleton.free)flatvelocity=skeleton.joints[howmany].velocity*scale/2;
                if(!skeleton.free)flatfacing=DoRotation(DoRotation(DoRotation(skeleton.joints[howmany].position,0,0,tilt),tilt2,0,0),0,rotation,0)*scale+coords;
                if(skeleton.free)flatfacing=skeleton.joints[howmany].position*scale+coords;
-               sprites.MakeSprite(breathsprite, flatfacing,flatvelocity, 1,1,1, .6+(float)abs(Random()%100)/200-.25, .3);
+               Sprite::MakeSprite(breathsprite, flatfacing,flatvelocity, 1,1,1, .6+(float)abs(Random()%100)/200-.25, .3);
        }
 
        if(bleeding>0){
                bleeding-=multiplier*.3;
                if(bloodtoggle==2){
                        glBindTexture(GL_TEXTURE_2D,skeleton.drawmodel.textureptr);
-                       if(bleeding<=0&&(detail!=2||osx))DoMipmaps(5,0,0,skeleton.skinsize,skeleton.skinsize);
+                       if(bleeding<=0&&(detail!=2||osx))DoMipmaps();
                }
        }
 
@@ -5135,8 +3872,8 @@ void      Person::DoStuff(){
                        }
                        if(skeleton.free)bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[head]].velocity,((float)(Random()%100))/40,rotation+((float)(Random()%100))/40,0)*scale;
                        if(!skeleton.free)bloodvel+=DoRotation(velocity,((float)(Random()%100))/40,((float)(Random()%100))/40,0)*scale;
-                       if(skeleton.free)sprites.MakeSprite(bloodsprite, (skeleton.joints[skeleton.jointlabels[neck]].position+(skeleton.joints[skeleton.jointlabels[neck]].position-skeleton.joints[skeleton.jointlabels[head]].position)/5)*scale+coords,bloodvel, 1,1,1, .05, .9);
-                       if(!skeleton.free)sprites.MakeSprite(bloodsprite, DoRotation(skeleton.joints[skeleton.jointlabels[neck]].position+(skeleton.joints[skeleton.jointlabels[neck]].position-skeleton.joints[skeleton.jointlabels[head]].position)/5,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, .9);
+                       if(skeleton.free)Sprite::MakeSprite(bloodsprite, (skeleton.joints[skeleton.jointlabels[neck]].position+(skeleton.joints[skeleton.jointlabels[neck]].position-skeleton.joints[skeleton.jointlabels[head]].position)/5)*scale+coords,bloodvel, 1,1,1, .05, .9);
+                       if(!skeleton.free)Sprite::MakeSprite(bloodsprite, DoRotation(skeleton.joints[skeleton.jointlabels[neck]].position+(skeleton.joints[skeleton.jointlabels[neck]].position-skeleton.joints[skeleton.jointlabels[head]].position)/5,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, .9);
                        neckspurtparticledelay=.05;
                }
                if(neckspurtdelay<0){
@@ -5154,14 +3891,10 @@ void    Person::DoStuff(){
                                bloodvel=0;
                                if(skeleton.free)bloodvel+=DoRotation(skeleton.joints[skeleton.jointlabels[abdomen]].velocity,((float)(Random()%100))/4,rotation+((float)(Random()%100))/4,0)*scale;
                                if(!skeleton.free)bloodvel+=DoRotation(velocity,((float)(Random()%100))/4,((float)(Random()%100))/4,0)*scale;
-                               if(skeleton.free)sprites.MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[abdomen]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
-                               if(!skeleton.free)sprites.MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[abdomen]].position+skeleton.joints[skeleton.jointlabels[abdomen]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
+                               if(skeleton.free)Sprite::MakeSprite(bloodsprite, skeleton.joints[skeleton.jointlabels[abdomen]].position*scale+coords,bloodvel, 1,1,1, .05, 1);
+                               if(!skeleton.free)Sprite::MakeSprite(bloodsprite, DoRotation((skeleton.joints[skeleton.jointlabels[abdomen]].position+skeleton.joints[skeleton.jointlabels[abdomen]].position)/2,0,rotation,0)*scale+coords,bloodvel, 1,1,1, .05, 1);
                        }
                }
-               /*if(id==0){
-               bloodloss+=deathbleeding*40;
-               deathbleeding=0;
-               }*/
                bloodloss+=deathbleeding*multiplier*80;
                deathbleeding-=multiplier*1.6;
                //if(id==0)deathbleeding-=multiplier*.2;
@@ -5197,9 +3930,7 @@ void      Person::DoStuff(){
                        }
 
                        if(!dead&&creature==wolftype){
-                               bonus=Wolfbonus;
-                               bonustime=0;
-                               bonusvalue=300;
+                         award_bonus(0, Wolfbonus);
                        }
                        dead=2;
                        if(targetanimation==knifefollowedanim&&!skeleton.free){
@@ -5235,10 +3966,6 @@ void     Person::DoStuff(){
                if(endy>skeleton.skinsize-1){endy=skeleton.skinsize-1;bleeding=0;}
                if(endx<startx)endx=startx;
                if(endy<starty)endy=starty;
-               /*int startx=0;
-               int starty=0;
-               int endx=256;
-               int endy=256;*/
 
                for(i=startx;i<endx;i++){
                        for(j=starty;j<endy;j++){
@@ -5252,7 +3979,7 @@ void      Person::DoStuff(){
                }
                if(!osx&&detail>1){
                        glBindTexture(GL_TEXTURE_2D,skeleton.drawmodel.textureptr);
-                       DoMipmaps(0,startx,endx,starty,endy);
+                       DoMipmaps();
                }
 
                if(!skeleton.free){
@@ -5381,7 +4108,7 @@ void      Person::DoStuff(){
                                if(!skeleton.free)footpoint=DoRotation((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2,0,rotation,0)*scale+coords;
                                if(skeleton.free)footpoint=((skeleton.joints[skeleton.jointlabels[head]].position+skeleton.joints[skeleton.jointlabels[neck]].position)/2)*scale+coords;
                                if(targetanimation==sleepanim)footvel=DoRotation(footvel,0,90,0);
-                               sprites.MakeSprite(breathsprite, footpoint+footvel*.2,footvel*.4, 1,1,1, .4, .3);
+                               Sprite::MakeSprite(breathsprite, footpoint+footvel*.2,footvel*.4, 1,1,1, .4, .3);
                        }
                }
 
@@ -5578,9 +4305,7 @@ void      Person::DoStuff(){
                unconscioustime=0;
 
                if(creature==wolftype){
-                       bonus=Wolfbonus;
-                       bonustime=0;
-                       bonusvalue=300;
+                 award_bonus(0, Wolfbonus);
                }
 
                RagDoll(0);
@@ -5614,12 +4339,6 @@ void     Person::DoStuff(){
                }
 
                damage+=20;
-
-               /*
-               if(bloodloss<damagetolerance)
-               for(i=0;i<skeleton.num_joints;i++){
-               skeleton.joints[i].velocity*=1.5;
-               }*/
        }
 
        //if(dead)damage-=multiplier/4;
@@ -5674,16 +4393,11 @@ void    Person::DoStuff(){
                bled=0;
 
                if(!dead&&creature==wolftype){
-                       bonus=Wolfbonus;
-                       bonustime=0;
-                       bonusvalue=300;
+                 award_bonus(0, Wolfbonus);
                }
 
-               if(id!=0&&unconscioustime<.1&&(bonus!=spinecrusher||bonustime>1)&&(bonus!=FinishedBonus||bonustime>1)&&bloodloss<damagetolerance){
-                       bonus=touchofdeath;
-                       bonustime=0;
-                       bonusvalue=150;
-               }
+               if(unconscioustime<.1&&(bonus!=spinecrusher||bonustime>1)&&(bonus!=FinishedBonus||bonustime>1)&&bloodloss<damagetolerance)
+                 award_bonus(id, touchofdeath);
                if(id!=0&&unconscioustime>.1){
                        numafterkill++;
                }
@@ -5692,26 +4406,11 @@ void    Person::DoStuff(){
 
                skeleton.free=1;
 
-               float gLoc[3];
-               float vel[3];
-               gLoc[0]=coords.x;
-               gLoc[1]=coords.y;
-               gLoc[2]=coords.z;
-               vel[0]=velocity.x;
-               vel[1]=velocity.y;
-               vel[2]=velocity.z;
-               PlaySoundEx( breaksound, samp[breaksound], NULL, true);
-               OPENAL_3D_SetAttributes(channels[breaksound], gLoc, vel);
-               OPENAL_SetVolume(channels[breaksound], 512);
-               OPENAL_SetPaused(channels[breaksound], false);
-               /*if(id==0||findDistancefast(&coords,&viewer)<50){
-               slomo=1;
-               slomodelay=.2;
-               }*/
+               emit_sound_at(breaksound, coords);
        }
 
        if(skeleton.free==1){
-               if(id==0)OPENAL_SetPaused(channels[whooshsound], true);
+               if(id==0)pause_sound(whooshsound);
 
                if(!dead){
                        //If knocked over, open hands and close mouth
@@ -5733,11 +4432,8 @@ void     Person::DoStuff(){
                skeleton.DoGravity(&scale);
                float damageamount;
                damageamount=skeleton.DoConstraints(&coords,&scale)*5;
-               if(id!=0&&damage>damagetolerance-damageamount&&!dead&&(bonus!=spinecrusher||bonustime>1)&&(bonus!=style||bonustime>1)&&(bonus!=cannon||bonustime>1)){
-                       bonus=deepimpact;
-                       bonustime=0;
-                       bonusvalue=50;
-               }
+               if(damage>damagetolerance-damageamount&&!dead&&(bonus!=spinecrusher||bonustime>1)&&(bonus!=style||bonustime>1)&&(bonus!=cannon||bonustime>1))
+                 award_bonus(id, deepimpact);
                DoDamage(damageamount/((protectionhigh+protectionhead+protectionlow)/3));
 
                average=0;
@@ -5777,7 +4473,7 @@ void      Person::DoStuff(){
                        skeleton.longdead+=(2000-findLength(&average))*multiplier+multiplier;
                        if(skeleton.longdead>2000){
                                if(skeleton.longdead>6000){
-                                       if(id==0)OPENAL_SetPaused(channels[whooshsound], true);
+                                       if(id==0)pause_sound(whooshsound);
                                        skeleton.free=3;
                                        DrawSkeleton();
                                        skeleton.free=2;
@@ -5861,12 +4557,8 @@ void     Person::DoStuff(){
                                if(terrainnormal.z<0)targetrotation=180-targetrotation;
                                rotation=targetrotation;
 
-                               //if(skeleton.forward.y<0){
                                targetframe=0;
-                               //}
-                               //if(skeleton.forward.y>-.3){
                                //      targetframe=2;
-                               //}
                                targetanimation=flipanim;
                                crouchtogglekeydown=1;
                                target=0;
@@ -5890,7 +4582,7 @@ void      Person::DoStuff(){
                if(findLength(&average)<10&&!dead&&skeleton.free){
                        skeleton.longdead+=(2000-findLength(&average))*multiplier+multiplier;
                        if(skeleton.longdead>(damage+500)*1.5){
-                               if(id==0)OPENAL_SetPaused(channels[whooshsound], true);
+                               if(id==0)pause_sound(whooshsound);
                                skeleton.free=0;
                                velocity=0;
                                XYZ middle;
@@ -6009,18 +4701,7 @@ void     Person::DoStuff(){
                                }
                                target=0;
 
-                               float gLoc[3];
-                               float vel[3];
-                               gLoc[0]=coords.x;
-                               gLoc[1]=coords.y;
-                               gLoc[2]=coords.z;
-                               vel[0]=velocity.x;
-                               vel[1]=velocity.y;
-                               vel[2]=velocity.z;
-                               PlaySoundEx( movewhooshsound, samp[movewhooshsound], NULL, true);
-                               OPENAL_3D_SetAttributes(channels[movewhooshsound], gLoc, vel);
-                               OPENAL_SetVolume(channels[movewhooshsound], 128);
-                               OPENAL_SetPaused(channels[movewhooshsound], false);
+                               emit_sound_at(movewhooshsound, coords, 128.);
 
                                currentanimation=targetanimation;
                                currentframe=targetframe-1;
@@ -6049,18 +4730,7 @@ void     Person::DoStuff(){
                                        if(findDistancefastflat(&coords,&objects.position[i])<objects.scale[i]*objects.scale[i]*12&&findDistancefast(&coords,&objects.position[i])<objects.scale[i]*objects.scale[i]*49){
                                                if(onfire){
                                                        if(!objects.onfire[i]){
-                                                               float gLoc[3];
-                                                               float vel[3];
-                                                               gLoc[0]=objects.position[i].x;
-                                                               gLoc[1]=objects.position[i].y;
-                                                               gLoc[2]=objects.position[i].z;
-                                                               vel[0]=0;
-                                                               vel[1]=0;
-                                                               vel[2]=0;
-                                                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[firestartsound], 256);
-                                                               OPENAL_SetPaused(channels[firestartsound], false);
+                                                               emit_sound_at(firestartsound, objects.position[i]);
                                                        }
                                                        objects.onfire[i]=1;
                                                }
@@ -6074,18 +4744,7 @@ void     Person::DoStuff(){
                                                if(findDistancefastflat(&coords,&objects.position[i])<objects.scale[i]*objects.scale[i]*12&&findDistancefast(&coords,&objects.position[i])<objects.scale[i]*objects.scale[i]*49){
                                                        if(onfire){
                                                                if(!objects.onfire[i]){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=objects.position[i].x;
-                                                                       gLoc[1]=objects.position[i].y;
-                                                                       gLoc[2]=objects.position[i].z;
-                                                                       vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
-                                                                       PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[firestartsound], 256);
-                                                                       OPENAL_SetPaused(channels[firestartsound], false);
+                                                                       emit_sound_at(firestartsound, objects.position[i]);
                                                                }
                                                                objects.onfire[i]=1;
                                                        }
@@ -6099,18 +4758,7 @@ void     Person::DoStuff(){
                                                                XYZ tempvel;
                                                                XYZ pos;
 
-                                                               float gLoc[3];
-                                                               float vel[3];
-                                                               gLoc[0]=coords.x;
-                                                               gLoc[1]=coords.y;
-                                                               gLoc[2]=coords.z;
-                                                               vel[0]=velocity.x;
-                                                               vel[1]=velocity.y;
-                                                               vel[2]=velocity.z;
-                                                               PlaySoundEx( bushrustle, samp[bushrustle], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[bushrustle], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[bushrustle], 40*findLength(&velocity));
-                                                               OPENAL_SetPaused(channels[bushrustle], false);
+                                                               emit_sound_at(bushrustle, coords, 40*findLength(&velocity));
 
                                                                if(id==0){
                                                                        envsound[numenvsounds]=coords;
@@ -6133,8 +4781,8 @@ void      Person::DoStuff(){
                                                                                        pos.x+=float(abs(Random()%100)-50)/200;
                                                                                        pos.y+=float(abs(Random()%100)-50)/200;
                                                                                        pos.z+=float(abs(Random()%100)-50)/200;
-                                                                                       sprites.MakeSprite(splintersprite, pos,tempvel*.5+velocity*float(abs(Random()%100))/100, 165/255+float(abs(Random()%100)-50)/400,0,0, .2+float(abs(Random()%100)-50)/1300, 1);
-                                                                                       sprites.special[sprites.numsprites-1]=1;
+                                                                                       Sprite::MakeSprite(splintersprite, pos,tempvel*.5+velocity*float(abs(Random()%100))/100, 165/255+float(abs(Random()%100)-50)/400,0,0, .2+float(abs(Random()%100)-50)/1300, 1);
+                                                                                       Sprite::setLastSpriteSpecial(1);
                                                                                }
                                                                                howmany=findLength(&velocity)*4;
                                                                                if(detail==2)
@@ -6148,8 +4796,8 @@ void      Person::DoStuff(){
                                                                                                        pos.x+=float(abs(Random()%100)-50)/200;
                                                                                                        pos.y+=float(abs(Random()%100)-50)/200;
                                                                                                        pos.z+=float(abs(Random()%100)-50)/200;
-                                                                                                       sprites.MakeSprite(splintersprite, pos,tempvel*.3+velocity*float(abs(Random()%100))/100/2, 1,1,1, .1, 1);
-                                                                                                       sprites.special[sprites.numsprites-1]=2;
+                                                                                                       Sprite::MakeSprite(splintersprite, pos,tempvel*.3+velocity*float(abs(Random()%100))/100/2, 1,1,1, .1, 1);
+                                                                                                       Sprite::setLastSpriteSpecial(2);
                                                                                                }
                                                        }
                                                        objects.rotx[i]+=velocity.x*multiplier*6;
@@ -6166,39 +4814,11 @@ void    Person::DoStuff(){
                                                                tempcoord+=objects.position[i];
                                                        }
                                                        if(findDistancefastflat(&tempcoord,&objects.position[i])<objects.scale[i]*objects.scale[i]*8&&findDistancefast(&tempcoord,&objects.position[i])<objects.scale[i]*objects.scale[i]*300&&tempcoord.y>objects.position[i].y+3*objects.scale[i]){
-                                                               /*if(onfire){
-                                                               if(!objects.onfire[i]){
-                                                               float gLoc[3];
-                                                               float vel[3];
-                                                               gLoc[0]=objects.position[i].x;
-                                                               gLoc[1]=objects.position[i].y;
-                                                               gLoc[2]=objects.position[i].z;
-                                                               vel[0]=0;
-                                                               vel[1]=0;
-                                                               vel[2]=0;
-                                                               PlaySoundEx( firestartsound, samp[firestartsound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[firestartsound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[firestartsound], 256);
-                                                               OPENAL_SetPaused(channels[firestartsound], false);
-                                                               objects.onfire[i]=1;
-                                                               }
-                                                               }*/
                                                                if(objects.messedwith[i]<=0){
                                                                        XYZ tempvel;
                                                                        XYZ pos;
 
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-                                                                       PlaySoundEx( bushrustle, samp[bushrustle], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[bushrustle], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[bushrustle], 40*findLength(&velocity));
-                                                                       OPENAL_SetPaused(channels[bushrustle], false);
+                                                                       emit_sound_at(bushrustle, coords, 40*findLength(&velocity));
 
                                                                        if(id==0){
                                                                                envsound[numenvsounds]=coords;
@@ -6222,8 +4842,8 @@ void      Person::DoStuff(){
                                                                                                pos.x+=float(abs(Random()%100)-50)/150;
                                                                                                pos.y+=float(abs(Random()%100)-50)/150;
                                                                                                pos.z+=float(abs(Random()%100)-50)/150;
-                                                                                               sprites.MakeSprite(splintersprite, pos,tempvel*.5+velocity*float(abs(Random()%100))/100, 165/255+float(abs(Random()%100)-50)/400,0,0, .2+float(abs(Random()%100)-50)/1300, 1);
-                                                                                               sprites.special[sprites.numsprites-1]=1;
+                                                                                               Sprite::MakeSprite(splintersprite, pos,tempvel*.5+velocity*float(abs(Random()%100))/100, 165/255+float(abs(Random()%100)-50)/400,0,0, .2+float(abs(Random()%100)-50)/1300, 1);
+                                                                                               Sprite::setLastSpriteSpecial(1);
                                                                                        }
                                                                                        howmany=findLength(&velocity)*4;
                                                                                        if(detail==2)
@@ -6238,8 +4858,8 @@ void      Person::DoStuff(){
                                                                                                                pos.x+=float(abs(Random()%100)-50)/150;
                                                                                                                pos.y+=float(abs(Random()%100)-50)/150;
                                                                                                                pos.z+=float(abs(Random()%100)-50)/150;
-                                                                                                               sprites.MakeSprite(splintersprite, pos,tempvel*.3+velocity*float(abs(Random()%100))/100/2, 1,1,1, .1, 1);
-                                                                                                               sprites.special[sprites.numsprites-1]=2;
+                                                                                                               Sprite::MakeSprite(splintersprite, pos,tempvel*.3+velocity*float(abs(Random()%100))/100/2, 1,1,1, .1, 1);
+                                                                                                               Sprite::setLastSpriteSpecial(2);
                                                                                                        }
                                                                }
                                                                objects.messedwith[i]=.5;
@@ -6256,14 +4876,6 @@ void     Person::DoStuff(){
                                if(tutoriallevel==1&&id!=0)play=0;
                                if(play&&aitype!=playercontrolled){
                                        int whichsound=-1;
-                                       float gLoc[3];
-                                       float vel[3];
-                                       gLoc[0]=coords.x;
-                                       gLoc[1]=coords.y;
-                                       gLoc[2]=coords.z;
-                                       vel[0]=velocity.x;
-                                       vel[1]=velocity.y;
-                                       vel[2]=velocity.z;
                                        i=abs(Random()%4);
                                        if(speechdelay<=0){
                                                if(creature==rabbittype){
@@ -6276,14 +4888,9 @@ void     Person::DoStuff(){
                                                }
                                        }
                                        speechdelay=.3;
-                                       //else if(animation[targetanimation].label[targetframe]==4)whichsound=knifeswishsound;
-                                       //if(animation[targetanimation].label[targetframe]==8)whichsound=landsound2;
 
                                        if(whichsound!=-1){
-                                               PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                               OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                               OPENAL_SetVolume(channels[whichsound], 512);
-                                               OPENAL_SetPaused(channels[whichsound], false);
+                                               emit_sound_at(whichsound, coords);
                                        }
                                }
 
@@ -6317,7 +4924,6 @@ void      Person::DoStuff(){
 
                                if(targetanimation==bounceidleanim||targetanimation==wolfidle||targetanimation==walkanim||targetanimation==drawrightanim||targetanimation==crouchdrawrightanim||targetanimation==drawleftanim||targetanimation==fightidleanim||targetanimation==fightsidestep||targetanimation==hanganim||isCrouch()||targetanimation==backhandspringanim){
                                        //open hands and close mouth
-                                       //if(targetanimation!=wolfidle){
                                        if(righthandmorphend!=0&&righthandmorphness==targetrighthandmorphness){
                                                righthandmorphness=0;
                                                righthandmorphend=0;
@@ -6329,7 +4935,6 @@ void      Person::DoStuff(){
                                                lefthandmorphend=0;
                                                targetlefthandmorphness=1;
                                        }
-                                       //s}
 
                                        if(headmorphend!=3&&headmorphend!=5&&headmorphstart!=3&&headmorphstart!=5&&headmorphend!=0&&headmorphness==targetheadmorphness){
                                                headmorphness=0;
@@ -6545,21 +5150,6 @@ void     Person::DoStuff(){
                                                velocity=flatfacing*velspeed;
                                        }
 
-                                       /*if(creature==wolftype)
-                                       if(isRun()){
-                                       velocity+=facing*multiplier*speed*700*scale;
-                                       velspeed=findLength(&velocity);
-                                       if(velspeed>speed*55*scale){
-                                       velocity/=velspeed;
-                                       velspeed=speed*55*scale;
-                                       velocity*=velspeed;
-                                       }
-                                       velocity.y+=gravity*multiplier*20;
-                                       ReflectVector(&velocity,terrain.getNormal(coords.x,coords.z));
-                                       velspeed=findLength(&velocity);
-                                       velocity=flatfacing*velspeed;
-                                       }*/
-
                                        if(targetanimation==rollanim&&animation[targetanimation].label[targetframe]!=6){
                                                velocity+=facing*multiplier*speed*700*scale;
                                                velspeed=findLength(&velocity);
@@ -6704,25 +5294,14 @@ void    Person::DoStuff(){
                                                onterrain=1;
 
                                                if(id==0){
-                                                       OPENAL_SetPaused(channels[whooshsound], true);
+                                                       pause_sound(whooshsound);
                                                        OPENAL_SetVolume(channels[whooshsound], 0);
                                                }
 
                                                if(targetanimation==jumpdownanim||isFlip()){
                                                        if(isFlip())jumppower=-4;
                                                        targetanimation=getLanding();
-                                                       float gLoc[3];
-                                                       float vel[3];
-                                                       gLoc[0]=coords.x;
-                                                       gLoc[1]=coords.y;
-                                                       gLoc[2]=coords.z;
-                                                       vel[0]=velocity.x;
-                                                       vel[1]=velocity.y;
-                                                       vel[2]=velocity.z;
-                                                       PlaySoundEx( landsound, samp[landsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[landsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[landsound], 128);
-                                                       OPENAL_SetPaused(channels[landsound], false);
+                                                       emit_sound_at(landsound, coords, 128.);
 
                                                        if(id==0){
                                                                envsound[numenvsounds]=coords;
@@ -6778,25 +5357,11 @@ void    Person::DoStuff(){
                                        if(skiddingdelay<0)skiddingdelay+=multiplier;
                                        if(skiddingdelay>.02&&!forwardkeydown&&!backkeydown&&!leftkeydown&&!rightkeydown&&!jumpkeydown&&isLanding()&&!landhard){
                                                skiddingdelay=-1;
-                                               float gLoc[3];
-                                               float vel[3];
-                                               gLoc[0]=coords.x;
-                                               gLoc[1]=coords.y;
-                                               gLoc[2]=coords.z;
-                                               vel[0]=velocity.x;
-                                               vel[1]=velocity.y;
-                                               vel[2]=velocity.z;
                                                if(!onterrain||environment==grassyenvironment){
-                                                       PlaySoundEx( skidsound, samp[skidsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[skidsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[skidsound], 128*velspeed/10);
-                                                       OPENAL_SetPaused(channels[skidsound], false);
+                                                       emit_sound_at(skidsound, coords, 128*velspeed/10);
                                                }
                                                else {
-                                                       PlaySoundEx( snowskidsound, samp[snowskidsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[snowskidsound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[snowskidsound], 128*velspeed/10);
-                                                       OPENAL_SetPaused(channels[snowskidsound], false);
+                                                       emit_sound_at(snowskidsound, coords, 128*velspeed/10);
                                                }
                                        }
 
@@ -6864,9 +5429,12 @@ int Person::DrawSkeleton(){
                if(findDistancefast(&viewer,&coords)<viewdistance*viewdistance/256&&(detail!=1&&detail!=2)){
                        playerdetail=1;
                }
-               if(id==0)playerdetail=1;
-               if(playerdetail!=oldplayerdetail)updatedelay=0;
-               if(playerdetail!=oldplayerdetail)normalsupdatedelay=0;
+               if(id==0)
+                       playerdetail=1;
+               if(playerdetail!=oldplayerdetail) {
+                       updatedelay=0;
+                       normalsupdatedelay=0;
+               }
                static float updatedelaychange;
                static float morphness;
                static float framemult;
@@ -7014,7 +5582,8 @@ int Person::DrawSkeleton(){
                                        }
                                }
                        }
-                       if(!skeleton.free&&(!animation[targetanimation].attack&&targetanimation!=getupfrombackanim&&targetanimation!=getupfrombackanim&&((targetanimation!=rollanim&&!isFlip())||animation[targetanimation].label[targetframe]==6)&&targetanimation!=getupfromfrontanim&&targetanimation!=wolfrunninganim&&targetanimation!=rabbitrunninganim&&targetanimation!=backhandspringanim&&targetanimation!=walljumpfrontanim&&targetanimation!=hurtidleanim&&!isLandhard()&&!isSleeping()))DoHead();
+                       if(!skeleton.free&&(!animation[targetanimation].attack&&targetanimation!=getupfrombackanim&&((targetanimation!=rollanim&&!isFlip())||animation[targetanimation].label[targetframe]==6)&&targetanimation!=getupfromfrontanim&&targetanimation!=wolfrunninganim&&targetanimation!=rabbitrunninganim&&targetanimation!=backhandspringanim&&targetanimation!=walljumpfrontanim&&targetanimation!=hurtidleanim&&!isLandhard()&&!isSleeping()))
+                               DoHead();
                        else {
                                targetheadrotation=-targetrotation;
                                targetheadrotation2=0;
@@ -7081,35 +5650,11 @@ int Person::DrawSkeleton(){
 
                                                skeleton.muscles[i].lastrotate3=skeleton.muscles[i].rotate3;
                                                glRotatef(-skeleton.muscles[i].lastrotate3,0,1,0);
-                                               /*
-                                               if(!isnormal(proportionbody.x)||!isnormal(proportionbody.y)||!isnormal(proportionbody.z)){
-                                               proportionbody=1;
-                                               proportionweird=1;
-                                               }
-                                               if(!isnormal(proportionarms.x)||!isnormal(proportionarms.y)||!isnormal(proportionarms.z)){
-                                               proportionarms=1;
-                                               proportionweird=1;
-                                               }
-                                               if(!isnormal(proportionhead.x)||!isnormal(proportionhead.y)||!isnormal(proportionhead.z)){
-                                               proportionhead=1;
-                                               proportionweird=1;
-                                               }
-                                               if(!isnormal(proportionlegs.x)||!isnormal(proportionlegs.y)||!isnormal(proportionlegs.z)){
-                                               proportionlegs=1;
-                                               proportionweird=1;
-                                               }*/
 
                                                if(playerdetail||skeleton.free==3)
                                                {
                                                        for(j=0;j<skeleton.muscles[i].numvertices;j++)
                                                        {
-                                                               /*if(!isnormal(skeleton.model[start].vertex[skeleton.muscles[i].vertices[j]].x))vertexweird[0]=1;
-                                                               if(!isnormal(skeleton.model[start].vertex[skeleton.muscles[i].vertices[j]].y))vertexweird[1]=1;
-                                                               if(!isnormal(skeleton.model[start].vertex[skeleton.muscles[i].vertices[j]].z))vertexweird[2]=1;
-                                                               if(!isnormal(skeleton.model[endthing].vertex[skeleton.muscles[i].vertices[j]].x))vertexweird[3]=1;
-                                                               if(!isnormal(skeleton.model[endthing].vertex[skeleton.muscles[i].vertices[j]].y))vertexweird[4]=1;
-                                                               if(!isnormal(skeleton.model[endthing].vertex[skeleton.muscles[i].vertices[j]].z))vertexweird[5]=1;
-                                                               if(skeleton.muscles[i].vertices[j]<skeleton.model[start].vertexNum&&skeleton.muscles[i].vertices[j]>=0){*/
                                                                glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
                                                                glPushMatrix();
                                                                        if(skeleton.muscles[i].parent1->label==abdomen||skeleton.muscles[i].parent2->label==abdomen)
@@ -7130,24 +5675,18 @@ int Person::DrawSkeleton(){
                                                                                (skeleton.model[start].vertex[skeleton.muscles[i].vertices[j]].z*(1-morphness)+skeleton.model[endthing].vertex[skeleton.muscles[i].vertices[j]].z*morphness)*proportionhead.z);
                                                                        glGetFloatv(GL_MODELVIEW_MATRIX,M);
                                                                        //if(!isnormal(M[12])||!isnormal(M[13])||!isnormal(M[14]))test=0;
-                                                                       //if(isnormal(M[12])&&isnormal(M[13])&&isnormal(M[14])){
                                                                        //if(!isnormal(scale))test=1;
-                                                                       //if(isnormal(scale)){
                                                                        skeleton.drawmodel.vertex[skeleton.muscles[i].vertices[j]].x=M[12]*scale;
                                                                        skeleton.drawmodel.vertex[skeleton.muscles[i].vertices[j]].y=M[13]*scale;
                                                                        skeleton.drawmodel.vertex[skeleton.muscles[i].vertices[j]].z=M[14]*scale;
                                                                        //test=2;
-                                                                       //}
-                                                                       //}
                                                                glPopMatrix();
-                                                               //}
                                                        }
                                                }
                                                if(!playerdetail||skeleton.free==3)
                                                {
                                                        for(j=0;j<skeleton.muscles[i].numverticeslow;j++)
                                                        {
-                                                               //if(skeleton.muscles[i].verticeslow[j]<skeleton.modellow.vertexNum&&skeleton.muscles[i].verticeslow[j]>=0){
                                                                glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
                                                                glPushMatrix();
                                                                        if(skeleton.muscles[i].parent1->label==abdomen||skeleton.muscles[i].parent2->label==abdomen)
@@ -7172,7 +5711,6 @@ int Person::DrawSkeleton(){
                                                                        skeleton.drawmodellow.vertex[skeleton.muscles[i].verticeslow[j]].y=M[13]*scale;
                                                                        skeleton.drawmodellow.vertex[skeleton.muscles[i].verticeslow[j]].z=M[14]*scale;
                                                                glPopMatrix();
-                                                               //}
                                                        }
                                                }
                                        glPopMatrix();
@@ -7318,12 +5856,12 @@ int Person::DrawSkeleton(){
                        }
                        if(playerdetail){
                                if(!showpoints){
-                                       if((tutoriallevel&&id!=0))skeleton.drawmodel.drawdifftex(sprites.cloudimpacttexture);
+                                       if((tutoriallevel&&id!=0))skeleton.drawmodel.drawdifftex(Sprite::cloudimpacttexture);
                                        else skeleton.drawmodel.draw();
                                }
                        }
                        if(!playerdetail){
-                               if((tutoriallevel&&id!=0))skeleton.drawmodellow.drawdifftex(sprites.cloudimpacttexture);
+                               if((tutoriallevel&&id!=0))skeleton.drawmodellow.drawdifftex(Sprite::cloudimpacttexture);
                                else skeleton.drawmodellow.drawdifftex(skeleton.drawmodel.textureptr);
                        }
 
@@ -7347,12 +5885,12 @@ int Person::DrawSkeleton(){
                                                glTranslatef(smoketex*.6,0,0);
                                                if(playerdetail){
                                                        if(!showpoints){
-                                                               if((tutoriallevel&&id!=0))skeleton.drawmodel.drawdifftex(sprites.cloudimpacttexture);
+                                                               if((tutoriallevel&&id!=0))skeleton.drawmodel.drawdifftex(Sprite::cloudimpacttexture);
                                                                else skeleton.drawmodel.draw();
                                                        }
                                                }
                                                if(!playerdetail){
-                                                       if((tutoriallevel&&id!=0))skeleton.drawmodellow.drawdifftex(sprites.cloudimpacttexture);
+                                                       if((tutoriallevel&&id!=0))skeleton.drawmodellow.drawdifftex(Sprite::cloudimpacttexture);
                                                        else skeleton.drawmodellow.drawdifftex(skeleton.drawmodel.textureptr);
                                                }
                                }
@@ -7411,13 +5949,6 @@ int Person::DrawSkeleton(){
                                                CrossProduct(&vec1,&vec2,&tempnormthing);
                                                Normalise(&tempnormthing);
                                                if(targetanimation!=staffhitanim&&currentanimation!=staffhitanim&&targetanimation!=staffgroundsmashanim&&currentanimation!=staffgroundsmashanim&&targetanimation!=staffspinhitanim&&currentanimation!=staffspinhitanim)weaponpoint+=tempnormthing*.1-skeleton.specialforward[1]*.3+(skeleton.joints[skeleton.jointlabels[rightwrist]].position-skeleton.joints[skeleton.jointlabels[rightelbow]].position);
-                                               /*if(targetanimation==staffhitanim||currentanimation==staffhitanim){
-                                               XYZ weaptargnorm;
-                                               weaptargnorm=DoRotation(weapons.tippoint[i]-weapons.position[i],0,-rotation,0);
-                                               //weaptargnorm=animation[currentanimation].weapontarget[currentframe]*(1-target)+animation[targetanimation].weapontarget[targetframe]*(target);
-                                               Normalise(&weaptargnorm);
-                                               weaponpoint-=weaptargnorm*2;
-                                               }*/
                                        }
                                }
                                if(weaponactive!=k&&weaponstuck!=k){
@@ -7585,8 +6116,6 @@ int Person::DrawSkeleton(){
                                        if(weaponstuckwhere==0)weapons.smallrotation[i]=180;
                                        else weapons.smallrotation[i]=0;
                                        weapons.smallrotation2[i]=10;
-                                       //if(animation[targetanimation].height==lowheight&&animation[targetanimation].attack==neutral){
-                                       //}
                                }
                        }
                }
@@ -7654,25 +6183,14 @@ int Person::SphereCheck(XYZ *p1,float radius, XYZ *p, XYZ *move, float *rotate,
                                                                onterrain=1;
 
                                                                if(id==0){
-                                                                       OPENAL_SetPaused(channels[whooshsound], true);
+                                                                       pause_sound(whooshsound);
                                                                        OPENAL_SetVolume(channels[whooshsound], 0);
                                                                }
 
                                                                if((targetanimation==jumpdownanim||isFlip())&&!wasLanding()&&!wasLandhard()){
                                                                        if(isFlip())jumppower=-4;
                                                                        targetanimation=getLanding();
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=coords.x;
-                                                                       gLoc[1]=coords.y;
-                                                                       gLoc[2]=coords.z;
-                                                                       vel[0]=velocity.x;
-                                                                       vel[1]=velocity.y;
-                                                                       vel[2]=velocity.z;
-                                                                       PlaySoundEx( landsound, samp[landsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[landsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[landsound], 128);
-                                                                       OPENAL_SetPaused(channels[landsound], false);
+                                                                       emit_sound_at(landsound, coords, 128.);
 
                                                                        if(id==0){
                                                                                envsound[numenvsounds]=coords;
@@ -7726,281 +6244,3 @@ int Person::SphereCheck(XYZ *p1,float radius, XYZ *p, XYZ *move, float *rotate,
        *p1+=*move;
        return firstintersecting;
 }
-
-Person::Person()
-{
-       whichpatchx = 0;
-       whichpatchz = 0;
-
-       currentframe = 0;
-       targetframe = 0;
-       currentanimation = 0;
-       targetanimation = 0;
-       oldcurrentframe = 0;
-       oldtargetframe = 0;
-       oldcurrentanimation = 0;
-       oldtargetanimation = 0;
-
-       howactive = 0;
-
-       parriedrecently = 0;
-
-       superruntoggle = 0;
-
-       lastattack = 0,lastattack2 = 0,lastattack3 = 0;
-
-       currentoffset = 0,targetoffset = 0,offset = 0;
-       target = 0;
-       transspeed = 0;
-
-       realoldcoords = 0;
-       oldcoords = 0;
-       coords = 0;
-       originalcoords = 0;
-       velocity = 0;
-
-       proportionhead = 0;
-       proportionlegs = 0;
-       proportionarms = 0;
-       proportionbody = 0;
-
-       heightleft = 0;
-       heightright = 0;
-
-       unconscioustime = 0;
-
-       immobile = 0;
-
-       velspeed = 0;
-       targetrotation = 0;
-       targetrot = 0;
-       rot = 0;
-       oldrot = 0;
-       lookrotation = 0;
-       lookrotation2 = 0;
-       rotation = 0;
-       rotation2 = 0;
-       lowrotation = 0;
-       tilt = 0;
-       targettilt = 0;
-       tilt2 = 0;
-       targettilt2 = 0;
-       rabbitkickenabled = 0;
-
-       bloodloss = 0;
-       bleeddelay = 0;
-       skiddelay = 0;
-       skiddingdelay = 0;
-       deathbleeding = 0;
-       tempdeltav = 0;
-
-       damagetolerance = 0;
-       damage = 0;
-       permanentdamage = 0;
-       superpermanentdamage = 0;       lastcollide = 0;
-       dead = 0;
-
-       jumppower = 0;
-       onground = 0;
-       madskills = 0;
-
-       wentforweapon = 0;
-
-       calcrot = 0;
-
-       backwardsanim = 0;
-
-       facing = 0;
-
-       bleeding = 0;
-       bleedx = 0,bleedy;
-       direction = 0;
-       texupdatedelay = 0;
-
-       headrotation = 0,headrotation2 = 0;
-       targetheadrotation = 0,targetheadrotation2 = 0;
-
-       onterrain = 0;
-       pause = 0;
-
-       grabdelay = 0;
-
-       victim = 0;
-       hasvictim = 0;
-
-       updatedelay = 0;
-       normalsupdatedelay = 0;
-
-       jumpstart = 0;
-
-       forwardkeydown = 0;
-       forwardstogglekeydown = 0;
-       rightkeydown = 0;
-       leftkeydown = 0;
-       backkeydown = 0;
-       jumpkeydown = 0;
-       jumptogglekeydown = 0;
-       crouchkeydown = 0;
-       crouchtogglekeydown = 0;
-       drawkeydown = 0;
-       drawtogglekeydown = 0;
-       throwkeydown = 0;
-       throwtogglekeydown = 0;
-       attackkeydown = 0;
-       feint = 0;
-       lastfeint = 0;
-       headless = 0;
-
-       crouchkeydowntime = 0;
-       jumpkeydowntime = 0;
-       freefall = 0;
-
-
-       turnspeed = 0;
-
-       aitype = 0;
-       aitarget = 0;
-       aiupdatedelay = 0;
-       losupdatedelay = 0;
-       ally = 0;
-       movetarget = 0;
-       collide = 0;
-       collided = 0;
-       avoidcollided = 0;
-       loaded = 0;
-       whichdirection = 0;
-       whichdirectiondelay = 0;
-       avoidsomething = 0;     avoidwhere = 0;
-       blooddimamount = 0;
-
-       staggerdelay = 0;
-       blinkdelay = 0;
-       twitchdelay = 0;
-       twitchdelay2 = 0;
-       twitchdelay3 = 0;
-       lefthandmorphness = 0;
-       righthandmorphness = 0;
-       headmorphness = 0;
-       chestmorphness = 0;
-       tailmorphness = 0;
-       targetlefthandmorphness = 0;
-       targetrighthandmorphness = 0;
-       targetheadmorphness = 0;
-       targetchestmorphness = 0;
-       targettailmorphness = 0;
-       lefthandmorphstart = 0,lefthandmorphend = 0;
-       righthandmorphstart = 0,righthandmorphend = 0;
-       headmorphstart = 0,headmorphend = 0;
-       chestmorphstart = 0,chestmorphend = 0;
-       tailmorphstart = 0,tailmorphend = 0;
-
-       weaponmissdelay = 0;
-       highreversaldelay = 0;
-       lowreversaldelay = 0;
-       nocollidedelay = 0;
-
-       creature = 0;
-
-       id = 0;
-
-       //Skeleton skeleton;
-
-       speed = 0;
-       scale = 0;
-       power = 0;
-       speedmult = 0;
-
-       protectionhead = 0;
-       protectionhigh = 0;
-       protectionlow = 0;
-       armorhead = 0;
-       armorhigh = 0;
-       armorlow = 0;
-       metalhead = 0;
-       metalhigh = 0;
-       metallow = 0;
-
-       numclothes = 0;
-
-       memset(clothes, 0, sizeof(clothes));
-       memset(clothestintr, 0, sizeof(clothestintr));
-       memset(clothestintg, 0, sizeof(clothestintg));
-       memset(clothestintb, 0, sizeof(clothestintb));
-
-       landhard = 0;
-       bled = 0;
-       spurt = 0;
-       onfire = 0;
-       onfiredelay = 0;        burnt = 0;
-       fireduration = 0;
-
-       flamedelay = 0;
-       updatestuffdelay = 0;
-
-       playerdetail = 0;
-
-       num_weapons = 0;
-
-       memset(weaponids, 0, sizeof(weaponids));
-
-       weaponactive = 0;
-       weaponstuck = 0;
-       weaponstuckwhere = 0;
-       weaponwhere = 0;
-
-       numwaypoints = 0;
-
-       memset(waypoints, 0, sizeof(waypoints));
-       memset(waypointtype, 0, sizeof(waypointtype));
-
-       pausetime = 0;
-       hastempwaypoint = 0;
-       tempwaypoint = 0;
-
-       headtarget = 0;
-       interestdelay = 0;
-
-       finalfinaltarget = 0;
-       finaltarget = 0;
-       finalpathfindpoint = 0;
-       targetpathfindpoint = 0;
-       lastpathfindpoint = 0;
-       lastpathfindpoint2 = 0;
-       lastpathfindpoint3 = 0;
-       lastpathfindpoint4 = 0;
-       onpath = 0;
-
-       waypoint = 0;
-       jumppath = 0;
-
-       lastseen = 0;
-       lastseentime = 0;
-       lastchecktime = 0;
-       stunned = 0;
-       surprised = 0;
-       runninghowlong = 0;     lastoccluded = 0;
-       laststanding = 0;
-       escapednum = 0;
-
-       speechdelay = 0;
-       neckspurtdelay = 0;
-       neckspurtparticledelay = 0;
-       neckspurtamount = 0;
-
-       whichskin = 0;
-       rabbitkickragdoll = 0;
-
-       averageloc = 0;
-       oldaverageloc = 0;
-
-       //Animation tempanimation;
-
-       occluded = 0;
-
-       jumpclimb = 0;
-}
-
-Person::~Person()
-{
-}
-
index cde2f8f7a93b2b16d6e76b346f1296fbb844b597..eed0a27490c1ae82db107f3092e88a463fe31785 100644 (file)
@@ -28,11 +28,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "Quaternions.h"
 #include "Skeleton.h"
 #include "Models.h"
-#include "Constants.h"
 #include "Terrain.h"
-#include "Sprites.h"
+#include "Sprite.h"
 #include <cmath>
 #include "Weapons.h"
+#include "Animation.h"
 
 #define passivetype 0
 #define guardtype 1
@@ -47,21 +47,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #define rabbittype 0
 #define wolftype 1
 
-class HitStruct
+struct Person
 {
-       public:
-               Joint *joint1;
-               Joint *joint2;
-               XYZ hitlocation;
-               bool collision;
-};
-
-class Person
-{
-       public:
-               Person();
-               ~Person();
-
                int whichpatchx;
                int whichpatchz;
                
@@ -331,48 +318,108 @@ class Person
                void DoBloodBig(float howmuch, int which);
                bool DoBloodBigWhere(float howmuch, int which, XYZ where);
                
-               bool wasIdle();
-               bool isIdle();
+               bool wasIdle()
+               {
+                 return animation_bits[currentanimation] & ab_idle;
+               }
+               bool isIdle()
+               {
+                 return animation_bits[targetanimation] & ab_idle;
+               }
                int getIdle();
                
-               bool isSitting();
-               bool isSleeping();
-               
-               
-               bool wasCrouch();
-               bool isCrouch();
+               bool isSitting()
+               {
+                 return animation_bits[targetanimation] & ab_sit;
+               }
+
+               bool isSleeping()
+               {
+                 return animation_bits[targetanimation] & ab_sleep;
+               }
+
+               bool wasCrouch()
+               {
+                 return animation_bits[currentanimation] & ab_crouch;
+               }
+               bool isCrouch()
+               {
+                 return animation_bits[targetanimation] & ab_crouch;
+               }
                int getCrouch();
                
-               bool wasStop();
-               bool isStop();
+               bool wasStop()
+               {
+                 return animation_bits[currentanimation] & ab_stop;
+               }
+               bool isStop()
+               {
+                 return animation_bits[targetanimation] & ab_stop;
+               }
                int getStop();
                
                bool wasSneak();
                bool isSneak();
                int getSneak();
                
-               bool wasRun();
-               bool isRun();
+               bool wasRun()
+               {
+                 return animation_bits[currentanimation] & ab_run;
+               }
+               bool isRun()
+               {
+                 return animation_bits[targetanimation] & ab_run;
+               }
                int getRun();
-               
-               bool wasLanding();
-               bool isLanding();
+
+               bool wasLanding()
+               {
+                 return animation_bits[currentanimation] & ab_land;
+               }
+               bool isLanding()
+               {
+                 return animation_bits[targetanimation] & ab_land;
+               }
                int getLanding();
-               
-               bool wasLandhard();
-               bool isLandhard();
+
+               bool wasLandhard()
+               {
+                 return animation_bits[currentanimation] & ab_landhard;
+               }
+               bool isLandhard()
+               {
+                 return animation_bits[targetanimation] & ab_landhard;
+               }
                int getLandhard();
-               
-               bool isFlip();
-               bool wasFlip();
-               
+
+               bool wasFlip()
+               {
+                 return animation_bits[currentanimation] & ab_flip;
+               }
+               bool isFlip()
+               {
+                 return animation_bits[targetanimation] & ab_flip;
+               }
+
                bool jumpclimb;
-               
-               bool isWallJump();
+
+               bool isWallJump()
+               {
+                 return animation_bits[targetanimation] & ab_walljump;
+               }
                void Reverse();
                void DoDamage(float howmuch);
                void DoHead();
-               void DoMipmaps(int howmanylevels, float startx, float endx, float starty, float endy);
+               void DoMipmaps()
+               {
+                 glBindTexture(GL_TEXTURE_2D, skeleton.drawmodel.textureptr);
+                 gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB,
+                                   skeleton.skinsize,
+                                   skeleton.skinsize,
+                                   GL_RGB, GL_UNSIGNED_BYTE,
+                                   &skeleton.skinText[0]);
+               }
+
                int SphereCheck(XYZ *p1,float radius, XYZ *p, XYZ *move, float *rotate, Model *model);
                int DrawSkeleton();
                void Puff(int whichlabel);
@@ -380,7 +427,8 @@ class Person
                void DoStuff();
                void DoAnimations();
                void RagDoll(bool checkcollision);
-               HitStruct BulletCollideWithPlayer(XYZ start, XYZ end);
 };
 
+const int maxplayers = 10;
+extern Person player[maxplayers];
 #endif
diff --git a/Source/Pointer.h b/Source/Pointer.h
deleted file mode 100644 (file)
index 16bd05b..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-// Pointer.h: interface for the Pointer class.
-//
-//////////////////////////////////////////////////////////////////////
-
-#ifndef _POINTER_H
-#define _POINTER_H
-
-template <class T>
-class Pointer 
-{
-private:
-       void Destroy()
-       {
-               p = NULL;
-               GC::Collect();          
-       }
-
-public:
-    T* p;
-
-    Pointer( T* p_ = NULL ) : p( p_ ) 
-       {
-       }
-
-    ~Pointer() 
-       { 
-               GC::SetTotalBytesAllocated( GC::GetTotalBytesAllocated() - sizeof( *p ) );
-
-               p->~T(); // Explicitely call the destructor
-               
-               Destroy();
-
-       }
-       
-    Pointer& operator = ( Pointer<T>& p_ )
-       {
-               return operator = ( ( T* ) p_);
-       }
-    
-       Pointer& operator = ( T* p_ ) 
-       {     
-               Destroy();
-               p = p_; 
-               return *this;
-    }
-
-    operator T*() 
-       { 
-               return p; 
-       }
-    
-       T& operator*() 
-       { 
-               return *p; 
-       }
-    
-       T* operator->() 
-       { 
-               return p; 
-       }
-    
-// For automatic type conversion during new call
-       operator void**()
-       {
-               return ( void** ) & p;
-       }
-};
-
-
-#endif 
-
diff --git a/Source/Random.c b/Source/Random.c
deleted file mode 100644 (file)
index add3a78..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-
-#include "Random.h"
-#include "stdlib.h"
-
-
-int randSeed = 1;
-
-short Random()
-{
-       /*unsigned int value = (unsigned int)randSeed;
-       unsigned int out=0;
-       int i=31;
-
-       while (i > 0)
-       {
-       value ^= 0x81010000;
-       value ^= out;
-       if (value & 1)
-       {
-       value >>= 1;
-       value |= 0x80000000;
-       }
-       else
-       value >>= 1;
-       out <<= 1;
-       out |= (value&0x1);
-       i--;
-       }
-       if (value&0x80000000)
-       {
-       out <<= 1;
-       out |= 1;
-       }
-       else
-       out <<= 1;
-
-       randSeed += out;
-       */
-       return rand();
-}
index 10f66cb257cac6b91648fb1790e0cea00db34101..3d53ebeb66897a533483922314ec1f908fa38cec 100644 (file)
@@ -22,18 +22,11 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #ifndef _RANDOM_H_
 #define _RANDOM_H_
 
+#include <stdlib.h>
 
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-
-extern int randSeed;
-short Random ();
-
-
-#if defined(__cplusplus)
+static inline short Random()
+{
+    return rand();
 }
-#endif
 
 #endif
index b2c761ddbe312dbe1fabc825ab2d19b100ac8aa4..71b7581bd77ce6683c386e20a582a8100ba79e77 100644 (file)
@@ -1,6 +1,6 @@
 #include "Settings.h"
 #include "Game.h"
-
+#include "Input.h"
 
 void DefaultSettings(Game &game) {
        detail=1;
@@ -28,19 +28,19 @@ void DefaultSettings(Game &game) {
        velocityblur=0;
        volume = 0.8f;
        ambientsound=1;
-       vblsync=0;
+       vblsync=1;
        debugmode=0;
        
-       game.crouchkey=MAC_SHIFT_KEY;
-       game.jumpkey=MAC_SPACE_KEY;
-       game.leftkey=MAC_A_KEY;
-       game.forwardkey=MAC_W_KEY;
-       game.backkey=MAC_S_KEY;
-       game.rightkey=MAC_D_KEY;
-       game.drawkey=MAC_E_KEY;
-       game.throwkey=MAC_Q_KEY;
-       game.attackkey=MAC_MOUSEBUTTON1;
-       game.chatkey=MAC_T_KEY;
+       game.crouchkey=SDLK_LSHIFT;
+       game.jumpkey=SDLK_SPACE;
+       game.leftkey=SDLK_a;
+       game.forwardkey=SDLK_w;
+       game.backkey=SDLK_s;
+       game.rightkey=SDLK_d;
+       game.drawkey=SDLK_e;
+       game.throwkey=SDLK_q;
+       game.attackkey=MOUSEBUTTON1;
+       game.chatkey=SDLK_t;
 }
 
 void SaveSettings(Game &game) {
@@ -99,25 +99,25 @@ void SaveSettings(Game &game) {
        opstream << "\nVolume:\n";
        opstream << volume;
        opstream << "\nForward key:\n";
-       opstream << KeyToChar(game.forwardkey);
+       opstream << Input::keyToChar(game.forwardkey);
        opstream << "\nBack key:\n";
-       opstream << KeyToChar(game.backkey);
+       opstream << Input::keyToChar(game.backkey);
        opstream << "\nLeft key:\n";
-       opstream << KeyToChar(game.leftkey);
+       opstream << Input::keyToChar(game.leftkey);
        opstream << "\nRight key:\n";
-       opstream << KeyToChar(game.rightkey);
+       opstream << Input::keyToChar(game.rightkey);
        opstream << "\nJump key:\n";
-       opstream << KeyToChar(game.jumpkey);
+       opstream << Input::keyToChar(game.jumpkey);
        opstream << "\nCrouch key:\n";
-       opstream << KeyToChar(game.crouchkey);
+       opstream << Input::keyToChar(game.crouchkey);
        opstream << "\nDraw key:\n";
-       opstream << KeyToChar(game.drawkey);
+       opstream << Input::keyToChar(game.drawkey);
        opstream << "\nThrow key:\n";
-       opstream << KeyToChar(game.throwkey);
+       opstream << Input::keyToChar(game.throwkey);
        opstream << "\nAttack key:\n";
-       opstream << KeyToChar(game.attackkey);
+       opstream << Input::keyToChar(game.attackkey);
        opstream << "\nChat key:\n";
-       opstream << KeyToChar(game.chatkey);
+       opstream << Input::keyToChar(game.chatkey);
        opstream << "\nDamage bar:\n";
        opstream << showdamagebar;
        opstream << "\nStereoMode:\n";
@@ -141,6 +141,7 @@ bool LoadSettings(Game &game) {
        printf("Loading config\n");
        while(!ipstream.eof()) {
                ipstream.getline( setting, sizeof(setting) );
+               printf("setting : %s\n",setting);
                
                // skip blank lines
                // assume lines starting with spaces are all blank
@@ -213,35 +214,35 @@ bool LoadSettings(Game &game) {
                } else if ( !strncmp(setting, "Volume", 6) ) {
                        ipstream >> volume;
                } else if ( !strncmp(setting, "Forward key", 11) ) {
-                       ipstream >> string;
-                       game.forwardkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.forwardkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Back key", 8) ) {
-                       ipstream >> string;
-                       game.backkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.backkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Left key", 8) ) {
-                       ipstream >> string;
-                       game.leftkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.leftkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Right key", 9) ) {
-                       ipstream >> string;
-                       game.rightkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.rightkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Jump key", 8) ) {
-                       ipstream >> string;
-                       game.jumpkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.jumpkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Crouch key", 10) ) {
-                       ipstream >> string;
-                       game.crouchkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.crouchkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Draw key", 8) ) {
-                       ipstream >> string;
-                       game.drawkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.drawkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Throw key", 9) ) {
-                       ipstream >> string;
-                       game.throwkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.throwkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Attack key", 10) ) {
-                       ipstream >> string;
-                       game.attackkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.attackkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Chat key", 8) ) {
-                       ipstream >> string;
-                       game.chatkey = CharToKey(string);
+                       ipstream.getline( string, sizeof(string) );
+                       game.chatkey = Input::CharToKey(string);
                } else if ( !strncmp(setting, "Damage bar", 10) ) {
                        ipstream >> showdamagebar;
                } else if ( !strncmp(setting, "StereoMode", 10) ) {
index 9bdd4cea0dcf6ac3bbbb0643395c0d4a272d83a1..5b28f738f4ac8cfcea8429e8fb0d8d5366e27271 100644 (file)
@@ -23,17 +23,14 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "Game.h"
 #include "Skeleton.h"
 #include "openal_wrapper.h"
+#include "Animation.h"
 
 extern float multiplier;
 extern float gravity;
 extern Skeleton testskeleton;
 extern Terrain terrain;
-extern OPENAL_SAMPLE   *samp[100];
-extern int channels[100];
 extern Objects objects;
-extern Sprites sprites;
 extern int environment;
-extern float terraindetail;
 extern float camerashake;
 extern bool freeze;
 extern int detail;
@@ -41,8 +38,6 @@ extern XYZ envsound[30];
 extern float envsoundvol[30];
 extern int numenvsounds;
 extern float envsoundlife[30];
-extern int bonus;
-extern float bonustime;
 extern int tutoriallevel;
 
 extern int whichjointstartarray[26];
@@ -50,13 +45,14 @@ extern int whichjointendarray[26];
 
 extern Game * pgame;
 extern bool visibleloading;
-extern "C"     void PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
 
 void dealloc2(void* param){
        free(param);
        param=0;
 }
 
+enum {boneconnect, constraint, muscle};
+
 void Muscle::DoConstraint(bool spinny)
 {
        static XYZ vel;
@@ -197,8 +193,8 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
        if(free){
                freetime+=multiplier;
 
-               whichpatchx=coords->x/(terrain.size/subdivision*terrain.scale*terraindetail);
-               whichpatchz=coords->z/(terrain.size/subdivision*terrain.scale*terraindetail);
+               whichpatchx=coords->x/(terrain.size/subdivision*terrain.scale);
+               whichpatchz=coords->z/(terrain.size/subdivision*terrain.scale);
 
                terrainlight=*coords;
                objects.SphereCheckPossible(&terrainlight, 1);
@@ -252,136 +248,6 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                        temp=joints[jointlabels[leftknee]].position-(joints[jointlabels[lefthip]].position+joints[jointlabels[leftankle]].position)/2;
                                }
                        }
-                       /*
-                       if(terrain.patchobjectnum[whichpatchx][whichpatchz])
-                       for(m=0;m<terrain.patchobjectnum[whichpatchx][whichpatchz];m++){
-                       k=terrain.patchobjects[whichpatchx][whichpatchz][m];
-                       if(k<objects.numobjects&&k>=0)
-                       if(objects.possible[k]){
-                       temp=joints[jointlabels[head]].position*(*scale)+*coords;
-                       if(objects.model[k].SphereCheck(&temp, 0.06, &start, &objects.position[k], &objects.rotation[k])!=-1){
-                       //temp=(joints[jointlabels[head]].position*(*scale)+*coords)-start;
-                       //Normalise(&temp);
-                       //joints[jointlabels[head]].position=((temp*.2+start)-*coords)/(*scale);
-                       joints[jointlabels[head]].position=(temp-*coords)/(*scale);
-                       }
-                       }
-                       }       */
-
-
-                       //Ears check
-                       /*XYZ startheadpos;
-                       startheadpos=joints[jointlabels[head]].position;
-                       XYZ headpos;
-                       headpos=joints[jointlabels[head]].position+(joints[jointlabels[head]].position-joints[jointlabels[neck]].position);
-                       if(terrain.patchobjectnum[whichpatchx][whichpatchz])
-                       for(m=0;m<terrain.patchobjectnum[whichpatchx][whichpatchz];m++){
-                       k=terrain.patchobjects[whichpatchx][whichpatchz][m];
-                       if(k<objects.numobjects&&k>=0)
-                       if(objects.possible[k]){
-                       friction=objects.friction[k];
-                       start=joints[jointlabels[head]].position*(*scale)+*coords;
-                       end=(headpos)*(*scale)+*coords;
-                       whichhit=objects.model[k].LineCheckPossible(&start,&end,&temp,&objects.position[k],&objects.rotation[k]);
-                       if(whichhit!=-1){
-                       if(joints[jointlabels[head]].label==groin&&!joints[jointlabels[head]].locked&&joints[jointlabels[head]].delay<=0){
-                       joints[jointlabels[head]].locked=1;
-                       joints[jointlabels[head]].delay=1;
-                       static float gLoc[3];
-                       static float vel[3];
-                       gLoc[0]=headpos.x*(*scale)+coords->x;
-                       gLoc[1]=headpos.y*(*scale)+coords->y;
-                       gLoc[2]=headpos.z*(*scale)+coords->z;
-                       vel[0]=joints[jointlabels[head]].velocity.x;
-                       vel[1]=joints[jointlabels[head]].velocity.y;
-                       vel[2]=joints[jointlabels[head]].velocity.z;
-                       PlaySoundEx( landsound1, samp[landsound1], NULL, true);
-                       OPENAL_3D_SetAttributes(channels[landsound1], gLoc, vel);
-                       OPENAL_SetVolume(channels[landsound1], 128);
-                       OPENAL_SetPaused(channels[landsound1], false);
-
-                       breaking=1;
-                       }
-
-                       if(joints[jointlabels[head]].label==head&&!joints[jointlabels[head]].locked&&joints[jointlabels[head]].delay<=0){
-                       joints[jointlabels[head]].locked=1;
-                       joints[jointlabels[head]].delay=1;
-                       static float gLoc[3];
-                       static float vel[3];
-                       gLoc[0]=headpos.x*(*scale)+coords->x;
-                       gLoc[1]=headpos.y*(*scale)+coords->y;
-                       gLoc[2]=headpos.z*(*scale)+coords->z;
-                       vel[0]=joints[jointlabels[head]].velocity.x;
-                       vel[1]=joints[jointlabels[head]].velocity.y;
-                       vel[2]=joints[jointlabels[head]].velocity.z;
-                       PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                       OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                       OPENAL_SetVolume(channels[landsound2], 128);
-                       OPENAL_SetPaused(channels[landsound2], false);
-                       }
-
-                       terrainnormal=DoRotation(objects.model[k].facenormals[whichhit],0,objects.rotation[k],0)*-1;
-                       if(terrainnormal.y>.8)freefall=0;
-                       bounceness=terrainnormal*findLength(&joints[jointlabels[head]].velocity)*(abs(normaldotproduct(joints[jointlabels[head]].velocity,terrainnormal)));
-                       if(findLengthfast(&joints[jointlabels[head]].velocity)>findLengthfast(&joints[jointlabels[head]].oldvelocity)){
-                       bounceness=0;
-                       joints[jointlabels[head]].velocity=joints[jointlabels[head]].oldvelocity;
-                       }
-                       if(findLengthfast(&bounceness)>4000&&breaking){
-                       objects.model[k].MakeDecal(breakdecal,DoRotation(temp-objects.position[k],0,-objects.rotation[k],0),.4,.5,Random()%360);
-                       sprites.MakeSprite(cloudsprite, headpos*(*scale)+*coords,joints[jointlabels[head]].velocity*.06, 1,1,1, 4, .2);
-                       breaking=0;
-                       camerashake+=.6;
-
-                       static float gLoc[3];
-                       static float vel[3];
-                       gLoc[0]=headpos.x*(*scale)+coords->x;
-                       gLoc[1]=headpos.y*(*scale)+coords->y;
-                       gLoc[2]=headpos.z*(*scale)+coords->z;
-                       vel[0]=joints[jointlabels[head]].velocity.x;
-                       vel[1]=joints[jointlabels[head]].velocity.y;
-                       vel[2]=joints[jointlabels[head]].velocity.z;
-                       PlaySoundEx( breaksound2, samp[breaksound2], NULL, true);
-                       OPENAL_3D_SetAttributes(channels[breaksound2], gLoc, vel);
-                       OPENAL_SetVolume(channels[breaksound2], 300);
-                       OPENAL_SetPaused(channels[breaksound2], false);
-
-                       envsound[numenvsounds]=*coords;
-                       envsoundvol[numenvsounds]=64;
-                       envsoundlife[numenvsounds]=.4;
-                       numenvsounds++;
-                       }
-                       if(objects.type[k]==treetrunktype){
-                       objects.rotx[k]+=joints[jointlabels[head]].velocity.x*multiplier*.4;
-                       objects.roty[k]+=joints[jointlabels[head]].velocity.z*multiplier*.4;
-                       objects.rotx[k+1]+=joints[jointlabels[head]].velocity.x*multiplier*.4;
-                       objects.roty[k+1]+=joints[jointlabels[head]].velocity.z*multiplier*.4;
-                       }
-                       if(!joints[jointlabels[head]].locked)damage+=findLengthfast(&bounceness)/2500;
-                       ReflectVector(&joints[jointlabels[head]].velocity,&terrainnormal);
-                       frictionness=abs(normaldotproduct(joints[jointlabels[head]].velocity,terrainnormal));//findLength(&bounceness)/findLength(&joints[jointlabels[head]].velocity);
-                       joints[jointlabels[head]].velocity-=bounceness;
-                       if(1-friction*frictionness>0)joints[jointlabels[head]].velocity*=1-friction*frictionness;
-                       else joints[jointlabels[head]].velocity=0;
-                       if(findLengthfast(&bounceness)>2500){
-                       Normalise(&bounceness);
-                       bounceness=bounceness*50;
-                       }
-                       joints[jointlabels[head]].velocity+=bounceness*elasticity;
-
-
-                       if(!joints[jointlabels[head]].locked)
-                       if(findLengthfast(&joints[jointlabels[head]].velocity)<1){
-                       joints[jointlabels[head]].locked=1;
-                       //joints[jointlabels[head]].velocity*=3;
-                       }
-                       if(findLengthfast(&bounceness)>500)sprites.MakeSprite(cloudsprite, headpos*(*scale)+*coords,joints[jointlabels[head]].velocity*.06, 1,1,1, .5, .2);
-                       joints[jointlabels[head]].position=(temp-*coords)/(*scale)+(startheadpos-headpos)+terrainnormal*.005;
-                       if(longdead>100)broken=1;
-                       }
-                       }
-                       }
-                       */
 
                        for(i=0; i<num_joints; i++){
                                //joints[i].delay-=multiplier/1.5;
@@ -417,19 +283,8 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                if(joints[i].label==groin&&!joints[i].locked&&joints[i].delay<=0){
                                                        joints[i].locked=1;
                                                        joints[i].delay=1;
-                                                       static float gLoc[3];
-                                                       static float vel[3];
-                                                       gLoc[0]=joints[i].position.x*(*scale)+coords->x;
-                                                       gLoc[1]=joints[i].position.y*(*scale)+coords->y;
-                                                       gLoc[2]=joints[i].position.z*(*scale)+coords->z;
-                                                       vel[0]=joints[i].velocity.x;
-                                                       vel[1]=joints[i].velocity.y;
-                                                       vel[2]=joints[i].velocity.z;
                                                        if(tutoriallevel!=1||id==0){
-                                                               PlaySoundEx( landsound1, samp[landsound1], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[landsound1], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[landsound1], 128);
-                                                               OPENAL_SetPaused(channels[landsound1], false);
+                                                               emit_sound_at(landsound1, joints[i].position*(*scale)+*coords, 128.);
                                                        }
                                                        breaking=1;
                                                }
@@ -437,19 +292,8 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                if(joints[i].label==head&&!joints[i].locked&&joints[i].delay<=0){
                                                        joints[i].locked=1;
                                                        joints[i].delay=1;
-                                                       static float gLoc[3];
-                                                       static float vel[3];
-                                                       gLoc[0]=joints[i].position.x*(*scale)+coords->x;
-                                                       gLoc[1]=joints[i].position.y*(*scale)+coords->y;
-                                                       gLoc[2]=joints[i].position.z*(*scale)+coords->z;
-                                                       vel[0]=joints[i].velocity.x;
-                                                       vel[1]=joints[i].velocity.y;
-                                                       vel[2]=joints[i].velocity.z;
                                                        if(tutoriallevel!=1||id==0){
-                                                               PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[landsound2], 128);
-                                                               OPENAL_SetPaused(channels[landsound2], false);
+                                                               emit_sound_at(landsound2, joints[i].position*(*scale)+*coords, 128.);
                                                        }
                                                }
 
@@ -466,23 +310,12 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                if(tutoriallevel!=1||id==0)
                                                        if(findLengthfast(&bounceness)>8000&&breaking){
                                                                objects.model[k].MakeDecal(breakdecal,DoRotation(temp-objects.position[k],0,-objects.rotation[k],0),.4,.5,Random()%360);
-                                                               sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, 4, .2);
-                                                               //sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, 1, .2);
+                                                               Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, 4, .2);
+                                                               //Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, 1, .2);
                                                                breaking=0;
                                                                camerashake+=.6;
 
-                                                               static float gLoc[3];
-                                                               static float vel[3];
-                                                               gLoc[0]=joints[i].position.x*(*scale)+coords->x;
-                                                               gLoc[1]=joints[i].position.y*(*scale)+coords->y;
-                                                               gLoc[2]=joints[i].position.z*(*scale)+coords->z;
-                                                               vel[0]=joints[i].velocity.x;
-                                                               vel[1]=joints[i].velocity.y;
-                                                               vel[2]=joints[i].velocity.z;
-                                                               PlaySoundEx( breaksound2, samp[breaksound2], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[breaksound2], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[breaksound2], 300);
-                                                               OPENAL_SetPaused(channels[breaksound2], false);
+                                                               emit_sound_at(breaksound2, joints[i].position*(*scale)+*coords);
 
                                                                envsound[numenvsounds]=*coords;
                                                                envsoundvol[numenvsounds]=64;
@@ -508,19 +341,19 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
 
                                                        if(environment==snowyenvironment&&findLengthfast(&bounceness)>500&&terrain.getOpacity(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z)<.2){
                                                                terrainlight=terrain.getLighting(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z);
-                                                               sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
+                                                               Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
                                                                if(detail==2)terrain.MakeDecal(bodyprintdecal, joints[i].position*(*scale)+*coords,.4,.4,0);
                                                        }
                                                        else if(environment==desertenvironment&&findLengthfast(&bounceness)>500&&terrain.getOpacity(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z)<.2){
                                                                terrainlight=terrain.getLighting(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z);
-                                                               sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
+                                                               Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
                                                        }
 
                                                        else if(environment==grassyenvironment&&findLengthfast(&bounceness)>500&&terrain.getOpacity(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z)<.2){
                                                                terrainlight=terrain.getLighting(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z);
-                                                               sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
+                                                               Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
                                                        }
-                                                       else if(findLengthfast(&bounceness)>500)sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x,terrainlight.y,terrainlight.z, .5, .2);
+                                                       else if(findLengthfast(&bounceness)>500)Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, terrainlight.x,terrainlight.y,terrainlight.z, .5, .2);
 
 
                                                        joints[i].position.y=(terrain.getHeight(joints[i].position.x*(*scale)+coords->x,joints[i].position.z*(*scale)+coords->z)+groundlevel-coords->y)/(*scale);
@@ -539,19 +372,8 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                                                if(joints[i].label==groin&&!joints[i].locked&&joints[i].delay<=0){
                                                                                        joints[i].locked=1;
                                                                                        joints[i].delay=1;
-                                                                                       static float gLoc[3];
-                                                                                       static float vel[3];
-                                                                                       gLoc[0]=joints[i].position.x*(*scale)+coords->x;
-                                                                                       gLoc[1]=joints[i].position.y*(*scale)+coords->y;
-                                                                                       gLoc[2]=joints[i].position.z*(*scale)+coords->z;
-                                                                                       vel[0]=joints[i].velocity.x;
-                                                                                       vel[1]=joints[i].velocity.y;
-                                                                                       vel[2]=joints[i].velocity.z;
                                                                                        if(tutoriallevel!=1||id==0){
-                                                                                               PlaySoundEx( landsound1, samp[landsound1], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[landsound1], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[landsound1], 128);
-                                                                                               OPENAL_SetPaused(channels[landsound1], false);
+                                                                                               emit_sound_at(landsound1, joints[i].position*(*scale)+*coords, 128.);
                                                                                        }
                                                                                        breaking=1;
                                                                                }
@@ -559,19 +381,8 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                                                if(joints[i].label==head&&!joints[i].locked&&joints[i].delay<=0){
                                                                                        joints[i].locked=1;
                                                                                        joints[i].delay=1;
-                                                                                       static float gLoc[3];
-                                                                                       static float vel[3];
-                                                                                       gLoc[0]=joints[i].position.x*(*scale)+coords->x;
-                                                                                       gLoc[1]=joints[i].position.y*(*scale)+coords->y;
-                                                                                       gLoc[2]=joints[i].position.z*(*scale)+coords->z;
-                                                                                       vel[0]=joints[i].velocity.x;
-                                                                                       vel[1]=joints[i].velocity.y;
-                                                                                       vel[2]=joints[i].velocity.z;
                                                                                        if(tutoriallevel!=1||id==0){
-                                                                                               PlaySoundEx( landsound2, samp[landsound2], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[landsound2], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[landsound2], 128);
-                                                                                               OPENAL_SetPaused(channels[landsound2], false);
+                                                                                               emit_sound_at(landsound2, joints[i].position*(*scale)+*coords, 128.);
                                                                                        }
                                                                                }
 
@@ -585,22 +396,11 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                                                if(tutoriallevel!=1||id==0)
                                                                                        if(findLengthfast(&bounceness)>4000&&breaking){
                                                                                                objects.model[k].MakeDecal(breakdecal,DoRotation(temp-objects.position[k],0,-objects.rotation[k],0),.4,.5,Random()%360);
-                                                                                               sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, 4, .2);
+                                                                                               Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, 4, .2);
                                                                                                breaking=0;
                                                                                                camerashake+=.6;
 
-                                                                                               static float gLoc[3];
-                                                                                               static float vel[3];
-                                                                                               gLoc[0]=joints[i].position.x*(*scale)+coords->x;
-                                                                                               gLoc[1]=joints[i].position.y*(*scale)+coords->y;
-                                                                                               gLoc[2]=joints[i].position.z*(*scale)+coords->z;
-                                                                                               vel[0]=joints[i].velocity.x;
-                                                                                               vel[1]=joints[i].velocity.y;
-                                                                                               vel[2]=joints[i].velocity.z;
-                                                                                               PlaySoundEx( breaksound2, samp[breaksound2], NULL, true);
-                                                                                               OPENAL_3D_SetAttributes(channels[breaksound2], gLoc, vel);
-                                                                                               OPENAL_SetVolume(channels[breaksound2], 300);
-                                                                                               OPENAL_SetPaused(channels[breaksound2], false);
+                                                                                               emit_sound_at(breaksound2, joints[i].position*(*scale)+*coords);
 
                                                                                                envsound[numenvsounds]=*coords;
                                                                                                envsoundvol[numenvsounds]=64;
@@ -624,8 +424,8 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                                                                pos.x+=float(abs(Random()%100)-50)/100*objects.scale[k]*5;
                                                                                                pos.y+=float(abs(Random()%100)-50)/100*objects.scale[k]*15;
                                                                                                pos.z+=float(abs(Random()%100)-50)/100*objects.scale[k]*5;
-                                                                                               sprites.MakeSprite(splintersprite, pos,tempvel*.5, 165/255+float(abs(Random()%100)-50)/400,0,0, .2+float(abs(Random()%100)-50)/1300, 1);
-                                                                                               sprites.special[sprites.numsprites-1]=1;
+                                                                                               Sprite::MakeSprite(splintersprite, pos,tempvel*.5, 165/255+float(abs(Random()%100)-50)/400,0,0, .2+float(abs(Random()%100)-50)/1300, 1);
+                                                                                               Sprite::special[Sprite::numsprites-1]=1;
                                                                                                }*/
                                                                                                objects.rotx[k]+=joints[i].velocity.x*multiplier*.4;
                                                                                                objects.roty[k]+=joints[i].velocity.z*multiplier*.4;
@@ -650,7 +450,7 @@ float Skeleton::DoConstraints(XYZ *coords,float *scale)
                                                                                                        joints[i].locked=1;
                                                                                                        //joints[i].velocity*=3;
                                                                                                }
-                                                                                               if(findLengthfast(&bounceness)>500)sprites.MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, .5, .2);
+                                                                                               if(findLengthfast(&bounceness)>500)Sprite::MakeSprite(cloudsprite, joints[i].position*(*scale)+*coords,joints[i].velocity*.06, 1,1,1, .5, .2);
                                                                                                joints[i].position=(temp-*coords)/(*scale)+terrainnormal*.005;
                                                                                                if(longdead>100)broken=1;
                                                                        }
@@ -913,6 +713,7 @@ void Skeleton::SetJoint(float x, float y, float z, int which, int whichjoint)
 
 void Skeleton::AddMuscle(int attach1,int attach2,float minlength,float maxlength,int type)
 {
+       const int max_muscles = 100; // FIXME: Probably can be dropped
        if(num_muscles<max_muscles-1&&attach1<num_joints&&attach1>=0&&attach2<num_joints&&attach2>=0&&attach1!=attach2){
                muscles[num_muscles].parent1=&joints[attach1];
                muscles[num_muscles].parent2=&joints[attach2];
@@ -1008,17 +809,24 @@ void Skeleton::FindRotationMuscle(int which, int animation)
        if(!isnormal(muscles[which].rotate3))muscles[which].rotate3=0;
 }
 
-void Animation::Load(char *filename, int aheight, int aattack)
+void Animation::Load(const char *filename, int aheight, int aattack)
 {
        static FILE *tfile;
        static int i,j;
        static XYZ startoffset,endoffset;
        static int howmany;
 
+       static const char *anim_prefix = ":Data:Animations:";
+
+
        LOGFUNC;
 
+       int len = strlen(anim_prefix) + strlen(filename);
+       char *buf = new char[len + 1];
+       snprintf(buf, len + 1, "%s%s", anim_prefix, filename);
        // Changing the filename into something the OS can understand
-       char *fixedFN = ConvertFileName(filename);
+       char *fixedFN = ConvertFileName(buf);
+       delete[] buf;
 
        LOG(std::string("Loading animation...") + fixedFN);
 
index 2e5085e6905a0d7c4d11775f8ebf9780d738f6fd..ca8ac30cf241037a5a072f54d7946a16412270cc 100644 (file)
@@ -24,23 +24,23 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "Models.h"
 #include "Quaternions.h"
-#include "Constants.h"
 
 
 /**> HEADER FILES <**/
 #include "gamegl.h"
 #include "Quaternions.h"
 #include "Objects.h"
-#include "Sprites.h"
+#include "Sprite.h"
 #include "binio.h"
 
-#define neutral 0
-#define normalattack 1
-#define reversed 2
-#define reversal 3
-#define lowheight 0
-#define middleheight 1
-#define highheight 2
+enum bodyparts {
+  head, neck,
+  leftshoulder,  leftelbow,  leftwrist,  lefthand,
+  rightshoulder, rightelbow, rightwrist, righthand,
+  abdomen, lefthip, righthip, groin,
+  leftknee,  leftankle,  leftfoot,
+  rightknee, rightankle, rightfoot
+};
 
 class Joint
 {
@@ -142,7 +142,7 @@ public:
 
        Animation & operator = (const Animation & ani);
 
-       void Load(char *fileName, int aheight, int aattack);
+       void Load(const char *fileName, int aheight, int aattack);
        void Move(XYZ how);
 
 protected:
@@ -150,6 +150,8 @@ protected:
 };
 
 
+const int max_joints = 50;
+
 class Skeleton
 {
 public:
index 811029ae92b9757704b579ec04128e0798f637a3..5c4aaab1fb10a8748d2edf769d82cf30560d262f 100644 (file)
@@ -23,234 +23,23 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "Game.h"
 
 extern float viewdistance;
-extern int detail;
-extern bool trilinear;
 extern float blurness;
 extern int environment;
-extern TGAImageRec texture;
 extern bool skyboxtexture;
 extern float skyboxr;
 extern float skyboxg;
 extern float skyboxb;
-extern int tutoriallevel;
 
-bool   SkyBox::load( const char *ffront,const char *fleft,const char *fback,const char *fright,const char *fup,const char *fdown,const char *fcloud,const char *freflect)
+void
+SkyBox::load (const char *ffront, const char *fleft, const char *fback,
+             const char *fright, const char *fup,   const char *fdown)
 {
-/*     static GLuint           type;
-       unsigned char fileNamep[256];
-*/
-       LOGFUNC;
-
-       //front
        Game::LoadTexture(ffront, &front, true, false);
-       //left
-       Game::LoadTexture(fleft, &left, true, false);
-       //back
-       Game::LoadTexture(fback, &back, true, false);
-       //right
+       Game::LoadTexture(fleft,  &left,  true, false);
+       Game::LoadTexture(fback,  &back,  true, false);
        Game::LoadTexture(fright, &right, true, false);
-       //up
-       Game::LoadTexture(fup, &up, true, false);
-       //down
-       Game::LoadTexture(fdown, &down, true, false);
-       //cloud
-       Game::LoadTexture(fcloud, &cloud, true, false);
-       //reflect
-       Game::LoadTexture(freflect, &reflect, true, false);
-/*
-       //front
-       CopyCStringToPascal(ffront,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!front)glGenTextures( 1, &front );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, front);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //left
-       CopyCStringToPascal(fleft,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!left)glGenTextures( 1, &left );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, left);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //back
-       CopyCStringToPascal(fback,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!back)glGenTextures( 1, &back );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, back);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //right
-       CopyCStringToPascal(fright,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!right)glGenTextures( 1, &right );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, right);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //up
-       CopyCStringToPascal(fup,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!up)glGenTextures( 1, &up );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, up);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //down
-       CopyCStringToPascal(fdown,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!down)glGenTextures( 1, &down );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, down);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //cloud
-       CopyCStringToPascal(fcloud,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!cloud)glGenTextures( 1, &cloud );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, cloud);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-
-       //up
-       CopyCStringToPascal(freflect,fileNamep);
-       upload_image( fileNamep ,0); 
-       if(1==1){
-               if ( texture.bpp == 24 )
-                       type = GL_RGB;
-               else
-                       type = GL_RGBA;
-
-               glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );
-
-               if(!reflect)glGenTextures( 1, &reflect );
-               glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
-
-               glBindTexture( GL_TEXTURE_2D, reflect);
-               glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
-               //glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
-               if(trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
-               if(!trilinear)glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
-
-               gluBuild2DMipmaps( GL_TEXTURE_2D, type, texture.sizeX, texture.sizeY, type, GL_UNSIGNED_BYTE, texture.data );
-
-       }
-*/
-       return true;
+       Game::LoadTexture(fup,    &up,    true, false);
+       Game::LoadTexture(fdown,  &down,  true, false);
 }
 
 void   SkyBox::draw()
@@ -263,7 +52,6 @@ void SkyBox::draw()
        M[13]=0;
        M[14]=0;
        glLoadMatrixf(M);
-       //if(environment==2)glTranslatef(0,blurness*viewdistance/1000,0);
        if(environment==2)glScalef(1+blurness/1000,1,1+blurness/1000);
        if(environment!=2)glColor3f(.85*skyboxr,.85*skyboxg,.95*skyboxb);
        else glColor3f(1*skyboxr,.95*skyboxg,.95*skyboxb);
@@ -276,7 +64,6 @@ void SkyBox::draw()
        glDisable(GL_CULL_FACE);
        glEnable(GL_BLEND);
        glDisable(GL_LIGHTING);
-       //              glActiveTextureARB(GL_TEXTURE0_ARB);
        if(skyboxtexture)glEnable(GL_TEXTURE_2D);
        glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
        glBindTexture(GL_TEXTURE_2D, front); 
@@ -309,7 +96,6 @@ void SkyBox::draw()
        glTexCoord2f(1, 0); glVertex3f( size,  size,  size);
        glTexCoord2f(1, 1); glVertex3f( size,  size, -size);
        glEnd();
-       //if(detail!=0){
        glBindTexture(GL_TEXTURE_2D, down);
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
@@ -321,7 +107,6 @@ void        SkyBox::draw()
        glTexCoord2f(1, 1); glVertex3f( size, -size,  size);
        glTexCoord2f(0, 1); glVertex3f(-size, -size,  size);
        glEnd();
-       //}
        glBindTexture(GL_TEXTURE_2D, right);
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
        glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
@@ -342,30 +127,11 @@ void      SkyBox::draw()
        glTexCoord2f(1, 1); glVertex3f(-size,  size,  size);
        glTexCoord2f(0, 1); glVertex3f(-size,  size, -size);
        glEnd();
-       /*
-       glEnable(GL_BLEND);
-       glColor4f(1,1,1,1);
-       glBindTexture(GL_TEXTURE_2D, cloud);
-       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
-       glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 
-       glBegin(GL_QUADS);
-       glNormal3f( 0.0f, -1.0f, 0);
-       glTexCoord2f(0,                                 (1+cloudmove)*30);      glVertex3f(-size,       size/200, -size);
-       glTexCoord2f(0,                                 0);                             glVertex3f(-size,       size/200,  size);
-       glTexCoord2f((1+cloudmove)*30,  0);                             glVertex3f( size,       size/200,  size);
-       glTexCoord2f((1+cloudmove)*30,  (1+cloudmove)*30);      glVertex3f( size,       size/200, -size);
-       glEnd();
-       glDisable(GL_BLEND);*/
        glEnable(GL_CULL_FACE);
        glDepthMask(1);
        glPopMatrix();
 }
 
-SkyBox::SkyBox()
-{
-       front = 0,left = 0,back = 0,right = 0,up = 0,down = 0,cloud = 0,reflect = 0;
-       cloudmove = 0;
-}
 SkyBox::~SkyBox()
 {
        if (front) glDeleteTextures( 1, &front );
@@ -374,7 +140,5 @@ SkyBox::~SkyBox()
        if (right) glDeleteTextures( 1, &right );
        if (up) glDeleteTextures( 1, &up );
        if (down) glDeleteTextures( 1, &down );
-       if (cloud) glDeleteTextures( 1, &cloud );
-       if (reflect) glDeleteTextures( 1, &reflect );
 };
 
index aa9e1f7e76fa35f63bb56dd0b0aab8301451849e..dc602ce216c78d92e7a54daa4a62c37e93575e8b 100644 (file)
@@ -29,13 +29,13 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 class SkyBox{
 public:
-       GLuint                          front,left,back,right,up,down,cloud,reflect;
-       float cloudmove;
+       GLuint front, left, back, right, up, down;
 
-       bool load(const char *ffront,const char *fleft,const char *fback,const char *fright,const char *fup,const char *fdown,const char *fcloud,const char *freflect);
+       void load(const char *ffront, const char *fleft, const char *fback,
+                 const char *fright, const char *fup,   const char *fdown);
        void draw();
 
-       SkyBox();
+       SkyBox(): front(0), left(0), back(0), right(0), up(0), down(0) {}
        ~SkyBox();
 };
 
diff --git a/Source/Sounds.cpp b/Source/Sounds.cpp
new file mode 100644 (file)
index 0000000..c853553
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#include "Quaternions.h"
+#include "Sounds.h"
+#include "openal_wrapper.h"
+
+struct OPENAL_SAMPLE *samp[sounds_count];
+
+int footstepsound, footstepsound2, footstepsound3, footstepsound4;
+
+int channels[100];
+
+static const char *sound_data[sounds_count] = {
+#define DECLARE_SOUND(id, filename) filename,
+#include "Sounds.def"
+#undef DECLARE_SOUND
+};
+
+// FIXME: dimensionality is not a property of the sound sample.
+// This should be decided at the time of playback
+static int snd_mode(int snd)
+{
+  switch (snd)
+    {
+    case alarmsound:
+    case consolefailsound:
+    case consolesuccesssound:
+    case firestartsound:
+    case fireendsound:
+      return OPENAL_2D;
+    default:
+      return OPENAL_HW3D;
+    }
+}
+
+void loadAllSounds()
+{
+  for (int i = 0; i < sounds_count; i++)
+    {
+      char buf[64];
+      snprintf(buf, 64, ":Data:Sounds:%s", sound_data[i]);
+      samp[i] = OPENAL_Sample_Load(OPENAL_FREE,
+                                  ConvertFileName(buf),
+                                  snd_mode(i),
+                                  0, 0);
+    }
+  footstepsound = footstepsn1;
+  footstepsound2 = footstepsn2;
+  footstepsound3 = footstepst1;
+  footstepsound4 = footstepst2;
+  // Huh?
+  // OPENAL_Sample_SetMode(samp[whooshsound], OPENAL_LOOP_NORMAL);
+  for (int i = stream_firesound; i <= stream_music3; i++)
+    OPENAL_Stream_SetMode(samp[i], OPENAL_LOOP_NORMAL);
+}
+
+void
+emit_sound_at(int soundid, const XYZ &pos, float vol)
+{
+  PlaySoundEx (soundid, samp[soundid], NULL, true);
+  OPENAL_3D_SetAttributes_ (channels[soundid], pos, NULL);
+  OPENAL_SetVolume (channels[soundid], vol);
+  OPENAL_SetPaused (channels[soundid], false);
+}
+
+void
+emit_sound_np(int soundid, float vol)
+{
+  PlaySoundEx (soundid, samp[soundid], NULL, true);
+  OPENAL_SetVolume (channels[soundid], vol);
+  OPENAL_SetPaused (channels[soundid], false);
+}
+
+void
+emit_stream_at(int soundid, const XYZ &pos, float vol)
+{
+  PlayStreamEx (soundid, samp[soundid], NULL, true);
+  OPENAL_3D_SetAttributes_ (channels[soundid], pos, NULL);
+  OPENAL_SetVolume (channels[soundid], vol);
+  OPENAL_SetPaused (channels[soundid], false);
+}
+
+void
+emit_stream_np(int soundid, float vol)
+{
+  PlayStreamEx (soundid, samp[soundid], NULL, true);
+  OPENAL_SetVolume (channels[soundid], vol);
+  OPENAL_SetPaused (channels[soundid], false);
+}
+
+void
+resume_stream(int soundid)
+{
+  OPENAL_SetPaused (channels[soundid], false);
+}
+
+void
+pause_sound(int soundid)
+{
+  OPENAL_SetPaused (channels[soundid], true);
+}
+
diff --git a/Source/Sounds.def b/Source/Sounds.def
new file mode 100644 (file)
index 0000000..c85ab84
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+DECLARE_SOUND(footstepsn1, "footstepsnow1.ogg")
+DECLARE_SOUND(footstepsn2, "footstepsnow2.ogg")
+DECLARE_SOUND(footstepst1, "footstepstone1.ogg")
+DECLARE_SOUND(footstepst2, "footstepstone2.ogg")
+DECLARE_SOUND(footstepgr1, "footstepgrass1.ogg")
+DECLARE_SOUND(footstepgr2, "footstepgrass2.ogg")
+DECLARE_SOUND(landsound, "land.ogg")
+DECLARE_SOUND(jumpsound, "jump.ogg")
+DECLARE_SOUND(hawksound, "hawk.ogg")
+DECLARE_SOUND(whooshsound, "whoosh.ogg")
+DECLARE_SOUND(landsound1, "land1.ogg")
+DECLARE_SOUND(landsound2, "land2.ogg")
+DECLARE_SOUND(breaksound, "broken.ogg")
+DECLARE_SOUND(lowwhooshsound, "lowwhoosh.ogg")
+DECLARE_SOUND(midwhooshsound, "midwhoosh.ogg")
+DECLARE_SOUND(highwhooshsound, "highwhoosh.ogg")
+DECLARE_SOUND(movewhooshsound, "movewhoosh.ogg")
+DECLARE_SOUND(heavyimpactsound, "heavyimpact.ogg")
+DECLARE_SOUND(whooshhitsound, "whooshhit.ogg")
+DECLARE_SOUND(thudsound, "thud.ogg")
+DECLARE_SOUND(alarmsound, "alarm.ogg")
+DECLARE_SOUND(breaksound2, "break.ogg")
+DECLARE_SOUND(knifedrawsound, "knifedraw.ogg")
+DECLARE_SOUND(knifesheathesound, "knifesheathe.ogg")
+DECLARE_SOUND(fleshstabsound, "fleshstab.ogg")
+DECLARE_SOUND(fleshstabremovesound, "fleshstabremove.ogg")
+DECLARE_SOUND(knifeswishsound, "knifeswish.ogg")
+DECLARE_SOUND(knifeslicesound, "knifeslice.ogg")
+DECLARE_SOUND(swordslicesound, "swordslice.ogg")
+DECLARE_SOUND(skidsound, "skid.ogg")
+DECLARE_SOUND(snowskidsound, "snowskid.ogg")
+DECLARE_SOUND(bushrustle, "bushrustle.ogg")
+DECLARE_SOUND(clank1sound, "clank1.ogg")
+DECLARE_SOUND(clank2sound, "clank2.ogg")
+DECLARE_SOUND(clank3sound, "clank3.ogg")
+DECLARE_SOUND(clank4sound, "clank4.ogg")
+DECLARE_SOUND(consolesuccesssound, "consolesuccess.ogg")
+DECLARE_SOUND(consolefailsound, "consolefail.ogg")
+DECLARE_SOUND(metalhitsound, "metalhit.ogg")
+DECLARE_SOUND(clawslicesound, "clawslice.ogg")
+DECLARE_SOUND(splattersound, "splatter.ogg")
+DECLARE_SOUND(growlsound, "growl.ogg")
+DECLARE_SOUND(growl2sound, "growl2.ogg")
+DECLARE_SOUND(barksound, "bark.ogg")
+DECLARE_SOUND(bark2sound, "bark2.ogg")
+DECLARE_SOUND(bark3sound, "bark3.ogg")
+DECLARE_SOUND(snarlsound, "snarl.ogg")
+DECLARE_SOUND(snarl2sound, "snarl2.ogg")
+DECLARE_SOUND(barkgrowlsound, "barkgrowl.ogg")
+DECLARE_SOUND(rabbitattacksound, "rabbitattack.ogg")
+DECLARE_SOUND(rabbitattack2sound, "rabbitattack2.ogg")
+DECLARE_SOUND(rabbitattack3sound, "rabbitattack3.ogg")
+DECLARE_SOUND(rabbitattack4sound, "rabbitattack4.ogg")
+DECLARE_SOUND(rabbitpainsound, "rabbitpain.ogg")
+DECLARE_SOUND(rabbitpain1sound, "rabbitpain2.ogg")
+DECLARE_SOUND(rabbitchitter, "rabbitchitter.ogg")
+DECLARE_SOUND(rabbitchitter2, "rabbitchitter2.ogg")
+DECLARE_SOUND(swordstaffsound, "swordstaff.ogg")
+DECLARE_SOUND(staffbodysound, "staffbody.ogg")
+DECLARE_SOUND(staffheadsound, "staffhead.ogg")
+DECLARE_SOUND(staffbreaksound, "staffbreak.ogg")
+DECLARE_SOUND(firestartsound, "firestart.ogg")
+DECLARE_SOUND(fireendsound, "fireend.ogg")
+DECLARE_SOUND(stream_firesound, "fire.ogg")
+DECLARE_SOUND(stream_music1grass, "music1grass.ogg")
+DECLARE_SOUND(stream_music1snow, "music1snow.ogg")
+DECLARE_SOUND(stream_music1desert, "music1desert.ogg")
+DECLARE_SOUND(stream_wind, "wind.ogg")
+DECLARE_SOUND(stream_desertambient, "desertambient.ogg")
+DECLARE_SOUND(stream_music2, "music2.ogg")
+DECLARE_SOUND(stream_music3, "music3.ogg")
diff --git a/Source/Sounds.h b/Source/Sounds.h
new file mode 100644 (file)
index 0000000..20cd2b0
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+Copyright (C) 2010 - Lugaru authors
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifndef SOUNDS_H
+#define SOUNDS_H
+
+enum sound_types {
+#define DECLARE_SOUND(id, filename) id,
+#include "Sounds.def"
+#undef DECLARE_SOUND
+sounds_count
+};
+
+extern struct OPENAL_SAMPLE *samp[sounds_count];
+extern int channels[];
+
+extern void loadAllSounds();
+
+extern void emit_sound_at(int soundid, const XYZ &pos = XYZ(), float vol = 256.f);
+extern void emit_sound_np(int soundid, float vol = 256.f);
+extern void emit_stream_at(int soundid, const XYZ &pos = XYZ(), float vol = 256.f);
+extern void emit_stream_np(int soundid, float vol = 256.f);
+extern void resume_stream(int soundid);
+extern void pause_sound(int soundid);
+
+extern int footstepsound, footstepsound2, footstepsound3, footstepsound4;
+#endif
diff --git a/Source/Sprite.cpp b/Source/Sprite.cpp
new file mode 100644 (file)
index 0000000..0998e09
--- /dev/null
@@ -0,0 +1,453 @@
+/*
+Copyright (C) 2003, 2010 - Wolfire Games
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#include "Sprite.h"
+#include "Person.h"
+#include "Game.h"
+extern XYZ viewer;
+extern float viewdistance;
+extern float fadestart;
+extern int environment;
+extern float texscale;
+extern Light light;
+extern float multiplier;
+extern float gravity;
+extern Terrain terrain;
+extern Objects objects;
+extern int detail;
+extern XYZ viewerfacing;
+extern int bloodtoggle;
+extern XYZ windvector;
+
+// init statics
+GLuint Sprite::cloudtexture = 0;
+GLuint Sprite::cloudimpacttexture = 0;
+GLuint Sprite::bloodtexture = 0;
+GLuint Sprite::flametexture = 0;
+GLuint Sprite::bloodflametexture = 0;
+GLuint Sprite::smoketexture = 0;
+GLuint Sprite::snowflaketexture = 0;
+GLuint Sprite::shinetexture = 0;
+GLuint Sprite::splintertexture = 0;
+GLuint Sprite::leaftexture = 0;
+GLuint Sprite::toothtexture = 0;
+
+float Sprite::checkdelay = 0;
+
+vector<Sprite*> Sprite::sprites = vector<Sprite*>();
+
+//Functions
+void Sprite::Draw()
+{
+       int i,j,k;
+       static float M[16];
+       static XYZ point;
+       static float distancemult;
+       static int lasttype;
+       static int lastspecial;
+       static int whichpatchx,whichpatchz;
+       static XYZ start,end,colpoint;
+       static bool check;
+       static bool blend;
+       static float tempmult;
+       static XYZ difference;
+       static float lightcolor[3];
+       static float viewdistsquared=viewdistance*viewdistance;
+       static XYZ tempviewer;
+
+       tempviewer=viewer+viewerfacing*6;
+       check=0;
+
+       lightcolor[0]=light.color[0]*.5+light.ambient[0];
+       lightcolor[1]=light.color[1]*.5+light.ambient[1];
+       lightcolor[2]=light.color[2]*.5+light.ambient[2];
+
+       checkdelay-=multiplier*10;
+
+       if(checkdelay<=0){
+               check=1;
+               checkdelay=1;
+       }
+
+       lasttype=-1;
+       lastspecial=-1;
+       glEnable(GL_BLEND);
+       glDisable(GL_LIGHTING);
+       glDisable(GL_CULL_FACE);
+       glEnable(GL_TEXTURE_2D);
+       blend = 1;
+       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+       glDepthMask(0);
+       glAlphaFunc(GL_GREATER, 0.0001);
+       for(i=0;i<sprites.size();i++){
+               if(lasttype!=sprites[i]->type) {
+                       switch(sprites[i]->type) {
+                               case cloudsprite:
+                                       glBindTexture( GL_TEXTURE_2D, cloudtexture);
+                                       if(!blend){
+                                               blend=1;
+                                               glAlphaFunc(GL_GREATER, 0.0001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                       }
+                               break;
+                               case cloudimpactsprite:
+                                       glBindTexture( GL_TEXTURE_2D, cloudimpacttexture);
+                                       if(!blend){
+                                               blend=1;
+                                               glAlphaFunc(GL_GREATER, 0.0001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                       }
+                               break;
+                               case breathsprite:
+                                       glBindTexture( GL_TEXTURE_2D, cloudimpacttexture);
+                                       if(!blend){
+                                               blend=1;
+                                               glAlphaFunc(GL_GREATER, 0.0001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                       }
+                               break;
+                               case smoketype:
+                                       glBindTexture( GL_TEXTURE_2D, smoketexture);
+                                       if(!blend){
+                                               blend=1;
+                                               glAlphaFunc(GL_GREATER, 0.0001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                       }
+                               break;
+                               case bloodsprite:
+                                       glBindTexture( GL_TEXTURE_2D, bloodtexture);
+                                       if(!blend){
+                                               blend=1;
+                                               glAlphaFunc(GL_GREATER, 0.0001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                       }
+                               break;
+                               case splintersprite :
+                                       if(lastspecial!=sprites[i]->special) {
+                                               if(sprites[i]->special==0)glBindTexture( GL_TEXTURE_2D, splintertexture);
+                                               if(sprites[i]->special==1)glBindTexture( GL_TEXTURE_2D, leaftexture);
+                                               if(sprites[i]->special==2)glBindTexture( GL_TEXTURE_2D, snowflaketexture);
+                                               if(sprites[i]->special==3)glBindTexture( GL_TEXTURE_2D, toothtexture);
+                                               if(!blend){
+                                                       blend=1;
+                                                       glAlphaFunc(GL_GREATER, 0.0001);
+                                                       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                               }
+                                       }
+                               break;
+                               case snowsprite:
+                                       glBindTexture( GL_TEXTURE_2D, snowflaketexture);
+                                       if(!blend){
+                                               blend=1;
+                                               glAlphaFunc(GL_GREATER, 0.0001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+                                       }
+                               break;
+                               case weaponshinesprite:
+                                       glBindTexture( GL_TEXTURE_2D, shinetexture);
+                                       if(blend){
+                                               blend=0;
+                                               glAlphaFunc(GL_GREATER, 0.001);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+                                       }
+                               break;
+                               case flamesprite:
+                               case weaponflamesprite:
+                                       glBindTexture( GL_TEXTURE_2D, flametexture);
+                                       if(blend||lasttype==bloodflamesprite){
+                                               blend=0;
+                                               glAlphaFunc(GL_GREATER, 0.3);
+                                               glBlendFunc(GL_SRC_ALPHA,GL_ONE);
+                                       }
+                               break;
+                               case bloodflamesprite:
+                                       glBindTexture( GL_TEXTURE_2D, bloodflametexture);
+                                       if(blend){
+                                               blend=0;
+                                               glAlphaFunc(GL_GREATER, 0.3);
+                                               glBlendFunc(GL_ONE,GL_ZERO);
+                                       }
+                               break;
+                       }
+               }
+               if(sprites[i]->type==snowsprite)
+                       distancemult=(144-(findDistancefast(&tempviewer,&sprites[i]->position)-(144*fadestart))*(1/(1-fadestart)))/144;
+               else
+                       distancemult=(viewdistsquared-(findDistancefast(&viewer,&sprites[i]->position)-(viewdistsquared*fadestart))*(1/(1-fadestart)))/viewdistsquared;
+               if(sprites[i]->type==flamesprite){
+                       if(distancemult>=1) glColor4f(sprites[i]->color[0],sprites[i]->color[1],sprites[i]->color[2],sprites[i]->opacity);
+                       else glColor4f(sprites[i]->color[0],sprites[i]->color[1],sprites[i]->color[2],sprites[i]->opacity*distancemult);
+               } else {
+                       if(distancemult>=1) glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],sprites[i]->opacity);
+                       else glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],sprites[i]->opacity*distancemult);
+               }
+               lasttype=sprites[i]->type;
+               lastspecial=sprites[i]->special;
+               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
+               glPushMatrix();
+                       glTranslatef(sprites[i]->position.x,sprites[i]->position.y,sprites[i]->position.z);
+                       if((sprites[i]->type==flamesprite||sprites[i]->type==weaponflamesprite||sprites[i]->type==weaponshinesprite)){
+                               difference=viewer-sprites[i]->position;
+                               Normalise(&difference);
+                               glTranslatef(difference.x*sprites[i]->size/4, difference.y*sprites[i]->size/4, difference.z*sprites[i]->size/4);
+                       }
+                       if(sprites[i]->type==snowsprite){
+                               glRotatef(sprites[i]->rotation*.2,0,.3,1);
+                               glTranslatef(1,0,0);
+                       }
+                       glGetFloatv(GL_MODELVIEW_MATRIX,M);
+                       point.x=M[12];
+                       point.y=M[13];
+                       point.z=M[14];
+                       glLoadIdentity();
+                       glTranslatef(point.x, point.y, point.z);
+
+                       glRotatef(sprites[i]->rotation,0,0,1);
+
+                       if((sprites[i]->type==flamesprite||sprites[i]->type==weaponflamesprite||sprites[i]->type==weaponshinesprite||sprites[i]->type==bloodflamesprite)){
+                               if(sprites[i]->alivetime<.14)glScalef(sprites[i]->alivetime/.14,sprites[i]->alivetime/.14,sprites[i]->alivetime/.14);
+                       }
+                       if(sprites[i]->type==smoketype||sprites[i]->type==snowsprite||sprites[i]->type==weaponshinesprite||sprites[i]->type==breathsprite){
+                               if(sprites[i]->alivetime<.3){
+                                       if(distancemult>=1)glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],sprites[i]->opacity*sprites[i]->alivetime/.3);
+                                       if(distancemult<1)glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],sprites[i]->opacity*distancemult*sprites[i]->alivetime/.3);
+                               }
+                       }
+                       if(sprites[i]->type==splintersprite&&sprites[i]->special>0&&sprites[i]->special!=3){
+                               if(sprites[i]->alivetime<.2){
+                                       if(distancemult>=1) glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],sprites[i]->alivetime/.2);
+                                       else glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],distancemult*sprites[i]->alivetime/.2);
+                               }
+                               else {
+                                       if(distancemult>=1) glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],1);
+                                       else glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],1);
+                               }
+                       }
+                       if(sprites[i]->type==splintersprite&&(sprites[i]->special==0||sprites[i]->special==3)){
+                               if(distancemult>=1) glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],1);
+                               else glColor4f(sprites[i]->color[0]*lightcolor[0],sprites[i]->color[1]*lightcolor[1],sprites[i]->color[2]*lightcolor[2],1);
+                       }
+
+                       glBegin(GL_TRIANGLES);
+                       glTexCoord2f(1.0f, 1.0f); glVertex3f( .5*sprites[i]->size, .5*sprites[i]->size, 0.0f);
+                       glTexCoord2f(0.0f, 1.0f); glVertex3f(-.5*sprites[i]->size, .5*sprites[i]->size, 0.0f);
+                       glTexCoord2f(1.0f, 0.0f); glVertex3f( .5*sprites[i]->size,-.5*sprites[i]->size, 0.0f);
+                       glTexCoord2f(0.0f, 0.0f); glVertex3f(-.5*sprites[i]->size,-.5*sprites[i]->size, 0.0f);
+                       glTexCoord2f(1.0f, 0.0f); glVertex3f( .5*sprites[i]->size, -.5*sprites[i]->size, 0.0f);
+                       glTexCoord2f(0.0f, 1.0f); glVertex3f(-.5*sprites[i]->size, .5*sprites[i]->size, 0.0f);
+                       glEnd();
+               glPopMatrix();
+       }
+       tempmult=multiplier;
+       for(i=sprites.size()-1;i>=0;i--){
+               multiplier=tempmult;
+               if(sprites[i]->type!=snowsprite) {
+                       sprites[i]->position+=sprites[i]->velocity*multiplier;
+                       sprites[i]->velocity+=windvector*multiplier;
+               }
+               if(sprites[i]->type==flamesprite||sprites[i]->type==smoketype)sprites[i]->position+=windvector*multiplier/2;
+               if((sprites[i]->type==flamesprite||sprites[i]->type==weaponflamesprite||sprites[i]->type==weaponshinesprite||sprites[i]->type==bloodflamesprite))
+                       multiplier*=sprites[i]->speed*.7;
+               sprites[i]->alivetime+=multiplier;
+
+               if(sprites[i]->type==cloudsprite||sprites[i]->type==cloudimpactsprite){
+                       sprites[i]->opacity-=multiplier/2;
+                       sprites[i]->size+=multiplier/2;
+                       sprites[i]->velocity.y+=gravity*multiplier*.25;
+               }
+               if(sprites[i]->type==breathsprite){
+                       sprites[i]->opacity-=multiplier/2;
+                       sprites[i]->size+=multiplier/2;
+                       if(findLength(&sprites[i]->velocity)<=multiplier)sprites[i]->velocity=0;
+                       else{
+                               XYZ slowdown;
+                               slowdown=sprites[i]->velocity*-1;
+                               Normalise(&slowdown);
+                               slowdown*=multiplier;
+                               sprites[i]->velocity+=slowdown;
+                       }
+               }
+               if(sprites[i]->type==snowsprite){
+                       sprites[i]->size-=multiplier/120;
+                       sprites[i]->rotation+=multiplier*360;
+                       sprites[i]->position.y-=multiplier;
+                       sprites[i]->position+=windvector*multiplier;
+                       if(sprites[i]->position.y<tempviewer.y-6)sprites[i]->position.y+=12;
+                       if(sprites[i]->position.y>tempviewer.y+6)sprites[i]->position.y-=12;
+                       if(sprites[i]->position.z<tempviewer.z-6)sprites[i]->position.z+=12;
+                       if(sprites[i]->position.z>tempviewer.z+6)sprites[i]->position.z-=12;
+                       if(sprites[i]->position.x<tempviewer.x-6)sprites[i]->position.x+=12;
+                       if(sprites[i]->position.x>tempviewer.x+6)sprites[i]->position.x-=12;
+               }
+               if(sprites[i]->type==bloodsprite){
+                       bool spritehit=0;
+                       sprites[i]->rotation+=multiplier*100;
+                       sprites[i]->velocity.y+=gravity*multiplier;
+                       if(check){
+                               XYZ where,startpoint,endpoint,movepoint,footpoint;
+                               float rotationpoint;
+                               int whichtri;
+
+                               for(j=0;j<numplayers;j++){
+                                       if(!spritehit&&player[j].dead&&sprites[i]->alivetime>.1){
+                                               where=sprites[i]->oldposition;
+                                               where-=player[j].coords;
+                                               if(!player[j].skeleton.free)where=DoRotation(where,0,-player[j].rotation,0);
+                                               startpoint=where;
+                                               where=sprites[i]->position;
+                                               where-=player[j].coords;
+                                               if(!player[j].skeleton.free)where=DoRotation(where,0,-player[j].rotation,0);
+                                               endpoint=where;
+
+                                               movepoint=0;
+                                               rotationpoint=0;
+                                               whichtri=player[j].skeleton.drawmodel.LineCheck(&startpoint,&endpoint, &footpoint, &movepoint, &rotationpoint);
+                                               if(whichtri!=-1){
+                                                       spritehit=1;
+                                                       player[j].DoBloodBigWhere(0,160,sprites[i]->oldposition);
+                                                       DeleteSprite(i);
+                                               }
+                                       }
+                               }
+
+                               whichpatchx=sprites[i]->position.x/(terrain.size/subdivision*terrain.scale);
+                               whichpatchz=sprites[i]->position.z/(terrain.size/subdivision*terrain.scale);
+                               if(whichpatchx>0&&whichpatchz>0&&whichpatchx<subdivision&&whichpatchz<subdivision)
+                                       if(terrain.patchobjectnum[whichpatchx][whichpatchz]){
+                                               if(!spritehit)
+                                                       for(j=0;j<terrain.patchobjectnum[whichpatchx][whichpatchz];j++){
+                                                               k=terrain.patchobjects[whichpatchx][whichpatchz][j];
+                                                               start=sprites[i]->oldposition;
+                                                               end=sprites[i]->position;
+                                                               if(!spritehit)
+                                                                       if(objects.model[k].LineCheck(&start,&end,&colpoint,&objects.position[k],&objects.rotation[k])!=-1){
+                                                                               if(detail==2||(detail==1&&abs(Random()%4)==0)||(detail==0&&abs(Random()%8)==0))objects.model[k].MakeDecal(blooddecalfast,DoRotation(colpoint-objects.position[k],0,-objects.rotation[k],0),sprites[i]->size*1.6/*+abs((float)(Random()%100))/2400*/,.5,Random()%360);
+                                                                               DeleteSprite(i);
+                                                                               spritehit=1;
+                                                                       }       
+                                                       }
+                                       }
+                                       if(!spritehit)
+                                               if(sprites[i]->position.y<terrain.getHeight(sprites[i]->position.x,sprites[i]->position.z)){
+                                                       terrain.MakeDecal(blooddecalfast,sprites[i]->position,sprites[i]->size*1.6/*+abs((float)(Random()%100))/2400*/,.6,Random()%360);
+                                                       DeleteSprite(i);
+                                               }
+                       }
+               }
+               if(sprites[i]->type==splintersprite){
+                       sprites[i]->rotation+=sprites[i]->rotatespeed*multiplier;
+                       sprites[i]->opacity-=multiplier/2;
+                       if(sprites[i]->special==0||sprites[i]->special==2||sprites[i]->special==3)sprites[i]->velocity.y+=gravity*multiplier;
+                       if(sprites[i]->special==1)sprites[i]->velocity.y+=gravity*multiplier*.5;
+               }
+               if(sprites[i]->type==flamesprite||sprites[i]->type==weaponflamesprite||sprites[i]->type==weaponshinesprite||sprites[i]->type==bloodflamesprite){
+                       sprites[i]->rotation+=multiplier*sprites[i]->rotatespeed;
+                       sprites[i]->opacity-=multiplier*5/4;
+                       if(sprites[i]->type!=weaponshinesprite&&sprites[i]->type!=bloodflamesprite)
+                               if(sprites[i]->opacity<.5&&sprites[i]->opacity+multiplier*5/4>=.5&&(abs(Random()%4)==0||(sprites[i]->initialsize>2&&Random()%2==0)))
+                                       MakeSprite(smoketype, sprites[i]->position,sprites[i]->velocity, .9,.9,.6, sprites[i]->size*1.2, .4);
+                       if(sprites[i]->alivetime>.14&&(sprites[i]->type==flamesprite)){
+                               sprites[i]->velocity=0;
+                               sprites[i]->velocity.y=1.5;
+                       }
+               }
+               if(sprites[i]->type==smoketype){
+                       sprites[i]->opacity-=multiplier/3/sprites[i]->initialsize;
+                       sprites[i]->color[0]-=multiplier;
+                       sprites[i]->color[1]-=multiplier;
+                       sprites[i]->color[2]-=multiplier;
+                       if(sprites[i]->color[0]<.6)sprites[i]->color[0]=.6;
+                       if(sprites[i]->color[1]<.6)sprites[i]->color[1]=.6;
+                       if(sprites[i]->color[2]<.6)sprites[i]->color[2]=.6;
+                       sprites[i]->size+=multiplier;
+                       sprites[i]->velocity=0;
+                       sprites[i]->velocity.y=1.5;
+                       sprites[i]->rotation+=multiplier*sprites[i]->rotatespeed/5;
+               }
+               if(sprites[i]->opacity<=0||sprites[i]->size<=0)DeleteSprite(i);
+       }
+       if(check)
+               for(i=sprites.size()-1;i>=0;i--){
+                       sprites[i]->oldposition=sprites[i]->position;
+               }
+               glAlphaFunc(GL_GREATER, 0.0001);
+               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
+}
+
+void Sprite::DeleteSprite(int i)
+{
+       sprites.erase(sprites.begin()+i);
+}
+
+void Sprite::MakeSprite(int atype, XYZ where, XYZ avelocity, float red, float green, float blue, float asize, float aopacity){
+       if(sprites.size()<max_sprites-1){
+               sprites.push_back(new Sprite());
+               if((atype!=bloodsprite&&atype!=bloodflamesprite)||bloodtoggle){
+                       sprites.back()->special=0;
+                       sprites.back()->type=atype;
+                       sprites.back()->position=where;
+                       sprites.back()->oldposition=where;
+                       sprites.back()->velocity=avelocity;
+                       sprites.back()->alivetime=0;
+                       sprites.back()->opacity=aopacity;
+                       sprites.back()->size=asize;
+                       sprites.back()->initialsize=asize;
+                       sprites.back()->color[0]=red;
+                       sprites.back()->color[1]=green;
+                       sprites.back()->color[2]=blue;
+                       sprites.back()->rotatespeed=abs(Random()%720)-360;
+                       sprites.back()->speed=float(abs(Random()%100))/200+1.5;
+               }               
+       }
+}
+
+Sprite::Sprite()
+{
+       oldposition = 0;
+       position = 0;
+       velocity = 0;
+       size = 0;
+       initialsize = 0;
+       type = 0;
+       special = 0;
+       memset(color,0,sizeof(color));
+       opacity = 0;
+       rotation = 0;
+       alivetime = 0;
+       speed = 0;
+       rotatespeed = 0;        
+}
+
+void Sprite::clearTextures()
+{
+       if (toothtexture) glDeleteTextures( 1, &toothtexture );
+       if (cloudtexture) glDeleteTextures( 1, &cloudtexture );
+       if (cloudimpacttexture) glDeleteTextures( 1, &cloudimpacttexture );
+       if (bloodtexture) glDeleteTextures( 1, &bloodtexture );
+       if (flametexture) glDeleteTextures( 1, &flametexture );
+       if (bloodflametexture) glDeleteTextures( 1, &bloodflametexture );
+       if (smoketexture) glDeleteTextures( 1, &smoketexture );
+       if (snowflaketexture) glDeleteTextures( 1, &snowflaketexture );
+       if (shinetexture) glDeleteTextures( 1, &shinetexture );
+       if (splintertexture) glDeleteTextures( 1, &splintertexture );
+       if (leaftexture) glDeleteTextures( 1, &leaftexture );
+}
+
diff --git a/Source/Sprite.h b/Source/Sprite.h
new file mode 100644 (file)
index 0000000..7f25a84
--- /dev/null
@@ -0,0 +1,110 @@
+/*
+Copyright (C) 2003, 2010 - Wolfire Games
+
+This file is part of Lugaru.
+
+Lugaru is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
+
+See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+*/
+
+#ifndef _SPRITE_H_
+#define _SPRITE_H_
+
+#include "Quaternions.h"
+#include "gamegl.h"
+#include "TGALoader.h"
+#include "Quaternions.h"
+#include "Frustum.h"
+#include "Lights.h"
+#include "Terrain.h"
+#include "Objects.h"
+
+#include <vector>
+
+#define max_sprites 20000
+
+enum {
+       cloudsprite = 0,
+       bloodsprite,
+       flamesprite,
+       smoketype,
+       weaponflamesprite,
+       cloudimpactsprite,
+       snowsprite,
+       weaponshinesprite,
+       bloodflamesprite,
+       breathsprite,
+       splintersprite,
+       spritenumber
+};
+
+class Sprite{
+       private:
+               XYZ oldposition;
+               XYZ position;
+               XYZ velocity;
+               float size;
+               float initialsize;
+               int type;
+               int special;
+               float color[3];
+               float opacity;
+               float rotation;
+               float alivetime;
+               float speed;
+               float rotatespeed;
+               
+               static float checkdelay;
+       
+               static vector<Sprite*> sprites;
+       
+       public:
+               static void DeleteSprite(int which);
+               static void MakeSprite(int atype, XYZ where, XYZ avelocity, float red, float green, float blue, float asize, float aopacity);
+               static void Draw();
+               static void deleteSprites() {
+                       sprites.clear();
+               }
+               static void setLastSpriteSpecial(int s) {
+                       sprites.back()->special = s;
+               }
+               static void setLastSpriteSpeed(int s) {
+                       sprites.back()->speed = s;
+               }
+               static void setLastSpriteAlivetime(float al) {
+                       sprites.back()->alivetime = al;
+               }
+               static void clearTextures();
+               
+               static GLuint cloudtexture;
+               static GLuint bloodtexture;
+               static GLuint flametexture;
+               static GLuint smoketexture;
+               
+               static GLuint cloudimpacttexture;
+               static GLuint snowflaketexture;
+               static GLuint shinetexture;
+               static GLuint bloodflametexture;
+               
+               static GLuint splintertexture;
+               
+               static GLuint leaftexture;
+               static GLuint toothtexture;
+
+               Sprite();
+               ~Sprite();
+};
+
+#endif
diff --git a/Source/Sprites.cpp b/Source/Sprites.cpp
deleted file mode 100644 (file)
index c80d5e7..0000000
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#include "Sprites.h"
-#include "Person.h"
-extern XYZ viewer;
-extern float viewdistance;
-extern float fadestart;
-extern int environment;
-extern float texscale;
-extern Light light;
-extern float multiplier;
-extern float gravity;
-extern Terrain terrain;
-extern Objects objects;
-extern int detail;
-extern XYZ viewerfacing;
-extern float terraindetail;
-extern int bloodtoggle;
-extern XYZ windvector;
-extern int numplayers;
-extern Person player[maxplayers];
-//Functions
-
-void Sprites::Draw()
-{
-       static int i,j,k;
-       static float M[16];
-       static XYZ point;
-       static float distancemult;
-       static int lasttype;
-       static int lastspecial;
-       static int whichpatchx,whichpatchz;
-       static XYZ start,end,colpoint;
-       static bool check;
-       static bool blend;
-       static float tempmult;
-       static XYZ difference;
-       static float lightcolor[3];
-       static float viewdistsquared=viewdistance*viewdistance;
-       static XYZ tempviewer;
-
-       tempviewer=viewer+viewerfacing*6;
-       check=0;
-
-       lightcolor[0]=light.color[0]*.5+light.ambient[0];
-       lightcolor[1]=light.color[1]*.5+light.ambient[1];
-       lightcolor[2]=light.color[2]*.5+light.ambient[2];
-
-       checkdelay-=multiplier*10;
-
-       if(checkdelay<=0){
-               check=1;
-               checkdelay=1;
-       }
-
-       lasttype=-1;
-       lastspecial=-1;
-       glEnable(GL_BLEND);
-       glDisable(GL_LIGHTING);
-       glDisable(GL_CULL_FACE);
-       glEnable(GL_TEXTURE_2D);
-       blend = 1;
-       glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-       glDepthMask(0);
-       glAlphaFunc(GL_GREATER, 0.0001);
-       for(i=0;i<numsprites;i++){
-               if(type[i]==cloudsprite&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, cloudtexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==cloudimpactsprite&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, cloudimpacttexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==breathsprite&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, cloudimpacttexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==smoketype&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, smoketexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==bloodsprite&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, bloodtexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==splintersprite&&(lasttype!=type[i]||lastspecial!=special[i])){
-                       if(special[i]==0)glBindTexture( GL_TEXTURE_2D, splintertexture);
-                       if(special[i]==1)glBindTexture( GL_TEXTURE_2D, leaftexture);
-                       if(special[i]==2)glBindTexture( GL_TEXTURE_2D, snowflaketexture);
-                       if(special[i]==3)glBindTexture( GL_TEXTURE_2D, toothtexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==snowsprite&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, snowflaketexture);
-                       if(!blend){
-                               blend=1;
-                               glAlphaFunc(GL_GREATER, 0.0001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]==weaponshinesprite&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, shinetexture);
-                       if(blend){
-                               blend=0;
-                               glAlphaFunc(GL_GREATER, 0.001);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE);
-                       }
-               }
-               if((type[i]==flamesprite||type[i]==weaponflamesprite)&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, flametexture);
-                       if(blend||lasttype==bloodflamesprite){
-                               blend=0;
-                               glAlphaFunc(GL_GREATER, 0.3);
-                               glBlendFunc(GL_SRC_ALPHA,GL_ONE);
-                       }
-               }
-               if((type[i]==bloodflamesprite)&&lasttype!=type[i]){
-                       glBindTexture( GL_TEXTURE_2D, bloodflametexture);
-                       if(blend){
-                               blend=0;
-                               glAlphaFunc(GL_GREATER, 0.3);
-                               glBlendFunc(GL_ONE,GL_ZERO);
-                               //glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-                       }
-               }
-               if(type[i]!=snowsprite)distancemult=(viewdistsquared-(findDistancefast(&viewer,&position[i])-(viewdistsquared*fadestart))*(1/(1-fadestart)))/viewdistsquared;
-               if(type[i]==snowsprite)distancemult=(144-(findDistancefast(&tempviewer,&position[i])-(144*fadestart))*(1/(1-fadestart)))/144;
-               if(type[i]!=flamesprite){
-                       if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]);
-                       if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]*distancemult);
-               }
-               if(type[i]==flamesprite){
-                       if(distancemult>=1)glColor4f(color[i][0],color[i][1],color[i][2],opacity[i]);
-                       if(distancemult<1)glColor4f(color[i][0],color[i][1],color[i][2],opacity[i]*distancemult);
-               }
-               lasttype=type[i];
-               lastspecial=special[i];
-               glMatrixMode(GL_MODELVIEW);                                                     // Select The Modelview Matrix
-               glPushMatrix();
-                       glTranslatef(position[i].x,position[i].y,position[i].z);
-                       if((type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite)){
-                               difference=viewer-position[i];
-                               Normalise(&difference);
-                               glTranslatef(difference.x*size[i]/4, difference.y*size[i]/4, difference.z*size[i]/4);
-                       }
-                       if(type[i]==snowsprite){
-                               glRotatef(rotation[i]*.2,0,.3,1);
-                               glTranslatef(1,0,0);
-                       }
-                       glGetFloatv(GL_MODELVIEW_MATRIX,M);
-                       point.x=M[12];
-                       point.y=M[13];
-                       point.z=M[14];
-                       glLoadIdentity();
-                       glTranslatef(point.x, point.y, point.z);
-
-                       glRotatef(rotation[i],0,0,1);
-
-                       if((type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite||type[i]==bloodflamesprite)){
-                               if(alivetime[i]<.14)glScalef(alivetime[i]/.14,alivetime[i]/.14,alivetime[i]/.14);
-                       }
-                       if(type[i]==smoketype||type[i]==snowsprite||type[i]==weaponshinesprite||type[i]==breathsprite){
-                               if(alivetime[i]<.3){
-                                       if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]*alivetime[i]/.3);
-                                       if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],opacity[i]*distancemult*alivetime[i]/.3);
-                               }
-                       }
-                       if(type[i]==splintersprite&&special[i]>0&&special[i]!=3){
-                               if(alivetime[i]<.2){
-                                       if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],alivetime[i]/.2);
-                                       if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],distancemult*alivetime[i]/.2);
-                               }
-                               else{
-                                       if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
-                                       if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
-                               }
-                       }
-                       if(type[i]==splintersprite&&(special[i]==0||special[i]==3)){
-                               if(distancemult>=1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
-                               if(distancemult<1)glColor4f(color[i][0]*lightcolor[0],color[i][1]*lightcolor[1],color[i][2]*lightcolor[2],1);
-                       }
-                       /*
-                       if(type[i]==snowsprite){
-                       glRotatef(rotation[i],0,0,1);
-                       glTranslatef(1,0,0);
-                       }*/
-
-                       glBegin(GL_TRIANGLES);
-                       glTexCoord2f(1.0f, 1.0f); glVertex3f( .5*size[i], .5*size[i], 0.0f);
-                       glTexCoord2f(0.0f, 1.0f); glVertex3f(-.5*size[i], .5*size[i], 0.0f);
-                       glTexCoord2f(1.0f, 0.0f); glVertex3f( .5*size[i],-.5*size[i], 0.0f);
-                       glTexCoord2f(0.0f, 0.0f); glVertex3f(-.5*size[i],-.5*size[i], 0.0f);
-                       glTexCoord2f(1.0f, 0.0f); glVertex3f( .5*size[i], -.5*size[i], 0.0f);
-                       glTexCoord2f(0.0f, 1.0f); glVertex3f(-.5*size[i], .5*size[i], 0.0f);
-                       glEnd();
-               glPopMatrix();
-       }
-       tempmult=multiplier;
-       for(i=numsprites-1;i>=0;i--){
-               multiplier=tempmult;
-               if(type[i]!=snowsprite)position[i]+=velocity[i]*multiplier;
-               if(type[i]!=snowsprite)velocity[i]+=windvector*multiplier;
-               if(type[i]==flamesprite||type[i]==smoketype)position[i]+=windvector*multiplier/2;
-               if((type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite||type[i]==bloodflamesprite))multiplier*=speed[i]*.7;
-               alivetime[i]+=multiplier;
-
-               if(type[i]==cloudsprite||type[i]==cloudimpactsprite){
-                       opacity[i]-=multiplier/2;
-                       size[i]+=multiplier/2;
-                       velocity[i].y+=gravity*multiplier*.25;
-               }
-               if(type[i]==breathsprite){
-                       opacity[i]-=multiplier/2;
-                       size[i]+=multiplier/2;
-                       if(findLength(&velocity[i])<=multiplier)velocity[i]=0;
-                       else{
-                               XYZ slowdown;
-                               slowdown=velocity[i]*-1;
-                               Normalise(&slowdown);
-                               slowdown*=multiplier;
-                               velocity[i]+=slowdown;
-                       }
-               }
-               if(type[i]==snowsprite){
-                       size[i]-=multiplier/120;
-                       rotation[i]+=multiplier*360;
-                       position[i].y-=multiplier;
-                       position[i]+=windvector*multiplier;
-                       if(position[i].y<tempviewer.y-6)position[i].y+=12;
-                       if(position[i].y>tempviewer.y+6)position[i].y-=12;
-                       if(position[i].z<tempviewer.z-6)position[i].z+=12;
-                       if(position[i].z>tempviewer.z+6)position[i].z-=12;
-                       if(position[i].x<tempviewer.x-6)position[i].x+=12;
-                       if(position[i].x>tempviewer.x+6)position[i].x-=12;
-               }
-               if(type[i]==bloodsprite){
-                       bool spritehit=0;
-                       rotation[i]+=multiplier*100;
-                       velocity[i].y+=gravity*multiplier;
-                       if(check){
-                               XYZ where,startpoint,endpoint,movepoint,footpoint;
-                               float rotationpoint;
-                               int whichtri;
-
-                               for(j=0;j<numplayers;j++){
-                                       if(!spritehit&&player[j].dead&&alivetime[i]>.1){
-                                               where=oldposition[i];
-                                               where-=player[j].coords;
-                                               if(!player[j].skeleton.free)where=DoRotation(where,0,-player[j].rotation,0);
-                                               startpoint=where;
-                                               where=position[i];
-                                               where-=player[j].coords;
-                                               if(!player[j].skeleton.free)where=DoRotation(where,0,-player[j].rotation,0);
-                                               endpoint=where;
-
-                                               movepoint=0;
-                                               rotationpoint=0;
-                                               whichtri=player[j].skeleton.drawmodel.LineCheck(&startpoint,&endpoint, &footpoint, &movepoint, &rotationpoint);
-                                               if(whichtri!=-1){
-                                                       spritehit=1;
-                                                       player[j].DoBloodBigWhere(0,160,oldposition[i]);
-                                                       DeleteSprite(i);
-                                               }
-                                       }
-                               }
-
-                               whichpatchx=position[i].x/(terrain.size/subdivision*terrain.scale*terraindetail);
-                               whichpatchz=position[i].z/(terrain.size/subdivision*terrain.scale*terraindetail);
-                               if(whichpatchx>0&&whichpatchz>0&&whichpatchx<subdivision&&whichpatchz<subdivision)
-                                       if(terrain.patchobjectnum[whichpatchx][whichpatchz]){
-                                               if(!spritehit)
-                                                       for(j=0;j<terrain.patchobjectnum[whichpatchx][whichpatchz];j++){
-                                                               k=terrain.patchobjects[whichpatchx][whichpatchz][j];
-                                                               start=oldposition[i];
-                                                               end=position[i];
-                                                               if(!spritehit)
-                                                                       if(objects.model[k].LineCheck(&start,&end,&colpoint,&objects.position[k],&objects.rotation[k])!=-1){
-                                                                               if(detail==2||(detail==1&&abs(Random()%4)==0)||(detail==0&&abs(Random()%8)==0))objects.model[k].MakeDecal(blooddecalfast,DoRotation(colpoint-objects.position[k],0,-objects.rotation[k],0),size[i]*1.6/*+abs((float)(Random()%100))/2400*/,.5,Random()%360);
-                                                                               DeleteSprite(i);
-                                                                               spritehit=1;
-                                                                       }       
-                                                       }
-                                       }
-                                       if(!spritehit)
-                                               if(position[i].y<terrain.getHeight(position[i].x,position[i].z)){
-                                                       terrain.MakeDecal(blooddecalfast,position[i],size[i]*1.6/*+abs((float)(Random()%100))/2400*/,.6,Random()%360);
-                                                       DeleteSprite(i);
-                                               }
-                       }
-               }
-               if(type[i]==splintersprite){
-                       rotation[i]+=rotatespeed[i]*multiplier;
-                       opacity[i]-=multiplier/2;
-                       if(special[i]==0||special[i]==2||special[i]==3)velocity[i].y+=gravity*multiplier;
-                       if(special[i]==1)velocity[i].y+=gravity*multiplier*.5;
-               }
-               if(type[i]==flamesprite||type[i]==weaponflamesprite||type[i]==weaponshinesprite||type[i]==bloodflamesprite){
-                       rotation[i]+=multiplier*rotatespeed[i];
-                       opacity[i]-=multiplier*5/4;
-                       if(type[i]!=weaponshinesprite&&type[i]!=bloodflamesprite)
-                               if(opacity[i]<.5&&opacity[i]+multiplier*5/4>=.5&&(abs(Random()%4)==0||(initialsize[i]>2&&Random()%2==0)))MakeSprite(smoketype, position[i],velocity[i], .9,.9,.6, size[i]*1.2, .4);
-                       if(alivetime[i]>.14&&(type[i]==flamesprite)){
-                               velocity[i]=0;
-                               velocity[i].y=1.5;
-                       }
-               }
-               /*if(type[i]==smoketype){
-               opacity[i]-=multiplier/3/initialsize[i];
-               size[i]+=multiplier;
-               velocity[i]=0;
-               velocity[i].y=1.5;
-               rotation[i]+=multiplier*rotatespeed[i]/5;
-               }*/
-               if(type[i]==smoketype){
-                       opacity[i]-=multiplier/3/initialsize[i];
-                       color[i][0]-=multiplier;
-                       color[i][1]-=multiplier;
-                       color[i][2]-=multiplier;
-                       if(color[i][0]<.6)color[i][0]=.6;
-                       if(color[i][1]<.6)color[i][1]=.6;
-                       if(color[i][2]<.6)color[i][2]=.6;
-                       size[i]+=multiplier;
-                       velocity[i]=0;
-                       velocity[i].y=1.5;
-                       rotation[i]+=multiplier*rotatespeed[i]/5;
-               }
-               if(opacity[i]<=0||size[i]<=0)DeleteSprite(i);
-       }
-       if(check)
-               for(i=numsprites-1;i>=0;i--){
-                       oldposition[i]=position[i];
-               }
-               glAlphaFunc(GL_GREATER, 0.0001);
-               glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
-}
-
-void Sprites::DeleteSprite(int which)
-{
-       type[which]=type[numsprites-1];
-       rotation[which]=rotation[numsprites-1];
-       alivetime[which]=alivetime[numsprites-1];
-       opacity[which]=opacity[numsprites-1];
-       position[which]=position[numsprites-1];
-       velocity[which]=velocity[numsprites-1];
-       size[which]=size[numsprites-1];
-       speed[which]=speed[numsprites-1];
-       special[which]=special[numsprites-1];
-       color[which][0]=color[numsprites-1][0];
-       color[which][1]=color[numsprites-1][1];
-       color[which][2]=color[numsprites-1][2];
-       numsprites--;
-}
-
-void Sprites::MakeSprite(int atype, XYZ where, XYZ avelocity, float red, float green, float blue, float asize, float aopacity){
-       if(numsprites<max_sprites-1){
-               if((atype!=bloodsprite&&atype!=bloodflamesprite)||bloodtoggle){
-                       special[numsprites]=0;
-                       type[numsprites]=atype;
-                       position[numsprites]=where;
-                       oldposition[numsprites]=where;
-                       velocity[numsprites]=avelocity;
-                       alivetime[numsprites]=0;
-                       opacity[numsprites]=aopacity;
-                       size[numsprites]=asize;
-                       initialsize[numsprites]=asize;
-                       color[numsprites][0]=red;
-                       color[numsprites][1]=green;
-                       color[numsprites][2]=blue;
-                       rotatespeed[numsprites]=abs(Random()%720)-360;
-                       speed[numsprites]=float(abs(Random()%100))/200+1.5;
-               }               
-               numsprites++;
-       }
-}
-
-Sprites::Sprites()
-{
-       cloudtexture = 0;
-       cloudimpacttexture = 0;
-       bloodtexture = 0;
-       flametexture = 0;
-       bloodflametexture = 0;
-       smoketexture = 0;
-       snowflaketexture = 0;
-       shinetexture = 0;
-       splintertexture = 0;
-       leaftexture = 0;
-       toothtexture = 0;
-
-       memset(oldposition, 0, sizeof(oldposition));
-       memset(position, 0, sizeof(position));
-       memset(velocity, 0, sizeof(velocity));
-       memset(size, 0, sizeof(size));
-       memset(initialsize, 0, sizeof(initialsize));
-       memset(type, 0, sizeof(type));
-       memset(special, 0, sizeof(special));
-       memset(color, 0, sizeof(color));
-       memset(opacity, 0, sizeof(opacity));
-       memset(rotation, 0, sizeof(rotation));
-       memset(alivetime, 0, sizeof(alivetime));
-       memset(speed, 0, sizeof(speed));
-       memset(rotatespeed, 0, sizeof(rotatespeed));
-
-       checkdelay = 0;
-       numsprites = 0;
-}
-Sprites::~Sprites()
-{
-       if (toothtexture) glDeleteTextures( 1, &toothtexture );
-       if (cloudtexture) glDeleteTextures( 1, &cloudtexture );
-       if (cloudimpacttexture) glDeleteTextures( 1, &cloudimpacttexture );
-       if (bloodtexture) glDeleteTextures( 1, &bloodtexture );
-       if (flametexture) glDeleteTextures( 1, &flametexture );
-       if (bloodflametexture) glDeleteTextures( 1, &bloodflametexture );
-       if (smoketexture) glDeleteTextures( 1, &smoketexture );
-       if (snowflaketexture) glDeleteTextures( 1, &snowflaketexture );
-       if (shinetexture) glDeleteTextures( 1, &shinetexture );
-       if (splintertexture) glDeleteTextures( 1, &splintertexture );
-       if (leaftexture) glDeleteTextures( 1, &leaftexture );
-}
-
diff --git a/Source/Sprites.h b/Source/Sprites.h
deleted file mode 100644 (file)
index 86677a1..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#ifndef _SPRITES_H_
-#define _SPRITES_H_
-
-#include "Quaternions.h"
-#include "gamegl.h"
-#include "TGALoader.h"
-#include "Quaternions.h"
-#include "Frustum.h"
-#include "Lights.h"
-#include "Terrain.h"
-#include "Objects.h"
-//
-// Model Structures
-//
-
-#define max_sprites 20000
-
-#define cloudsprite 0
-#define bloodsprite 1
-#define flamesprite 2
-#define smoketype 3
-#define weaponflamesprite 4
-#define cloudimpactsprite 5
-#define snowsprite 6
-#define weaponshinesprite 7
-#define bloodflamesprite 8
-#define breathsprite 9
-#define splintersprite 10
-
-class Sprites{
-public:
-       GLuint cloudtexture;
-       GLuint cloudimpacttexture;
-       GLuint bloodtexture;
-       GLuint flametexture;
-       GLuint bloodflametexture;
-       GLuint smoketexture;
-       GLuint snowflaketexture;
-       GLuint shinetexture;
-       GLuint splintertexture;
-       GLuint leaftexture;
-       GLuint toothtexture;
-
-       XYZ oldposition[max_sprites];
-       XYZ position[max_sprites];
-       XYZ velocity[max_sprites];
-       float size[max_sprites];
-       float initialsize[max_sprites];
-       int type[max_sprites];
-       int special[max_sprites];
-       float color[max_sprites][3];
-       float opacity[max_sprites];
-       float rotation[max_sprites];
-       float alivetime[max_sprites];
-       float speed[max_sprites];
-       float rotatespeed[max_sprites];
-       float checkdelay;
-       int numsprites;
-
-       void DeleteSprite(int which);
-       void MakeSprite(int atype, XYZ where, XYZ avelocity, float red, float green, float blue, float asize, float aopacity);
-       void Draw();
-
-       Sprites();
-       ~Sprites();
-};
-
-#endif
index 89d28be7c7d4d1fd0d194bb6c8288dd30885844e..89d9b6b0a34d2a009928a8ca5ee57240a17cb11a 100644 (file)
@@ -35,7 +35,7 @@ extern bool LoadImage(const char * fname, TGAImageRec & tex);
 /********************> LoadTGA() <*****/
 bool upload_image(const unsigned char* filePath, bool hasalpha)
 {
-       if(visibleloading){
+       if(visibleloading) {
                loadscreencolor=1;
                pgame->LoadingScreen();
        }
@@ -180,109 +180,3 @@ bool upload_image(const unsigned char* filePath, bool hasalpha)
 
 #endif
 }
-
-
-TGAImageRec*   LoadTGA( char *filename )
-{    
-       GLubyte                 TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};        // Uncompressed TGA Header
-       GLubyte                 TGAcompare[12];                                                         // Used To Compare TGA Header
-       GLubyte                 header[6];                                                                      // First 6 Useful Bytes From The Header
-       GLuint                  bytesPerPixel;                                                          // Holds Number Of Bytes Per Pixel Used In The TGA File
-       GLuint                  imageSize;                                                                      // Used To Store The Image Size When Setting Aside Ram
-       GLuint                  temp;                                                                           // Temporary Variable
-       GLuint                  type = GL_RGBA;                                                         // Set The Default GL Mode To RBGA (32 BPP)
-       //TGAImageRec           *texture;
-       FILE                    *file;
-
-       // Open The TGA File
-       file = fopen( filename, "rb" );
-
-       if( ( file == NULL ) || // Does File Even Exist?
-               ( fread( TGAcompare, 1, sizeof( TGAcompare ), file ) != sizeof( TGAcompare ) ) ||       // Are There 12 Bytes To Read?
-               ( memcmp( TGAheader, TGAcompare, sizeof( TGAheader ) ) != 0 ) ||        // Does The Header Match What We Want?
-               ( fread( header, 1, sizeof( header ), file ) != sizeof( header ) ) )// If So Read Next 6 Header Bytes
-       {
-               // If anything failed then close the file and return false
-               if (file) fclose( file );
-               return NULL;
-       }
-
-       // Create a new RGBAImageRec
-       //texture = ( TGAImageRec* )malloc( sizeof( TGAImageRec ) );
-
-       // Determine the TGA width (highbyte*256+lowbyte) and height (highbyte*256+lowbyte)
-       texture.sizeX  = (header[1] * 256 + header[0]);
-       texture.sizeY = (header[3] * 256 + header[2]);
-
-       // Make sure the height, width, and bit depth are valid
-       if(     ( texture.sizeX <= 0 ) || ( texture.sizeY <= 0 ) || ( ( header[4] != 24 ) && ( header[4] != 32 ) ) )
-       {
-               // If anything failed then close the file, free up memory for the image, and return NULL
-               fclose( file );
-               //free( texture );
-               return NULL;
-       }
-
-       // Grab The TGA's Bits Per Pixel (24 or 32)
-       texture.bpp = header[4];                                                        
-       bytesPerPixel = texture.bpp/8;  // Divide By 8 To Get The Bytes Per Pixel
-
-       // Calculate The Memory Required For The TGA Data
-       imageSize = texture.sizeX * texture.sizeY * bytesPerPixel;
-
-       // Reserve Memory To Hold The TGA Data
-       //texture.data = ( GLubyte* )malloc( imageSize );               
-
-       // Make sure the right amount of memory was allocated
-       if(     ( texture.data == NULL ) || ( fread( texture.data, 1, imageSize, file ) != imageSize ) )
-       {
-               // Free up the image data if there was any
-               //              if( texture.data != NULL )
-               //                      free( texture.data );
-
-               // If anything failed then close the file, free up memory for the image, and return NULL
-               fclose( file );
-               //              free( texture );
-               return NULL;
-       }
-
-       // Loop Through The Image Data
-       for( GLuint i = 0; i < int( imageSize ); i += bytesPerPixel )
-       {
-               // Swaps The 1st And 3rd Bytes ('R'ed and 'B'lue)
-               temp = texture.data[i];                                 // Temporarily Store The Value At Image Data 'i'
-               texture.data[i] = texture.data[i + 2];  // Set The 1st Byte To The Value Of The 3rd Byte
-               texture.data[i + 2] = temp;                             // Set The 3rd Byte To The Value In 'temp' (1st Byte Value)
-       }
-
-       if(texdetail>1){
-               int which=0;
-               float temp;
-               float howmany;
-               for( GLuint k = 0; k < int( imageSize); k += bytesPerPixel*texture.sizeX*texdetail )
-               {
-                       for( GLuint i = 0; i < int( imageSize/texture.sizeY ); i += bytesPerPixel*texdetail )
-                       {
-                               for( GLuint b = 0; b < bytesPerPixel ; b ++ ){  
-                                       temp=0;
-                                       howmany=0;
-                                       for( GLuint l = 0; l < texdetail*texture.sizeX ; l +=texture.sizeX ){
-                                               for( GLuint j = 0; j < texdetail ; j ++ )
-                                               {
-                                                       temp += (int)texture.data[k+i+j*bytesPerPixel+l*bytesPerPixel+b];       // Set The 1st Byte To The Value Of The 3rd Byte
-                                                       howmany++;
-                                               }
-                                       }
-                                       texture.data[which+b]=GLubyte(temp/howmany);
-                               }
-                               which+=bytesPerPixel;
-                       }
-               }
-               texture.sizeX/=texdetail;
-               texture.sizeY/=texdetail;
-       }
-
-       // Close The File
-       fclose( file );
-       return &texture;
-}
index b27cb182aa4601fea6b0e6e56d6991985f0a1183..7b54de8e18a0abaecc7e9345ac31882ba85857f1 100644 (file)
@@ -56,9 +56,5 @@ typedef struct TGAImageRec
 
 bool upload_image(const unsigned char* filePath, bool hasalpha);
 
-/**> FUNCTION PROTOTYPES <**/
-TGAImageRec*   LoadTGA( char *filename );
-
-
 #endif
 
index 1683dfc88c0426cd7d2ab8b79bfd903e565a2d0e..649d3f390fc1cb2b0ea51a2851d17b5a9942e0b5 100644 (file)
@@ -31,7 +31,7 @@ extern float texscale;
 extern Light light;
 extern float multiplier;
 extern FRUSTUM frustum;
-extern float texdetail,terraindetail;
+extern float texdetail;
 extern int detail;
 extern bool decals;
 extern float blurness;
@@ -378,7 +378,6 @@ bool Terrain::load(const char *fileName)
        static float patch_size;
 
        float temptexdetail=texdetail;
-       texdetail=terraindetail;
        //LoadTGA( fileName );
 
        // Fixing filename so that it works with its own os
@@ -429,7 +428,7 @@ bool Terrain::load(const char *fileName)
 
                for(i=0;i<size;i++){
                        for(j=0;j<size;j++){
-                               heightmap[size-1-i][j]=(float)((texture.data[(i+(j*size))*texture.bpp/8]))/5/terraindetail;
+                               heightmap[size-1-i][j]=(float)((texture.data[(i+(j*size))*texture.bpp/8]))/5;
                        }
                }
 
@@ -1154,10 +1153,10 @@ void Terrain::AddObject(XYZ where, float radius, int id)
                                        points[3].x=(size/subdivision)*i;
                                        points[3].z=(size/subdivision)*(j+1);
                                        points[3].y=heightmap[(int)points[3].x][(int)points[3].z];
-                                       points[0]*=scale*terraindetail;
-                                       points[1]*=scale*terraindetail;
-                                       points[2]*=scale*terraindetail;
-                                       points[3]*=scale*terraindetail;
+                                       points[0]*=scale;
+                                       points[1]*=scale;
+                                       points[2]*=scale;
+                                       points[3]*=scale;
                                        if(!done&&where.x+radius>points[0].x&&where.x-radius<points[2].x&&where.z+radius>points[0].z&&where.z-radius<points[2].z){
                                                patchobjects[i][j][patchobjectnum[i][j]]=id;
                                                patchobjectnum[i][j]++;
index e1c2878b4fc4686c665e9421a4f89422872e6a96..0652c87b2d4085820d13aeef395a496f15dfe9a1 100644 (file)
@@ -116,12 +116,12 @@ void Text::BuildFont()                                                            // Build Our Font Display List
        }                                                                                                       // Loop Until All 256 Are Built
 }
 
-void Text::glPrint(float x, float y, char *string, int set, float size, float width, float height)     // Where The Printing Happens
+void Text::glPrint(float x, float y, const char *string, int set, float size, float width, float height)       // Where The Printing Happens
 {
        glPrint(x, y, string, set, size, width, height, 0, strlen(string));
 }
 
-void Text::_glPrint(float x, float y, char *string, int set, float size, float width, float height,int start,int end, int offset)      // Where The Printing Happens
+void Text::_glPrint(float x, float y, const char *string, int set, float size, float width, float height,int start,int end, int offset)        // Where The Printing Happens
 {
        if (set>1)
        {
@@ -152,26 +152,26 @@ void Text::_glPrint(float x, float y, char *string, int set, float size, float w
        glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
 }
 
-void Text::glPrint(float x, float y, char *string, int set, float size, float width, float height,int start,int end)   // Where The Printing Happens
+void Text::glPrint(float x, float y, const char *string, int set, float size, float width, float height,int start,int end)     // Where The Printing Happens
 {
        _glPrint(x, y, string, set, size, width, height, start, end, 0);
 }
 
-void Text::glPrintOutline(float x, float y, char *string, int set, float size, float width, float height)      // Where The Printing Happens
+void Text::glPrintOutline(float x, float y, const char *string, int set, float size, float width, float height)        // Where The Printing Happens
 {
        glPrintOutline(x, y, string, set, size, width, height, 0, strlen(string));
 }
 
-void Text::glPrintOutline(float x, float y, char *string, int set, float size, float width, float height,int start,int end)    // Where The Printing Happens
+void Text::glPrintOutline(float x, float y, const char *string, int set, float size, float width, float height,int start,int end)      // Where The Printing Happens
 {
        _glPrint(x, y, string, set, size, width, height, start, end, 256);
 }
-void Text::glPrintOutlined(float x, float y, char *string, int set, float size, float width, float height)     // Where The Printing Happens
+void Text::glPrintOutlined(float x, float y, const char *string, int set, float size, float width, float height)       // Where The Printing Happens
 {
        glPrintOutlined(1, 1, 1, x, y, string, set, size, width, height);
 }
 
-void Text::glPrintOutlined(float r, float g, float b, float x, float y, char *string, int set, float size, float width, float height)  // Where The Printing Happens
+void Text::glPrintOutlined(float r, float g, float b, float x, float y, const char *string, int set, float size, float width, float height)    // Where The Printing Happens
 {
        glColor4f(0,0,0,1);
        glPrintOutline( x-2*size,  y-2*size, string,  set,  size*2.5/2,  width,  height);
index d2502abed9d3e5cc4f8ffd7bc5185af6fa1974fc..eba21593e81082014951c7a547ec411455b7dac0 100644 (file)
@@ -37,18 +37,18 @@ public:
 
        void LoadFontTexture(const char *fileName);
        void BuildFont();
-       void glPrint(float x, float y, char *string, int set, float size, float width, float height);
-       void glPrintOutline(float x, float y, char *string, int set, float size, float width, float height);
-       void glPrint(float x, float y, char *string, int set, float size, float width, float height,int start,int end);
-       void glPrintOutline(float x, float y, char *string, int set, float size, float width, float height,int start,int end);
-       void glPrintOutlined(float x, float y, char *string, int set, float size, float width, float height);
-       void glPrintOutlined(float r, float g, float b, float x, float y, char *string, int set, float size, float width, float height);
+       void glPrint(float x, float y, const char *string, int set, float size, float width, float height);
+       void glPrintOutline(float x, float y, const char *string, int set, float size, float width, float height);
+       void glPrint(float x, float y, const char *string, int set, float size, float width, float height,int start,int end);
+       void glPrintOutline(float x, float y, const char *string, int set, float size, float width, float height,int start,int end);
+       void glPrintOutlined(float x, float y, const char *string, int set, float size, float width, float height);
+       void glPrintOutlined(float r, float g, float b, float x, float y, const char *string, int set, float size, float width, float height);
 
        Text();
        ~Text();
 
 private:
-       void _glPrint(float x, float y, char *string, int set, float size, float width, float height, int start, int end, int offset);
+       void _glPrint(float x, float y, const char *string, int set, float size, float width, float height, int start, int end, int offset);
 };
 
 #endif
index 2caa4c6e9eb1697034d4ddd7adb32722966c982d..d250f1ee84676c50d008dbc35e4724ce22db42ac 100644 (file)
@@ -22,15 +22,15 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 /**> HEADER FILES <**/
 #include "Weapons.h"
 #include "openal_wrapper.h"
+#include "Animation.h"
+#include "Sounds.h"
+#include "Game.h"
+#include "Awards.h"
 
 extern float multiplier;
-extern Animation animation[animation_count];
-extern OPENAL_SAMPLE   *samp[100];
-extern int channels[100];
 extern Terrain terrain;
 extern float gravity;
 extern int environment;
-extern Sprites sprites;
 extern int detail;
 extern FRUSTUM frustum;
 extern XYZ viewer;
@@ -46,20 +46,12 @@ extern bool osx;
 extern bool autoslomo;
 extern float camerashake;
 extern float woozy;
-extern float terraindetail;
 extern float viewdistance;
 extern float blackout;
 extern int difficulty;
-extern Person player[maxplayers];
-extern int numplayers;
 extern bool freeze;
-extern int bonus;
-extern float bonusvalue;
-extern float bonustotal;
-extern float bonustime;
 extern int tutoriallevel;
 extern int numthrowkill;
-extern "C"     void PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
 
 void   Weapons::DoStuff(){
        static int i,whichpatchx,whichpatchz,j,k,whichhit,m;
@@ -90,35 +82,17 @@ void        Weapons::DoStuff(){
                        oldowner[i]=owner[i];
                }
                if(damage[i]>=2&&type[i]==staff&&owner[i]!=-1){
-                       float gLoc[3];
-                       float vel[3];
-                       gLoc[0]=tippoint[i].x;
-                       gLoc[1]=tippoint[i].y;
-                       gLoc[2]=tippoint[i].z;
-                       vel[0]=0;
-                       vel[1]=0;
-                       vel[2]=0;
-                       PlaySoundEx( staffbreaksound, samp[staffbreaksound], NULL, true);
-                       OPENAL_3D_SetAttributes(channels[staffbreaksound], gLoc, vel);
-                       OPENAL_SetVolume(channels[staffbreaksound], 256);
-                       OPENAL_SetPaused(channels[staffbreaksound], false);
+                       emit_sound_at(staffbreaksound, tippoint[i]);
                        XYZ tempvel;
                        XYZ speed;
                        //speed=(tippoint[i]-oldtippoint[i])/multiplier/6;
                        speed=0;
-                       /*for(j=0;j<10;j++){
-                       tempvel.x=float(abs(Random()%100)-50)/20;
-                       tempvel.y=float(abs(Random()%100)-50)/20;
-                       tempvel.z=float(abs(Random()%100)-50)/20;
-                       tempvel+=speed;
-                       sprites.MakeSprite(cloudimpactsprite, position[i]+(tippoint[i]-position[i])*((float)j-2)/8,tempvel*.5, 115/255,73/255,12/255, .15+float(abs(Random()%100)-50)/1000, .7);
-                       }*/
                        for(j=0;j<40;j++){
                                tempvel.x=float(abs(Random()%100)-50)/20;
                                tempvel.y=float(abs(Random()%100)-50)/20;
                                tempvel.z=float(abs(Random()%100)-50)/20;
                                tempvel+=speed;
-                               sprites.MakeSprite(splintersprite, position[i]+(tippoint[i]-position[i])*((float)j-8)/32,tempvel*.5, 115/255,73/255,12/255, .1, 1);
+                               Sprite::MakeSprite(splintersprite, position[i]+(tippoint[i]-position[i])*((float)j-8)/32,tempvel*.5, 115/255,73/255,12/255, .1, 1);
                        }
                        int tempowner;
                        tempowner=owner[i];
@@ -143,8 +117,8 @@ void        Weapons::DoStuff(){
                if(owner[i]==-1&&(velocity[i].x||velocity[i].y||velocity[i].z)&&!physics[i]){
                        position[i]+=velocity[i]*multiplier;
                        tippoint[i]+=velocity[i]*multiplier;
-                       whichpatchx=position[i].x/(terrain.size/subdivision*terrain.scale*terraindetail);
-                       whichpatchz=position[i].z/(terrain.size/subdivision*terrain.scale*terraindetail);
+                       whichpatchx=position[i].x/(terrain.size/subdivision*terrain.scale);
+                       whichpatchz=position[i].z/(terrain.size/subdivision*terrain.scale);
                        if(whichpatchx>0&&whichpatchz>0&&whichpatchx<subdivision&&whichpatchz<subdivision)
                                if(terrain.patchobjectnum[whichpatchx][whichpatchz]){
                                        for(j=0;j<terrain.patchobjectnum[whichpatchx][whichpatchz];j++){
@@ -181,22 +155,11 @@ void      Weapons::DoStuff(){
                                                                bigtilt2[i]=0;
                                                                bigrotation[i]=0;
 
-                                                               float gLoc[3];
-                                                               float vel[3];
-                                                               gLoc[0]=position[i].x;
-                                                               gLoc[1]=position[i].y;
-                                                               gLoc[2]=position[i].z;
-                                                               vel[0]=0;
-                                                               vel[1]=0;
-                                                               vel[2]=0;
-                                                               PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                                               OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                                               OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                                               OPENAL_SetPaused(channels[knifesheathesound], false);
+                                                               emit_sound_at(knifesheathesound, position[i], 128.);
 
                                                                bloody[i]=0;
 
-                                                               sprites.MakeSprite(cloudimpactsprite, position[i],velocity[i], 1,1,1, .8, .3);
+                                                               Sprite::MakeSprite(cloudimpactsprite, position[i],velocity[i], 1,1,1, .8, .3);
                                                        }
                                                        else {
                                                                physics[i]=1;
@@ -216,18 +179,7 @@ void       Weapons::DoStuff(){
                                                        if((player[j].aitype!=attacktypecutoff||abs(Random()%6)==0||(player[j].targetanimation!=backhandspringanim&&player[j].targetanimation!=rollanim&&player[j].targetanimation!=flipanim&&Random()%2==0))&&!missed[i]){
                                                                bool caught=0;
                                                                if((player[j].creature==wolftype&&Random()%3!=0&&player[j].weaponactive==-1&&(player[j].isIdle()||player[j].isRun()||player[j].targetanimation==walkanim))||(player[j].creature==rabbittype&&Random()%2==0&&player[j].aitype==attacktypecutoff&&player[j].weaponactive==-1)){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=player[j].coords.x;
-                                                                       gLoc[1]=player[j].coords.y;
-                                                                       gLoc[2]=player[j].coords.z;
-                                                                       vel[0]=player[j].velocity.x;
-                                                                       vel[1]=player[j].velocity.y;
-                                                                       vel[2]=player[j].velocity.z;
-                                                                       PlaySoundEx( knifedrawsound, samp[knifedrawsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[knifedrawsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[knifedrawsound], 128);
-                                                                       OPENAL_SetPaused(channels[knifedrawsound], false);
+                                                                       emit_sound_at(knifedrawsound, player[j].coords, 128.);
 
                                                                        player[j].weaponactive=0;
                                                                        player[j].targetanimation=removeknifeanim;
@@ -257,11 +209,11 @@ void      Weapons::DoStuff(){
                                                                        player[j].skeleton.joints[player[j].skeleton.jointlabels[rightshoulder]].velocity+=velocity[i]*2;
                                                                        player[j].skeleton.joints[player[j].skeleton.jointlabels[leftshoulder]].velocity+=velocity[i]*2;
                                                                        //player[j].Puff(abdomen);
-                                                                       if(bloodtoggle&&tutoriallevel!=1)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
-                                                                       if(tutoriallevel==1)sprites.MakeSprite(cloudimpactsprite, footpoint,footvel, 1,1,1, .8, .3);
+                                                                       if(bloodtoggle&&tutoriallevel!=1)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,0,0, .8, .3);
+                                                                       if(tutoriallevel==1)Sprite::MakeSprite(cloudimpactsprite, footpoint,footvel, 1,1,1, .8, .3);
                                                                        footvel=tippoint[i]-position[i];
                                                                        Normalise(&footvel);
-                                                                       if(bloodtoggle&&tutoriallevel!=1)sprites.MakeSprite(bloodflamesprite, footpoint,footvel*-1, 1,0,0, .6, 1);
+                                                                       if(bloodtoggle&&tutoriallevel!=1)Sprite::MakeSprite(bloodflamesprite, footpoint,footvel*-1, 1,0,0, .6, 1);
 
                                                                        if(tutoriallevel!=1){
                                                                                if(player[j].weaponstuckwhere==0)player[j].DoBloodBig(2,205);
@@ -274,29 +226,12 @@ void      Weapons::DoStuff(){
                                                                                blooddrip[i]=5;
                                                                        }
 
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       gLoc[0]=position[i].x;
-                                                                       gLoc[1]=position[i].y;
-                                                                       gLoc[2]=position[i].z;
-                                                                       vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
-                                                                       PlaySoundEx( fleshstabsound, samp[fleshstabsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[fleshstabsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[fleshstabsound], 128);
-                                                                       OPENAL_SetPaused(channels[fleshstabsound], false);
-
-                                                                       if(animation[player[0].targetanimation].height==highheight){
-                                                                               bonus=ninja;
-                                                                               bonustime=0;
-                                                                               bonusvalue=60;
-                                                                       }
-                                                                       else{
-                                                                               bonus=Bullseyebonus;
-                                                                               bonustime=0;
-                                                                               bonusvalue=30;
-                                                                       }
+                                                                       emit_sound_at(fleshstabsound, position[i], 128.);
+
+                                                                       if(animation[player[0].targetanimation].height==highheight)
+                                                                         award_bonus(0, ninja);
+                                                                       else
+                                                                         award_bonus(0, Bullseyebonus);
                                                                }
                                                        }
                                                        else missed[i]=1;
@@ -343,29 +278,18 @@ void      Weapons::DoStuff(){
                                                        bigtilt2[i]=0;
                                                        bigrotation[i]=0;
 
-                                                       float gLoc[3];
-                                                       float vel[3];
-                                                       gLoc[0]=position[i].x;
-                                                       gLoc[1]=position[i].y;
-                                                       gLoc[2]=position[i].z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( knifesheathesound, samp[knifesheathesound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[knifesheathesound], gLoc, vel);
-                                                       OPENAL_SetVolume(channels[knifesheathesound], 128);
-                                                       OPENAL_SetPaused(channels[knifesheathesound], false);
+                                                       emit_sound_at(knifesheathesound, position[i], 128.);
 
                                                        XYZ terrainlight;
                                                        terrainlight=terrain.getLighting(position[i].x,position[i].z);
                                                        if(environment==snowyenvironment){
-                                                               if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
+                                                               if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
                                                        }
                                                        else if(environment==grassyenvironment){
-                                                               if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
+                                                               if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
                                                        }
                                                        else if(environment==desertenvironment){
-                                                               if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
+                                                               if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
                                                        }
 
                                                        bloody[i]=0;
@@ -430,8 +354,8 @@ void        Weapons::DoStuff(){
 
 
                                //Object collisions
-                               whichpatchx=(position[i].x)/(terrain.size/subdivision*terrain.scale*terraindetail);
-                               whichpatchz=(position[i].z)/(terrain.size/subdivision*terrain.scale*terraindetail);
+                               whichpatchx=(position[i].x)/(terrain.size/subdivision*terrain.scale);
+                               whichpatchz=(position[i].z)/(terrain.size/subdivision*terrain.scale);
                                if(whichpatchx>0&&whichpatchz>0&&whichpatchx<subdivision&&whichpatchz<subdivision)
                                        if(terrain.patchobjectnum[whichpatchx][whichpatchz]){
                                                for(j=0;j<terrain.patchobjectnum[whichpatchx][whichpatchz];j++){
@@ -491,21 +415,10 @@ void      Weapons::DoStuff(){
                                                                velocity[i]+=bounceness*elasticity;
 
                                                                if(findLengthfast(&bounceness)>1){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       //int whichsound=clank1sound+abs(Random()%4);
                                                                        int whichsound;
                                                                        if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
-                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);gLoc[0]=position[i].x;
-                                                                       gLoc[1]=position[i].y;
-                                                                       gLoc[2]=position[i].z;
-                                                                       vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
-                                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
+                                                                       emit_sound_at(whichsound, position[i], 128*findLengthfast(&bounceness));
                                                                }
                                                        }
                                                        start=oldtippoint[i];
@@ -527,22 +440,10 @@ void      Weapons::DoStuff(){
                                                                tipvelocity[i]+=bounceness*elasticity;
 
                                                                if(findLengthfast(&bounceness)>1){
-                                                                       float gLoc[3];
-                                                                       float vel[3];
-                                                                       //int whichsound=clank1sound+abs(Random()%4);
                                                                        int whichsound;
                                                                        if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
-                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);gLoc[0]=position[i].x;
-                                                                       gLoc[0]=position[i].x;
-                                                                       gLoc[1]=position[i].y;
-                                                                       gLoc[2]=position[i].z;
-                                                                       vel[0]=0;
-                                                                       vel[1]=0;
-                                                                       vel[2]=0;
-                                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                                       OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
+                                                                       emit_sound_at(whichsound, position[i], 128*findLengthfast(&bounceness));
                                                                }
                                                        }
 
@@ -570,21 +471,10 @@ void      Weapons::DoStuff(){
                                                                                velocity[i]+=bounceness*elasticity;
 
                                                                                if(findLengthfast(&bounceness)>1){
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       //int whichsound=clank1sound+abs(Random()%4);
                                                                                        int whichsound;
                                                                                        if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
-                                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);gLoc[0]=mid.x;
-                                                                                       gLoc[1]=mid.y;
-                                                                                       gLoc[2]=mid.z;
-                                                                                       vel[0]=0;
-                                                                                       vel[1]=0;
-                                                                                       vel[2]=0;
-                                                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
+                                                                                       emit_sound_at(whichsound, mid, 128*findLengthfast(&bounceness));
                                                                                }
                                                                                position[i]+=(mid-oldmid2)*(20/(1+(float)m*10));
                                                                        }
@@ -611,21 +501,10 @@ void      Weapons::DoStuff(){
                                                                                tipvelocity[i]+=bounceness*elasticity;
 
                                                                                if(findLengthfast(&bounceness)>1){
-                                                                                       float gLoc[3];
-                                                                                       float vel[3];
-                                                                                       //int whichsound=clank1sound+abs(Random()%4);
                                                                                        int whichsound;
                                                                                        if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
-                                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);gLoc[0]=mid.x;
-                                                                                       gLoc[1]=mid.y;
-                                                                                       gLoc[2]=mid.z;
-                                                                                       vel[0]=0;
-                                                                                       vel[1]=0;
-                                                                                       vel[2]=0;
-                                                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                                                       OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
+                                                                                       emit_sound_at(whichsound, mid, 128*findLengthfast(&bounceness));
                                                                                }
                                                                                tippoint[i]+=(mid-oldmid2)*(20/(1+(float)m*10));
                                                                        }
@@ -694,37 +573,29 @@ void      Weapons::DoStuff(){
                                                else velocity[i]+=bounceness*elasticity;
 //if (type[i]==knife) printf("velocity of knife %d now %f,%f,%f.\n", i, velocity[i].x, velocity[i].y, velocity[i].z);
                                                if(findLengthfast(&bounceness)>1){
-                                                       float gLoc[3];
-                                                       float vel[3];
                                                        int whichsound;
                                                        if(terrain.getOpacity(position[i].x,position[i].z)>.2){
                                                                if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
                                                                if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
                                                        }
                                                        else whichsound=footstepsound+abs(Random()%2);
-                                                       gLoc[0]=position[i].x;
-                                                       gLoc[1]=position[i].y;
-                                                       gLoc[2]=position[i].z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                       if(terrain.getOpacity(position[i].x,position[i].z)>.2)OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                       else OPENAL_SetVolume(channels[whichsound], 32*findLengthfast(&bounceness));
-                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                       emit_sound_at(whichsound, position[i],
+                                                                     findLengthfast(&bounceness)
+                                                                     * (terrain.getOpacity(position[i].x,position[i].z) > .2
+                                                                        ? 128.
+                                                                        : 32.));
 
                                                        if(terrain.getOpacity(position[i].x,position[i].z)<.2){
                                                                XYZ terrainlight;
                                                                terrainlight=terrain.getLighting(position[i].x,position[i].z);
                                                                if(environment==snowyenvironment){
-                                                                       if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
+                                                                       if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
                                                                }
                                                                else if(environment==grassyenvironment){
-                                                                       if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
+                                                                       if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
                                                                }
                                                                else if(environment==desertenvironment){
-                                                                       if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
+                                                                       if(findDistancefast(&position[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, position[i],velocity[i], terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
                                                                }
                                                        }
                                                }
@@ -748,37 +619,29 @@ void      Weapons::DoStuff(){
 //if (type[i]==knife) printf("tipvelocity of knife %d now %f,%f,%f.\n", i, tipvelocity[i].x, tipvelocity[i].y, tipvelocity[i].z);
 
                                                if(findLengthfast(&bounceness)>1){
-                                                       float gLoc[3];
-                                                       float vel[3];
                                                        int whichsound;
                                                        if(terrain.getOpacity(tippoint[i].x,tippoint[i].z)>.2){
                                                                if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
                                                                if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
                                                        }
                                                        else whichsound=footstepsound+abs(Random()%2);
-                                                       gLoc[0]=tippoint[i].x;
-                                                       gLoc[1]=tippoint[i].y;
-                                                       gLoc[2]=tippoint[i].z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                       if(terrain.getOpacity(tippoint[i].x,tippoint[i].z)>.2)OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                       else OPENAL_SetVolume(channels[whichsound], 32*findLengthfast(&bounceness));
-                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                       emit_sound_at(whichsound, tippoint[i],
+                                                                     findLengthfast(&bounceness)
+                                                                     * (terrain.getOpacity(tippoint[i].x,tippoint[i].z) > .2
+                                                                        ? 128.
+                                                                        : 32.));
 
                                                        if(terrain.getOpacity(tippoint[i].x,tippoint[i].z)<.2){
                                                                XYZ terrainlight;
                                                                terrainlight=terrain.getLighting(tippoint[i].x,tippoint[i].z);
                                                                if(environment==snowyenvironment){
-                                                                       if(findDistancefast(&tippoint[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, tippoint[i],tipvelocity[i], terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
+                                                                       if(findDistancefast(&tippoint[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, tippoint[i],tipvelocity[i], terrainlight.x,terrainlight.y,terrainlight.z, .5, .7);
                                                                }
                                                                else if(environment==grassyenvironment){
-                                                                       if(findDistancefast(&tippoint[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, tippoint[i],tipvelocity[i], terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
+                                                                       if(findDistancefast(&tippoint[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, tippoint[i],tipvelocity[i], terrainlight.x*90/255,terrainlight.y*70/255,terrainlight.z*8/255, .5, .5);
                                                                }
                                                                else if(environment==desertenvironment){
-                                                                       if(findDistancefast(&tippoint[i],&viewer)<viewdistance*viewdistance/4)sprites.MakeSprite(cloudsprite, tippoint[i],tipvelocity[i], terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
+                                                                       if(findDistancefast(&tippoint[i],&viewer)<viewdistance*viewdistance/4)Sprite::MakeSprite(cloudsprite, tippoint[i],tipvelocity[i], terrainlight.x*190/255,terrainlight.y*170/255,terrainlight.z*108/255, .5, .7);
                                                                }
                                                        }
                                                }
@@ -806,25 +669,17 @@ void      Weapons::DoStuff(){
                                                else velocity[i]+=bounceness*elasticity;
 
                                                if(findLengthfast(&bounceness)>1){
-                                                       float gLoc[3];
-                                                       float vel[3];
                                                        int whichsound;
                                                        if(terrain.getOpacity(mid.x,mid.z)>.2){
                                                                if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
                                                                if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
                                                        }
                                                        else whichsound=footstepsound+abs(Random()%2);
-                                                       gLoc[0]=mid.x;
-                                                       gLoc[1]=mid.y;
-                                                       gLoc[2]=mid.z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                       if(terrain.getOpacity(position[i].x,position[i].z)>.2)OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                       else OPENAL_SetVolume(channels[whichsound], 32*findLengthfast(&bounceness));
-                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                       emit_sound_at(whichsound, mid,
+                                                                     findLengthfast(&bounceness)
+                                                                     * (terrain.getOpacity(position[i].x,position[i].z) > .2
+                                                                        ? 128.
+                                                                        : 32.));
                                                }
                                                position[i]+=(mid-oldmid)*20;
                                        }
@@ -850,184 +705,20 @@ void     Weapons::DoStuff(){
                                                else tipvelocity[i]+=bounceness*elasticity;
 
                                                if(findLengthfast(&bounceness)>1){
-                                                       float gLoc[3];
-                                                       float vel[3];
                                                        int whichsound;
                                                        if(terrain.getOpacity(mid.x,mid.z)>.2){
                                                                if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
                                                                if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
                                                        }
                                                        else whichsound=footstepsound+abs(Random()%2);
-                                                       gLoc[0]=mid.x;
-                                                       gLoc[1]=mid.y;
-                                                       gLoc[2]=mid.z;
-                                                       vel[0]=0;
-                                                       vel[1]=0;
-                                                       vel[2]=0;
-                                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                                       if(terrain.getOpacity(position[i].x,position[i].z)>.2)OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                                       else OPENAL_SetVolume(channels[whichsound], 32*findLengthfast(&bounceness));
-                                                       OPENAL_SetPaused(channels[whichsound], false);
+                                                       emit_sound_at(whichsound, mid,
+                                                                     findLengthfast(&bounceness)
+                                                                     * (terrain.getOpacity(position[i].x,position[i].z) > .2
+                                                                        ? 128.
+                                                                        : 32.));
                                                }
                                                tippoint[i]+=(mid-oldmid)*20;
                                        }
-                                       /*XYZ mid;
-                                       mid=position[i]+tippoint[i];
-                                       mid/=2;
-                                       if(position[i].y<terrain.getHeightExtrude(mid.x,mid.z,position[i].x,position[i].z)){
-                                       hitsomething[i]=1;
-                                       position[i].y=terrain.getHeightExtrude(mid.x,mid.z,position[i].x,position[i].z);
-
-                                       terrainnormal=terrain.getNormal(mid.x,mid.z);
-                                       ReflectVector(&velocity[i],&terrainnormal);
-                                       position[i]+=terrainnormal*.002;
-                                       bounceness=terrainnormal*findLength(&velocity[i])*(abs(normaldotproduct(velocity[i],terrainnormal)));
-                                       if(findLengthfast(&velocity[i])<findLengthfast(&bounceness))bounceness=0;
-                                       frictionness=abs(normaldotproduct(velocity[i],terrainnormal));
-                                       velocity[i]-=bounceness;
-                                       if(1-friction*frictionness>0)velocity[i]*=1-friction*frictionness;
-                                       else velocity[i]=0;
-                                       if(terrain.getOpacity(mid.x,mid.z)<.2)velocity[i]+=bounceness*elasticity*.3;
-                                       else velocity[i]+=bounceness*elasticity;
-
-                                       if(findLengthfast(&bounceness)>1){
-                                       float gLoc[3];
-                                       float vel[3];
-                                       int whichsound;
-                                       if(terrain.getOpacity(mid.x,mid.z)>.2){
-                                       if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
-                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
-                                       }
-                                       else whichsound=footstepsound+abs(Random()%2);
-                                       gLoc[0]=position[i].x;
-                                       gLoc[1]=position[i].y;
-                                       gLoc[2]=position[i].z;
-                                       vel[0]=0;
-                                       vel[1]=0;
-                                       vel[2]=0;
-                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                       if(terrain.getOpacity(position[i].x,position[i].z)>.2)OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                       else OPENAL_SetVolume(channels[whichsound], 32*findLengthfast(&bounceness));
-                                       OPENAL_SetPaused(channels[whichsound], false);
-                                       }
-                                       }
-
-                                       if(tippoint[i].y<terrain.getHeightExtrude(mid.x,mid.z,tippoint[i].x,tippoint[i].z)){
-                                       hitsomething[i]=1;
-                                       tippoint[i].y=terrain.getHeightExtrude(mid.x,mid.z,tippoint[i].x,tippoint[i].z);
-
-                                       terrainnormal=terrain.getNormal(mid.x,mid.z);
-                                       ReflectVector(&tipvelocity[i],&terrainnormal);
-                                       tippoint[i]+=terrainnormal*.002;
-                                       bounceness=terrainnormal*findLength(&tipvelocity[i])*(abs(normaldotproduct(tipvelocity[i],terrainnormal)));
-                                       if(findLengthfast(&tipvelocity[i])<findLengthfast(&bounceness))bounceness=0;
-                                       frictionness=abs(normaldotproduct(tipvelocity[i],terrainnormal));
-                                       tipvelocity[i]-=bounceness;
-                                       if(1-friction*frictionness>0)tipvelocity[i]*=1-friction*frictionness;
-                                       else tipvelocity[i]=0;
-                                       if(terrain.getOpacity(mid.x,mid.z)<.2)tipvelocity[i]+=bounceness*elasticity*.3;
-                                       else tipvelocity[i]+=bounceness*elasticity;
-
-                                       if(findLengthfast(&bounceness)>1){
-                                       float gLoc[3];
-                                       float vel[3];
-                                       int whichsound;
-                                       if(terrain.getOpacity(mid.x,mid.z)>.2){
-                                       if(type[i]==staff)whichsound=footstepsound3+abs(Random()%2);
-                                       if(type[i]!=staff)whichsound=clank1sound+abs(Random()%4);
-                                       }
-                                       else whichsound=footstepsound+abs(Random()%2);
-                                       gLoc[0]=tippoint[i].x;
-                                       gLoc[1]=tippoint[i].y;
-                                       gLoc[2]=tippoint[i].z;
-                                       vel[0]=0;
-                                       vel[1]=0;
-                                       vel[2]=0;
-                                       PlaySoundEx( whichsound, samp[whichsound], NULL, true);
-                                       OPENAL_3D_SetAttributes(channels[whichsound], gLoc, vel);
-                                       if(terrain.getOpacity(tippoint[i].x,tippoint[i].z)>.2)OPENAL_SetVolume(channels[whichsound], 128*findLengthfast(&bounceness));
-                                       else OPENAL_SetVolume(channels[whichsound], 32*findLengthfast(&bounceness));
-                                       OPENAL_SetPaused(channels[whichsound], false);
-                                       }
-                                       }*/
-
-                                       //Fix terrain edge collision
-                                       /*start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       if(whichhit!=-1){
-                                       XYZ tippoi,posit;
-                                       tippoi=tippoint[i];
-                                       posit=position[i];
-
-
-                                       while(whichhit!=-1){
-                                       position[i].y+=.1;
-                                       tippoint[i].y+=.1;
-                                       velocity[i].y+=.1;
-                                       tipvelocity[i].y+=.1;
-                                       start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       if(whichhit!=-1)
-                                       closestpoint=colpoint*terrain.scale;
-                                       }
-                                       position[i].y-=.1;
-                                       tippoint[i].y-=.1;
-                                       velocity[i].y-=.1;
-                                       tipvelocity[i].y-=.1;
-                                       start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       while(whichhit!=-1){
-                                       position[i].y+=.01;
-                                       tippoint[i].y+=.01;
-                                       velocity[i].y+=.01;
-                                       tipvelocity[i].y+=.01;
-                                       start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       if(whichhit!=-1)
-                                       closestpoint=colpoint*terrain.scale;
-                                       }
-                                       }*/
-                                       /*if(whichhit!=-1){
-                                       whichhit=terrain.lineTerrain(end,start,&closestswordpoint);
-                                       if(whichhit!=-1){
-                                       colpoint=(closestswordpoint*terrain.scale+colpoint*terrain.scale)/2;
-                                       proportion=findDistance(&tippoint[i],&colpoint)/findDistance(&position[i],&tippoint[i]);
-                                       if(proportion<=1){
-                                       while(whichhit!=-1){
-                                       position[i].y+=.1*proportion;
-                                       tippoint[i].y+=.1*(1-proportion);
-                                       velocity[i].y+=.1*proportion;
-                                       tipvelocity[i].y+=.1*(1-proportion);
-                                       start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       }
-                                       position[i].y-=.1*proportion;
-                                       tippoint[i].y-=.1*(1-proportion);
-                                       velocity[i].y-=.1*proportion;
-                                       tipvelocity[i].y-=.1*(1-proportion);
-                                       start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       while(whichhit!=-1){
-                                       position[i].y+=.01*proportion;
-                                       tippoint[i].y+=.01*(1-proportion);
-                                       velocity[i].y+=.01*proportion;
-                                       tipvelocity[i].y+=.01*(1-proportion);
-                                       start=position[i];
-                                       end=tippoint[i];
-                                       whichhit=terrain.lineTerrain(start,end,&colpoint);
-                                       }
-                                       }
-                                       }
-                                       }
-                                       */
                                        //Gravity
                                        velocity[i].y+=gravity*multiplier;
                                        tipvelocity[i].y+=gravity*multiplier;
@@ -1083,7 +774,7 @@ void       Weapons::DoStuff(){
                                bloodloc.y-=.05;
                                if(bloodtoggle){
                                        bloodvel=0;
-                                       sprites.MakeSprite(bloodsprite, bloodloc,bloodvel, 1,1,1, .03, 1);
+                                       Sprite::MakeSprite(bloodsprite, bloodloc,bloodvel, 1,1,1, .03, 1);
                                }
                        }
                }
@@ -1102,9 +793,9 @@ void       Weapons::DoStuff(){
                                                normalrot.y=1;
                                        }
                                }
-                               sprites.MakeSprite(weaponflamesprite, position[i]+tippoint[i]*(((float)abs(Random()%100))/600+.05),normalrot, 1,1,1, (.6+(float)abs(Random()%100)/200-.25)*1/3, 1);
-                               sprites.speed[sprites.numsprites-1]=4;
-                               sprites.alivetime[sprites.numsprites-1]=.3;
+                               Sprite::MakeSprite(weaponflamesprite, position[i]+tippoint[i]*(((float)abs(Random()%100))/600+.05),normalrot, 1,1,1, (.6+(float)abs(Random()%100)/200-.25)*1/3, 1);
+                               Sprite::setLastSpriteSpeed(4);
+                               Sprite::setLastSpriteAlivetime(.3);
                        }
                }
 
@@ -1117,9 +808,9 @@ void       Weapons::DoStuff(){
                                if(Random()%50==0&&findDistancefast(&position[i],&viewer)>80){
                                        XYZ shinepoint;
                                        shinepoint=position[i]+(tippoint[i]-position[i])*(((float)abs(Random()%100))/100);
-                                       sprites.MakeSprite(weaponshinesprite, shinepoint,normalrot, 1,1,1, (.1+(float)abs(Random()%100)/200-.25)*1/3*fast_sqrt(findDistance(&shinepoint,&viewer)), 1);
-                                       sprites.speed[sprites.numsprites-1]=4;
-                                       sprites.alivetime[sprites.numsprites-1]=.3;
+                                       Sprite::MakeSprite(weaponshinesprite, shinepoint,normalrot, 1,1,1, (.1+(float)abs(Random()%100)/200-.25)*1/3*fast_sqrt(findDistance(&shinepoint,&viewer)), 1);
+                                       Sprite::setLastSpriteSpeed(4);
+                                       Sprite::setLastSpriteAlivetime(.3);
                                }
                        }
                }
@@ -1278,13 +969,13 @@ int Weapons::Draw()
                        XYZ nothingpoint;
                        nothingpoint=0;
                        shinepoint=position[i];
-                       sprites.MakeSprite(weaponshinesprite, shinepoint,nothingpoint, 1,1,1,multiplier*2, 1);
-                       sprites.speed[sprites.numsprites-1]=4;
-                       sprites.alivetime[sprites.numsprites-1]=.3;
+                       Sprite::MakeSprite(weaponshinesprite, shinepoint,nothingpoint, 1,1,1,multiplier*2, 1);
+                       Sprite::speed[Sprite::numsprites-1]=4;
+                       Sprite::alivetime[Sprite::numsprites-1]=.3;
                        shinepoint=tippoint[i];
-                       sprites.MakeSprite(weaponshinesprite, shinepoint,nothingpoint, 1,1,1,multiplier*2, 1);
-                       sprites.speed[sprites.numsprites-1]=4;
-                       sprites.alivetime[sprites.numsprites-1]=.3;*/
+                       Sprite::MakeSprite(weaponshinesprite, shinepoint,nothingpoint, 1,1,1,multiplier*2, 1);
+                       Sprite::speed[Sprite::numsprites-1]=4;
+                       Sprite::alivetime[Sprite::numsprites-1]=.3;*/
                }
        }
        return 0;
index e11a424c7649e319c5cf87200afc0e0cc4598473..c6f4560bf20cc28f70e7315b7ffdbaf88a1c38c8 100644 (file)
@@ -28,9 +28,8 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "Quaternions.h"
 #include "Skeleton.h"
 #include "Models.h"
-#include "Constants.h"
 #include "Terrain.h"
-#include "Sprites.h"
+#include "Sprite.h"
 #include "Person.h"
 #include <cmath>
 
@@ -114,4 +113,5 @@ public:
        ~Weapons();
 };
 
+extern Weapons weapons;
 #endif
index 55a71900291a25e023f2347b47f5771d06ee88ce..36bdf4a0c0cee6d840986a0db8c31a10a7b7686b 100644 (file)
@@ -47,16 +47,16 @@ static AppTime g_appTime;
 void CopyCStringToPascal( const char* src, unsigned char dst[256])
 {
        int len = strlen( src);
-       dst[ 0] = len;
+       dst[0] = len;
        memcpy( dst + 1, src, len);
 }
 
 
 void CopyPascalStringToC( const unsigned char* src, char* dst)
 {
-       int len = src[ 0];
+       int len = src[0];
        memcpy( dst, src + 1, len);
-       dst[ len] = 0;
+       dst[len] = 0;
 }
 
 
index e598863b4151e066ab4b8fd9753b339e27fd05e4..4cf515e6270abca56c6fe9eb871c083022bc6096 100644 (file)
@@ -42,7 +42,6 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 typedef bool Boolean;
 
-
 struct Point
 {
        short v;
@@ -99,16 +98,16 @@ char* ConvertFileName( const char* orgfilename);
 char* ConvertFileName( const char* orgfilename, const char* junk);
 
 
-#define fopen( a, b) fopen( ConvertFileName( a), b);
+#define fopen(a, b) fopen(ConvertFileName(a), b);
 
-inline float abs( float f)
+inline float abs(float f)
 {
        if (f < 0)
                return -f;
        return f;
 }
 
-inline double abs( double f)
+inline double abs(double f)
 {
        if (f < 0)
                return -f;
diff --git a/Source/WinInput.cpp b/Source/WinInput.cpp
deleted file mode 100644 (file)
index d42ae78..0000000
+++ /dev/null
@@ -1,1008 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-/**> HEADER FILES <**/
-#include "WinInput.h"
-
-#ifdef WIN32
-#include <string.h>
-#else
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#endif
-
-extern bool keyboardfrozen;
-extern bool buttons[3];
-/********************> IsKeyDown() <*****/
-Boolean        IsKeyDown( unsigned char *keyMap, unsigned short theKey )
-{
-       if(keyboardfrozen)return 0;
-       if(theKey< 0x80 /*1000*/){
-               static long     keyMapIndex;
-               static Boolean  isKeyDown;
-               static short    bitToCheck;
-
-               // Calculate the key map index
-               keyMapIndex = keyMap[theKey/8];
-
-               // Calculate the individual bit to check
-               bitToCheck = theKey%8;
-
-               // Check the status of the key
-               isKeyDown = ( keyMapIndex >> bitToCheck ) & 0x01;
-
-               // Return the status of the key
-               return isKeyDown;
-       }
-       else if(theKey==MAC_MOUSEBUTTON1)
-               return buttons[0];
-       else if(theKey==MAC_MOUSEBUTTON2)
-               return buttons[1];
-
-       return 0;
-}
-
-unsigned short         CharToKey(const char* which)
-{
-       // alphabetic keys
-       if(!strcasecmp(which,"a")){
-               return MAC_A_KEY;
-       }
-       if(!strcasecmp(which,"b")){
-               return MAC_B_KEY;
-       }
-       if(!strcasecmp(which,"c")){
-               return MAC_C_KEY;
-       }
-       if(!strcasecmp(which,"d")){
-               return MAC_D_KEY;
-       }
-       if(!strcasecmp(which,"e")){
-               return MAC_E_KEY;
-       }
-       if(!strcasecmp(which,"f")){
-               return MAC_F_KEY;
-       }
-       if(!strcasecmp(which,"g")){
-               return MAC_G_KEY;
-       }
-       if(!strcasecmp(which,"h")){
-               return MAC_H_KEY;
-       }
-       if(!strcasecmp(which,"i")){
-               return MAC_I_KEY;
-       }
-       if(!strcasecmp(which,"j")){
-               return MAC_J_KEY;
-       }
-       if(!strcasecmp(which,"k")){
-               return MAC_K_KEY;
-       }
-       if(!strcasecmp(which,"l")){
-               return MAC_L_KEY;
-       }
-       if(!strcasecmp(which,"m")){
-               return MAC_M_KEY;
-       }
-       if(!strcasecmp(which,"n")){
-               return MAC_N_KEY;
-       }
-       if(!strcasecmp(which,"o")){
-               return MAC_O_KEY;
-       }
-       if(!strcasecmp(which,"p")){
-               return MAC_P_KEY;
-       }
-       if(!strcasecmp(which,"q")){
-               return MAC_Q_KEY;
-       }
-       if(!strcasecmp(which,"r")){
-               return MAC_R_KEY;
-       }
-       if(!strcasecmp(which,"s")){
-               return MAC_S_KEY;
-       }
-       if(!strcasecmp(which,"t")){
-               return MAC_T_KEY;
-       }
-       if(!strcasecmp(which,"u")){
-               return MAC_U_KEY;
-       }
-       if(!strcasecmp(which,"v")){
-               return MAC_V_KEY;
-       }
-       if(!strcasecmp(which,"w")){
-               return MAC_W_KEY;
-       }
-       if(!strcasecmp(which,"x")){
-               return MAC_X_KEY;
-       }
-       if(!strcasecmp(which,"y")){
-               return MAC_Y_KEY;
-       }
-       if(!strcasecmp(which,"z")){
-               return MAC_Z_KEY;
-       }
-
-       // keypad keys
-       if(!strcasecmp(which,"KP0")){
-               return MAC_NUMPAD_0_KEY;
-       }
-       if(!strcasecmp(which,"KP1")){
-               return MAC_NUMPAD_1_KEY;
-       }
-       if(!strcasecmp(which,"KP2")){
-               return MAC_NUMPAD_2_KEY;
-       }
-       if(!strcasecmp(which,"KP3")){
-               return MAC_NUMPAD_3_KEY;
-       }
-       if(!strcasecmp(which,"KP4")){
-               return MAC_NUMPAD_4_KEY;
-       }
-       if(!strcasecmp(which,"KP5")){
-               return MAC_NUMPAD_5_KEY;
-       }
-       if(!strcasecmp(which,"KP6")){
-               return MAC_NUMPAD_6_KEY;
-       }
-       if(!strcasecmp(which,"KP7")){
-               return MAC_NUMPAD_7_KEY;
-       }
-       if(!strcasecmp(which,"KP8")){
-               return MAC_NUMPAD_8_KEY;
-       }
-       if(!strcasecmp(which,"KP9")){
-               return MAC_NUMPAD_9_KEY;
-       }
-
-       // enter
-       if(!strcasecmp(which,"enter")){
-               return MAC_ENTER_KEY;
-       }
-
-       // number keys
-       if(!strcasecmp(which,"0")){
-               return MAC_0_KEY;
-       }
-       if(!strcasecmp(which,"1")){
-               return MAC_1_KEY;
-       }
-       if(!strcasecmp(which,"2")){
-               return MAC_2_KEY;
-       }
-       if(!strcasecmp(which,"3")){
-               return MAC_3_KEY;
-       }
-       if(!strcasecmp(which,"4")){
-               return MAC_4_KEY;
-       }
-       if(!strcasecmp(which,"5")){
-               return MAC_5_KEY;
-       }
-       if(!strcasecmp(which,"6")){
-               return MAC_6_KEY;
-       }
-       if(!strcasecmp(which,"7")){
-               return MAC_7_KEY;
-       }
-       if(!strcasecmp(which,"8")){
-               return MAC_8_KEY;
-       }
-       if(!strcasecmp(which,"9")){
-               return MAC_9_KEY;
-       }
-
-       // function keys
-       if(!strcasecmp(which,"F1")){
-               return MAC_F1_KEY;
-       }
-       if(!strcasecmp(which,"F2")){
-               return MAC_F2_KEY;
-       }
-       if(!strcasecmp(which,"F3")){
-               return MAC_F3_KEY;
-       }
-       if(!strcasecmp(which,"F4")){
-               return MAC_F4_KEY;
-       }
-       if(!strcasecmp(which,"F5")){
-               return MAC_F5_KEY;
-       }
-       if(!strcasecmp(which,"F6")){
-               return MAC_F6_KEY;
-       }
-       if(!strcasecmp(which,"F7")){
-               return MAC_F7_KEY;
-       }
-       if(!strcasecmp(which,"F8")){
-               return MAC_F8_KEY;
-       }
-       if(!strcasecmp(which,"F9")){
-               return MAC_F9_KEY;
-       }
-       if(!strcasecmp(which,"F10")){
-               return MAC_F10_KEY;
-       }
-       if(!strcasecmp(which,"F11")){
-               return MAC_F11_KEY;
-       }
-       if(!strcasecmp(which,"F12")){
-               return MAC_F12_KEY;
-       }
-
-       // escape
-       if(!strcasecmp(which,"escape")){
-               return MAC_ESCAPE_KEY;
-       }
-       if(!strcasecmp(which,"backspace")){
-               return MAC_DELETE_KEY;
-       }
-       if(!strcasecmp(which,"tab")){
-               return MAC_TAB_KEY;
-       }
-       if(!strcasecmp(which,"`")){
-               return MAC_TILDE_KEY;
-       }
-       if(!strcasecmp(which,"caps_lock")){
-               return MAC_CAPS_LOCK_KEY;
-       }
-//     if(which==){
-//             return "";
-//     }
-       if(!strcasecmp(which,"command")){
-               return MAC_COMMAND_KEY;
-       }
-       if(!strcasecmp(which,"option")){
-               return MAC_OPTION_KEY;
-       }
-       if(!strcasecmp(which,"delete")){
-               return MAC_DEL_KEY;
-       }
-       if(!strcasecmp(which,"insert")){
-               return MAC_INSERT_KEY;
-       }
-       if(!strcasecmp(which,"home")){
-               return MAC_HOME_KEY;
-       }
-       if(!strcasecmp(which,"end")){
-               return MAC_END_KEY;
-       }
-       if(!strcasecmp(which,"page_up")){
-               return MAC_PAGE_UP_KEY;
-       }
-       if(!strcasecmp(which,"page_down")){
-               return MAC_PAGE_DOWN_KEY;
-       }
-       if(!strcasecmp(which,"clear")){
-               return MAC_NUMPAD_CLEAR_KEY;
-       }
-
-       if(!strcasecmp(which,"control")){
-               return MAC_CONTROL_KEY;
-       }
-       if(!strcasecmp(which,"return")){
-               return MAC_RETURN_KEY;
-       }
-       if(!strcasecmp(which,"space")){
-               return MAC_SPACE_KEY;
-       }
-       if(!strcasecmp(which,"shift")){
-               return MAC_SHIFT_KEY;
-       }
-       if(!strcasecmp(which,"uparrow")){
-               return MAC_ARROW_UP_KEY;
-       }
-       if(!strcasecmp(which,"downarrow")){
-               return MAC_ARROW_DOWN_KEY;
-       }
-       if(!strcasecmp(which,"leftarrow")){
-               return MAC_ARROW_LEFT_KEY;
-       }
-       if(!strcasecmp(which,"rightarrow")){
-               return MAC_ARROW_RIGHT_KEY;
-       }
-       if(!strcasecmp(which,"mouse1")){
-               return MAC_MOUSEBUTTON1;
-       }
-       if(!strcasecmp(which,"mouse2")){
-               return MAC_MOUSEBUTTON2;
-       }
-       if(!strcasecmp(which,"+")){
-               return MAC_NUMPAD_PLUS_KEY;
-       }
-       if(!strcasecmp(which,"*")){
-               return MAC_NUMPAD_ASTERISK_KEY;
-       }
-       if(!strcasecmp(which,"/")){
-               return MAC_SLASH_KEY;
-       }
-       if(!strcasecmp(which,"\\")){
-               return MAC_BACKSLASH_KEY;
-       }
-       if(!strcasecmp(which,"[")){
-               return MAC_LEFTBRACKET_KEY;
-       }
-       if(!strcasecmp(which,"]")){
-               return MAC_RIGHTBRACKET_KEY;
-       }
-       if(!strcasecmp(which,".")){
-               return MAC_PERIOD_KEY;
-       }
-       if(!strcasecmp(which,",")){
-               return MAC_COMMA_KEY;
-       }
-       if(!strcasecmp(which,"\"")){
-               return MAC_APOSTROPHE_KEY;
-       }
-       if(!strcasecmp(which,";")){
-               return MAC_SEMICOLON_KEY;
-       }
-       return UNKNOWN_KEY;
-}
-
-const char*    KeyToChar(unsigned short which)
-{
-       static int i;
-
-       // alphabetic keys
-       if(which==MAC_A_KEY){
-               return "a";
-       }
-       if(which==MAC_B_KEY){
-               return "b";
-       }
-       if(which==MAC_C_KEY){
-               return "c";
-       }
-       if(which==MAC_D_KEY){
-               return "d";
-       }
-       if(which==MAC_E_KEY){
-               return "e";
-       }
-       if(which==MAC_F_KEY){
-               return "f";
-       }
-       if(which==MAC_G_KEY){
-               return "g";
-       }
-       if(which==MAC_H_KEY){
-               return "h";
-       }
-       if(which==MAC_I_KEY){
-               return "i";
-       }
-       if(which==MAC_J_KEY){
-               return "j";
-       }
-       if(which==MAC_K_KEY){
-               return "k";
-       }
-       if(which==MAC_L_KEY){
-               return "l";
-       }
-       if(which==MAC_M_KEY){
-               return "m";
-       }
-       if(which==MAC_N_KEY){
-               return "n";
-       }
-       if(which==MAC_O_KEY){
-               return "o";
-       }
-       if(which==MAC_P_KEY){
-               return "p";
-       }
-       if(which==MAC_Q_KEY){
-               return "q";
-       }
-       if(which==MAC_R_KEY){
-               return "r";
-       }
-       if(which==MAC_S_KEY){
-               return "s";
-       }
-       if(which==MAC_T_KEY){
-               return "t";
-       }
-       if(which==MAC_U_KEY){
-               return "u";
-       }
-       if(which==MAC_V_KEY){
-               return "v";
-       }
-       if(which==MAC_W_KEY){
-               return "w";
-       }
-       if(which==MAC_X_KEY){
-               return "x";
-       }
-       if(which==MAC_Y_KEY){
-               return "y";
-       }
-       if(which==MAC_Z_KEY){
-               return "z";
-       }
-
-       // keypad keys
-       if(which==MAC_NUMPAD_1_KEY){
-               return "KP1";
-       }
-       if(which==MAC_NUMPAD_2_KEY){
-               return "KP2";
-       }
-       if(which==MAC_NUMPAD_3_KEY){
-               return "KP3";
-       }
-       if(which==MAC_NUMPAD_4_KEY){
-               return "KP4";
-       }
-       if(which==MAC_NUMPAD_5_KEY){
-               return "KP5";
-       }
-       if(which==MAC_NUMPAD_6_KEY){
-               return "KP6";
-       }
-       if(which==MAC_NUMPAD_7_KEY){
-               return "KP7";
-       }
-       if(which==MAC_NUMPAD_8_KEY){
-               return "KP8";
-       }
-       if(which==MAC_NUMPAD_9_KEY){
-               return "KP9";
-       }
-       if(which==MAC_NUMPAD_0_KEY){
-               return "KP0";
-       }
-
-       // enter
-       if(which==MAC_ENTER_KEY){
-               return "enter";
-       }
-
-       // number keys
-       if(which==MAC_1_KEY){
-               return "1";
-       }
-       if(which==MAC_2_KEY){
-               return "2";
-       }
-       if(which==MAC_3_KEY){
-               return "3";
-       }
-       if(which==MAC_4_KEY){
-               return "4";
-       }
-       if(which==MAC_5_KEY){
-               return "5";
-       }
-       if(which==MAC_6_KEY){
-               return "6";
-       }
-       if(which==MAC_7_KEY){
-               return "7";
-       }
-       if(which==MAC_8_KEY){
-               return "8";
-       }
-       if(which==MAC_9_KEY){
-               return "9";
-       }
-       if(which==MAC_0_KEY){
-               return "0";
-       }
-
-       // function keys
-       if(which==MAC_F1_KEY){
-               return "F1";
-       }
-       if(which==MAC_F2_KEY){
-               return "F2";
-       }
-       if(which==MAC_F3_KEY){
-               return "F3";
-       }
-       if(which==MAC_F4_KEY){
-               return "F4";
-       }
-       if(which==MAC_F5_KEY){
-               return "F5";
-       }
-       if(which==MAC_F6_KEY){
-               return "F6";
-       }
-       if(which==MAC_F7_KEY){
-               return "F7";
-       }
-       if(which==MAC_F8_KEY){
-               return "F8";
-       }
-       if(which==MAC_F9_KEY){
-               return "F9";
-       }
-       if(which==MAC_F10_KEY){
-               return "F10";
-       }
-       if(which==MAC_F11_KEY){
-               return "F11";
-       }
-       if(which==MAC_F12_KEY){
-               return "F12";
-       }
-
-       // escape
-       if(which==MAC_ESCAPE_KEY){
-               return "escape";
-       }
-       if(which==MAC_DELETE_KEY){
-               return "backspace";
-       }
-       if(which==MAC_TAB_KEY){
-               return "tab";
-       }
-       if(which==MAC_TILDE_KEY){
-               return "`";
-       }
-       if(which==MAC_CAPS_LOCK_KEY){
-               return "caps_lock";
-       }
-       if(which==MAC_COMMAND_KEY){
-               return "command";
-       }
-       if(which==MAC_OPTION_KEY){
-               return "option";
-       }
-       if(which==MAC_DEL_KEY){
-               return "delete";
-       }
-       if(which==MAC_INSERT_KEY){
-               return "insert";
-       }
-       if(which==MAC_HOME_KEY){
-               return "home";
-       }
-       if(which==MAC_END_KEY){
-               return "end";
-       }
-       if(which==MAC_PAGE_UP_KEY){
-               return "page_up";
-       }
-       if(which==MAC_PAGE_DOWN_KEY){
-               return "page_down";
-       }
-       if(which==MAC_NUMPAD_CLEAR_KEY){
-               return "clear";
-       }
-       if(which==MAC_CONTROL_KEY){
-               return "control";
-       }
-       if(which==MAC_SPACE_KEY){
-               return "space";
-       }
-       if(which==MAC_RETURN_KEY){
-               return "return";
-       }
-       if(which==MAC_SHIFT_KEY){
-               return "shift";
-       }
-       if(which==MAC_ARROW_UP_KEY){
-               return "uparrow";
-       }
-       if(which==MAC_ARROW_DOWN_KEY){
-               return "downarrow";
-       }
-       if(which==MAC_ARROW_LEFT_KEY){
-               return "leftarrow";
-       }
-       if(which==MAC_ARROW_RIGHT_KEY){
-               return "rightarrow";
-       }
-       if(which==MAC_MOUSEBUTTON1){
-               return "mouse1";
-       }
-       if(which==MAC_MOUSEBUTTON2){
-               return "mouse2";
-       }
-       if(which==MAC_ARROW_RIGHT_KEY){
-               return "rightarrow";
-       }
-       if(which==MAC_MINUS_KEY||which==MAC_NUMPAD_MINUS_KEY){
-               return "-";
-       }
-       if(which==MAC_PLUS_KEY||which==MAC_NUMPAD_EQUALS_KEY){
-               return "=";
-       }
-       if(which==MAC_NUMPAD_PLUS_KEY){
-               return "+";
-       }
-       if(which==MAC_NUMPAD_ASTERISK_KEY){
-               return "*";
-       }
-       if(which==MAC_SLASH_KEY||which==MAC_NUMPAD_SLASH_KEY){
-               return "/";
-       }
-       if(which==MAC_BACKSLASH_KEY){
-               return "\\";
-       }
-       if(which==MAC_LEFTBRACKET_KEY){
-               return "[";
-       }
-       if(which==MAC_RIGHTBRACKET_KEY){
-               return "]";
-       }
-       if(which==MAC_PERIOD_KEY||which==MAC_NUMPAD_PERIOD_KEY){
-               return ".";
-       }
-       if(which==MAC_COMMA_KEY){
-               return ",";
-       }
-       if(which==MAC_APOSTROPHE_KEY){
-               return "\"";
-       }
-       if(which==MAC_SEMICOLON_KEY){
-               return ";";
-       }
-       return "unknown";
-}
-
-char   KeyToSingleChar(unsigned short which)
-{
-       static int i;
-
-       if(which==MAC_A_KEY){
-               return 'a';
-       }
-       if(which==MAC_B_KEY){
-               return 'b';
-       }
-       if(which==MAC_C_KEY){
-               return 'c';
-       }
-       if(which==MAC_D_KEY){
-               return 'd';
-       }
-       if(which==MAC_E_KEY){
-               return 'e';
-       }
-       if(which==MAC_F_KEY){
-               return 'f';
-       }
-       if(which==MAC_G_KEY){
-               return 'g';
-       }
-       if(which==MAC_H_KEY){
-               return 'h';
-       }
-       if(which==MAC_I_KEY){
-               return 'i';
-       }
-       if(which==MAC_J_KEY){
-               return 'j';
-       }
-       if(which==MAC_K_KEY){
-               return 'k';
-       }
-       if(which==MAC_L_KEY){
-               return 'l';
-       }
-       if(which==MAC_M_KEY){
-               return 'm';
-       }
-       if(which==MAC_N_KEY){
-               return 'n';
-       }
-       if(which==MAC_O_KEY){
-               return 'o';
-       }
-       if(which==MAC_P_KEY){
-               return 'p';
-       }
-       if(which==MAC_Q_KEY){
-               return 'q';
-       }
-       if(which==MAC_R_KEY){
-               return 'r';
-       }
-       if(which==MAC_S_KEY){
-               return 's';
-       }
-       if(which==MAC_T_KEY){
-               return 't';
-       }
-       if(which==MAC_U_KEY){
-               return 'u';
-       }
-       if(which==MAC_V_KEY){
-               return 'v';
-       }
-       if(which==MAC_W_KEY){
-               return 'w';
-       }
-       if(which==MAC_X_KEY){
-               return 'x';
-       }
-       if(which==MAC_Y_KEY){
-               return 'y';
-       }
-       if(which==MAC_Z_KEY){
-               return 'z';
-       }
-       if(which==MAC_NUMPAD_1_KEY){
-               return '1';
-       }
-       if(which==MAC_NUMPAD_2_KEY){
-               return '2';
-       }
-       if(which==MAC_NUMPAD_3_KEY){
-               return '3';
-       }
-       if(which==MAC_NUMPAD_4_KEY){
-               return '4';
-       }
-       if(which==MAC_NUMPAD_5_KEY){
-               return '5';
-       }
-       if(which==MAC_NUMPAD_6_KEY){
-               return '6';
-       }
-       if(which==MAC_NUMPAD_7_KEY){
-               return '7';
-       }
-       if(which==MAC_NUMPAD_8_KEY){
-               return '8';
-       }
-       if(which==MAC_NUMPAD_9_KEY){
-               return '9';
-       }
-       if(which==MAC_NUMPAD_0_KEY){
-               return '0';
-       }
-       if(which==MAC_1_KEY){
-               return '1';
-       }
-       if(which==MAC_2_KEY){
-               return '2';
-       }
-       if(which==MAC_3_KEY){
-               return '3';
-       }
-       if(which==MAC_4_KEY){
-               return '4';
-       }
-       if(which==MAC_5_KEY){
-               return '5';
-       }
-       if(which==MAC_6_KEY){
-               return '6';
-       }
-       if(which==MAC_7_KEY){
-               return '7';
-       }
-       if(which==MAC_8_KEY){
-               return '8';
-       }
-       if(which==MAC_9_KEY){
-               return '9';
-       }
-       if(which==MAC_0_KEY){
-               return '0';
-       }
-       if(which==MAC_SPACE_KEY){
-               return ' ';
-       }
-       if(which==MAC_MINUS_KEY||which==MAC_NUMPAD_MINUS_KEY){
-               return '-';
-       }
-       if(which==MAC_PLUS_KEY||which==MAC_NUMPAD_EQUALS_KEY){
-               return '=';
-       }
-       if(which==MAC_NUMPAD_PLUS_KEY){
-               return '+';
-       }
-       if(which==MAC_NUMPAD_ASTERISK_KEY){
-               return '*';
-       }
-       if(which==MAC_SLASH_KEY||which==MAC_NUMPAD_SLASH_KEY){
-               return '/';
-       }
-       if(which==MAC_BACKSLASH_KEY){
-               return '\\';
-       }
-       if(which==MAC_LEFTBRACKET_KEY){
-               return '[';
-       }
-       if(which==MAC_RIGHTBRACKET_KEY){
-               return ']';
-       }
-       if(which==MAC_PERIOD_KEY||which==MAC_NUMPAD_PERIOD_KEY){
-               return '.';
-       }
-       if(which==MAC_COMMA_KEY){
-               return ',';
-       }
-       if(which==MAC_APOSTROPHE_KEY){
-               return '\'';
-       }
-       if(which==MAC_SEMICOLON_KEY){
-               return ';';
-       }
-       return '\0';
-}
-
-char   Shift(char which)
-{
-       static int i;
-
-       if(which=='a'){
-               return 'A';
-       }
-       if(which=='b'){
-               return 'B';
-       }
-       if(which=='c'){
-               return 'C';
-       }
-       if(which=='d'){
-               return 'D';
-       }
-       if(which=='e'){
-               return 'E';
-       }
-       if(which=='f'){
-               return 'F';
-       }
-       if(which=='g'){
-               return 'G';
-       }
-       if(which=='h'){
-               return 'H';
-       }
-       if(which=='e'){
-               return 'E';
-       }
-       if(which=='f'){
-               return 'F';
-       }
-       if(which=='g'){
-               return 'G';
-       }
-       if(which=='h'){
-               return 'H';
-       }
-       if(which=='i'){
-               return 'I';
-       }
-       if(which=='j'){
-               return 'J';
-       }
-       if(which=='k'){
-               return 'K';
-       }
-       if(which=='l'){
-               return 'L';
-       }
-       if(which=='m'){
-               return 'M';
-       }
-       if(which=='n'){
-               return 'N';
-       }
-       if(which=='o'){
-               return 'O';
-       }
-       if(which=='p'){
-               return 'P';
-       }
-       if(which=='q'){
-               return 'Q';
-       }
-       if(which=='r'){
-               return 'R';
-       }
-       if(which=='s'){
-               return 'S';
-       }
-       if(which=='t'){
-               return 'T';
-       }
-       if(which=='u'){
-               return 'U';
-       }
-       if(which=='v'){
-               return 'V';
-       }
-       if(which=='w'){
-               return 'W';
-       }
-       if(which=='x'){
-               return 'X';
-       }
-       if(which=='y'){
-               return 'Y';
-       }
-       if(which=='z'){
-               return 'Z';
-       }
-       if(which=='1'){
-               return '!';
-       }
-       if(which=='2'){
-               return '@';
-       }
-       if(which=='3'){
-               return '#';
-       }
-       if(which=='4'){
-               return '$';
-       }
-       if(which=='5'){
-               return '%';
-       }
-       if(which=='6'){
-               return '^';
-       }
-       if(which=='7'){
-               return '&';
-       }
-       if(which=='8'){
-               return '*';
-       }
-       if(which=='9'){
-               return '(';
-       }
-       if(which=='0'){
-               return ')';
-       }
-       if(which=='-'){
-               return '_';
-       }
-       if(which=='='){
-               return '+';
-       }
-       if(which=='['){
-               return '{';
-       }
-       if(which==']'){
-               return '}';
-       }
-       if(which=='\\'){
-               return '|';
-       }
-       if(which=='.'){
-               return '>';
-       }
-       if(which==','){
-               return '<';
-       }
-       if(which=='/'){
-               return '?';
-       }
-       if(which==';'){
-               return ':';
-       }
-       if(which=='\''){
-               return '\"';
-       }
-       return which;
-}
diff --git a/Source/WinInput.h b/Source/WinInput.h
deleted file mode 100644 (file)
index bbdf597..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#ifndef _WININPUT_H_
-#define _WININPUT_H_
-
-/**> HEADER FILES <**/
-#include <stdlib.h>
-#include <stdio.h>
-#include "MacCompatibility.h"
-
-/**> CONSTANT DECLARATIONS <**/
-// Mac Keyboard Codes
-#define        MAC_1_KEY                               0x12
-#define        MAC_2_KEY                               0x13
-#define        MAC_3_KEY                               0x14
-#define        MAC_4_KEY                               0x15
-#define        MAC_5_KEY                               0x17
-#define        MAC_6_KEY                               0x16
-#define        MAC_7_KEY                               0x1A
-#define        MAC_8_KEY                               0x1C
-#define        MAC_9_KEY                               0x19
-#define        MAC_0_KEY                               0x1D
-#define        MAC_NUMPAD_1_KEY                0x53
-#define        MAC_NUMPAD_2_KEY                0x54
-#define        MAC_NUMPAD_3_KEY                0x55
-#define        MAC_NUMPAD_4_KEY                0x56
-#define        MAC_NUMPAD_5_KEY                0x57
-#define        MAC_NUMPAD_6_KEY                0x58
-#define        MAC_NUMPAD_7_KEY                0x59
-#define        MAC_NUMPAD_8_KEY                0x5B
-#define        MAC_NUMPAD_9_KEY                0x5C
-#define        MAC_NUMPAD_0_KEY                0x52
-#define        MAC_A_KEY                               0x00
-#define        MAC_B_KEY                               0x0B
-#define        MAC_C_KEY                               0x08
-#define        MAC_D_KEY                               0x02
-#define        MAC_E_KEY                               0x0E
-#define        MAC_F_KEY                               0x03
-#define        MAC_G_KEY                               0x05
-#define        MAC_H_KEY                               0x04
-#define        MAC_I_KEY                               0x22
-#define        MAC_J_KEY                               0x26
-#define        MAC_K_KEY                               0x28
-#define        MAC_L_KEY                               0x25
-#define        MAC_M_KEY                               0x2E
-#define        MAC_N_KEY                               0x2D
-#define        MAC_O_KEY                               0x1F
-#define        MAC_P_KEY                               0x23
-#define        MAC_Q_KEY                               0x0C
-#define        MAC_R_KEY                               0x0F
-#define        MAC_S_KEY                               0x01
-#define        MAC_T_KEY                               0x11
-#define        MAC_U_KEY                               0x20
-#define        MAC_V_KEY                               0x09
-#define        MAC_W_KEY                               0x0D
-#define        MAC_X_KEY                               0x07
-#define        MAC_Y_KEY                               0x10
-#define        MAC_Z_KEY                               0x06
-#define        MAC_F1_KEY                              0x7A
-#define        MAC_F2_KEY                              0x78
-#define        MAC_F3_KEY                              0x63
-#define        MAC_F4_KEY                              0x76
-#define        MAC_F5_KEY                              0x60
-#define        MAC_F6_KEY                              0x61
-#define        MAC_F7_KEY                              0x62
-#define        MAC_F8_KEY                              0x64
-#define        MAC_F9_KEY                              0x65
-#define        MAC_F10_KEY                             0x6D
-#define        MAC_F11_KEY                             0x67
-#define        MAC_F12_KEY                             0x6F
-#define        MAC_RETURN_KEY                  0x24
-#define        MAC_ENTER_KEY                   0x4C
-#define        MAC_TAB_KEY                             0x30
-#define        MAC_SPACE_KEY                   0x31
-#define        MAC_DELETE_KEY                  0x33
-#define        MAC_ESCAPE_KEY                  0x35
-#define        MAC_COMMAND_KEY                 0x37
-#define        MAC_SHIFT_KEY                   0x38
-#define        MAC_CAPS_LOCK_KEY               0x39
-#define        MAC_OPTION_KEY                  0x3A
-#define        MAC_CONTROL_KEY                 0x3B
-#define        MAC_PAGE_UP_KEY                 0x74
-#define        MAC_PAGE_DOWN_KEY               0x79
-#define        MAC_INSERT_KEY                  0x72
-#define        MAC_DEL_KEY                             0x75
-#define        MAC_HOME_KEY                    0x73
-#define        MAC_END_KEY                             0x77
-#define        MAC_LEFT_BRACKET_KEY    0x21
-#define        MAC_RIGHT_BRACKET_KEY   0x1E
-#define        MAC_ARROW_UP_KEY                0x7E
-#define        MAC_ARROW_DOWN_KEY              0x7D
-#define        MAC_ARROW_LEFT_KEY              0x7B
-#define        MAC_ARROW_RIGHT_KEY             0x7C
-#define        MAC_TILDE_KEY                   0x32
-#define MAC_MINUS_KEY                  0x1B
-#define MAC_PLUS_KEY                   0x18
-#define MAC_SLASH_KEY                  0x2C
-#define MAC_PERIOD_KEY                 0x2F
-#define MAC_COMMA_KEY                  0x2B
-#define MAC_BACKSLASH_KEY              0x2A
-#define MAC_LEFTBRACKET_KEY            0x21
-#define MAC_RIGHTBRACKET_KEY   0x1E
-#define MAC_NUMPAD_CLEAR_KEY   0x47
-#define MAC_NUMPAD_MINUS_KEY   0x4E
-#define MAC_NUMPAD_EQUALS_KEY  0x51
-#define MAC_NUMPAD_PLUS_KEY            0x45
-#define MAC_NUMPAD_SLASH_KEY   0x4B
-#define MAC_NUMPAD_ASTERISK_KEY        0x43
-#define MAC_NUMPAD_ENTER_KEY   0x4C
-#define MAC_NUMPAD_PERIOD_KEY  0x41
-#define MAC_SEMICOLON_KEY              0x29
-#define MAC_APOSTROPHE_KEY             0x27
-#define MAC_MOUSEBUTTON1               10000
-#define MAC_MOUSEBUTTON2               10001
-
-#define UNKNOWN_KEY 0xFF
-
-
-/**> FUNCTION PROTOTYPES <**/
-Boolean        IsKeyDown( unsigned char *keyMap, unsigned short theKey );
-void   InitMouse();
-void   MoveMouse(int xcoord, int ycoord, Point *mouseloc);
-void   RefreshMouse(Point *mouseloc);
-void   DisposeMouse();
-unsigned short         CharToKey(const char* which);
-const char*    KeyToChar(unsigned short which);
-char   KeyToSingleChar(unsigned short which);
-char   Shift(char which);
-
-
-typedef unsigned char KeyMap[16];
-void GetKeys( unsigned char theKeys[16]);
-
-Boolean Button();
-
-
-#endif
index e6823615fdbe9e82094d816305f886aec343d394..fc062c053e57cf9e65bd7906af59dad2acb09051 100644 (file)
@@ -43,17 +43,6 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include "GL/glext.h"
 #include "MacCompatibility.h"
 
-#if !PLATFORM_MACOSX
-struct RGBColor
-{
-       unsigned short red;
-       unsigned short green;
-       unsigned short blue;
-};
-typedef struct RGBColor RGBColor;
-typedef RGBColor * RGBColorPtr;
-#endif
-
 using namespace std;
 
 /* !!! FIXME: until we replace logger better. --ryan. */
index e11ca0db0f000d1874db3f885880c9a67c57c24e..87d086374d04622cef9c4774041abfc8465469d0 100644 (file)
@@ -88,6 +88,10 @@ GL_FUNC(void,glVertexPointer,(GLint size, GLenum type, GLsizei stride, const GLv
 GL_FUNC(void,glViewport,(GLint x, GLint y, GLsizei width, GLsizei height),(x,y,width,height),)
 GL_FUNC(void,glLockArraysEXT,(GLint first, GLsizei count),(first,count),)
 GL_FUNC(void,glUnlockArraysEXT,(void),(),)
+GL_FUNC(void,glStencilFunc,(GLenum func, GLint ref, GLuint mask),(func,ref,mask),)
+GL_FUNC(void,glStencilOp,(GLenum fail, GLenum zfail, GLenum zpass),(fail,zfail,zpass),)
+GL_FUNC(void,glClearStencil,(GLint s),(s),)
+GL_FUNC(void,glLineWidth,(GLfloat width),(width),)
 
 // stuff GLU needs...
 GL_FUNC(void,glGetIntegerv,(GLenum pname, GLint *params),(pname,params),)
diff --git a/Source/mmgr.cpp b/Source/mmgr.cpp
deleted file mode 100644 (file)
index ea78e15..0000000
+++ /dev/null
@@ -1,1773 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-//                                                      
-//                                                      
-//  _ __ ___  _ __ ___   __ _ _ __      ___ _ __  _ __  
-// | '_ ` _ \| '_ ` _ \ / _` | '__|    / __| '_ \| '_ \ 
-// | | | | | | | | | | | (_| | |    _ | (__| |_) | |_) |
-// |_| |_| |_|_| |_| |_|\__, |_|   (_) \___| .__/| .__/ 
-//                       __/ |             | |   | |    
-//                      |___/              |_|   |_|    
-//
-// Memory manager & tracking software
-//
-// Best viewed with 8-character tabs and (at least) 132 columns
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-//
-// Restrictions & freedoms pertaining to usage and redistribution of this software:
-//
-//  * This software is 100% free
-//  * If you use this software (in part or in whole) you must credit the author.
-//  * This software may not be re-distributed (in part or in whole) in a modified
-//    form without clear documentation on how to obtain a copy of the original work.
-//  * You may not use this software to directly or indirectly cause harm to others.
-//  * This software is provided as-is and without warrantee. Use at your own risk.
-//
-// For more information, visit HTTP://www.FluidStudios.com
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Originally created on 12/22/2000 by Paul Nettle
-//
-// Copyright 2000, Fluid Studios, Inc., all rights reserved.
-// ---------------------------------------------------------------------------------------------------------------------------------
-//
-// !!IMPORTANT!!
-//
-// This software is self-documented with periodic comments. Before you start using this software, perform a search for the string
-// "-DOC-" to locate pertinent information about how to use this software.
-//
-// You are also encouraged to read the comment blocks throughout this source file. They will help you understand how this memory
-// tracking software works, so you can better utilize it within your applications.
-//
-// NOTES:
-//
-// 1. If you get compiler errors having to do with set_new_handler, then go through this source and search/replace
-//    "std::set_new_handler" with "set_new_handler".
-//
-// 2. This code purposely uses no external routines that allocate RAM (other than the raw allocation routines, such as malloc). We
-//    do this because we want this to be as self-contained as possible. As an example, we don't use assert, because when running
-//    under WIN32, the assert brings up a dialog box, which allocates RAM. Doing this in the middle of an allocation would be bad.
-//
-// 3. When trying to override new/delete under MFC (which has its own version of global new/delete) the linker will complain. In
-//    order to fix this error, use the compiler option: /FORCE, which will force it to build an executable even with linker errors.
-//    Be sure to check those errors each time you compile, otherwise, you may miss a valid linker error.
-//
-// 4. If you see something that looks odd to you or seems like a strange way of going about doing something, then consider that this
-//    code was carefully thought out. If something looks odd, then just assume I've got a good reason for doing it that way (an
-//    example is the use of the class MemStaticTimeTracker.)
-//
-// 5. With MFC applications, you will need to comment out any occurance of "#define new DEBUG_NEW" from all source files.
-//
-// 6. Include file dependencies are _very_important_ for getting the MMGR to integrate nicely into your application. Be careful if
-//    you're including standard includes from within your own project inclues; that will break this very specific dependency order. 
-//    It should look like this:
-//
-//             #include <stdio.h>   // Standard includes MUST come first
-//             #include <stdlib.h>  //
-//             #include <streamio>  //
-//
-//             #include "mmgr.h"    // mmgr.h MUST come next
-//
-//             #include "myfile1.h" // Project includes MUST come last
-//             #include "myfile2.h" //
-//             #include "myfile3.h" //
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#include <iostream>
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-#include <string.h>
-#include <time.h>
-#include <stdarg.h>
-#include <new>
-
-#ifndef        WIN32
-#include <unistd.h>
-#endif
-
-#include "mmgr.h"
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- If you're like me, it's hard to gain trust in foreign code. This memory manager will try to INDUCE your code to crash (for
-// very good reasons... like making bugs obvious as early as possible.) Some people may be inclined to remove this memory tracking
-// software if it causes crashes that didn't exist previously. In reality, these new crashes are the BEST reason for using this
-// software!
-//
-// Whether this software causes your application to crash, or if it reports errors, you need to be able to TRUST this software. To
-// this end, you are given some very simple debugging tools.
-// 
-// The quickest way to locate problems is to enable the STRESS_TEST macro (below.) This should catch 95% of the crashes before they
-// occur by validating every allocation each time this memory manager performs an allocation function. If that doesn't work, keep
-// reading...
-//
-// If you enable the TEST_MEMORY_MANAGER #define (below), this memory manager will log an entry in the memory.log file each time it
-// enters and exits one of its primary allocation handling routines. Each call that succeeds should place an "ENTER" and an "EXIT"
-// into the log. If the program crashes within the memory manager, it will log an "ENTER", but not an "EXIT". The log will also
-// report the name of the routine.
-//
-// Just because this memory manager crashes does not mean that there is a bug here! First, an application could inadvertantly damage
-// the heap, causing malloc(), realloc() or free() to crash. Also, an application could inadvertantly damage some of the memory used
-// by this memory tracking software, causing it to crash in much the same way that a damaged heap would affect the standard
-// allocation routines.
-//
-// In the event of a crash within this code, the first thing you'll want to do is to locate the actual line of code that is
-// crashing. You can do this by adding log() entries throughout the routine that crashes, repeating this process until you narrow
-// in on the offending line of code. If the crash happens in a standard C allocation routine (i.e. malloc, realloc or free) don't
-// bother contacting me, your application has damaged the heap. You can help find the culprit in your code by enabling the
-// STRESS_TEST macro (below.)
-//
-// If you truely suspect a bug in this memory manager (and you had better be sure about it! :) you can contact me at
-// midnight@FluidStudios.com. Before you do, however, check for a newer version at:
-//
-//     http://www.FluidStudios.com/publications.html
-//
-// When using this debugging aid, make sure that you are NOT setting the alwaysLogAll variable on, otherwise the log could be
-// cluttered and hard to read.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-//#define      TEST_MEMORY_MANAGER
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Enable this sucker if you really want to stress-test your app's memory usage, or to help find hard-to-find bugs
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-//#define      STRESS_TEST
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Enable this sucker if you want to stress-test your app's error-handling. Set RANDOM_FAIL to the percentage of failures you
-//       want to test with (0 = none, >100 = all failures).
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-//#define      RANDOM_FAILURE 10.0
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Locals -- modify these flags to suit your needs
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#ifdef STRESS_TEST
-static const   unsigned int    hashBits               = 12;
-static         bool            randomWipe             = true;
-static         bool            alwaysValidateAll      = true;
-static         bool            alwaysLogAll           = true;
-static         bool            alwaysWipeAll          = true;
-static         bool            cleanupLogOnFirstRun   = true;
-static const   unsigned int    paddingSize            = 1024; // An extra 8K per allocation!
-#else
-static const   unsigned int    hashBits               = 12;
-static         bool            randomWipe             = false;
-static         bool            alwaysValidateAll      = false;
-static         bool            alwaysLogAll           = false;
-static         bool            alwaysWipeAll          = true;
-static         bool            cleanupLogOnFirstRun   = true;
-static const   unsigned int    paddingSize            = 4;
-#endif
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// We define our own assert, because we don't want to bring up an assertion dialog, since that allocates RAM. Our new assert
-// simply declares a forced breakpoint.
-//
-// The BEOS assert added by Arvid Norberg <arvid@iname.com>.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#ifdef WIN32
-       #ifdef  _DEBUG
-       #define m_assert(x) if ((x) == false) __asm { int 3 }
-       #else
-       #define m_assert(x) {}
-       #endif
-#elif defined(__BEOS__)
-       #ifdef DEBUG
-               extern void debugger(const char *message);
-               #define m_assert(x) if ((x) == false) debugger("mmgr: assert failed")
-       #else
-               #define m_assert(x) {}
-       #endif
-#else  // Linux uses assert, which we can use safely, since it doesn't bring up a dialog within the program.
-       #define m_assert(cond) assert(cond)
-#endif
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Here, we turn off our macros because any place in this source file where the word 'new' or the word 'delete' (etc.)
-// appear will be expanded by the macro. So to avoid problems using them within this source file, we'll just #undef them.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#undef new
-#undef delete
-#undef malloc
-#undef calloc
-#undef realloc
-#undef free
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Defaults for the constants & statics in the MemoryManager class
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-const          unsigned int    m_alloc_unknown        = 0;
-const          unsigned int    m_alloc_new            = 1;
-const          unsigned int    m_alloc_new_array      = 2;
-const          unsigned int    m_alloc_malloc         = 3;
-const          unsigned int    m_alloc_calloc         = 4;
-const          unsigned int    m_alloc_realloc        = 5;
-const          unsigned int    m_alloc_delete         = 6;
-const          unsigned int    m_alloc_delete_array   = 7;
-const          unsigned int    m_alloc_free           = 8;
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Get to know these values. They represent the values that will be used to fill unused and deallocated RAM.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static         unsigned int    prefixPattern          = 0xbaadf00d; // Fill pattern for bytes preceeding allocated blocks
-static         unsigned int    postfixPattern         = 0xdeadc0de; // Fill pattern for bytes following allocated blocks
-static         unsigned int    unusedPattern          = 0xfeedface; // Fill pattern for freshly allocated blocks
-static         unsigned int    releasedPattern        = 0xdeadbeef; // Fill pattern for deallocated blocks
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Other locals
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static const   unsigned int    hashSize               = 1 << hashBits;
-static const   char            *allocationTypes[]     = {"Unknown",
-                                                         "new",     "new[]",  "malloc",   "calloc",
-                                                         "realloc", "delete", "delete[]", "free"};
-static         sAllocUnit      *hashTable[hashSize];
-static         sAllocUnit      *reservoir;
-static         unsigned int    currentAllocationCount = 0;
-static         unsigned int    breakOnAllocationCount = 0;
-static         sMStats         stats;
-static const   char            *sourceFile            = "??";
-static const   char            *sourceFunc            = "??";
-static         unsigned int    sourceLine             = 0;
-static         bool            staticDeinitTime       = false;
-static         sAllocUnit      **reservoirBuffer      = NULL;
-static         unsigned int    reservoirBufferSize    = 0;
-static const   char            *memoryLogFile         = "memory.log";
-static const   char            *memoryLeakLogFile     = "memleaks.log";
-static         void            doCleanupLogOnFirstRun();
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Local functions only
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    log(const char *format, ...)
-{
-       // Cleanup the log?
-
-       if (cleanupLogOnFirstRun) doCleanupLogOnFirstRun();
-
-       // Build the buffer
-
-       static char buffer[2048];
-       va_list ap;
-       va_start(ap, format);
-       vsprintf(buffer, format, ap);
-       va_end(ap);
-
-       // Open the log file
-
-       FILE    *fp = fopen(memoryLogFile, "ab");
-
-       // If you hit this assert, then the memory logger is unable to log information to a file (can't open the file for some
-       // reason.) You can interrogate the variable 'buffer' to see what was supposed to be logged (but won't be.)
-       m_assert(fp);
-
-       if (!fp) return;
-
-       // Spit out the data to the log
-
-       fprintf(fp, "%s\r\n", buffer);
-       fclose(fp);
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    doCleanupLogOnFirstRun()
-{
-       if (cleanupLogOnFirstRun)
-       {
-               unlink(memoryLogFile);
-               cleanupLogOnFirstRun = false;
-
-               // Print a header for the log
-
-               time_t  t = time(NULL);
-               log("--------------------------------------------------------------------------------");
-               log("");
-               log("      %s - Memory logging file created on %s", memoryLogFile, asctime(localtime(&t)));
-               log("--------------------------------------------------------------------------------");
-               log("");
-               log("This file contains a log of all memory operations performed during the last run.");
-               log("");
-               log("Interrogate this file to track errors or to help track down memory-related");
-               log("issues. You can do this by tracing the allocations performed by a specific owner");
-               log("or by tracking a specific address through a series of allocations and");
-               log("reallocations.");
-               log("");
-               log("There is a lot of useful information here which, when used creatively, can be");
-               log("extremely helpful.");
-               log("");
-               log("Note that the following guides are used throughout this file:");
-               log("");
-               log("   [!] - Error");
-               log("   [+] - Allocation");
-               log("   [~] - Reallocation");
-               log("   [-] - Deallocation");
-               log("   [I] - Generic information");
-               log("   [F] - Failure induced for the purpose of stress-testing your application");
-               log("   [D] - Information used for debugging this memory manager");
-               log("");
-               log("...so, to find all errors in the file, search for \"[!]\"");
-               log("");
-               log("--------------------------------------------------------------------------------");
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static const char      *sourceFileStripper(const char *sourceFile)
-{
-       char    *ptr = strrchr(sourceFile, '\\');
-       if (ptr) return ptr + 1;
-       ptr = strrchr(sourceFile, '/');
-       if (ptr) return ptr + 1;
-       return sourceFile;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static const char      *ownerString(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc)
-{
-       static  char    str[90];
-       memset(str, 0, sizeof(str));
-       sprintf(str, "%s(%05d)::%s", sourceFileStripper(sourceFile), sourceLine, sourceFunc);
-       return str;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static const char      *insertCommas(unsigned int value)
-{
-       static  char    str[30];
-       memset(str, 0, sizeof(str));
-
-       sprintf(str, "%u", value);
-       if (strlen(str) > 3)
-       {
-               memmove(&str[strlen(str)-3], &str[strlen(str)-4], 4);
-               str[strlen(str) - 4] = ',';
-       }
-       if (strlen(str) > 7)
-       {
-               memmove(&str[strlen(str)-7], &str[strlen(str)-8], 8);
-               str[strlen(str) - 8] = ',';
-       }
-       if (strlen(str) > 11)
-       {
-               memmove(&str[strlen(str)-11], &str[strlen(str)-12], 12);
-               str[strlen(str) - 12] = ',';
-       }
-
-       return str;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static const char      *memorySizeString(unsigned long size)
-{
-       static  char    str[90];
-            if (size > (1024*1024))    sprintf(str, "%10s (%7.2fM)", insertCommas(size), static_cast<float>(size) / (1024.0f * 1024.0f));
-       else if (size > 1024)           sprintf(str, "%10s (%7.2fK)", insertCommas(size), static_cast<float>(size) / 1024.0f);
-       else                            sprintf(str, "%10s bytes     ", insertCommas(size));
-       return str;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static sAllocUnit      *findAllocUnit(const void *reportedAddress)
-{
-       // Just in case...
-       m_assert(reportedAddress != NULL);
-
-       // Use the address to locate the hash index. Note that we shift off the lower four bits. This is because most allocated
-       // addresses will be on four-, eight- or even sixteen-byte boundaries. If we didn't do this, the hash index would not have
-       // very good coverage.
-
-       unsigned int    hashIndex = (reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)) >> 4) & (hashSize - 1);
-       sAllocUnit      *ptr = hashTable[hashIndex];
-       while(ptr)
-       {
-               if (ptr->reportedAddress == reportedAddress) return ptr;
-               ptr = ptr->next;
-       }
-
-       return NULL;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static size_t  calculateActualSize(const size_t reportedSize)
-{
-       // We use DWORDS as our padding, and a long is guaranteed to be 4 bytes, but an int is not (ANSI defines an int as
-       // being the standard word size for a processor; on a 32-bit machine, that's 4 bytes, but on a 64-bit machine, it's
-       // 8 bytes, which means an int can actually be larger than a long.)
-
-       return reportedSize + paddingSize * sizeof(long) * 2;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static size_t  calculateReportedSize(const size_t actualSize)
-{
-       // We use DWORDS as our padding, and a long is guaranteed to be 4 bytes, but an int is not (ANSI defines an int as
-       // being the standard word size for a processor; on a 32-bit machine, that's 4 bytes, but on a 64-bit machine, it's
-       // 8 bytes, which means an int can actually be larger than a long.)
-
-       return actualSize - paddingSize * sizeof(long) * 2;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    *calculateReportedAddress(const void *actualAddress)
-{
-       // We allow this...
-
-       if (!actualAddress) return NULL;
-
-       // JUst account for the padding
-
-       return reinterpret_cast<void *>(const_cast<char *>(reinterpret_cast<const char *>(actualAddress) + sizeof(long) * paddingSize));
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    wipeWithPattern(sAllocUnit *allocUnit, unsigned long pattern, const unsigned int originalReportedSize = 0)
-{
-       // For a serious test run, we use wipes of random a random value. However, if this causes a crash, we don't want it to
-       // crash in a differnt place each time, so we specifically DO NOT call srand. If, by chance your program calls srand(),
-       // you may wish to disable that when running with a random wipe test. This will make any crashes more consistent so they
-       // can be tracked down easier.
-
-       if (randomWipe)
-       {
-               pattern = ((rand() & 0xff) << 24) | ((rand() & 0xff) << 16) | ((rand() & 0xff) << 8) | (rand() & 0xff);
-       }
-
-       // -DOC- We should wipe with 0's if we're not in debug mode, so we can help hide bugs if possible when we release the
-       // product. So uncomment the following line for releases.
-       //
-       // Note that the "alwaysWipeAll" should be turned on for this to have effect, otherwise it won't do much good. But we'll
-       // leave it this way (as an option) because this does slow things down.
-//     pattern = 0;
-
-       // This part of the operation is optional
-
-       if (alwaysWipeAll && allocUnit->reportedSize > originalReportedSize)
-       {
-               // Fill the bulk
-
-               long    *lptr = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->reportedAddress) + originalReportedSize);
-               int     length = static_cast<int>(allocUnit->reportedSize - originalReportedSize);
-               int     i;
-               for (i = 0; i < (length >> 2); i++, lptr++)
-               {
-                       *lptr = pattern;
-               }
-
-               // Fill the remainder
-
-               unsigned int    shiftCount = 0;
-               char            *cptr = reinterpret_cast<char *>(lptr);
-               for (i = 0; i < (length & 0x3); i++, cptr++, shiftCount += 8)
-               {
-                       *cptr = static_cast<char>((pattern & (0xff << shiftCount)) >> shiftCount);
-               }
-       }
-
-       // Write in the prefix/postfix bytes
-
-       long            *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
-       long            *post = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->actualAddress) + allocUnit->actualSize - paddingSize * sizeof(long));
-       for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
-       {
-               *pre = prefixPattern;
-               *post = postfixPattern;
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    dumpAllocations(FILE *fp)
-{
-       fprintf(fp, "Alloc.   Addr       Size       Addr       Size                        BreakOn BreakOn              \r\n");
-       fprintf(fp, "Number Reported   Reported    Actual     Actual     Unused    Method  Dealloc Realloc Allocated by \r\n");
-       fprintf(fp, "------ ---------- ---------- ---------- ---------- ---------- -------- ------- ------- --------------------------------------------------- \r\n");
-
-
-       for (unsigned int i = 0; i < hashSize; i++)
-       {
-               sAllocUnit *ptr = hashTable[i];
-               while(ptr)
-               {
-                       fprintf(fp, "%06d 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X %-8s    %c       %c    %s\r\n",
-                               ptr->allocationNumber,
-                               reinterpret_cast<unsigned int>(ptr->reportedAddress), ptr->reportedSize,
-                               reinterpret_cast<unsigned int>(ptr->actualAddress), ptr->actualSize,
-                               m_calcUnused(ptr),
-                               allocationTypes[ptr->allocationType],
-                               ptr->breakOnDealloc ? 'Y':'N',
-                               ptr->breakOnRealloc ? 'Y':'N',
-                               ownerString(ptr->sourceFile, ptr->sourceLine, ptr->sourceFunc));
-                       ptr = ptr->next;
-               }
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    dumpLeakReport()
-{
-       // Open the report file
-
-       FILE    *fp = fopen(memoryLeakLogFile, "w+b");
-
-       // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
-       // some reason.)
-       m_assert(fp);
-       if (!fp) return;
-
-       // Any leaks?
-
-       // Header
-
-       static  char    timeString[25];
-       memset(timeString, 0, sizeof(timeString));
-       time_t  t = time(NULL);
-       struct  tm *tme = localtime(&t);
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "|                                          Memory leak report for:  %02d/%02d/%04d %02d:%02d:%02d                                            |\r\n", tme->tm_mon + 1, tme->tm_mday, tme->tm_year + 1900, tme->tm_hour, tme->tm_min, tme->tm_sec);
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "\r\n");
-       fprintf(fp, "\r\n");
-       if (stats.totalAllocUnitCount)
-       {
-               fprintf(fp, "%d memory leak%s found:\r\n", stats.totalAllocUnitCount, stats.totalAllocUnitCount == 1 ? "":"s");
-       }
-       else
-       {
-               fprintf(fp, "Congratulations! No memory leaks found!\r\n");
-
-               // We can finally free up our own memory allocations
-
-               if (reservoirBuffer)
-               {
-                       for (unsigned int i = 0; i < reservoirBufferSize; i++)
-                       {
-                               free(reservoirBuffer[i]);
-                       }
-                       free(reservoirBuffer);
-                       reservoirBuffer = 0;
-                       reservoirBufferSize = 0;
-                       reservoir = NULL;
-               }
-       }
-       fprintf(fp, "\r\n");
-
-       if (stats.totalAllocUnitCount)
-       {
-               dumpAllocations(fp);
-       }
-
-       fclose(fp);
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// We use a static class to let us know when we're in the midst of static deinitialization
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-class  MemStaticTimeTracker
-{
-public:
-       MemStaticTimeTracker() {doCleanupLogOnFirstRun();}
-       ~MemStaticTimeTracker() {staticDeinitTime = true; dumpLeakReport();}
-};
-static MemStaticTimeTracker    mstt;
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Flags & options -- Call these routines to enable/disable the following options
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   &m_alwaysValidateAll()
-{
-       // Force a validation of all allocation units each time we enter this software
-       return alwaysValidateAll;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   &m_alwaysLogAll()
-{
-       // Force a log of every allocation & deallocation into memory.log
-       return alwaysLogAll;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   &m_alwaysWipeAll()
-{
-       // Force this software to always wipe memory with a pattern when it is being allocated/dallocated
-       return alwaysWipeAll;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   &m_randomeWipe()
-{
-       // Force this software to use a random pattern when wiping memory -- good for stress testing
-       return randomWipe;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
-// reallocated.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   &m_breakOnRealloc(void *reportedAddress)
-{
-       // Locate the existing allocation unit
-
-       sAllocUnit      *au = findAllocUnit(reportedAddress);
-
-       // If you hit this assert, you tried to set a breakpoint on reallocation for an address that doesn't exist. Interrogate the
-       // stack frame or the variable 'au' to see which allocation this is.
-       m_assert(au != NULL);
-
-       // If you hit this assert, you tried to set a breakpoint on reallocation for an address that wasn't allocated in a way that
-       // is compatible with reallocation.
-       m_assert(au->allocationType == m_alloc_malloc ||
-                au->allocationType == m_alloc_calloc ||
-                au->allocationType == m_alloc_realloc);
-
-       return au->breakOnRealloc;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
-// deallocated.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   &m_breakOnDealloc(void *reportedAddress)
-{
-       // Locate the existing allocation unit
-
-       sAllocUnit      *au = findAllocUnit(reportedAddress);
-
-       // If you hit this assert, you tried to set a breakpoint on deallocation for an address that doesn't exist. Interrogate the
-       // stack frame or the variable 'au' to see which allocation this is.
-       m_assert(au != NULL);
-
-       return au->breakOnDealloc;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- When tracking down a difficult bug, use this routine to force a breakpoint on a specific allocation count
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   m_breakOnAllocation(unsigned int count)
-{
-       breakOnAllocationCount = count;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Used by the macros
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   m_setOwner(const char *file, const unsigned int line, const char *func)
-{
-       // You're probably wondering about this...
-       //
-       // It's important for this memory manager to primarily work with global new/delete in their original forms (i.e. with
-       // no extra parameters.) In order to do this, we use macros that call this function prior to operators new & delete. This
-       // is fine... usually. Here's what actually happens when you use this macro to delete an object:
-       //
-       // m_setOwner(__FILE__, __LINE__, __FUNCTION__) --> object::~object() --> delete
-       //
-       // Note that the compiler inserts a call to the object's destructor just prior to calling our overridden operator delete.
-       // But what happens when we delete an object whose destructor deletes another object, whose desctuctor deletes another
-       // object? Here's a diagram (indentation follows stack depth):
-       //
-       // m_setOwner(...) -> ~obj1()                          // original call to delete obj1
-       //     m_setOwner(...) -> ~obj2()                      // obj1's destructor deletes obj2
-       //         m_setOwner(...) -> ~obj3()                  // obj2's destructor deletes obj3
-       //             ...                                     // obj3's destructor just does some stuff
-       //         delete                                      // back in obj2's destructor, we call delete
-       //     delete                                          // back in obj1's destructor, we call delete
-       // delete                                              // back to our original call, we call delete
-       //
-       // Because m_setOwner() just sets up some static variables (below) it's important that each call to m_setOwner() and
-       // successive calls to new/delete alternate. However, in this case, three calls to m_setOwner() happen in succession
-       // followed by three calls to delete in succession (with a few calls to destructors mixed in for fun.) This means that
-       // only the final call to delete (in this chain of events) will have the proper reporting, and the first two in the chain
-       // will not have ANY owner-reporting information. The deletes will still work fine, we just won't know who called us.
-       //
-       // "Then build a stack, my friend!" you might think... but it's a very common thing that people will be working with third-
-       // party libraries (including MFC under Windows) which is not compiled with this memory manager's macros. In those cases,
-       // m_setOwner() is never called, and rightfully should not have the proper trace-back information. So if one of the
-       // destructors in the chain ends up being a call to a delete from a non-mmgr-compiled library, the stack will get confused.
-       //
-       // I've been unable to find a solution to this problem, but at least we can detect it and report the data before we
-       // lose it. That's what this is all about. It makes it somewhat confusing to read in the logs, but at least ALL the
-       // information is present...
-       //
-       // There's a caveat here... The compiler is not required to call operator delete if the value being deleted is NULL.
-       // In this case, any call to delete with a NULL will sill call m_setOwner(), which will make m_setOwner() think that
-       // there is a destructor chain becuase we setup the variables, but nothing gets called to clear them. Because of this
-       // we report a "Possible destructor chain".
-       //
-       // Thanks to J. Woznack (from Kodiak Interactive Software Studios -- www.kodiakgames.com) for pointing this out.
-
-       if (sourceLine && alwaysLogAll)
-       {
-               log("[I] NOTE! Possible destructor chain: previous owner is %s", ownerString(sourceFile, sourceLine, sourceFunc));
-       }
-
-       // Okay... save this stuff off so we can keep track of the caller
-
-       sourceFile = file;
-       sourceLine = line;
-       sourceFunc = func;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-static void    resetGlobals()
-{
-       sourceFile = "??";
-       sourceLine = 0;
-       sourceFunc = "??";
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Global new/new[]
-//
-// These are the standard new/new[] operators. They are merely interface functions that operate like normal new/new[], but use our
-// memory tracking routines.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *operator new(size_t reportedSize)
-{
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] ENTER: new");
-       #endif
-
-       // Save these off...
-
-       const   char            *file = sourceFile;
-       const   unsigned int    line = sourceLine;
-       const   char            *func = sourceFunc;
-
-       // ANSI says: allocation requests of 0 bytes will still return a valid value
-
-       if (reportedSize == 0) reportedSize = 1;
-
-       // ANSI says: loop continuously because the error handler could possibly free up some memory
-
-       for(;;)
-       {
-               // Try the allocation
-
-               void    *ptr = m_allocator(file, line, func, m_alloc_new, reportedSize);
-               if (ptr)
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new");
-                       #endif
-                       return ptr;
-               }
-
-               // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
-               // set it back again.
-
-               std::new_handler        nh = std::set_new_handler(0);
-               std::set_new_handler(nh);
-
-               // If there is an error handler, call it
-
-               if (nh)
-               {
-                       (*nh)();
-               }
-
-               // Otherwise, throw the exception
-
-               else
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new");
-                       #endif
-                       throw std::bad_alloc();
-               }
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *operator new[](size_t reportedSize)
-{
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] ENTER: new[]");
-       #endif
-
-       // Save these off...
-
-       const   char            *file = sourceFile;
-       const   unsigned int    line = sourceLine;
-       const   char            *func = sourceFunc;
-
-       // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
-
-       if (reportedSize == 0) reportedSize = 1;
-
-       // ANSI says: loop continuously because the error handler could possibly free up some memory
-
-       for(;;)
-       {
-               // Try the allocation
-
-               void    *ptr = m_allocator(file, line, func, m_alloc_new_array, reportedSize);
-               if (ptr)
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new[]");
-                       #endif
-                       return ptr;
-               }
-
-               // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
-               // set it back again.
-
-               std::new_handler        nh = std::set_new_handler(0);
-               std::set_new_handler(nh);
-
-               // If there is an error handler, call it
-
-               if (nh)
-               {
-                       (*nh)();
-               }
-
-               // Otherwise, throw the exception
-
-               else
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new[]");
-                       #endif
-                       throw std::bad_alloc();
-               }
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Other global new/new[]
-//
-// These are the standard new/new[] operators as used by Microsoft's memory tracker. We don't want them interfering with our memory
-// tracking efforts. Like the previous versions, these are merely interface functions that operate like normal new/new[], but use
-// our memory tracking routines.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *operator new(size_t reportedSize, const char *sourceFile, int sourceLine)
-{
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] ENTER: new");
-       #endif
-
-       // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
-
-       if (reportedSize == 0) reportedSize = 1;
-
-       // ANSI says: loop continuously because the error handler could possibly free up some memory
-
-       for(;;)
-       {
-               // Try the allocation
-
-               void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new, reportedSize);
-               if (ptr)
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new");
-                       #endif
-                       return ptr;
-               }
-
-               // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
-               // set it back again.
-
-               std::new_handler        nh = std::set_new_handler(0);
-               std::set_new_handler(nh);
-
-               // If there is an error handler, call it
-
-               if (nh)
-               {
-                       (*nh)();
-               }
-
-               // Otherwise, throw the exception
-
-               else
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new");
-                       #endif
-                       throw std::bad_alloc();
-               }
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *operator new[](size_t reportedSize, const char *sourceFile, int sourceLine)
-{
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] ENTER: new[]");
-       #endif
-
-       // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
-
-       if (reportedSize == 0) reportedSize = 1;
-
-       // ANSI says: loop continuously because the error handler could possibly free up some memory
-
-       for(;;)
-       {
-               // Try the allocation
-
-               void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new_array, reportedSize);
-               if (ptr)
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new[]");
-                       #endif
-                       return ptr;
-               }
-
-               // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
-               // set it back again.
-
-               std::new_handler        nh = std::set_new_handler(0);
-               std::set_new_handler(nh);
-
-               // If there is an error handler, call it
-
-               if (nh)
-               {
-                       (*nh)();
-               }
-
-               // Otherwise, throw the exception
-
-               else
-               {
-                       #ifdef TEST_MEMORY_MANAGER
-                       log("[D] EXIT : new[]");
-                       #endif
-                       throw std::bad_alloc();
-               }
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Global delete/delete[]
-//
-// These are the standard delete/delete[] operators. They are merely interface functions that operate like normal delete/delete[],
-// but use our memory tracking routines.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   operator delete(void *reportedAddress)
-{
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] ENTER: delete");
-       #endif
-
-       // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
-
-       if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete, reportedAddress);
-       else if (alwaysLogAll) log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete], ownerString(sourceFile, sourceLine, sourceFunc));
-
-       // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
-       // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
-
-       resetGlobals();
-
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] EXIT : delete");
-       #endif
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   operator delete[](void *reportedAddress)
-{
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] ENTER: delete[]");
-       #endif
-
-       // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
-
-       if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete_array, reportedAddress);
-       else if (alwaysLogAll)
-               log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete_array], ownerString(sourceFile, sourceLine, sourceFunc));
-
-       // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
-       // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
-
-       resetGlobals();
-
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] EXIT : delete[]");
-       #endif
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Allocate memory and track it
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *m_allocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int allocationType, const size_t reportedSize)
-{
-       try
-       {
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] ENTER: m_allocator()");
-               #endif
-
-               // Increase our allocation count
-
-               currentAllocationCount++;
-
-               // Log the request
-
-               if (alwaysLogAll) log("[+] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[allocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
-
-               // If you hit this assert, you requested a breakpoint on a specific allocation count
-               m_assert(currentAllocationCount != breakOnAllocationCount);
-
-               // If necessary, grow the reservoir of unused allocation units
-
-               if (!reservoir)
-               {
-                       // Allocate 256 reservoir elements
-
-                       reservoir = (sAllocUnit *) malloc(sizeof(sAllocUnit) * 256);
-
-                       // If you hit this assert, then the memory manager failed to allocate internal memory for tracking the
-                       // allocations
-                       m_assert(reservoir != NULL);
-
-                       // Danger Will Robinson!
-
-                       if (reservoir == NULL) throw "Unable to allocate RAM for internal memory tracking data";
-
-                       // Build a linked-list of the elements in our reservoir
-
-                       memset(reservoir, 0, sizeof(sAllocUnit) * 256);
-                       for (unsigned int i = 0; i < 256 - 1; i++)
-                       {
-                               reservoir[i].next = &reservoir[i+1];
-                       }
-
-                       // Add this address to our reservoirBuffer so we can free it later
-
-                       sAllocUnit      **temp = (sAllocUnit **) realloc(reservoirBuffer, (reservoirBufferSize + 1) * sizeof(sAllocUnit *));
-                       m_assert(temp);
-                       if (temp)
-                       {
-                               reservoirBuffer = temp;
-                               reservoirBuffer[reservoirBufferSize++] = reservoir;
-                       }
-               }
-
-               // Logical flow says this should never happen...
-               m_assert(reservoir != NULL);
-
-               // Grab a new allocaton unit from the front of the reservoir
-
-               sAllocUnit      *au = reservoir;
-               reservoir = au->next;
-
-               // Populate it with some real data
-
-               memset(au, 0, sizeof(sAllocUnit));
-               au->actualSize        = calculateActualSize(reportedSize);
-               #ifdef RANDOM_FAILURE
-               double  a = rand();
-               double  b = RAND_MAX / 100.0 * RANDOM_FAILURE;
-               if (a > b)
-               {
-                       au->actualAddress = malloc(au->actualSize);
-               }
-               else
-               {
-                       log("[F] Random faiure");
-                       au->actualAddress = NULL;
-               }
-               #else
-               au->actualAddress     = malloc(au->actualSize);
-               #endif
-               au->reportedSize      = reportedSize;
-               au->reportedAddress   = calculateReportedAddress(au->actualAddress);
-               au->allocationType    = allocationType;
-               au->sourceLine        = sourceLine;
-               au->allocationNumber  = currentAllocationCount;
-               if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
-               else            strcpy (au->sourceFile, "??");
-               if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
-               else            strcpy (au->sourceFunc, "??");
-
-               // We don't want to assert with random failures, because we want the application to deal with them.
-
-               #ifndef RANDOM_FAILURE
-               // If you hit this assert, then the requested allocation simply failed (you're out of memory.) Interrogate the
-               // variable 'au' or the stack frame to see what you were trying to do.
-               m_assert(au->actualAddress != NULL);
-               #endif
-
-               if (au->actualAddress == NULL)
-               {
-                       throw "Request for allocation failed. Out of memory.";
-               }
-
-               // If you hit this assert, then this allocation was made from a source that isn't setup to use this memory tracking
-               // software, use the stack frame to locate the source and include our H file.
-               m_assert(allocationType != m_alloc_unknown);
-
-               // Insert the new allocation into the hash table
-
-               unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
-               if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
-               au->next = hashTable[hashIndex];
-               au->prev = NULL;
-               hashTable[hashIndex] = au;
-
-               // Account for the new allocatin unit in our stats
-
-               stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
-               stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
-               stats.totalAllocUnitCount++;
-               if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
-               if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
-               if (stats.totalAllocUnitCount > stats.peakAllocUnitCount) stats.peakAllocUnitCount = stats.totalAllocUnitCount;
-               stats.accumulatedReportedMemory += static_cast<unsigned int>(au->reportedSize);
-               stats.accumulatedActualMemory += static_cast<unsigned int>(au->actualSize);
-               stats.accumulatedAllocUnitCount++;
-
-               // Prepare the allocation unit for use (wipe it with recognizable garbage)
-
-               wipeWithPattern(au, unusedPattern);
-
-               // calloc() expects the reported memory address range to be filled with 0's
-
-               if (allocationType == m_alloc_calloc)
-               {
-                       memset(au->reportedAddress, 0, au->reportedSize);
-               }
-
-               // Validate every single allocated unit in memory
-
-               if (alwaysValidateAll) m_validateAllAllocUnits();
-
-               // Log the result
-
-               if (alwaysLogAll) log("[+] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
-
-               // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
-               // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
-
-               resetGlobals();
-
-               // Return the (reported) address of the new allocation unit
-
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] EXIT : m_allocator()");
-               #endif
-
-               return au->reportedAddress;
-       }
-       catch(const char *err)
-       {
-               // Deal with the errors
-
-               log("[!] %s", err);
-               resetGlobals();
-
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] EXIT : m_allocator()");
-               #endif
-
-               return NULL;
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Reallocate memory and track it
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *m_reallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int reallocationType, const size_t reportedSize, void *reportedAddress)
-{
-       try
-       {
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] ENTER: m_reallocator()");
-               #endif
-
-               // Calling realloc with a NULL should force same operations as a malloc
-
-               if (!reportedAddress)
-               {
-                       return m_allocator(sourceFile, sourceLine, sourceFunc, reallocationType, reportedSize);
-               }
-
-               // Increase our allocation count
-
-               currentAllocationCount++;
-
-               // If you hit this assert, you requested a breakpoint on a specific allocation count
-               m_assert(currentAllocationCount != breakOnAllocationCount);
-
-               // Log the request
-
-               if (alwaysLogAll) log("[~] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[reallocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
-
-               // Locate the existing allocation unit
-
-               sAllocUnit      *au = findAllocUnit(reportedAddress);
-
-               // If you hit this assert, you tried to reallocate RAM that wasn't allocated by this memory manager.
-               m_assert(au != NULL);
-               if (au == NULL) throw "Request to reallocate RAM that was never allocated";
-
-               // If you hit this assert, then the allocation unit that is about to be reallocated is damaged. But you probably
-               // already know that from a previous assert you should have seen in validateAllocUnit() :)
-               m_assert(m_validateAllocUnit(au));
-
-               // If you hit this assert, then this reallocation was made from a source that isn't setup to use this memory
-               // tracking software, use the stack frame to locate the source and include our H file.
-               m_assert(reallocationType != m_alloc_unknown);
-
-               // If you hit this assert, you were trying to reallocate RAM that was not allocated in a way that is compatible with
-               // realloc. In other words, you have a allocation/reallocation mismatch.
-               m_assert(au->allocationType == m_alloc_malloc ||
-                        au->allocationType == m_alloc_calloc ||
-                        au->allocationType == m_alloc_realloc);
-
-               // If you hit this assert, then the "break on realloc" flag for this allocation unit is set (and will continue to be
-               // set until you specifically shut it off. Interrogate the 'au' variable to determine information about this
-               // allocation unit.
-               m_assert(au->breakOnRealloc == false);
-
-               // Keep track of the original size
-
-               unsigned int    originalReportedSize = static_cast<unsigned int>(au->reportedSize);
-
-               if (alwaysLogAll) log("[~] ---->             from 0x%08X(%08d)", originalReportedSize, originalReportedSize);
-
-               // Do the reallocation
-
-               void    *oldReportedAddress = reportedAddress;
-               size_t  newActualSize = calculateActualSize(reportedSize);
-               void    *newActualAddress = NULL;
-               #ifdef RANDOM_FAILURE
-               double  a = rand();
-               double  b = RAND_MAX / 100.0 * RANDOM_FAILURE;
-               if (a > b)
-               {
-                       newActualAddress = realloc(au->actualAddress, newActualSize);
-               }
-               else
-               {
-                       log("[F] Random faiure");
-               }
-               #else
-               newActualAddress = realloc(au->actualAddress, newActualSize);
-               #endif
-
-               // We don't want to assert with random failures, because we want the application to deal with them.
-
-               #ifndef RANDOM_FAILURE
-               // If you hit this assert, then the requested allocation simply failed (you're out of memory) Interrogate the
-               // variable 'au' to see the original allocation. You can also query 'newActualSize' to see the amount of memory
-               // trying to be allocated. Finally, you can query 'reportedSize' to see how much memory was requested by the caller.
-               m_assert(newActualAddress);
-               #endif
-
-               if (!newActualAddress) throw "Request for reallocation failed. Out of memory.";
-
-               // Remove this allocation from our stats (we'll add the new reallocation again later)
-
-               stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
-               stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
-
-               // Update the allocation with the new information
-
-               au->actualSize        = newActualSize;
-               au->actualAddress     = newActualAddress;
-               au->reportedSize      = calculateReportedSize(newActualSize);
-               au->reportedAddress   = calculateReportedAddress(newActualAddress);
-               au->allocationType    = reallocationType;
-               au->sourceLine        = sourceLine;
-               au->allocationNumber  = currentAllocationCount;
-               if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
-               else            strcpy (au->sourceFile, "??");
-               if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
-               else            strcpy (au->sourceFunc, "??");
-
-               // The reallocation may cause the address to change, so we should relocate our allocation unit within the hash table
-
-               unsigned int    hashIndex = static_cast<unsigned int>(-1);
-               if (oldReportedAddress != au->reportedAddress)
-               {
-                       // Remove this allocation unit from the hash table
-
-                       {
-                               unsigned int    hashIndex = (reinterpret_cast<unsigned int>(oldReportedAddress) >> 4) & (hashSize - 1);
-                               if (hashTable[hashIndex] == au)
-                               {
-                                       hashTable[hashIndex] = hashTable[hashIndex]->next;
-                               }
-                               else
-                               {
-                                       if (au->prev)   au->prev->next = au->next;
-                                       if (au->next)   au->next->prev = au->prev;
-                               }
-                       }
-
-                       // Re-insert it back into the hash table
-
-                       hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
-                       if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
-                       au->next = hashTable[hashIndex];
-                       au->prev = NULL;
-                       hashTable[hashIndex] = au;
-               }
-
-               // Account for the new allocatin unit in our stats
-
-               stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
-               stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
-               if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
-               if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
-               int     deltaReportedSize = static_cast<int>(reportedSize - originalReportedSize);
-               if (deltaReportedSize > 0)
-               {
-                       stats.accumulatedReportedMemory += deltaReportedSize;
-                       stats.accumulatedActualMemory += deltaReportedSize;
-               }
-
-               // Prepare the allocation unit for use (wipe it with recognizable garbage)
-
-               wipeWithPattern(au, unusedPattern, originalReportedSize);
-
-               // If you hit this assert, then something went wrong, because the allocation unit was properly validated PRIOR to
-               // the reallocation. This should not happen.
-               m_assert(m_validateAllocUnit(au));
-
-               // Validate every single allocated unit in memory
-
-               if (alwaysValidateAll) m_validateAllAllocUnits();
-
-               // Log the result
-
-               if (alwaysLogAll) log("[~] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
-
-               // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
-               // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
-
-               resetGlobals();
-
-               // Return the (reported) address of the new allocation unit
-
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] EXIT : m_reallocator()");
-               #endif
-
-               return au->reportedAddress;
-       }
-       catch(const char *err)
-       {
-               // Deal with the errors
-
-               log("[!] %s", err);
-               resetGlobals();
-
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] EXIT : m_reallocator()");
-               #endif
-
-               return NULL;
-       }
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Deallocate memory and track it
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   m_deallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int deallocationType, const void *reportedAddress)
-{
-       try
-       {
-               #ifdef TEST_MEMORY_MANAGER
-               log("[D] ENTER: m_deallocator()");
-               #endif
-
-               // Log the request
-
-               if (alwaysLogAll) log("[-] ----- %8s of addr 0x%08X           by %s", allocationTypes[deallocationType], reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)), ownerString(sourceFile, sourceLine, sourceFunc));
-
-               // We should only ever get here with a null pointer if they try to do so with a call to free() (delete[] and delete will
-               // both bail before they get here.) So, since ANSI allows free(NULL), we'll not bother trying to actually free the allocated
-               // memory or track it any further.
-
-               if (reportedAddress)
-               {
-                       // Go get the allocation unit
-
-                       sAllocUnit      *au = findAllocUnit(reportedAddress);
-
-                       // If you hit this assert, you tried to deallocate RAM that wasn't allocated by this memory manager.
-                       m_assert(au != NULL);
-                       if (au == NULL) throw "Request to deallocate RAM that was never allocated";
-
-                       // If you hit this assert, then the allocation unit that is about to be deallocated is damaged. But you probably
-                       // already know that from a previous assert you should have seen in validateAllocUnit() :)
-                       m_assert(m_validateAllocUnit(au));
-
-                       // If you hit this assert, then this deallocation was made from a source that isn't setup to use this memory
-                       // tracking software, use the stack frame to locate the source and include our H file.
-                       m_assert(deallocationType != m_alloc_unknown);
-
-                       // If you hit this assert, you were trying to deallocate RAM that was not allocated in a way that is compatible with
-                       // the deallocation method requested. In other words, you have a allocation/deallocation mismatch.
-                       m_assert((deallocationType == m_alloc_delete       && au->allocationType == m_alloc_new      ) ||
-                               (deallocationType == m_alloc_delete_array && au->allocationType == m_alloc_new_array) ||
-                               (deallocationType == m_alloc_free         && au->allocationType == m_alloc_malloc   ) ||
-                               (deallocationType == m_alloc_free         && au->allocationType == m_alloc_calloc   ) ||
-                               (deallocationType == m_alloc_free         && au->allocationType == m_alloc_realloc  ) ||
-                               (deallocationType == m_alloc_unknown                                                ) );
-
-                       // If you hit this assert, then the "break on dealloc" flag for this allocation unit is set. Interrogate the 'au'
-                       // variable to determine information about this allocation unit.
-                       m_assert(au->breakOnDealloc == false);
-
-                       // Wipe the deallocated RAM with a new pattern. This doen't actually do us much good in debug mode under WIN32,
-                       // because Microsoft's memory debugging & tracking utilities will wipe it right after we do. Oh well.
-
-                       wipeWithPattern(au, releasedPattern);
-
-                       // Do the deallocation
-
-                       free(au->actualAddress);
-
-                       // Remove this allocation unit from the hash table
-
-                       unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
-                       if (hashTable[hashIndex] == au)
-                       {
-                               hashTable[hashIndex] = au->next;
-                       }
-                       else
-                       {
-                               if (au->prev)   au->prev->next = au->next;
-                               if (au->next)   au->next->prev = au->prev;
-                       }
-
-                       // Remove this allocation from our stats
-
-                       stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
-                       stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
-                       stats.totalAllocUnitCount--;
-
-                       // Add this allocation unit to the front of our reservoir of unused allocation units
-
-                       memset(au, 0, sizeof(sAllocUnit));
-                       au->next = reservoir;
-                       reservoir = au;
-               }
-
-               // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
-               // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
-
-               resetGlobals();
-
-               // Validate every single allocated unit in memory
-
-               if (alwaysValidateAll) m_validateAllAllocUnits();
-
-               // If we're in the midst of static deinitialization time, track any pending memory leaks
-
-               if (staticDeinitTime) dumpLeakReport();
-       }
-       catch(const char *err)
-       {
-               // Deal with errors
-
-               log("[!] %s", err);
-               resetGlobals();
-       }
-
-       #ifdef TEST_MEMORY_MANAGER
-       log("[D] EXIT : m_deallocator()");
-       #endif
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- The following utilitarian allow you to become proactive in tracking your own memory, or help you narrow in on those tough
-// bugs.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   m_validateAddress(const void *reportedAddress)
-{
-       // Just see if the address exists in our allocation routines
-
-       return findAllocUnit(reportedAddress) != NULL;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   m_validateAllocUnit(const sAllocUnit *allocUnit)
-{
-       // Make sure the padding is untouched
-
-       long    *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
-       long    *post = reinterpret_cast<long *>((char *)allocUnit->actualAddress + allocUnit->actualSize - paddingSize * sizeof(long));
-       bool    errorFlag = false;
-       for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
-       {
-               if (*pre != (long) prefixPattern)
-               {
-                       log("[!] A memory allocation unit was corrupt because of an underrun:");
-                       m_dumpAllocUnit(allocUnit, "  ");
-                       errorFlag = true;
-               }
-
-               // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
-               // owner?) has underrun the allocation unit (modified a few bytes prior to the start). You can interrogate the
-               // variable 'allocUnit' to see statistics and information about this damaged allocation unit.
-               m_assert(*pre == static_cast<long>(prefixPattern));
-
-               if (*post != static_cast<long>(postfixPattern))
-               {
-                       log("[!] A memory allocation unit was corrupt because of an overrun:");
-                       m_dumpAllocUnit(allocUnit, "  ");
-                       errorFlag = true;
-               }
-
-               // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
-               // owner?) has overrun the allocation unit (modified a few bytes after the end). You can interrogate the variable
-               // 'allocUnit' to see statistics and information about this damaged allocation unit.
-               m_assert(*post == static_cast<long>(postfixPattern));
-       }
-
-       // Return the error status (we invert it, because a return of 'false' means error)
-
-       return !errorFlag;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool   m_validateAllAllocUnits()
-{
-       // Just go through each allocation unit in the hash table and count the ones that have errors
-
-       unsigned int    errors = 0;
-       unsigned int    allocCount = 0;
-       for (unsigned int i = 0; i < hashSize; i++)
-       {
-               sAllocUnit      *ptr = hashTable[i];
-               while(ptr)
-               {
-                       allocCount++;
-                       if (!m_validateAllocUnit(ptr)) errors++;
-                       ptr = ptr->next;
-               }
-       }
-
-       // Test for hash-table correctness
-
-       if (allocCount != stats.totalAllocUnitCount)
-       {
-               log("[!] Memory tracking hash table corrupt!");
-               errors++;
-       }
-
-       // If you hit this assert, then the internal memory (hash table) used by this memory tracking software is damaged! The
-       // best way to track this down is to use the alwaysLogAll flag in conjunction with STRESS_TEST macro to narrow in on the
-       // offending code. After running the application with these settings (and hitting this assert again), interrogate the
-       // memory.log file to find the previous successful operation. The corruption will have occurred between that point and this
-       // assertion.
-       m_assert(allocCount == stats.totalAllocUnitCount);
-
-       // If you hit this assert, then you've probably already been notified that there was a problem with a allocation unit in a
-       // prior call to validateAllocUnit(), but this assert is here just to make sure you know about it. :)
-       m_assert(errors == 0);
-
-       // Log any errors
-
-       if (errors) log("[!] While validting all allocation units, %d allocation unit(s) were found to have problems", errors);
-
-       // Return the error status
-
-       return errors != 0;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- Unused RAM calculation routines. Use these to determine how much of your RAM is unused (in bytes)
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-unsigned int   m_calcUnused(const sAllocUnit *allocUnit)
-{
-       const unsigned long     *ptr = reinterpret_cast<const unsigned long *>(allocUnit->reportedAddress);
-       unsigned int            count = 0;
-
-       for (unsigned int i = 0; i < allocUnit->reportedSize; i += sizeof(long), ptr++)
-       {
-               if (*ptr == unusedPattern) count += sizeof(long);
-       }
-
-       return count;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-unsigned int   m_calcAllUnused()
-{
-       // Just go through each allocation unit in the hash table and count the unused RAM
-
-       unsigned int    total = 0;
-       for (unsigned int i = 0; i < hashSize; i++)
-       {
-               sAllocUnit      *ptr = hashTable[i];
-               while(ptr)
-               {
-                       total += m_calcUnused(ptr);
-                       ptr = ptr->next;
-               }
-       }
-
-       return total;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// -DOC- The following functions are for logging and statistics reporting.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   m_dumpAllocUnit(const sAllocUnit *allocUnit, const char *prefix)
-{
-       log("[I] %sAddress (reported): %010p",       prefix, allocUnit->reportedAddress);
-       log("[I] %sAddress (actual)  : %010p",       prefix, allocUnit->actualAddress);
-       log("[I] %sSize (reported)   : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->reportedSize), memorySizeString(static_cast<unsigned int>(allocUnit->reportedSize)));
-       log("[I] %sSize (actual)     : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->actualSize), memorySizeString(static_cast<unsigned int>(allocUnit->actualSize)));
-       log("[I] %sOwner             : %s(%d)::%s",  prefix, allocUnit->sourceFile, allocUnit->sourceLine, allocUnit->sourceFunc);
-       log("[I] %sAllocation type   : %s",          prefix, allocationTypes[allocUnit->allocationType]);
-       log("[I] %sAllocation number : %d",          prefix, allocUnit->allocationNumber);
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   m_dumpMemoryReport(const char *filename, const bool overwrite)
-{
-       // Open the report file
-
-       FILE    *fp = NULL;
-       
-       if (overwrite)  fp = fopen(filename, "w+b");
-       else            fp = fopen(filename, "ab");
-
-       // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
-       // some reason.)
-       m_assert(fp);
-       if (!fp) return;
-
-        // Header
-
-        static  char    timeString[25];
-        memset(timeString, 0, sizeof(timeString));
-        time_t  t = time(NULL);
-        struct  tm *tme = localtime(&t);
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-        fprintf(fp, "|                                             Memory report for: %02d/%02d/%04d %02d:%02d:%02d                                               |\r\n", tme->tm_mon + 1, tme->tm_mday, tme->tm_year + 1900, tme->tm_hour, tme->tm_min, tme->tm_sec);
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "\r\n");
-       fprintf(fp, "\r\n");
-
-       // Report summary
-
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "|                                                           T O T A L S                                                            |\r\n");
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.totalAllocUnitCount));
-       fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.totalReportedMemory));
-       fprintf(fp, "         Actual total memory in use: %s\r\n", memorySizeString(stats.totalActualMemory));
-       fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.totalActualMemory - stats.totalReportedMemory));
-       fprintf(fp, "\r\n");
-
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "|                                                            P E A K S                                                             |\r\n");
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.peakAllocUnitCount));
-       fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.peakReportedMemory));
-       fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.peakActualMemory));
-       fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.peakActualMemory - stats.peakReportedMemory));
-       fprintf(fp, "\r\n");
-
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "|                                                      A C C U M U L A T E D                                                       |\r\n");
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "              Allocation unit count: %s\r\n", memorySizeString(stats.accumulatedAllocUnitCount));
-       fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.accumulatedReportedMemory));
-       fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.accumulatedActualMemory));
-       fprintf(fp, "\r\n");
-
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "|                                                           U N U S E D                                                            |\r\n");
-       fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
-       fprintf(fp, "    Memory allocated but not in use: %s\r\n", memorySizeString(m_calcAllUnused()));
-       fprintf(fp, "\r\n");
-
-       dumpAllocations(fp);
-
-       fclose(fp);
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-sMStats        m_getMemoryStatistics()
-{
-       return stats;
-}
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// mmgr.cpp - End of file
-// ---------------------------------------------------------------------------------------------------------------------------------
-
diff --git a/Source/mmgr.h b/Source/mmgr.h
deleted file mode 100644 (file)
index 550bbd2..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-//                                     _     
-//                                    | |    
-//  _ __ ___  _ __ ___   __ _ _ __    | |__  
-// | '_ ` _ \| '_ ` _ \ / _` | '__|   | '_ \ 
-// | | | | | | | | | | | (_| | |    _ | | | |
-// |_| |_| |_|_| |_| |_|\__, |_|   (_)|_| |_|
-//                       __/ |               
-//                      |___/                
-//
-// Memory manager & tracking software
-//
-// Best viewed with 8-character tabs and (at least) 132 columns
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-//
-// Restrictions & freedoms pertaining to usage and redistribution of this software:
-//
-//  * This software is 100% free
-//  * If you use this software (in part or in whole) you must credit the author.
-//  * This software may not be re-distributed (in part or in whole) in a modified
-//    form without clear documentation on how to obtain a copy of the original work.
-//  * You may not use this software to directly or indirectly cause harm to others.
-//  * This software is provided as-is and without warrantee. Use at your own risk.
-//
-// For more information, visit HTTP://www.FluidStudios.com
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Originally created on 12/22/2000 by Paul Nettle
-//
-// Copyright 2000, Fluid Studios, Inc., all rights reserved.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#ifndef        _H_MMGR
-#define        _H_MMGR
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// For systems that don't have the __FUNCTION__ variable, we can just define it here
-// ---------------------------------------------------------------------------------------------------------------------------------
-#ifndef __FUNCTION__
-#define        __FUNCTION__ "??"
-#endif
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Types
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-typedef        struct tag_au
-{
-       size_t          actualSize;
-       size_t          reportedSize;
-       void            *actualAddress;
-       void            *reportedAddress;
-       char            sourceFile[40];
-       char            sourceFunc[40];
-       unsigned int    sourceLine;
-       unsigned int    allocationType;
-       bool            breakOnDealloc;
-       bool            breakOnRealloc;
-       unsigned int    allocationNumber;
-       struct tag_au   *next;
-       struct tag_au   *prev;
-} sAllocUnit;
-
-typedef        struct
-{
-       unsigned int    totalReportedMemory;
-       unsigned int    totalActualMemory;
-       unsigned int    peakReportedMemory;
-       unsigned int    peakActualMemory;
-       unsigned int    accumulatedReportedMemory;
-       unsigned int    accumulatedActualMemory;
-       unsigned int    accumulatedAllocUnitCount;
-       unsigned int    totalAllocUnitCount;
-       unsigned int    peakAllocUnitCount;
-} sMStats;
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// External constants
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-extern const   unsigned int    m_alloc_unknown;
-extern const   unsigned int    m_alloc_new;
-extern const   unsigned int    m_alloc_new_array;
-extern const   unsigned int    m_alloc_malloc;
-extern const   unsigned int    m_alloc_calloc;
-extern const   unsigned int    m_alloc_realloc;
-extern const   unsigned int    m_alloc_delete;
-extern const   unsigned int    m_alloc_delete_array;
-extern const   unsigned int    m_alloc_free;
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Used by the macros
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void           m_setOwner(const char *file, const unsigned int line, const char *func);
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Allocation breakpoints
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool           &m_breakOnRealloc(void *reportedAddress);
-bool           &m_breakOnDealloc(void *reportedAddress);
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// The meat of the memory tracking software
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void           *m_allocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc,
-                            const unsigned int allocationType, const size_t reportedSize);
-void           *m_reallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc,
-                              const unsigned int reallocationType, const size_t reportedSize, void *reportedAddress);
-void           m_deallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc,
-                             const unsigned int deallocationType, const void *reportedAddress);
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Utilitarian functions
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-bool           m_validateAddress(const void *reportedAddress);
-bool           m_validateAllocUnit(const sAllocUnit *allocUnit);
-bool           m_validateAllAllocUnits();
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Unused RAM calculations
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-unsigned int   m_calcUnused(const sAllocUnit *allocUnit);
-unsigned int   m_calcAllUnused();
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Logging and reporting
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void           m_dumpAllocUnit(const sAllocUnit *allocUnit, const char *prefix = "");
-void           m_dumpMemoryReport(const char *filename = "memreport.log", const bool overwrite = true);
-sMStats                m_getMemoryStatistics();
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Variations of global operators new & delete
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-void   *operator new(size_t reportedSize);
-void   *operator new[](size_t reportedSize);
-void   *operator new(size_t reportedSize, const char *sourceFile, int sourceLine);
-void   *operator new[](size_t reportedSize, const char *sourceFile, int sourceLine);
-void   operator delete(void *reportedAddress);
-void   operator delete[](void *reportedAddress);
-
-#endif // _H_MMGR
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Macros -- "Kids, please don't try this at home. We're trained professionals here." :)
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#include "nommgr.h"
-#define        new             (m_setOwner  (__FILE__,__LINE__,__FUNCTION__),false) ? NULL : new
-#define        delete          (m_setOwner  (__FILE__,__LINE__,__FUNCTION__),false) ? m_setOwner("",0,"") : delete
-#define        malloc(sz)      m_allocator  (__FILE__,__LINE__,__FUNCTION__,m_alloc_malloc,sz)
-#define        calloc(sz)      m_allocator  (__FILE__,__LINE__,__FUNCTION__,m_alloc_calloc,sz)
-#define        realloc(ptr,sz) m_reallocator(__FILE__,__LINE__,__FUNCTION__,m_alloc_realloc,sz,ptr)
-#define        free(ptr)       m_deallocator(__FILE__,__LINE__,__FUNCTION__,m_alloc_free,ptr)
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// mmgr.h - End of file
-// ---------------------------------------------------------------------------------------------------------------------------------
-
diff --git a/Source/nommgr.h b/Source/nommgr.h
deleted file mode 100644 (file)
index af9bce0..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-//                                                 _     
-//                                                | |    
-//  _ __   ___  _ __ ___  _ __ ___   __ _ _ __    | |__  
-// | '_ \ / _ \| '_ ` _ \| '_ ` _ \ / _` | '__|   | '_ \ 
-// | | | | (_) | | | | | | | | | | | (_| | |    _ | | | |
-// |_| |_|\___/|_| |_| |_|_| |_| |_|\__, |_|   (_)|_| |_|
-//                                   __/ |               
-//                                  |___/                
-//
-// Memory manager & tracking software
-//
-// Best viewed with 8-character tabs and (at least) 132 columns
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-//
-// Restrictions & freedoms pertaining to usage and redistribution of this software:
-//
-//  * This software is 100% free
-//  * If you use this software (in part or in whole) you must credit the author.
-//  * This software may not be re-distributed (in part or in whole) in a modified
-//    form without clear documentation on how to obtain a copy of the original work.
-//  * You may not use this software to directly or indirectly cause harm to others.
-//  * This software is provided as-is and without warrantee. Use at your own risk.
-//
-// For more information, visit HTTP://www.FluidStudios.com
-//
-// ---------------------------------------------------------------------------------------------------------------------------------
-// Originally created on 12/22/2000 by Paul Nettle
-//
-// Copyright 2000, Fluid Studios, Inc., all rights reserved.
-// ---------------------------------------------------------------------------------------------------------------------------------
-
-#ifdef new
-#undef new
-#endif
-
-#ifdef delete
-#undef delete
-#endif
-
-#ifdef malloc
-#undef malloc
-#endif
-
-#ifdef calloc
-#undef calloc
-#endif
-
-#ifdef realloc
-#undef realloc
-#endif
-
-#ifdef free
-#undef free
-#endif
-
-// ---------------------------------------------------------------------------------------------------------------------------------
-// nommgr.h - End of file
-// ---------------------------------------------------------------------------------------------------------------------------------
-
diff --git a/Source/nsp_network.c b/Source/nsp_network.c
deleted file mode 100644 (file)
index c7f39e4..0000000
+++ /dev/null
@@ -1,741 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-/*
- * Copyright (c) 2002 Lane Roathe. All rights reserved.
- *     Developed in cooperation with Freeverse, Inc.
- *
- * @APPLE_LICENSE_HEADER_START@
- * 
- * Portions Copyright (c) 1999-2002 Apple Computer, Inc.  All Rights
- * Reserved.  This file contains Original Code and/or Modifications of
- * Original Code as defined in and that are subject to the Apple Public
- * Source License Version 1.1 (the "License").  You may not use this file
- * except in compliance with the License.  Please obtain a copy of the
- * License at http://www.apple.com/publicsource and read it before using
- * this file.
- * 
- * The Original Code and all software distributed under the License are
- * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
- * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
- * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT.  Please see the
- * License for the specific language governing rights and limitations
- * under the License.
- * 
- * @APPLE_LICENSE_HEADER_END@
- *
- * Modified: $Date: 2002/04/27 21:42:01 $
- * Revision: $Id: nsp_network.c,v 1.1 2002/04/27 21:42:01 lane Exp $
- */
-
-/* NOTES:
-
-       - This example is designed so that all networking code is in this one file. The purpose is to make
-               it easier for a programmer to study the basic use of OpenPlay's NetSprocket API and not to
-               demonstrate good programming style or OOP practices.
-
-       - This file is not game independent (hey, that's what OpenPlay is about!), it simply helped me keep
-               the example use of NetSprocket's more managable ... I hope :)
-
-       - I wanted the host (ie, server) to also be a player, and found it was pretty easy to do; I simply
-               made sure that I tracked whether I was a server or client (see the _server variable in main.h) and
-               then when sending all players a message I had to modify the "to" portion of the header and
-               resend it to the host. This means the host is sending itself messages, which works great.
-
-*/
-
-/* ----------------------------------------------------------- Includes */
-
-#include <ctype.h>
-#include <stdio.h>
-#include <time.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include "main.h"
-
-#include "network.h"
-
-/* ----------------------------------------------------------- Macro definitions */
-
-enum
-{
-       kMessageType_Question = 256,
-       kMessageType_Answer,
-
-       kMessageType_Information
-};
-
-#define kPlayerType 1234       /* just defines a way to allow/reject players of different types */
-
-
-/* ----------------------------------------------------------- Type definitions */
-
-/* Questions are sent out in message packets from server to players */
-
-/* NOTE        Message string is ZERO terminated!      */
-/*             This allows us to strcpy, strcmp, etc. on raw packet data       */
-/*             Meaning packet size = sizeof(packet_t) + strlen(string) */
-
-typedef struct
-{
-       NSpMessageHeader  header;
-
-       char            str[1];                 /* message (question, info, etc) string */
-
-}MessagePacket_t, *MessagePacketPtr;
-
-/* Answers are sent from the players to the server in this packet */
-
-typedef struct
-{
-       NSpMessageHeader  header;
-
-       char            answer;                 /* finally, the answer */
-
-}AnswerPacket_t, *AnswerPacketPtr;
-
-/* ----------------------------------------------------------- Local Variables */
-
-/* name of this version of the app*/
-char *GameNameStr = "OpenPlay NSp API Example 1";
-
-/* Local vars used to handle our interaction with OpenPlay's NetSprockets API */
-
-static NSpGameReference                        _gameReference = NULL;          /* general game info */
-static NSpProtocolListReference        _protocolListRef = NULL;        /* list of protocols we've started up */
-
-static NMBoolean _approved;            /* after requesting to join a new game, this tracks whether or not we were approved */
-static NMBoolean _response;            /* true if we get a response following a request to join a new game (else we time out */
-
-/*--------------------------------------------------------------------------------*/
-/*--------------------------------------------------------------------------------*/
-#if __MWERKS__
-       #pragma mark -
-       #pragma mark Ãˆ Local Routines
-       #pragma mark -
-#endif
-
-
-/*--------------------------------------------------------------------------------*/
-/*--------------------------------------------------------------------------------*/
-#if __MWERKS__
-       #pragma mark -
-       #pragma mark Ãˆ Global Routines
-       #pragma mark -
-#endif
-
-unsigned char *GameC2PStr
-(
-       char *s,                        /* source C string */
-       unsigned char *d        /* destination buffer for Pascal string */
-)
-{
-       int c = 0;
-
-       if( s && d )    /* make sure we got got inputs */
-       {
-               while( *s )
-                       d[++c] = (unsigned char)*s++;   /* no blockmove, copy & get length in one shot */
-       }
-       *d = (unsigned char)c;
-
-       return( d );
-}
-
-char *GameP2CStr
-(
-       unsigned char *s,       /* source Pascal string */
-       char *d                         /* buffer to hold converted C string */
-)
-{
-       if( s && d )
-       {
-               memcpy( d, s+1, *s );   /* pretty simple */
-               d[*s] = 0;
-       }
-       return( d );
-}
-
-/* ================================================================================
-       Handle all of the network messages that are sent to this application
-
-        EXIT:  0 == no error, else error code
-*/
-
-void NetworkHandleMessage( void )
-{
-       NSpMessageHeader *mhp;
-       char str[256];                          /* buffer for converted PStrings */
-
-       /* Ask NetSprocket to give us a message if any are waiting */
-
-       mhp = NSpMessage_Get( _gameReference );
-       if( mhp )
-       {
-               /* Print out the type of message received */
-
-               switch(mhp -> what)
-               {
-
-/* --- Handle NetSprocket's generic messages */
-
-                       case kNSpJoinApproved:
-                               printf( "Approved!\n\n", str );
-                               fflush(stdout);
-                               _response = true;
-                               _approved = true;       /* tell our waiting loop that we were approved */
-#if __USE_SIOUX__
-                               {
-                                       NMErr err;
-
-                                       err = NSpGame_GetInfo( _gameReference, &gameInfo );
-                                       if( !err )
-                                               SIOUXSetTitle( gameInfo.name );
-                               }
-#endif
-                               break;
-                       
-                       case kNSpJoinDenied:
-                               GameP2CStr( ((NSpJoinDeniedMessage *)mhp)->reason, str );
-                               printf( "Denied!\n   Reason: %s\n\n", str );
-                               fflush(stdout);
-                               //GameOver();
-
-                               _response = true;
-                               _approved = false;      /* tell our waiting loop we were denied */
-                               break;
-
-                       case kNSpError:
-                               printf( "*** ERROR *** (reported value: %d)\n\n", ((NSpErrorMessage *)mhp)->error );
-                               fflush(stdout);
-
-                               _response = true;
-                               _approved = false;
-                               break;
-                       
-                       case kNSpGameTerminated:
-                               printf( "--- Host Terminated Game ---\n\n" );
-                               fflush(stdout);
-                               //GameOver();
-
-                               _response = true;
-                               _approved = false;
-                               break;
-
-                       case kNSpPlayerJoined:
-                       {
-                               NSpGameInfo gameInfo;
-                               char gamename[256];
-                               NMErr err;
-
-                               err = NSpGame_GetInfo( _gameReference, &gameInfo );
-                               if( !err )
-                                       GameP2CStr( gameInfo.name, gamename );
-                               else
-                                       strcpy( gamename, "ERRROR" );
-
-                               GameP2CStr( ((NSpPlayerJoinedMessage *)mhp)->playerInfo.name, str );
-                               printf( "===> Player %s joined game '%s', %d players now!\n\n",
-                                               str, gamename, ((NSpPlayerJoinedMessage *)mhp)->playerCount );
-                               fflush(stdout);
-
-                               /* Lets go ahead and re-send the current question, as the new guy deserves a shot at it too */
-                               /*if( GameIsHost() )
-                               {
-                                       //QuestionPtr theQuestion = GameGetCurrentQuestion();
-                                       //if (theQuestion)
-                                       //      NetworkSendQuestion(theQuestion->question);
-                               }*/
-                       }
-                       break;
-
-                       case kNSpPlayerLeft:
-                               GameP2CStr( ((NSpPlayerLeftMessage *)mhp)->playerName, str );
-                               printf( "===> Player, %s, Left game, leaving %d players!\n\n",
-                                               str, ((NSpPlayerLeftMessage *)mhp)->playerCount );
-                               fflush(stdout);
-                               break;
-
-                       case kNSpHostChanged:
-                               printf( "===> ??? Host changed to player ID %d\n\n",
-                                               ((NSpHostChangedMessage *)mhp)->newHost );
-                               fflush(stdout);
-                               break;
-
-                       case kNSpGroupCreated:
-                               printf( "===> Player #%d created a new Group, ID %d\n\n",
-                                               ((NSpCreateGroupMessage *)mhp)->requestingPlayer, ((NSpCreateGroupMessage *)mhp)->groupID );
-                               fflush(stdout);
-                               break;
-
-                       case kNSpGroupDeleted:
-                               printf( "===> Player #%d deleted group #%d\n\n",
-                                               ((NSpDeleteGroupMessage *)mhp)->requestingPlayer, ((NSpDeleteGroupMessage *)mhp)->groupID );
-                               fflush(stdout);
-                               break;
-                       
-                       case kNSpPlayerAddedToGroup:
-                               printf( "===> Player %d was added to group %d\n\n",
-                                               ((NSpAddPlayerToGroupMessage *)mhp)->player, ((NSpAddPlayerToGroupMessage *)mhp)->group );
-                               fflush(stdout);
-                               break;
-
-                       case kNSpPlayerRemovedFromGroup:
-                               printf( "===> Player %d was removed from group %d\n\n",
-                                               ((NSpRemovePlayerFromGroupMessage *)mhp)->player, ((NSpRemovePlayerFromGroupMessage *)mhp)->group );
-                               fflush(stdout);
-                               break;
-
-                       case kNSpPlayerTypeChanged:
-                               printf( "===> Player %d changed to a new type, %d\n\n",
-                                               ((NSpPlayerTypeChangedMessage *)mhp)->player, ((NSpPlayerTypeChangedMessage *)mhp)->newType );
-                               break;
-
-
-/* --- Handle our game specific messages */
-
-
-                       /* Got a message, see if it is correct or not and let everyone know the results */
-
-                       case kMessageType_Answer:
-                       {
-                               NSpPlayerInfoPtr pip;
-                               char cname[kNSpStr32Len];
-                               NMErr err;
-
-                               err = NSpPlayer_GetInfo( _gameReference, mhp->from, &pip );
-                               if( !err )
-                               {               
-                                       GameP2CStr( pip->name, cname );
-
-                                       NSpPlayer_ReleaseInfo( _gameReference, pip );
-                               }
-                               else
-                                       strcpy( cname, "UNKOWN -- error!" );
-
-                               //sprintf( str, "Player #%d, %s, answered with '%c', which is %s", mhp->from, cname, ((AnswerPacketPtr)mhp)->answer,
-                                       //GameCheckAnswer( ((AnswerPacketPtr)mhp)->answer ) ? "Correct!" : "WRONG!" );
-
-                               NetworkSendInformation( str );
-                       }
-                       break;
-
-                       /* allow game to do any special processing needed when a question arrives */
-
-                       case kMessageType_Question:
-                               //GameDisplayQuestion( ((MessagePacketPtr)mhp)->str );
-                               break;
-
-                       /* pretty simple, just display the info message */
-
-                       case kMessageType_Information:
-                               printf( "%s\n\n", ((MessagePacketPtr)mhp)->str );
-                               fflush(stdout);
-                               break;
-
-                       default:
-                               break;
-               }
-
-               /* Once done with it, release the message */
-
-               NSpMessage_Release( _gameReference, mhp );
-       }
-}
-
-/* ================================================================================
-       Return the # of players in the current game
-
-        EXIT:  none
-*/
-
-NMUInt32 NetworkGetPlayerCount( void )
-{
-       NSpGameInfo gameInfo;
-       NMErr err;
-
-       err = NSpGame_GetInfo( _gameReference, &gameInfo );     /* player count is in the game info record */
-       if( !err )
-       {
-               return( gameInfo.currentPlayers );
-       }
-
-       return( 0 );
-}
-
-/* ================================================================================
-       Send an answer to the server
-
-        EXIT:  none
-*/
-
-NMErr NetworkSendAnswer
-(
-       char answer                     /* the answer to send (just a char!) */
-)
-{
-       AnswerPacket_t answerPacket;
-       NMErr err;
-
-       /* init the NetSprocket portion of the packet */
-
-       NSpClearMessageHeader( &answerPacket.header );
-
-       answerPacket.header.what = kMessageType_Answer;
-       answerPacket.header.to = kNSpHostOnly;
-       answerPacket.header.messageLen = sizeof(answerPacket);
-
-       /* fill in the data section */
-
-       answerPacket.answer = answer;
-
-       /* tell NetSprocket to send the message */
-
-       err = NSpMessage_Send( _gameReference, &answerPacket.header, kNSpSendFlag_Registered );
-       if( err )
-       {
-               printf( "*** ERROR *** Unable to send answer packet, error # %d\n\n", err );
-               fflush(stdout);
-       }
-
-       return( err );
-}
-
-/* ================================================================================
-       Send a message to all players
-
-        EXIT:  none
-*/
-
-NMErr NetworkSendPlayerMessage
-(
-       const char *message,            /* ptr to message string to send */
-       NMUInt32 messageType            /* type of message (question, info, etc. */
-)
-{
-       MessagePacketPtr qpp;
-       unsigned long messageLen, size;
-       NMErr err;
-
-       /* sanity checks */
-
-       if( !message )
-               return( kNSpInvalidParameterErr );
-
-       /* get size of message string & total size of network packet */
-
-       messageLen = strlen( message );
-       size = sizeof(MessagePacket_t) + messageLen + 1;        /* header + num_chars + terminator */
-
-       /* allocate the memory for the packet */
-
-       qpp = (MessagePacketPtr)malloc( size );
-       if( !qpp )
-       {
-               printf( " *** ERROR *** Unable to allocate message buffer!\n\n" );
-               fflush(stdout);
-               return( kNSpMemAllocationErr );
-       }
-
-       /* init the NetSprocket portion of the packet */
-
-       NSpClearMessageHeader( &qpp->header );
-
-       qpp->header.what = (NMSInt32)messageType;
-       qpp->header.to = kNSpAllPlayers;
-       qpp->header.messageLen = size;
-
-       /* fill in the data section */
-
-       strcpy( qpp->str, message );
-
-       /* tell NetSprocket to send the message */
-
-       err = NSpMessage_Send( _gameReference, &qpp->header, kNSpSendFlag_Registered );
-       if( !err )
-       {
-               qpp->header.to = kNSpHostOnly;          /* allow host to play as well! */
-
-               err = NSpMessage_Send( _gameReference, &qpp->header, kNSpSendFlag_Registered );
-       }
-
-       if( err )
-       {
-               printf( "*** ERROR *** Unable to send message packet, error # %d\n\n", err );
-               fflush(stdout);
-       }
-
-       /* clean up after ourselves! */
-
-       free( qpp );
-
-       return( err );
-}
-
-/* ================================================================================
-       Send a question to all players
-
-        EXIT:  none
-*/
-
-NMErr NetworkSendQuestion
-(
-       const char *question    /* ptr to question string to send */
-)
-{
-       return( NetworkSendPlayerMessage( question, kMessageType_Question ) );
-}
-
-/* ================================================================================
-       Send information to all players
-
-        EXIT:  none
-*/
-
-NMErr NetworkSendInformation
-(
-       const char *message             /* ptr to information string to send */
-)
-{
-       return( NetworkSendPlayerMessage( message, kMessageType_Information ) );
-}
-
-#if __MWERKS__
-       #pragma mark -
-#endif
-
-/* ================================================================================
-       Initialize server networking
-
-        EXIT:  0 == no error, else error code
-*/
-
-NMErr NetworkStartServer
-(
-       NMUInt16 port,                                  /* port clients will connect on */
-       NMUInt32 maxPlayers,                    /* max # of players to allow into game */
-       const unsigned char *gameName,  /* name of game (displayed to clients on connect) */
-       const unsigned char *playerName /* name of player on server computer */
-)
-{
-       NSpProtocolReference protocolRef;
-       NMErr err;
-
-       /* Create a new protocol list to store our IP protocol reference in */
-
-       err = NSpProtocolList_New( NULL, &_protocolListRef );
-       if( !err )
-       {
-               /* Create a protocol reference for our IP connection, on our specified port w/default maxRTT and throughput */
-
-               protocolRef = NSpProtocol_CreateIP( port, 0, 0 );
-               if( protocolRef )
-               {
-                       /* We got a good reference, append it to the list we created earlier */
-
-                       err = NSpProtocolList_Append( _protocolListRef, protocolRef );
-                       if( !err )
-                       {
-                               /* We got a protocol and it's in our reference list, now we can create the game
-                                       to host, using the parms sent in and defaulting rest of the "unused" hosting parms */
-
-                               err = NSpGame_Host( &_gameReference, _protocolListRef, maxPlayers, gameName,
-                                                                       "\pPassword", playerName, kPlayerType, kNSpClientServer, 0 );
-                       }
-               }
-               else
-                       err = kNSpInvalidProtocolRefErr;        /* assign somewhat meaningful error on failure to create protocol reference */
-       }
-
-       return( err );
-}
-
-
-/* ================================================================================
-       Shutdown the networking, release resources, etc.
-
-        EXIT:  0 == no error, else error code
-*/
-
-NMErr NetworkStartClient
-(
-       char *ipAddr,                                   /* IP address (or domain name) to look for server (host) on */
-       char *port,                                             /* Port to talk to server via */
-       const unsigned char *playerName /* name of player wanting to join */
-)
-{
-       NSpAddressReference addRef;
-       NMErr err;
-
-       /* Given our input strings, create an OpenPlay address reference for talking to server */
-
-       addRef = NSpCreateIPAddressReference( ipAddr, port );
-       if( addRef )
-       {
-               printf( "\nAttempting to join game..." );
-               fflush(stdout);
-
-               /* Now, look for a server on the IP/Port given and see if we can connect */
-
-               err = NSpGame_Join( &_gameReference, addRef, playerName, "\pPassword", kPlayerType, NULL, 0, 0 );
-               if( !err )
-               {
-                       NMUInt32 startTime, currentTime;
-                       time_t seconds;
-
-                       printf( "connected!\n\nWaiting for approval to join game (press 'q' to quit)..." );
-                       fflush(stdout);
-
-                       time(&seconds);
-                       startTime = seconds;
-
-                       _response = _approved = false;
-
-                       /* We connected, now we have to wait for the server to approve our join request */
-
-                       while( !_response )
-                       {
-                               /* Check for a time out in connecting to server */
-                               /* this is before the event handler so that we are not approved, but time out anyway (small chance, but...) */
-
-                               time(&seconds);
-                               currentTime = seconds;
-
-                               if( (currentTime - startTime > 60) && (!_response) )
-                               {
-                                       printf( "ERROR: Connection timed out!\n\n" );
-                                       fflush(stdout);
-
-                                       _response = true;
-                                       _approved = false;
-                               }
-
-                               /* Handle system messages and allow user to quit via 'q' */
-                               /* This also gets and handles network messages, like accept/deny */
-
-                               //GameHandleEvents();
-                       }
-
-                       /* if we were not approved, we must dispose of the game object here */
-
-                       if( !_approved )
-                       {
-                               err = NSpGame_Dispose( _gameReference, kNSpGameFlag_ForceTerminateGame );
-                               _gameReference = NULL;
-                       }
-                       else    /* let the user know that they were accepted to the game */
-                       {
-                               NSpGameInfo gameInfo;
-                               char str[256];
-
-                               err = NSpGame_GetInfo( _gameReference, &gameInfo );
-                               if( !err )
-                               {
-                                       GameP2CStr( gameInfo.name, str );
-
-                                       printf( "   Welcome to the game '%s', with %d players\n\n", str, (int)gameInfo.currentPlayers );
-                                       fflush(stdout);
-                               }
-                       }
-               }
-       }
-       else
-               err = kNMParameterErr;
-
-       return( err );
-}
-
-
-#if __MWERKS__
-       #pragma mark -
-#endif
-
-/* ================================================================================
-       Shutdown the networking, release resources, etc.
-
-        EXIT:  0 == no error, else error code
-*/
-
-NMErr NetworkShutdown( void )
-{
-       NMUInt32 refCount;
-       NMErr err = kNMNoError;
-
-       /* if we have a game object (we should!) dispose if it now */
-
-       if( _gameReference )
-               err = NSpGame_Dispose( _gameReference, kNSpGameFlag_ForceTerminateGame );
-
-       /* dispose of our protocol references & the list containing them */
-
-       if( _protocolListRef )
-       {
-               NSpProtocolReference pRef;
-
-               refCount = NSpProtocolList_GetCount( _protocolListRef );        /* get number of protocols */
-
-               while( refCount-- && !err )
-               {
-                       pRef = NSpProtocolList_GetIndexedRef( _protocolListRef, refCount );     /* get currect reference */
-
-                       err = NSpProtocolList_RemoveIndexed( _protocolListRef, refCount );      /* then remove it from the list */
-
-                       /* now, we can dispose of the reference safely */
-                       NSpProtocol_Dispose( pRef );    /* this should have an NMErr return, but has a void return... */
-               }
-
-               /* once all of the protocols are disposed, we can dispose of the containing reference list */
-               NSpProtocolList_Dispose( _protocolListRef );
-       }
-
-
-       /* Make sure we can't use old values */
-
-       _protocolListRef = NULL;
-       _gameReference = NULL;
-       
-       return( err );
-}
-
-/* ================================================================================
-       Startup the networking system (NetSprockets in this case)
-
-        EXIT:  0 == no error, else error code
-*/
-
-NMErr NetworkStartup( void )
-{
-       NMErr err;
-
-       /* First, make sure that NetSprockets is available (we weak linked to OpenPlayStubLib) */
-
-       if( NULL == NSpInitialize )     /*|| NULL == ProtocolAcceptConnection )*/
-               return( errModuleNotFound );
-
-       /* Initialize NetSprockets, 0 == use defaults & NSe1 stands for "NetSprocket Example 1" 
-                       It is an identifier for games of our type on the network */
-
-       err = NSpInitialize( 0, 0, 0, 'NSe1', 0 );
-
-       return( err );
-}
index 1e31312af8f87ebabfa45e2ad8ae2fb077f76108..5e832fb5bc6959099b292cc2eea29e4aeb22184b 100644 (file)
@@ -25,7 +25,9 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 #include <stdlib.h>
 #include <string.h>
 
+#include "Quaternions.h"
 #include "openal_wrapper.h"
+#include "Sounds.h"
 
 // NOTE:
 // FMOD uses a Left Handed Coordinate system, OpenAL uses a Right Handed
@@ -112,37 +114,17 @@ typedef struct OPENAL_SAMPLE
     ALuint bid;  // buffer id.
     int mode;
     int is2d;
-    float min_distance;
 } OPENAL_SAMPLE;
 
-typedef struct OPENAL_STREAM
-{
-    char *name;
-    ALuint bid;  // buffer id.
-    int mode;
-    int is2d;
-} OPENAL_STREAM;
-
 static size_t num_channels = 0;
-static OPENAL_Channels *channels = NULL;
+static OPENAL_Channels *impl_channels = NULL;
 static bool initialized = false;
 static float listener_position[3];
 
-static inline bool source_too_close(const int channel)
-{
-    const OPENAL_Channels *chan = &channels[channel];
-    const float *pos = chan->position;
-    const float distance = sqrtf(powf((pos[0] - listener_position[0]), 2.0f) +
-                                 powf((pos[1] - listener_position[1]), 2.0f) +
-                                 powf((pos[2] - listener_position[2]), 2.0f));
-    return (distance <= chan->sample->min_distance);
-}
-
-
 static void set_channel_position(const int channel, const float x,
                                  const float y, const float z)
 {
-    OPENAL_Channels *chan = &channels[channel];
+    OPENAL_Channels *chan = &impl_channels[channel];
 
     chan->position[0] = x;
     chan->position[1] = y;
@@ -153,7 +135,7 @@ static void set_channel_position(const int channel, const float x,
         return;
 
     const ALuint sid = chan->sid;
-    const bool no_attenuate = ((sptr->is2d) || (source_too_close(channel)));
+    const bool no_attenuate = sptr->is2d;
 
     if (no_attenuate)
     {
@@ -187,7 +169,7 @@ AL_API void OPENAL_3D_Listener_SetAttributes(const float *pos, const float *vel,
     // adjust existing positions...
     for (int i = 0; i < num_channels; i++)
     {
-        const float *p = channels[i].position;
+        const float *p = impl_channels[i].position;
         set_channel_position(i, p[0], p[1], p[2]);
     }
 }
@@ -205,10 +187,14 @@ AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const
     return true;
 }
 
-AL_API void OPENAL_3D_SetDopplerFactor(float scale)
+AL_API signed char OPENAL_3D_SetAttributes_(int channel, const XYZ &pos, const float *vel)
 {
-    if (!initialized) return;
-    // unimplemented...looks like init routines just call this with scale == 0.0f anyhow.
+    if (!initialized) return false;
+    if ((channel < 0) || (channel >= num_channels)) return false;
+
+    set_channel_position(channel, pos.x, pos.y, -pos.z);
+
+    return true;
 }
 
 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags)
@@ -253,10 +239,10 @@ AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned in
     }
 
     num_channels = maxsoftwarechannels;
-    channels = new OPENAL_Channels[maxsoftwarechannels];
-    memset(channels, '\0', sizeof (OPENAL_Channels) * num_channels);
+    impl_channels = new OPENAL_Channels[maxsoftwarechannels];
+    memset(impl_channels, '\0', sizeof (OPENAL_Channels) * num_channels);
     for (int i = 0; i < num_channels; i++)
-        alGenSources(1, &channels[i].sid);  // !!! FIXME: verify this didn't fail!
+        alGenSources(1, &impl_channels[i].sid);  // !!! FIXME: verify this didn't fail!
 
     initialized = true;
     return true;
@@ -271,9 +257,9 @@ AL_API void OPENAL_Close()
     {
         for (int i = 0; i < num_channels; i++)
         {
-            alSourceStop(channels[i].sid);
-            alSourcei(channels[i].sid, AL_BUFFER, 0);
-            alDeleteSources(1, &channels[i].sid);
+            alSourceStop(impl_channels[i].sid);
+            alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
+            alDeleteSources(1, &impl_channels[i].sid);
         }
         ALCdevice *dev = alcGetContextsDevice(ctx);
         alcMakeContextCurrent(NULL);
@@ -283,53 +269,53 @@ AL_API void OPENAL_Close()
     }
 
     num_channels = 0;
-    delete[] channels;
-    channels = NULL;
+    delete[] impl_channels;
+    impl_channels = NULL;
 
     unload_alsyms();
     initialized = false;
 }
 
-AL_API OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
+static OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel)
 {
     if (!initialized) return NULL;
     if ((channel < 0) || (channel >= num_channels)) return NULL;
-    return channels[channel].sample;
+    return impl_channels[channel].sample;
 }
 
-AL_API signed char OPENAL_GetPaused(int channel)
+static signed char OPENAL_GetPaused(int channel)
 {
     if (!initialized) return false;
     if ((channel < 0) || (channel >= num_channels)) return false;
-    if (channels[channel].startpaused)
+    if (impl_channels[channel].startpaused)
         return(true);
 
     ALint state = 0;
-    alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
+    alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
     return((state == AL_PAUSED) ? true : false);
 }
 
-AL_API unsigned int OPENAL_GetLoopMode(int channel)
+static unsigned int OPENAL_GetLoopMode(int channel)
 {
     if (!initialized) return 0;
     if ((channel < 0) || (channel >= num_channels)) return 0;
     ALint loop = 0;
-    alGetSourceiv(channels[channel].sid, AL_LOOPING, &loop);
+    alGetSourceiv(impl_channels[channel].sid, AL_LOOPING, &loop);
     if (loop)
         return(OPENAL_LOOP_NORMAL);
     return OPENAL_LOOP_OFF;
 }
 
-AL_API signed char OPENAL_IsPlaying(int channel)
+static signed char OPENAL_IsPlaying(int channel)
 {
     if (!initialized) return false;
     if ((channel < 0) || (channel >= num_channels)) return false;
     ALint state = 0;
-    alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
+    alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
     return((state == AL_PLAYING) ? true : false);
 }
 
-AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
+static int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
 {
     if (!initialized) return -1;
     if (sptr == NULL) return -1;
@@ -339,7 +325,7 @@ AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *
         for (int i = 0; i < num_channels; i++)
         {
             ALint state = 0;
-            alGetSourceiv(channels[i].sid, AL_SOURCE_STATE, &state);
+            alGetSourceiv(impl_channels[i].sid, AL_SOURCE_STATE, &state);
             if ((state != AL_PLAYING) && (state != AL_PAUSED))
             {
                 channel = i;
@@ -349,15 +335,15 @@ AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *
     }
 
     if ((channel < 0) || (channel >= num_channels)) return -1;
-    alSourceStop(channels[channel].sid);
-    channels[channel].sample = sptr;
-    alSourcei(channels[channel].sid, AL_BUFFER, sptr->bid);
-    alSourcei(channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
+    alSourceStop(impl_channels[channel].sid);
+    impl_channels[channel].sample = sptr;
+    alSourcei(impl_channels[channel].sid, AL_BUFFER, sptr->bid);
+    alSourcei(impl_channels[channel].sid, AL_LOOPING, (sptr->mode == OPENAL_LOOP_OFF) ? AL_FALSE : AL_TRUE);
     set_channel_position(channel, 0.0f, 0.0f, 0.0f);
 
-    channels[channel].startpaused = ((startpaused) ? true : false);
+    impl_channels[channel].startpaused = ((startpaused) ? true : false);
     if (!startpaused)
-        alSourcePlay(channels[channel].sid);
+        alSourcePlay(impl_channels[channel].sid);
     return channel;
 }
 
@@ -374,7 +360,7 @@ static void *decode_to_pcm(const char *_fname, ALenum &format, ALsizei &size, AL
     char *fname = (char *) alloca(strlen(_fname) + 16);
     strcpy(fname, _fname);
     char *ptr = strchr(fname, '.');
-    if (ptr) *ptr = NULL;
+    if (ptr) *ptr = '\0';
     strcat(fname, ".ogg");
 
     // just in case...
@@ -499,11 +485,11 @@ AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
     {
         for (int i = 0; i < num_channels; i++)
         {
-            if (channels[i].sample == sptr)
+            if (impl_channels[i].sample == sptr)
             {
-                alSourceStop(channels[i].sid);
-                alSourcei(channels[i].sid, AL_BUFFER, 0);
-                channels[i].sample = NULL;
+                alSourceStop(impl_channels[i].sid);
+                alSourcei(impl_channels[i].sid, AL_BUFFER, 0);
+                impl_channels[i].sample = NULL;
             }
         }
         alDeleteBuffers(1, &sptr->bid);
@@ -512,7 +498,7 @@ AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr)
     }
 }
 
-AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
+static signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
 {
     if (!initialized) return false;
     if ((mode != OPENAL_LOOP_NORMAL) && (mode != OPENAL_LOOP_OFF)) return false;
@@ -521,27 +507,6 @@ AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode)
     return true;
 }
 
-AL_API signed char OPENAL_Sample_SetMinMaxDistance(OPENAL_SAMPLE *sptr, float mindist, float maxdist)
-{
-    if (!initialized) return false;
-    if (sptr == NULL) return false;
-    sptr->min_distance = mindist;
-    // we ignore maxdist. It's not really important to this game, and the
-    //  FMOD docs suggest that it's worthless anyhow.
-
-    // recalc sources to see if we need to adjust attenuation.
-    for (int i = 0; i < num_channels; i++)
-    {
-        if (channels[i].sample == sptr)
-        {
-            const float *p = channels[i].position;
-            set_channel_position(i, p[0], p[1], p[2]);
-        }
-    }
-
-    return 0;
-}
-
 AL_API signed char OPENAL_SetFrequency(int channel, int freq)
 {
     if (!initialized) return false;
@@ -554,9 +519,9 @@ AL_API signed char OPENAL_SetFrequency(int channel, int freq)
 
     if ((channel < 0) || (channel >= num_channels)) return false;
     if (freq == 8012)  // hack
-        alSourcef(channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
+        alSourcef(impl_channels[channel].sid, AL_PITCH, 8012.0f / 44100.0f);
     else
-        alSourcef(channels[channel].sid, AL_PITCH, 1.0f);
+        alSourcef(impl_channels[channel].sid, AL_PITCH, 1.0f);
     return true;
 }
 
@@ -576,7 +541,7 @@ AL_API signed char OPENAL_SetVolume(int channel, int vol)
     if (vol < 0) vol = 0;
     else if (vol > 255) vol = 255;
     ALfloat gain = ((ALfloat) vol) / 255.0f;
-    alSourcef(channels[channel].sid, AL_GAIN, gain);
+    alSourcef(impl_channels[channel].sid, AL_GAIN, gain);
     return true;
 }
 
@@ -594,17 +559,17 @@ AL_API signed char OPENAL_SetPaused(int channel, signed char paused)
     if ((channel < 0) || (channel >= num_channels)) return false;
 
     ALint state = 0;
-    if (channels[channel].startpaused)
+    if (impl_channels[channel].startpaused)
         state = AL_PAUSED;
     else
-        alGetSourceiv(channels[channel].sid, AL_SOURCE_STATE, &state);
+        alGetSourceiv(impl_channels[channel].sid, AL_SOURCE_STATE, &state);
 
     if ((paused) && (state == AL_PLAYING))
-        alSourcePause(channels[channel].sid);
+        alSourcePause(impl_channels[channel].sid);
     else if ((!paused) && (state == AL_PAUSED))
     {
-        alSourcePlay(channels[channel].sid);
-        channels[channel].startpaused = false;
+        alSourcePlay(impl_channels[channel].sid);
+        impl_channels[channel].startpaused = false;
     }
     return true;
 }
@@ -628,41 +593,36 @@ AL_API signed char OPENAL_StopSound(int channel)
     }
 
     if ((channel < 0) || (channel >= num_channels)) return false;
-    alSourceStop(channels[channel].sid);
-    channels[channel].startpaused = false;
+    alSourceStop(impl_channels[channel].sid);
+    impl_channels[channel].startpaused = false;
     return true;
 }
 
-AL_API OPENAL_STREAM *OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length)
-{
-    return (OPENAL_STREAM *) OPENAL_Sample_Load(OPENAL_FREE, name_or_data, mode, offset, length);
-}
-
 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream)
 {
     OPENAL_Sample_Free((OPENAL_SAMPLE *) stream);
 }
 
-AL_API OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
+static OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream)
 {
     if (!initialized) return NULL;
     return (OPENAL_SAMPLE *) stream;
 }
 
-AL_API int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
+static int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused)
 {
     return OPENAL_PlaySoundEx(channel, (OPENAL_SAMPLE *) stream, dsp, startpaused);
 }
 
-AL_API signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
+static signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream)
 {
     if (!initialized) return false;
     for (int i = 0; i < num_channels; i++)
     {
-        if (channels[i].sample == (OPENAL_SAMPLE *) stream)
+        if (impl_channels[i].sample == (OPENAL_SAMPLE *) stream)
         {
-            alSourceStop(channels[i].sid);
-            channels[i].startpaused = false;
+            alSourceStop(impl_channels[i].sid);
+            impl_channels[i].startpaused = false;
         }
     }
     return true;
@@ -684,5 +644,59 @@ AL_API signed char OPENAL_SetOutput(int outputtype)
     return true;
 }
 
+extern int channels[];
+
+extern "C" void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
+{
+       const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
+       if (currSample && currSample == samp[chan])
+       {
+               if (OPENAL_GetPaused(channels[chan]))
+               {
+                       OPENAL_StopSound(channels[chan]);
+                       channels[chan] = OPENAL_FREE;
+               }
+               else if (OPENAL_IsPlaying(channels[chan]))
+               {
+                       int loop_mode = OPENAL_GetLoopMode(channels[chan]);
+                       if (loop_mode & OPENAL_LOOP_OFF)
+                       {
+                               channels[chan] = OPENAL_FREE;
+                       }
+               }
+       }
+       else
+       {
+               channels[chan] = OPENAL_FREE;
+       }
+
+       channels[chan] = OPENAL_PlaySoundEx(channels[chan], sptr, dsp, startpaused);
+       if (channels[chan] < 0)
+       {
+               channels[chan] = OPENAL_PlaySoundEx(OPENAL_FREE, sptr, dsp, startpaused);
+       }
+}
+
+extern "C" void PlayStreamEx(int chan, OPENAL_STREAM *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused)
+{
+       const OPENAL_SAMPLE * currSample = OPENAL_GetCurrentSample(channels[chan]);
+       if (currSample && currSample == OPENAL_Stream_GetSample(sptr))
+       {
+                       OPENAL_StopSound(channels[chan]);
+                       OPENAL_Stream_Stop(sptr);
+       }
+       else
+       {
+               OPENAL_Stream_Stop(sptr);
+               channels[chan] = OPENAL_FREE;
+       }
+
+       channels[chan] = OPENAL_Stream_PlayEx(channels[chan], sptr, dsp, startpaused);
+       if (channels[chan] < 0)
+       {
+               channels[chan] = OPENAL_Stream_PlayEx(OPENAL_FREE, sptr, dsp, startpaused);
+       }
+}
+
 #endif
 
index 44fb7ecb62ba6e94db7939b70e88a9315822e8bf..e0c8b7d7b586ec190edac1160e2bd88a90db2fb2 100644 (file)
@@ -44,7 +44,7 @@
 
 
 typedef struct OPENAL_SAMPLE    OPENAL_SAMPLE;
-typedef struct OPENAL_STREAM    OPENAL_STREAM;
+typedef OPENAL_SAMPLE    OPENAL_STREAM;
 typedef struct OPENAL_DSPUNIT   OPENAL_DSPUNIT;
 
 enum OPENAL_OUTPUTTYPES
@@ -70,42 +70,25 @@ extern "C" {
 
 AL_API void OPENAL_3D_Listener_SetAttributes(const float *pos, const float *vel, float fx, float fy, float fz, float tx, float ty, float tz);
 AL_API signed char OPENAL_3D_SetAttributes(int channel, const float *pos, const float *vel);
-AL_API void OPENAL_3D_SetDopplerFactor(float scale);
+AL_API signed char OPENAL_3D_SetAttributes_(int channel, const XYZ &pos, const float *vel);
 AL_API signed char OPENAL_Init(int mixrate, int maxsoftwarechannels, unsigned int flags);
 AL_API void OPENAL_Close();
-AL_API OPENAL_SAMPLE *OPENAL_GetCurrentSample(int channel);
-AL_API signed char OPENAL_GetPaused(int channel);
-AL_API unsigned int OPENAL_GetLoopMode(int channel);
-AL_API signed char OPENAL_IsPlaying(int channel);
-AL_API int OPENAL_PlaySoundEx(int channel, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
 AL_API OPENAL_SAMPLE *OPENAL_Sample_Load(int index, const char *name_or_data, unsigned int mode, int offset, int length);
 AL_API void OPENAL_Sample_Free(OPENAL_SAMPLE *sptr);
-AL_API signed char OPENAL_Sample_SetMode(OPENAL_SAMPLE *sptr, unsigned int mode);
-AL_API signed char OPENAL_Sample_SetMinMaxDistance(OPENAL_SAMPLE *sptr, float mindist, float maxdist);
 AL_API signed char OPENAL_SetFrequency(int channel, int freq);
 AL_API signed char OPENAL_SetVolume(int channel, int vol);
 AL_API signed char OPENAL_SetPaused(int channel, signed char paused);
 AL_API void OPENAL_SetSFXMasterVolume(int volume);
 AL_API signed char OPENAL_StopSound(int channel);
-AL_API OPENAL_STREAM *OPENAL_Stream_Open(const char *name_or_data, unsigned int mode, int offset, int length);
 AL_API void OPENAL_Stream_Close(OPENAL_STREAM *stream);
-AL_API OPENAL_SAMPLE *OPENAL_Stream_GetSample(OPENAL_STREAM *stream);
-AL_API int OPENAL_Stream_PlayEx(int channel, OPENAL_STREAM *stream, OPENAL_DSPUNIT *dsp, signed char startpaused);
-AL_API signed char OPENAL_Stream_Stop(OPENAL_STREAM *stream);
 AL_API signed char OPENAL_Stream_SetMode(OPENAL_STREAM *stream, unsigned int mode);
 AL_API void OPENAL_Update();
 AL_API signed char OPENAL_SetOutput(int outputtype);
+void PlaySoundEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
+void PlayStreamEx(int chan, OPENAL_SAMPLE *sptr, OPENAL_DSPUNIT *dsp, signed char startpaused);
 
 #ifdef __cplusplus
 }
 #endif
 
-#if USE_OPENAL
-#  define OPENAL_Sample_LoadEx(a, b, c, d, e) OPENAL_Sample_Load( a, ConvertFileName( b), c, d, e)
-#  define OPENAL_Stream_OpenEx(a, b, c, d) OPENAL_Stream_Open(ConvertFileName(a), b, c, d)
-#elif !PLATFORM_MACOSX
-#  define OPENAL_Sample_LoadEx(a, b, c, d, e) OPENAL_Sample_Load( a, ConvertFileName( b), c, d, e)
-#  define OPENAL_Stream_OpenEx(a, b, c, d) OPENAL_Stream_Open(ConvertFileName(a), b, c, d)
-#endif
-
 #endif
index e410ab438f9fe3c42538f2dfa894d810801c4977..7c371f8ff83b6f8a2bdafd242d61c651e0710993 100644 (file)
@@ -23,7 +23,83 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "binio.h"
 #include "private.h"
-#include "pack_private.h"
+
+struct BinIOPackContext
+{
+    uint8_t *buffer;
+    va_list  args;
+};
+
+static void BinIOPack(void *context, int type, int byte_order, int count)
+{
+    struct BinIOPackContext *ctx = (struct BinIOPackContext*)context;
+    if (count == -1)
+    {
+        switch (type)
+        {
+            case BinIO_TYPE_IGNORE_BYTE:
+                {
+                    ctx->buffer += 1;
+                }
+                break;
+            case BinIO_TYPE_BYTE:
+                {
+                    uint8_t value = va_arg(ctx->args, int);
+                    BinIOConvert1(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
+                    ctx->buffer += 1;
+                }
+                break;
+            case BinIO_TYPE_INT16:
+                {
+                    uint16_t value = va_arg(ctx->args, int);
+                    BinIOConvert2(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
+                    ctx->buffer += 2;
+                }
+                break;
+            case BinIO_TYPE_INT32:
+                {
+                    int value = va_arg(ctx->args, int);
+                    BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
+                    ctx->buffer += 4;
+                }
+                break;
+            case BinIO_TYPE_INT64:
+                {
+                    uint64_t value = va_arg(ctx->args, uint64_t);
+                    BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
+                    ctx->buffer += 8;
+                }
+                break;
+            case BinIO_TYPE_FLOAT32:
+                {
+                    float32_t value = (float32_t)va_arg(ctx->args, double);
+                    BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
+                    ctx->buffer += 4;
+                }
+                break;
+            case BinIO_TYPE_FLOAT64:
+                {
+                    float64_t value = va_arg(ctx->args, float64_t);
+                    BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
+                    ctx->buffer += 8;
+                }
+                break;
+        }
+    }
+    else
+    {
+        switch (type)
+        {
+            case BinIO_TYPE_IGNORE_BYTE:                                                                                                     ctx->buffer += 1 * count; break;
+            case BinIO_TYPE_BYTE:        BinIOConvert1(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 1 * count; break;
+            case BinIO_TYPE_INT16:       BinIOConvert2(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 2 * count; break;
+            case BinIO_TYPE_INT32:       BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 4 * count; break;
+            case BinIO_TYPE_INT64:       BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 8 * count; break;
+            case BinIO_TYPE_FLOAT32:     BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 4 * count; break;
+            case BinIO_TYPE_FLOAT64:     BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 8 * count; break;
+        }
+    }
+}
 
 extern void packf(const char *format, ...)
 {
diff --git a/Source/pack_private.c b/Source/pack_private.c
deleted file mode 100644 (file)
index a501751..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#include "pack_private.h"
-
-void BinIOPack(void *context, int type, int byte_order, int count)
-{
-    struct BinIOPackContext *ctx = (struct BinIOPackContext*)context;
-    if (count == -1)
-    {
-        switch (type)
-        {
-            case BinIO_TYPE_IGNORE_BYTE:
-                {
-                    ctx->buffer += 1;
-                }
-                break;
-            case BinIO_TYPE_BYTE:
-                {
-                    uint8_t value = va_arg(ctx->args, int);
-                    BinIOConvert1(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
-                    ctx->buffer += 1;
-                }
-                break;
-            case BinIO_TYPE_INT16:
-                {
-                    uint16_t value = va_arg(ctx->args, int);
-                    BinIOConvert2(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
-                    ctx->buffer += 2;
-                }
-                break;
-            case BinIO_TYPE_INT32:
-                {
-                    int value = va_arg(ctx->args, int);
-                    BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
-                    ctx->buffer += 4;
-                }
-                break;
-            case BinIO_TYPE_INT64:
-                {
-                    uint64_t value = va_arg(ctx->args, uint64_t);
-                    BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
-                    ctx->buffer += 8;
-                }
-                break;
-            case BinIO_TYPE_FLOAT32:
-                {
-                    float32_t value = (float32_t)va_arg(ctx->args, double);
-                    BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
-                    ctx->buffer += 4;
-                }
-                break;
-            case BinIO_TYPE_FLOAT64:
-                {
-                    float64_t value = va_arg(ctx->args, float64_t);
-                    BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, (const uint8_t *)&value, ctx->buffer, 1);
-                    ctx->buffer += 8;
-                }
-                break;
-        }
-    }
-    else
-    {
-        switch (type)
-        {
-            case BinIO_TYPE_IGNORE_BYTE:                                                                                                     ctx->buffer += 1 * count; break;
-            case BinIO_TYPE_BYTE:        BinIOConvert1(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 1 * count; break;
-            case BinIO_TYPE_INT16:       BinIOConvert2(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 2 * count; break;
-            case BinIO_TYPE_INT32:       BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 4 * count; break;
-            case BinIO_TYPE_INT64:       BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 8 * count; break;
-            case BinIO_TYPE_FLOAT32:     BinIOConvert4(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 4 * count; break;
-            case BinIO_TYPE_FLOAT64:     BinIOConvert8(BinIO_HOST_BYTE_ORDER, byte_order, va_arg(ctx->args, uint8_t *), ctx->buffer, count); ctx->buffer += 8 * count; break;
-        }
-    }
-}
diff --git a/Source/pack_private.h b/Source/pack_private.h
deleted file mode 100644 (file)
index 2a96dbb..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#ifndef pack_private_h
-#define pack_private_h
-
-#include "private.h"
-
-struct BinIOPackContext
-{
-    uint8_t *buffer;
-    va_list  args;
-};
-
-extern void BinIOPack(void *context, int type, int byte_order, int count);
-
-#endif
-
index 7715cc0f8f81ca279b68a5e4a67a9dee9cfdea34..c40c5b7cb42ecda8d20990a4d6f915bb1d10c067 100644 (file)
@@ -23,7 +23,32 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 #include "binio.h"
 #include "private.h"
-#include "unpack_private.h"
+
+struct BinIOUnpackContext
+{
+    const uint8_t *data;
+    va_list        args;
+};
+
+static void BinIOUnpack(void *context, int type, int byte_order, int count)
+{
+    struct BinIOUnpackContext *ctx = (struct BinIOUnpackContext*)context;
+    if (count == -1)
+    {
+        count = 1;
+    }
+
+    switch (type)
+    {
+        case BinIO_TYPE_IGNORE_BYTE:                                                                                                   ctx->data += 1 * count; break;
+        case BinIO_TYPE_BYTE:        BinIOConvert1(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 1 * count; break;
+        case BinIO_TYPE_INT16:       BinIOConvert2(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 2 * count; break;
+        case BinIO_TYPE_INT32:       BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 4 * count; break;
+        case BinIO_TYPE_INT64:       BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 8 * count; break;
+        case BinIO_TYPE_FLOAT32:     BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 4 * count; break;
+        case BinIO_TYPE_FLOAT64:     BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 8 * count; break;
+    }
+}
 
 void unpackf(const char *format, ...)
 {
diff --git a/Source/unpack_private.c b/Source/unpack_private.c
deleted file mode 100644 (file)
index 45ed1dd..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#include "unpack_private.h"
-
-extern void BinIOUnpack(void *context, int type, int byte_order, int count)
-{
-    struct BinIOUnpackContext *ctx = (struct BinIOUnpackContext*)context;
-    if (count == -1)
-    {
-        count = 1;
-    }
-
-    switch (type)
-    {
-        case BinIO_TYPE_IGNORE_BYTE:                                                                                                   ctx->data += 1 * count; break;
-        case BinIO_TYPE_BYTE:        BinIOConvert1(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 1 * count; break;
-        case BinIO_TYPE_INT16:       BinIOConvert2(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 2 * count; break;
-        case BinIO_TYPE_INT32:       BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 4 * count; break;
-        case BinIO_TYPE_INT64:       BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 8 * count; break;
-        case BinIO_TYPE_FLOAT32:     BinIOConvert4(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 4 * count; break;
-        case BinIO_TYPE_FLOAT64:     BinIOConvert8(byte_order, BinIO_HOST_BYTE_ORDER, ctx->data, va_arg(ctx->args, uint8_t *), count); ctx->data += 8 * count; break;
-    }
-}
diff --git a/Source/unpack_private.h b/Source/unpack_private.h
deleted file mode 100644 (file)
index d30969f..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
-Copyright (C) 2003, 2010 - Wolfire Games
-
-This file is part of Lugaru.
-
-Lugaru is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-*/
-
-#ifndef unpack_private_h
-#define unpack_private_h
-
-#include "private.h"
-
-struct BinIOUnpackContext
-{
-    const uint8_t *data;
-    va_list        args;
-};
-
-extern void BinIOUnpack(void *context, int type, int byte_order, int count);
-
-#endif
-