Merge branch 'develop'

This commit is contained in:
jacksonmj 2015-05-15 17:24:06 +01:00
commit 26e170abcd
202 changed files with 3935 additions and 3157 deletions

1
.gitignore vendored
View File

@ -15,6 +15,7 @@ stderr.txt
build*/* build*/*
stamps/* stamps/*
Saves/* Saves/*
scripts/*
generated/* generated/*
includes/* includes/*
generate generate

View File

@ -68,8 +68,10 @@ AddSconsOption('opengl-renderer', False, False, "Build with OpenGL renderer supp
AddSconsOption('renderer', False, False, "Build the save renderer.") AddSconsOption('renderer', False, False, "Build the save renderer.")
AddSconsOption('wall', False, False, "Error on all warnings.") AddSconsOption('wall', False, False, "Error on all warnings.")
AddSconsOption('no-warnings', True, False, "Disable all compiler warnings (default).") AddSconsOption('no-warnings', False, False, "Disable all compiler warnings.")
AddSconsOption('nolua', False, False, "Disable Lua.") AddSconsOption('nolua', False, False, "Disable Lua.")
AddSconsOption('luajit', False, False, "Enable LuaJIT")
AddSconsOption('lua52', False, False, "Compile using lua 5.2")
AddSconsOption('nofft', False, False, "Disable FFT.") AddSconsOption('nofft', False, False, "Disable FFT.")
AddSconsOption("output", False, True, "Executable output name.") AddSconsOption("output", False, True, "Executable output name.")
@ -92,7 +94,9 @@ if msvc and platform != "Windows":
FatalError("Error: --msvc only works on windows") FatalError("Error: --msvc only works on windows")
#Create SCons Environment #Create SCons Environment
if platform == "Windows" and not GetOption('msvc'): if GetOption('msvc'):
env = Environment(tools = ['default'], ENV = {'PATH' : os.environ['PATH'], 'TMP' : os.environ['TMP']}, TARGET_ARCH = 'x86')
elif platform == "Windows" and not GetOption('msvc'):
env = Environment(tools = ['mingw'], ENV = {'PATH' : os.environ['PATH']}) env = Environment(tools = ['mingw'], ENV = {'PATH' : os.environ['PATH']})
else: else:
env = Environment(tools = ['default'], ENV = {'PATH' : os.environ['PATH']}) env = Environment(tools = ['default'], ENV = {'PATH' : os.environ['PATH']})
@ -168,6 +172,7 @@ if GetOption("msvc"):
env.Append(LIBPATH=['StaticLibs/']) env.Append(LIBPATH=['StaticLibs/'])
else: else:
env.Append(LIBPATH=['Libraries/']) env.Append(LIBPATH=['Libraries/'])
env.Append(CPPPATH=['includes/'])
#Check 32/64 bit #Check 32/64 bit
def CheckBit(context): def CheckBit(context):
@ -249,28 +254,46 @@ def findLibs(env, conf):
if not GetOption('nolua') and not GetOption('renderer'): if not GetOption('nolua') and not GetOption('renderer'):
#Look for Lua #Look for Lua
luaver = "lua5.1" luaver = "lua5.1"
if not conf.CheckLib(['lua5.1', 'lua-5.1', 'lua51', 'lua']): if GetOption('luajit'):
if conf.CheckLib(['lua5.2', 'lua-5.2', 'lua52']): if not conf.CheckLib(['luajit-5.1', 'luajit5.1', 'luajit', 'libluajit']):
FatalError("luajit development library not found or not installed")
env.Append(CPPDEFINES=["LUAJIT"])
luaver = "luajit"
elif GetOption('lua52'):
if not conf.CheckLib(['lua5.2', 'lua-5.2', 'lua52']):
FatalError("lua5.2 development library not found or not installed")
env.Append(CPPDEFINES=["LUA_COMPAT_ALL"]) env.Append(CPPDEFINES=["LUA_COMPAT_ALL"])
luaver = "lua5.2" luaver = "lua5.2"
elif platform != "Darwin" or not conf.CheckFramework("Lua"): else:
if not conf.CheckLib(['lua5.1', 'lua-5.1', 'lua51', 'lua']):
if platform != "Darwin" or not conf.CheckFramework("Lua"):
FatalError("lua5.1 development library not found or not installed") FatalError("lua5.1 development library not found or not installed")
foundpkg = False
if platform == "Linux": if platform == "Linux":
try: try:
env.ParseConfig("pkg-config --cflags {0}".format(luaver)) env.ParseConfig("pkg-config --cflags {0}".format(luaver))
env.ParseConfig("pkg-config --libs {0}".format(luaver)) env.ParseConfig("pkg-config --libs {0}".format(luaver))
env.Append(CPPDEFINES=["LUA_R_INCL"])
foundpkg = True
except: except:
pass pass
if not foundpkg:
#Look for lua.h #Look for lua.h
if not conf.CheckCHeader('lua.h'): foundheader = False
if conf.CheckCHeader('lua5.1/lua.h'): if GetOption('luajit'):
env.Append(CPPDEFINES=["LUA_INC"]) foundheader = conf.CheckCHeader('luajit-2.0/lua.h')
elif GetOption('lua52'):
foundheader = conf.CheckCHeader('lua5.2/lua.h')
else:
foundheader = conf.CheckCHeader('lua5.1/lua.h')
if not foundheader:
if conf.CheckCHeader('lua.h'):
env.Append(CPPDEFINES=["LUA_R_INCL"])
else: else:
FatalError("lua.h not found") FatalError("lua.h not found")
#Look for fftw #Look for fftw
if not GetOption('nofft') and not conf.CheckLib(['fftw3f', 'fftw3f-3', 'libfftw3f-3']): if not GetOption('nofft') and not conf.CheckLib(['fftw3f', 'fftw3f-3', 'libfftw3f-3', 'libfftw3f']):
FatalError("fftw3f development library not found or not installed") FatalError("fftw3f development library not found or not installed")
#Look for bz2 #Look for bz2
@ -282,7 +305,7 @@ def findLibs(env, conf):
FatalError("bzip2 headers not found") FatalError("bzip2 headers not found")
#Look for libz #Look for libz
if not conf.CheckLib('z'): if not conf.CheckLib(['z', 'zlib']):
FatalError("libz not found or not installed") FatalError("libz not found or not installed")
#Look for pthreads #Look for pthreads
@ -342,14 +365,14 @@ elif not GetOption('help'):
conf.AddTest('CheckBit', CheckBit) conf.AddTest('CheckBit', CheckBit)
if not conf.CheckCC() or not conf.CheckCXX(): if not conf.CheckCC() or not conf.CheckCXX():
FatalError("compiler not correctly configured") FatalError("compiler not correctly configured")
if platform == compilePlatform and isX86 and not GetOption('32bit') and not GetOption('64bit'): if platform == compilePlatform and isX86 and not GetOption('32bit') and not GetOption('64bit') and not GetOption('msvc'):
conf.CheckBit() conf.CheckBit()
findLibs(env, conf) findLibs(env, conf)
env = conf.Finish() env = conf.Finish()
if not msvc: if not msvc:
if platform == "Windows": if platform == "Windows":
env.Append(CCFLAGS=['-std=gnu++98']) env.Append(CXXFLAGS=['-std=gnu++98'])
else: else:
env.Append(CXXFLAGS=['-std=c++98']) env.Append(CXXFLAGS=['-std=c++98'])
env.Append(CXXFLAGS=['-Wno-invalid-offsetof']) env.Append(CXXFLAGS=['-Wno-invalid-offsetof'])
@ -381,6 +404,7 @@ if isX86:
if not GetOption('no-sse'): if not GetOption('no-sse'):
if GetOption('sse'): if GetOption('sse'):
if msvc: if msvc:
if not GetOption('sse2'):
env.Append(CCFLAGS=['/arch:SSE']) env.Append(CCFLAGS=['/arch:SSE'])
else: else:
env.Append(CCFLAGS=['-msse']) env.Append(CCFLAGS=['-msse'])

View File

@ -2,7 +2,7 @@
#define FONT_H_CHECK #define FONT_H_CHECK
#define FONT_H 10 #define FONT_H 10
#ifdef INCLUDE_FONTDATA #ifdef INCLUDE_FONTDATA
char font_data[] = { unsigned char font_data[] = {
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
@ -295,7 +295,7 @@ short font_ptrs[] = {
0x11A1, 0x11B1, 0x11C1, 0x11D1, 0x11E1, 0x11F1, 0x1201, 0x1211, 0x11A1, 0x11B1, 0x11C1, 0x11D1, 0x11E1, 0x11F1, 0x1201, 0x1211,
}; };
#else #else
extern char font_data[]; extern unsigned char font_data[];
extern short font_ptrs[]; extern short font_ptrs[];
#endif #endif
#endif #endif

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -19,7 +19,7 @@
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/ */
static unsigned char icon_doc_32_png[] = { const static unsigned char icon_doc_32_png[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x08, 0x06, 0x00, 0x00, 0x00, 0x73, 0x7a, 0x7a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x08, 0x06, 0x00, 0x00, 0x00, 0x73, 0x7a, 0x7a,
0xf4, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0xf4, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00,
@ -100,7 +100,7 @@ static unsigned char icon_doc_32_png[] = {
0xbf, 0x2f, 0x89, 0x69, 0x46, 0x25, 0x68, 0x1c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0xbf, 0x2f, 0x89, 0x69, 0x46, 0x25, 0x68, 0x1c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
0x44, 0xae, 0x42, 0x60, 0x82 0x44, 0xae, 0x42, 0x60, 0x82
}; };
static unsigned char icon_doc_16_png[] = { const static unsigned char icon_doc_16_png[] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff,
0x61, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00,

File diff suppressed because one or more lines are too long

View File

@ -36,10 +36,14 @@ def generateElements(elementFiles, outputCpp, outputH):
directives.append(match.split(" ")) directives.append(match.split(" "))
classDirectives = [] classDirectives = []
usedIDs = []
for d in directives: for d in directives:
if d[0] == "ElementClass": if d[0] == "ElementClass":
d[3] = int(d[3]) d[3] = int(d[3])
classDirectives.append(d) classDirectives.append(d)
if d[3] in usedIDs:
print("WARNING: duplicate element ID {} ({})".format(d[3],d[2]))
usedIDs.append(d[3])
elementIDs = sorted(classDirectives, key=lambda directive: directive[3]) elementIDs = sorted(classDirectives, key=lambda directive: directive[3])
@ -168,12 +172,16 @@ def generateTools(toolFiles, outputCpp, outputH):
directives.append(match.split(" ")) directives.append(match.split(" "))
classDirectives = [] classDirectives = []
usedIDs = []
for d in directives: for d in directives:
if d[0] == "ToolClass": if d[0] == "ToolClass":
toolClasses[d[1]] = [] toolClasses[d[1]] = []
toolHeader += "#define %s %s\n" % (d[2], d[3]) toolHeader += "#define %s %s\n" % (d[2], d[3])
d[3] = int(d[3]) d[3] = int(d[3])
classDirectives.append(d) classDirectives.append(d)
if d[3] in usedIDs:
print("WARNING: duplicate tool ID {} ({})".format(d[3],d[2]))
usedIDs.append(d[3])
for d in directives: for d in directives:
if d[0] == "ToolHeader": if d[0] == "ToolHeader":

View File

@ -87,11 +87,11 @@ std::string format::CleanString(std::string dirtyString, size_t maxVisualSize, s
{ {
newString = newString.substr(0, maxVisualSize/10); newString = newString.substr(0, maxVisualSize/10);
} }
for(int i = 0; i < newString.size(); i++){ for (unsigned int i = 0; i < newString.size(); i++)
if(!(newString[i]>=' ' && newString[i]<127)){ //Clamp to ASCII range {
if (!(newString[i]>=' ' && newString[i]<127)) //Clamp to ASCII range
newString[i] = '?'; //Replace with "huh" char newString[i] = '?'; //Replace with "huh" char
} }
}
return newString; return newString;
} }
@ -113,11 +113,11 @@ std::string format::CleanString(char * dirtyData, size_t maxVisualSize, size_t m
{ {
newString = newString.substr(0, maxVisualSize/10); newString = newString.substr(0, maxVisualSize/10);
} }
for(int i = 0; i < newString.size(); i++){ for (unsigned int i = 0; i < newString.size(); i++)
if(!(newString[i]>=' ' && newString[i]<127)){ //Clamp to ASCII range {
if (!(newString[i]>=' ' && newString[i]<127)) //Clamp to ASCII range
newString[i] = '?'; //Replace with "huh" char newString[i] = '?'; //Replace with "huh" char
} }
}
return newString; return newString;
} }
@ -213,7 +213,7 @@ std::vector<char> format::VideoBufferToPPM(const VideoBuffer & vidBuf)
} }
data.insert(data.end(), currentRow, currentRow+(vidBuf.Width*3)); data.insert(data.end(), currentRow, currentRow+(vidBuf.Width*3));
} }
delete currentRow; delete [] currentRow;
return data; return data;
} }
@ -228,11 +228,11 @@ struct PNGChunk
PNGChunk(int length, std::string name) PNGChunk(int length, std::string name)
{ {
if(name.length()!=4) if (name.length()!=4)
throw std::runtime_error("Invalid chunk name"); throw std::runtime_error("Invalid chunk name");
std::copy(name.begin(), name.begin()+4, Name); std::copy(name.begin(), name.begin()+4, Name);
Length = length; Length = length;
if(length) if (length)
{ {
Data = new char[length]; Data = new char[length];
std::fill(Data, Data+length, 0); std::fill(Data, Data+length, 0);
@ -244,7 +244,7 @@ struct PNGChunk
} }
unsigned long CRC() unsigned long CRC()
{ {
if(!Data) if (!Data)
{ {
return format::CalculateCRC((unsigned char*)Name, 4); return format::CalculateCRC((unsigned char*)Name, 4);
} }
@ -260,7 +260,7 @@ struct PNGChunk
} }
~PNGChunk() ~PNGChunk()
{ {
if(Data) if (Data)
delete[] Data; delete[] Data;
} }
}; };
@ -270,28 +270,28 @@ std::vector<char> format::VideoBufferToPNG(const VideoBuffer & vidBuf)
std::vector<PNGChunk*> chunks; std::vector<PNGChunk*> chunks;
//Begin IHDR (Image header) chunk (Image size and depth) //Begin IHDR (Image header) chunk (Image size and depth)
PNGChunk IHDRChunk = PNGChunk(13, "IHDR"); PNGChunk *IHDRChunk = new PNGChunk(13, "IHDR");
//Image Width //Image Width
IHDRChunk.Data[0] = (vidBuf.Width>>24)&0xFF; IHDRChunk->Data[0] = (vidBuf.Width>>24)&0xFF;
IHDRChunk.Data[1] = (vidBuf.Width>>16)&0xFF; IHDRChunk->Data[1] = (vidBuf.Width>>16)&0xFF;
IHDRChunk.Data[2] = (vidBuf.Width>>8)&0xFF; IHDRChunk->Data[2] = (vidBuf.Width>>8)&0xFF;
IHDRChunk.Data[3] = (vidBuf.Width)&0xFF; IHDRChunk->Data[3] = (vidBuf.Width)&0xFF;
//Image Height //Image Height
IHDRChunk.Data[4] = (vidBuf.Height>>24)&0xFF; IHDRChunk->Data[4] = (vidBuf.Height>>24)&0xFF;
IHDRChunk.Data[5] = (vidBuf.Height>>16)&0xFF; IHDRChunk->Data[5] = (vidBuf.Height>>16)&0xFF;
IHDRChunk.Data[6] = (vidBuf.Height>>8)&0xFF; IHDRChunk->Data[6] = (vidBuf.Height>>8)&0xFF;
IHDRChunk.Data[7] = (vidBuf.Height)&0xFF; IHDRChunk->Data[7] = (vidBuf.Height)&0xFF;
//Bit depth //Bit depth
IHDRChunk.Data[8] = 8; //8bits per channel or 24bpp IHDRChunk->Data[8] = 8; //8bits per channel or 24bpp
//Colour type //Colour type
IHDRChunk.Data[9] = 2; //RGB triple IHDRChunk->Data[9] = 2; //RGB triple
//Everything else is default //Everything else is default
chunks.push_back(&IHDRChunk); chunks.push_back(IHDRChunk);
//Begin image data, format is 8bit RGB (24bit pixel) //Begin image data, format is 8bit RGB (24bit pixel)
int dataPos = 0; int dataPos = 0;
@ -356,17 +356,17 @@ std::vector<char> format::VideoBufferToPNG(const VideoBuffer & vidBuf)
if (result != Z_STREAM_END) exit(result); if (result != Z_STREAM_END) exit(result);
int compressedSize = compressedBufferSize-zipStream.avail_out; int compressedSize = compressedBufferSize-zipStream.avail_out;
PNGChunk IDATChunk = PNGChunk(compressedSize, "IDAT"); PNGChunk *IDATChunk = new PNGChunk(compressedSize, "IDAT");
std::copy(compressedData, compressedData+compressedSize, IDATChunk.Data); std::copy(compressedData, compressedData+compressedSize, IDATChunk->Data);
chunks.push_back(&IDATChunk); chunks.push_back(IDATChunk);
deflateEnd(&zipStream); deflateEnd(&zipStream);
delete[] compressedData; delete[] compressedData;
delete[] uncompressedData; delete[] uncompressedData;
PNGChunk IENDChunk = PNGChunk(0, "IEND"); PNGChunk *IENDChunk = new PNGChunk(0, "IEND");
chunks.push_back(&IENDChunk); chunks.push_back(IENDChunk);
//Write chunks to output buffer //Write chunks to output buffer
int finalDataSize = 8; int finalDataSize = 8;
@ -416,6 +416,8 @@ std::vector<char> format::VideoBufferToPNG(const VideoBuffer & vidBuf)
finalData[finalDataPos++] = (tempCRC>>16)&0xFF; finalData[finalDataPos++] = (tempCRC>>16)&0xFF;
finalData[finalDataPos++] = (tempCRC>>8)&0xFF; finalData[finalDataPos++] = (tempCRC>>8)&0xFF;
finalData[finalDataPos++] = (tempCRC)&0xFF; finalData[finalDataPos++] = (tempCRC)&0xFF;
delete cChunk;
} }
std::vector<char> outputData(finalData, finalData+finalDataPos); std::vector<char> outputData(finalData, finalData+finalDataPos);

View File

