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*/*
stamps/*
Saves/*
scripts/*
generated/*
includes/*
generate

1090
SConscript

File diff suppressed because it is too large Load Diff

View File

@ -2,7 +2,7 @@
#define FONT_H_CHECK
#define FONT_H 10
#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,
@ -295,7 +295,7 @@ short font_ptrs[] = {
0x11A1, 0x11B1, 0x11C1, 0x11D1, 0x11E1, 0x11F1, 0x1201, 0x1211,
};
#else
extern char font_data[];
extern unsigned char font_data[];
extern short font_ptrs[];
#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
*/
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,
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,
@ -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,
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,
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,

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(" "))
classDirectives = []
usedIDs = []
for d in directives:
if d[0] == "ElementClass":
d[3] = int(d[3])
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])
@ -168,12 +172,16 @@ def generateTools(toolFiles, outputCpp, outputH):
directives.append(match.split(" "))
classDirectives = []
usedIDs = []
for d in directives:
if d[0] == "ToolClass":
toolClasses[d[1]] = []
toolHeader += "#define %s %s\n" % (d[2], d[3])
d[3] = int(d[3])
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:
if d[0] == "ToolHeader":

View File

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

View File

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

View File

@ -20,6 +20,7 @@
#include <mach-o/dyld.h>
#endif
const static char hex[] = "0123456789ABCDEF";
std::string URLEscape(std::string source)
{
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;
}
for(i = 0; i < strlen(text); i++){
if(! (text[i]>=' ' && text[i]<127)){
for (unsigned i = 0; i < strlen(text); i++)
{
if (! (text[i]>=' ' && text[i]<127))
{
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 match=0,r;
int r;
if (str[0]=='{' && (str[1]=='c' || str[1]=='t' || str[1]=='b'))
{
const char* p=str+2;

View File

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

View File

@ -78,25 +78,43 @@ int main(int argc, char *argv[])
engine = &ui::Engine::Ref();
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();
Renderer * ren = new Renderer(ui::Engine::Ref().g, sim);
sim->Load(gameSave);
//Render save
ren->decorations_enable = true;
ren->blackDecorations = true;
int frame = 15;
while(frame)
if (gameSave)
{
frame--;
ren->render_parts();
ren->render_fire();
ren->clearScreen(1.0f);
sim->Load(gameSave);
//Render save
ren->decorations_enable = true;
ren->blackDecorations = true;
int frame = 15;
while(frame)
{
frame--;
ren->render_parts();
ren->render_fire();
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();

View File

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

View File

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

View File

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

View File

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

View File

@ -67,10 +67,10 @@ void writeUserPreferences(const char * prefData);
Client::Client():
authUser(0, ""),
updateAvailable(false),
messageOfTheDay(""),
versionCheckRequest(NULL),
messageOfTheDay("")
updateAvailable(false),
authUser(0, "")
{
int i = 0;
for(i = 0; i < THUMB_CACHE_SIZE; i++)
@ -126,7 +126,10 @@ Client::Client():
#ifndef MACOSX
configFile.close();
#endif
firstRun = false;
}
else
firstRun = true;
}
void Client::Initialise(std::string proxyString)
@ -173,6 +176,11 @@ void Client::Initialise(std::string proxyString)
}
}
bool Client::IsFirstRun()
{
return firstRun;
}
bool Client::DoInstallation()
{
#if defined(WIN)
@ -344,7 +352,18 @@ bool Client::DoInstallation()
#elif defined(LIN)
#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;
const char *mimedata =
"<?xml version=\"1.0\"?>\n"
@ -367,16 +386,14 @@ bool Client::DoInstallation()
"Name=Powder Toy\n"
"Comment=Physics sandbox game\n"
"MimeType=x-scheme-handler/ptsave;\n"
"NoDisplay=true\n";
char *protocolfiledata = (char *)malloc(strlen(protocolfiledata_tmp)+strlen(currentfilename)+100);
strcpy(protocolfiledata, protocolfiledata_tmp);
strappend(protocolfiledata, "Exec=");
strappend(protocolfiledata, currentfilename);
strappend(protocolfiledata, " ptsave %u\n");
"NoDisplay=true\n"
"Categories=Game\n";
std::stringstream protocolfiledata;
protocolfiledata << protocolfiledata_tmp << "Exec=" << filename <<" ptsave %u\nPath=" << pathname << "\n";
f = fopen("powdertoy-tpt-ptsave.desktop", "wb");
if (!f)
return 0;
fwrite(protocolfiledata, 1, strlen(protocolfiledata), f);
fwrite(protocolfiledata.str().c_str(), 1, strlen(protocolfiledata.str().c_str()), f);
fclose(f);
system("xdg-desktop-menu install powdertoy-tpt-ptsave.desktop");
@ -386,16 +403,14 @@ bool Client::DoInstallation()
"Name=Powder Toy\n"
"Comment=Physics sandbox game\n"
"MimeType=application/vnd.powdertoy.save;\n"
"NoDisplay=true\n";
char *desktopfiledata = (char *)malloc(strlen(desktopfiledata_tmp)+strlen(currentfilename)+100);
strcpy(desktopfiledata, desktopfiledata_tmp);
strappend(desktopfiledata, "Exec=");
strappend(desktopfiledata, currentfilename);
strappend(desktopfiledata, " open %f\n");
"NoDisplay=true\n"
"Categories=Game\n";
std::stringstream desktopfiledata;
desktopfiledata << desktopfiledata_tmp << "Exec=" << filename <<" open %f\nPath=" << pathname << "\n";
f = fopen("powdertoy-tpt.desktop", "wb");
if (!f)
return 0;
fwrite(desktopfiledata, 1, strlen(desktopfiledata), f);
fwrite(desktopfiledata.str().c_str(), 1, strlen(desktopfiledata.str().c_str()), f);
fclose(f);
system("xdg-mime install powdertoy-save.xml");
system("xdg-desktop-menu install powdertoy-tpt.desktop");
@ -482,7 +497,7 @@ std::vector<std::string> Client::DirectorySearch(std::string directory, std::str
#endif
return std::vector<std::string>();
}
while(directoryEntry = readdir(directoryHandle))
while ((directoryEntry = readdir(directoryHandle)))
{
std::string currentFileName = std::string(directoryEntry->d_name);
if(currentFileName.length()>4)
@ -498,7 +513,7 @@ std::vector<std::string> Client::DirectorySearch(std::string directory, std::str
bool extensionMatch = !extensions.size();
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)
{
extensionMatch = true;
@ -687,7 +702,7 @@ void Client::Tick()
//Notifications from server
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 notificationText = notificationsArray[j]["Text"];
@ -705,31 +720,25 @@ void Client::Tick()
#ifndef IGNORE_UPDATES
//Check for updates
json::Object versions = objDocument["Updates"];
#if not defined(BETA) && not defined(SNAPSHOT)
json::Object stableVersion = versions["Stable"];
json::Object betaVersion = versions["Beta"];
json::Object snapshotVersion = versions["Snapshot"];
json::Number stableMajor = stableVersion["Major"];
json::Number stableMinor = stableVersion["Minor"];
json::Number stableBuild = stableVersion["Build"];
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)
{
updateAvailable = true;
updateInfo = UpdateInfo(stableMajor.Value(), stableMinor.Value(), stableBuild.Value(), stableFile.Value(), UpdateInfo::Stable);
}
#endif
#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)
{
updateAvailable = true;
@ -738,6 +747,9 @@ void Client::Tick()
#endif
#ifdef SNAPSHOT
json::Object snapshotVersion = versions["Snapshot"];
json::Number snapshotSnapshot = snapshotVersion["Snapshot"];
json::String snapshotFile = snapshotVersion["File"];
if(snapshotSnapshot.Value() > SNAPSHOT_ID)
{
updateAvailable = true;
@ -887,7 +899,7 @@ User Client::GetAuthUser()
RequestStatus Client::UploadSave(SaveInfo & save)
{
lastError = "";
int gameDataLength;
unsigned int gameDataLength;
char * gameData = NULL;
int dataStatus;
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 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;
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)
{
std::string stampFile = std::string(STAMPS_DIR PATH_SEP + stampID + ".stm");
SaveFile * file = new SaveFile(stampID);
if (!FileExists(stampFile))
stampFile = stampID;
if(FileExists(stampFile))
if (FileExists(stampFile))
{
SaveFile * file = new SaveFile(stampID);
try
{
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;
}
return file;
}
else
{
return NULL;
}
return file;
}
void Client::DeleteStamp(std::string stampID)
@ -1049,7 +1057,7 @@ std::string Client::AddStamp(GameSave * saveData)
MakeDirectory(STAMPS_DIR);
int gameDataLength;
unsigned int gameDataLength;
char * gameData = saveData->Serialise(gameDataLength);
std::ofstream stampStream;
@ -1089,7 +1097,7 @@ void Client::RescanStamps()
if (directory != NULL)
{
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)
{
@ -1110,15 +1118,18 @@ int Client::GetStampsCount()
std::vector<std::string> Client::GetStamps(int start, int count)
{
if(start+count > stampIDs.size()) {
if(start > stampIDs.size())
int size = (int)stampIDs.size();
if (start+count > size)
{
if(start > size)
return std::vector<std::string>();
count = stampIDs.size()-start;
count = size-start;
}
std::vector<std::string> stampRange;
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)
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 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;
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;
const char *const postNames[] = { "Username", "Hash", NULL };
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);
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::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 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 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);
}
else
@ -1575,7 +1586,7 @@ RequestStatus Client::ReportSave(int saveID, std::string message)
const char *const postNames[] = { "Reason", NULL };
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);
}
else
@ -1673,6 +1684,36 @@ failure:
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)
{
lastError = "";
@ -1720,7 +1761,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate)
json::Array tagsArray = objDocument["Tags"];
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];
tempTags.push_back(tempTag.Value());
@ -1796,7 +1837,7 @@ RequestBroker::Request * Client::GetSaveAsync(int saveID, int saveDate)
json::Array tagsArray = objDocument["Tags"];
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];
tempTags.push_back(tempTag.Value());
@ -1889,7 +1930,7 @@ RequestBroker::Request * Client::GetCommentsAsync(int saveID, int start, int cou
json::Array commentsArray;
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::String tempUsername = commentsArray[j]["Username"];
@ -1942,7 +1983,7 @@ std::vector<SaveComment*> * Client::GetComments(int saveID, int start, int count
json::Array commentsArray;
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::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"];
resultCount = tempCount.Value();
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::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"];
resultCount = tempCount.Value();
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 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>();
for(int j = 0; j < tagsArray.Size(); j++)
for (size_t j = 0; j < tagsArray.Size(); j++)
{
json::String tempTag = tagsArray[j];
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>();
for(int j = 0; j < tagsArray.Size(); j++)
for (size_t j = 0; j < tagsArray.Size(); j++)
{
json::String tempTag = tagsArray[j];
tags->push_back(tempTag.Value());

View File

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

View File

@ -18,15 +18,16 @@ GameSave::GameSave(GameSave & save) :
waterEEnabled(save.waterEEnabled),
legacyEnable(save.legacyEnable),
gravityEnable(save.gravityEnable),
aheatEnable(save.aheatEnable),
paused(save.paused),
gravityMode(save.gravityMode),
aheatEnable(save.aheatEnable),
airMode(save.airMode),
edgeMode(save.edgeMode),
signs(save.signs),
palette(save.palette),
expanded(save.expanded),
hasOriginalData(save.hasOriginalData),
originalData(save.originalData),
palette(save.palette)
originalData(save.originalData)
{
blockMap = NULL;
blockMapPtr = NULL;
@ -179,6 +180,7 @@ void GameSave::Expand()
paused = false;
gravityMode = 0;
airMode = 0;
edgeMode = 0;
expanded = true;
read(&originalData[0], originalData.size());
}
@ -286,14 +288,14 @@ void GameSave::setSize(int newWidth, int newHeight)
std::vector<char> GameSave::Serialise()
{
int dataSize;
unsigned int dataSize;
char * data = Serialise(dataSize);
std::vector<char> dataVect(data, data+dataSize);
delete[] data;
return dataVect;
}
char * GameSave::Serialise(int & dataSize)
char * GameSave::Serialise(unsigned int & dataSize)
{
return serialiseOPS(dataSize);
}
@ -302,7 +304,7 @@ void GameSave::Transform(matrix2d transform, vector2d translate)
{
if(Collapsed())
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 cornerso[4];
// 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[2] = v2d_new(0,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]);
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];
// 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_add(m2d_multiply_v2d(transform,pos),translate);
@ -369,7 +371,7 @@ void GameSave::Transform(matrix2d transform, vector2d translate)
signs[i].x = nx;
signs[i].y = ny;
}
for (i=0; i<particlesCount; i++)
for (int i = 0; i < particlesCount; i++)
{
if (!particles[i].type) continue;
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 int inputDataLen = dataLength, bsonDataLen = 0, partsDataLen, partsPosDataLen, fanDataLen, wallDataLen, soapLinkDataLen;
unsigned partsCount = 0, *partsSimIndex = NULL;
int i, x, y, j;
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];
bson b;
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));
}
}
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)
{
palette.clear();
@ -704,15 +716,15 @@ void GameSave::readOPS(char * data, int dataLength)
//Read wall and fan data
if(wallData)
{
j = 0;
if(blockW * blockH > wallDataLen)
unsigned int j = 0;
if (blockW * blockH > wallDataLen)
{
fprintf(stderr, "Not enough wall data\n");
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])
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;
}
if (blockMap[y][x] < 0 || blockMap[y][x] >= UI_WALLCOUNT)
if (blockMap[y][x] >= UI_WALLCOUNT)
blockMap[y][x] = 0;
}
}
}
//Read particle data
if(partsData && partsPosData)
if (partsData && partsPosData)
{
int newIndex = 0, fieldDescriptor, tempTemp;
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");
goto fail;
@ -781,11 +792,12 @@ void GameSave::readOPS(char * data, int dataLength)
partsSimIndex = (unsigned int*)calloc(NPART, sizeof(unsigned));
partsCount = 0;
i = 0;
unsigned int i = 0;
unsigned int saved_x, saved_y, x, y;
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
posTotal = 0;
@ -793,10 +805,10 @@ void GameSave::readOPS(char * data, int dataLength)
posTotal |= partsPosData[partsPosDataIndex++]<<8;
posTotal |= partsPosData[partsPosDataIndex++];
//Put the next posTotal particles at this position
for (posCount=0; posCount<posTotal; posCount++)
for (posCount = 0; posCount < posTotal; posCount++)
{
particlesCount = newIndex+1;
if(newIndex>=NPART)
if (newIndex >= NPART)
{
goto fail;
}
@ -808,15 +820,13 @@ void GameSave::readOPS(char * data, int dataLength)
y = saved_y + fullY;
fieldDescriptor = partsData[i+1];
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]);
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;
//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);
particles[newIndex].type = PT_EMBR;
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;
case PT_PSTN:
if (savedVersion < 87 && particles[newIndex].ctype)
particles[newIndex].life = 1;
if (savedVersion < 91)
particles[newIndex].temp = 283.15;
break;
case PT_STKM:
case PT_STKM2:
@ -1008,6 +1020,13 @@ void GameSave::readOPS(char * data, int dataLength)
{
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
newIndex++;
@ -1016,13 +1035,13 @@ void GameSave::readOPS(char * data, int dataLength)
}
if (soapLinkData)
{
int soapLinkDataPos = 0;
for (i=0; i<partsCount; i++)
unsigned int soapLinkDataPos = 0;
for (unsigned int i = 0; i < partsCount; i++)
{
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
int linkedIndex = 0;
unsigned int linkedIndex = 0;
if (soapLinkDataPos+3 > soapLinkDataLen) break;
linkedIndex |= soapLinkData[soapLinkDataPos++]<<16;
linkedIndex |= soapLinkData[soapLinkDataPos++]<<8;
@ -1045,7 +1064,7 @@ void GameSave::readOPS(char * data, int dataLength)
if(tempSigns.size())
{
for (int i = 0; i < tempSigns.size(); i++)
for (size_t i = 0; i < tempSigns.size(); i++)
{
if(signs.size() == MAXSIGNS)
break;
@ -1072,9 +1091,9 @@ fin:
void GameSave::readPSv(char * data, int dataLength)
{
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 nf=0, new_format = 0, ttv = 0;
int new_format = 0, ttv = 0;
int *fp = (int *)malloc(NPART*sizeof(int));
std::vector<sign> tempSigns;
@ -1167,7 +1186,7 @@ void GameSave::readPSv(char * data, int dataLength)
setSize(bw, bh);
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;
bzStatusStr << bzStatus;
@ -1274,7 +1293,7 @@ void GameSave::readPSv(char * data, int dataLength)
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;
}
@ -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);
particles[i-1].type = PT_EMBR;
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 ((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 (particles[i-1].type == PT_FILT)
@ -1660,6 +1679,11 @@ void GameSave::readPSv(char * data, int dataLength)
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;
}
for (i = 0; i < tempSigns.size(); i++)
for (size_t i = 0; i < tempSigns.size(); i++)
{
if(signs.size() == MAXSIGNS)
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;
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
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;
}
else
{
fieldDesc |= 1;
tempTemp = particles[i].temp;
tempTemp = (int)(particles[i].temp+0.5f);
partsData[partsDataLen++] = tempTemp;
partsData[partsDataLen++] = tempTemp >> 8;
}
@ -1911,7 +1935,7 @@ char * GameSave::serialiseOPS(int & dataLength)
life = 0;
fieldDesc |= 1 << 1;
partsData[partsDataLen++] = life;
if(particles[i].life & 0xFF00)
if (life & 0xFF00)
{
fieldDesc |= 1 << 2;
partsData[partsDataLen++] = life >> 8;
@ -2079,6 +2103,7 @@ char * GameSave::serialiseOPS(int & dataLength)
bson_append_bool(&b, "paused", paused);
bson_append_int(&b, "gravityMode", gravityMode);
bson_append_int(&b, "airMode", airMode);
bson_append_int(&b, "edgeMode", edgeMode);
//bson_append_int(&b, "leftSelectedElement", sl);
//bson_append_int(&b, "rightSelectedElement", sr);
@ -2103,17 +2128,17 @@ char * GameSave::serialiseOPS(int & dataLength)
bson_append_finish_array(&b);
}
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)
{
signsCount++;
}
}
if(signsCount)
if (signsCount)
{
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)
{
@ -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)
{
puts("Save Error\n");
free(outputData);
delete [] outputData;
dataLength = 0;
outputData = NULL;
goto fin;

View File

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

View File

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

View File

@ -20,7 +20,7 @@
#ifndef HTTP_H
#define HTTP_H
static char hexChars[] = "0123456789abcdef";
static const char hexChars[] = "0123456789abcdef";
void http_init(char *proxy);
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);
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);
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[2], digest + 8);
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)))