@ -7,7 +7,7 @@ class VideoBuffer;
namespace format namespace format
{ {
static char hex[] = "0123456789ABCDEF"; const static char hex[] = "0123456789ABCDEF";
template <typename T> std::string NumberToString(T number) template <typename T> std::string NumberToString(T number)
{ {

View File

@ -20,6 +20,7 @@
#include <mach-o/dyld.h> #include <mach-o/dyld.h>
#endif #endif
const static char hex[] = "0123456789ABCDEF";
std::string URLEscape(std::string source) std::string URLEscape(std::string source)
{ {
char * src = (char *)source.c_str(); char * src = (char *)source.c_str();
@ -161,14 +162,16 @@ void strlist_free(struct strlist **list)
} }
} }
void clean_text(char *text, int vwidth) void clean_text(char *text, unsigned int vwidth)
{ {
int i = 0; if (strlen(text)*10 > vwidth)
if(strlen(text)*10 > vwidth){ {
text[vwidth/10] = 0; text[vwidth/10] = 0;
} }
for(i = 0; i < strlen(text); i++){ for (unsigned i = 0; i < strlen(text); i++)
if(! (text[i]>=' ' && text[i]<127)){ {
if (! (text[i]>=' ' && text[i]<127))
{
text[i] = ' '; text[i] = ' ';
} }
} }
@ -626,7 +629,7 @@ void membwand(void * destv, void * srcv, size_t destsize, size_t srcsize)
int splitsign(const char* str, char * type) int splitsign(const char* str, char * type)
{ {
int match=0,r; int r;
if (str[0]=='{' && (str[1]=='c' || str[1]=='t' || str[1]=='b')) if (str[0]=='{' && (str[1]=='c' || str[1]=='t' || str[1]=='b'))
{ {
const char* p=str+2; const char* p=str+2;

View File

@ -22,8 +22,6 @@ __asm__ __volatile ("cpuid":\
"=a" (af), "=b" (bf), "=c" (cf), "=d" (df) : "a" (func)); "=a" (af), "=b" (bf), "=c" (cf), "=d" (df) : "a" (func));
#endif #endif
static char hex[] = "0123456789ABCDEF";
char *exe_name(void); char *exe_name(void);
//Linear interpolation //Linear interpolation

View File

@ -78,14 +78,25 @@ int main(int argc, char *argv[])
engine = &ui::Engine::Ref(); engine = &ui::Engine::Ref();
engine->Begin(WINDOWW, WINDOWH); engine->Begin(WINDOWW, WINDOWH);
GameSave * gameSave = new GameSave(inputFile); GameSave * gameSave = NULL;
try
{
gameSave = new GameSave(inputFile);
}
catch (ParseException e)
{
//Render the save again later or something? I don't know
if (e.what() == "Save from newer version")
throw e;
}
Simulation * sim = new Simulation(); Simulation * sim = new Simulation();
Renderer * ren = new Renderer(ui::Engine::Ref().g, sim); Renderer * ren = new Renderer(ui::Engine::Ref().g, sim);
if (gameSave)
{
sim->Load(gameSave); sim->Load(gameSave);
//Render save //Render save
ren->decorations_enable = true; ren->decorations_enable = true;
ren->blackDecorations = true; ren->blackDecorations = true;
@ -98,6 +109,13 @@ int main(int argc, char *argv[])
ren->render_fire(); ren->render_fire();
ren->clearScreen(1.0f); ren->clearScreen(1.0f);
} }
}
else
{
int w = Graphics::textwidth("Save file invalid")+16, x = (XRES-w)/2, y = (YRES-24)/2;
ren->drawrect(x, y, w, 24, 192, 192, 192, 255);
ren->drawtext(x+8, y+8, "Save file invalid", 192, 192, 240, 255);
}
ren->RenderBegin(); ren->RenderBegin();
ren->RenderEnd(); ren->RenderEnd();

View File

@ -295,7 +295,6 @@ void blit2(pixel * vid, int currentScale)
int SDLOpen() int SDLOpen()
{ {
SDL_Surface * surface;
#if defined(WIN) && defined(WINCONSOLE) #if defined(WIN) && defined(WINCONSOLE)
FILE * console = fopen("CON", "w" ); FILE * console = fopen("CON", "w" );
#endif #endif
@ -321,7 +320,7 @@ int SDLOpen()
SDL_SysWMinfo SysInfo; SDL_SysWMinfo SysInfo;
SDL_VERSION(&SysInfo.version); SDL_VERSION(&SysInfo.version);
if(SDL_GetWMInfo(&SysInfo) <= 0) { if(SDL_GetWMInfo(&SysInfo) <= 0) {
printf("%s : %d\n", SDL_GetError(), SysInfo.window); printf("%s : %p\n", SDL_GetError(), SysInfo.window);
exit(-1); exit(-1);
} }
HWND WindowHandle = SysInfo.window; HWND WindowHandle = SysInfo.window;
@ -333,8 +332,8 @@ int SDLOpen()
SendMessage(WindowHandle, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall); SendMessage(WindowHandle, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
SendMessage(WindowHandle, WM_SETICON, ICON_BIG, (LPARAM)hIconBig); SendMessage(WindowHandle, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
#elif defined(LIN) #elif defined(LIN)
SDL_Surface *icon = SDL_CreateRGBSurfaceFrom(app_icon, 16, 16, 32, 64, 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); SDL_Surface *icon = SDL_CreateRGBSurfaceFrom((void*)app_icon, 48, 48, 24, 144, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
SDL_WM_SetIcon(icon, NULL); SDL_WM_SetIcon(icon, (Uint8*)app_icon_bitmap);
#endif #endif
SDL_WM_SetCaption("The Powder Toy", "Powder Toy"); SDL_WM_SetCaption("The Powder Toy", "Powder Toy");
@ -574,12 +573,11 @@ void EventProcess(SDL_Event event)
void EngineProcess() void EngineProcess()
{ {
int frameStart = SDL_GetTicks(); double frameTimeAvg = 0.0f, correctedFrameTimeAvg = 0.0f;
float frameTime;
float frameTimeAvg = 0.0f, correctedFrameTimeAvg = 0.0f;
SDL_Event event; SDL_Event event;
while(engine->Running()) while(engine->Running())
{ {
int frameStart = SDL_GetTicks();
if(engine->Broken()) { engine->UnBreak(); break; } if(engine->Broken()) { engine->UnBreak(); break; }
event.type = 0; event.type = 0;
while (SDL_PollEvent(&event)) while (SDL_PollEvent(&event))
@ -595,7 +593,7 @@ void EngineProcess()
if(scale != engine->Scale || fullscreen != engine->Fullscreen) if(scale != engine->Scale || fullscreen != engine->Fullscreen)
{ {
sdl_scrn = SDLSetScreen(engine->Scale, engine->Fullscreen); sdl_scrn = SDLSetScreen(engine->Scale, engine->Fullscreen);
inputScale = 1.0f/float(scale); inputScale = 1.0f/(float)scale;
} }
#ifdef OGLI #ifdef OGLI
@ -607,23 +605,19 @@ void EngineProcess()
blit(engine->g->vid); blit(engine->g->vid);
#endif #endif
frameTime = SDL_GetTicks() - frameStart; int frameTime = SDL_GetTicks() - frameStart;
frameTimeAvg = (frameTimeAvg*(1.0f-0.2f)) + (0.2f*frameTime); frameTimeAvg = frameTimeAvg * 0.8 + frameTime * 0.2;
if(ui::Engine::Ref().FpsLimit > 2.0f) int fpsLimit = ui::Engine::Ref().FpsLimit;
if(fpsLimit > 2)
{ {
float targetFrameTime = 1000.0f/((float)ui::Engine::Ref().FpsLimit); double offset = 1000.0 / fpsLimit - frameTimeAvg;
if(targetFrameTime - frameTimeAvg > 0) if(offset > 0)
{ SDL_Delay(offset + 0.5);
SDL_Delay((targetFrameTime - frameTimeAvg) + 0.5f);
frameTime = SDL_GetTicks() - frameStart;//+= (int)(targetFrameTime - frameTimeAvg);
} }
} int correctedFrameTime = SDL_GetTicks() - frameStart;
correctedFrameTimeAvg = (correctedFrameTimeAvg*(1.0f-0.05f)) + (0.05f*frameTime); correctedFrameTimeAvg = correctedFrameTimeAvg * 0.95 + correctedFrameTime * 0.05;
fps = 1000.0f/correctedFrameTimeAvg; engine->SetFps(1000.0 / correctedFrameTimeAvg);
engine->SetFps(fps); if(frameStart - lastTick > 1000)
frameStart = SDL_GetTicks();
if(frameStart-lastTick>250)
{ {
//Run client tick every second //Run client tick every second
lastTick = frameStart; lastTick = frameStart;
@ -839,7 +833,12 @@ int main(int argc, char * argv[])
if(tempScale != 1 && tempScale != 2) if(tempScale != 1 && tempScale != 2)
tempScale = 1; tempScale = 1;
int sdlStatus = SDLOpen(); SDLOpen();
if (Client::Ref().IsFirstRun() && desktopWidth > WINDOWW*2 && desktopHeight > WINDOWH*2)
{
tempScale = 2;
Client::Ref().SetPref("Scale", 2);
}
#ifdef WIN #ifdef WIN
LoadWindowPosition(tempScale); LoadWindowPosition(tempScale);
#endif #endif
@ -949,8 +948,8 @@ int main(int argc, char * argv[])
{ {
std::string saveIdPart = ""; std::string saveIdPart = "";
int saveId; int saveId;
int hashPos = ptsaveArg.find('#'); size_t hashPos = ptsaveArg.find('#');
if(hashPos != std::string::npos) if (hashPos != std::string::npos)
{ {
saveIdPart = ptsaveArg.substr(7, hashPos-7); saveIdPart = ptsaveArg.substr(7, hashPos-7);
} }
@ -958,7 +957,7 @@ int main(int argc, char * argv[])
{ {
saveIdPart = ptsaveArg.substr(7); saveIdPart = ptsaveArg.substr(7);
} }
if(saveIdPart.length()) if (saveIdPart.length())
{ {
#ifdef DEBUG #ifdef DEBUG
std::cout << "Got Ptsave: id: " << saveIdPart << std::endl; std::cout << "Got Ptsave: id: " << saveIdPart << std::endl;
@ -968,10 +967,10 @@ int main(int argc, char * argv[])
throw std::runtime_error("Invalid Save ID"); throw std::runtime_error("Invalid Save ID");
SaveInfo * newSave = Client::Ref().GetSave(saveId, 0); SaveInfo * newSave = Client::Ref().GetSave(saveId, 0);
if (!newSave)
throw std::runtime_error("Could not load save");
GameSave * newGameSave = new GameSave(Client::Ref().GetSaveData(saveId, 0)); GameSave * newGameSave = new GameSave(Client::Ref().GetSaveData(saveId, 0));
newSave->SetGameSave(newGameSave); newSave->SetGameSave(newGameSave);
if(!newSave)
throw std::runtime_error("Could not load save");
gameController->LoadSave(newSave); gameController->LoadSave(newSave);
delete newSave; delete newSave;
@ -988,11 +987,15 @@ int main(int argc, char * argv[])
} }
} }
//initial mouse coords
int sdl_x, sdl_y;
SDL_GetMouseState(&sdl_x, &sdl_y);
engine->onMouseMove(sdl_x*inputScale, sdl_y*inputScale);
EngineProcess(); EngineProcess();
#ifdef WIN #ifdef WIN
SaveWindowPosition(); SaveWindowPosition();
#endif #endif
#if !defined(DEBUG) && !defined(_DEBUG) #if !defined(DEBUG) && !defined(_DEBUG)
} }

View File

@ -395,6 +395,7 @@ void writeUserPreferences(const char * prefData)
[prefDataNSString release]; [prefDataNSString release];
} }
//doesn't work on OS X 10.5 or below
char * readClipboard() char * readClipboard()
{ {
NSPasteboard *clipboard = [NSPasteboard generalPasteboard]; NSPasteboard *clipboard = [NSPasteboard generalPasteboard];
@ -416,6 +417,7 @@ char * readClipboard()
return clipboardDataCopy; return clipboardDataCopy;
} }
//doesn't work on OS X 10.5 or below
void writeClipboard(const char * clipboardData) void writeClipboard(const char * clipboardData)
{ {
NSPasteboard *clipboard = [NSPasteboard generalPasteboard]; NSPasteboard *clipboard = [NSPasteboard generalPasteboard];

View File

@ -66,7 +66,7 @@
return name; return name;
}*/ }*/
int update_start(char *data, int len) int update_start(char *data, unsigned int len)
{ {
char *self=exe_name(), *temp; char *self=exe_name(), *temp;
#ifdef WIN #ifdef WIN

View File

@ -2,7 +2,7 @@
#define UPDATE_H_ #define UPDATE_H_
//char *exe_name(void); //char *exe_name(void);
int update_start(char *data, int len); int update_start(char *data, unsigned int len);
int update_finish(void); int update_finish(void);
void update_cleanup(void); void update_cleanup(void);

View File

@ -67,10 +67,10 @@ void writeUserPreferences(const char * prefData);
Client::Client(): Client::Client():
authUser(0, ""), messageOfTheDay(""),
updateAvailable(false),
versionCheckRequest(NULL), versionCheckRequest(NULL),
messageOfTheDay("") updateAvailable(false),
authUser(0, "")
{ {
int i = 0; int i = 0;
for(i = 0; i < THUMB_CACHE_SIZE; i++) for(i = 0; i < THUMB_CACHE_SIZE; i++)
@ -126,7 +126,10 @@ Client::Client():
#ifndef MACOSX #ifndef MACOSX
configFile.close(); configFile.close();
#endif #endif
firstRun = false;
} }
else
firstRun = true;
} }
void Client::Initialise(std::string proxyString) void Client::Initialise(std::string proxyString)
@ -173,6 +176,11 @@ void Client::Initialise(std::string proxyString)
} }
} }
bool Client::IsFirstRun()
{
return firstRun;
}
bool Client::DoInstallation() bool Client::DoInstallation()
{ {
#if defined(WIN) #if defined(WIN)
@ -344,7 +352,18 @@ bool Client::DoInstallation()
#elif defined(LIN) #elif defined(LIN)
#include "icondoc.h" #include "icondoc.h"
char *currentfilename = exe_name(); std::string filename = exe_name(), pathname = filename.substr(0, filename.rfind('/'));
for (size_t i = 0; i < filename.size(); i++)
{
if (filename[i] == '\'')
{
filename.insert(i, "'\\'");
i += 3;
}
}
filename.insert(filename.size(), "'");
filename.insert(0, "'");
FILE *f; FILE *f;
const char *mimedata = const char *mimedata =
"<?xml version=\"1.0\"?>\n" "<?xml version=\"1.0\"?>\n"
@ -367,16 +386,14 @@ bool Client::DoInstallation()
"Name=Powder Toy\n" "Name=Powder Toy\n"
"Comment=Physics sandbox game\n" "Comment=Physics sandbox game\n"
"MimeType=x-scheme-handler/ptsave;\n" "MimeType=x-scheme-handler/ptsave;\n"
"NoDisplay=true\n"; "NoDisplay=true\n"
char *protocolfiledata = (char *)malloc(strlen(protocolfiledata_tmp)+strlen(currentfilename)+100); "Categories=Game\n";
strcpy(protocolfiledata, protocolfiledata_tmp); std::stringstream protocolfiledata;
strappend(protocolfiledata, "Exec="); protocolfiledata << protocolfiledata_tmp << "Exec=" << filename <<" ptsave %u\nPath=" << pathname << "\n";
strappend(protocolfiledata, currentfilename);
strappend(protocolfiledata, " ptsave %u\n");
f = fopen("powdertoy-tpt-ptsave.desktop", "wb"); f = fopen("powdertoy-tpt-ptsave.desktop", "wb");
if (!f) if (!f)
return 0; return 0;
fwrite(protocolfiledata, 1, strlen(protocolfiledata), f); fwrite(protocolfiledata.str().c_str(), 1, strlen(protocolfiledata.str().c_str()), f);
fclose(f); fclose(f);
system("xdg-desktop-menu install powdertoy-tpt-ptsave.desktop"); system("xdg-desktop-menu install powdertoy-tpt-ptsave.desktop");
@ -386,16 +403,14 @@ bool Client::DoInstallation()
"Name=Powder Toy\n" "Name=Powder Toy\n"
"Comment=Physics sandbox game\n" "Comment=Physics sandbox game\n"
"MimeType=application/vnd.powdertoy.save;\n" "MimeType=application/vnd.powdertoy.save;\n"
"NoDisplay=true\n"; "NoDisplay=true\n"
char *desktopfiledata = (char *)malloc(strlen(desktopfiledata_tmp)+strlen(currentfilename)+100); "Categories=Game\n";
strcpy(desktopfiledata, desktopfiledata_tmp); std::stringstream desktopfiledata;
strappend(desktopfiledata, "Exec="); desktopfiledata << desktopfiledata_tmp << "Exec=" << filename <<" open %f\nPath=" << pathname << "\n";
strappend(desktopfiledata, currentfilename);
strappend(desktopfiledata, " open %f\n");
f = fopen("powdertoy-tpt.desktop", "wb"); f = fopen("powdertoy-tpt.desktop", "wb");
if (!f) if (!f)
return 0; return 0;
fwrite(desktopfiledata, 1, strlen(desktopfiledata), f); fwrite(desktopfiledata.str().c_str(), 1, strlen(desktopfiledata.str().c_str()), f);
fclose(f); fclose(f);
system("xdg-mime install powdertoy-save.xml"); system("xdg-mime install powdertoy-save.xml");
system("xdg-desktop-menu install powdertoy-tpt.desktop"); system("xdg-desktop-menu install powdertoy-tpt.desktop");
@ -482,7 +497,7 @@ std::vector<std::string> Client::DirectorySearch(std::string directory, std::str
#endif #endif
return std::vector<std::string>(); return std::vector<std::string>();
} }
while(directoryEntry = readdir(directoryHandle)) while ((directoryEntry = readdir(directoryHandle)))
{ {
std::string currentFileName = std::string(directoryEntry->d_name); std::string currentFileName = std::string(directoryEntry->d_name);
if(currentFileName.length()>4) if(currentFileName.length()>4)
@ -498,7 +513,7 @@ std::vector<std::string> Client::DirectorySearch(std::string directory, std::str
bool extensionMatch = !extensions.size(); bool extensionMatch = !extensions.size();
for(std::vector<std::string>::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter) for(std::vector<std::string>::iterator extIter = extensions.begin(), extEnd = extensions.end(); extIter != extEnd; ++extIter)
{ {
int filenameLength = filename.length()-(*extIter).length(); size_t filenameLength = filename.length()-(*extIter).length();
if(filename.find(*extIter, filenameLength) == filenameLength) if(filename.find(*extIter, filenameLength) == filenameLength)
{ {
extensionMatch = true; extensionMatch = true;
@ -687,7 +702,7 @@ void Client::Tick()
//Notifications from server //Notifications from server
json::Array notificationsArray = objDocument["Notifications"]; json::Array notificationsArray = objDocument["Notifications"];
for(int j = 0; j < notificationsArray.Size(); j++) for(size_t j = 0; j < notificationsArray.Size(); j++)
{ {
json::String notificationLink = notificationsArray[j]["Link"]; json::String notificationLink = notificationsArray[j]["Link"];
json::String notificationText = notificationsArray[j]["Text"]; json::String notificationText = notificationsArray[j]["Text"];
@ -705,31 +720,25 @@ void Client::Tick()
#ifndef IGNORE_UPDATES #ifndef IGNORE_UPDATES
//Check for updates //Check for updates
json::Object versions = objDocument["Updates"]; json::Object versions = objDocument["Updates"];
#if not defined(BETA) && not defined(SNAPSHOT)
json::Object stableVersion = versions["Stable"]; json::Object stableVersion = versions["Stable"];
json::Object betaVersion = versions["Beta"];
json::Object snapshotVersion = versions["Snapshot"];
json::Number stableMajor = stableVersion["Major"]; json::Number stableMajor = stableVersion["Major"];
json::Number stableMinor = stableVersion["Minor"]; json::Number stableMinor = stableVersion["Minor"];
json::Number stableBuild = stableVersion["Build"]; json::Number stableBuild = stableVersion["Build"];
json::String stableFile = stableVersion["File"]; json::String stableFile = stableVersion["File"];
json::Number betaMajor = betaVersion["Major"];
json::Number betaMinor = betaVersion["Minor"];
json::Number betaBuild = betaVersion["Build"];
json::String betaFile = betaVersion["File"];
json::Number snapshotSnapshot = snapshotVersion["Snapshot"];
json::String snapshotFile = snapshotVersion["File"];
if(stableMajor.Value()>SAVE_VERSION || (stableMinor.Value()>MINOR_VERSION && stableMajor.Value()==SAVE_VERSION) || stableBuild.Value()>BUILD_NUM) if(stableMajor.Value()>SAVE_VERSION || (stableMinor.Value()>MINOR_VERSION && stableMajor.Value()==SAVE_VERSION) || stableBuild.Value()>BUILD_NUM)
{ {
updateAvailable = true; updateAvailable = true;
updateInfo = UpdateInfo(stableMajor.Value(), stableMinor.Value(), stableBuild.Value(), stableFile.Value(), UpdateInfo::Stable); updateInfo = UpdateInfo(stableMajor.Value(), stableMinor.Value(), stableBuild.Value(), stableFile.Value(), UpdateInfo::Stable);
} }
#endif
#ifdef BETA #ifdef BETA
json::Object betaVersion = versions["Beta"];
json::Number betaMajor = betaVersion["Major"];
json::Number betaMinor = betaVersion["Minor"];
json::Number betaBuild = betaVersion["Build"];
json::String betaFile = betaVersion["File"];
if(betaMajor.Value()>SAVE_VERSION || (betaMinor.Value()>MINOR_VERSION && betaMajor.Value()==SAVE_VERSION) || betaBuild.Value()>BUILD_NUM) if(betaMajor.Value()>SAVE_VERSION || (betaMinor.Value()>MINOR_VERSION && betaMajor.Value()==SAVE_VERSION) || betaBuild.Value()>BUILD_NUM)
{ {
updateAvailable = true; updateAvailable = true;
@ -738,6 +747,9 @@ void Client::Tick()
#endif #endif
#ifdef SNAPSHOT #ifdef SNAPSHOT
json::Object snapshotVersion = versions["Snapshot"];
json::Number snapshotSnapshot = snapshotVersion["Snapshot"];
json::String snapshotFile = snapshotVersion["File"];
if(snapshotSnapshot.Value() > SNAPSHOT_ID) if(snapshotSnapshot.Value() > SNAPSHOT_ID)
{ {
updateAvailable = true; updateAvailable = true;
@ -887,7 +899,7 @@ User Client::GetAuthUser()
RequestStatus Client::UploadSave(SaveInfo & save) RequestStatus Client::UploadSave(SaveInfo & save)
{ {
lastError = ""; lastError = "";
int gameDataLength; unsigned int gameDataLength;
char * gameData = NULL; char * gameData = NULL;
int dataStatus; int dataStatus;
char * data; char * data;
@ -922,7 +934,7 @@ RequestStatus Client::UploadSave(SaveInfo & save)
const char *const postNames[] = { "Name", "Description", "Data:save.bin", "Publish", NULL }; const char *const postNames[] = { "Name", "Description", "Data:save.bin", "Publish", NULL };
const char *const postDatas[] = { saveName, saveDescription, gameData, (char *)(save.GetPublished()?"Public":"Private") }; const char *const postDatas[] = { saveName, saveDescription, gameData, (char *)(save.GetPublished()?"Public":"Private") };
int postLengths[] = { save.GetName().length(), save.GetDescription().length(), gameDataLength, save.GetPublished()?6:7 }; size_t postLengths[] = { save.GetName().length(), save.GetDescription().length(), gameDataLength, (size_t)(save.GetPublished()?6:7) };
//std::cout << postNames[0] << " " << postDatas[0] << " " << postLengths[0] << std::endl; //std::cout << postNames[0] << " " << postDatas[0] << " " << postLengths[0] << std::endl;
data = http_multipart_post("http://" SERVER "/Save.api", postNames, postDatas, postLengths, userid, NULL, session, &dataStatus, &dataLength); data = http_multipart_post("http://" SERVER "/Save.api", postNames, postDatas, postLengths, userid, NULL, session, &dataStatus, &dataLength);
@ -989,11 +1001,11 @@ void Client::MoveStampToFront(std::string stampID)
SaveFile * Client::GetStamp(std::string stampID) SaveFile * Client::GetStamp(std::string stampID)
{ {
std::string stampFile = std::string(STAMPS_DIR PATH_SEP + stampID + ".stm"); std::string stampFile = std::string(STAMPS_DIR PATH_SEP + stampID + ".stm");
SaveFile * file = new SaveFile(stampID);
if (!FileExists(stampFile)) if (!FileExists(stampFile))
stampFile = stampID; stampFile = stampID;
if(FileExists(stampFile)) if (FileExists(stampFile))
{ {
SaveFile * file = new SaveFile(stampID);
try try
{ {
GameSave * tempSave = new GameSave(ReadFile(stampFile)); GameSave * tempSave = new GameSave(ReadFile(stampFile));
@ -1003,12 +1015,8 @@ SaveFile * Client::GetStamp(std::string stampID)
{ {
std::cerr << "Client: Invalid stamp file, " << stampID << " " << std::string(e.what()) << std::endl; std::cerr << "Client: Invalid stamp file, " << stampID << " " << std::string(e.what()) << std::endl;
} }
}
return file; return file;
}
else
{
return NULL;
}
} }
void Client::DeleteStamp(std::string stampID) void Client::DeleteStamp(std::string stampID)
@ -1049,7 +1057,7 @@ std::string Client::AddStamp(GameSave * saveData)
MakeDirectory(STAMPS_DIR); MakeDirectory(STAMPS_DIR);
int gameDataLength; unsigned int gameDataLength;
char * gameData = saveData->Serialise(gameDataLength); char * gameData = saveData->Serialise(gameDataLength);
std::ofstream stampStream; std::ofstream stampStream;
@ -1089,7 +1097,7 @@ void Client::RescanStamps()
if (directory != NULL) if (directory != NULL)
{ {
stampIDs.clear(); stampIDs.clear();
while (entry = readdir(directory)) while ((entry = readdir(directory)))
{ {
if(strncmp(entry->d_name, "..", 3) && strncmp(entry->d_name, ".", 2) && strstr(entry->d_name, ".stm") && strlen(entry->d_name) == 14) if(strncmp(entry->d_name, "..", 3) && strncmp(entry->d_name, ".", 2) && strstr(entry->d_name, ".stm") && strlen(entry->d_name) == 14)
{ {
@ -1110,15 +1118,18 @@ int Client::GetStampsCount()
std::vector<std::string> Client::GetStamps(int start, int count) std::vector<std::string> Client::GetStamps(int start, int count)
{ {
if(start+count > stampIDs.size()) { int size = (int)stampIDs.size();
if(start > stampIDs.size()) if (start+count > size)
{
if(start > size)
return std::vector<std::string>(); return std::vector<std::string>();
count = stampIDs.size()-start; count = size-start;
} }
std::vector<std::string> stampRange; std::vector<std::string> stampRange;
int index = 0; int index = 0;
for (std::list<std::string>::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator, ++index) { for (std::list<std::string>::const_iterator iterator = stampIDs.begin(), end = stampIDs.end(); iterator != end; ++iterator, ++index)
{
if(index>=start && index < start+count) if(index>=start && index < start+count)
stampRange.push_back(*iterator); stampRange.push_back(*iterator);
} }
@ -1149,7 +1160,7 @@ RequestStatus Client::ExecVote(int saveID, int direction)
const char *const postNames[] = { "ID", "Action", NULL }; const char *const postNames[] = { "ID", "Action", NULL };
const char *const postDatas[] = { id, directionText }; const char *const postDatas[] = { id, directionText };
int postLengths[] = { saveIDText.length(), strlen(directionText) }; size_t postLengths[] = { saveIDText.length(), strlen(directionText) };
//std::cout << postNames[0] << " " << postDatas[0] << " " << postLengths[0] << std::endl; //std::cout << postNames[0] << " " << postDatas[0] << " " << postLengths[0] << std::endl;
data = http_multipart_post("http://" SERVER "/Vote.api", postNames, postDatas, postLengths, userid, NULL, session, &dataStatus, &dataLength); data = http_multipart_post("http://" SERVER "/Vote.api", postNames, postDatas, postLengths, userid, NULL, session, &dataStatus, &dataLength);
@ -1330,7 +1341,7 @@ LoginStatus Client::Login(std::string username, std::string password, User & use
int dataStatus, dataLength; int dataStatus, dataLength;
const char *const postNames[] = { "Username", "Hash", NULL }; const char *const postNames[] = { "Username", "Hash", NULL };
const char *const postDatas[] = { (char*)username.c_str(), totalHash }; const char *const postDatas[] = { (char*)username.c_str(), totalHash };
int postLengths[] = { username.length(), 32 }; size_t postLengths[] = { username.length(), 32 };
data = http_multipart_post("http://" SERVER "/Login.json", postNames, postDatas, postLengths, NULL, NULL, NULL, &dataStatus, &dataLength); data = http_multipart_post("http://" SERVER "/Login.json", postNames, postDatas, postLengths, NULL, NULL, NULL, &dataStatus, &dataLength);
if(dataStatus == 200 && data) if(dataStatus == 200 && data)
{ {
@ -1350,7 +1361,7 @@ LoginStatus Client::Login(std::string username, std::string password, User & use
json::String userElevationTemp = objDocument["Elevation"]; json::String userElevationTemp = objDocument["Elevation"];
json::Array notificationsArray = objDocument["Notifications"]; json::Array notificationsArray = objDocument["Notifications"];
for(int j = 0; j < notificationsArray.Size(); j++) for (size_t j = 0; j < notificationsArray.Size(); j++)
{ {
json::String notificationLink = notificationsArray[j]["Link"]; json::String notificationLink = notificationsArray[j]["Link"];
json::String notificationText = notificationsArray[j]["Text"]; json::String notificationText = notificationsArray[j]["Text"];
@ -1459,7 +1470,7 @@ RequestStatus Client::AddComment(int saveID, std::string comment)
const char *const postNames[] = { "Comment", NULL }; const char *const postNames[] = { "Comment", NULL };
const char *const postDatas[] = { (char*)(comment.c_str()) }; const char *const postDatas[] = { (char*)(comment.c_str()) };
int postLengths[] = { comment.length() }; size_t postLengths[] = { comment.length() };
data = http_multipart_post((char *)urlStream.str().c_str(), postNames, postDatas, postLengths, (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); data = http_multipart_post((char *)urlStream.str().c_str(), postNames, postDatas, postLengths, (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength);
} }
else else
@ -1575,7 +1586,7 @@ RequestStatus Client::ReportSave(int saveID, std::string message)
const char *const postNames[] = { "Reason", NULL }; const char *const postNames[] = { "Reason", NULL };
const char *const postDatas[] = { (char*)(message.c_str()) }; const char *const postDatas[] = { (char*)(message.c_str()) };
int postLengths[] = { message.length() }; size_t postLengths[] = { message.length() };
data = http_multipart_post((char *)urlStream.str().c_str(), postNames, postDatas, postLengths, (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength); data = http_multipart_post((char *)urlStream.str().c_str(), postNames, postDatas, postLengths, (char *)(userIDStream.str().c_str()), NULL, (char *)(authUser.SessionID.c_str()), &dataStatus, &dataLength);
} }
else else
@ -1673,6 +1684,36 @@ failure:
return RequestFailure; return RequestFailure;
} }
RequestStatus Client::PublishSave(int saveID)
{
lastError = "";
std::stringstream urlStream;
int dataStatus;
urlStream << "http://" << SERVER << "/Browse/View.html?ID=" << saveID << "&Key=" << authUser.SessionKey;
if (authUser.ID)
{
std::stringstream userIDStream;
userIDStream << authUser.ID;
const char *const postNames[] = { "ActionPublish", NULL };
const char *const postDatas[] = { "" };
size_t postLengths[] = { 1 };
char *data = http_multipart_post(urlStream.str().c_str(), postNames, postDatas, postLengths, userIDStream.str().c_str(), NULL, authUser.SessionID.c_str(), &dataStatus, NULL);
if (data)
free(data);
}
else
{
lastError = "Not authenticated";
return RequestFailure;
}
if (dataStatus != 302)
{
lastError = http_ret_text(dataStatus);
return RequestFailure;
}
return RequestOkay;
}
SaveInfo * Client::GetSave(int saveID, int saveDate) SaveInfo * Client::GetSave(int saveID, int saveDate)
{ {
lastError = ""; lastError = "";
@ -1720,7 +1761,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate)
json::Array tagsArray = objDocument["Tags"]; json::Array tagsArray = objDocument["Tags"];
std::list<std::string> tempTags; std::list<std::string> tempTags;
for(int j = 0; j < tagsArray.Size(); j++) for (size_t j = 0; j < tagsArray.Size(); j++)
{ {
json::String tempTag = tagsArray[j]; json::String tempTag = tagsArray[j];
tempTags.push_back(tempTag.Value()); tempTags.push_back(tempTag.Value());
@ -1796,7 +1837,7 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate)
json::Array tagsArray = objDocument["Tags"]; json::Array tagsArray = objDocument["Tags"];
std::list<std::string> tempTags; std::list<std::string> tempTags;
for(int j = 0; j < tagsArray.Size(); j++) for (size_t j = 0; j < tagsArray.Size(); j++)
{ {
json::String tempTag = tagsArray[j]; json::String tempTag = tagsArray[j];
tempTags.push_back(tempTag.Value()); tempTags.push_back(tempTag.Value());
@ -1889,7 +1930,7 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou
json::Array commentsArray; json::Array commentsArray;
json::Reader::Read(commentsArray, dataStream); json::Reader::Read(commentsArray, dataStream);
for(int j = 0; j < commentsArray.Size(); j++) for (size_t j = 0; j < commentsArray.Size(); j++)
{ {
json::Number tempUserID = commentsArray[j]["UserID"]; json::Number tempUserID = commentsArray[j]["UserID"];
json::String tempUsername = commentsArray[j]["Username"]; json::String tempUsername = commentsArray[j]["Username"];
@ -1942,7 +1983,7 @@ std::vector<SaveComment*> * Client::GetComments(int saveID, int start, int count
json::Array commentsArray; json::Array commentsArray;
json::Reader::Read(commentsArray, dataStream); json::Reader::Read(commentsArray, dataStream);
for(int j = 0; j < commentsArray.Size(); j++) for (size_t j = 0; j < commentsArray.Size(); j++)
{ {
json::Number tempUserID = commentsArray[j]["UserID"]; json::Number tempUserID = commentsArray[j]["UserID"];
json::String tempUsername = commentsArray[j]["Username"]; json::String tempUsername = commentsArray[j]["Username"];
@ -2000,7 +2041,7 @@ std::vector<std::pair<std::string, int> > * Client::GetTags(int start, int count
json::Number tempCount = objDocument["TagTotal"]; json::Number tempCount = objDocument["TagTotal"];
resultCount = tempCount.Value(); resultCount = tempCount.Value();
json::Array tagsArray = objDocument["Tags"]; json::Array tagsArray = objDocument["Tags"];
for(int j = 0; j < tagsArray.Size(); j++) for (size_t j = 0; j < tagsArray.Size(); j++)
{ {
json::Number tagCount = tagsArray[j]["Count"]; json::Number tagCount = tagsArray[j]["Count"];
json::String tag = tagsArray[j]["Tag"]; json::String tag = tagsArray[j]["Tag"];
@ -2067,7 +2108,7 @@ std::vector<SaveInfo*> * Client::SearchSaves(int start, int count, std::string q
json::Number tempCount = objDocument["Count"]; json::Number tempCount = objDocument["Count"];
resultCount = tempCount.Value(); resultCount = tempCount.Value();
json::Array savesArray = objDocument["Saves"]; json::Array savesArray = objDocument["Saves"];
for(int j = 0; j < savesArray.Size(); j++) for (size_t j = 0; j < savesArray.Size(); j++)
{ {
json::Number tempID = savesArray[j]["ID"]; json::Number tempID = savesArray[j]["ID"];
json::Number tempDate = savesArray[j]["Date"]; json::Number tempDate = savesArray[j]["Date"];
@ -2272,7 +2313,7 @@ std::list<std::string> * Client::RemoveTag(int saveID, std::string tag)
tags = new std::list<std::string>(); tags = new std::list<std::string>();
for(int j = 0; j < tagsArray.Size(); j++) for (size_t j = 0; j < tagsArray.Size(); j++)
{ {
json::String tempTag = tagsArray[j]; json::String tempTag = tagsArray[j];
tags->push_back(tempTag.Value()); tags->push_back(tempTag.Value());
@ -2333,7 +2374,7 @@ std::list<std::string> * Client::AddTag(int saveID, std::string tag)
tags = new std::list<std::string>(); tags = new std::list<std::string>();
for(int j = 0; j < tagsArray.Size(); j++) for (size_t j = 0; j < tagsArray.Size(); j++)
{ {
json::String tempTag = tagsArray[j]; json::String tempTag = tagsArray[j];
tags->push_back(tempTag.Value()); tags->push_back(tempTag.Value());

View File

@ -40,9 +40,9 @@ public:
int Build; int Build;
int Time; int Time;
BuildType Type; BuildType Type;
UpdateInfo() : Major(0), Minor(0), Build(0), Time(0), File(""), Type(Stable) {} UpdateInfo() : File(""), Major(0), Minor(0), Build(0), Time(0), Type(Stable) {}
UpdateInfo(int major, int minor, int build, std::string file, BuildType type) : Major(major), Minor(minor), Build(build), Time(0), File(file), Type(type) {} UpdateInfo(int major, int minor, int build, std::string file, BuildType type) : File(file), Major(major), Minor(minor), Build(build), Time(0), Type(type) {}
UpdateInfo(int time, std::string file, BuildType type) : Major(0), Minor(0), Build(0), Time(time), File(file), Type(type) {} UpdateInfo(int time, std::string file, BuildType type) : File(file), Major(0), Minor(0), Build(0), Time(time), Type(type) {}
}; };
class RequestListener; class RequestListener;
@ -56,11 +56,11 @@ private:
bool updateAvailable; bool updateAvailable;
UpdateInfo updateInfo; UpdateInfo updateInfo;
std::string lastError; std::string lastError;
bool firstRun;
std::list<std::string> stampIDs; std::list<std::string> stampIDs;
int lastStampTime; unsigned lastStampTime;
int lastStampName; int lastStampName;
//Auth session //Auth session
@ -73,7 +73,6 @@ private:
int activeThumbRequestTimes[IMGCONNS]; int activeThumbRequestTimes[IMGCONNS];
int activeThumbRequestCompleteTimes[IMGCONNS]; int activeThumbRequestCompleteTimes[IMGCONNS];
std::string activeThumbRequestIDs[IMGCONNS]; std::string activeThumbRequestIDs[IMGCONNS];
void updateStamps();
static std::vector<std::string> explodePropertyString(std::string property); static std::vector<std::string> explodePropertyString(std::string property);
void notifyUpdateAvailable(); void notifyUpdateAvailable();
void notifyAuthUserChanged(); void notifyAuthUserChanged();
@ -109,6 +108,7 @@ public:
void Initialise(std::string proxyString); void Initialise(std::string proxyString);
void SetProxy(std::string proxy); void SetProxy(std::string proxy);
bool IsFirstRun();
int MakeDirectory(const char * dirname); int MakeDirectory(const char * dirname);
bool WriteFile(std::vector<unsigned char> fileData, std::string filename); bool WriteFile(std::vector<unsigned char> fileData, std::string filename);
@ -129,6 +129,7 @@ public:
int GetStampsCount(); int GetStampsCount();
SaveFile * GetFirstStamp(); SaveFile * GetFirstStamp();
void MoveStampToFront(std::string stampID); void MoveStampToFront(std::string stampID);
void updateStamps();
RequestStatus AddComment(int saveID, std::string comment); RequestStatus AddComment(int saveID, std::string comment);
@ -157,6 +158,7 @@ public:
RequestStatus DeleteSave(int saveID); RequestStatus DeleteSave(int saveID);
RequestStatus ReportSave(int saveID, std::string message); RequestStatus ReportSave(int saveID, std::string message);
RequestStatus UnpublishSave(int saveID); RequestStatus UnpublishSave(int saveID);
RequestStatus PublishSave(int saveID);
RequestStatus FavouriteSave(int saveID, bool favourite); RequestStatus FavouriteSave(int saveID, bool favourite);
void SetAuthUser(User user); void SetAuthUser(User user);
User GetAuthUser(); User GetAuthUser();

View File

@ -18,15 +18,16 @@ GameSave::GameSave(GameSave & save) :
waterEEnabled(save.waterEEnabled), waterEEnabled(save.waterEEnabled),
legacyEnable(save.legacyEnable), legacyEnable(save.legacyEnable),
gravityEnable(save.gravityEnable), gravityEnable(save.gravityEnable),
aheatEnable(save.aheatEnable),
paused(save.paused), paused(save.paused),
gravityMode(save.gravityMode), gravityMode(save.gravityMode),
aheatEnable(save.aheatEnable),
airMode(save.airMode), airMode(save.airMode),
edgeMode(save.edgeMode),
signs(save.signs), signs(save.signs),
palette(save.palette),
expanded(save.expanded), expanded(save.expanded),
hasOriginalData(save.hasOriginalData), hasOriginalData(save.hasOriginalData),
originalData(save.originalData), originalData(save.originalData)
palette(save.palette)
{ {
blockMap = NULL; blockMap = NULL;
blockMapPtr = NULL; blockMapPtr = NULL;
@ -179,6 +180,7 @@ void GameSave::Expand()
paused = false; paused = false;
gravityMode = 0; gravityMode = 0;
airMode = 0; airMode = 0;
edgeMode = 0;
expanded = true; expanded = true;
read(&originalData[0], originalData.size()); read(&originalData[0], originalData.size());
} }
@ -286,14 +288,14 @@ void GameSave::setSize(int newWidth, int newHeight)
std::vector<char> GameSave::Serialise() std::vector<char> GameSave::Serialise()
{ {
int dataSize; unsigned int dataSize;
char * data = Serialise(dataSize); char * data = Serialise(dataSize);
std::vector<char> dataVect(data, data+dataSize); std::vector<char> dataVect(data, data+dataSize);
delete[] data; delete[] data;
return dataVect; return dataVect;
} }
char * GameSave::Serialise(int & dataSize) char * GameSave::Serialise(unsigned int & dataSize)
{ {
return serialiseOPS(dataSize); return serialiseOPS(dataSize);
} }
@ -302,7 +304,7 @@ void GameSave::Transform(matrix2d transform, vector2d translate)
{ {
if(Collapsed()) if(Collapsed())
Expand(); Expand();
int i, x, y, nx, ny, width = blockWidth*CELL, height = blockHeight*CELL, newWidth, newHeight, newBlockWidth, newBlockHeight; int x, y, nx, ny, width = blockWidth*CELL, height = blockHeight*CELL, newWidth, newHeight, newBlockWidth, newBlockHeight;
vector2d pos, tmp, ctl, cbr, vel; vector2d pos, tmp, ctl, cbr, vel;
vector2d cornerso[4]; vector2d cornerso[4];
// undo any translation caused by rotation // undo any translation caused by rotation
@ -310,7 +312,7 @@ void GameSave::Transform(matrix2d transform, vector2d translate)
cornerso[1] = v2d_new(width-1,0); cornerso[1] = v2d_new(width-1,0);
cornerso[2] = v2d_new(0,height-1); cornerso[2] = v2d_new(0,height-1);
cornerso[3] = v2d_new(width-1,height-1); cornerso[3] = v2d_new(width-1,height-1);
for (i=0; i<4; i++) for (int i = 0; i < 4; i++)
{ {
tmp = m2d_multiply_v2d(transform,cornerso[i]); tmp = m2d_multiply_v2d(transform,cornerso[i]);
if (i==0) ctl = cbr = tmp; // top left, bottom right corner if (i==0) ctl = cbr = tmp; // top left, bottom right corner
@ -355,7 +357,7 @@ void GameSave::Transform(matrix2d transform, vector2d translate)
fanVelYNew[y] = &fanVelYPtrNew[y*newBlockWidth]; fanVelYNew[y] = &fanVelYPtrNew[y*newBlockWidth];
// rotate and translate signs, parts, walls // rotate and translate signs, parts, walls
for (i=0; i < signs.size(); i++) for (size_t i = 0; i < signs.size(); i++)
{ {
pos = v2d_new(signs[i].x, signs[i].y); pos = v2d_new(signs[i].x, signs[i].y);
pos = v2d_add(m2d_multiply_v2d(transform,pos),translate); pos = v2d_add(m2d_multiply_v2d(transform,pos),translate);
@ -369,7 +371,7 @@ void GameSave::Transform(matrix2d transform, vector2d translate)
signs[i].x = nx; signs[i].x = nx;
signs[i].y = ny; signs[i].y = ny;
} }
for (i=0; i<particlesCount; i++) for (int i = 0; i < particlesCount; i++)
{ {
if (!particles[i].type) continue; if (!particles[i].type) continue;
pos = v2d_new(particles[i].x, particles[i].y); pos = v2d_new(particles[i].x, particles[i].y);
@ -435,9 +437,8 @@ void GameSave::readOPS(char * data, int dataLength)
unsigned char * inputData = (unsigned char*)data, *bsonData = NULL, *partsData = NULL, *partsPosData = NULL, *fanData = NULL, *wallData = NULL, *soapLinkData = NULL; unsigned char * inputData = (unsigned char*)data, *bsonData = NULL, *partsData = NULL, *partsPosData = NULL, *fanData = NULL, *wallData = NULL, *soapLinkData = NULL;
unsigned int inputDataLen = dataLength, bsonDataLen = 0, partsDataLen, partsPosDataLen, fanDataLen, wallDataLen, soapLinkDataLen; unsigned int inputDataLen = dataLength, bsonDataLen = 0, partsDataLen, partsPosDataLen, fanDataLen, wallDataLen, soapLinkDataLen;
unsigned partsCount = 0, *partsSimIndex = NULL; unsigned partsCount = 0, *partsSimIndex = NULL;
int i, x, y, j;
int *freeIndices = NULL; int *freeIndices = NULL;
int blockX, blockY, blockW, blockH, fullX, fullY, fullW, fullH; unsigned int blockX, blockY, blockW, blockH, fullX, fullY, fullW, fullH;
int savedVersion = inputData[4]; int savedVersion = inputData[4];
bson b; bson b;
bson_iterator iter; bson_iterator iter;
@ -681,6 +682,17 @@ void GameSave::readOPS(char * data, int dataLength)
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter)); fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
} }
} }
else if (!strcmp(bson_iterator_key(&iter), "edgeMode"))
{
if(bson_iterator_type(&iter)==BSON_INT)
{
edgeMode = bson_iterator_int(&iter);
}
else
{
fprintf(stderr, "Wrong type for %s\n", bson_iterator_key(&iter));
}
}
else if(strcmp(bson_iterator_key(&iter), "palette")==0) else if(strcmp(bson_iterator_key(&iter), "palette")==0)
{ {
palette.clear(); palette.clear();
@ -704,15 +716,15 @@ void GameSave::readOPS(char * data, int dataLength)
//Read wall and fan data //Read wall and fan data
if(wallData) if(wallData)
{ {
j = 0; unsigned int j = 0;
if(blockW * blockH > wallDataLen) if (blockW * blockH > wallDataLen)
{ {
fprintf(stderr, "Not enough wall data\n"); fprintf(stderr, "Not enough wall data\n");
goto fail; goto fail;
} }
for(x = 0; x < blockW; x++) for (unsigned int x = 0; x < blockW; x++)
{ {
for(y = 0; y < blockH; y++) for (unsigned int y = 0; y < blockH; y++)
{ {
if (wallData[y*blockW+x]) if (wallData[y*blockW+x])
blockMap[blockY+y][blockX+x] = wallData[y*blockW+x]; blockMap[blockY+y][blockX+x] = wallData[y*blockW+x];
@ -760,19 +772,18 @@ void GameSave::readOPS(char * data, int dataLength)
fanVelY[blockY+y][blockX+x] = (fanData[j++]-127.0f)/64.0f; fanVelY[blockY+y][blockX+x] = (fanData[j++]-127.0f)/64.0f;
} }
if (blockMap[y][x] < 0 || blockMap[y][x] >= UI_WALLCOUNT) if (blockMap[y][x] >= UI_WALLCOUNT)
blockMap[y][x] = 0; blockMap[y][x] = 0;
} }
} }
} }
//Read particle data //Read particle data
if(partsData && partsPosData) if (partsData && partsPosData)
{ {
int newIndex = 0, fieldDescriptor, tempTemp; int newIndex = 0, fieldDescriptor, tempTemp;
int posCount, posTotal, partsPosDataIndex = 0; int posCount, posTotal, partsPosDataIndex = 0;
int saved_x, saved_y; if (fullW * fullH * 3 > partsPosDataLen)
if(fullW * fullH * 3 > partsPosDataLen)
{ {
fprintf(stderr, "Not enough particle position data\n"); fprintf(stderr, "Not enough particle position data\n");
goto fail; goto fail;
@ -781,11 +792,12 @@ void GameSave::readOPS(char * data, int dataLength)
partsSimIndex = (unsigned int*)calloc(NPART, sizeof(unsigned)); partsSimIndex = (unsigned int*)calloc(NPART, sizeof(unsigned));
partsCount = 0; partsCount = 0;
i = 0; unsigned int i = 0;
unsigned int saved_x, saved_y, x, y;
newIndex = 0; newIndex = 0;
for (saved_y=0; saved_y<fullH; saved_y++) for (saved_y = 0; saved_y < fullH; saved_y++)
{ {
for (saved_x=0; saved_x<fullW; saved_x++) for (saved_x = 0; saved_x < fullW; saved_x++)
{ {
//Read total number of particles at this position //Read total number of particles at this position
posTotal = 0; posTotal = 0;
@ -793,10 +805,10 @@ void GameSave::readOPS(char * data, int dataLength)
posTotal |= partsPosData[partsPosDataIndex++]<<8; posTotal |= partsPosData[partsPosDataIndex++]<<8;
posTotal |= partsPosData[partsPosDataIndex++]; posTotal |= partsPosData[partsPosDataIndex++];
//Put the next posTotal particles at this position //Put the next posTotal particles at this position
for (posCount=0; posCount<posTotal; posCount++) for (posCount = 0; posCount < posTotal; posCount++)
{ {
particlesCount = newIndex+1; particlesCount = newIndex+1;
if(newIndex>=NPART) if (newIndex >= NPART)
{ {
goto fail; goto fail;
} }
@ -808,15 +820,13 @@ void GameSave::readOPS(char * data, int dataLength)
y = saved_y + fullY; y = saved_y + fullY;
fieldDescriptor = partsData[i+1]; fieldDescriptor = partsData[i+1];
fieldDescriptor |= partsData[i+2] << 8; fieldDescriptor |= partsData[i+2] << 8;
if(x >= fullW || x < 0 || y >= fullH || y < 0) if (x >= fullW || y >= fullH)
{ {
fprintf(stderr, "Out of range [%d]: %d %d, [%d, %d], [%d, %d]\n", i, x, y, (unsigned)partsData[i+1], (unsigned)partsData[i+2], (unsigned)partsData[i+3], (unsigned)partsData[i+4]); fprintf(stderr, "Out of range [%d]: %d %d, [%d, %d], [%d, %d]\n", i, x, y, (unsigned)partsData[i+1], (unsigned)partsData[i+2], (unsigned)partsData[i+3], (unsigned)partsData[i+4]);
goto fail; goto fail;
} }
if(partsData[i] >= PT_NUM)
partsData[i] = PT_DMND; //Replace all invalid elements with diamond
if(newIndex < 0 || newIndex >= NPART) if (newIndex < 0 || newIndex >= NPART)
goto fail; goto fail;
//Store partsptr index+1 for this saved particle index (0 means not loaded) //Store partsptr index+1 for this saved particle index (0 means not loaded)
@ -973,12 +983,14 @@ void GameSave::readOPS(char * data, int dataLength)
int caddress = restrict_flt(restrict_flt((float)(particles[newIndex].tmp-4), 0.0f, 200.0f)*3, 0.0f, (200.0f*3)-3); int caddress = restrict_flt(restrict_flt((float)(particles[newIndex].tmp-4), 0.0f, 200.0f)*3, 0.0f, (200.0f*3)-3);
particles[newIndex].type = PT_EMBR; particles[newIndex].type = PT_EMBR;
particles[newIndex].tmp = 1; particles[newIndex].tmp = 1;
particles[newIndex].ctype = (((unsigned char)(firw_data[caddress]))<<16) | (((unsigned char)(firw_data[caddress+1]))<<8) | ((unsigned char)(firw_data[caddress+2])); particles[newIndex].ctype = (((firw_data[caddress]))<<16) | (((firw_data[caddress+1]))<<8) | ((firw_data[caddress+2]));
} }
break; break;
case PT_PSTN: case PT_PSTN:
if (savedVersion < 87 && particles[newIndex].ctype) if (savedVersion < 87 && particles[newIndex].ctype)
particles[newIndex].life = 1; particles[newIndex].life = 1;
if (savedVersion < 91)
particles[newIndex].temp = 283.15;
break; break;
case PT_STKM: case PT_STKM:
case PT_STKM2: case PT_STKM2:
@ -1008,6 +1020,13 @@ void GameSave::readOPS(char * data, int dataLength)
{ {
particles[newIndex].flags |= FLAG_PHOTDECO; particles[newIndex].flags |= FLAG_PHOTDECO;
} }
break;
case PT_VINE:
if (savedVersion < 91)
{
particles[newIndex].tmp = 1;
}
break;
} }
//note: PSv was used in version 77.0 and every version before, add something in PSv too if the element is that old //note: PSv was used in version 77.0 and every version before, add something in PSv too if the element is that old
newIndex++; newIndex++;
@ -1016,13 +1035,13 @@ void GameSave::readOPS(char * data, int dataLength)
} }
if (soapLinkData) if (soapLinkData)
{ {
int soapLinkDataPos = 0; unsigned int soapLinkDataPos = 0;
for (i=0; i<partsCount; i++) for (unsigned int i = 0; i < partsCount; i++)
{ {
if (partsSimIndex[i] && particles[partsSimIndex[i]-1].type == PT_SOAP) if (partsSimIndex[i] && particles[partsSimIndex[i]-1].type == PT_SOAP)
{ {
// Get the index of the particle forward linked from this one, if present in the save data // Get the index of the particle forward linked from this one, if present in the save data
int linkedIndex = 0; unsigned int linkedIndex = 0;
if (soapLinkDataPos+3 > soapLinkDataLen) break; if (soapLinkDataPos+3 > soapLinkDataLen) break;
linkedIndex |= soapLinkData[soapLinkDataPos++]<<16; linkedIndex |= soapLinkData[soapLinkDataPos++]<<16;
linkedIndex |= soapLinkData[soapLinkDataPos++]<<8; linkedIndex |= soapLinkData[soapLinkDataPos++]<<8;
@ -1045,7 +1064,7 @@ void GameSave::readOPS(char * data, int dataLength)
if(tempSigns.size()) if(tempSigns.size())
{ {
for (int i = 0; i < tempSigns.size(); i++) for (size_t i = 0; i < tempSigns.size(); i++)
{ {
if(signs.size() == MAXSIGNS) if(signs.size() == MAXSIGNS)
break; break;
@ -1072,9 +1091,9 @@ fin:
void GameSave::readPSv(char * data, int dataLength) void GameSave::readPSv(char * data, int dataLength)
{ {
unsigned char * d = NULL, * c = (unsigned char *)data; unsigned char * d = NULL, * c = (unsigned char *)data;
int q,i,j,k,x,y,p=0,*m=NULL, ver, pty, ty, legacy_beta=0, tempGrav = 0; int q,i,j,k,x,y,p=0,*m=NULL, ver, pty, ty, legacy_beta=0;
int bx0=0, by0=0, bw, bh, w, h, y0 = 0, x0 = 0; int bx0=0, by0=0, bw, bh, w, h, y0 = 0, x0 = 0;
int nf=0, new_format = 0, ttv = 0; int new_format = 0, ttv = 0;
int *fp = (int *)malloc(NPART*sizeof(int)); int *fp = (int *)malloc(NPART*sizeof(int));
std::vector<sign> tempSigns; std::vector<sign> tempSigns;
@ -1167,7 +1186,7 @@ void GameSave::readPSv(char * data, int dataLength)
setSize(bw, bh); setSize(bw, bh);
int bzStatus = 0; int bzStatus = 0;
if (bzStatus = BZ2_bzBuffToBuffDecompress((char *)d, (unsigned *)&i, (char *)(c+12), dataLength-12, 0, 0)) if ((bzStatus = BZ2_bzBuffToBuffDecompress((char *)d, (unsigned *)&i, (char *)(c+12), dataLength-12, 0, 0)))
{ {
std::stringstream bzStatusStr; std::stringstream bzStatusStr;
bzStatusStr << bzStatus; bzStatusStr << bzStatus;
@ -1274,7 +1293,7 @@ void GameSave::readPSv(char * data, int dataLength)
blockMap[y][x]=WL_ALLOWENERGY; blockMap[y][x]=WL_ALLOWENERGY;
} }
if (blockMap[y][x] < 0 || blockMap[y][x] >= UI_WALLCOUNT) if (blockMap[y][x] >= UI_WALLCOUNT)
blockMap[y][x] = 0; blockMap[y][x] = 0;
} }
@ -1639,12 +1658,12 @@ void GameSave::readPSv(char * data, int dataLength)
int caddress = restrict_flt(restrict_flt((float)(particles[i-1].tmp-4), 0.0f, 200.0f)*3, 0.0f, (200.0f*3)-3); int caddress = restrict_flt(restrict_flt((float)(particles[i-1].tmp-4), 0.0f, 200.0f)*3, 0.0f, (200.0f*3)-3);
particles[i-1].type = PT_EMBR; particles[i-1].type = PT_EMBR;
particles[i-1].tmp = 1; particles[i-1].tmp = 1;
particles[i-1].ctype = (((unsigned char)(firw_data[caddress]))<<16) | (((unsigned char)(firw_data[caddress+1]))<<8) | ((unsigned char)(firw_data[caddress+2])); particles[i-1].ctype = (((firw_data[caddress]))<<16) | (((firw_data[caddress+1]))<<8) | ((firw_data[caddress+2]));
} }
} }
if (ver < 88) //fix air blowing stickmen if (ver < 88) //fix air blowing stickmen
if ((particles[i-1].type == PT_STKM || particles[i-1].type == PT_STKM2 || particles[i-1].type == PT_FIGH) && particles[i-1].ctype == OLD_SPC_AIR) if ((particles[i-1].type == PT_STKM || particles[i-1].type == PT_STKM2 || particles[i-1].type == PT_FIGH) && particles[i-1].ctype == OLD_SPC_AIR)
particles[i-1].ctype == SPC_AIR; particles[i-1].ctype = SPC_AIR;
if (ver < 89) if (ver < 89)
{ {
if (particles[i-1].type == PT_FILT) if (particles[i-1].type == PT_FILT)
@ -1660,6 +1679,11 @@ void GameSave::readPSv(char * data, int dataLength)
particles[i-1].ctype = 0; particles[i-1].ctype = 0;
} }
} }
if (ver < 91)
{
if (particles[i-1].type == PT_VINE)
particles[i-1].tmp = 1;
}
} }
} }
@ -1690,7 +1714,7 @@ void GameSave::readPSv(char * data, int dataLength)
p += x; p += x;
} }
for (i = 0; i < tempSigns.size(); i++) for (size_t i = 0; i < tempSigns.size(); i++)
{ {
if(signs.size() == MAXSIGNS) if(signs.size() == MAXSIGNS)
break; break;
@ -1736,7 +1760,7 @@ void GameSave::readPSv(char * data, int dataLength)
} }
} }
char * GameSave::serialiseOPS(int & dataLength) char * GameSave::serialiseOPS(unsigned int & dataLength)
{ {
//Particle *particles = sim->parts; //Particle *particles = sim->parts;
unsigned char *partsData = NULL, *partsPosData = NULL, *fanData = NULL, *wallData = NULL, *finalData = NULL, *outputData = NULL, *soapLinkData = NULL; unsigned char *partsData = NULL, *partsPosData = NULL, *fanData = NULL, *wallData = NULL, *finalData = NULL, *outputData = NULL, *soapLinkData = NULL;
@ -1890,13 +1914,13 @@ char * GameSave::serialiseOPS(int & dataLength)
//Store temperature as an offset of 21C(294.15K) or go into a 16byte int and store the whole thing //Store temperature as an offset of 21C(294.15K) or go into a 16byte int and store the whole thing
if(fabs(particles[i].temp-294.15f)<127) if(fabs(particles[i].temp-294.15f)<127)
{ {
tempTemp = (particles[i].temp-294.15f); tempTemp = floor(particles[i].temp-294.15f+0.5f);
partsData[partsDataLen++] = tempTemp; partsData[partsDataLen++] = tempTemp;
} }
else else
{ {
fieldDesc |= 1; fieldDesc |= 1;
tempTemp = particles[i].temp; tempTemp = (int)(particles[i].temp+0.5f);
partsData[partsDataLen++] = tempTemp; partsData[partsDataLen++] = tempTemp;
partsData[partsDataLen++] = tempTemp >> 8; partsData[partsDataLen++] = tempTemp >> 8;
} }
@ -1911,7 +1935,7 @@ char * GameSave::serialiseOPS(int & dataLength)
life = 0; life = 0;
fieldDesc |= 1 << 1; fieldDesc |= 1 << 1;
partsData[partsDataLen++] = life; partsData[partsDataLen++] = life;
if(particles[i].life & 0xFF00) if (life & 0xFF00)
{ {
fieldDesc |= 1 << 2; fieldDesc |= 1 << 2;
partsData[partsDataLen++] = life >> 8; partsData[partsDataLen++] = life >> 8;
@ -2079,6 +2103,7 @@ char * GameSave::serialiseOPS(int & dataLength)
bson_append_bool(&b, "paused", paused); bson_append_bool(&b, "paused", paused);
bson_append_int(&b, "gravityMode", gravityMode); bson_append_int(&b, "gravityMode", gravityMode);
bson_append_int(&b, "airMode", airMode); bson_append_int(&b, "airMode", airMode);
bson_append_int(&b, "edgeMode", edgeMode);
//bson_append_int(&b, "leftSelectedElement", sl); //bson_append_int(&b, "leftSelectedElement", sl);
//bson_append_int(&b, "rightSelectedElement", sr); //bson_append_int(&b, "rightSelectedElement", sr);
@ -2103,17 +2128,17 @@ char * GameSave::serialiseOPS(int & dataLength)
bson_append_finish_array(&b); bson_append_finish_array(&b);
} }
signsCount = 0; signsCount = 0;
for(i = 0; i < signs.size(); i++) for (size_t i = 0; i < signs.size(); i++)
{ {
if(signs[i].text.length() && signs[i].x>=0 && signs[i].x<=fullW && signs[i].y>=0 && signs[i].y<=fullH) if(signs[i].text.length() && signs[i].x>=0 && signs[i].x<=fullW && signs[i].y>=0 && signs[i].y<=fullH)
{ {
signsCount++; signsCount++;
} }
} }
if(signsCount) if (signsCount)
{ {
bson_append_start_array(&b, "signs"); bson_append_start_array(&b, "signs");
for(i = 0; i < signs.size(); i++) for (size_t i = 0; i < signs.size(); i++)
{ {
if(signs[i].text.length() && signs[i].x>=0 && signs[i].x<=fullW && signs[i].y>=0 && signs[i].y<=fullH) if(signs[i].text.length() && signs[i].x>=0 && signs[i].x<=fullW && signs[i].y>=0 && signs[i].y<=fullH)
{ {
@ -2153,7 +2178,7 @@ char * GameSave::serialiseOPS(int & dataLength)
if (BZ2_bzBuffToBuffCompress((char*)(outputData+12), &outputDataLen, (char*)finalData, bson_size(&b), 9, 0, 0) != BZ_OK) if (BZ2_bzBuffToBuffCompress((char*)(outputData+12), &outputDataLen, (char*)finalData, bson_size(&b), 9, 0, 0) != BZ_OK)
{ {
puts("Save Error\n"); puts("Save Error\n");
free(outputData); delete [] outputData;
dataLength = 0; dataLength = 0;
outputData = NULL; outputData = NULL;
goto fin; goto fin;

View File

@ -46,6 +46,7 @@ public:
bool paused; bool paused;
int gravityMode; int gravityMode;
int airMode; int airMode;
int edgeMode;
//Signs //Signs
std::vector<sign> signs; std::vector<sign> signs;
@ -62,7 +63,7 @@ public:
GameSave(std::vector<unsigned char> data); GameSave(std::vector<unsigned char> data);
~GameSave(); ~GameSave();
void setSize(int width, int height); void setSize(int width, int height);
char * Serialise(int & dataSize); char * Serialise(unsigned int & dataSize);
std::vector<char> Serialise(); std::vector<char> Serialise();
void Transform(matrix2d transform, vector2d translate); void Transform(matrix2d transform, vector2d translate);
@ -99,7 +100,7 @@ private:
void read(char * data, int dataSize); void read(char * data, int dataSize);
void readOPS(char * data, int dataLength); void readOPS(char * data, int dataLength);
void readPSv(char * data, int dataLength); void readPSv(char * data, int dataLength);
char * serialiseOPS(int & dataSize); char * serialiseOPS(unsigned int & dataSize);
//serialisePSv(); //serialisePSv();
}; };

View File

@ -72,6 +72,11 @@
#define PCLOSE close #define PCLOSE close
#endif #endif
#ifdef _MSC_VER
#include <BaseTsd.h> //for SSIZE_T
typedef SSIZE_T ssize_t;
#endif
char * userAgent; char * userAgent;
static int http_up = 0; static int http_up = 0;
static long http_timeout = 15; static long http_timeout = 15;
@ -706,7 +711,6 @@ void http_auth_headers(void *ctx, const char *user, const char *pass, const char
char *tmp; char *tmp;
int i; int i;
unsigned char hash[16]; unsigned char hash[16];
unsigned int m;
struct md5_context md5; struct md5_context md5;
if (user) if (user)
@ -716,7 +720,6 @@ void http_auth_headers(void *ctx, const char *user, const char *pass, const char
md5_init(&md5); md5_init(&md5);
md5_update(&md5, (unsigned char *)user, strlen(user)); md5_update(&md5, (unsigned char *)user, strlen(user));
md5_update(&md5, (unsigned char *)"-", 1); md5_update(&md5, (unsigned char *)"-", 1);
m = 0;
md5_update(&md5, (unsigned char *)pass, strlen(pass)); md5_update(&md5, (unsigned char *)pass, strlen(pass));
md5_final(hash, &md5); md5_final(hash, &md5);
@ -908,7 +911,7 @@ const char *http_ret_text(int ret)
return "Unknown Status Code"; return "Unknown Status Code";
} }
} }
char *http_multipart_post(const char *uri, const char *const *names, const char *const *parts, int *plens, const char *user, const char *pass, const char *session_id, int *ret, int *len) char *http_multipart_post(const char *uri, const char *const *names, const char *const *parts, size_t *plens, const char *user, const char *pass, const char *session_id, int *ret, int *len)
{ {
void *ctx; void *ctx;
char *data = NULL, *tmp; char *data = NULL, *tmp;
@ -927,7 +930,7 @@ char *http_multipart_post(const char *uri, const char *const *names, const char
{ {
own_plen = 1; own_plen = 1;
for (i=0; names[i]; i++) ; for (i=0; names[i]; i++) ;
plens = (int *)calloc(i, sizeof(int)); plens = (size_t *)calloc(i, sizeof(size_t));
for (i=0; names[i]; i++) for (i=0; names[i]; i++)
plens[i] = strlen(parts[i]); plens[i] = strlen(parts[i]);
} }
@ -938,7 +941,7 @@ retry:
memset(map, 0, 62*sizeof(int)); memset(map, 0, 62*sizeof(int));
for (i=0; names[i]; i++) for (i=0; names[i]; i++)
{ {
for (j=0; j<plens[i]-blen; j++) for (ssize_t j=0; j<(ssize_t)plens[i]-blen; j++)
if (!blen || !memcmp(parts[i]+j, boundary, blen)) if (!blen || !memcmp(parts[i]+j, boundary, blen))
{ {
ch = parts[i][j+blen]; ch = parts[i][j+blen];

View File

@ -20,7 +20,7 @@
#ifndef HTTP_H #ifndef HTTP_H
#define HTTP_H #define HTTP_H
static char hexChars[] = "0123456789abcdef"; static const char hexChars[] = "0123456789abcdef";
void http_init(char *proxy); void http_init(char *proxy);
void http_done(void); void http_done(void);
@ -38,7 +38,7 @@ void http_async_get_length(void *ctx, int *total, int *done);
char *http_async_req_stop(void *ctx, int *ret, int *len); char *http_async_req_stop(void *ctx, int *ret, int *len);
void http_async_req_close(void *ctx); void http_async_req_close(void *ctx);
char *http_multipart_post(const char *uri, const char *const *names, const char *const *parts, int *plens, const char *user, const char *pass, const char * session_id, int *ret, int *len); char *http_multipart_post(const char *uri, const char *const *names, const char *const *parts, size_t *plens, const char *user, const char *pass, const char * session_id, int *ret, int *len);
void *http_multipart_post_async(const char *uri, const char *const *names, const char *const *parts, int *plens, const char *user, const char *pass, const char *session_id); void *http_multipart_post_async(const char *uri, const char *const *names, const char *const *parts, int *plens, const char *user, const char *pass, const char *session_id);
const char *http_ret_text(int ret); const char *http_ret_text(int ret);

View File

@ -109,7 +109,7 @@ void md5_final(unsigned char digest[16], struct md5_context *ctx)
putu32(ctx->buf[1], digest + 4); putu32(ctx->buf[1], digest + 4);
putu32(ctx->buf[2], digest + 8); putu32(ctx->buf[2], digest + 8);
putu32(ctx->buf[3], digest + 12); putu32(ctx->buf[3], digest + 12);
memset(ctx, 0, sizeof(ctx)); memset(&ctx, 0, sizeof(ctx));
} }
#define F1(x, y, z) (z ^ (x & (y ^ z))) #define F1(x, y, z) (z ^ (x & (y ^ z)))

View File

@ -4,8 +4,8 @@
#include "gui/search/Thumbnail.h" #include "gui/search/Thumbnail.h"
SaveFile::SaveFile(SaveFile & save): SaveFile::SaveFile(SaveFile & save):
gameSave(NULL),
thumbnail(NULL), thumbnail(NULL),
gameSave(NULL),
filename(save.filename), filename(save.filename),
displayName(save.displayName) displayName(save.displayName)
{ {
@ -26,10 +26,10 @@ void SaveFile::SetThumbnail(Thumbnail * thumb)
} }
SaveFile::SaveFile(std::string filename): SaveFile::SaveFile(std::string filename):
filename(filename), thumbnail(NULL),
displayName(filename),
gameSave(NULL), gameSave(NULL),
thumbnail(NULL) filename(filename),
displayName(filename)
{ {
} }

View File

@ -3,60 +3,64 @@
#include "Client.h" #include "Client.h"
SaveInfo::SaveInfo(SaveInfo & save): SaveInfo::SaveInfo(SaveInfo & save):
id(save.id),
date(save.date),
votesUp(save.votesUp),
votesDown(save.votesDown),
vote(save.vote),
Favourite(false),
Comments(save.Comments),
Views(save.Views),
Version(save.Version),
userName(save.userName), userName(save.userName),
name(save.name), name(save.name),
Description(save.Description), Description(save.Description),
date(save.date),
Published(save.Published), Published(save.Published),
id(save.id), gameSave(NULL)
votesUp(save.votesUp),
votesDown(save.votesDown),
gameSave(NULL),
vote(save.vote),
Comments(save.Comments),
Views(save.Views),
Version(save.Version)
{ {
std::list<std::string> tagsSorted = save.tags; std::list<std::string> tagsSorted = save.tags;
tagsSorted.sort(); tagsSorted.sort();
tags=tagsSorted; tags = tagsSorted;
if(save.gameSave) if (save.gameSave)
gameSave = new GameSave(*save.gameSave); gameSave = new GameSave(*save.gameSave);
} }
SaveInfo::SaveInfo(int _id, int _date, int _votesUp, int _votesDown, std::string _userName, std::string _name): SaveInfo::SaveInfo(int _id, int _date, int _votesUp, int _votesDown, std::string _userName, std::string _name):
id(_id), id(_id),
date(_date),
votesUp(_votesUp), votesUp(_votesUp),
votesDown(_votesDown), votesDown(_votesDown),
vote(0),
Favourite(false),
Comments(0),
Views(0),
Version(0),
userName(_userName), userName(_userName),
name(_name), name(_name),
Description(""), Description(""),
date(_date),
Published(false), Published(false),
gameSave(NULL),
vote(0),
tags(), tags(),
Comments(0), gameSave(NULL)
Views(0),
Version(0)
{ {
} }
SaveInfo::SaveInfo(int _id, int date_, int _votesUp, int _votesDown, int _vote, std::string _userName, std::string _name, std::string description_, bool published_, std::list<std::string> tags_): SaveInfo::SaveInfo(int _id, int date_, int _votesUp, int _votesDown, int _vote, std::string _userName, std::string _name, std::string description_, bool published_, std::list<std::string> tags_):
id(_id), id(_id),
date(date_),
votesUp(_votesUp), votesUp(_votesUp),
votesDown(_votesDown), votesDown(_votesDown),
vote(_vote),
Favourite(false),
Comments(0),
Views(0),
Version(0),
userName(_userName), userName(_userName),
name(_name), name(_name),
Description(description_), Description(description_),
date(date_),
Published(published_), Published(published_),
gameSave(NULL), tags(),
vote(_vote), gameSave(NULL)
Comments(0),
Views(0),
Version(0)
{ {
std::list<std::string> tagsSorted = tags_; std::list<std::string> tagsSorted = tags_;
tagsSorted.sort(); tagsSorted.sort();

View File

@ -16,11 +16,19 @@ public:
int id; int id;
int date; int date;
int votesUp, votesDown; int votesUp, votesDown;
int vote;
bool Favourite; bool Favourite;
int Comments; int Comments;
int Views; int Views;
int Version; int Version;
std::string userName;
std::string name;
std::string Description;
bool Published;
std::list<std::string> tags;
GameSave * gameSave; GameSave * gameSave;
SaveInfo(SaveInfo & save); SaveInfo(SaveInfo & save);
@ -31,17 +39,6 @@ public:
~SaveInfo(); ~SaveInfo();
std::string userName;
std::string name;
std::string Description;
std::list<std::string> tags;
int vote;
bool Published;
void SetName(std::string name); void SetName(std::string name);
std::string GetName(); std::string GetName();

View File

@ -103,7 +103,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb)
std::strcpy(userName, format::NumberToString<int>(user.ID).c_str()); std::strcpy(userName, format::NumberToString<int>(user.ID).c_str());
std::strcpy(userSession, user.SessionID.c_str()); std::strcpy(userSession, user.SessionID.c_str());
HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession);
delete userSession; delete[] userSession;
} }
else else
{ {

View File

@ -14,6 +14,8 @@
//Asynchronous Thumbnail render & request processing //Asynchronous Thumbnail render & request processing
unsigned int RequestListener::nextListenerID = 0;
RequestBroker::RequestBroker() RequestBroker::RequestBroker()
{ {
thumbnailQueueRunning = false; thumbnailQueueRunning = false;
@ -265,7 +267,7 @@ bool RequestBroker::CheckRequestListener(ListenerHandle handle)
ListenerHandle RequestBroker::AttachRequestListener(RequestListener * tListener) ListenerHandle RequestBroker::AttachRequestListener(RequestListener * tListener)
{ {
ListenerHandle handle = ListenerHandle(tListener->ListenerRand, tListener); ListenerHandle handle = ListenerHandle(tListener->ListenerID, tListener);
pthread_mutex_lock(&listenersMutex); pthread_mutex_lock(&listenersMutex);
validListeners.push_back(handle); validListeners.push_back(handle);
pthread_mutex_unlock(&listenersMutex); pthread_mutex_unlock(&listenersMutex);
@ -282,7 +284,7 @@ void RequestBroker::DetachRequestListener(RequestListener * tListener)
std::vector<ListenerHandle>::iterator iter = validListeners.begin(); std::vector<ListenerHandle>::iterator iter = validListeners.begin();
while (iter != validListeners.end()) while (iter != validListeners.end())
{ {
if(*iter == ListenerHandle(tListener->ListenerRand, tListener)) if(*iter == ListenerHandle(tListener->ListenerID, tListener))
iter = validListeners.erase(iter); iter = validListeners.erase(iter);
else else
++iter; ++iter;
@ -306,7 +308,7 @@ RequestBroker::Request::~Request()
delete (*iter); delete (*iter);
iter++; iter++;
} }
Children.empty(); Children.clear();
} }
void RequestBroker::Request::Cleanup() void RequestBroker::Request::Cleanup()
{ {

View File

@ -3,8 +3,9 @@
class RequestListener class RequestListener
{ {
public: public:
int ListenerRand; static unsigned int nextListenerID;
RequestListener() { ListenerRand = rand(); } int ListenerID;
RequestListener() { ListenerID = nextListenerID++; }
virtual ~RequestListener() {} virtual ~RequestListener() {}
virtual void OnResponseReady(void * response, int identifier) {} virtual void OnResponseReady(void * response, int identifier) {}

View File

@ -103,7 +103,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb)
std::strcpy(userName, format::NumberToString<int>(user.ID).c_str()); std::strcpy(userName, format::NumberToString<int>(user.ID).c_str());
std::strcpy(userSession, user.SessionID.c_str()); std::strcpy(userSession, user.SessionID.c_str());
HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession); HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession);
delete userSession; delete[] userSession;
} }
else else
{ {

View File

@ -5,5 +5,7 @@
class DebugInfo class DebugInfo
{ {
public: public:
virtual void Draw(ui::Point position) {} DebugInfo(unsigned int id):ID(id) { }
unsigned int ID;
virtual void Draw() {}
}; };

52
src/debug/DebugLines.cpp Normal file
View File

@ -0,0 +1,52 @@
#include "DebugLines.h"
#include "gui/interface/Engine.h"
#include "gui/game/GameView.h"
#include "gui/game/GameController.h"
DebugLines::DebugLines(unsigned int id, GameView * view, GameController * controller):
DebugInfo(id),
view(view),
controller(controller)
{
}
void DebugLines::Draw()
{
Graphics * g = ui::Engine::Ref().g;
if (view->GetDrawingLine())
{
ui::Point drawPoint1 = controller->PointTranslate(view->GetLineStartCoords()), drawPoint2 = controller->PointTranslate(view->GetLineFinishCoords());
if (view->GetDrawSnap())
drawPoint2 = view->lineSnapCoords(drawPoint1, drawPoint2);
//g->draw_line(drawPoint1.X, drawPoint1.Y, drawPoint2.X, drawPoint2.Y, 255, 0, 255, 255);
g->draw_line(0, drawPoint1.Y, XRES, drawPoint1.Y, 255, 255, 255, 120);
g->draw_line(drawPoint1.X, 0, drawPoint1.X, YRES, 255, 255, 255, 120);
g->draw_line(0, drawPoint2.Y, XRES, drawPoint2.Y, 255, 255, 255, 120);
g->draw_line(drawPoint2.X, 0, drawPoint2.X, YRES, 255, 255, 255, 120);
std::stringstream info;
info << drawPoint2.X << " x " << drawPoint2.Y;
g->drawtext_outline(drawPoint2.X+(drawPoint2.X>drawPoint1.X?3:-g->textwidth(info.str().c_str())-3), drawPoint2.Y+(drawPoint2.Y<drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200);
info.str("");
info << drawPoint1.X << " x " << drawPoint1.Y;
g->drawtext_outline(drawPoint1.X+(drawPoint2.X<drawPoint1.X?3:-g->textwidth(info.str().c_str())-2), drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200);
info.str("");
info << std::abs(drawPoint2.X-drawPoint1.X);
g->drawtext_outline((drawPoint1.X+drawPoint2.X)/2-g->textwidth(info.str().c_str())/2, drawPoint1.Y+(drawPoint2.Y>drawPoint1.Y?-10:3), info.str().c_str(), 255, 255, 255, 200);
info.str("");
info << std::abs(drawPoint2.Y-drawPoint1.Y);
g->drawtext_outline(drawPoint1.X+(drawPoint2.X<drawPoint1.X?3:-g->textwidth(info.str().c_str())-2), (drawPoint1.Y+drawPoint2.Y)/2-3, info.str().c_str(), 255, 255, 255, 200);
}
}
DebugLines::~DebugLines()
{
}

15
src/debug/DebugLines.h Normal file
View File

@ -0,0 +1,15 @@
#pragma once
#include "DebugInfo.h"
class GameView;
class GameController;
class DebugLines : public DebugInfo
{
GameView * view;
GameController * controller;
public:
DebugLines(unsigned int id, GameView * view, GameController * controller);
virtual void Draw();
virtual ~DebugLines();
};

55
src/debug/DebugParts.cpp Normal file
View File

@ -0,0 +1,55 @@
#include "DebugParts.h"
#include "gui/interface/Engine.h"
#include "simulation/Simulation.h"
#include <iomanip>
DebugParts::DebugParts(unsigned int id, Simulation * sim):
DebugInfo(id),
sim(sim)
{
}
void DebugParts::Draw()
{
Graphics * g = ui::Engine::Ref().g;
int x = 0, y = 0, lpx = 0, lpy = 0;
std::stringstream info;
info << sim->parts_lastActiveIndex << "/" << NPART << " (" << std::fixed << std::setprecision(2) << (float)sim->parts_lastActiveIndex/(NPART)*100.0f << "%)";
for (int i = 0; i < NPART; i++)
{
if (sim->parts[i].type)
g->addpixel(x, y, 255, 255, 255, 180);
else
g->addpixel(x, y, 0, 0, 0, 180);
if (i == sim->parts_lastActiveIndex)
{
lpx = x;
lpy = y;
}
x++;
if(x >= XRES)
{
y++;
x = 0;
}
}
g->draw_line(0, lpy, XRES, lpy, 0, 255, 120, 255);
g->draw_line(lpx, 0, lpx, YRES, 0, 255, 120, 255);
g->addpixel(lpx, lpy, 255, 50, 50, 220);
g->addpixel(lpx+1, lpy, 255, 50, 50, 120);
g->addpixel(lpx-1, lpy, 255, 50, 50, 120);
g->addpixel(lpx, lpy+1, 255, 50, 50, 120);
g->addpixel(lpx, lpy-1, 255, 50, 50, 120);
g->fillrect(7, YRES-26, g->textwidth(info.str().c_str())+5, 14, 0, 0, 0, 180);
g->drawtext(10, YRES-22, info.str().c_str(), 255, 255, 255, 255);
}
DebugParts::~DebugParts()
{
}

13
src/debug/DebugParts.h Normal file
View File

@ -0,0 +1,13 @@
#pragma once
#include "DebugInfo.h"
class Simulation;
class DebugParts : public DebugInfo
{
Simulation * sim;
public:
DebugParts(unsigned int id, Simulation * sim);
virtual void Draw();
virtual ~DebugParts();
};

View File

@ -3,17 +3,17 @@
#include "simulation/Simulation.h" #include "simulation/Simulation.h"
#include "Format.h" #include "Format.h"
ElementPopulationDebug::ElementPopulationDebug(Simulation * sim): ElementPopulationDebug::ElementPopulationDebug(unsigned int id, Simulation * sim):
DebugInfo(id),
sim(sim), sim(sim),
maxAverage(255.0f) maxAverage(255.0f)
{ {
} }
void ElementPopulationDebug::Draw(ui::Point position) void ElementPopulationDebug::Draw()
{ {
Graphics * g = ui::Engine::Ref().g; Graphics * g = ui::Engine::Ref().g;
//g->drawtext(10, 10, "Arse", 255, 255, 255, 255);
int yBottom = YRES-10; int yBottom = YRES-10;
int xStart = 10; int xStart = 10;

View File

@ -8,7 +8,7 @@ class ElementPopulationDebug : public DebugInfo
Simulation * sim; Simulation * sim;
float maxAverage; float maxAverage;
public: public:
ElementPopulationDebug(Simulation * sim); ElementPopulationDebug(unsigned int id, Simulation * sim);
virtual void Draw(ui::Point position); virtual void Draw();
virtual ~ElementPopulationDebug(); virtual ~ElementPopulationDebug();
}; };

View File

@ -89,7 +89,7 @@ void VideoBuffer::Resize(int width, int height, bool resample, bool fixedRatio)
int VideoBuffer::SetCharacter(int x, int y, int c, int r, int g, int b, int a) int VideoBuffer::SetCharacter(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; int i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c]; unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++); w = *(rp++);
for (j=0; j<FONT_H; j++) for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++) for (i=0; i<w; i++)
@ -109,7 +109,7 @@ int VideoBuffer::SetCharacter(int x, int y, int c, int r, int g, int b, int a)
int VideoBuffer::BlendCharacter(int x, int y, int c, int r, int g, int b, int a) int VideoBuffer::BlendCharacter(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; int i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c]; unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++); w = *(rp++);
for (j=0; j<FONT_H; j++) for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++) for (i=0; i<w; i++)
@ -129,7 +129,7 @@ int VideoBuffer::BlendCharacter(int x, int y, int c, int r, int g, int b, int a)
int VideoBuffer::AddCharacter(int x, int y, int c, int r, int g, int b, int a) int VideoBuffer::AddCharacter(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; int i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c]; unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++); w = *(rp++);
for (j=0; j<FONT_H; j++) for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++) for (i=0; i<w; i++)
@ -826,7 +826,7 @@ void Graphics::textsize(const char * s, int & width, int & height)
} }
else if (*s == '\x0F') else if (*s == '\x0F')
{ {
if(!s[1] || !s[2] || !s[1]) break; if(!s[1] || !s[2] || !s[3]) break;
s+=3; s+=3;
} }
else if (*s == '\b') else if (*s == '\b')
@ -1119,11 +1119,12 @@ void Graphics::draw_icon(int x, int y, Icon icon, unsigned char alpha, bool inve
} }
} }
void Graphics::draw_rgba_image(unsigned char *data, int x, int y, float alpha) void Graphics::draw_rgba_image(const unsigned char *data_, int x, int y, float alpha)
{ {
unsigned char w, h; unsigned char w, h;
int i, j; int i, j;
unsigned char r, g, b, a; unsigned char r, g, b, a;
unsigned char *data = (unsigned char*)data_;
if (!data) return; if (!data) return;
w = *(data++)&0xFF; w = *(data++)&0xFF;
h = *(data++)&0xFF; h = *(data++)&0xFF;

View File

@ -35,6 +35,7 @@
#define PIXG(x) (((x)>>16)&0xFF) #define PIXG(x) (((x)>>16)&0xFF)
#define PIXB(x) (((x)>>24)&0xFF) #define PIXB(x) (((x)>>24)&0xFF)
#elif defined(PIX32OGL) #elif defined(PIX32OGL)
#undef PIXELCHANNELS
#define PIXELCHANNELS 4 #define PIXELCHANNELS 4
#define PIXPACK(x) (0xFF000000|((x)&0xFFFFFF)) //32bit ARGB in 32bit int: AARRGGBB #define PIXPACK(x) (0xFF000000|((x)&0xFFFFFF)) //32bit ARGB in 32bit int: AARRGGBB
#define PIXRGB(r,g,b) (0xFF000000|((r)<<16)|((g)<<8)|((b))) #define PIXRGB(r,g,b) (0xFF000000|((r)<<16)|((g)<<8)|((b)))
@ -247,7 +248,7 @@ public:
void draw_image(pixel *img, int x, int y, int w, int h, int a); void draw_image(pixel *img, int x, int y, int w, int h, int a);
void draw_image(const VideoBuffer & vidBuf, int w, int h, int a); void draw_image(const VideoBuffer & vidBuf, int w, int h, int a);
void draw_image(VideoBuffer * vidBuf, int w, int h, int a); void draw_image(VideoBuffer * vidBuf, int w, int h, int a);
void draw_rgba_image(unsigned char *data, int x, int y, float alpha); void draw_rgba_image(const unsigned char *data, int x, int y, float alpha);
Graphics(); Graphics();
~Graphics(); ~Graphics();

View File

@ -135,9 +135,8 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, std::string s, int r, int g, int
int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a) int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c];
char *rp = font_data + font_ptrs[c]; int w = *(rp++);
w = *(rp++);
VideoBuffer texture(w, 12); VideoBuffer texture(w, 12);
texture.SetCharacter(0, 0, c, r, g, b, a); texture.SetCharacter(0, 0, c, r, g, b, a);
@ -165,9 +164,8 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a
int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a) int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; unsigned char *rp = font_data + font_ptrs[c];
char *rp = font_data + font_ptrs[c]; int w = *(rp++);
w = *(rp++);
VideoBuffer texture(w, 12); VideoBuffer texture(w, 12);
texture.AddCharacter(0, 0, c, r, g, b, a); texture.AddCharacter(0, 0, c, r, g, b, a);

View File

@ -16,7 +16,6 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int
{ {
if(!strlen(s)) if(!strlen(s))
return 0; return 0;
int width, height;
int invert = 0; int invert = 0;
int oR = r, oG = g, oB = b; int oR = r, oG = g, oB = b;
@ -111,7 +110,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, std::string s, int r, int g, int
int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a) int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; int i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c]; unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++); w = *(rp++);
for (j=0; j<FONT_H; j++) for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++) for (i=0; i<w; i++)
@ -131,7 +130,7 @@ int PIXELMETHODS_CLASS::drawchar(int x, int y, int c, int r, int g, int b, int a
int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a) int PIXELMETHODS_CLASS::addchar(int x, int y, int c, int r, int g, int b, int a)
{ {
int i, j, w, bn = 0, ba = 0; int i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c]; unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++); w = *(rp++);
for (j=0; j<FONT_H; j++) for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++) for (i=0; i<w; i++)

View File

@ -201,7 +201,7 @@ void Renderer::clearScreen(float alpha)
#endif #endif
} }
#ifdef OGLR #ifdef OGLR
void Renderer::checkShader(GLuint shader, char * shname) void Renderer::checkShader(GLuint shader, const char * shname)
{ {
GLint status; GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status); glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
@ -214,7 +214,7 @@ void Renderer::checkShader(GLuint shader, char * shname)
exit(1); exit(1);
} }
} }
void Renderer::checkProgram(GLuint program, char * progname) void Renderer::checkProgram(GLuint program, const char * progname)
{ {
GLint status; GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status); glGetProgramiv(program, GL_LINK_STATUS, &status);
@ -521,7 +521,7 @@ wall_type * Renderer_wtypes = LoadWalls(Renderer_wtypesCount);
VideoBuffer * Renderer::WallIcon(int wallID, int width, int height) VideoBuffer * Renderer::WallIcon(int wallID, int width, int height)
{ {
int i, j, cr, cg, cb; int i, j;
int wt = wallID; int wt = wallID;
if (wt<0 || wt>=Renderer_wtypesCount) if (wt<0 || wt>=Renderer_wtypesCount)
return 0; return 0;
@ -706,7 +706,7 @@ void Renderer::DrawWalls()
if (bmap[y][x]) if (bmap[y][x])
{ {
wt = bmap[y][x]; wt = bmap[y][x];
if (wt<0 || wt>=UI_WALLCOUNT) if (wt >= UI_WALLCOUNT)
continue; continue;
pc = wtypes[wt].colour; pc = wtypes[wt].colour;
gc = wtypes[wt].eglow; gc = wtypes[wt].eglow;
@ -912,7 +912,7 @@ void Renderer::DrawWalls()
void Renderer::DrawSigns() void Renderer::DrawSigns()
{ {
int i, j, x, y, w, h, dx, dy,mx,my,b=1,bq,match; int x, y, w, h;
std::vector<sign> signs = sim->signs; std::vector<sign> signs = sim->signs;
#ifdef OGLR #ifdef OGLR
GLint prevFbo; GLint prevFbo;
@ -920,7 +920,7 @@ void Renderer::DrawSigns()
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, partsFbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, partsFbo);
glTranslated(0, MENUSIZE, 0); glTranslated(0, MENUSIZE, 0);
#endif #endif
for (i=0; i < signs.size(); i++) for (size_t i = 0; i < signs.size(); i++)
if (signs[i].text.length()) if (signs[i].text.length())
{ {
char type = 0; char type = 0;
@ -936,10 +936,10 @@ void Renderer::DrawSigns()
else else
drawtext(x+3, y+3, text, 0, 191, 255, 255); drawtext(x+3, y+3, text, 0, 191, 255, 255);
x = signs[i].x; int x = signs[i].x;
y = signs[i].y; int y = signs[i].y;
dx = 1 - signs[i].ju; int dx = 1 - signs[i].ju;
dy = (signs[i].y > 18) ? -1 : 1; int dy = (signs[i].y > 18) ? -1 : 1;
#ifdef OGLR #ifdef OGLR
glBegin(GL_LINES); glBegin(GL_LINES);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
@ -947,11 +947,11 @@ void Renderer::DrawSigns()
glVertex2i(x+(dx*4), y+(dy*4)); glVertex2i(x+(dx*4), y+(dy*4));
glEnd(); glEnd();
#else #else
for (j=0; j<4; j++) for (int j = 0; j < 4; j++)
{ {
blendpixel(x, y, 192, 192, 192, 255); blendpixel(x, y, 192, 192, 192, 255);
x+=dx; x += dx;
y+=dy; y += dy;
} }
#endif #endif
} }
@ -1004,7 +1004,7 @@ void Renderer::render_fire()
#ifndef OGLR #ifndef OGLR
if(!(render_mode & FIREMODE)) if(!(render_mode & FIREMODE))
return; return;
int i,j,x,y,r,g,b,nx,ny; int i,j,x,y,r,g,b;
for (j=0; j<YRES/CELL; j++) for (j=0; j<YRES/CELL; j++)
for (i=0; i<XRES/CELL; i++) for (i=0; i<XRES/CELL; i++)
{ {
@ -1043,7 +1043,7 @@ float blur_alphaf[7][7];
void Renderer::prepare_alpha(int size, float intensity) void Renderer::prepare_alpha(int size, float intensity)
{ {
//TODO: implement size //TODO: implement size
int x,y,i,j,c; int x,y,i,j;
float multiplier = 255.0f*intensity; float multiplier = 255.0f*intensity;
memset(temp, 0, sizeof(temp)); memset(temp, 0, sizeof(temp));
@ -1071,7 +1071,7 @@ void Renderer::prepare_alpha(int size, float intensity)
memset(glow_alphaf, 0, sizeof(glow_alphaf)); memset(glow_alphaf, 0, sizeof(glow_alphaf));
c = 5; int c = 5;
glow_alphaf[c][c-1] = 0.4f; glow_alphaf[c][c-1] = 0.4f;
glow_alphaf[c][c+1] = 0.4f; glow_alphaf[c][c+1] = 0.4f;
@ -1125,7 +1125,7 @@ void Renderer::render_parts()
{ {
int deca, decr, decg, decb, cola, colr, colg, colb, firea, firer, fireg, fireb, pixel_mode, q, i, t, nx, ny, x, y, caddress; int deca, decr, decg, decb, cola, colr, colg, colb, firea, firer, fireg, fireb, pixel_mode, q, i, t, nx, ny, x, y, caddress;
int orbd[4] = {0, 0, 0, 0}, orbl[4] = {0, 0, 0, 0}; int orbd[4] = {0, 0, 0, 0}, orbl[4] = {0, 0, 0, 0};
float gradv, flicker, fnx, fny; float gradv, flicker;
Particle * parts; Particle * parts;
Element *elements; Element *elements;
if(!sim) if(!sim)
@ -1133,6 +1133,7 @@ void Renderer::render_parts()
parts = sim->parts; parts = sim->parts;
elements = sim->elements; elements = sim->elements;
#ifdef OGLR #ifdef OGLR
float fnx, fny;
int cfireV = 0, cfireC = 0, cfire = 0; int cfireV = 0, cfireC = 0, cfire = 0;
int csmokeV = 0, csmokeC = 0, csmoke = 0; int csmokeV = 0, csmokeC = 0, csmoke = 0;
int cblobV = 0, cblobC = 0, cblob = 0; int cblobV = 0, cblobC = 0, cblob = 0;
@ -1168,8 +1169,10 @@ void Renderer::render_parts()
nx = (int)(sim->parts[i].x+0.5f); nx = (int)(sim->parts[i].x+0.5f);
ny = (int)(sim->parts[i].y+0.5f); ny = (int)(sim->parts[i].y+0.5f);
#ifdef OGLR
fnx = sim->parts[i].x; fnx = sim->parts[i].x;
fny = sim->parts[i].y; fny = sim->parts[i].y;
#endif
if(nx >= XRES || nx < 0 || ny >= YRES || ny < 0) if(nx >= XRES || nx < 0 || ny >= YRES || ny < 0)
continue; continue;
@ -1280,9 +1283,9 @@ void Renderer::render_parts()
{ {
caddress = restrict_flt((int)( restrict_flt((float)(sim->parts[i].temp+(-MIN_TEMP)), 0.0f, MAX_TEMP+(-MIN_TEMP)) / ((MAX_TEMP+(-MIN_TEMP))/1024) ) *3, 0.0f, (1024.0f*3)-3); caddress = restrict_flt((int)( restrict_flt((float)(sim->parts[i].temp+(-MIN_TEMP)), 0.0f, MAX_TEMP+(-MIN_TEMP)) / ((MAX_TEMP+(-MIN_TEMP))/1024) ) *3, 0.0f, (1024.0f*3)-3);
firea = 255; firea = 255;
firer = colr = (unsigned char)color_data[caddress]; firer = colr = color_data[caddress];
fireg = colg = (unsigned char)color_data[caddress+1]; fireg = colg = color_data[caddress+1];
fireb = colb = (unsigned char)color_data[caddress+2]; fireb = colb = color_data[caddress+2];
cola = 255; cola = 255;
if(pixel_mode & (FIREMODE | PMODE_GLOW)) if(pixel_mode & (FIREMODE | PMODE_GLOW))
pixel_mode = (pixel_mode & ~(FIREMODE|PMODE_GLOW)) | PMODE_BLUR; pixel_mode = (pixel_mode & ~(FIREMODE|PMODE_GLOW)) | PMODE_BLUR;
@ -1365,7 +1368,7 @@ void Renderer::render_parts()
{ {
if (t==PT_SOAP) if (t==PT_SOAP)
{ {
if ((parts[i].ctype&7) == 7 && parts[i].tmp >= 0 && parts[i].tmp < NPART && parts[i].tmp2 >= 0 && parts[i].tmp2 < NPART) if ((parts[i].ctype&3) == 3 && parts[i].tmp >= 0 && parts[i].tmp < NPART)
draw_line(nx, ny, (int)(parts[parts[i].tmp].x+0.5f), (int)(parts[parts[i].tmp].y+0.5f), colr, colg, colb, cola); draw_line(nx, ny, (int)(parts[parts[i].tmp].x+0.5f), (int)(parts[parts[i].tmp].y+0.5f), colr, colg, colb, cola);
} }
} }
@ -1377,7 +1380,7 @@ void Renderer::render_parts()
cplayer = &sim->player; cplayer = &sim->player;
else if(t==PT_STKM2) else if(t==PT_STKM2)
cplayer = &sim->player2; cplayer = &sim->player2;
else if(t==PT_FIGH) else if (t==PT_FIGH && sim->parts[i].tmp >= 0 && sim->parts[i].tmp < MAX_FIGHTERS)
cplayer = &sim->fighters[(unsigned char)sim->parts[i].tmp]; cplayer = &sim->fighters[(unsigned char)sim->parts[i].tmp];
else else
continue; continue;
@ -2268,7 +2271,7 @@ void Renderer::draw_air()
{ {
float ttemp = hv[y][x]+(-MIN_TEMP); float ttemp = hv[y][x]+(-MIN_TEMP);
int caddress = restrict_flt((int)( restrict_flt(ttemp, 0.0f, MAX_TEMP+(-MIN_TEMP)) / ((MAX_TEMP+(-MIN_TEMP))/1024) ) *3, 0.0f, (1024.0f*3)-3); int caddress = restrict_flt((int)( restrict_flt(ttemp, 0.0f, MAX_TEMP+(-MIN_TEMP)) / ((MAX_TEMP+(-MIN_TEMP))/1024) ) *3, 0.0f, (1024.0f*3)-3);
c = PIXRGB((int)((unsigned char)color_data[caddress]*0.7f), (int)((unsigned char)color_data[caddress+1]*0.7f), (int)((unsigned char)color_data[caddress+2]*0.7f)); c = PIXRGB((int)(color_data[caddress]*0.7f), (int)(color_data[caddress+1]*0.7f), (int)(color_data[caddress+2]*0.7f));
//c = PIXRGB(clamp_flt(fabsf(vx[y][x]), 0.0f, 8.0f),//vx adds red //c = PIXRGB(clamp_flt(fabsf(vx[y][x]), 0.0f, 8.0f),//vx adds red
// clamp_flt(hv[y][x], 0.0f, 1600.0f),//heat adds green // clamp_flt(hv[y][x], 0.0f, 1600.0f),//heat adds green
// clamp_flt(fabsf(vy[y][x]), 0.0f, 8.0f));//vy adds blue // clamp_flt(fabsf(vy[y][x]), 0.0f, 8.0f));//vy adds blue
@ -2421,22 +2424,22 @@ pixel Renderer::GetPixel(int x, int y)
Renderer::Renderer(Graphics * g, Simulation * sim): Renderer::Renderer(Graphics * g, Simulation * sim):
sim(NULL), sim(NULL),
g(NULL), g(NULL),
render_mode(0),
colour_mode(0),
display_mode(0),
gravityZonesEnabled(false),
gravityFieldEnabled(false),
decorations_enable(1),
blackDecorations(false),
debugLines(false),
sampleColor(0xFFFFFFFF),
mousePos(0, 0),
zoomWindowPosition(0, 0), zoomWindowPosition(0, 0),
zoomScopePosition(0, 0), zoomScopePosition(0, 0),
zoomScopeSize(32), zoomScopeSize(32),
ZFACTOR(8),
zoomEnabled(false), zoomEnabled(false),
decorations_enable(1), ZFACTOR(8),
gravityFieldEnabled(false), gridSize(0)
gravityZonesEnabled(false),
mousePos(0, 0),
display_mode(0),
render_mode(0),
colour_mode(0),
gridSize(0),
blackDecorations(false),
debugLines(false),
sampleColor(0xFFFFFFFF)
{ {
this->g = g; this->g = g;
this->sim = sim; this->sim = sim;
@ -2685,7 +2688,7 @@ void Renderer::CompileRenderMode()
{ {
int old_render_mode = render_mode; int old_render_mode = render_mode;
render_mode = 0; render_mode = 0;
for(int i = 0; i < render_modes.size(); i++) for (size_t i = 0; i < render_modes.size(); i++)
render_mode |= render_modes[i]; render_mode |= render_modes[i];
//If firemode is removed, clear the fire display //If firemode is removed, clear the fire display
@ -2707,7 +2710,7 @@ void Renderer::ClearAccumulation()
void Renderer::AddRenderMode(unsigned int mode) void Renderer::AddRenderMode(unsigned int mode)
{ {
for(int i = 0; i < render_modes.size(); i++) for (size_t i = 0; i < render_modes.size(); i++)
{ {
if(render_modes[i] == mode) if(render_modes[i] == mode)
{ {
@ -2720,7 +2723,7 @@ void Renderer::AddRenderMode(unsigned int mode)
void Renderer::RemoveRenderMode(unsigned int mode) void Renderer::RemoveRenderMode(unsigned int mode)
{ {
for(int i = 0; i < render_modes.size(); i++) for (size_t i = 0; i < render_modes.size(); i++)
{ {
if(render_modes[i] == mode) if(render_modes[i] == mode)
{ {
@ -2746,9 +2749,9 @@ void Renderer::CompileDisplayMode()
{ {
int old_display_mode = display_mode; int old_display_mode = display_mode;
display_mode = 0; display_mode = 0;
for(int i = 0; i < display_modes.size(); i++) for (size_t i = 0; i < display_modes.size(); i++)
display_mode |= display_modes[i]; display_mode |= display_modes[i];
if(!(display_mode & DISPLAY_PERS) && (old_display_mode & DISPLAY_PERS)) if (!(display_mode & DISPLAY_PERS) && (old_display_mode & DISPLAY_PERS))
{ {
ClearAccumulation(); ClearAccumulation();
} }
@ -2756,13 +2759,13 @@ void Renderer::CompileDisplayMode()
void Renderer::AddDisplayMode(unsigned int mode) void Renderer::AddDisplayMode(unsigned int mode)
{ {
for(int i = 0; i < display_modes.size(); i++) for (size_t i = 0; i < display_modes.size(); i++)
{ {
if(display_modes[i] == mode) if (display_modes[i] == mode)
{ {
return; return;
} }
if(display_modes[i] & DISPLAY_AIR) if (display_modes[i] & DISPLAY_AIR)
{ {
display_modes.erase(display_modes.begin()+i); display_modes.erase(display_modes.begin()+i);
} }
@ -2773,9 +2776,9 @@ void Renderer::AddDisplayMode(unsigned int mode)
void Renderer::RemoveDisplayMode(unsigned int mode) void Renderer::RemoveDisplayMode(unsigned int mode)
{ {
for(int i = 0; i < display_modes.size(); i++) for (size_t i = 0; i < display_modes.size(); i++)
{ {
if(display_modes[i] == mode) if (display_modes[i] == mode)
{ {
display_modes.erase(display_modes.begin() + i); display_modes.erase(display_modes.begin() + i);
i = 0; i = 0;

View File

@ -41,6 +41,10 @@ typedef struct gcache_item gcache_item;
class Renderer class Renderer
{ {
public: public:
Simulation * sim;
Graphics * g;
gcache_item *graphicscache;
std::vector<unsigned int> render_modes; std::vector<unsigned int> render_modes;
unsigned int render_mode; unsigned int render_mode;
unsigned int colour_mode; unsigned int colour_mode;
@ -60,9 +64,6 @@ public:
int decorations_enable; int decorations_enable;
bool blackDecorations; bool blackDecorations;
bool debugLines; bool debugLines;
Simulation * sim;
Graphics * g;
gcache_item *graphicscache;
pixel sampleColor; pixel sampleColor;
//Mouse position for debug information //Mouse position for debug information
@ -98,8 +99,8 @@ public:
void SetSample(int x, int y); void SetSample(int x, int y);
#ifdef OGLR #ifdef OGLR
void checkShader(GLuint shader, char * shname); void checkShader(GLuint shader, const char * shname);
void checkProgram(GLuint program, char * progname); void checkProgram(GLuint program, const char * progname);
void loadShaders(); void loadShaders();
GLuint vidBuf,textTexture; GLuint vidBuf,textTexture;
GLint prevFbo; GLint prevFbo;

View File

@ -39,14 +39,14 @@ std::string ConsoleController::FormatCommand(std::string command)
void ConsoleController::NextCommand() void ConsoleController::NextCommand()
{ {
int cIndex = consoleModel->GetCurrentCommandIndex(); size_t cIndex = consoleModel->GetCurrentCommandIndex();
if(cIndex < consoleModel->GetPreviousCommands().size()) if (cIndex < consoleModel->GetPreviousCommands().size())
consoleModel->SetCurrentCommandIndex(cIndex+1); consoleModel->SetCurrentCommandIndex(cIndex+1);
} }
void ConsoleController::PreviousCommand() void ConsoleController::PreviousCommand()
{ {
int cIndex = consoleModel->GetCurrentCommandIndex(); size_t cIndex = consoleModel->GetCurrentCommandIndex();
if(cIndex > 0) if(cIndex > 0)
consoleModel->SetCurrentCommandIndex(cIndex-1); consoleModel->SetCurrentCommandIndex(cIndex-1);
} }

View File

@ -19,12 +19,12 @@ void ConsoleModel::AddObserver(ConsoleView * observer)
observer->NotifyPreviousCommandsChanged(this); observer->NotifyPreviousCommandsChanged(this);
} }
int ConsoleModel::GetCurrentCommandIndex() size_t ConsoleModel::GetCurrentCommandIndex()
{ {
return currentCommandIndex; return currentCommandIndex;
} }
void ConsoleModel::SetCurrentCommandIndex(int index) void ConsoleModel::SetCurrentCommandIndex(size_t index)
{ {
currentCommandIndex = index; currentCommandIndex = index;
notifyCurrentCommandChanged(); notifyCurrentCommandChanged();
@ -55,7 +55,7 @@ std::deque<ConsoleCommand> ConsoleModel::GetPreviousCommands()
void ConsoleModel::notifyPreviousCommandsChanged() void ConsoleModel::notifyPreviousCommandsChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyPreviousCommandsChanged(this); observers[i]->NotifyPreviousCommandsChanged(this);
} }
@ -63,7 +63,7 @@ void ConsoleModel::notifyPreviousCommandsChanged()
void ConsoleModel::notifyCurrentCommandChanged() void ConsoleModel::notifyCurrentCommandChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyCurrentCommandChanged(this); observers[i]->NotifyCurrentCommandChanged(this);
} }

View File

@ -8,14 +8,14 @@
class ConsoleView; class ConsoleView;
class ConsoleModel { class ConsoleModel {
int currentCommandIndex; size_t currentCommandIndex;
std::vector<ConsoleView*> observers; std::vector<ConsoleView*> observers;
std::deque<ConsoleCommand> previousCommands; std::deque<ConsoleCommand> previousCommands;
void notifyPreviousCommandsChanged(); void notifyPreviousCommandsChanged();
void notifyCurrentCommandChanged(); void notifyCurrentCommandChanged();
public: public:
int GetCurrentCommandIndex(); size_t GetCurrentCommandIndex();
void SetCurrentCommandIndex(int index); void SetCurrentCommandIndex(size_t index);
ConsoleCommand GetCurrentCommand(); ConsoleCommand GetCurrentCommand();
std::deque<ConsoleCommand> GetPreviousCommands(); std::deque<ConsoleCommand> GetPreviousCommands();

View File

@ -55,7 +55,7 @@ void ConsoleView::DoKeyPress(int key, Uint16 character, bool shift, bool ctrl, b
void ConsoleView::NotifyPreviousCommandsChanged(ConsoleModel * sender) void ConsoleView::NotifyPreviousCommandsChanged(ConsoleModel * sender)
{ {
for(int i = 0; i < commandList.size(); i++) for (size_t i = 0; i < commandList.size(); i++)
{ {
RemoveComponent(commandList[i]); RemoveComponent(commandList[i]);
delete commandList[i]; delete commandList[i];

View File

@ -8,7 +8,6 @@ ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, ConfirmDial
ui::Window(ui::Point(-1, -1), ui::Point(250, 35)), ui::Window(ui::Point(-1, -1), ui::Point(250, 35)),
callback(callback_) callback(callback_)
{ {
int width, height;
ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title); ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title);
titleLabel->SetTextColour(style::Colour::WarningTitle); titleLabel->SetTextColour(style::Colour::WarningTitle);
titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -64,7 +63,6 @@ ConfirmPrompt::ConfirmPrompt(std::string title, std::string message, std::string
ui::Window(ui::Point(-1, -1), ui::Point(250, 50)), ui::Window(ui::Point(-1, -1), ui::Point(250, 50)),
callback(callback_) callback(callback_)
{ {
int width, height;
ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title); ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title);
titleLabel->SetTextColour(style::Colour::WarningTitle); titleLabel->SetTextColour(style::Colour::WarningTitle);
titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;

View File

@ -23,9 +23,9 @@ public:
ElementSearchActivity::ElementSearchActivity(GameController * gameController, std::vector<Tool*> tools) : ElementSearchActivity::ElementSearchActivity(GameController * gameController, std::vector<Tool*> tools) :
WindowActivity(ui::Point(-1, -1), ui::Point(236, 302)), WindowActivity(ui::Point(-1, -1), ui::Point(236, 302)),
firstResult(NULL),
gameController(gameController), gameController(gameController),
tools(tools), tools(tools),
firstResult(NULL),
exit(false) exit(false)
{ {
ui::Label * title = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), "Element Search"); ui::Label * title = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), "Element Search");

View File

@ -204,19 +204,19 @@ void FileBrowserActivity::RenameSave(SaveFile * file)
void FileBrowserActivity::loadDirectory(std::string directory, std::string search) void FileBrowserActivity::loadDirectory(std::string directory, std::string search)
{ {
for(int i = 0; i < components.size(); i++) for (size_t i = 0; i < components.size(); i++)
{ {
RemoveComponent(components[i]); RemoveComponent(components[i]);
itemList->RemoveChild(components[i]); itemList->RemoveChild(components[i]);
} }
for(std::vector<ui::Component*>::iterator iter = componentsQueue.begin(), end = componentsQueue.end(); iter != end; ++iter) for (std::vector<ui::Component*>::iterator iter = componentsQueue.begin(), end = componentsQueue.end(); iter != end; ++iter)
{ {
delete *iter; delete *iter;
} }
componentsQueue.clear(); componentsQueue.clear();
for(std::vector<SaveFile*>::iterator iter = files.begin(), end = files.end(); iter != end; ++iter) for (std::vector<SaveFile*>::iterator iter = files.begin(), end = files.end(); iter != end; ++iter)
{ {
delete *iter; delete *iter;
} }
@ -239,12 +239,12 @@ void FileBrowserActivity::NotifyDone(Task * task)
totalFiles = files.size(); totalFiles = files.size();
delete loadFiles; delete loadFiles;
loadFiles = NULL; loadFiles = NULL;
if(!files.size()) if (!files.size())
{ {
progressBar->Visible = false; progressBar->Visible = false;
infoText->Visible = true; infoText->Visible = true;
} }
for(int i = 0; i < components.size(); i++) for (size_t i = 0; i < components.size(); i++)
{ {
delete components[i]; delete components[i];
} }
@ -253,7 +253,7 @@ void FileBrowserActivity::NotifyDone(Task * task)
void FileBrowserActivity::OnMouseDown(int x, int y, unsigned button) void FileBrowserActivity::OnMouseDown(int x, int y, unsigned button)
{ {
if(!(x > Position.X && y > Position.Y && y < Position.Y+Size.Y && x < Position.X+Size.X)) //Clicked outside window if (!(x > Position.X && y > Position.Y && y < Position.Y+Size.Y && x < Position.X+Size.X)) //Clicked outside window
Exit(); Exit();
} }

View File

@ -3,7 +3,7 @@
void Brush::RenderRect(Renderer * ren, ui::Point position1, ui::Point position2) void Brush::RenderRect(Renderer * ren, ui::Point position1, ui::Point position2)
{ {
int width, height, t; int width, height;
width = position2.X-position1.X; width = position2.X-position1.X;
height = position2.Y-position1.Y; height = position2.Y-position1.Y;
if(height<0) if(height<0)

View File

@ -36,10 +36,10 @@ protected:
} }
public: public:
Brush(ui::Point size_): Brush(ui::Point size_):
bitmap(NULL),
outline(NULL), outline(NULL),
radius(0, 0), bitmap(NULL),
size(0, 0) size(0, 0),
radius(0, 0)
{ {
SetRadius(size_); SetRadius(size_);
}; };

View File

@ -11,7 +11,7 @@ public:
Brush(size_) Brush(size_)
{ {
SetRadius(size_); SetRadius(size_);
}; }
virtual void GenerateBitmap() virtual void GenerateBitmap()
{ {
if(bitmap) if(bitmap)
@ -29,7 +29,7 @@ public:
} }
else else
{ {
int yTop = ry+1, yBottom, i, j; int yTop = ry+1, yBottom, i;
for (i = 0; i <= rx; i++) for (i = 0; i <= rx; i++)
{ {
while (pow(i-rx,2.0)*pow(ry,2.0) + pow(yTop-ry,2.0)*pow(rx,2.0) <= pow(rx,2.0)*pow(ry,2.0)) while (pow(i-rx,2.0)*pow(ry,2.0) + pow(yTop-ry,2.0)*pow(rx,2.0) <= pow(rx,2.0)*pow(ry,2.0))

View File

@ -26,12 +26,14 @@
#include "gui/interface/Keys.h" #include "gui/interface/Keys.h"
#include "simulation/Snapshot.h" #include "simulation/Snapshot.h"
#include "debug/DebugInfo.h" #include "debug/DebugInfo.h"
#include "debug/DebugParts.h"
#include "debug/ElementPopulation.h"
#include "debug/DebugLines.h"
#ifdef LUACONSOLE #ifdef LUACONSOLE
#include "lua/LuaScriptInterface.h" #include "lua/LuaScriptInterface.h"
#else #else
#include "lua/TPTScriptInterface.h" #include "lua/TPTScriptInterface.h"
#endif #endif
//#include "debug/ElementPopulation.h"
using namespace std; using namespace std;
@ -109,26 +111,26 @@ public:
{ {
if(cc->localBrowser->GetSave()) if(cc->localBrowser->GetSave())
{ {
cc->gameModel->SetStamp(cc->localBrowser->GetSave()->GetGameSave());
if (cc->localBrowser->GetMoveToFront()) if (cc->localBrowser->GetMoveToFront())
Client::Ref().MoveStampToFront(cc->localBrowser->GetSave()->GetName()); Client::Ref().MoveStampToFront(cc->localBrowser->GetSave()->GetName());
cc->LoadStamp(); cc->LoadStamp(cc->localBrowser->GetSave()->GetGameSave());
} }
} }
}; };
GameController::GameController(): GameController::GameController():
firstTick(true),
foundSign(NULL),
activePreview(NULL),
search(NULL), search(NULL),
renderOptions(NULL), renderOptions(NULL),
loginWindow(NULL), loginWindow(NULL),
console(NULL), console(NULL),
tagsWindow(NULL), tagsWindow(NULL),
options(NULL),
activePreview(NULL),
localBrowser(NULL), localBrowser(NULL),
foundSign(NULL), options(NULL),
HasDone(false), debugFlags(0),
firstTick(true) HasDone(false)
{ {
gameView = new GameView(); gameView = new GameView();
gameModel = new GameModel(); gameModel = new GameModel();
@ -152,10 +154,11 @@ GameController::GameController():
ActiveToolChanged(2, gameModel->GetActiveTool(2)); ActiveToolChanged(2, gameModel->GetActiveTool(2));
ActiveToolChanged(3, gameModel->GetActiveTool(3)); ActiveToolChanged(3, gameModel->GetActiveTool(3));
//sim = new Simulation();
Client::Ref().AddListener(this); Client::Ref().AddListener(this);
//debugInfo.push_back(new ElementPopulationDebug(gameModel->GetSimulation())); debugInfo.push_back(new DebugParts(0x1, gameModel->GetSimulation()));
debugInfo.push_back(new ElementPopulationDebug(0x2, gameModel->GetSimulation()));
debugInfo.push_back(new DebugLines(0x4, gameView, this));
} }
GameController::~GameController() GameController::~GameController()
@ -376,6 +379,20 @@ void GameController::AdjustZoomSize(int direction, bool logarithmic)
gameModel->SetZoomFactor(newZoomFactor); gameModel->SetZoomFactor(newZoomFactor);
} }
bool GameController::MouseInZoom(ui::Point position)
{
if(position.X >= XRES)
position.X = XRES-1;
if(position.Y >= YRES)
position.Y = YRES-1;
if(position.Y < 0)
position.Y = 0;
if(position.X < 0)
position.X = 0;
return gameModel->MouseInZoom(position);
}
ui::Point GameController::PointTranslate(ui::Point point) ui::Point GameController::PointTranslate(ui::Point point)
{ {
if(point.X >= XRES) if(point.X >= XRES)
@ -483,9 +500,9 @@ void GameController::LoadClipboard()
gameModel->GetPlaceSave()->Expand(); gameModel->GetPlaceSave()->Expand();
} }
void GameController::LoadStamp() void GameController::LoadStamp(GameSave *stamp)
{ {
gameModel->SetPlaceSave(gameModel->GetStamp()); gameModel->SetPlaceSave(stamp);
if(gameModel->GetPlaceSave() && gameModel->GetPlaceSave()->Collapsed()) if(gameModel->GetPlaceSave() && gameModel->GetPlaceSave()->Collapsed())
gameModel->GetPlaceSave()->Expand(); gameModel->GetPlaceSave()->Expand();
} }
@ -522,7 +539,7 @@ std::string GameController::StampRegion(ui::Point point1, ui::Point point2)
if(newSave) if(newSave)
{ {
newSave->paused = gameModel->GetPaused(); newSave->paused = gameModel->GetPaused();
return gameModel->AddStamp(newSave); return Client::Ref().AddStamp(newSave);
} }
else else
{ {
@ -566,7 +583,7 @@ bool GameController::MouseDown(int x, int y, unsigned button)
ui::Point point = gameModel->AdjustZoomCoords(ui::Point(x, y)); ui::Point point = gameModel->AdjustZoomCoords(ui::Point(x, y));
x = point.X; x = point.X;
y = point.Y; y = point.Y;
if (gameModel->GetActiveTool(0) && gameModel->GetActiveTool(0)->GetIdentifier() != "DEFAULT_UI_SIGN" || button != BUTTON_LEFT) //If it's not a sign tool or you are right/middle clicking if (!gameModel->GetActiveTool(0) || gameModel->GetActiveTool(0)->GetIdentifier() != "DEFAULT_UI_SIGN" || button != BUTTON_LEFT) //If it's not a sign tool or you are right/middle clicking
{ {
foundSign = GetSignAt(x, y); foundSign = GetSignAt(x, y);
if(foundSign && splitsign(foundSign->text.c_str())) if(foundSign && splitsign(foundSign->text.c_str()))
@ -584,7 +601,7 @@ bool GameController::MouseUp(int x, int y, unsigned button)
ui::Point point = gameModel->AdjustZoomCoords(ui::Point(x, y)); ui::Point point = gameModel->AdjustZoomCoords(ui::Point(x, y));
x = point.X; x = point.X;
y = point.Y; y = point.Y;
if (gameModel->GetActiveTool(0) && gameModel->GetActiveTool(0)->GetIdentifier() != "DEFAULT_UI_SIGN" || button != BUTTON_LEFT) //If it's not a sign tool or you are right/middle clicking if (!gameModel->GetActiveTool(0) || gameModel->GetActiveTool(0)->GetIdentifier() != "DEFAULT_UI_SIGN" || button != BUTTON_LEFT) //If it's not a sign tool or you are right/middle clicking
{ {
sign * foundSign = GetSignAt(x, y); sign * foundSign = GetSignAt(x, y);
if(foundSign) { if(foundSign) {
@ -723,6 +740,11 @@ bool GameController::KeyRelease(int key, Uint16 character, bool shift, bool ctrl
return ret; return ret;
} }
bool GameController::MouseTick()
{
return commandInterface->OnMouseTick();
}
void GameController::Tick() void GameController::Tick()
{ {
if(firstTick) if(firstTick)
@ -731,9 +753,8 @@ void GameController::Tick()
((LuaScriptInterface*)commandInterface)->Init(); ((LuaScriptInterface*)commandInterface)->Init();
#endif #endif
#if !defined(MACOSX) && !defined(NO_INSTALL_CHECK) #if !defined(MACOSX) && !defined(NO_INSTALL_CHECK)
if(!Client::Ref().GetPrefBool("InstallCheck", false)) if (Client::Ref().IsFirstRun())
{ {
Client::Ref().SetPref("InstallCheck", true);
Install(); Install();
} }
#endif #endif
@ -741,7 +762,8 @@ void GameController::Tick()
} }
for(std::vector<DebugInfo*>::iterator iter = debugInfo.begin(), end = debugInfo.end(); iter != end; iter++) for(std::vector<DebugInfo*>::iterator iter = debugInfo.begin(), end = debugInfo.end(); iter != end; iter++)
{ {
(*iter)->Draw(ui::Point(10, 10)); if ((*iter)->ID & debugFlags)
(*iter)->Draw();
} }
commandInterface->OnTick(); commandInterface->OnTick();
} }
@ -859,7 +881,9 @@ void GameController::Update()
gameView->SetSample(gameModel->GetSimulation()->GetSample(pos.X, pos.Y)); gameView->SetSample(gameModel->GetSimulation()->GetSample(pos.X, pos.Y));
Simulation * sim = gameModel->GetSimulation(); Simulation * sim = gameModel->GetSimulation();
sim->update_particles(); sim->UpdateSim();
if (!sim->sys_pause || sim->framerender)
sim->UpdateParticles(0, NPART);
//if either STKM or STK2 isn't out, reset it's selected element. Defaults to PT_DUST unless right selected is something else //if either STKM or STK2 isn't out, reset it's selected element. Defaults to PT_DUST unless right selected is something else
//This won't run if the stickmen dies in a frame, since it respawns instantly //This won't run if the stickmen dies in a frame, since it respawns instantly
@ -1060,19 +1084,15 @@ void GameController::OpenLocalSaveWindow(bool asCurrent)
{ {
Simulation * sim = gameModel->GetSimulation(); Simulation * sim = gameModel->GetSimulation();
GameSave * gameSave = sim->Save(); GameSave * gameSave = sim->Save();
gameSave->paused = gameModel->GetPaused();
gameSave->gravityMode = sim->gravityMode;
gameSave->airMode = sim->air->airMode;
gameSave->legacyEnable = sim->legacy_enable;
gameSave->waterEEnabled = sim->water_equal_test;
gameSave->gravityEnable = sim->grav->ngrav_enable;
gameSave->aheatEnable = sim->aheat_enable;
if(!gameSave) if(!gameSave)
{ {
new ErrorMessage("Error", "Unable to build save."); new ErrorMessage("Error", "Unable to build save.");
} }
else else
{ {
sim->SaveSimOptions(gameSave);
gameSave->paused = gameModel->GetPaused();
std::string filename = ""; std::string filename = "";
if (gameModel->GetSaveFile()) if (gameModel->GetSaveFile())
filename = gameModel->GetSaveFile()->GetDisplayName(); filename = gameModel->GetSaveFile()->GetDisplayName();
@ -1268,19 +1288,15 @@ void GameController::OpenSaveWindow()
{ {
Simulation * sim = gameModel->GetSimulation(); Simulation * sim = gameModel->GetSimulation();
GameSave * gameSave = sim->Save(); GameSave * gameSave = sim->Save();
gameSave->paused = gameModel->GetPaused();
gameSave->gravityMode = sim->gravityMode;
gameSave->airMode = sim->air->airMode;
gameSave->legacyEnable = sim->legacy_enable;
gameSave->waterEEnabled = sim->water_equal_test;
gameSave->gravityEnable = sim->grav->ngrav_enable;
gameSave->aheatEnable = sim->aheat_enable;
if(!gameSave) if(!gameSave)
{ {
new ErrorMessage("Error", "Unable to build save."); new ErrorMessage("Error", "Unable to build save.");
} }
else else
{ {
sim->SaveSimOptions(gameSave);
gameSave->paused = gameModel->GetPaused();
if(gameModel->GetSave()) if(gameModel->GetSave())
{ {
SaveInfo tempSave(*gameModel->GetSave()); SaveInfo tempSave(*gameModel->GetSave());
@ -1320,19 +1336,15 @@ void GameController::SaveAsCurrent()
{ {
Simulation * sim = gameModel->GetSimulation(); Simulation * sim = gameModel->GetSimulation();
GameSave * gameSave = sim->Save(); GameSave * gameSave = sim->Save();
gameSave->paused = gameModel->GetPaused();
gameSave->gravityMode = sim->gravityMode;
gameSave->airMode = sim->air->airMode;
gameSave->legacyEnable = sim->legacy_enable;
gameSave->waterEEnabled = sim->water_equal_test;
gameSave->gravityEnable = sim->grav->ngrav_enable;
gameSave->aheatEnable = sim->aheat_enable;
if(!gameSave) if(!gameSave)
{ {
new ErrorMessage("Error", "Unable to build save."); new ErrorMessage("Error", "Unable to build save.");
} }
else else
{ {
gameSave->paused = gameModel->GetPaused();
sim->SaveSimOptions(gameSave);
if(gameModel->GetSave()) if(gameModel->GetSave())
{ {
SaveInfo tempSave(*gameModel->GetSave()); SaveInfo tempSave(*gameModel->GetSave());
@ -1402,6 +1414,51 @@ void GameController::ReloadSim()
} }
} }
#ifdef PARTICLEDEBUG
void GameController::ParticleDebug(int mode, int x, int y)
{
Simulation *sim = gameModel->GetSimulation();
int debug_currentParticle = sim->debug_currentParticle;
int i;
std::stringstream logmessage;
if (mode == 0)
{
if (!sim->NUM_PARTS)
return;
i = debug_currentParticle;
while (i < NPART && !sim->parts[i].type)
i++;
if (i == NPART)
logmessage << "End of particles reached, updated sim";
else
logmessage << "Updated particle #" << i;
}
else if (mode == 1)
{
if (x < 0 || x >= XRES || y < 0 || y >= YRES || !(i = (sim->pmap[y][x]>>8)) || i < debug_currentParticle)
{
i = NPART;
logmessage << "Updated particles from #" << debug_currentParticle << " to end, updated sim";
}
else
logmessage << "Updated particles #" << debug_currentParticle << " through #" << i;
}
gameModel->Log(logmessage.str());
sim->UpdateParticles(debug_currentParticle, i);
if (i < NPART-1)
sim->debug_currentParticle = i+1;
else
{
sim->framerender = 1;
sim->UpdateSim();
sim->framerender = 0;
sim->debug_currentParticle = 0;
}
}
#endif
std::string GameController::ElementResolve(int type, int ctype) std::string GameController::ElementResolve(int type, int ctype)
{ {
if(gameModel && gameModel->GetSimulation()) if(gameModel && gameModel->GetSimulation())
@ -1418,7 +1475,7 @@ bool GameController::IsValidElement(int type)
{ {
if(gameModel && gameModel->GetSimulation()) if(gameModel && gameModel->GetSimulation())
{ {
return (type > 0 && type < PT_NUM && gameModel->GetSimulation()->elements[type].Enabled); return (type && gameModel->GetSimulation()->IsValidElement(type));
} }
else else
return false; return false;
@ -1444,7 +1501,7 @@ void GameController::NotifyNewNotification(Client * sender, std::pair<std::strin
{ {
std::string link; std::string link;
public: public:
LinkNotification(std::string link_, std::string message) : link(link_), Notification(message) {} LinkNotification(std::string link_, std::string message) : Notification(message), link(link_) {}
virtual ~LinkNotification() {} virtual ~LinkNotification() {}
virtual void Action() virtual void Action()
@ -1474,7 +1531,7 @@ void GameController::NotifyUpdateAvailable(Client * sender)
{ {
GameController * c; GameController * c;
public: public:
UpdateNotification(GameController * c, std::string message) : c(c), Notification(message) {} UpdateNotification(GameController * c, std::string message) : Notification(message), c(c) {}
virtual ~UpdateNotification() {} virtual ~UpdateNotification() {}
virtual void Action() virtual void Action()

View File

@ -29,9 +29,7 @@ class ConsoleController;
class GameController: public ClientListener class GameController: public ClientListener
{ {
private: private:
//Simulation * sim;
bool firstTick; bool firstTick;
int screenshotIndex;
sign * foundSign; sign * foundSign;
PreviewController * activePreview; PreviewController * activePreview;
@ -46,6 +44,7 @@ private:
OptionsController * options; OptionsController * options;
CommandInterface * commandInterface; CommandInterface * commandInterface;
vector<DebugInfo*> debugInfo; vector<DebugInfo*> debugInfo;
unsigned int debugFlags;
public: public:
bool HasDone; bool HasDone;
class SearchCallback; class SearchCallback;
@ -67,6 +66,7 @@ public:
bool MouseWheel(int x, int y, int d); bool MouseWheel(int x, int y, int d);
bool KeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt); bool KeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt);
bool KeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt); bool KeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt);
bool MouseTick();
void Tick(); void Tick();
void Exit(); void Exit();
@ -101,6 +101,7 @@ public:
bool GetHudEnable(); bool GetHudEnable();
void SetDebugHUD(bool hudState); void SetDebugHUD(bool hudState);
bool GetDebugHUD(); bool GetDebugHUD();
void SetDebugFlags(unsigned int flags) { debugFlags = flags; }
void SetActiveMenu(int menuID); void SetActiveMenu(int menuID);
std::vector<Menu*> GetMenuList(); std::vector<Menu*> GetMenuList();
Tool * GetActiveTool(int selection); Tool * GetActiveTool(int selection);
@ -131,6 +132,9 @@ public:
void PlaceSave(ui::Point position); void PlaceSave(ui::Point position);
void ClearSim(); void ClearSim();
void ReloadSim(); void ReloadSim();
#ifdef PARTICLEDEBUG
void ParticleDebug(int mode, int x, int y);
#endif
void Vote(int direction); void Vote(int direction);
void ChangeBrush(); void ChangeBrush();
void ShowConsole(); void ShowConsole();
@ -138,6 +142,7 @@ public:
void FrameStep(); void FrameStep();
void TranslateSave(ui::Point point); void TranslateSave(ui::Point point);
void TransformSave(matrix2d transform); void TransformSave(matrix2d transform);
bool MouseInZoom(ui::Point position);
ui::Point PointTranslate(ui::Point point); ui::Point PointTranslate(ui::Point point);
ui::Point NormaliseBlockCoord(ui::Point point); ui::Point NormaliseBlockCoord(ui::Point point);
std::string ElementResolve(int type, int ctype); std::string ElementResolve(int type, int ctype);
@ -152,7 +157,7 @@ public:
void ToggleNewtonianGravity(); void ToggleNewtonianGravity();
void LoadClipboard(); void LoadClipboard();
void LoadStamp(); void LoadStamp(GameSave *stamp);
void RemoveNotification(Notification * notification); void RemoveNotification(Notification * notification);

View File

@ -12,26 +12,24 @@
#include "BitmapBrush.h" #include "BitmapBrush.h"
#include "client/Client.h" #include "client/Client.h"
#include "client/GameSave.h" #include "client/GameSave.h"
#include "client/SaveFile.h"
#include "gui/game/DecorationTool.h" #include "gui/game/DecorationTool.h"
#include "QuickOptions.h" #include "QuickOptions.h"
#include "GameModelException.h" #include "GameModelException.h"
#include "Format.h" #include "Format.h"
GameModel::GameModel(): GameModel::GameModel():
sim(NULL), clipboard(NULL),
ren(NULL), placeSave(NULL),
activeMenu(-1),
currentBrush(0), currentBrush(0),
currentUser(0, ""),
currentSave(NULL), currentSave(NULL),
currentFile(NULL), currentFile(NULL),
colourSelector(false), currentUser(0, ""),
clipboard(NULL),
stamp(NULL),
placeSave(NULL),
colour(255, 0, 0, 255),
toolStrength(1.0f), toolStrength(1.0f),
activeColourPreset(-1), activeColourPreset(0),
activeMenu(-1), colourSelector(false),
colour(255, 0, 0, 255),
edgeMode(0) edgeMode(0)
{ {
sim = new Simulation(); sim = new Simulation();
@ -95,15 +93,6 @@ GameModel::GameModel():
currentUser = Client::Ref().GetAuthUser(); currentUser = Client::Ref().GetAuthUser();
} }
//Set stamp to first stamp in list
vector<string> stamps = Client::Ref().GetStamps(0, 1);
if(stamps.size()>0)
{
SaveFile * stampFile = Client::Ref().GetStamp(stamps[0]);
if(stampFile && stampFile->GetGameSave())
stamp = stampFile->GetGameSave();
}
BuildMenus(); BuildMenus();
//Set default brush palette //Set default brush palette
@ -113,7 +102,7 @@ GameModel::GameModel():
//Load more from brushes folder //Load more from brushes folder
std::vector<string> brushFiles = Client::Ref().DirectorySearch(BRUSH_DIR, "", ".ptb"); std::vector<string> brushFiles = Client::Ref().DirectorySearch(BRUSH_DIR, "", ".ptb");
for(int i = 0; i < brushFiles.size(); i++) for (size_t i = 0; i < brushFiles.size(); i++)
{ {
std::vector<unsigned char> brushData = Client::Ref().ReadFile(brushFiles[i]); std::vector<unsigned char> brushData = Client::Ref().ReadFile(brushFiles[i]);
if(!brushData.size()) if(!brushData.size())
@ -121,8 +110,8 @@ GameModel::GameModel():
std::cout << "Brushes: Skipping " << brushFiles[i] << ". Could not open" << std::endl; std::cout << "Brushes: Skipping " << brushFiles[i] << ". Could not open" << std::endl;
continue; continue;
} }
int dimension = std::sqrt((float)brushData.size()); size_t dimension = std::sqrt((float)brushData.size());
if(dimension * dimension != brushData.size()) if (dimension * dimension != brushData.size())
{ {
std::cout << "Brushes: Skipping " << brushFiles[i] << ". Invalid bitmap size" << std::endl; std::cout << "Brushes: Skipping " << brushFiles[i] << ". Invalid bitmap size" << std::endl;
continue; continue;
@ -173,15 +162,15 @@ GameModel::~GameModel()
Client::Ref().SetPref("Decoration.Blue", (int)colour.Blue); Client::Ref().SetPref("Decoration.Blue", (int)colour.Blue);
Client::Ref().SetPref("Decoration.Alpha", (int)colour.Alpha); Client::Ref().SetPref("Decoration.Alpha", (int)colour.Alpha);
for(int i = 0; i < menuList.size(); i++) for (size_t i = 0; i < menuList.size(); i++)
{ {
delete menuList[i]; delete menuList[i];
} }
for(std::vector<Tool*>::iterator iter = extraElementTools.begin(), end = extraElementTools.end(); iter != end; ++iter) for (std::vector<Tool*>::iterator iter = extraElementTools.begin(), end = extraElementTools.end(); iter != end; ++iter)
{ {
delete *iter; delete *iter;
} }
for(int i = 0; i < brushList.size(); i++) for (size_t i = 0; i < brushList.size(); i++)
{ {
delete brushList[i]; delete brushList[i];
} }
@ -191,8 +180,6 @@ GameModel::~GameModel()
delete placeSave; delete placeSave;
if(clipboard) if(clipboard)
delete clipboard; delete clipboard;
if(stamp)
delete stamp;
if(currentSave) if(currentSave)
delete currentSave; delete currentSave;
if(currentFile) if(currentFile)
@ -289,7 +276,7 @@ void GameModel::BuildMenus()
tempTool = new ElementTool(i, sim->elements[i].Name, sim->elements[i].Description, PIXR(sim->elements[i].Colour), PIXG(sim->elements[i].Colour), PIXB(sim->elements[i].Colour), sim->elements[i].Identifier, sim->elements[i].IconGenerator); tempTool = new ElementTool(i, sim->elements[i].Name, sim->elements[i].Description, PIXR(sim->elements[i].Colour), PIXG(sim->elements[i].Colour), PIXB(sim->elements[i].Colour), sim->elements[i].Identifier, sim->elements[i].IconGenerator);
} }
if(sim->elements[i].MenuSection < SC_TOTAL && sim->elements[i].MenuVisible) if (sim->elements[i].MenuSection >= 0 && sim->elements[i].MenuSection < SC_TOTAL && sim->elements[i].MenuVisible)
{ {
menuList[sim->elements[i].MenuSection]->AddTool(tempTool); menuList[sim->elements[i].MenuSection]->AddTool(tempTool);
} }
@ -317,7 +304,7 @@ void GameModel::BuildMenus()
} }
//Build menu for tools //Build menu for tools
for(int i = 0; i < sim->tools.size(); i++) for (size_t i = 0; i < sim->tools.size(); i++)
{ {
Tool * tempTool; Tool * tempTool;
tempTool = new Tool(i, sim->tools[i]->Name, sim->tools[i]->Description, PIXR(sim->tools[i]->Colour), PIXG(sim->tools[i]->Colour), PIXB(sim->tools[i]->Colour), sim->tools[i]->Identifier); tempTool = new Tool(i, sim->tools[i]->Name, sim->tools[i]->Description, PIXR(sim->tools[i]->Colour), PIXG(sim->tools[i]->Colour), PIXB(sim->tools[i]->Colour), sim->tools[i]->Identifier);
@ -586,6 +573,7 @@ void GameModel::SetSave(SaveInfo * newSave)
SetPaused(saveData->paused | GetPaused()); SetPaused(saveData->paused | GetPaused());
sim->gravityMode = saveData->gravityMode; sim->gravityMode = saveData->gravityMode;
sim->air->airMode = saveData->airMode; sim->air->airMode = saveData->airMode;
sim->edgeMode = saveData->edgeMode;
sim->legacy_enable = saveData->legacyEnable; sim->legacy_enable = saveData->legacyEnable;
sim->water_equal_test = saveData->waterEEnabled; sim->water_equal_test = saveData->waterEEnabled;
sim->aheat_enable = saveData->aheatEnable; sim->aheat_enable = saveData->aheatEnable;
@ -628,6 +616,7 @@ void GameModel::SetSaveFile(SaveFile * newSave)
SetPaused(saveData->paused | GetPaused()); SetPaused(saveData->paused | GetPaused());
sim->gravityMode = saveData->gravityMode; sim->gravityMode = saveData->gravityMode;
sim->air->airMode = saveData->airMode; sim->air->airMode = saveData->airMode;
sim->edgeMode = saveData->edgeMode;
sim->legacy_enable = saveData->legacyEnable; sim->legacy_enable = saveData->legacyEnable;
sim->water_equal_test = saveData->waterEEnabled; sim->water_equal_test = saveData->waterEEnabled;
sim->aheat_enable = saveData->aheatEnable; sim->aheat_enable = saveData->aheatEnable;
@ -700,6 +689,20 @@ ui::Point GameModel::GetZoomPosition()
return ren->zoomScopePosition; return ren->zoomScopePosition;
} }
bool GameModel::MouseInZoom(ui::Point position)
{
if (!GetZoomEnabled())
return false;
int zoomFactor = GetZoomFactor();
ui::Point zoomWindowPosition = GetZoomWindowPosition();
ui::Point zoomWindowSize = ui::Point(GetZoomSize()*zoomFactor, GetZoomSize()*zoomFactor);
if (position.X >= zoomWindowPosition.X && position.X >= zoomWindowPosition.Y && position.X <= zoomWindowPosition.X+zoomWindowSize.X && position.Y <= zoomWindowPosition.Y+zoomWindowSize.Y)
return true;
return false;
}
ui::Point GameModel::AdjustZoomCoords(ui::Point position) ui::Point GameModel::AdjustZoomCoords(ui::Point position)
{ {
if (!GetZoomEnabled()) if (!GetZoomEnabled())
@ -747,10 +750,10 @@ int GameModel::GetZoomFactor()
return ren->ZFACTOR; return ren->ZFACTOR;
} }
void GameModel::SetActiveColourPreset(int preset) void GameModel::SetActiveColourPreset(size_t preset)
{ {
if (activeColourPreset != preset) if (activeColourPreset-1 != preset)
activeColourPreset = preset; activeColourPreset = preset+1;
else else
{ {
activeTools[0] = GetToolFromIdentifier("DEFAULT_DECOR_SET"); activeTools[0] = GetToolFromIdentifier("DEFAULT_DECOR_SET");
@ -759,16 +762,16 @@ void GameModel::SetActiveColourPreset(int preset)
notifyColourActivePresetChanged(); notifyColourActivePresetChanged();
} }
int GameModel::GetActiveColourPreset() size_t GameModel::GetActiveColourPreset()
{ {
return activeColourPreset; return activeColourPreset-1;
} }
void GameModel::SetPresetColour(ui::Colour colour) void GameModel::SetPresetColour(ui::Colour colour)
{ {
if(activeColourPreset >= 0 && activeColourPreset < colourPresets.size()) if (activeColourPreset > 0 && activeColourPreset <= colourPresets.size())
{ {
colourPresets[activeColourPreset] = colour; colourPresets[activeColourPreset-1] = colour;
notifyColourPresetsChanged(); notifyColourPresetsChanged();
} }
} }
@ -797,7 +800,7 @@ void GameModel::SetColourSelectorColour(ui::Colour colour_)
colour = colour_; colour = colour_;
vector<Tool*> tools = GetMenuList()[SC_DECO]->GetToolList(); vector<Tool*> tools = GetMenuList()[SC_DECO]->GetToolList();
for(int i = 0; i < tools.size(); i++) for (size_t i = 0; i < tools.size(); i++)
{ {
((DecorationTool*)tools[i])->Red = colour.Red; ((DecorationTool*)tools[i])->Red = colour.Red;
((DecorationTool*)tools[i])->Green = colour.Green; ((DecorationTool*)tools[i])->Green = colour.Green;
@ -833,7 +836,7 @@ bool GameModel::GetPaused()
void GameModel::SetDecoration(bool decorationState) void GameModel::SetDecoration(bool decorationState)
{ {
if (ren->decorations_enable != decorationState) if (ren->decorations_enable != (decorationState?1:0))
{ {
ren->decorations_enable = decorationState?1:0; ren->decorations_enable = decorationState?1:0;
notifyDecorationChanged(); notifyDecorationChanged();
@ -900,19 +903,6 @@ void GameModel::ClearSimulation()
UpdateQuickOptions(); UpdateQuickOptions();
} }
void GameModel::SetStamp(GameSave * save)
{
if(stamp != save)
{
if(stamp)
delete stamp;
if(save)
stamp = new GameSave(*save);
else
stamp = NULL;
}
}
void GameModel::SetPlaceSave(GameSave * save) void GameModel::SetPlaceSave(GameSave * save)
{ {
if(save != placeSave) if(save != placeSave)
@ -927,14 +917,6 @@ void GameModel::SetPlaceSave(GameSave * save)
notifyPlaceSaveChanged(); notifyPlaceSaveChanged();
} }
std::string GameModel::AddStamp(GameSave * save)
{
if(stamp)
delete stamp;
stamp = save;
return Client::Ref().AddStamp(save);
}
void GameModel::SetClipboard(GameSave * save) void GameModel::SetClipboard(GameSave * save)
{ {
if(clipboard) if(clipboard)
@ -952,11 +934,6 @@ GameSave * GameModel::GetPlaceSave()
return placeSave; return placeSave;
} }
GameSave * GameModel::GetStamp()
{
return stamp;
}
void GameModel::Log(string message) void GameModel::Log(string message)
{ {
consoleLog.push_front(message); consoleLog.push_front(message);
@ -1020,7 +997,7 @@ std::string GameModel::GetInfoTip()
void GameModel::notifyNotificationsChanged() void GameModel::notifyNotificationsChanged()
{ {
for(std::vector<GameView*>::iterator iter = observers.begin(); iter != observers.end(); ++iter) for (std::vector<GameView*>::iterator iter = observers.begin(); iter != observers.end(); ++iter)
{ {
(*iter)->NotifyNotificationsChanged(this); (*iter)->NotifyNotificationsChanged(this);
} }
@ -1028,7 +1005,7 @@ void GameModel::notifyNotificationsChanged()
void GameModel::notifyColourPresetsChanged() void GameModel::notifyColourPresetsChanged()
{ {
for(std::vector<GameView*>::iterator iter = observers.begin(); iter != observers.end(); ++iter) for (std::vector<GameView*>::iterator iter = observers.begin(); iter != observers.end(); ++iter)
{ {
(*iter)->NotifyColourPresetsChanged(this); (*iter)->NotifyColourPresetsChanged(this);
} }
@ -1036,7 +1013,7 @@ void GameModel::notifyColourPresetsChanged()
void GameModel::notifyColourActivePresetChanged() void GameModel::notifyColourActivePresetChanged()
{ {
for(std::vector<GameView*>::iterator iter = observers.begin(); iter != observers.end(); ++iter) for (std::vector<GameView*>::iterator iter = observers.begin(); iter != observers.end(); ++iter)
{ {
(*iter)->NotifyColourActivePresetChanged(this); (*iter)->NotifyColourActivePresetChanged(this);
} }
@ -1044,7 +1021,7 @@ void GameModel::notifyColourActivePresetChanged()
void GameModel::notifyColourSelectorColourChanged() void GameModel::notifyColourSelectorColourChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyColourSelectorColourChanged(this); observers[i]->NotifyColourSelectorColourChanged(this);
} }
@ -1052,7 +1029,7 @@ void GameModel::notifyColourSelectorColourChanged()
void GameModel::notifyColourSelectorVisibilityChanged() void GameModel::notifyColourSelectorVisibilityChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyColourSelectorVisibilityChanged(this); observers[i]->NotifyColourSelectorVisibilityChanged(this);
} }
@ -1060,7 +1037,7 @@ void GameModel::notifyColourSelectorVisibilityChanged()
void GameModel::notifyRendererChanged() void GameModel::notifyRendererChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyRendererChanged(this); observers[i]->NotifyRendererChanged(this);
} }
@ -1068,7 +1045,7 @@ void GameModel::notifyRendererChanged()
void GameModel::notifySaveChanged() void GameModel::notifySaveChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifySaveChanged(this); observers[i]->NotifySaveChanged(this);
} }
@ -1076,7 +1053,7 @@ void GameModel::notifySaveChanged()
void GameModel::notifySimulationChanged() void GameModel::notifySimulationChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifySimulationChanged(this); observers[i]->NotifySimulationChanged(this);
} }
@ -1084,7 +1061,7 @@ void GameModel::notifySimulationChanged()
void GameModel::notifyPausedChanged() void GameModel::notifyPausedChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyPausedChanged(this); observers[i]->NotifyPausedChanged(this);
} }
@ -1092,7 +1069,7 @@ void GameModel::notifyPausedChanged()
void GameModel::notifyDecorationChanged() void GameModel::notifyDecorationChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
//observers[i]->NotifyPausedChanged(this); //observers[i]->NotifyPausedChanged(this);
} }
@ -1100,7 +1077,7 @@ void GameModel::notifyDecorationChanged()
void GameModel::notifyBrushChanged() void GameModel::notifyBrushChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyBrushChanged(this); observers[i]->NotifyBrushChanged(this);
} }
@ -1108,7 +1085,7 @@ void GameModel::notifyBrushChanged()
void GameModel::notifyMenuListChanged() void GameModel::notifyMenuListChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyMenuListChanged(this); observers[i]->NotifyMenuListChanged(this);
} }
@ -1116,7 +1093,7 @@ void GameModel::notifyMenuListChanged()
void GameModel::notifyToolListChanged() void GameModel::notifyToolListChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyToolListChanged(this); observers[i]->NotifyToolListChanged(this);
} }
@ -1124,7 +1101,7 @@ void GameModel::notifyToolListChanged()
void GameModel::notifyActiveToolsChanged() void GameModel::notifyActiveToolsChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyActiveToolsChanged(this); observers[i]->NotifyActiveToolsChanged(this);
} }
@ -1132,7 +1109,7 @@ void GameModel::notifyActiveToolsChanged()
void GameModel::notifyUserChanged() void GameModel::notifyUserChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyUserChanged(this); observers[i]->NotifyUserChanged(this);
} }
@ -1140,7 +1117,7 @@ void GameModel::notifyUserChanged()
void GameModel::notifyZoomChanged() void GameModel::notifyZoomChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyZoomChanged(this); observers[i]->NotifyZoomChanged(this);
} }
@ -1148,7 +1125,7 @@ void GameModel::notifyZoomChanged()
void GameModel::notifyPlaceSaveChanged() void GameModel::notifyPlaceSaveChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyPlaceSaveChanged(this); observers[i]->NotifyPlaceSaveChanged(this);
} }
@ -1156,7 +1133,7 @@ void GameModel::notifyPlaceSaveChanged()
void GameModel::notifyLogChanged(string entry) void GameModel::notifyLogChanged(string entry)
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyLogChanged(this, entry); observers[i]->NotifyLogChanged(this, entry);
} }
@ -1164,7 +1141,7 @@ void GameModel::notifyLogChanged(string entry)
void GameModel::notifyInfoTipChanged() void GameModel::notifyInfoTipChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyInfoTipChanged(this); observers[i]->NotifyInfoTipChanged(this);
} }
@ -1172,7 +1149,7 @@ void GameModel::notifyInfoTipChanged()
void GameModel::notifyToolTipChanged() void GameModel::notifyToolTipChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyToolTipChanged(this); observers[i]->NotifyToolTipChanged(this);
} }
@ -1180,7 +1157,7 @@ void GameModel::notifyToolTipChanged()
void GameModel::notifyQuickOptionsChanged() void GameModel::notifyQuickOptionsChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyQuickOptionsChanged(this); observers[i]->NotifyQuickOptionsChanged(this);
} }
@ -1188,7 +1165,7 @@ void GameModel::notifyQuickOptionsChanged()
void GameModel::notifyLastToolChanged() void GameModel::notifyLastToolChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyLastToolChanged(this); observers[i]->NotifyLastToolChanged(this);
} }

View File

@ -38,7 +38,6 @@ private:
vector<Notification*> notifications; vector<Notification*> notifications;
//int clipboardSize; //int clipboardSize;
//unsigned char * clipboardData; //unsigned char * clipboardData;
GameSave * stamp;
GameSave * clipboard; GameSave * clipboard;
GameSave * placeSave; GameSave * placeSave;
deque<string> consoleLog; deque<string> consoleLog;
@ -50,6 +49,8 @@ private:
//Tools that are present in elementTools, but don't have an associated menu and need to be freed manually //Tools that are present in elementTools, but don't have an associated menu and need to be freed manually
vector<Tool*> extraElementTools; vector<Tool*> extraElementTools;
Simulation * sim;
Renderer * ren;
vector<Menu*> menuList; vector<Menu*> menuList;
vector<QuickOption*> quickOptions; vector<QuickOption*> quickOptions;
int activeMenu; int activeMenu;
@ -57,8 +58,6 @@ private:
vector<Brush *> brushList; vector<Brush *> brushList;
SaveInfo * currentSave; SaveInfo * currentSave;
SaveFile * currentFile; SaveFile * currentFile;
Simulation * sim;
Renderer * ren;
Tool * lastTool; Tool * lastTool;
Tool ** activeTools; Tool ** activeTools;
Tool * decoToolset[4]; Tool * decoToolset[4];
@ -67,7 +66,7 @@ private:
float toolStrength; float toolStrength;
std::deque<Snapshot*> history; std::deque<Snapshot*> history;
int activeColourPreset; size_t activeColourPreset;
std::vector<ui::Colour> colourPresets; std::vector<ui::Colour> colourPresets;
bool colourSelector; bool colourSelector;
ui::Colour colour; ui::Colour colour;
@ -107,8 +106,8 @@ public:
void SetEdgeMode(int edgeMode); void SetEdgeMode(int edgeMode);
int GetEdgeMode(); int GetEdgeMode();
void SetActiveColourPreset(int preset); void SetActiveColourPreset(size_t preset);
int GetActiveColourPreset(); size_t GetActiveColourPreset();
void SetPresetColour(ui::Colour colour); void SetPresetColour(ui::Colour colour);
@ -182,17 +181,15 @@ public:
int GetZoomFactor(); int GetZoomFactor();
void SetZoomPosition(ui::Point position); void SetZoomPosition(ui::Point position);
ui::Point GetZoomPosition(); ui::Point GetZoomPosition();
bool MouseInZoom(ui::Point position);
ui::Point AdjustZoomCoords(ui::Point position); ui::Point AdjustZoomCoords(ui::Point position);
void SetZoomWindowPosition(ui::Point position); void SetZoomWindowPosition(ui::Point position);
ui::Point GetZoomWindowPosition(); ui::Point GetZoomWindowPosition();
void SetStamp(GameSave * newStamp);
std::string AddStamp(GameSave * save);
void SetClipboard(GameSave * save); void SetClipboard(GameSave * save);
void SetPlaceSave(GameSave * save); void SetPlaceSave(GameSave * save);
void Log(string message); void Log(string message);
deque<string> GetLog(); deque<string> GetLog();
GameSave * GetClipboard(); GameSave * GetClipboard();
GameSave * GetStamp();
GameSave * GetPlaceSave(); GameSave * GetPlaceSave();
std::vector<Notification*> GetNotifications(); std::vector<Notification*> GetNotifications();

View File

@ -14,6 +14,7 @@
#include "simulation/SaveRenderer.h" #include "simulation/SaveRenderer.h"
#include "simulation/SimulationData.h" #include "simulation/SimulationData.h"
#include "gui/dialogues/ConfirmPrompt.h" #include "gui/dialogues/ConfirmPrompt.h"
#include "client/SaveFile.h"
#include "Format.h" #include "Format.h"
#include "QuickOptions.h" #include "QuickOptions.h"
#include "IntroText.h" #include "IntroText.h"
@ -40,10 +41,10 @@ private:
public: public:
SplitButton(ui::Point position, ui::Point size, std::string buttonText, std::string toolTip, std::string toolTip2, int split) : SplitButton(ui::Point position, ui::Point size, std::string buttonText, std::string toolTip, std::string toolTip2, int split) :
Button(position, size, buttonText, toolTip), Button(position, size, buttonText, toolTip),
toolTip2(toolTip2), showSplit(true),
splitPosition(split), splitPosition(split),
splitActionCallback(NULL), toolTip2(toolTip2),
showSplit(true) splitActionCallback(NULL)
{ {
} }
@ -149,51 +150,54 @@ public:
GameView::GameView(): GameView::GameView():
ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)), ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)),
pointQueue(queue<ui::Point>()),
isMouseDown(false), isMouseDown(false),
ren(NULL),
activeBrush(NULL),
currentMouse(0, 0),
toolIndex(0),
zoomEnabled(false), zoomEnabled(false),
zoomCursorFixed(false), zoomCursorFixed(false),
drawPoint1(0, 0), mouseInZoom(false),
drawPoint2(0, 0),
drawMode(DrawPoints),
drawModeReset(false),
selectMode(SelectNone),
selectPoint1(0, 0),
selectPoint2(0, 0),
placeSaveThumb(NULL),
mousePosition(0, 0),
lastOffset(0),
drawSnap(false), drawSnap(false),
toolTip(""),
infoTip(""),
infoTipPresence(0),
buttonTipShow(0),
isToolTipFadingIn(false),
isButtonTipFadingIn(false),
toolTipPosition(-1, -1),
saveSimulationButtonEnabled(false),
shiftBehaviour(false), shiftBehaviour(false),
ctrlBehaviour(false), ctrlBehaviour(false),
altBehaviour(false), altBehaviour(false),
showHud(true), showHud(true),
showDebug(false), showDebug(false),
introText(2048),
introTextMessage(introTextData),
wallBrush(false), wallBrush(false),
toolBrush(false), toolBrush(false),
windTool(false), windTool(false),
toolIndex(0),
currentSaveType(0),
lastMenu(-1),
toolTipPresence(0),
toolTip(""),
isToolTipFadingIn(false),
toolTipPosition(-1, -1),
infoTipPresence(0),
infoTip(""),
buttonTipShow(0),
buttonTip(""),
isButtonTipFadingIn(false),
introText(2048),
introTextMessage(introTextData),
doScreenshot(false), doScreenshot(false),
recording(false), recording(false),
screenshotIndex(0), screenshotIndex(0),
recordingIndex(0), recordingIndex(0),
toolTipPresence(0), pointQueue(queue<ui::Point>()),
currentSaveType(0), ren(NULL),
lastLogEntry(0.0f), activeBrush(NULL),
lastMenu(-1) saveSimulationButtonEnabled(false),
drawMode(DrawPoints),
drawModeReset(false),
drawPoint1(0, 0),
drawPoint2(0, 0),
selectMode(SelectNone),
selectPoint1(0, 0),
selectPoint2(0, 0),
currentMouse(0, 0),
mousePosition(0, 0),
placeSaveThumb(NULL),
lastOffset(0)
{ {
int currentX = 1; int currentX = 1;
@ -219,7 +223,7 @@ GameView::GameView():
scrollBar->Appearance.VerticalAlign = ui::Appearance::AlignMiddle; scrollBar->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(scrollBar); AddComponent(scrollBar);
searchButton = new ui::Button(ui::Point(currentX, Size.Y-16), ui::Point(17, 15), "", "Find & open a simulation"); //Open searchButton = new ui::Button(ui::Point(currentX, Size.Y-16), ui::Point(17, 15), "", "Find & open a simulation. Hold Ctrl to load offline saves."); //Open
searchButton->SetIcon(IconOpen); searchButton->SetIcon(IconOpen);
currentX+=18; currentX+=18;
searchButton->SetTogglable(false); searchButton->SetTogglable(false);
@ -254,24 +258,25 @@ GameView::GameView():
SaveSimulationAction(GameView * _v) { v = _v; } SaveSimulationAction(GameView * _v) { v = _v; }
void ActionCallbackRight(ui::Button * sender) void ActionCallbackRight(ui::Button * sender)
{ {
if(v->CtrlBehaviour()) if(v->CtrlBehaviour() || !Client::Ref().GetAuthUser().ID)
v->c->OpenLocalSaveWindow(false); v->c->OpenLocalSaveWindow(false);
else else
v->c->OpenSaveWindow(); v->c->OpenSaveWindow();
} }
void ActionCallbackLeft(ui::Button * sender) void ActionCallbackLeft(ui::Button * sender)
{ {
if(v->CtrlBehaviour()) if(v->CtrlBehaviour() || !Client::Ref().GetAuthUser().ID)
v->c->OpenLocalSaveWindow(true); v->c->OpenLocalSaveWindow(true);
else else
v->c->SaveAsCurrent(); v->c->SaveAsCurrent();
} }
}; };
saveSimulationButton = new SplitButton(ui::Point(currentX, Size.Y-16), ui::Point(150, 15), "[untitled simulation]", "Upload the simulation under the current name", "Upload the simulation under a new name", 19); saveSimulationButton = new SplitButton(ui::Point(currentX, Size.Y-16), ui::Point(150, 15), "[untitled simulation]", "", "", 19);
saveSimulationButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft; saveSimulationButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
saveSimulationButton->SetIcon(IconSave); saveSimulationButton->SetIcon(IconSave);
currentX+=151; currentX+=151;
((SplitButton*)saveSimulationButton)->SetSplitActionCallback(new SaveSimulationAction(this)); ((SplitButton*)saveSimulationButton)->SetSplitActionCallback(new SaveSimulationAction(this));
SetSaveButtonTooltips();
AddComponent(saveSimulationButton); AddComponent(saveSimulationButton);
class UpVoteAction : public ui::ButtonAction class UpVoteAction : public ui::ButtonAction
@ -511,6 +516,9 @@ public:
case QuickOption::Toggle: case QuickOption::Toggle:
button->SetTogglable(true); button->SetTogglable(true);
button->SetToggleState(option->GetToggle()); button->SetToggleState(option->GetToggle());
break;
default:
break;
} }
} }
}; };
@ -534,7 +542,7 @@ public:
void GameView::NotifyQuickOptionsChanged(GameModel * sender) void GameView::NotifyQuickOptionsChanged(GameModel * sender)
{ {
for(int i = 0; i < quickOptionButtons.size(); i++) for (size_t i = 0; i < quickOptionButtons.size(); i++)
{ {
RemoveComponent(quickOptionButtons[i]); RemoveComponent(quickOptionButtons[i]);
delete quickOptionButtons[i]; delete quickOptionButtons[i];
@ -560,20 +568,20 @@ void GameView::NotifyQuickOptionsChanged(GameModel * sender)
void GameView::NotifyMenuListChanged(GameModel * sender) void GameView::NotifyMenuListChanged(GameModel * sender)
{ {
int currentY = WINDOWH-48;//-(sender->GetMenuList().size()*16); int currentY = WINDOWH-48;//-(sender->GetMenuList().size()*16);
for(int i = 0; i < menuButtons.size(); i++) for (size_t i = 0; i < menuButtons.size(); i++)
{ {
RemoveComponent(menuButtons[i]); RemoveComponent(menuButtons[i]);
delete menuButtons[i]; delete menuButtons[i];
} }
menuButtons.clear(); menuButtons.clear();
for(int i = 0; i < toolButtons.size(); i++) for (size_t i = 0; i < toolButtons.size(); i++)
{ {
RemoveComponent(toolButtons[i]); RemoveComponent(toolButtons[i]);
delete toolButtons[i]; delete toolButtons[i];
} }
toolButtons.clear(); toolButtons.clear();
vector<Menu*> menuList = sender->GetMenuList(); vector<Menu*> menuList = sender->GetMenuList();
for (int i = menuList.size()-1; i >= 0; i--) for (int i = (int)menuList.size()-1; i >= 0; i--)
{ {
std::string tempString = ""; std::string tempString = "";
tempString += menuList[i]->GetIcon(); tempString += menuList[i]->GetIcon();
@ -631,7 +639,7 @@ bool GameView::GetPlacingZoom()
void GameView::NotifyActiveToolsChanged(GameModel * sender) void GameView::NotifyActiveToolsChanged(GameModel * sender)
{ {
for(int i = 0; i < toolButtons.size(); i++) for (size_t i = 0; i < toolButtons.size(); i++)
{ {
Tool * tool = ((ToolAction*)toolButtons[i]->GetActionCallback())->tool; Tool * tool = ((ToolAction*)toolButtons[i]->GetActionCallback())->tool;
if(sender->GetActiveTool(0) == tool) if(sender->GetActiveTool(0) == tool)
@ -683,9 +691,9 @@ void GameView::NotifyToolListChanged(GameModel * sender)
{ {
lastOffset = 0; lastOffset = 0;
int currentX = WINDOWW-56; int currentX = WINDOWW-56;
for(int i = 0; i < menuButtons.size(); i++) for (size_t i = 0; i < menuButtons.size(); i++)
{ {
if(((MenuAction*)menuButtons[i]->GetActionCallback())->menuID==sender->GetActiveMenu()) if (((MenuAction*)menuButtons[i]->GetActionCallback())->menuID==sender->GetActiveMenu())
{ {
menuButtons[i]->SetToggleState(true); menuButtons[i]->SetToggleState(true);
} }
@ -694,14 +702,14 @@ void GameView::NotifyToolListChanged(GameModel * sender)
menuButtons[i]->SetToggleState(false); menuButtons[i]->SetToggleState(false);
} }
} }
for(int i = 0; i < toolButtons.size(); i++) for (size_t i = 0; i < toolButtons.size(); i++)
{ {
RemoveComponent(toolButtons[i]); RemoveComponent(toolButtons[i]);
delete toolButtons[i]; delete toolButtons[i];
} }
toolButtons.clear(); toolButtons.clear();
vector<Tool*> toolList = sender->GetToolList(); vector<Tool*> toolList = sender->GetToolList();
for(int i = 0; i < toolList.size(); i++) for (size_t i = 0; i < toolList.size(); i++)
{ {
VideoBuffer * tempTexture = toolList[i]->GetTexture(26, 14); VideoBuffer * tempTexture = toolList[i]->GetTexture(26, 14);
ToolButton * tempButton; ToolButton * tempButton;
@ -821,9 +829,9 @@ void GameView::NotifyColourPresetsChanged(GameModel * sender)
void GameView::NotifyColourActivePresetChanged(GameModel * sender) void GameView::NotifyColourActivePresetChanged(GameModel * sender)
{ {
for(int i = 0; i < colourPresets.size(); i++) for (size_t i = 0; i < colourPresets.size(); i++)
{ {
if(sender->GetActiveColourPreset() == i) if (sender->GetActiveColourPreset() == i)
{ {
colourPresets[i]->SetSelectionState(0); //Primary colourPresets[i]->SetSelectionState(0); //Primary
} }
@ -864,7 +872,8 @@ void GameView::NotifyUserChanged(GameModel * sender)
((SplitButton*)loginButton)->SetShowSplit(true); ((SplitButton*)loginButton)->SetShowSplit(true);
((SplitButton*)loginButton)->SetRightToolTip("Edit profile"); ((SplitButton*)loginButton)->SetRightToolTip("Edit profile");
} }
saveSimulationButtonEnabled = sender->GetUser().ID; // saveSimulationButtonEnabled = sender->GetUser().ID;
saveSimulationButtonEnabled = true;
NotifySaveChanged(sender); NotifySaveChanged(sender);
} }
@ -981,6 +990,7 @@ void GameView::NotifySaveChanged(GameModel * sender)
currentSaveType = 0; currentSaveType = 0;
} }
saveSimulationButton->Enabled = (saveSimulationButtonEnabled || ctrlBehaviour); saveSimulationButton->Enabled = (saveSimulationButtonEnabled || ctrlBehaviour);
SetSaveButtonTooltips();
c->HistorySnapshot(); c->HistorySnapshot();
} }
@ -1038,83 +1048,99 @@ void GameView::setToolButtonOffset(int offset)
void GameView::OnMouseMove(int x, int y, int dx, int dy) void GameView::OnMouseMove(int x, int y, int dx, int dy)
{ {
bool newMouseInZoom = c->MouseInZoom(ui::Point(x, y));
mousePosition = c->PointTranslate(ui::Point(x, y)); mousePosition = c->PointTranslate(ui::Point(x, y));
currentMouse = ui::Point(x, y); currentMouse = ui::Point(x, y);
if(selectMode!=SelectNone) if (selectMode != SelectNone)
{ {
if(selectMode==PlaceSave) if (selectMode == PlaceSave)
selectPoint1 = c->PointTranslate(ui::Point(x, y)); selectPoint1 = c->PointTranslate(ui::Point(x, y));
if(selectPoint1.X!=-1) if (selectPoint1.X != -1)
selectPoint2 = c->PointTranslate(ui::Point(x, y)); selectPoint2 = c->PointTranslate(ui::Point(x, y));
return;
} }
if(isMouseDown && drawMode == DrawPoints) else if (isMouseDown)
{
if (newMouseInZoom == mouseInZoom)
{
if (drawMode == DrawPoints)
{ {
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x-dx, y-dy)))); pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x-dx, y-dy))));
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y)))); pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y))));
} }
}
else if (drawMode == DrawPoints || drawMode == DrawFill)
isMouseDown = false;
}
mouseInZoom = newMouseInZoom;
} }
void GameView::OnMouseDown(int x, int y, unsigned button) void GameView::OnMouseDown(int x, int y, unsigned button)
{ {
if(altBehaviour && !shiftBehaviour && !ctrlBehaviour) if (altBehaviour && !shiftBehaviour && !ctrlBehaviour)
button = BUTTON_MIDDLE; button = BUTTON_MIDDLE;
if(selectMode!=SelectNone) if (!(zoomEnabled && !zoomCursorFixed))
{ {
if(button==BUTTON_LEFT) if (selectMode != SelectNone)
{
if (button == BUTTON_LEFT && selectPoint1.X == -1)
{ {
selectPoint1 = c->PointTranslate(ui::Point(x, y)); selectPoint1 = c->PointTranslate(ui::Point(x, y));
selectPoint2 = selectPoint1; selectPoint2 = selectPoint1;
} }
return; return;
} }
if(currentMouse.X >= 0 && currentMouse.X < XRES && currentMouse.Y >= 0 && currentMouse.Y < YRES && !(zoomEnabled && !zoomCursorFixed)) if (currentMouse.X >= 0 && currentMouse.X < XRES && currentMouse.Y >= 0 && currentMouse.Y < YRES)
{ {
if(button == BUTTON_LEFT) if (button == BUTTON_LEFT)
toolIndex = 0; toolIndex = 0;
if(button == BUTTON_RIGHT) if (button == BUTTON_RIGHT)
toolIndex = 1; toolIndex = 1;
if(button == BUTTON_MIDDLE) if (button == BUTTON_MIDDLE)
toolIndex = 2; toolIndex = 2;
isMouseDown = true; isMouseDown = true;
if(!pointQueue.size()) if (!pointQueue.size())
c->HistorySnapshot(); c->HistorySnapshot();
if(drawMode == DrawRect || drawMode == DrawLine) if (drawMode == DrawRect || drawMode == DrawLine)
{ {
drawPoint1 = c->PointTranslate(ui::Point(x, y)); drawPoint1 = c->PointTranslate(ui::Point(x, y));
} }
if(drawMode == DrawPoints) if (drawMode == DrawPoints)
{ {
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y)))); pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y))));
} }
} }
}
} }
void GameView::OnMouseUp(int x, int y, unsigned button) void GameView::OnMouseUp(int x, int y, unsigned button)
{ {
if(zoomEnabled && !zoomCursorFixed) if (zoomEnabled && !zoomCursorFixed)
{
zoomCursorFixed = true; zoomCursorFixed = true;
drawMode = DrawPoints;
isMouseDown = false;
}
else else
{ {
if(selectMode!=SelectNone) if (selectMode != SelectNone)
{ {
if(button==BUTTON_LEFT) if (button == BUTTON_LEFT)
{ {
if(selectMode==PlaceSave) if (selectMode == PlaceSave)
{ {
if(placeSaveThumb && y <= WINDOWH-BARSIZE) if (placeSaveThumb && y <= WINDOWH-BARSIZE)
{ {
int thumbX = selectPoint2.X - (placeSaveThumb->Width/2); int thumbX = selectPoint2.X - (placeSaveThumb->Width/2);
int thumbY = selectPoint2.Y - (placeSaveThumb->Height/2); int thumbY = selectPoint2.Y - (placeSaveThumb->Height/2);
if(thumbX<0) if (thumbX < 0)
thumbX = 0; thumbX = 0;
if(thumbX+(placeSaveThumb->Width)>=XRES) if (thumbX+(placeSaveThumb->Width) >= XRES)
thumbX = XRES-placeSaveThumb->Width; thumbX = XRES-placeSaveThumb->Width;
if(thumbY<0) if (thumbY < 0)
thumbY = 0; thumbY = 0;
if(thumbY+(placeSaveThumb->Height)>=YRES) if (thumbY+(placeSaveThumb->Height) >= YRES)
thumbY = YRES-placeSaveThumb->Height; thumbY = YRES-placeSaveThumb->Height;
c->PlaceSave(ui::Point(thumbX, thumbY)); c->PlaceSave(ui::Point(thumbX, thumbY));
@ -1122,15 +1148,15 @@ void GameView::OnMouseUp(int x, int y, unsigned button)
} }
else else
{ {
int x2 = (selectPoint1.X>selectPoint2.X)?selectPoint1.X:selectPoint2.X; int x2 = (selectPoint1.X>selectPoint2.X) ? selectPoint1.X : selectPoint2.X;
int y2 = (selectPoint1.Y>selectPoint2.Y)?selectPoint1.Y:selectPoint2.Y; int y2 = (selectPoint1.Y>selectPoint2.Y) ? selectPoint1.Y : selectPoint2.Y;
int x1 = (selectPoint2.X<selectPoint1.X)?selectPoint2.X:selectPoint1.X; int x1 = (selectPoint2.X<selectPoint1.X) ? selectPoint2.X : selectPoint1.X;
int y1 = (selectPoint2.Y<selectPoint1.Y)?selectPoint2.Y:selectPoint1.Y; int y1 = (selectPoint2.Y<selectPoint1.Y) ? selectPoint2.Y : selectPoint1.Y;
if(selectMode==SelectCopy) if (selectMode ==SelectCopy)
c->CopyRegion(ui::Point(x1, y1), ui::Point(x2, y2)); c->CopyRegion(ui::Point(x1, y1), ui::Point(x2, y2));
else if(selectMode==SelectCut) else if (selectMode == SelectCut)
c->CutRegion(ui::Point(x1, y1), ui::Point(x2, y2)); c->CutRegion(ui::Point(x1, y1), ui::Point(x2, y2));
else if(selectMode==SelectStamp) else if (selectMode == SelectStamp)
c->StampRegion(ui::Point(x1, y1), ui::Point(x2, y2)); c->StampRegion(ui::Point(x1, y1), ui::Point(x2, y2));
} }
} }
@ -1138,39 +1164,39 @@ void GameView::OnMouseUp(int x, int y, unsigned button)
return; return;
} }
if(isMouseDown) if (isMouseDown)
{ {
isMouseDown = false; isMouseDown = false;
if(drawMode == DrawRect || drawMode == DrawLine) if (drawMode == DrawRect || drawMode == DrawLine)
{ {
ui::Point finalDrawPoint2(0, 0); ui::Point finalDrawPoint2(0, 0);
drawPoint2 = c->PointTranslate(ui::Point(x, y)); drawPoint2 = c->PointTranslate(ui::Point(x, y));
finalDrawPoint2 = drawPoint2; finalDrawPoint2 = drawPoint2;
if(drawSnap && drawMode == DrawLine) if (drawSnap && drawMode == DrawLine)
{ {
finalDrawPoint2 = lineSnapCoords(c->PointTranslate(drawPoint1), drawPoint2); finalDrawPoint2 = lineSnapCoords(c->PointTranslate(drawPoint1), drawPoint2);
} }
if(drawSnap && drawMode == DrawRect) if (drawSnap && drawMode == DrawRect)
{ {
finalDrawPoint2 = rectSnapCoords(c->PointTranslate(drawPoint1), drawPoint2); finalDrawPoint2 = rectSnapCoords(c->PointTranslate(drawPoint1), drawPoint2);
} }
if(drawMode == DrawRect) if (drawMode == DrawRect)
{ {
c->DrawRect(toolIndex, c->PointTranslate(drawPoint1), finalDrawPoint2); c->DrawRect(toolIndex, c->PointTranslate(drawPoint1), finalDrawPoint2);
} }
if(drawMode == DrawLine) if (drawMode == DrawLine)
{ {
c->DrawLine(toolIndex, c->PointTranslate(drawPoint1), finalDrawPoint2); c->DrawLine(toolIndex, c->PointTranslate(drawPoint1), finalDrawPoint2);
} }
} }
if(drawMode == DrawPoints) if (drawMode == DrawPoints)
{ {
c->ToolClick(toolIndex, c->PointTranslate(ui::Point(x, y))); c->ToolClick(toolIndex, c->PointTranslate(ui::Point(x, y)));
} }
if(drawModeReset) if (drawModeReset)
{ {
drawModeReset = false; drawModeReset = false;
drawMode = DrawPoints; drawMode = DrawPoints;
@ -1352,7 +1378,7 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
c->ChangeBrush(); c->ChangeBrush();
break; break;
case 'z': case 'z':
if(ctrl) if (ctrl)
{ {
c->HistoryRestore(); c->HistoryRestore();
} }
@ -1387,7 +1413,21 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
c->OpenElementSearch(); c->OpenElementSearch();
break; break;
case 'f': case 'f':
#ifdef PARTICLEDEBUG
if (ctrl)
{
c->ParticleDebug(0, 0, 0);
}
else if (shift)
{
ui::Point mouse = c->PointTranslate(currentMouse);
c->ParticleDebug(1, mouse.X, mouse.Y);
}
else
c->FrameStep(); c->FrameStep();
#else
c->FrameStep();
#endif
break; break;
case 'g': case 'g':
if (ctrl) if (ctrl)
@ -1472,12 +1512,18 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
} }
break; break;
case 'l': case 'l':
c->LoadStamp(); {
std::vector<std::string> stampList = Client::Ref().GetStamps(0, 1);
if (stampList.size())
{
c->LoadStamp(Client::Ref().GetStamp(stampList[0])->GetGameSave());
selectPoint2 = mousePosition; selectPoint2 = mousePosition;
selectPoint1 = selectPoint2; selectPoint1 = selectPoint2;
isMouseDown = false; isMouseDown = false;
drawMode = DrawPoints; drawMode = DrawPoints;
break; break;
}
}
case 'k': case 'k':
selectPoint2 = ui::Point(-1, -1); selectPoint2 = ui::Point(-1, -1);
selectPoint1 = selectPoint2; selectPoint1 = selectPoint2;
@ -1640,8 +1686,6 @@ void GameView::OnTick(float dt)
toolTipPresence = 0; toolTipPresence = 0;
} }
c->Update(); c->Update();
if(lastLogEntry > -0.1f)
lastLogEntry -= 0.16*dt;
} }
@ -1722,6 +1766,19 @@ void GameView::DoKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bo
Window::DoKeyRelease(key, character, shift, ctrl, alt); Window::DoKeyRelease(key, character, shift, ctrl, alt);
} }
void GameView::DoTick(float dt)
{
//mouse events trigger every frame when mouse is held down, needs to happen here (before things are drawn) so it can clear the point queue if false is returned from a lua mouse event
if (!c->MouseTick())
{
isMouseDown = false;
drawMode = DrawPoints;
while (!pointQueue.empty())
pointQueue.pop();
}
Window::DoTick(dt);
}
void GameView::DoDraw() void GameView::DoDraw()
{ {
Window::DoDraw(); Window::DoDraw();
@ -1780,11 +1837,11 @@ void GameView::NotifyNotificationsChanged(GameModel * sender)
AddComponent(tempButton); AddComponent(tempButton);
notificationComponents.push_back(tempButton); notificationComponents.push_back(tempButton);
tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15)); tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), "\xAA");
tempButton->SetIcon(IconClose); //tempButton->SetIcon(IconClose);
tempButton->SetActionCallback(new CloseNotificationButtonAction(this, *iter)); tempButton->SetActionCallback(new CloseNotificationButtonAction(this, *iter));
tempButton->Appearance.Margin.Left+=2; tempButton->Appearance.Margin.Left -= 1;
tempButton->Appearance.Margin.Top+=2; tempButton->Appearance.Margin.Top -= 1;
tempButton->Appearance.BorderInactive = style::Colour::WarningTitle; tempButton->Appearance.BorderInactive = style::Colour::WarningTitle;
tempButton->Appearance.TextInactive = style::Colour::WarningTitle; tempButton->Appearance.TextInactive = style::Colour::WarningTitle;
tempButton->Appearance.BorderHover = ui::Colour(255, 175, 0); tempButton->Appearance.BorderHover = ui::Colour(255, 175, 0);
@ -1803,9 +1860,8 @@ void GameView::NotifyZoomChanged(GameModel * sender)
void GameView::NotifyLogChanged(GameModel * sender, string entry) void GameView::NotifyLogChanged(GameModel * sender, string entry)
{ {
logEntries.push_front(entry); logEntries.push_front(std::pair<std::string, int>(entry, 600));
lastLogEntry = 100.0f; if (logEntries.size() > 20)
if(logEntries.size()>20)
logEntries.pop_back(); logEntries.pop_back();
} }
@ -1864,20 +1920,32 @@ void GameView::disableAltBehaviour()
} }
} }
void GameView::enableCtrlBehaviour() void GameView::enableCtrlBehaviour() {
// "Usual" Ctrl-holding behavior uses highlights
enableCtrlBehaviour(true);
}
void GameView::enableCtrlBehaviour(bool isHighlighted)
{ {
if(!ctrlBehaviour) if(!ctrlBehaviour)
{ {
ctrlBehaviour = true; ctrlBehaviour = true;
//Show HDD save & load buttons //Show HDD save & load buttons
if (isHighlighted) {
saveSimulationButton->Appearance.BackgroundInactive = saveSimulationButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255); saveSimulationButton->Appearance.BackgroundInactive = saveSimulationButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255);
saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(0, 0, 0); saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(0, 0, 0);
}
saveSimulationButton->Enabled = true; saveSimulationButton->Enabled = true;
((SplitButton*)saveSimulationButton)->SetToolTips("Save the simulation to your hard drive", "Save the simulation to your hard drive"); SetSaveButtonTooltips();
if (isHighlighted) {
searchButton->Appearance.BackgroundInactive = searchButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255); searchButton->Appearance.BackgroundInactive = searchButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255);
searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(0, 0, 0); searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(0, 0, 0);
searchButton->SetToolTip("Open a simulation from your hard drive"); }
searchButton->SetToolTip("Open a simulation from your hard drive.");
if (currentSaveType == 2) if (currentSaveType == 2)
((SplitButton*)saveSimulationButton)->SetShowSplit(true); ((SplitButton*)saveSimulationButton)->SetShowSplit(true);
if(isMouseDown || (toolBrush && drawMode == DrawPoints)) if(isMouseDown || (toolBrush && drawMode == DrawPoints))
@ -1901,11 +1969,11 @@ void GameView::disableCtrlBehaviour()
saveSimulationButton->Appearance.BackgroundHover = ui::Colour(20, 20, 20); saveSimulationButton->Appearance.BackgroundHover = ui::Colour(20, 20, 20);
saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(255, 255, 255); saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(255, 255, 255);
saveSimulationButton->Enabled = saveSimulationButtonEnabled; saveSimulationButton->Enabled = saveSimulationButtonEnabled;
((SplitButton*)saveSimulationButton)->SetToolTips("Upload the simulation under current name", "Upload the simulation under new name"); SetSaveButtonTooltips();
searchButton->Appearance.BackgroundInactive = ui::Colour(0, 0, 0); searchButton->Appearance.BackgroundInactive = ui::Colour(0, 0, 0);
searchButton->Appearance.BackgroundHover = ui::Colour(20, 20, 20); searchButton->Appearance.BackgroundHover = ui::Colour(20, 20, 20);
searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(255, 255, 255); searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(255, 255, 255);
searchButton->SetToolTip("Find & open a simulation"); searchButton->SetToolTip("Find & open a simulation. Hold Ctrl to load offline saves.");
if (currentSaveType == 2) if (currentSaveType == 2)
((SplitButton*)saveSimulationButton)->SetShowSplit(false); ((SplitButton*)saveSimulationButton)->SetShowSplit(false);
if(!shiftBehaviour) if(!shiftBehaviour)
@ -1915,6 +1983,18 @@ void GameView::disableCtrlBehaviour()
} }
} }
void GameView::SetSaveButtonTooltips()
{
if (!Client::Ref().GetAuthUser().ID)
((SplitButton*)saveSimulationButton)->SetToolTips("Overwrite the open simulation on your hard drive.", "Save the simulation to your hard drive. Login to save online.");
else if (ctrlBehaviour)
((SplitButton*)saveSimulationButton)->SetToolTips("Overwrite the open simulation on your hard drive.", "Save the simulation to your hard drive.");
else if (((SplitButton*)saveSimulationButton)->GetShowSplit())
((SplitButton*)saveSimulationButton)->SetToolTips("Reupload the current simulation", "Modify simulation properties");
else
((SplitButton*)saveSimulationButton)->SetToolTips("Reupload the current simulation", "Upload a new simulation. Hold Ctrl to save offline.");
}
void GameView::OnDraw() void GameView::OnDraw()
{ {
Graphics * g = ui::Engine::Ref().g; Graphics * g = ui::Engine::Ref().g;
@ -2056,20 +2136,24 @@ void GameView::OnDraw()
Client::Ref().WriteFile(data, filename.str()); Client::Ref().WriteFile(data, filename.str());
} }
if (logEntries.size())
{
int startX = 20; int startX = 20;
int startY = YRES-20; int startY = YRES-20;
int startAlpha; deque<std::pair<std::string, int> >::iterator iter;
if(lastLogEntry>0.1f && logEntries.size()) for(iter = logEntries.begin(); iter != logEntries.end(); iter++)
{ {
startAlpha = 2.55f*lastLogEntry; string message = (*iter).first;
deque<string>::iterator iter; int alpha = std::min((*iter).second, 255);
for(iter = logEntries.begin(); iter != logEntries.end() && startAlpha>0; iter++) if (alpha <= 0) //erase this and everything older
{ {
string message = (*iter); logEntries.erase(iter, logEntries.end());
break;
}
startY -= 14; startY -= 14;
g->fillrect(startX-3, startY-3, Graphics::textwidth((char*)message.c_str())+6, 14, 0, 0, 0, 100); g->fillrect(startX-3, startY-3, Graphics::textwidth((char*)message.c_str())+6, 14, 0, 0, 0, 100);
g->drawtext(startX, startY, message.c_str(), 255, 255, 255, startAlpha); g->drawtext(startX, startY, message.c_str(), 255, 255, 255, alpha);
startAlpha-=14; (*iter).second -= 3;
} }
} }
} }

View File

@ -33,16 +33,10 @@ class GameModel;
class GameView: public ui::Window class GameView: public ui::Window
{ {
private: private:
DrawMode drawMode;
bool doScreenshot;
bool recording;
int screenshotIndex;
int recordingIndex;
bool isMouseDown; bool isMouseDown;
bool zoomEnabled; bool zoomEnabled;
bool zoomCursorFixed; bool zoomCursorFixed;
bool mouseInZoom;
bool drawSnap; bool drawSnap;
bool shiftBehaviour; bool shiftBehaviour;
bool ctrlBehaviour; bool ctrlBehaviour;
@ -52,8 +46,6 @@ private:
bool wallBrush; bool wallBrush;
bool toolBrush; bool toolBrush;
bool windTool; bool windTool;
int introText;
std::string introTextMessage;
int toolIndex; int toolIndex;
int currentSaveType; int currentSaveType;
int lastMenu; int lastMenu;
@ -67,6 +59,13 @@ private:
int buttonTipShow; int buttonTipShow;
std::string buttonTip; std::string buttonTip;
bool isButtonTipFadingIn; bool isButtonTipFadingIn;
int introText;
std::string introTextMessage;
bool doScreenshot;
bool recording;
int screenshotIndex;
int recordingIndex;
queue<ui::Point> pointQueue; queue<ui::Point> pointQueue;
GameController * c; GameController * c;
@ -77,8 +76,7 @@ private:
vector<ui::Button*> menuButtons; vector<ui::Button*> menuButtons;
vector<ToolButton*> toolButtons; vector<ToolButton*> toolButtons;
vector<ui::Component*> notificationComponents; vector<ui::Component*> notificationComponents;
deque<string> logEntries; deque<std::pair<std::string, int> > logEntries;
float lastLogEntry;
ui::Button * scrollBar; ui::Button * scrollBar;
ui::Button * searchButton; ui::Button * searchButton;
ui::Button * reloadButton; ui::Button * reloadButton;
@ -92,11 +90,11 @@ private:
ui::Button * simulationOptionButton; ui::Button * simulationOptionButton;
ui::Button * displayModeButton; ui::Button * displayModeButton;
ui::Button * pauseButton; ui::Button * pauseButton;
ui::Point currentMouse;
ui::Button * colourPicker; ui::Button * colourPicker;
vector<ToolButton*> colourPresets; vector<ToolButton*> colourPresets;
DrawMode drawMode;
bool drawModeReset; bool drawModeReset;
ui::Point drawPoint1; ui::Point drawPoint1;
ui::Point drawPoint2; ui::Point drawPoint2;
@ -105,6 +103,7 @@ private:
ui::Point selectPoint1; ui::Point selectPoint1;
ui::Point selectPoint2; ui::Point selectPoint2;
ui::Point currentMouse;
ui::Point mousePosition; ui::Point mousePosition;
VideoBuffer * placeSaveThumb; VideoBuffer * placeSaveThumb;
@ -113,8 +112,8 @@ private:
int lastOffset; int lastOffset;
void setToolButtonOffset(int offset); void setToolButtonOffset(int offset);
virtual ui::Point lineSnapCoords(ui::Point point1, ui::Point point2);
virtual ui::Point rectSnapCoords(ui::Point point1, ui::Point point2); void SetSaveButtonTooltips();
void screenshot(); void screenshot();
void record(); void record();
@ -122,6 +121,7 @@ private:
void enableShiftBehaviour(); void enableShiftBehaviour();
void disableShiftBehaviour(); void disableShiftBehaviour();
void enableCtrlBehaviour(); void enableCtrlBehaviour();
void enableCtrlBehaviour(bool isHighlighted);
void disableCtrlBehaviour(); void disableCtrlBehaviour();
void enableAltBehaviour(); void enableAltBehaviour();
void disableAltBehaviour(); void disableAltBehaviour();
@ -145,6 +145,14 @@ public:
SelectMode GetSelectMode() { return selectMode; } SelectMode GetSelectMode() { return selectMode; }
void BeginStampSelection(); void BeginStampSelection();
//all of these are only here for one debug lines
bool GetDrawingLine() { return drawMode == DrawLine && isMouseDown; }
bool GetDrawSnap() { return drawSnap; }
ui::Point GetLineStartCoords() { return drawPoint1; }
ui::Point GetLineFinishCoords() { return currentMouse; }
ui::Point lineSnapCoords(ui::Point point1, ui::Point point2);
ui::Point rectSnapCoords(ui::Point point1, ui::Point point2);
void AttachController(GameController * _c){ c = _c; } void AttachController(GameController * _c){ c = _c; }
void NotifyRendererChanged(GameModel * sender); void NotifyRendererChanged(GameModel * sender);
void NotifySimulationChanged(GameModel * sender); void NotifySimulationChanged(GameModel * sender);
@ -182,6 +190,7 @@ public:
virtual void OnBlur(); virtual void OnBlur();
//Top-level handlers, for Lua interface //Top-level handlers, for Lua interface
virtual void DoTick(float dt);
virtual void DoDraw(); virtual void DoDraw();
virtual void DoMouseMove(int x, int y, int dx, int dy); virtual void DoMouseMove(int x, int y, int dx, int dy);
virtual void DoMouseDown(int x, int y, unsigned button); virtual void DoMouseDown(int x, int y, unsigned button);

View File

@ -19,7 +19,7 @@ public:
virtual ~Menu() virtual ~Menu()
{ {
for(int i = 0; i < tools.size(); i++) for(unsigned int i = 0; i < tools.size(); i++)
{ {
delete tools[i]; delete tools[i];
} }

View File

@ -76,7 +76,7 @@ sim(sim_)
property = new ui::DropDown(ui::Point(8, 25), ui::Point(Size.X-16, 17)); property = new ui::DropDown(ui::Point(8, 25), ui::Point(Size.X-16, 17));
property->SetActionCallback(new PropertyChanged(this)); property->SetActionCallback(new PropertyChanged(this));
AddComponent(property); AddComponent(property);
for(int i = 0; i < properties.size(); i++) for (size_t i = 0; i < properties.size(); i++)
{ {
property->AddOption(std::pair<std::string, int>(properties[i].Name, i)); property->AddOption(std::pair<std::string, int>(properties[i].Name, i));
} }

View File

@ -26,10 +26,10 @@ protected:
std::string icon; std::string icon;
std::string description; std::string description;
QuickOption(std::string icon, std::string description, GameModel * m, Type type) : QuickOption(std::string icon, std::string description, GameModel * m, Type type) :
icon(icon),
description(description),
m(m), m(m),
type(type) type(type),
icon(icon),
description(description)
{ {
} }

View File

@ -101,11 +101,11 @@ public:
SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Point position_): SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Point position_):
ui::Window(ui::Point(-1, -1), ui::Point(200, 87)), ui::Window(ui::Point(-1, -1), ui::Point(200, 87)),
tool(tool_), tool(tool_),
signID(signID_),
sim(sim_),
signPosition(position_),
movingSign(NULL), movingSign(NULL),
signMoving(false) signMoving(false),
sim(sim_),
signID(signID_),
signPosition(position_)
{ {
ui::Label * messageLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), "New sign"); ui::Label * messageLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), "New sign");
messageLabel->SetTextColour(style::Colour::InformationTitle); messageLabel->SetTextColour(style::Colour::InformationTitle);
@ -271,9 +271,10 @@ VideoBuffer * SignTool::GetIcon(int toolID, int width, int height)
void SignTool::Click(Simulation * sim, Brush * brush, ui::Point position) void SignTool::Click(Simulation * sim, Brush * brush, ui::Point position)
{ {
int signX, signY, signW, signH, signIndex = -1; int signX, signY, signW, signH, signIndex = -1;
for(int i = 0; i < sim->signs.size(); i++){ for (size_t i = 0; i < sim->signs.size(); i++)
{
sim->signs[i].pos(sim->signs[i].getText(sim), signX, signY, signW, signH); sim->signs[i].pos(sim->signs[i].getText(sim), signX, signY, signW, signH);
if(position.X > signX && position.X < signX+signW && position.Y > signY && position.Y < signY+signH) if (position.X > signX && position.X < signX+signW && position.Y > signY && position.Y < signY+signH)
{ {
signIndex = i; signIndex = i;
break; break;

View File

@ -7,16 +7,16 @@
using namespace std; using namespace std;
Tool::Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)): Tool::Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)):
textureGen(textureGen),
toolID(id), toolID(id),
toolName(name), toolName(name),
toolDescription(description), toolDescription(description),
colRed(r),
colGreen(g),
colBlue(b),
textureGen(textureGen),
strength(1.0f), strength(1.0f),
resolution(1), resolution(1),
identifier(identifier) identifier(identifier),
colRed(r),
colGreen(g),
colBlue(b)
{ {
} }
@ -114,11 +114,7 @@ WindTool::WindTool(int id, string name, string description, int r, int g, int b,
Tool(id, name, description, r, g, b, identifier, textureGen) Tool(id, name, description, r, g, b, identifier, textureGen)
{ {
} }
WindTool::~WindTool() {}
void WindTool::Draw(Simulation * sim, Brush * brush, ui::Point position)
{
}
void WindTool::DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging) void WindTool::DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging)
{ {
int radiusX, radiusY, sizeX, sizeY; int radiusX, radiusY, sizeX, sizeY;
@ -146,39 +142,15 @@ void WindTool::DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui
} }
} }
} }
void WindTool::DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) {}
void WindTool::DrawFill(Simulation * sim, Brush * brush, ui::Point position) {}
void Element_LIGH_Tool::Draw(Simulation * sim, Brush * brush, ui::Point position) void Element_LIGH_Tool::DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging)
{ {
if(sim->currentTick >= nextUse) if (dragging)
{ sim->CreateParts(position1.X, position1.Y, brush->GetRadius().X, brush->GetRadius().Y, PT_LIGH);
int p = sim->create_part(-2, position.X, position.Y, toolID);
if (p != -1)
{
sim->parts[p].life = brush->GetRadius().X+brush->GetRadius().Y;
if (sim->parts[p].life > 55)
sim->parts[p].life = 55;
sim->parts[p].temp = sim->parts[p].life*150; // temperature of the lighting shows the power of the lighting
nextUse = sim->currentTick+sim->parts[p].life/4;
}
}
} }
Element_TESC_Tool::Element_TESC_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int)):
ElementTool(id, name, description, r, g, b, identifier, textureGen)
{
}
void Element_TESC_Tool::Draw(Simulation * sim, Brush * brush, ui::Point position){
int radiusInfo = brush->GetRadius().X*4+brush->GetRadius().Y*4+7;
sim->CreateParts(position.X, position.Y, toolID | (radiusInfo << 8), brush);
}
void Element_TESC_Tool::DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging) {
int radiusInfo = brush->GetRadius().X*4+brush->GetRadius().Y*4+7;
sim->CreateLine(position1.X, position1.Y, position2.X, position2.Y, toolID | (radiusInfo << 8), brush);
}
void Element_TESC_Tool::DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { void Element_TESC_Tool::DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) {
int radiusInfo = brush->GetRadius().X*4+brush->GetRadius().Y*4+7; int radiusInfo = brush->GetRadius().X*4+brush->GetRadius().Y*4+7;
sim->CreateBox(position1.X, position1.Y, position2.X, position2.Y, toolID | (radiusInfo << 8)); sim->CreateBox(position1.X, position1.Y, position2.X, position2.Y, toolID | (radiusInfo << 8));

View File

@ -23,6 +23,8 @@ protected:
int resolution; int resolution;
std::string identifier; std::string identifier;
public: public:
int colRed, colGreen, colBlue;
Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL);
int GetToolID() { return toolID; } int GetToolID() { return toolID; }
string GetName(); string GetName();
@ -39,7 +41,6 @@ public:
virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false);
virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2); virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2);
virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position);
int colRed, colBlue, colGreen;
}; };
class GameModel; class GameModel;
@ -103,17 +104,13 @@ public:
class Element_LIGH_Tool: public Tool class Element_LIGH_Tool: public Tool
{ {
int nextUse;
public: public:
Element_LIGH_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): Element_LIGH_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL):
Tool(id, name, description, r, g, b, identifier, textureGen), Tool(id, name, description, r, g, b, identifier, textureGen)
nextUse(0) { }
{ virtual ~Element_LIGH_Tool() { }
}
virtual ~Element_LIGH_Tool() {}
virtual void Draw(Simulation * sim, Brush * brush, ui::Point position);
virtual void Click(Simulation * sim, Brush * brush, ui::Point position) { } virtual void Click(Simulation * sim, Brush * brush, ui::Point position) { }
virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false) { } virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false);
virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { } virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { }
virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position) { } virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position) { }
}; };
@ -133,10 +130,10 @@ public:
class Element_TESC_Tool: public ElementTool class Element_TESC_Tool: public ElementTool
{ {
public: public:
Element_TESC_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); Element_TESC_Tool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL):
ElementTool(id, name, description, r, g, b, identifier, textureGen)
{ }
virtual ~Element_TESC_Tool() {} virtual ~Element_TESC_Tool() {}
virtual void Draw(Simulation * sim, Brush * brush, ui::Point position);
virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false);
virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2); virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2);
virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position);
}; };
@ -146,10 +143,9 @@ class PlopTool: public ElementTool
public: public:
PlopTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL): PlopTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL):
ElementTool(id, name, description, r, g, b, identifier, textureGen) ElementTool(id, name, description, r, g, b, identifier, textureGen)
{ { }
} virtual ~PlopTool() { }
virtual ~PlopTool() {} virtual void Draw(Simulation * sim, Brush * brush, ui::Point position) { }
virtual void Draw(Simulation * sim, Brush * brush, ui::Point position) {}
virtual void Click(Simulation * sim, Brush * brush, ui::Point position); virtual void Click(Simulation * sim, Brush * brush, ui::Point position);
virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false) { } virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false) { }
virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { } virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { }
@ -171,11 +167,11 @@ class WindTool: public Tool
{ {
public: public:
WindTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL); WindTool(int id, string name, string description, int r, int g, int b, std::string identifier, VideoBuffer * (*textureGen)(int, int, int) = NULL);
virtual ~WindTool(); virtual ~WindTool() { }
virtual void Draw(Simulation * sim, Brush * brush, ui::Point position); virtual void Draw(Simulation * sim, Brush * brush, ui::Point position) { }
virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false); virtual void DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging = false);
virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2); virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { }
virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position); virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position) { }
}; };
#endif /* TOOL_H_ */ #endif /* TOOL_H_ */

View File

@ -6,6 +6,10 @@ ToolButton::ToolButton(ui::Point position, ui::Point size, std::string text_, st
{ {
SetSelectionState(-1); SetSelectionState(-1);
Appearance.BorderActive = ui::Colour(255, 0, 0); Appearance.BorderActive = ui::Colour(255, 0, 0);
//don't use "..." on elements that have long names
buttonDisplayText = ButtonText;
Component::TextPosition(buttonDisplayText);
} }
void ToolButton::OnMouseClick(int x, int y, unsigned int button) void ToolButton::OnMouseClick(int x, int y, unsigned int button)

View File

@ -4,8 +4,10 @@
namespace ui namespace ui
{ {
Appearance::Appearance(): Appearance::Appearance():
HorizontalAlign(AlignCentre), texture(NULL),
VerticalAlign(AlignMiddle), VerticalAlign(AlignMiddle),
HorizontalAlign(AlignCentre),
BackgroundHover(20, 20, 20), BackgroundHover(20, 20, 20),
BackgroundInactive(0, 0, 0), BackgroundInactive(0, 0, 0),
@ -25,10 +27,8 @@ namespace ui
Margin(1, 4), Margin(1, 4),
Border(1), Border(1),
icon(NoIcon), icon(NoIcon)
{}
texture(NULL)
{};
VideoBuffer * Appearance::GetTexture() VideoBuffer * Appearance::GetTexture()
{ {

View File

@ -14,10 +14,10 @@ namespace ui {
AvatarButton::AvatarButton(Point position, Point size, std::string username): AvatarButton::AvatarButton(Point position, Point size, std::string username):
Component(position, size), Component(position, size),
name(username),
actionCallback(NULL),
avatar(NULL), avatar(NULL),
tried(false) name(username),
tried(false),
actionCallback(NULL)
{ {
} }

View File

@ -8,14 +8,14 @@ namespace ui {
Button::Button(Point position, Point size, std::string buttonText, std::string toolTip): Button::Button(Point position, Point size, std::string buttonText, std::string toolTip):
Component(position, size), Component(position, size),
Enabled(true),
ButtonText(buttonText), ButtonText(buttonText),
isMouseInside(false), toolTip(toolTip),
isButtonDown(false), isButtonDown(false),
isMouseInside(false),
isTogglable(false), isTogglable(false),
toggle(false), toggle(false),
actionCallback(NULL), actionCallback(NULL)
Enabled(true),
toolTip(toolTip)
{ {
TextPosition(); TextPosition();
} }
@ -134,14 +134,7 @@ void Button::Draw(const Point& screenPos)
if(Appearance.icon) if(Appearance.icon)
{ {
if(Enabled) if(Enabled)
if(isButtonDown || (isTogglable && toggle))
{
g->draw_icon(Position.X+iconPosition.X, Position.Y+iconPosition.Y, Appearance.icon, 255, iconInvert); g->draw_icon(Position.X+iconPosition.X, Position.Y+iconPosition.Y, Appearance.icon, 255, iconInvert);
}
else
{
g->draw_icon(Position.X+iconPosition.X, Position.Y+iconPosition.Y, Appearance.icon, 255, iconInvert);
}
else else
g->draw_icon(Position.X+iconPosition.X, Position.Y+iconPosition.Y, Appearance.icon, 180, iconInvert); g->draw_icon(Position.X+iconPosition.X, Position.Y+iconPosition.Y, Appearance.icon, 180, iconInvert);
} }

View File

@ -24,7 +24,6 @@ public:
Button(Point position = Point(0, 0), Point size = Point(0, 0), std::string buttonText = "", std::string toolTip = ""); Button(Point position = Point(0, 0), Point size = Point(0, 0), std::string buttonText = "", std::string toolTip = "");
virtual ~Button(); virtual ~Button();
bool Toggleable;
bool Enabled; bool Enabled;
virtual void OnMouseClick(int x, int y, unsigned int button); virtual void OnMouseClick(int x, int y, unsigned int button);
@ -53,9 +52,9 @@ public:
void SetToolTip(std::string newToolTip) { toolTip = newToolTip; } void SetToolTip(std::string newToolTip) { toolTip = newToolTip; }
protected: protected:
std::string ButtonText;
std::string toolTip; std::string toolTip;
std::string buttonDisplayText; std::string buttonDisplayText;
std::string ButtonText;
bool isButtonDown, isAltButtonDown, state, isMouseInside, isTogglable, toggle; bool isButtonDown, isAltButtonDown, state, isMouseInside, isTogglable, toggle;
ButtonAction * actionCallback; ButtonAction * actionCallback;

View File

@ -6,8 +6,8 @@ Checkbox::Checkbox(ui::Point position, ui::Point size, std::string text, std::st
Component(position, size), Component(position, size),
text(text), text(text),
toolTip(toolTip), toolTip(toolTip),
isMouseOver(false),
checked(false), checked(false),
isMouseOver(false),
actionCallback(NULL) actionCallback(NULL)
{ {

View File

@ -12,15 +12,15 @@ using namespace ui;
Component::Component(Window* parent_state): Component::Component(Window* parent_state):
parentstate_(parent_state), parentstate_(parent_state),
_parent(NULL), _parent(NULL),
Position(Point(0,0)), drawn(false),
Size(Point(0,0)),
Locked(false),
Visible(true),
textPosition(0, 0), textPosition(0, 0),
textSize(0, 0), textSize(0, 0),
iconPosition(0, 0), iconPosition(0, 0),
drawn(false), menu(NULL),
menu(NULL) Position(Point(0,0)),
Size(Point(0,0)),
Locked(false),
Visible(true)
{ {
} }
@ -28,15 +28,15 @@ Component::Component(Window* parent_state):
Component::Component(Point position, Point size): Component::Component(Point position, Point size):
parentstate_(0), parentstate_(0),
_parent(NULL), _parent(NULL),
Position(position), drawn(false),
Size(size),
Locked(false),
Visible(true),
textPosition(0, 0), textPosition(0, 0),
textSize(0, 0), textSize(0, 0),
iconPosition(0, 0), iconPosition(0, 0),
drawn(false), menu(NULL),
menu(NULL) Position(position),
Size(size),
Locked(false),
Visible(true)
{ {
} }
@ -44,15 +44,15 @@ Component::Component(Point position, Point size):
Component::Component(): Component::Component():
parentstate_(NULL), parentstate_(NULL),
_parent(NULL), _parent(NULL),
Position(Point(0,0)), drawn(false),
Size(Point(0,0)),
Locked(false),
Visible(true),
textPosition(0, 0), textPosition(0, 0),
textSize(0, 0), textSize(0, 0),
iconPosition(0, 0), iconPosition(0, 0),
drawn(false), menu(NULL),
menu(NULL) Position(Point(0,0)),
Size(Point(0,0)),
Locked(false),
Visible(true)
{ {
} }

View File

@ -16,14 +16,14 @@ public:
ContextMenu::ContextMenu(Component * source): ContextMenu::ContextMenu(Component * source):
Window(ui::Point(0, 0), ui::Point(0, 0)), Window(ui::Point(0, 0), ui::Point(0, 0)),
Appearance(source->Appearance), source(source),
source(source) Appearance(source->Appearance)
{ {
} }
void ContextMenu::Show(ui::Point position) void ContextMenu::Show(ui::Point position)
{ {
for(int i = 0; i < buttons.size(); i++) for (size_t i = 0; i < buttons.size(); i++)
{ {
RemoveComponent(buttons[i]); RemoveComponent(buttons[i]);
delete buttons[i]; delete buttons[i];
@ -40,7 +40,7 @@ void ContextMenu::Show(ui::Point position)
Position = position; Position = position;
int currentY = 1; int currentY = 1;
for(int i = 0; i < items.size(); i++) for (size_t i = 0; i < items.size(); i++)
{ {
Button * tempButton = new Button(Point(1, currentY), Point(Size.X-2, 16), items[i].Text); Button * tempButton = new Button(Point(1, currentY), Point(Size.X-2, 16), items[i].Text);
tempButton->Appearance = Appearance; tempButton->Appearance = Appearance;
@ -69,9 +69,9 @@ void ContextMenu::OnMouseDown(int x, int y, unsigned button)
void ContextMenu::SetItem(int id, std::string text) void ContextMenu::SetItem(int id, std::string text)
{ {
for(int i = 0; i < items.size(); i++) for (size_t i = 0; i < items.size(); i++)
{ {
if(items[i].ID == id) if (items[i].ID == id)
{ {
items[i].Text = text; items[i].Text = text;
break; break;
@ -81,9 +81,9 @@ void ContextMenu::SetItem(int id, std::string text)
void ContextMenu::RemoveItem(int id) void ContextMenu::RemoveItem(int id)
{ {
for(int i = 0; i < items.size(); i++) for (size_t i = 0; i < items.size(); i++)
{ {
if(items[i].ID == id) if (items[i].ID == id)
{ {
items.erase(items.begin()+i); items.erase(items.begin()+i);
break; break;

View File

@ -14,7 +14,7 @@ public:
int ID; int ID;
std::string Text; std::string Text;
bool Enabled; bool Enabled;
ContextMenuItem(std::string text, int id, bool enabled) : Text(text), ID(id), Enabled(enabled) {} ContextMenuItem(std::string text, int id, bool enabled) : ID(id), Text(text), Enabled(enabled) {}
}; };
class ContextMenu: public ui::Window, public ButtonAction { class ContextMenu: public ui::Window, public ButtonAction {

View File

@ -21,7 +21,6 @@ namespace ui
ui::Button::OnMouseClick(x, y, button); ui::Button::OnMouseClick(x, y, button);
ClipboardPush((char*)ButtonText.c_str()); ClipboardPush((char*)ButtonText.c_str());
int textWidth = Graphics::textwidth("Copied!");
copyTextLabel->SetText("Copied!"); copyTextLabel->SetText("Copied!");
Appearance.TextInactive = ui::Colour(180, 230, 180); Appearance.TextInactive = ui::Colour(180, 230, 180);

View File

@ -8,8 +8,8 @@ namespace ui {
class ItemSelectedAction; class ItemSelectedAction;
class DropDownWindow: public ui::Window { class DropDownWindow: public ui::Window {
friend class ItemSelectedAction; friend class ItemSelectedAction;
Appearance appearance;
DropDown * dropDown; DropDown * dropDown;
Appearance appearance;
std::vector<Button> buttons; std::vector<Button> buttons;
bool isMouseInside; bool isMouseInside;
public: public:
@ -32,11 +32,11 @@ public:
appearance(dropDown->Appearance) appearance(dropDown->Appearance)
{ {
int currentY = 1; int currentY = 1;
for(int i = 0; i < dropDown->options.size(); i++) for (size_t i = 0; i < dropDown->options.size(); i++)
{ {
Button * tempButton = new Button(Point(1, currentY), Point(Size.X-2, 16), dropDown->options[i].first); Button * tempButton = new Button(Point(1, currentY), Point(Size.X-2, 16), dropDown->options[i].first);
tempButton->Appearance = appearance; tempButton->Appearance = appearance;
if(i) if (i)
tempButton->Appearance.Border = ui::Border(0, 1, 1, 1); tempButton->Appearance.Border = ui::Border(0, 1, 1, 1);
tempButton->SetActionCallback(new ItemSelectedAction(this, dropDown->options[i].first)); tempButton->SetActionCallback(new ItemSelectedAction(this, dropDown->options[i].first));
AddComponent(tempButton); AddComponent(tempButton);
@ -51,10 +51,10 @@ public:
void setOption(std::string option) void setOption(std::string option)
{ {
dropDown->SetOption(option); dropDown->SetOption(option);
if(dropDown->callback) if (dropDown->callback)
{ {
int optionIndex = 0; size_t optionIndex = 0;
for(optionIndex = 0; optionIndex < dropDown->options.size(); optionIndex++) for (optionIndex = 0; optionIndex < dropDown->options.size(); optionIndex++)
{ {
if(option == dropDown->options[optionIndex].first) if(option == dropDown->options[optionIndex].first)
break; break;
@ -138,9 +138,9 @@ void DropDown::OnMouseLeave(int x, int y)
void DropDown::SetOption(std::string option) void DropDown::SetOption(std::string option)
{ {
for(int i = 0; i < options.size(); i++) for (size_t i = 0; i < options.size(); i++)
{ {
if(options[i].first == option) if (options[i].first == option)
{ {
optionIndex = i; optionIndex = i;
TextPosition(options[optionIndex].first); TextPosition(options[optionIndex].first);
@ -150,9 +150,9 @@ void DropDown::OnMouseLeave(int x, int y)
} }
void DropDown::SetOption(int option) void DropDown::SetOption(int option)
{ {
for(int i = 0; i < options.size(); i++) for (size_t i = 0; i < options.size(); i++)
{ {
if(options[i].second == option) if (options[i].second == option)
{ {
optionIndex = i; optionIndex = i;
TextPosition(options[optionIndex].first); TextPosition(options[optionIndex].first);
@ -162,9 +162,9 @@ void DropDown::OnMouseLeave(int x, int y)
} }
void DropDown::AddOption(std::pair<std::string, int> option) void DropDown::AddOption(std::pair<std::string, int> option)
{ {
for(int i = 0; i < options.size(); i++) for (size_t i = 0; i < options.size(); i++)
{ {
if(options[i] == option) if (options[i] == option)
return; return;
} }
options.push_back(option); options.push_back(option);
@ -172,11 +172,11 @@ void DropDown::OnMouseLeave(int x, int y)
void DropDown::RemoveOption(std::string option) void DropDown::RemoveOption(std::string option)
{ {
start: start:
for(int i = 0; i < options.size(); i++) for (size_t i = 0; i < options.size(); i++)
{ {
if(options[i].first == option) if (options[i].first == option)
{ {
if(i == optionIndex) if ((int)i == optionIndex)
optionIndex = -1; optionIndex = -1;
options.erase(options.begin()+i); options.erase(options.begin()+i);
goto start; goto start;

View File

@ -1,6 +1,7 @@
#include <iostream> #include <iostream>
#include <stack> #include <stack>
#include <cstdio> #include <cstdio>
#include <cmath>
#include "Config.h" #include "Config.h"
#include "Misc.h" #include "Misc.h"
@ -13,26 +14,26 @@ using namespace ui;
using namespace std; using namespace std;
Engine::Engine(): Engine::Engine():
FpsLimit(60.0f),
Scale(1),
Fullscreen(false),
FrameIndex(0),
lastBuffer(NULL),
prevBuffers(stack<pixel*>()),
windows(stack<Window*>()),
mousePositions(stack<Point>()),
state_(NULL), state_(NULL),
maxWidth(0), windowTargetPosition(0, 0),
maxHeight(0), break_(false),
FastQuit(1),
lastTick(0),
mouseb_(0), mouseb_(0),
mousex_(0), mousex_(0),
mousey_(0), mousey_(0),
mousexp_(0), mousexp_(0),
mouseyp_(0), mouseyp_(0),
FpsLimit(60.0f), maxWidth(0),
windows(stack<Window*>()), maxHeight(0)
mousePositions(stack<Point>()),
lastBuffer(NULL),
prevBuffers(stack<pixel*>()),
windowTargetPosition(0, 0),
FrameIndex(0),
Fullscreen(false),
Scale(1),
FastQuit(1),
break_(false),
lastTick(0)
{ {
} }
@ -76,7 +77,7 @@ void Engine::Exit()
void Engine::ShowWindow(Window * window) void Engine::ShowWindow(Window * window)
{ {
windowOpenState = 0.0f; windowOpenState = 0;
if(window->Position.X==-1) if(window->Position.X==-1)
{ {
window->Position.X = (width_-window->Size.X)/2; window->Position.X = (width_-window->Size.X)/2;
@ -182,22 +183,6 @@ void Engine::Tick()
lastTick = gettime(); lastTick = gettime();
if(windowOpenState<1.0f)
{
if(lastBuffer)
{
pixel * vid = g->vid;
g->vid = lastBuffer;
g->fillrect(0, 0, width_, height_, 0, 0, 0, 5);
g->vid = vid;
}
/*if(windowTargetPosition.Y < state_->Position.Y)
{
state_->Position.Y += windowTargetPosition.Y/20;
}*/
windowOpenState += 0.05f;//*dt;
}
/*if(statequeued_ != NULL) /*if(statequeued_ != NULL)
{ {
@ -217,12 +202,15 @@ void Engine::Tick()
void Engine::Draw() void Engine::Draw()
{ {
if(lastBuffer && !(state_->Position.X == 0 && state_->Position.Y == 0 && state_->Size.X == width_ && state_->Size.Y == height_)) if(lastBuffer && !(state_ && state_->Position.X == 0 && state_->Position.Y == 0 && state_->Size.X == width_ && state_->Size.Y == height_))
{ {
g->Acquire(); g->Acquire();
g->Clear(); g->Clear();
#ifndef OGLI #ifndef OGLI
memcpy(g->vid, lastBuffer, (width_ * height_) * PIXELSIZE); memcpy(g->vid, lastBuffer, (width_ * height_) * PIXELSIZE);
if(windowOpenState < 20)
windowOpenState++;
g->fillrect(0, 0, width_, height_, 0, 0, 0, 255-std::pow(.98, windowOpenState)*255);
#endif #endif
} }
else else

View File

@ -87,7 +87,7 @@ namespace ui
//Window* statequeued_; //Window* statequeued_;
Window* state_; Window* state_;
Point windowTargetPosition; Point windowTargetPosition;
float windowOpenState; int windowOpenState;
bool running_; bool running_;
bool break_; bool break_;

View File

@ -17,8 +17,7 @@ Label::Label(Point position, Point size, std::string labelText):
selectionXH(-1), selectionXH(-1),
multiline(false), multiline(false),
selecting(false), selecting(false),
autoHeight(size.Y==-1?true:false), autoHeight(size.Y==-1?true:false)
caret(-1)
{ {
menu = new ContextMenu(this); menu = new ContextMenu(this);
menu->AddItem(ContextMenuItem("Copy", 0, true)); menu->AddItem(ContextMenuItem("Copy", 0, true));
@ -70,7 +69,7 @@ void Label::AutoHeight()
void Label::updateMultiline() void Label::updateMultiline()
{ {
int lines = 1; int lines = 1;
if(text.length()>0) if (text.length()>0)
{ {
char * rawText = new char[text.length()+1]; char * rawText = new char[text.length()+1];
std::copy(text.begin(), text.end(), rawText); std::copy(text.begin(), text.end(), rawText);
@ -82,7 +81,7 @@ void Label::updateMultiline()
int wordWidth = 0; int wordWidth = 0;
int lineWidth = 0; int lineWidth = 0;
char * wordStart = NULL; char * wordStart = NULL;
while(c = rawText[charIndex++]) while ((c = rawText[charIndex++]))
{ {
switch(c) switch(c)
{ {
@ -99,19 +98,19 @@ void Label::updateMultiline()
wordWidth += Graphics::CharWidth(c); wordWidth += Graphics::CharWidth(c);
break; break;
} }
if(pc == ' ') if (pc == ' ')
{ {
wordStart = &rawText[charIndex-2]; wordStart = &rawText[charIndex-2];
} }
if ((c != ' ' || pc == ' ') && lineWidth + wordWidth >= Size.X-(Appearance.Margin.Left+Appearance.Margin.Right)) if ((c != ' ' || pc == ' ') && lineWidth + wordWidth >= Size.X-(Appearance.Margin.Left+Appearance.Margin.Right))
{ {
if(wordStart && *wordStart) if (wordStart && *wordStart)
{ {
*wordStart = '\n'; *wordStart = '\n';
if (lineWidth != 0) if (lineWidth != 0)
lineWidth = wordWidth; lineWidth = wordWidth;
} }
else if(!wordStart) else if (!wordStart)
{ {
rawText[charIndex-1] = '\n'; rawText[charIndex-1] = '\n';
lineWidth = 0; lineWidth = 0;
@ -122,7 +121,7 @@ void Label::updateMultiline()
} }
pc = c; pc = c;
} }
if(autoHeight) if (autoHeight)
{ {
Size.Y = lines*12; Size.Y = lines*12;
} }
@ -163,7 +162,7 @@ void Label::updateMultiline()
} }
else else
{ {
if(autoHeight) if (autoHeight)
{ {
Size.Y = 12; Size.Y = 12;
} }
@ -281,10 +280,10 @@ void Label::updateSelection()
{ {
std::string currentText; std::string currentText;
if(selectionIndex0 < 0) selectionIndex0 = 0; if (selectionIndex0 < 0) selectionIndex0 = 0;
if(selectionIndex0 > text.length()) selectionIndex0 = text.length(); if (selectionIndex0 > (int)text.length()) selectionIndex0 = text.length();
if(selectionIndex1 < 0) selectionIndex1 = 0; if (selectionIndex1 < 0) selectionIndex1 = 0;
if(selectionIndex1 > text.length()) selectionIndex1 = text.length(); if (selectionIndex1 > (int)text.length()) selectionIndex1 = text.length();
if(selectionIndex0 == -1 || selectionIndex1 == -1) if(selectionIndex0 == -1 || selectionIndex1 == -1)
{ {

View File

@ -19,7 +19,6 @@ namespace ui
std::string text; std::string text;
Colour textColour; Colour textColour;
int caret;
int selectionIndex0; int selectionIndex0;
int selectionIndex1; int selectionIndex1;

View File

@ -75,9 +75,9 @@ Component* Panel::GetChild(unsigned idx)
void Panel::RemoveChild(Component* c) void Panel::RemoveChild(Component* c)
{ {
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
if(children[i] == c) if (children[i] == c)
{ {
//remove child from parent. Does not free memory //remove child from parent. Does not free memory
children.erase(children.begin() + i); children.erase(children.begin() + i);
@ -114,13 +114,13 @@ void Panel::Draw(const Point& screenPos)
#endif #endif
// attempt to draw all children // attempt to draw all children
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
// the component must be visible // the component must be visible
if(children[i]->Visible) if (children[i]->Visible)
{ {
//check if the component is in the screen, draw if it is //check if the component is in the screen, draw if it is
if( children[i]->Position.X + ViewportPosition.X + children[i]->Size.X >= 0 && if (children[i]->Position.X + ViewportPosition.X + children[i]->Size.X >= 0 &&
children[i]->Position.Y + ViewportPosition.Y + children[i]->Size.Y >= 0 && children[i]->Position.Y + ViewportPosition.Y + children[i]->Size.Y >= 0 &&
children[i]->Position.X + ViewportPosition.X < ui::Engine::Ref().GetWidth() && children[i]->Position.X + ViewportPosition.X < ui::Engine::Ref().GetWidth() &&
children[i]->Position.Y + ViewportPosition.Y < ui::Engine::Ref().GetHeight() ) children[i]->Position.Y + ViewportPosition.Y < ui::Engine::Ref().GetHeight() )
@ -222,7 +222,7 @@ void Panel::OnMouseClick(int localx, int localy, unsigned button)
void Panel::OnMouseDown(int x, int y, unsigned button) void Panel::OnMouseDown(int x, int y, unsigned button)
{ {
XOnMouseDown(x, y, button); XOnMouseDown(x, y, button);
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
if(!children[i]->Locked) if(!children[i]->Locked)
children[i]->OnMouseDown(x, y, button); children[i]->OnMouseDown(x, y, button);
@ -232,9 +232,9 @@ void Panel::OnMouseDown(int x, int y, unsigned button)
void Panel::OnMouseHover(int localx, int localy) void Panel::OnMouseHover(int localx, int localy)
{ {
// check if hovering on children // check if hovering on children
for(int i = children.size() - 1; i >= 0; --i) for (int i = children.size() - 1; i >= 0; --i)
{ {
if(!children[i]->Locked) if (!children[i]->Locked)
{ {
if( localx >= children[i]->Position.X && if( localx >= children[i]->Position.X &&
localy >= children[i]->Position.Y && localy >= children[i]->Position.Y &&
@ -254,7 +254,7 @@ void Panel::OnMouseHover(int localx, int localy)
void Panel::OnMouseMoved(int localx, int localy, int dx, int dy) void Panel::OnMouseMoved(int localx, int localy, int dx, int dy)
{ {
XOnMouseMoved(localx, localy, dx, dy); XOnMouseMoved(localx, localy, dx, dy);
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
if(!children[i]->Locked) if(!children[i]->Locked)
children[i]->OnMouseMoved(localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y, dx, dy); children[i]->OnMouseMoved(localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y, dx, dy);
@ -264,9 +264,9 @@ void Panel::OnMouseMoved(int localx, int localy, int dx, int dy)
void Panel::OnMouseMovedInside(int localx, int localy, int dx, int dy) void Panel::OnMouseMovedInside(int localx, int localy, int dx, int dy)
{ {
mouseInside = true; mouseInside = true;
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
if(!children[i]->Locked) if (!children[i]->Locked)
{ {
Point local (localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y) Point local (localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y)
, prevlocal (local.X - dx, local.Y - dy); , prevlocal (local.X - dx, local.Y - dy);
@ -344,7 +344,7 @@ void Panel::OnMouseUnclick(int localx, int localy, unsigned button)
} }
//if a child wasn't clicked, send click to ourself //if a child wasn't clicked, send click to ourself
if(!childunclicked) if (!childunclicked)
{ {
XOnMouseUnclick(localx, localy, button); XOnMouseUnclick(localx, localy, button);
} }
@ -353,9 +353,9 @@ void Panel::OnMouseUnclick(int localx, int localy, unsigned button)
void Panel::OnMouseUp(int x, int y, unsigned button) void Panel::OnMouseUp(int x, int y, unsigned button)
{ {
XOnMouseUp(x, y, button); XOnMouseUp(x, y, button);
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
if(!children[i]->Locked) if (!children[i]->Locked)
children[i]->OnMouseUp(x, y, button); children[i]->OnMouseUp(x, y, button);
} }
} }
@ -363,9 +363,9 @@ void Panel::OnMouseUp(int x, int y, unsigned button)
void Panel::OnMouseWheel(int localx, int localy, int d) void Panel::OnMouseWheel(int localx, int localy, int d)
{ {
XOnMouseWheel(localx, localy, d); XOnMouseWheel(localx, localy, d);
for(int i = 0; i < children.size(); ++i) for (size_t i = 0; i < children.size(); ++i)
{ {
if(!children[i]->Locked) if (!children[i]->Locked)
children[i]->OnMouseWheel(localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y, d); children[i]->OnMouseWheel(localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y, d);
} }
} }
@ -374,13 +374,13 @@ void Panel::OnMouseWheelInside(int localx, int localy, int d)
{ {
XOnMouseWheelInside(localx, localy, d); XOnMouseWheelInside(localx, localy, d);
//check if clicked a child //check if clicked a child
for(int i = children.size()-1; i >= 0 ; --i) for (int i = children.size()-1; i >= 0 ; --i)
{ {
//child must be unlocked //child must be unlocked
if(!children[i]->Locked) if (!children[i]->Locked)
{ {
//is mouse inside? //is mouse inside?
if( localx >= children[i]->Position.X + ViewportPosition.X && if (localx >= children[i]->Position.X + ViewportPosition.X &&
localy >= children[i]->Position.Y + ViewportPosition.Y && localy >= children[i]->Position.Y + ViewportPosition.Y &&
localx < children[i]->Position.X + ViewportPosition.X + children[i]->Size.X && localx < children[i]->Position.X + ViewportPosition.X + children[i]->Size.X &&
localy < children[i]->Position.Y + ViewportPosition.Y + children[i]->Size.Y ) localy < children[i]->Position.Y + ViewportPosition.Y + children[i]->Size.Y )

View File

@ -5,9 +5,9 @@ using namespace ui;
ProgressBar::ProgressBar(Point position, Point size, int startProgress, std::string startStatus): ProgressBar::ProgressBar(Point position, Point size, int startProgress, std::string startStatus):
Component(position, size), Component(position, size),
progress(0),
intermediatePos(0.0f), intermediatePos(0.0f),
progressStatus(""), progressStatus("")
progress(0)
{ {
SetStatus(startStatus); SetStatus(startStatus);
SetProgress(startProgress); SetProgress(startProgress);

View File

@ -18,15 +18,15 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
file(NULL), file(NULL),
save(save), save(save),
thumbnail(NULL), thumbnail(NULL),
isMouseInside(false),
isButtonDown(false),
actionCallback(NULL),
selectable(false),
selected(false),
waitingForThumb(false), waitingForThumb(false),
isMouseInsideAuthor(false), isMouseInsideAuthor(false),
isMouseInsideHistory(false), isMouseInsideHistory(false),
showVotes(false) showVotes(false),
isButtonDown(false),
isMouseInside(false),
selected(false),
selectable(false),
actionCallback(NULL)
{ {
if(save) if(save)
{ {
@ -42,7 +42,7 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
votes = format::NumberToString<int>(save->GetVotesUp()-save->GetVotesDown()); votes = format::NumberToString<int>(save->GetVotesUp()-save->GetVotesDown());
icon += 0xBB; icon += 0xBB;
for (int j = 1; j < votes.length(); j++) for (size_t j = 1; j < votes.length(); j++)
icon += 0xBC; icon += 0xBC;
icon += 0xB9; icon += 0xB9;
icon += 0xBA; icon += 0xBA;
@ -88,19 +88,19 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
SaveButton::SaveButton(Point position, Point size, SaveFile * file): SaveButton::SaveButton(Point position, Point size, SaveFile * file):
Component(position, size), Component(position, size),
save(NULL),
file(file), file(file),
save(NULL),
thumbnail(NULL), thumbnail(NULL),
isMouseInside(false),
isButtonDown(false),
actionCallback(NULL),
selectable(false),
selected(false),
wantsDraw(false), wantsDraw(false),
waitingForThumb(false), waitingForThumb(false),
isMouseInsideAuthor(false), isMouseInsideAuthor(false),
isMouseInsideHistory(false), isMouseInsideHistory(false),
showVotes(false) showVotes(false),
isButtonDown(false),
isMouseInside(false),
selected(false),
selectable(false),
actionCallback(NULL)
{ {
if(file) if(file)
{ {
@ -190,6 +190,8 @@ void SaveButton::Draw(const Point& screenPos)
else else
g->draw_image(thumbnail, screenPos.X+(Size.X-thumbBoxSize.X)/2, screenPos.Y+(Size.Y-21-thumbBoxSize.Y)/2, 255); g->draw_image(thumbnail, screenPos.X+(Size.X-thumbBoxSize.X)/2, screenPos.Y+(Size.Y-21-thumbBoxSize.Y)/2, 255);
} }
else if (file && !file->GetGameSave())
g->drawtext(screenPos.X+(Size.X-Graphics::textwidth("Error loading save"))/2, screenPos.Y+(Size.Y-28)/2, "Error loading save", 180, 180, 180, 255);
if(save) if(save)
{ {
if(save->id) if(save->id)
@ -253,14 +255,14 @@ void SaveButton::Draw(const Point& screenPos)
g->drawtext(screenPos.X, screenPos.Y-2, "\xCE", 212, 151, 81, 255); g->drawtext(screenPos.X, screenPos.Y-2, "\xCE", 212, 151, 81, 255);
} }
} }
if(file) else if (file)
{ {
if(isMouseInside) if (isMouseInside)
g->drawrect(screenPos.X+(Size.X-thumbBoxSize.X)/2, screenPos.Y+(Size.Y-21-thumbBoxSize.Y)/2, thumbBoxSize.X, thumbBoxSize.Y, 210, 230, 255, 255); g->drawrect(screenPos.X+(Size.X-thumbBoxSize.X)/2, screenPos.Y+(Size.Y-21-thumbBoxSize.Y)/2, thumbBoxSize.X, thumbBoxSize.Y, 210, 230, 255, 255);
else else
g->drawrect(screenPos.X+(Size.X-thumbBoxSize.X)/2, screenPos.Y+(Size.Y-21-thumbBoxSize.Y)/2, thumbBoxSize.X, thumbBoxSize.Y, 180, 180, 180, 255); g->drawrect(screenPos.X+(Size.X-thumbBoxSize.X)/2, screenPos.Y+(Size.Y-21-thumbBoxSize.Y)/2, thumbBoxSize.X, thumbBoxSize.Y, 180, 180, 180, 255);
if(isMouseInside) if (isMouseInside)
{ {
g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255); g->drawtext(screenPos.X+(Size.X-Graphics::textwidth((char *)name.c_str()))/2, screenPos.Y+Size.Y - 21, name, 255, 255, 255, 255);
} }

View File

@ -5,18 +5,18 @@ using namespace ui;
ScrollPanel::ScrollPanel(Point position, Point size): ScrollPanel::ScrollPanel(Point position, Point size):
Panel(position, size), Panel(position, size),
scrollBarWidth(0),
maxOffset(0, 0), maxOffset(0, 0),
offsetX(0), offsetX(0),
offsetY(0), offsetY(0),
yScrollVel(0.0f), yScrollVel(0.0f),
xScrollVel(0.0f), xScrollVel(0.0f),
scrollBarWidth(0),
isMouseInsideScrollbar(false), isMouseInsideScrollbar(false),
isMouseInsideScrollbarArea(false), isMouseInsideScrollbarArea(false),
scrollbarClickLocation(0),
scrollbarSelected(false), scrollbarSelected(false),
scrollbarInitialYOffset(0), scrollbarInitialYOffset(0),
scrollbarInitialYClick(0) scrollbarInitialYClick(0),
scrollbarClickLocation(0)
{ {
} }
@ -135,7 +135,6 @@ void ScrollPanel::XTick(float dt)
int oldOffsetY = offsetY; int oldOffsetY = offsetY;
offsetY += yScrollVel; offsetY += yScrollVel;
int oldOffsetX = offsetX;
offsetX += xScrollVel; offsetX += xScrollVel;
yScrollVel*=0.98f; yScrollVel*=0.98f;

View File

@ -25,7 +25,6 @@ void Slider::updatePosition(int position)
float fPosition = position-3; float fPosition = position-3;
float fSize = Size.X-6; float fSize = Size.X-6;
float fSteps = sliderSteps;
float fSliderPosition = (fPosition/fSize)*sliderSteps;//position;//((x-3)/(Size.X-6))*sliderSteps; float fSliderPosition = (fPosition/fSize)*sliderSteps;//position;//((x-3)/(Size.X-6))*sliderSteps;
@ -67,7 +66,7 @@ void Slider::OnMouseUp(int x, int y, unsigned button)
void Slider::SetColour(Colour col1, Colour col2) void Slider::SetColour(Colour col1, Colour col2)
{ {
pixel pix[2] = {PIXRGB(col1.Red, col1.Green, col1.Blue), PIXRGB(col2.Red, col2.Green, col2.Blue)}; pixel pix[2] = {(pixel)PIXRGB(col1.Red, col1.Green, col1.Blue), (pixel)PIXRGB(col2.Red, col2.Green, col2.Blue)};
float fl[2] = {0.0f, 1.0f}; float fl[2] = {0.0f, 1.0f};
if(bgGradient) if(bgGradient)
free(bgGradient); free(bgGradient);

View File

@ -12,15 +12,15 @@ using namespace ui;
Textbox::Textbox(Point position, Point size, std::string textboxText, std::string textboxPlaceholder): Textbox::Textbox(Point position, Point size, std::string textboxText, std::string textboxPlaceholder):
Label(position, size, ""), Label(position, size, ""),
actionCallback(NULL), ReadOnly(false),
masked(false),
border(true),
mouseDown(false),
limit(std::string::npos),
inputType(All), inputType(All),
limit(std::string::npos),
keyDown(0), keyDown(0),
characterDown(0), characterDown(0),
ReadOnly(false) mouseDown(false),
masked(false),
border(true),
actionCallback(NULL)
{ {
placeHolder = textboxPlaceholder; placeHolder = textboxPlaceholder;
@ -135,10 +135,9 @@ void Textbox::TabFocus()
void Textbox::cutSelection() void Textbox::cutSelection()
{ {
std::string newText = ClipboardPull(); if (HasSelection())
if(HasSelection())
{ {
if(getLowerSelectionBound() < 0 || getHigherSelectionBound() > backingText.length()) if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length())
return; return;
ClipboardPush((char*)backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()).c_str()); ClipboardPush((char*)backingText.substr(getLowerSelectionBound(), getHigherSelectionBound()-getLowerSelectionBound()).c_str());
backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound());
@ -191,7 +190,7 @@ void Textbox::pasteIntoSelection()
std::string newText = ClipboardPull(); std::string newText = ClipboardPull();
if(HasSelection()) if(HasSelection())
{ {
if(getLowerSelectionBound() < 0 || getHigherSelectionBound() > backingText.length()) if(getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length())
return; return;
backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound());
cursor = getLowerSelectionBound(); cursor = getLowerSelectionBound();
@ -288,12 +287,12 @@ bool Textbox::CharacterValid(Uint16 character)
void Textbox::Tick(float dt) void Textbox::Tick(float dt)
{ {
Label::Tick(dt); Label::Tick(dt);
if(!IsFocused()) if (!IsFocused())
{ {
keyDown = 0; keyDown = 0;
characterDown = 0; characterDown = 0;
} }
if((keyDown || characterDown) && repeatTime <= gettime()) if ((keyDown || characterDown) && repeatTime <= gettime())
{ {
OnVKeyPress(keyDown, characterDown, false, false, false); OnVKeyPress(keyDown, characterDown, false, false, false);
repeatTime = gettime()+30; repeatTime = gettime()+30;
@ -356,24 +355,24 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
ClearSelection(); ClearSelection();
break; break;
case KEY_RIGHT: case KEY_RIGHT:
if(cursor < backingText.length()) if (cursor < (int)backingText.length())
cursor++; cursor++;
ClearSelection(); ClearSelection();
break; break;
case KEY_DELETE: case KEY_DELETE:
if(ReadOnly) if(ReadOnly)
break; break;
if(HasSelection()) if (HasSelection())
{ {
if(getLowerSelectionBound() < 0 || getHigherSelectionBound() > backingText.length()) if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length())
return; return;
backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound());
cursor = getLowerSelectionBound(); cursor = getLowerSelectionBound();
changed = true; changed = true;
} }
else if(backingText.length() && cursor < backingText.length()) else if (backingText.length() && cursor < (int)backingText.length())
{ {
if(ctrl) if (ctrl)
backingText.erase(cursor, backingText.length()-cursor); backingText.erase(cursor, backingText.length()-cursor);
else else
backingText.erase(cursor, 1); backingText.erase(cursor, 1);
@ -382,19 +381,19 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
ClearSelection(); ClearSelection();
break; break;
case KEY_BACKSPACE: case KEY_BACKSPACE:
if(ReadOnly) if (ReadOnly)
break; break;
if(HasSelection()) if (HasSelection())
{ {
if(getLowerSelectionBound() < 0 || getHigherSelectionBound() > backingText.length()) if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length())
return; return;
backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound());
cursor = getLowerSelectionBound(); cursor = getLowerSelectionBound();
changed = true; changed = true;
} }
else if(backingText.length() && cursor > 0) else if (backingText.length() && cursor > 0)
{ {
if(ctrl) if (ctrl)
{ {
backingText.erase(0, cursor); backingText.erase(0, cursor);
cursor = 0; cursor = 0;
@ -409,24 +408,24 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
ClearSelection(); ClearSelection();
break; break;
default: default:
if(CharacterValid(character) && !ReadOnly) if (CharacterValid(character) && !ReadOnly)
{ {
if(HasSelection()) if (HasSelection())
{ {
if(getLowerSelectionBound() < 0 || getHigherSelectionBound() > backingText.length()) if (getLowerSelectionBound() < 0 || getHigherSelectionBound() > (int)backingText.length())
return; return;
backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound()); backingText.erase(backingText.begin()+getLowerSelectionBound(), backingText.begin()+getHigherSelectionBound());
cursor = getLowerSelectionBound(); cursor = getLowerSelectionBound();
} }
int regionWidth = Size.X; int regionWidth = Size.X;
if(Appearance.icon) if( Appearance.icon)
regionWidth -= 13; regionWidth -= 13;
regionWidth -= Appearance.Margin.Left; regionWidth -= Appearance.Margin.Left;
regionWidth -= Appearance.Margin.Right; regionWidth -= Appearance.Margin.Right;
if((limit==std::string::npos || backingText.length() < limit) && (Graphics::textwidth((char*)std::string(backingText+char(character)).c_str()) <= regionWidth || multiline || limit!=std::string::npos)) if ((limit==std::string::npos || backingText.length() < limit) && (Graphics::textwidth((char*)std::string(backingText+char(character)).c_str()) <= regionWidth || multiline || limit!=std::string::npos))
{ {
if(cursor == backingText.length()) if (cursor == (int)backingText.length())
{ {
backingText += character; backingText += character;
} }
@ -442,22 +441,22 @@ void Textbox::OnVKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
break; break;
} }
} }
catch(std::out_of_range &e) catch (std::out_of_range &e)
{ {
cursor = 0; cursor = 0;
backingText = ""; backingText = "";
} }
if(inputType == Number) if (inputType == Number)
{ {
//Remove extra preceding 0's //Remove extra preceding 0's
while(backingText[0] == '0' && backingText.length()>1) while(backingText[0] == '0' && backingText.length()>1)
backingText.erase(backingText.begin()); backingText.erase(backingText.begin());
} }
if(cursor > backingText.length()) if (cursor > (int)backingText.length())
cursor = backingText.length(); cursor = backingText.length();
if(changed) if (changed)
{ {
if(masked) if (masked)
{ {
std::string maskedText = std::string(backingText); std::string maskedText = std::string(backingText);
std::fill(maskedText.begin(), maskedText.end(), '\x8D'); std::fill(maskedText.begin(), maskedText.end(), '\x8D');

View File

@ -59,7 +59,7 @@ public:
protected: protected:
ValidInput inputType; ValidInput inputType;
size_t limit; size_t limit;
int repeatTime; unsigned long repeatTime;
int keyDown; int keyDown;
Uint16 characterDown; Uint16 characterDown;
bool mouseDown; bool mouseDown;

View File

@ -10,16 +10,16 @@ using namespace ui;
Window::Window(Point _position, Point _size): Window::Window(Point _position, Point _size):
Position(_position), Position(_position),
Size(_size), Size(_size),
focusedComponent_(NULL),
AllowExclusiveDrawing(true), AllowExclusiveDrawing(true),
okayButton(NULL),
cancelButton(NULL),
focusedComponent_(NULL),
#ifdef DEBUG
debugMode(false),
#endif
halt(false), halt(false),
destruct(false), destruct(false),
stop(false), stop(false)
cancelButton(NULL),
okayButton(NULL)
#ifdef DEBUG
,debugMode(false)
#endif
{ {
} }

View File

@ -102,14 +102,14 @@ enum ChromeStyle
Component* focusedComponent_; Component* focusedComponent_;
ChromeStyle chrome; ChromeStyle chrome;
#ifdef DEBUG
bool debugMode;
#endif
//These controls allow a component to call the destruction of the Window inside an event (called by the Window) //These controls allow a component to call the destruction of the Window inside an event (called by the Window)
void finalise(); void finalise();
bool halt; bool halt;
bool destruct; bool destruct;
bool stop; bool stop;
#ifdef DEBUG
bool debugMode;
#endif
}; };

View File

@ -64,7 +64,7 @@ void LocalBrowserController::removeSelectedC()
RemoveSavesTask(LocalBrowserController * c, std::vector<std::string> saves_) : c(c) { saves = saves_; } RemoveSavesTask(LocalBrowserController * c, std::vector<std::string> saves_) : c(c) { saves = saves_; }
virtual bool doWork() virtual bool doWork()
{ {
for(int i = 0; i < saves.size(); i++) for (size_t i = 0; i < saves.size(); i++)
{ {
std::stringstream saveName; std::stringstream saveName;
saveName << "Deleting stamp [" << saves[i] << "] ..."; saveName << "Deleting stamp [" << saves[i] << "] ...";
@ -76,6 +76,7 @@ void LocalBrowserController::removeSelectedC()
} }
virtual void after() virtual void after()
{ {
Client::Ref().updateStamps();
c->RefreshSavesList(); c->RefreshSavesList();
} }
}; };
@ -131,6 +132,12 @@ void LocalBrowserController::PrevPage()
browserModel->UpdateSavesList(browserModel->GetPageNum()-1); browserModel->UpdateSavesList(browserModel->GetPageNum()-1);
} }
void LocalBrowserController::SetPage(int page)
{
if (page != browserModel->GetPageNum() && page > 0 && page <= browserModel->GetPageCount())
browserModel->UpdateSavesList(page);
}
void LocalBrowserController::Update() void LocalBrowserController::Update()
{ {
if(browserModel->GetSave()) if(browserModel->GetSave())

View File

@ -28,6 +28,7 @@ public:
void SetMoveToFront(bool move); void SetMoveToFront(bool move);
void NextPage(); void NextPage();
void PrevPage(); void PrevPage();
void SetPage(int page);
void Update(); void Update();
void Exit(); void Exit();
virtual ~LocalBrowserController(); virtual ~LocalBrowserController();

View File

@ -28,15 +28,16 @@ void LocalBrowserModel::AddObserver(LocalBrowserView * observer)
void LocalBrowserModel::notifySavesListChanged() void LocalBrowserModel::notifySavesListChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifySavesListChanged(this); observers[i]->NotifySavesListChanged(this);
observers[i]->NotifyPageChanged(this);
} }
} }
void LocalBrowserModel::notifyPageChanged() void LocalBrowserModel::notifyPageChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyPageChanged(this); observers[i]->NotifyPageChanged(this);
} }
@ -79,10 +80,10 @@ void LocalBrowserModel::UpdateSavesList(int pageNumber)
stampIDs = Client::Ref().GetStamps((pageNumber-1)*20, 20); stampIDs = Client::Ref().GetStamps((pageNumber-1)*20, 20);
for(int i = 0; i<stampIDs.size(); i++) for (size_t i = 0; i < stampIDs.size(); i++)
{ {
SaveFile * tempSave = Client::Ref().GetStamp(stampIDs[i]); SaveFile * tempSave = Client::Ref().GetStamp(stampIDs[i]);
if(tempSave) if (tempSave)
{ {
savesList.push_back(tempSave); savesList.push_back(tempSave);
} }
@ -102,9 +103,9 @@ int LocalBrowserModel::GetPageCount()
void LocalBrowserModel::SelectSave(std::string stampID) void LocalBrowserModel::SelectSave(std::string stampID)
{ {
for(int i = 0; i < selected.size(); i++) for (size_t i = 0; i < selected.size(); i++)
{ {
if(selected[i]==stampID) if (selected[i] == stampID)
{ {
return; return;
} }
@ -117,9 +118,9 @@ void LocalBrowserModel::DeselectSave(std::string stampID)
{ {
bool changed = false; bool changed = false;
restart: restart:
for(int i = 0; i < selected.size(); i++) for (size_t i = 0; i < selected.size(); i++)
{ {
if(selected[i]==stampID) if (selected[i] == stampID)
{ {
selected.erase(selected.begin()+i); selected.erase(selected.begin()+i);
changed = true; changed = true;
@ -132,7 +133,7 @@ restart:
void LocalBrowserModel::notifySelectedChanged() void LocalBrowserModel::notifySelectedChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
LocalBrowserView* cObserver = observers[i]; LocalBrowserView* cObserver = observers[i];
cObserver->NotifySelectedChanged(this); cObserver->NotifySelectedChanged(this);

View File

@ -1,5 +1,6 @@
#include <sstream> #include <sstream>
#include "client/Client.h" #include "client/Client.h"
#include "Format.h"
#include "LocalBrowserView.h" #include "LocalBrowserView.h"
#include "gui/interface/Button.h" #include "gui/interface/Button.h"
@ -15,17 +16,39 @@
#include "LocalBrowserModelException.h" #include "LocalBrowserModelException.h"
LocalBrowserView::LocalBrowserView(): LocalBrowserView::LocalBrowserView():
ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)) ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)),
changed(false),
lastChanged(0),
pageCount(0)
{ {
nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next \x95"); nextButton = new ui::Button(ui::Point(WINDOWW-52, WINDOWH-18), ui::Point(50, 16), "Next \x95");
previousButton = new ui::Button(ui::Point(1, WINDOWH-18), ui::Point(50, 16), "\x96 Prev"); previousButton = new ui::Button(ui::Point(1, WINDOWH-18), ui::Point(50, 16), "\x96 Prev");
undeleteButton = new ui::Button(ui::Point(WINDOWW-122, WINDOWH-18), ui::Point(60, 16), "Rescan"); undeleteButton = new ui::Button(ui::Point(WINDOWW-122, WINDOWH-18), ui::Point(60, 16), "Rescan");
infoLabel = new ui::Label(ui::Point(51, WINDOWH-18), ui::Point(WINDOWW-102, 16), "Loading...");
AddComponent(infoLabel);
AddComponent(nextButton); AddComponent(nextButton);
AddComponent(previousButton); AddComponent(previousButton);
AddComponent(undeleteButton); AddComponent(undeleteButton);
class PageNumAction : public ui::TextboxAction
{
LocalBrowserView * v;
public:
PageNumAction(LocalBrowserView * _v) { v = _v; }
void TextChangedCallback(ui::Textbox * sender)
{
v->textChanged();
}
};
pageTextbox = new ui::Textbox(ui::Point(283, WINDOWH-18), ui::Point(41, 16), "");
pageTextbox->SetActionCallback(new PageNumAction(this));
pageTextbox->SetInputType(ui::Textbox::Number);
pageLabel = new ui::Label(ui::Point(0, WINDOWH-18), ui::Point(30, 16), "Page"); //page [TEXTBOX] of y
pageLabel->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
pageCountLabel = new ui::Label(ui::Point(WINDOWW/2+6, WINDOWH-18), ui::Point(50, 16), "");
pageCountLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
AddComponent(pageLabel);
AddComponent(pageCountLabel);
AddComponent(pageTextbox);
class NextPageAction : public ui::ButtonAction class NextPageAction : public ui::ButtonAction
{ {
LocalBrowserView * v; LocalBrowserView * v;
@ -83,16 +106,56 @@ LocalBrowserView::LocalBrowserView():
AddComponent(removeSelected); AddComponent(removeSelected);
} }
void LocalBrowserView::textChanged()
{
int num = format::StringToNumber<int>(pageTextbox->GetText());
if (num < 0) //0 is allowed so that you can backspace the 1
pageTextbox->SetText("1");
else if (num > pageCount)
pageTextbox->SetText(format::NumberToString(pageCount));
changed = true;
#ifdef USE_SDL
lastChanged = SDL_GetTicks()+600;
#endif
}
void LocalBrowserView::OnTick(float dt) void LocalBrowserView::OnTick(float dt)
{ {
c->Update(); c->Update();
#ifdef USE_SDL
if (changed && lastChanged < SDL_GetTicks())
{
changed = false;
c->SetPage(std::max(format::StringToNumber<int>(pageTextbox->GetText()), 0));
}
#endif
} }
void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender) void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender)
{ {
pageCount = sender->GetPageCount();
if (!sender->GetSavesList().size()) //no saves
{
pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = false;
}
else
{
std::stringstream pageInfo; std::stringstream pageInfo;
pageInfo << "Page " << sender->GetPageNum() << " of " << sender->GetPageCount(); pageInfo << "of " << pageCount;
infoLabel->SetText(pageInfo.str()); pageCountLabel->SetText(pageInfo.str());
int width = Graphics::textwidth(pageInfo.str().c_str());
pageLabel->Position.X = WINDOWW/2-width-20;
pageTextbox->Position.X = WINDOWW/2-width+11;
pageTextbox->Size.X = width-4;
//pageCountLabel->Position.X = WINDOWW/2+6;
pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = true;
pageInfo.str("");
pageInfo << sender->GetPageNum();
pageTextbox->SetText(pageInfo.str());
}
if(sender->GetPageNum() == 1) if(sender->GetPageNum() == 1)
{ {
previousButton->Visible = false; previousButton->Visible = false;
@ -113,12 +176,11 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender)
void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender) void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
{ {
int i = 0;
int buttonWidth, buttonHeight, saveX = 0, saveY = 0, savesX = 5, savesY = 4, buttonPadding = 2; int buttonWidth, buttonHeight, saveX = 0, saveY = 0, savesX = 5, savesY = 4, buttonPadding = 2;
int buttonAreaWidth, buttonAreaHeight, buttonXOffset, buttonYOffset; int buttonAreaWidth, buttonAreaHeight, buttonXOffset, buttonYOffset;
vector<SaveFile*> saves = sender->GetSavesList(); vector<SaveFile*> saves = sender->GetSavesList();
for(i = 0; i < stampButtons.size(); i++) for (size_t i = 0; i < stampButtons.size(); i++)
{ {
RemoveComponent(stampButtons[i]); RemoveComponent(stampButtons[i]);
delete stampButtons[i]; delete stampButtons[i];
@ -146,7 +208,7 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
v->c->Selected(sender->GetSaveFile()->GetName(), sender->GetSelected()); v->c->Selected(sender->GetSaveFile()->GetName(), sender->GetSelected());
} }
}; };
for(i = 0; i < saves.size(); i++) for (size_t i = 0; i < saves.size(); i++)
{ {
if(saveX == savesX) if(saveX == savesX)
{ {
@ -174,12 +236,12 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
void LocalBrowserView::NotifySelectedChanged(LocalBrowserModel * sender) void LocalBrowserView::NotifySelectedChanged(LocalBrowserModel * sender)
{ {
vector<std::string> selected = sender->GetSelected(); vector<std::string> selected = sender->GetSelected();
for(int j = 0; j < stampButtons.size(); j++) for (size_t j = 0; j < stampButtons.size(); j++)
{ {
stampButtons[j]->SetSelected(false); stampButtons[j]->SetSelected(false);
for(int i = 0; i < selected.size(); i++) for (size_t i = 0; i < selected.size(); i++)
{ {
if(stampButtons[j]->GetSaveFile()->GetName()==selected[i]) if (stampButtons[j]->GetSaveFile()->GetName()==selected[i])
stampButtons[j]->SetSelected(true); stampButtons[j]->SetSelected(true);
} }
} }
@ -216,6 +278,4 @@ void LocalBrowserView::OnKeyRelease(int key, Uint16 character, bool shift, bool
c->SetMoveToFront(true); c->SetMoveToFront(true);
} }
LocalBrowserView::~LocalBrowserView() { LocalBrowserView::~LocalBrowserView() { }
}

View File

@ -7,6 +7,7 @@
namespace ui namespace ui
{ {
class Label; class Label;
class Textbox;
class Button; class Button;
class SaveButton; class SaveButton;
} }
@ -19,13 +20,20 @@ class LocalBrowserView: public ui::Window {
ui::Button * undeleteButton; ui::Button * undeleteButton;
ui::Button * previousButton; ui::Button * previousButton;
ui::Button * nextButton; ui::Button * nextButton;
ui::Label * infoLabel; ui::Label * pageLabel;
ui::Label * pageCountLabel;
ui::Textbox * pageTextbox;
ui::Button * removeSelected; ui::Button * removeSelected;
void textChanged();
bool changed;
unsigned int lastChanged;
int pageCount;
public: public:
LocalBrowserView(); LocalBrowserView();
//virtual void OnDraw(); //virtual void OnDraw();
virtual void OnTick(float dt); virtual void OnTick(float dt);
void AttachController(LocalBrowserController * c_) { c = c_; }; void AttachController(LocalBrowserController * c_) { c = c_; }
void NotifyPageChanged(LocalBrowserModel * sender); void NotifyPageChanged(LocalBrowserModel * sender);
void NotifySavesListChanged(LocalBrowserModel * sender); void NotifySavesListChanged(LocalBrowserModel * sender);
void NotifySelectedChanged(LocalBrowserModel * sender); void NotifySelectedChanged(LocalBrowserModel * sender);

View File

@ -20,7 +20,7 @@ void LoginModel::Login(string username, string password)
break; break;
case LoginError: case LoginError:
statusText = "Error: " + Client::Ref().GetLastError(); statusText = "Error: " + Client::Ref().GetLastError();
int banStart = statusText.find(". Ban expire in"); //TODO: temporary, remove this when the ban message is fixed size_t banStart = statusText.find(". Ban expire in"); //TODO: temporary, remove this when the ban message is fixed
if (banStart != statusText.npos) if (banStart != statusText.npos)
statusText.replace(banStart, 15, ". Login at http://powdertoy.co.uk in order to see the full ban reason. Ban expires in"); statusText.replace(banStart, 15, ". Login at http://powdertoy.co.uk in order to see the full ban reason. Ban expires in");
break; break;
@ -50,7 +50,7 @@ bool LoginModel::GetStatus()
void LoginModel::notifyStatusChanged() void LoginModel::notifyStatusChanged()
{ {
for(int i = 0; i < observers.size(); i++) for (size_t i = 0; i < observers.size(); i++)
{ {
observers[i]->NotifyStatusChanged(this); observers[i]->NotifyStatusChanged(this);
} }

View File

@ -33,9 +33,9 @@ LoginView::LoginView():
loginButton(new ui::Button(ui::Point(200-100, 87-17), ui::Point(100, 17), "Sign in")), loginButton(new ui::Button(ui::Point(200-100, 87-17), ui::Point(100, 17), "Sign in")),
cancelButton(new ui::Button(ui::Point(0, 87-17), ui::Point(101, 17), "Sign Out")), cancelButton(new ui::Button(ui::Point(0, 87-17), ui::Point(101, 17), "Sign Out")),
titleLabel(new ui::Label(ui::Point(4, 5), ui::Point(200-16, 16), "Server login")), titleLabel(new ui::Label(ui::Point(4, 5), ui::Point(200-16, 16), "Server login")),
infoLabel(new ui::Label(ui::Point(8, 67), ui::Point(200-16, 16), "")),
usernameField(new ui::Textbox(ui::Point(8, 25), ui::Point(200-16, 17), Client::Ref().GetAuthUser().Username, "[username]")), usernameField(new ui::Textbox(ui::Point(8, 25), ui::Point(200-16, 17), Client::Ref().GetAuthUser().Username, "[username]")),
passwordField(new ui::Textbox(ui::Point(8, 46), ui::Point(200-16, 17), "", "[password]")), passwordField(new ui::Textbox(ui::Point(8, 46), ui::Point(200-16, 17), "", "[password]")),
infoLabel(new ui::Label(ui::Point(8, 67), ui::Point(200-16, 16), "")),
targetSize(0, 0) targetSize(0, 0)
{ {
targetSize = Size; targetSize = Size;

View File

@ -16,13 +16,13 @@ class LoginController;
class LoginMode; class LoginMode;
class LoginView: public ui::Window { class LoginView: public ui::Window {
LoginController * c; LoginController * c;
ui::Point targetSize;
ui::Button * loginButton; ui::Button * loginButton;
ui::Button * cancelButton; ui::Button * cancelButton;
ui::Label * titleLabel; ui::Label * titleLabel;
ui::Label * infoLabel; ui::Label * infoLabel;
ui::Textbox * usernameField; ui::Textbox * usernameField;
ui::Textbox * passwordField; ui::Textbox * passwordField;
ui::Point targetSize;
public: public:
class LoginAction; class LoginAction;
class CancelAction; class CancelAction;

View File

@ -2,8 +2,8 @@
#include "gui/dialogues/ErrorMessage.h" #include "gui/dialogues/ErrorMessage.h"
OptionsController::OptionsController(GameModel * gModel_, ControllerCallback * callback_): OptionsController::OptionsController(GameModel * gModel_, ControllerCallback * callback_):
callback(callback_),
gModel(gModel_), gModel(gModel_),
callback(callback_),
HasExited(false) HasExited(false)
{ {
view = new OptionsView(); view = new OptionsView();
@ -44,9 +44,9 @@ void OptionsController::SetAirMode(int airMode)
model->SetAirMode(airMode); model->SetAirMode(airMode);
} }
void OptionsController::SetEdgeMode(int airMode) void OptionsController::SetEdgeMode(int edgeMode)
{ {
model->SetEdgeMode(airMode); model->SetEdgeMode(edgeMode);
} }
void OptionsController::SetFullscreen(bool fullscreen) void OptionsController::SetFullscreen(bool fullscreen)

View File

@ -23,7 +23,7 @@ public:
void SetWaterEqualisation(bool state); void SetWaterEqualisation(bool state);
void SetGravityMode(int gravityMode); void SetGravityMode(int gravityMode);
void SetAirMode(int airMode); void SetAirMode(int airMode);
void SetEdgeMode(int airMode); void SetEdgeMode(int edgeMode);
void SetFullscreen(bool fullscreen); void SetFullscreen(bool fullscreen);
void SetScale(bool scale); void SetScale(bool scale);
void SetFastQuit(bool fastquit); void SetFastQuit(bool fastquit);

Some files were not shown because too many files have changed in this diff Show More