View File

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

View File

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

View File

@ -16,11 +16,19 @@ public:
int id;
int date;
int votesUp, votesDown;
int vote;
bool Favourite;
int Comments;
int Views;
int Version;
std::string userName;
std::string name;
std::string Description;
bool Published;
std::list<std::string> tags;
GameSave * gameSave;
SaveInfo(SaveInfo & save);
@ -31,17 +39,6 @@ public:
~SaveInfo();
std::string userName;
std::string name;
std::string Description;
std::list<std::string> tags;
int vote;
bool Published;
void SetName(std::string name);
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(userSession, user.SessionID.c_str());
HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession);
delete userSession;
delete[] userSession;
}
else
{

View File

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

View File

@ -3,8 +3,9 @@
class RequestListener
{
public:
int ListenerRand;
RequestListener() { ListenerRand = rand(); }
static unsigned int nextListenerID;
int ListenerID;
RequestListener() { ListenerID = nextListenerID++; }
virtual ~RequestListener() {}
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(userSession, user.SessionID.c_str());
HTTPContext = http_multipart_post_async((char*)URL.c_str(), postNames, postData, postLength, userName, NULL, userSession);
delete userSession;
delete[] userSession;
}
else
{

View File

@ -5,5 +5,7 @@
class DebugInfo
{
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 "Format.h"
ElementPopulationDebug::ElementPopulationDebug(Simulation * sim):
ElementPopulationDebug::ElementPopulationDebug(unsigned int id, Simulation * sim):
DebugInfo(id),
sim(sim),
maxAverage(255.0f)
{
}
void ElementPopulationDebug::Draw(ui::Point position)
void ElementPopulationDebug::Draw()
{
Graphics * g = ui::Engine::Ref().g;
//g->drawtext(10, 10, "Arse", 255, 255, 255, 255);
int yBottom = YRES-10;
int xStart = 10;

View File

@ -8,7 +8,7 @@ class ElementPopulationDebug : public DebugInfo
Simulation * sim;
float maxAverage;
public:
ElementPopulationDebug(Simulation * sim);
virtual void Draw(ui::Point position);
ElementPopulationDebug(unsigned int id, Simulation * sim);
virtual void Draw();
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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++);
for (j=0; j<FONT_H; j++)
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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++);
for (j=0; j<FONT_H; j++)
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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++);
for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++)
@ -826,7 +826,7 @@ void Graphics::textsize(const char * s, int & width, int & height)
}
else if (*s == '\x0F')
{
if(!s[1] || !s[2] || !s[1]) break;
if(!s[1] || !s[2] || !s[3]) break;
s+=3;
}
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;
int i, j;
unsigned char r, g, b, a;
unsigned char *data = (unsigned char*)data_;
if (!data) return;
w = *(data++)&0xFF;
h = *(data++)&0xFF;

View File

@ -35,6 +35,7 @@
#define PIXG(x) (((x)>>16)&0xFF)
#define PIXB(x) (((x)>>24)&0xFF)
#elif defined(PIX32OGL)
#undef PIXELCHANNELS
#define PIXELCHANNELS 4
#define PIXPACK(x) (0xFF000000|((x)&0xFFFFFF)) //32bit ARGB in 32bit int: AARRGGBB
#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(const 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();

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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
w = *(rp++);
unsigned char *rp = font_data + font_ptrs[c];
int w = *(rp++);
VideoBuffer texture(w, 12);
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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
w = *(rp++);
unsigned char *rp = font_data + font_ptrs[c];
int w = *(rp++);
VideoBuffer texture(w, 12);
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))
return 0;
int width, height;
int invert = 0;
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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++);
for (j=0; j<FONT_H; j++)
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 i, j, w, bn = 0, ba = 0;
char *rp = font_data + font_ptrs[c];
unsigned char *rp = font_data + font_ptrs[c];
w = *(rp++);
for (j=0; j<FONT_H; j++)
for (i=0; i<w; i++)

View File

@ -201,7 +201,7 @@ void Renderer::clearScreen(float alpha)
#endif
}
#ifdef OGLR
void Renderer::checkShader(GLuint shader, char * shname)
void Renderer::checkShader(GLuint shader, const char * shname)
{
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
@ -214,7 +214,7 @@ void Renderer::checkShader(GLuint shader, char * shname)
exit(1);
}
}
void Renderer::checkProgram(GLuint program, char * progname)
void Renderer::checkProgram(GLuint program, const char * progname)
{
GLint 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)
{
int i, j, cr, cg, cb;
int i, j;
int wt = wallID;
if (wt<0 || wt>=Renderer_wtypesCount)
return 0;
@ -706,7 +706,7 @@ void Renderer::DrawWalls()
if (bmap[y][x])
{
wt = bmap[y][x];
if (wt<0 || wt>=UI_WALLCOUNT)
if (wt >= UI_WALLCOUNT)
continue;
pc = wtypes[wt].colour;
gc = wtypes[wt].eglow;
@ -912,7 +912,7 @@ void Renderer::DrawWalls()
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;
#ifdef OGLR
GLint prevFbo;
@ -920,7 +920,7 @@ void Renderer::DrawSigns()
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, partsFbo);
glTranslated(0, MENUSIZE, 0);
#endif
for (i=0; i < signs.size(); i++)
for (size_t i = 0; i < signs.size(); i++)
if (signs[i].text.length())
{
char type = 0;
@ -936,10 +936,10 @@ void Renderer::DrawSigns()
else
drawtext(x+3, y+3, text, 0, 191, 255, 255);
x = signs[i].x;
y = signs[i].y;
dx = 1 - signs[i].ju;
dy = (signs[i].y > 18) ? -1 : 1;
int x = signs[i].x;
int y = signs[i].y;
int dx = 1 - signs[i].ju;
int dy = (signs[i].y > 18) ? -1 : 1;
#ifdef OGLR
glBegin(GL_LINES);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
@ -947,11 +947,11 @@ void Renderer::DrawSigns()
glVertex2i(x+(dx*4), y+(dy*4));
glEnd();
#else
for (j=0; j<4; j++)
for (int j = 0; j < 4; j++)
{
blendpixel(x, y, 192, 192, 192, 255);
x+=dx;
y+=dy;
x += dx;
y += dy;
}
#endif
}
@ -1004,7 +1004,7 @@ void Renderer::render_fire()
#ifndef OGLR
if(!(render_mode & FIREMODE))
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 (i=0; i<XRES/CELL; i++)
{
@ -1043,7 +1043,7 @@ float blur_alphaf[7][7];
void Renderer::prepare_alpha(int size, float intensity)
{
//TODO: implement size
int x,y,i,j,c;
int x,y,i,j;
float multiplier = 255.0f*intensity;
memset(temp, 0, sizeof(temp));
@ -1071,7 +1071,7 @@ void Renderer::prepare_alpha(int size, float intensity)
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;
@ -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 orbd[4] = {0, 0, 0, 0}, orbl[4] = {0, 0, 0, 0};
float gradv, flicker, fnx, fny;
float gradv, flicker;
Particle * parts;
Element *elements;
if(!sim)
@ -1133,6 +1133,7 @@ void Renderer::render_parts()
parts = sim->parts;
elements = sim->elements;
#ifdef OGLR
float fnx, fny;
int cfireV = 0, cfireC = 0, cfire = 0;
int csmokeV = 0, csmokeC = 0, csmoke = 0;
int cblobV = 0, cblobC = 0, cblob = 0;
@ -1168,8 +1169,10 @@ void Renderer::render_parts()
nx = (int)(sim->parts[i].x+0.5f);
ny = (int)(sim->parts[i].y+0.5f);
#ifdef OGLR
fnx = sim->parts[i].x;
fny = sim->parts[i].y;
#endif
if(nx >= XRES || nx < 0 || ny >= YRES || ny < 0)
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);
firea = 255;
firer = colr = (unsigned char)color_data[caddress];
fireg = colg = (unsigned char)color_data[caddress+1];
fireb = colb = (unsigned char)color_data[caddress+2];
firer = colr = color_data[caddress];
fireg = colg = color_data[caddress+1];
fireb = colb = color_data[caddress+2];
cola = 255;
if(pixel_mode & (FIREMODE | PMODE_GLOW))
pixel_mode = (pixel_mode & ~(FIREMODE|PMODE_GLOW)) | PMODE_BLUR;
@ -1365,7 +1368,7 @@ void Renderer::render_parts()
{
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);
}
}
@ -1377,7 +1380,7 @@ void Renderer::render_parts()
cplayer = &sim->player;
else if(t==PT_STKM2)
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];
else
continue;
@ -2268,7 +2271,7 @@ void Renderer::draw_air()
{
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);
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
// 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
@ -2421,22 +2424,22 @@ pixel Renderer::GetPixel(int x, int y)
Renderer::Renderer(Graphics * g, Simulation * sim):
sim(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),
zoomScopePosition(0, 0),
zoomScopeSize(32),
ZFACTOR(8),
zoomEnabled(false),
decorations_enable(1),
gravityFieldEnabled(false),
gravityZonesEnabled(false),
mousePos(0, 0),
display_mode(0),
render_mode(0),
colour_mode(0),
gridSize(0),
blackDecorations(false),
debugLines(false),
sampleColor(0xFFFFFFFF)
ZFACTOR(8),
gridSize(0)
{
this->g = g;
this->sim = sim;
@ -2685,7 +2688,7 @@ void Renderer::CompileRenderMode()
{
int old_render_mode = render_mode;
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];
//If firemode is removed, clear the fire display
@ -2707,7 +2710,7 @@ void Renderer::ClearAccumulation()
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)
{
@ -2720,7 +2723,7 @@ void Renderer::AddRenderMode(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)
{
@ -2746,9 +2749,9 @@ void Renderer::CompileDisplayMode()
{
int old_display_mode = display_mode;
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];
if(!(display_mode & DISPLAY_PERS) && (old_display_mode & DISPLAY_PERS))
if (!(display_mode & DISPLAY_PERS) && (old_display_mode & DISPLAY_PERS))
{
ClearAccumulation();
}
@ -2756,13 +2759,13 @@ void Renderer::CompileDisplayMode()
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;
}
if(display_modes[i] & DISPLAY_AIR)
if (display_modes[i] & DISPLAY_AIR)
{
display_modes.erase(display_modes.begin()+i);
}
@ -2773,9 +2776,9 @@ void Renderer::AddDisplayMode(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);
i = 0;

View File

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

View File

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

View File

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

View File

@ -8,14 +8,14 @@
class ConsoleView;
class ConsoleModel {
int currentCommandIndex;
size_t currentCommandIndex;
std::vector<ConsoleView*> observers;
std::deque<ConsoleCommand> previousCommands;
void notifyPreviousCommandsChanged();
void notifyCurrentCommandChanged();
public:
int GetCurrentCommandIndex();
void SetCurrentCommandIndex(int index);
size_t GetCurrentCommandIndex();
void SetCurrentCommandIndex(size_t index);
ConsoleCommand GetCurrentCommand();
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)
{
for(int i = 0; i < commandList.size(); i++)
for (size_t i = 0; i < commandList.size(); i++)
{
RemoveComponent(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)),
callback(callback_)
{
int width, height;
ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title);
titleLabel->SetTextColour(style::Colour::WarningTitle);
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)),
callback(callback_)
{
int width, height;
ui::Label * titleLabel = new ui::Label(ui::Point(4, 5), ui::Point(Size.X-8, 15), title);
titleLabel->SetTextColour(style::Colour::WarningTitle);
titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;

View File

@ -23,9 +23,9 @@ public:
ElementSearchActivity::ElementSearchActivity(GameController * gameController, std::vector<Tool*> tools) :
WindowActivity(ui::Point(-1, -1), ui::Point(236, 302)),
firstResult(NULL),
gameController(gameController),
tools(tools),
firstResult(NULL),
exit(false)
{
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)
{
for(int i = 0; i < components.size(); i++)
for (size_t i = 0; i < components.size(); i++)
{
RemoveComponent(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;
}
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;
}
@ -239,12 +239,12 @@ void FileBrowserActivity::NotifyDone(Task * task)
totalFiles = files.size();
delete loadFiles;
loadFiles = NULL;
if(!files.size())
if (!files.size())
{
progressBar->Visible = false;
infoText->Visible = true;
}
for(int i = 0; i < components.size(); i++)
for (size_t i = 0; i < components.size(); i++)
{
delete components[i];
}
@ -253,7 +253,7 @@ void FileBrowserActivity::NotifyDone(Task * task)
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();
}

View File

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

View File

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

View File

@ -11,7 +11,7 @@ public:
Brush(size_)
{
SetRadius(size_);
};
}
virtual void GenerateBitmap()
{
if(bitmap)
@ -29,7 +29,7 @@ public:
}
else
{
int yTop = ry+1, yBottom, i, j;
int yTop = ry+1, yBottom, 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))

View File

@ -26,12 +26,14 @@
#include "gui/interface/Keys.h"
#include "simulation/Snapshot.h"
#include "debug/DebugInfo.h"
#include "debug/DebugParts.h"
#include "debug/ElementPopulation.h"
#include "debug/DebugLines.h"
#ifdef LUACONSOLE
#include "lua/LuaScriptInterface.h"
#else
#include "lua/TPTScriptInterface.h"
#endif
//#include "debug/ElementPopulation.h"
using namespace std;
@ -109,26 +111,26 @@ public:
{
if(cc->localBrowser->GetSave())
{
cc->gameModel->SetStamp(cc->localBrowser->GetSave()->GetGameSave());
if (cc->localBrowser->GetMoveToFront())
Client::Ref().MoveStampToFront(cc->localBrowser->GetSave()->GetName());
cc->LoadStamp();
cc->LoadStamp(cc->localBrowser->GetSave()->GetGameSave());
}
}
};
GameController::GameController():
search(NULL),
renderOptions(NULL),
loginWindow(NULL),
console(NULL),
tagsWindow(NULL),
options(NULL),
activePreview(NULL),
localBrowser(NULL),
foundSign(NULL),
HasDone(false),
firstTick(true)
firstTick(true),
foundSign(NULL),
activePreview(NULL),
search(NULL),
renderOptions(NULL),
loginWindow(NULL),
console(NULL),
tagsWindow(NULL),
localBrowser(NULL),
options(NULL),
debugFlags(0),
HasDone(false)
{
gameView = new GameView();
gameModel = new GameModel();
@ -152,10 +154,11 @@ GameController::GameController():
ActiveToolChanged(2, gameModel->GetActiveTool(2));
ActiveToolChanged(3, gameModel->GetActiveTool(3));
//sim = new Simulation();
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()
@ -376,6 +379,20 @@ void GameController::AdjustZoomSize(int direction, bool logarithmic)
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)
{
if(point.X >= XRES)
@ -483,9 +500,9 @@ void GameController::LoadClipboard()
gameModel->GetPlaceSave()->Expand();
}
void GameController::LoadStamp()
void GameController::LoadStamp(GameSave *stamp)
{
gameModel->SetPlaceSave(gameModel->GetStamp());
gameModel->SetPlaceSave(stamp);
if(gameModel->GetPlaceSave() && gameModel->GetPlaceSave()->Collapsed())
gameModel->GetPlaceSave()->Expand();
}
@ -522,7 +539,7 @@ std::string GameController::StampRegion(ui::Point point1, ui::Point point2)
if(newSave)
{
newSave->paused = gameModel->GetPaused();
return gameModel->AddStamp(newSave);
return Client::Ref().AddStamp(newSave);
}
else
{
@ -566,7 +583,7 @@ bool GameController::MouseDown(int x, int y, unsigned button)
ui::Point point = gameModel->AdjustZoomCoords(ui::Point(x, y));
x = point.X;
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);
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));
x = point.X;
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);
if(foundSign) {
@ -723,6 +740,11 @@ bool GameController::KeyRelease(int key, Uint16 character, bool shift, bool ctrl
return ret;
}
bool GameController::MouseTick()
{
return commandInterface->OnMouseTick();
}
void GameController::Tick()
{
if(firstTick)
@ -731,9 +753,8 @@ void GameController::Tick()
((LuaScriptInterface*)commandInterface)->Init();
#endif
#if !defined(MACOSX) && !defined(NO_INSTALL_CHECK)
if(!Client::Ref().GetPrefBool("InstallCheck", false))
if (Client::Ref().IsFirstRun())
{
Client::Ref().SetPref("InstallCheck", true);
Install();
}
#endif
@ -741,7 +762,8 @@ void GameController::Tick()
}
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();
}
@ -859,7 +881,9 @@ void GameController::Update()
gameView->SetSample(gameModel->GetSimulation()->GetSample(pos.X, pos.Y));
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
//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();
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)
{
new ErrorMessage("Error", "Unable to build save.");
}
else
{
sim->SaveSimOptions(gameSave);
gameSave->paused = gameModel->GetPaused();
std::string filename = "";
if (gameModel->GetSaveFile())
filename = gameModel->GetSaveFile()->GetDisplayName();
@ -1268,19 +1288,15 @@ void GameController::OpenSaveWindow()
{
Simulation * sim = gameModel->GetSimulation();
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)
{
new ErrorMessage("Error", "Unable to build save.");
}
else
{
sim->SaveSimOptions(gameSave);
gameSave->paused = gameModel->GetPaused();
if(gameModel->GetSave())
{
SaveInfo tempSave(*gameModel->GetSave());
@ -1320,19 +1336,15 @@ void GameController::SaveAsCurrent()
{
Simulation * sim = gameModel->GetSimulation();
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)
{
new ErrorMessage("Error", "Unable to build save.");
}
else
{
gameSave->paused = gameModel->GetPaused();
sim->SaveSimOptions(gameSave);
if(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)
{
if(gameModel && gameModel->GetSimulation())
@ -1418,7 +1475,7 @@ bool GameController::IsValidElement(int type)
{
if(gameModel && gameModel->GetSimulation())
{
return (type > 0 && type < PT_NUM && gameModel->GetSimulation()->elements[type].Enabled);
return (type && gameModel->GetSimulation()->IsValidElement(type));
}
else
return false;
@ -1444,7 +1501,7 @@ void GameController::NotifyNewNotification(Client * sender, std::pair<std::strin
{
std::string link;
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 void Action()
@ -1474,7 +1531,7 @@ void GameController::NotifyUpdateAvailable(Client * sender)
{
GameController * c;
public:
UpdateNotification(GameController * c, std::string message) : c(c), Notification(message) {}
UpdateNotification(GameController * c, std::string message) : Notification(message), c(c) {}
virtual ~UpdateNotification() {}
virtual void Action()

View File

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

View File

@ -12,26 +12,24 @@
#include "BitmapBrush.h"
#include "client/Client.h"
#include "client/GameSave.h"
#include "client/SaveFile.h"
#include "gui/game/DecorationTool.h"
#include "QuickOptions.h"
#include "GameModelException.h"
#include "Format.h"
GameModel::GameModel():
sim(NULL),
ren(NULL),
clipboard(NULL),
placeSave(NULL),
activeMenu(-1),
currentBrush(0),
currentUser(0, ""),
currentSave(NULL),
currentFile(NULL),
colourSelector(false),
clipboard(NULL),
stamp(NULL),
placeSave(NULL),
colour(255, 0, 0, 255),
currentUser(0, ""),
toolStrength(1.0f),
activeColourPreset(-1),
activeMenu(-1),
activeColourPreset(0),
colourSelector(false),
colour(255, 0, 0, 255),
edgeMode(0)
{
sim = new Simulation();
@ -95,15 +93,6 @@ GameModel::GameModel():
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();
//Set default brush palette
@ -113,7 +102,7 @@ GameModel::GameModel():
//Load more from brushes folder
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]);
if(!brushData.size())
@ -121,8 +110,8 @@ GameModel::GameModel():
std::cout << "Brushes: Skipping " << brushFiles[i] << ". Could not open" << std::endl;
continue;
}
int dimension = std::sqrt((float)brushData.size());
if(dimension * dimension != brushData.size())
size_t dimension = std::sqrt((float)brushData.size());
if (dimension * dimension != brushData.size())
{
std::cout << "Brushes: Skipping " << brushFiles[i] << ". Invalid bitmap size" << std::endl;
continue;
@ -173,15 +162,15 @@ GameModel::~GameModel()
Client::Ref().SetPref("Decoration.Blue", (int)colour.Blue);
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];
}
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;
}
for(int i = 0; i < brushList.size(); i++)
for (size_t i = 0; i < brushList.size(); i++)
{
delete brushList[i];
}
@ -191,8 +180,6 @@ GameModel::~GameModel()
delete placeSave;
if(clipboard)
delete clipboard;
if(stamp)
delete stamp;
if(currentSave)
delete currentSave;
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);
}
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);
}
@ -317,7 +304,7 @@ void GameModel::BuildMenus()
}
//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;
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());
sim->gravityMode = saveData->gravityMode;
sim->air->airMode = saveData->airMode;
sim->edgeMode = saveData->edgeMode;
sim->legacy_enable = saveData->legacyEnable;
sim->water_equal_test = saveData->waterEEnabled;
sim->aheat_enable = saveData->aheatEnable;
@ -628,6 +616,7 @@ void GameModel::SetSaveFile(SaveFile * newSave)
SetPaused(saveData->paused | GetPaused());
sim->gravityMode = saveData->gravityMode;
sim->air->airMode = saveData->airMode;
sim->edgeMode = saveData->edgeMode;
sim->legacy_enable = saveData->legacyEnable;
sim->water_equal_test = saveData->waterEEnabled;
sim->aheat_enable = saveData->aheatEnable;
@ -700,6 +689,20 @@ ui::Point GameModel::GetZoomPosition()
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)
{
if (!GetZoomEnabled())
@ -747,10 +750,10 @@ int GameModel::GetZoomFactor()
return ren->ZFACTOR;
}
void GameModel::SetActiveColourPreset(int preset)
void GameModel::SetActiveColourPreset(size_t preset)
{
if (activeColourPreset != preset)
activeColourPreset = preset;
if (activeColourPreset-1 != preset)
activeColourPreset = preset+1;
else
{
activeTools[0] = GetToolFromIdentifier("DEFAULT_DECOR_SET");
@ -759,16 +762,16 @@ void GameModel::SetActiveColourPreset(int preset)
notifyColourActivePresetChanged();
}
int GameModel::GetActiveColourPreset()
size_t GameModel::GetActiveColourPreset()
{
return activeColourPreset;
return activeColourPreset-1;
}
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();
}
}
@ -797,7 +800,7 @@ void GameModel::SetColourSelectorColour(ui::Colour colour_)
colour = colour_;
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])->Green = colour.Green;
@ -833,7 +836,7 @@ bool GameModel::GetPaused()
void GameModel::SetDecoration(bool decorationState)
{
if (ren->decorations_enable != decorationState)
if (ren->decorations_enable != (decorationState?1:0))
{
ren->decorations_enable = decorationState?1:0;
notifyDecorationChanged();
@ -900,19 +903,6 @@ void GameModel::ClearSimulation()
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)
{
if(save != placeSave)
@ -927,14 +917,6 @@ void GameModel::SetPlaceSave(GameSave * save)
notifyPlaceSaveChanged();
}
std::string GameModel::AddStamp(GameSave * save)
{
if(stamp)
delete stamp;
stamp = save;
return Client::Ref().AddStamp(save);
}
void GameModel::SetClipboard(GameSave * save)
{
if(clipboard)
@ -952,11 +934,6 @@ GameSave * GameModel::GetPlaceSave()
return placeSave;
}
GameSave * GameModel::GetStamp()
{
return stamp;
}
void GameModel::Log(string message)
{
consoleLog.push_front(message);
@ -1020,7 +997,7 @@ std::string GameModel::GetInfoTip()
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);
}
@ -1028,7 +1005,7 @@ void GameModel::notifyNotificationsChanged()
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);
}
@ -1036,7 +1013,7 @@ void GameModel::notifyColourPresetsChanged()
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);
}
@ -1044,7 +1021,7 @@ void GameModel::notifyColourActivePresetChanged()
void GameModel::notifyColourSelectorColourChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyColourSelectorColourChanged(this);
}
@ -1052,7 +1029,7 @@ void GameModel::notifyColourSelectorColourChanged()
void GameModel::notifyColourSelectorVisibilityChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyColourSelectorVisibilityChanged(this);
}
@ -1060,7 +1037,7 @@ void GameModel::notifyColourSelectorVisibilityChanged()
void GameModel::notifyRendererChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyRendererChanged(this);
}
@ -1068,7 +1045,7 @@ void GameModel::notifyRendererChanged()
void GameModel::notifySaveChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifySaveChanged(this);
}
@ -1076,7 +1053,7 @@ void GameModel::notifySaveChanged()
void GameModel::notifySimulationChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifySimulationChanged(this);
}
@ -1084,7 +1061,7 @@ void GameModel::notifySimulationChanged()
void GameModel::notifyPausedChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyPausedChanged(this);
}
@ -1092,7 +1069,7 @@ void GameModel::notifyPausedChanged()
void GameModel::notifyDecorationChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
//observers[i]->NotifyPausedChanged(this);
}
@ -1100,7 +1077,7 @@ void GameModel::notifyDecorationChanged()
void GameModel::notifyBrushChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyBrushChanged(this);
}
@ -1108,7 +1085,7 @@ void GameModel::notifyBrushChanged()
void GameModel::notifyMenuListChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyMenuListChanged(this);
}
@ -1116,7 +1093,7 @@ void GameModel::notifyMenuListChanged()
void GameModel::notifyToolListChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyToolListChanged(this);
}
@ -1124,7 +1101,7 @@ void GameModel::notifyToolListChanged()
void GameModel::notifyActiveToolsChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyActiveToolsChanged(this);
}
@ -1132,7 +1109,7 @@ void GameModel::notifyActiveToolsChanged()
void GameModel::notifyUserChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyUserChanged(this);
}
@ -1140,7 +1117,7 @@ void GameModel::notifyUserChanged()
void GameModel::notifyZoomChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyZoomChanged(this);
}
@ -1148,7 +1125,7 @@ void GameModel::notifyZoomChanged()
void GameModel::notifyPlaceSaveChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyPlaceSaveChanged(this);
}
@ -1156,7 +1133,7 @@ void GameModel::notifyPlaceSaveChanged()
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);
}
@ -1164,7 +1141,7 @@ void GameModel::notifyLogChanged(string entry)
void GameModel::notifyInfoTipChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyInfoTipChanged(this);
}
@ -1172,7 +1149,7 @@ void GameModel::notifyInfoTipChanged()
void GameModel::notifyToolTipChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyToolTipChanged(this);
}
@ -1180,7 +1157,7 @@ void GameModel::notifyToolTipChanged()
void GameModel::notifyQuickOptionsChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyQuickOptionsChanged(this);
}
@ -1188,7 +1165,7 @@ void GameModel::notifyQuickOptionsChanged()
void GameModel::notifyLastToolChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyLastToolChanged(this);
}

View File

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

View File

@ -14,6 +14,7 @@
#include "simulation/SaveRenderer.h"
#include "simulation/SimulationData.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "client/SaveFile.h"
#include "Format.h"
#include "QuickOptions.h"
#include "IntroText.h"
@ -40,10 +41,10 @@ private:
public:
SplitButton(ui::Point position, ui::Point size, std::string buttonText, std::string toolTip, std::string toolTip2, int split) :
Button(position, size, buttonText, toolTip),
toolTip2(toolTip2),
showSplit(true),
splitPosition(split),
splitActionCallback(NULL),
showSplit(true)
toolTip2(toolTip2),
splitActionCallback(NULL)
{
}
@ -149,51 +150,54 @@ public:
GameView::GameView():
ui::Window(ui::Point(0, 0), ui::Point(WINDOWW, WINDOWH)),
pointQueue(queue<ui::Point>()),
isMouseDown(false),
ren(NULL),
activeBrush(NULL),
currentMouse(0, 0),
toolIndex(0),
zoomEnabled(false),
zoomCursorFixed(false),
drawPoint1(0, 0),
drawPoint2(0, 0),
drawMode(DrawPoints),
drawModeReset(false),
selectMode(SelectNone),
selectPoint1(0, 0),
selectPoint2(0, 0),
placeSaveThumb(NULL),
mousePosition(0, 0),
lastOffset(0),
mouseInZoom(false),
drawSnap(false),
toolTip(""),
infoTip(""),
infoTipPresence(0),
buttonTipShow(0),
isToolTipFadingIn(false),
isButtonTipFadingIn(false),
toolTipPosition(-1, -1),
saveSimulationButtonEnabled(false),
shiftBehaviour(false),
ctrlBehaviour(false),
altBehaviour(false),
showHud(true),
showDebug(false),
introText(2048),
introTextMessage(introTextData),
wallBrush(false),
toolBrush(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),
recording(false),
screenshotIndex(0),
recordingIndex(0),
toolTipPresence(0),
currentSaveType(0),
lastLogEntry(0.0f),
lastMenu(-1)
pointQueue(queue<ui::Point>()),
ren(NULL),
activeBrush(NULL),
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;
@ -219,7 +223,7 @@ GameView::GameView():
scrollBar->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
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);
currentX+=18;
searchButton->SetTogglable(false);
@ -254,24 +258,25 @@ GameView::GameView():
SaveSimulationAction(GameView * _v) { v = _v; }
void ActionCallbackRight(ui::Button * sender)
{
if(v->CtrlBehaviour())
if(v->CtrlBehaviour() || !Client::Ref().GetAuthUser().ID)
v->c->OpenLocalSaveWindow(false);
else
v->c->OpenSaveWindow();
}
void ActionCallbackLeft(ui::Button * sender)
{
if(v->CtrlBehaviour())
if(v->CtrlBehaviour() || !Client::Ref().GetAuthUser().ID)
v->c->OpenLocalSaveWindow(true);
else
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->SetIcon(IconSave);
currentX+=151;
((SplitButton*)saveSimulationButton)->SetSplitActionCallback(new SaveSimulationAction(this));
SetSaveButtonTooltips();
AddComponent(saveSimulationButton);
class UpVoteAction : public ui::ButtonAction
@ -407,7 +412,7 @@ GameView::GameView():
};
pauseButton = new ui::Button(ui::Point(Size.X-16, Size.Y-16), ui::Point(15, 15), "", "Pause/Resume the simulation"); //Pause
pauseButton->SetIcon(IconPause);
pauseButton->SetTogglable(true);
pauseButton->SetTogglable(true);
pauseButton->SetActionCallback(new PauseAction(this));
AddComponent(pauseButton);
@ -466,9 +471,9 @@ public:
int menuID;
bool needsClick;
MenuAction(GameView * _v, int menuID_)
{
{
v = _v;
menuID = menuID_;
menuID = menuID_;
if (menuID == SC_DECO)
needsClick = true;
else
@ -511,6 +516,9 @@ public:
case QuickOption::Toggle:
button->SetTogglable(true);
button->SetToggleState(option->GetToggle());
break;
default:
break;
}
}
};
@ -534,7 +542,7 @@ public:
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]);
delete quickOptionButtons[i];
@ -560,20 +568,20 @@ void GameView::NotifyQuickOptionsChanged(GameModel * sender)
void GameView::NotifyMenuListChanged(GameModel * sender)
{
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]);
delete menuButtons[i];
}
menuButtons.clear();
for(int i = 0; i < toolButtons.size(); i++)
for (size_t i = 0; i < toolButtons.size(); i++)
{
RemoveComponent(toolButtons[i]);
delete toolButtons[i];
}
toolButtons.clear();
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 = "";
tempString += menuList[i]->GetIcon();
@ -631,7 +639,7 @@ bool GameView::GetPlacingZoom()
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;
if(sender->GetActiveTool(0) == tool)
@ -683,9 +691,9 @@ void GameView::NotifyToolListChanged(GameModel * sender)
{
lastOffset = 0;
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);
}
@ -694,14 +702,14 @@ void GameView::NotifyToolListChanged(GameModel * sender)
menuButtons[i]->SetToggleState(false);
}
}
for(int i = 0; i < toolButtons.size(); i++)
for (size_t i = 0; i < toolButtons.size(); i++)
{
RemoveComponent(toolButtons[i]);
delete toolButtons[i];
}
toolButtons.clear();
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);
ToolButton * tempButton;
@ -821,9 +829,9 @@ void GameView::NotifyColourPresetsChanged(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
}
@ -864,7 +872,8 @@ void GameView::NotifyUserChanged(GameModel * sender)
((SplitButton*)loginButton)->SetShowSplit(true);
((SplitButton*)loginButton)->SetRightToolTip("Edit profile");
}
saveSimulationButtonEnabled = sender->GetUser().ID;
// saveSimulationButtonEnabled = sender->GetUser().ID;
saveSimulationButtonEnabled = true;
NotifySaveChanged(sender);
}
@ -981,6 +990,7 @@ void GameView::NotifySaveChanged(GameModel * sender)
currentSaveType = 0;
}
saveSimulationButton->Enabled = (saveSimulationButtonEnabled || ctrlBehaviour);
SetSaveButtonTooltips();
c->HistorySnapshot();
}
@ -1038,83 +1048,99 @@ void GameView::setToolButtonOffset(int offset)
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));
currentMouse = ui::Point(x, y);
if(selectMode!=SelectNone)
if (selectMode != SelectNone)
{
if(selectMode==PlaceSave)
if (selectMode == PlaceSave)
selectPoint1 = c->PointTranslate(ui::Point(x, y));
if(selectPoint1.X!=-1)
if (selectPoint1.X != -1)
selectPoint2 = c->PointTranslate(ui::Point(x, y));
return;
}
if(isMouseDown && drawMode == DrawPoints)
else if (isMouseDown)
{
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x-dx, y-dy))));
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y))));
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, y))));
}
}
else if (drawMode == DrawPoints || drawMode == DrawFill)
isMouseDown = false;
}
mouseInZoom = newMouseInZoom;
}
void GameView::OnMouseDown(int x, int y, unsigned button)
{
if(altBehaviour && !shiftBehaviour && !ctrlBehaviour)
if (altBehaviour && !shiftBehaviour && !ctrlBehaviour)
button = BUTTON_MIDDLE;
if(selectMode!=SelectNone)
if (!(zoomEnabled && !zoomCursorFixed))
{
if(button==BUTTON_LEFT)
if (selectMode != SelectNone)
{
selectPoint1 = c->PointTranslate(ui::Point(x, y));
selectPoint2 = selectPoint1;
if (button == BUTTON_LEFT && selectPoint1.X == -1)
{
selectPoint1 = c->PointTranslate(ui::Point(x, y));
selectPoint2 = selectPoint1;
}
return;
}
return;
}
if(currentMouse.X >= 0 && currentMouse.X < XRES && currentMouse.Y >= 0 && currentMouse.Y < YRES && !(zoomEnabled && !zoomCursorFixed))
{
if(button == BUTTON_LEFT)
toolIndex = 0;
if(button == BUTTON_RIGHT)
toolIndex = 1;
if(button == BUTTON_MIDDLE)
toolIndex = 2;
isMouseDown = true;
if(!pointQueue.size())
c->HistorySnapshot();
if(drawMode == DrawRect || drawMode == DrawLine)
if (currentMouse.X >= 0 && currentMouse.X < XRES && currentMouse.Y >= 0 && currentMouse.Y < YRES)
{
drawPoint1 = c->PointTranslate(ui::Point(x, y));
}
if(drawMode == DrawPoints)
{
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y))));
if (button == BUTTON_LEFT)
toolIndex = 0;
if (button == BUTTON_RIGHT)
toolIndex = 1;
if (button == BUTTON_MIDDLE)
toolIndex = 2;
isMouseDown = true;
if (!pointQueue.size())
c->HistorySnapshot();
if (drawMode == DrawRect || drawMode == DrawLine)
{
drawPoint1 = c->PointTranslate(ui::Point(x, y));
}
if (drawMode == DrawPoints)
{
pointQueue.push(ui::Point(c->PointTranslate(ui::Point(x, y))));
}
}
}
}
void GameView::OnMouseUp(int x, int y, unsigned button)
{
if(zoomEnabled && !zoomCursorFixed)
if (zoomEnabled && !zoomCursorFixed)
{
zoomCursorFixed = true;
drawMode = DrawPoints;
isMouseDown = false;
}
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 thumbY = selectPoint2.Y - (placeSaveThumb->Height/2);
if(thumbX<0)
if (thumbX < 0)
thumbX = 0;
if(thumbX+(placeSaveThumb->Width)>=XRES)
if (thumbX+(placeSaveThumb->Width) >= XRES)
thumbX = XRES-placeSaveThumb->Width;
if(thumbY<0)
if (thumbY < 0)
thumbY = 0;
if(thumbY+(placeSaveThumb->Height)>=YRES)
if (thumbY+(placeSaveThumb->Height) >= YRES)
thumbY = YRES-placeSaveThumb->Height;
c->PlaceSave(ui::Point(thumbX, thumbY));
@ -1122,15 +1148,15 @@ void GameView::OnMouseUp(int x, int y, unsigned button)
}
else
{
int x2 = (selectPoint1.X>selectPoint2.X)?selectPoint1.X:selectPoint2.X;
int y2 = (selectPoint1.Y>selectPoint2.Y)?selectPoint1.Y:selectPoint2.Y;
int x1 = (selectPoint2.X<selectPoint1.X)?selectPoint2.X:selectPoint1.X;
int y1 = (selectPoint2.Y<selectPoint1.Y)?selectPoint2.Y:selectPoint1.Y;
if(selectMode==SelectCopy)
int x2 = (selectPoint1.X>selectPoint2.X) ? selectPoint1.X : selectPoint2.X;
int y2 = (selectPoint1.Y>selectPoint2.Y) ? selectPoint1.Y : selectPoint2.Y;
int x1 = (selectPoint2.X<selectPoint1.X) ? selectPoint2.X : selectPoint1.X;
int y1 = (selectPoint2.Y<selectPoint1.Y) ? selectPoint2.Y : selectPoint1.Y;
if (selectMode ==SelectCopy)
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));
else if(selectMode==SelectStamp)
else if (selectMode == SelectStamp)
c->StampRegion(ui::Point(x1, y1), ui::Point(x2, y2));
}
}
@ -1138,39 +1164,39 @@ void GameView::OnMouseUp(int x, int y, unsigned button)
return;
}
if(isMouseDown)
if (isMouseDown)
{
isMouseDown = false;
if(drawMode == DrawRect || drawMode == DrawLine)
if (drawMode == DrawRect || drawMode == DrawLine)
{
ui::Point finalDrawPoint2(0, 0);
drawPoint2 = c->PointTranslate(ui::Point(x, y));
finalDrawPoint2 = drawPoint2;
if(drawSnap && drawMode == DrawLine)
if (drawSnap && drawMode == DrawLine)
{
finalDrawPoint2 = lineSnapCoords(c->PointTranslate(drawPoint1), drawPoint2);
}
if(drawSnap && drawMode == DrawRect)
if (drawSnap && drawMode == DrawRect)
{
finalDrawPoint2 = rectSnapCoords(c->PointTranslate(drawPoint1), drawPoint2);
}
if(drawMode == DrawRect)
if (drawMode == DrawRect)
{
c->DrawRect(toolIndex, c->PointTranslate(drawPoint1), finalDrawPoint2);
}
if(drawMode == DrawLine)
if (drawMode == DrawLine)
{
c->DrawLine(toolIndex, c->PointTranslate(drawPoint1), finalDrawPoint2);
}
}
if(drawMode == DrawPoints)
if (drawMode == DrawPoints)
{
c->ToolClick(toolIndex, c->PointTranslate(ui::Point(x, y)));
}
if(drawModeReset)
if (drawModeReset)
{
drawModeReset = false;
drawMode = DrawPoints;
@ -1352,7 +1378,7 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
c->ChangeBrush();
break;
case 'z':
if(ctrl)
if (ctrl)
{
c->HistoryRestore();
}
@ -1387,7 +1413,21 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
c->OpenElementSearch();
break;
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();
#else
c->FrameStep();
#endif
break;
case 'g':
if (ctrl)
@ -1472,12 +1512,18 @@ void GameView::OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool
}
break;
case 'l':
c->LoadStamp();
selectPoint2 = mousePosition;
selectPoint1 = selectPoint2;
isMouseDown = false;
drawMode = DrawPoints;
break;
{
std::vector<std::string> stampList = Client::Ref().GetStamps(0, 1);
if (stampList.size())
{
c->LoadStamp(Client::Ref().GetStamp(stampList[0])->GetGameSave());
selectPoint2 = mousePosition;
selectPoint1 = selectPoint2;
isMouseDown = false;
drawMode = DrawPoints;
break;
}
}
case 'k':
selectPoint2 = ui::Point(-1, -1);
selectPoint1 = selectPoint2;
@ -1640,8 +1686,6 @@ void GameView::OnTick(float dt)
toolTipPresence = 0;
}
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);
}
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()
{
Window::DoDraw();
@ -1780,11 +1837,11 @@ void GameView::NotifyNotificationsChanged(GameModel * sender)
AddComponent(tempButton);
notificationComponents.push_back(tempButton);
tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15));
tempButton->SetIcon(IconClose);
tempButton = new ui::Button(ui::Point(XRES-20, currentY), ui::Point(15, 15), "\xAA");
//tempButton->SetIcon(IconClose);
tempButton->SetActionCallback(new CloseNotificationButtonAction(this, *iter));
tempButton->Appearance.Margin.Left+=2;
tempButton->Appearance.Margin.Top+=2;
tempButton->Appearance.Margin.Left -= 1;
tempButton->Appearance.Margin.Top -= 1;
tempButton->Appearance.BorderInactive = style::Colour::WarningTitle;
tempButton->Appearance.TextInactive = style::Colour::WarningTitle;
tempButton->Appearance.BorderHover = ui::Colour(255, 175, 0);
@ -1803,9 +1860,8 @@ void GameView::NotifyZoomChanged(GameModel * sender)
void GameView::NotifyLogChanged(GameModel * sender, string entry)
{
logEntries.push_front(entry);
lastLogEntry = 100.0f;
if(logEntries.size()>20)
logEntries.push_front(std::pair<std::string, int>(entry, 600));
if (logEntries.size() > 20)
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)
{
ctrlBehaviour = true;
//Show HDD save & load buttons
saveSimulationButton->Appearance.BackgroundInactive = saveSimulationButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255);
saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(0, 0, 0);
if (isHighlighted) {
saveSimulationButton->Appearance.BackgroundInactive = saveSimulationButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255);
saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(0, 0, 0);
}
saveSimulationButton->Enabled = true;
((SplitButton*)saveSimulationButton)->SetToolTips("Save the simulation to your hard drive", "Save the simulation to your hard drive");
searchButton->Appearance.BackgroundInactive = searchButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255);
searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(0, 0, 0);
searchButton->SetToolTip("Open a simulation from your hard drive");
SetSaveButtonTooltips();
if (isHighlighted) {
searchButton->Appearance.BackgroundInactive = searchButton->Appearance.BackgroundHover = ui::Colour(255, 255, 255);
searchButton->Appearance.TextInactive = searchButton->Appearance.TextHover = ui::Colour(0, 0, 0);
}
searchButton->SetToolTip("Open a simulation from your hard drive.");
if (currentSaveType == 2)
((SplitButton*)saveSimulationButton)->SetShowSplit(true);
if(isMouseDown || (toolBrush && drawMode == DrawPoints))
@ -1901,11 +1969,11 @@ void GameView::disableCtrlBehaviour()
saveSimulationButton->Appearance.BackgroundHover = ui::Colour(20, 20, 20);
saveSimulationButton->Appearance.TextInactive = saveSimulationButton->Appearance.TextHover = ui::Colour(255, 255, 255);
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.BackgroundHover = ui::Colour(20, 20, 20);
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)
((SplitButton*)saveSimulationButton)->SetShowSplit(false);
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()
{
Graphics * g = ui::Engine::Ref().g;
@ -2056,20 +2136,24 @@ void GameView::OnDraw()
Client::Ref().WriteFile(data, filename.str());
}
int startX = 20;
int startY = YRES-20;
int startAlpha;
if(lastLogEntry>0.1f && logEntries.size())
if (logEntries.size())
{
startAlpha = 2.55f*lastLogEntry;
deque<string>::iterator iter;
for(iter = logEntries.begin(); iter != logEntries.end() && startAlpha>0; iter++)
int startX = 20;
int startY = YRES-20;
deque<std::pair<std::string, int> >::iterator iter;
for(iter = logEntries.begin(); iter != logEntries.end(); iter++)
{
string message = (*iter);
string message = (*iter).first;
int alpha = std::min((*iter).second, 255);
if (alpha <= 0) //erase this and everything older
{
logEntries.erase(iter, logEntries.end());
break;
}
startY -= 14;
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);
startAlpha-=14;
g->drawtext(startX, startY, message.c_str(), 255, 255, 255, alpha);
(*iter).second -= 3;
}
}
}

View File

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

View File

@ -19,7 +19,7 @@ public:
virtual ~Menu()
{
for(int i = 0; i < tools.size(); i++)
for(unsigned int i = 0; i < tools.size(); 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->SetActionCallback(new PropertyChanged(this));
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));
}

View File

@ -26,10 +26,10 @@ protected:
std::string icon;
std::string description;
QuickOption(std::string icon, std::string description, GameModel * m, Type type) :
icon(icon),
description(description),
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_):
ui::Window(ui::Point(-1, -1), ui::Point(200, 87)),
tool(tool_),
signID(signID_),
sim(sim_),
signPosition(position_),
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");
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)
{
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);
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;
break;

View File

@ -7,16 +7,16 @@
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)):
textureGen(textureGen),
toolID(id),
toolName(name),
toolDescription(description),
colRed(r),
colGreen(g),
colBlue(b),
textureGen(textureGen),
strength(1.0f),
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)
{
}
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)
{
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)
{
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;
}
}
if (dragging)
sim->CreateParts(position1.X, position1.Y, brush->GetRadius().X, brush->GetRadius().Y, PT_LIGH);
}
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) {
int radiusInfo = brush->GetRadius().X*4+brush->GetRadius().Y*4+7;
sim->CreateBox(position1.X, position1.Y, position2.X, position2.Y, toolID | (radiusInfo << 8));

View File

@ -23,6 +23,8 @@ protected:
int resolution;
std::string identifier;
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);
int GetToolID() { return toolID; }
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 DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2);
virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position);
int colRed, colBlue, colGreen;
};
class GameModel;
@ -103,17 +104,13 @@ public:
class Element_LIGH_Tool: public Tool
{
int nextUse;
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):
Tool(id, name, description, r, g, b, identifier, textureGen),
nextUse(0)
{
}
virtual ~Element_LIGH_Tool() {}
virtual void Draw(Simulation * sim, Brush * brush, ui::Point position);
Tool(id, name, description, r, g, b, identifier, textureGen)
{ }
virtual ~Element_LIGH_Tool() { }
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 DrawFill(Simulation * sim, Brush * brush, ui::Point position) { }
};
@ -133,10 +130,10 @@ public:
class Element_TESC_Tool: public ElementTool
{
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 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 DrawFill(Simulation * sim, Brush * brush, ui::Point position);
};
@ -145,11 +142,10 @@ class PlopTool: public ElementTool
{
public:
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)
{
}
virtual ~PlopTool() {}
virtual void Draw(Simulation * sim, Brush * brush, ui::Point position) {}
ElementTool(id, name, description, r, g, b, identifier, textureGen)
{ }
virtual ~PlopTool() { }
virtual void Draw(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 DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { }
@ -171,11 +167,11 @@ class WindTool: public Tool
{
public:
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 void Draw(Simulation * sim, Brush * brush, ui::Point position);
virtual ~WindTool() { }
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 DrawFill(Simulation * sim, Brush * brush, ui::Point position);
virtual void DrawRect(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2) { }
virtual void DrawFill(Simulation * sim, Brush * brush, ui::Point position) { }
};
#endif /* TOOL_H_ */

View File

@ -6,6 +6,10 @@ ToolButton::ToolButton(ui::Point position, ui::Point size, std::string text_, st
{
SetSelectionState(-1);
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)

View File

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

View File

@ -14,10 +14,10 @@ namespace ui {
AvatarButton::AvatarButton(Point position, Point size, std::string username):
Component(position, size),
name(username),
actionCallback(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):
Component(position, size),
Enabled(true),
ButtonText(buttonText),
isMouseInside(false),
toolTip(toolTip),
isButtonDown(false),
isMouseInside(false),
isTogglable(false),
toggle(false),
actionCallback(NULL),
Enabled(true),
toolTip(toolTip)
actionCallback(NULL)
{
TextPosition();
}
@ -134,14 +134,7 @@ void Button::Draw(const Point& screenPos)
if(Appearance.icon)
{
if(Enabled)
if(isButtonDown || (isTogglable && toggle))
{
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);
}
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, 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 = "");
virtual ~Button();
bool Toggleable;
bool Enabled;
virtual void OnMouseClick(int x, int y, unsigned int button);
@ -53,9 +52,9 @@ public:
void SetToolTip(std::string newToolTip) { toolTip = newToolTip; }
protected:
std::string ButtonText;
std::string toolTip;
std::string buttonDisplayText;
std::string ButtonText;
bool isButtonDown, isAltButtonDown, state, isMouseInside, isTogglable, toggle;
ButtonAction * actionCallback;

View File

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

View File

@ -12,15 +12,15 @@ using namespace ui;
Component::Component(Window* parent_state):
parentstate_(parent_state),
_parent(NULL),
Position(Point(0,0)),
Size(Point(0,0)),
Locked(false),
Visible(true),
drawn(false),
textPosition(0, 0),
textSize(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):
parentstate_(0),
_parent(NULL),
Position(position),
Size(size),
Locked(false),
Visible(true),
drawn(false),
textPosition(0, 0),
textSize(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():
parentstate_(NULL),
_parent(NULL),
Position(Point(0,0)),
Size(Point(0,0)),
Locked(false),
Visible(true),
drawn(false),
textPosition(0, 0),
textSize(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):
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)
{
for(int i = 0; i < buttons.size(); i++)
for (size_t i = 0; i < buttons.size(); i++)
{
RemoveComponent(buttons[i]);
delete buttons[i];
@ -40,7 +40,7 @@ void ContextMenu::Show(ui::Point position)
Position = position;
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);
tempButton->Appearance = Appearance;
@ -69,9 +69,9 @@ void ContextMenu::OnMouseDown(int x, int y, unsigned button)
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;
break;
@ -81,9 +81,9 @@ void ContextMenu::SetItem(int id, std::string text)
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);
break;

View File

@ -14,7 +14,7 @@ public:
int ID;
std::string Text;
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 {

View File

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

View File

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

View File

@ -1,6 +1,7 @@
#include <iostream>
#include <stack>
#include <cstdio>
#include <cmath>
#include "Config.h"
#include "Misc.h"
@ -13,26 +14,26 @@ using namespace ui;
using namespace std;
Engine::Engine():
FpsLimit(60.0f),
Scale(1),
Fullscreen(false),
FrameIndex(0),
lastBuffer(NULL),
prevBuffers(stack<pixel*>()),
windows(stack<Window*>()),
mousePositions(stack<Point>()),
state_(NULL),
maxWidth(0),
maxHeight(0),
windowTargetPosition(0, 0),
break_(false),
FastQuit(1),
lastTick(0),
mouseb_(0),
mousex_(0),
mousey_(0),
mousexp_(0),
mouseyp_(0),
FpsLimit(60.0f),
windows(stack<Window*>()),
mousePositions(stack<Point>()),
lastBuffer(NULL),
prevBuffers(stack<pixel*>()),
windowTargetPosition(0, 0),
FrameIndex(0),
Fullscreen(false),
Scale(1),
FastQuit(1),
break_(false),
lastTick(0)
maxWidth(0),
maxHeight(0)
{
}
@ -76,7 +77,7 @@ void Engine::Exit()
void Engine::ShowWindow(Window * window)
{
windowOpenState = 0.0f;
windowOpenState = 0;
if(window->Position.X==-1)
{
window->Position.X = (width_-window->Size.X)/2;
@ -182,22 +183,6 @@ void Engine::Tick()
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)
{
@ -217,12 +202,15 @@ void Engine::Tick()
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->Clear();
#ifndef OGLI
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
}
else

View File

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

View File

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

View File

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

View File

@ -75,9 +75,9 @@ Component* Panel::GetChild(unsigned idx)
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
children.erase(children.begin() + i);
@ -114,13 +114,13 @@ void Panel::Draw(const Point& screenPos)
#endif
// 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
if(children[i]->Visible)
if (children[i]->Visible)
{
//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.X + ViewportPosition.X < ui::Engine::Ref().GetWidth() &&
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)
{
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)
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)
{
// 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 &&
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)
{
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)
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)
{
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)
, 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(!childunclicked)
if (!childunclicked)
{
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)
{
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);
}
}
@ -363,9 +363,9 @@ void Panel::OnMouseUp(int x, int y, unsigned button)
void Panel::OnMouseWheel(int localx, int localy, int 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);
}
}
@ -374,13 +374,13 @@ void Panel::OnMouseWheelInside(int localx, int localy, int d)
{
XOnMouseWheelInside(localx, localy, d);
//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
if(!children[i]->Locked)
if (!children[i]->Locked)
{
//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 &&
localx < children[i]->Position.X + ViewportPosition.X + children[i]->Size.X &&
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):
Component(position, size),
progress(0),
intermediatePos(0.0f),
progressStatus(""),
progress(0)
progressStatus("")
{
SetStatus(startStatus);
SetProgress(startProgress);

View File

@ -18,15 +18,15 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
file(NULL),
save(save),
thumbnail(NULL),
isMouseInside(false),
isButtonDown(false),
actionCallback(NULL),
selectable(false),
selected(false),
waitingForThumb(false),
isMouseInsideAuthor(false),
isMouseInsideHistory(false),
showVotes(false)
showVotes(false),
isButtonDown(false),
isMouseInside(false),
selected(false),
selectable(false),
actionCallback(NULL)
{
if(save)
{
@ -42,7 +42,7 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
votes = format::NumberToString<int>(save->GetVotesUp()-save->GetVotesDown());
icon += 0xBB;
for (int j = 1; j < votes.length(); j++)
for (size_t j = 1; j < votes.length(); j++)
icon += 0xBC;
icon += 0xB9;
icon += 0xBA;
@ -88,19 +88,19 @@ SaveButton::SaveButton(Point position, Point size, SaveInfo * save):
SaveButton::SaveButton(Point position, Point size, SaveFile * file):
Component(position, size),
save(NULL),
file(file),
save(NULL),
thumbnail(NULL),
isMouseInside(false),
isButtonDown(false),
actionCallback(NULL),
selectable(false),
selected(false),
wantsDraw(false),
waitingForThumb(false),
isMouseInsideAuthor(false),
isMouseInsideHistory(false),
showVotes(false)
showVotes(false),
isButtonDown(false),
isMouseInside(false),
selected(false),
selectable(false),
actionCallback(NULL)
{
if(file)
{
@ -190,6 +190,8 @@ void SaveButton::Draw(const Point& screenPos)
else
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->id)
@ -253,14 +255,14 @@ void SaveButton::Draw(const Point& screenPos)
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);
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);
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);
}

View File

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

View File

@ -25,7 +25,6 @@ void Slider::updatePosition(int position)
float fPosition = position-3;
float fSize = Size.X-6;
float fSteps = 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)
{
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};
if(bgGradient)
free(bgGradient);

View File

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

View File

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

View File

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

View File

@ -102,14 +102,14 @@ enum ChromeStyle
Component* focusedComponent_;
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)
void finalise();
bool halt;
bool destruct;
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_; }
virtual bool doWork()
{
for(int i = 0; i < saves.size(); i++)
for (size_t i = 0; i < saves.size(); i++)
{
std::stringstream saveName;
saveName << "Deleting stamp [" << saves[i] << "] ...";
@ -76,6 +76,7 @@ void LocalBrowserController::removeSelectedC()
}
virtual void after()
{
Client::Ref().updateStamps();
c->RefreshSavesList();
}
};
@ -131,6 +132,12 @@ void LocalBrowserController::PrevPage()
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()
{
if(browserModel->GetSave())

View File

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

View File

@ -28,15 +28,16 @@ void LocalBrowserModel::AddObserver(LocalBrowserView * observer)
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]->NotifyPageChanged(this);
}
}
void LocalBrowserModel::notifyPageChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
observers[i]->NotifyPageChanged(this);
}
@ -79,10 +80,10 @@ void LocalBrowserModel::UpdateSavesList(int pageNumber)
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]);
if(tempSave)
if (tempSave)
{
savesList.push_back(tempSave);
}
@ -102,9 +103,9 @@ int LocalBrowserModel::GetPageCount()
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;
}
@ -117,9 +118,9 @@ void LocalBrowserModel::DeselectSave(std::string stampID)
{
bool changed = false;
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);
changed = true;
@ -132,7 +133,7 @@ restart:
void LocalBrowserModel::notifySelectedChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
LocalBrowserView* cObserver = observers[i];
cObserver->NotifySelectedChanged(this);

View File

@ -1,5 +1,6 @@
#include <sstream>
#include "client/Client.h"
#include "Format.h"
#include "LocalBrowserView.h"
#include "gui/interface/Button.h"
@ -15,17 +16,39 @@
#include "LocalBrowserModelException.h"
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");
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");
infoLabel = new ui::Label(ui::Point(51, WINDOWH-18), ui::Point(WINDOWW-102, 16), "Loading...");
AddComponent(infoLabel);
AddComponent(nextButton);
AddComponent(previousButton);
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
{
LocalBrowserView * v;
@ -83,16 +106,56 @@ LocalBrowserView::LocalBrowserView():
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)
{
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)
{
std::stringstream pageInfo;
pageInfo << "Page " << sender->GetPageNum() << " of " << sender->GetPageCount();
infoLabel->SetText(pageInfo.str());
pageCount = sender->GetPageCount();
if (!sender->GetSavesList().size()) //no saves
{
pageLabel->Visible = pageCountLabel->Visible = pageTextbox->Visible = false;
}
else
{
std::stringstream pageInfo;
pageInfo << "of " << pageCount;
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)
{
previousButton->Visible = false;
@ -113,12 +176,11 @@ void LocalBrowserView::NotifyPageChanged(LocalBrowserModel * sender)
void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
{
int i = 0;
int buttonWidth, buttonHeight, saveX = 0, saveY = 0, savesX = 5, savesY = 4, buttonPadding = 2;
int buttonAreaWidth, buttonAreaHeight, buttonXOffset, buttonYOffset;
vector<SaveFile*> saves = sender->GetSavesList();
for(i = 0; i < stampButtons.size(); i++)
for (size_t i = 0; i < stampButtons.size(); i++)
{
RemoveComponent(stampButtons[i]);
delete stampButtons[i];
@ -146,7 +208,7 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
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)
{
@ -174,12 +236,12 @@ void LocalBrowserView::NotifySavesListChanged(LocalBrowserModel * sender)
void LocalBrowserView::NotifySelectedChanged(LocalBrowserModel * sender)
{
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);
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);
}
}
@ -216,6 +278,4 @@ void LocalBrowserView::OnKeyRelease(int key, Uint16 character, bool shift, bool
c->SetMoveToFront(true);
}
LocalBrowserView::~LocalBrowserView() {
}
LocalBrowserView::~LocalBrowserView() { }

View File

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

View File

@ -20,7 +20,7 @@ void LoginModel::Login(string username, string password)
break;
case LoginError:
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)
statusText.replace(banStart, 15, ". Login at http://powdertoy.co.uk in order to see the full ban reason. Ban expires in");
break;
@ -50,7 +50,7 @@ bool LoginModel::GetStatus()
void LoginModel::notifyStatusChanged()
{
for(int i = 0; i < observers.size(); i++)
for (size_t i = 0; i < observers.size(); i++)
{
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")),
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")),
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]")),
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 = Size;

View File

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

View File

@ -2,8 +2,8 @@
#include "gui/dialogues/ErrorMessage.h"
OptionsController::OptionsController(GameModel * gModel_, ControllerCallback * callback_):
callback(callback_),
gModel(gModel_),
callback(callback_),
HasExited(false)
{
view = new OptionsView();
@ -44,9 +44,9 @@ void OptionsController::SetAirMode(int 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)

View File

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

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