Strip whitespace from files in repo (#553)

This commit is contained in:
wolfy1339 2018-04-03 21:46:01 -04:00 committed by jacob1
parent 31fcb1bfaa
commit 27f6a6b297
142 changed files with 651 additions and 650 deletions

2
.gitattributes vendored
View File

@ -1,2 +1,2 @@
.gitattributes export-ignore
.gitignore export-ignore
.gitignore export-ignore

4
TODO
View File

@ -1,5 +1,5 @@
HTTP API:
Make it OO,
Make it OO,
Use STL (i.e std::string for url, etc)
RequestBroker:
@ -16,4 +16,4 @@ Interface General:
Move interfaces into separate folder
Interface Elements:
Vertical Scrolling for Textbox,
Vertical Scrolling for Textbox,

View File

@ -300,3 +300,4 @@ extern unsigned char font_data[];
extern short font_ptrs[];
#endif
#endif

View File

@ -1,21 +1,21 @@
editor: editor.c
gcc -oeditor -DSCALE=1 -DFONTEDITOR editor.c -lSDL -lm -O3 -ffast-math -march=k8 -Wno-unused-result
editor.exe: editor.c
i686-w64-mingw32-gcc -oeditor.exe -DSCALE=1 -DFONTEDITOR editor.c -lmingw32 -lm -lSDLmain -lSDL -O3 -ffast-math -march=k8 -mwindows -Wno-unused-result
packer: packer.c
gcc -opacker -DFONTEDITOR packer.c -lm -O3 -ffast-math -march=k8 -Wno-unused-result
packer.exe: packer.c
i686-w64-mingw32-gcc -opacker.exe -DFONTEDITOR packer.c -lm -O3 -ffast-math -march=k8 -Wno-unused-result
unpacker: unpacker.c
gcc -ounpacker -DFONTEDITOR unpacker.c -lm -O3 -ffast-math -march=k8 -Wno-unused-result
unpacker.exe: unpacker.c
i686-w64-mingw32-gcc -ounpacker.exe -DFONTEDITOR unpacker.c -lm -O3 -ffast-math -march=k8 -Wno-unused-result
clean:
rm -f editor packer unpacker editor.exe packer.exe unpacker.exe

View File

@ -374,7 +374,7 @@ int main(int argc, char *argv[])
#endif
drawchar(vid_buf, 32, 192+32*CELLH, c, 255, 255, 255);
sprintf(hex, "%02X", c);
drawtext(vid_buf, 32, 192+34*CELLH, hex, 255, 255, 255);
#ifdef EXTENDED_FONT

View File

@ -24,7 +24,7 @@ def generateElements(elementFiles, outputCpp, outputH):
f = open(elementFile, "r")
except:
f = open("src/simulation/elements/"+elementFile, "r")
fileData = f.read()
f.close()
@ -144,7 +144,7 @@ std::vector<Element> GetElements()
def generateTools(toolFiles, outputCpp, outputH):
toolClasses = {}
toolHeader = """#ifndef TOOLCLASSES_H
#define TOOLCLASSES_H
@ -153,7 +153,7 @@ def generateTools(toolFiles, outputCpp, outputH):
#include "simulation/simtools/SimTool.h"
"""
directives = []
for toolFile in toolFiles:
@ -163,14 +163,14 @@ def generateTools(toolFiles, outputCpp, outputH):
f = open("src/simulation/simtools/"+toolFile, "r")
fileData = f.read()
f.close()
directiveMatcher = '//#TPT-Directive\s+([^\r\n]+)'
matcher = re.compile(directiveMatcher)
directiveMatches = matcher.findall(fileData)
for match in directiveMatches:
directives.append(match.split(" "))
classDirectives = []
usedIDs = []
for d in directives:
@ -182,11 +182,11 @@ def generateTools(toolFiles, outputCpp, outputH):
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":
toolClasses[d[1]].append(" ".join(d[2:])+";")
for className, classMembers in list(toolClasses.items()):
toolHeader += """
class {0}: public SimTool
@ -197,24 +197,24 @@ public:
virtual int Perform(Simulation * sim, Particle * cpart, int x, int y, int brushX, int brushY, float strength);
}};
""".format(className, str.join("\n", classMembers))
toolHeader += """
std::vector<SimTool*> GetTools();
#endif
"""
toolContent = """#include "ToolClasses.h"
std::vector<SimTool*> GetTools()
{
std::vector<SimTool*> tools;
""";
toolIDs = sorted(classDirectives, key=lambda directive: directive[3])
for d in toolIDs:
toolContent += """ tools.push_back(new %s());
""" % (d[1])
toolContent += """ return tools;
}
""";
@ -226,7 +226,7 @@ std::vector<SimTool*> GetTools()
f = open(outputH, "w")
f.write(toolHeader)
f.close()
f = open(outputCpp, "w")
f.write(toolContent)
f.close()

View File

@ -26,7 +26,7 @@
import os
import new
import sys
##
##
import SCons
if sys.version_info < (2,6,0):
@ -98,16 +98,16 @@ def MFProgramEmitter(target, source, env):
"""Ensures that target list is complete, and does validity checking. Sets precious"""
if len(target) == 1 and len(source) > 1:
#Looks like the user specified many sources and SCons created 1 target
#targets are implicit, but the builder doesn't know how to handle
#targets are implicit, but the builder doesn't know how to handle
#suffixes for multiple target files, so we'll do it here
objdir = env.get('OBJDIR', '')
#target = [os.path.join(
# objdir,
# objdir,
# os.path.splitext(
# os.path.basename(str(i)))[0] + '.o' ) for i in source]
elif len(source) == 1 and 'OBJDIR' in env:
target = os.path.join(
env['OBJDIR'],
env['OBJDIR'],
os.path.splitext(
os.path.basename(str(source[0])))[0] + '.o' )
else:
@ -129,7 +129,7 @@ def MFProgramEmitter(target, source, env):
return target, source
def MFProgramGenerator(source, target, env, for_signature):
#Rebuild everything if
#Rebuild everything if
# a) the number of dependencies has changed
# b) any target does not exist
# c) the build command has changed
@ -137,7 +137,7 @@ def MFProgramGenerator(source, target, env, for_signature):
#The signature of this builder should always be the same, because the
#multifile compile is always functionally equivalent to rebuilding
#everything
if for_signature:
pared_sources = source
else:
@ -145,9 +145,9 @@ def MFProgramGenerator(source, target, env, for_signature):
assert len(set([os.path.splitext(str(i))[1] for i in source])) == 1, \
"All source files must have the same extension."
pared_sources = []
src_names = [os.path.splitext(os.path.basename(str(i)))[0]
src_names = [os.path.splitext(os.path.basename(str(i)))[0]
for i in source]
tgt_names = [os.path.splitext(os.path.basename(str(t)))[0]
tgt_names = [os.path.splitext(os.path.basename(str(t)))[0]
for t in target]
ni = target[0].get_binfo()
oi = target[0].get_stored_info().binfo
@ -191,7 +191,7 @@ def MFProgramGenerator(source, target, env, for_signature):
prefixed_sources = [relpath(str(i), destdir) for i in pared_sources]
prefixed_sources_str = ' '.join([str(i) for i in prefixed_sources])
lang_ext = os.path.splitext(prefixed_sources[0])[1]
tgt_names2 = [os.path.splitext(os.path.basename(str(t)))[0]
tgt_names2 = [os.path.splitext(os.path.basename(str(t)))[0]
for t in target]
_CPPPATH = []
@ -201,7 +201,7 @@ def MFProgramGenerator(source, target, env, for_signature):
##_CPPPATH.append(relpath(i[1:], destdir))
_CPPPATH.append(i)
#else:
# _CPPPATH.append(relpath(os.path.join(sconscript_dir, i),
# _CPPPATH.append(relpath(os.path.join(sconscript_dir, i),
# destdir))
defines = ""
@ -231,11 +231,11 @@ def MFProgramGenerator(source, target, env, for_signature):
def generate(env):
"""Adds the MFObject builder to your environment"""
MFProgramBld = env.Builder(generator = MFProgramGenerator,
MFProgramBld = env.Builder(generator = MFProgramGenerator,
emitter = MFProgramEmitter,
suffix = '.o',
suffix = '.o',
source_scanner=SCons.Tool.SourceFileScanner)
MFProgramBld.get_single_executor = new.instancemethod(MF_get_single_executor,
MFProgramBld.get_single_executor = new.instancemethod(MF_get_single_executor,
MFProgramBld, MFProgramBld.__class__)
env.Append(BUILDERS = {'MFProgram': MFProgramBld})
env.Append(BUILDERS = {'MFProgram': MFProgramBld})

View File

@ -70,4 +70,4 @@ def relpath(path, start=curdir):
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
return join(*rel_list)

View File

@ -310,7 +310,7 @@ std::vector<char> format::VideoBufferToPNG(const VideoBuffer & vidBuf)
currentRow[rowPos++] = PIXB(vidBuf.Buffer[(y*vidBuf.Width)+x]);
}
uncompressedData[dataPos++] = 2; //Up Sub(x) filter
uncompressedData[dataPos++] = 2; //Up Sub(x) filter
for(int b = 0; b < rowPos; b++)
{
int filteredByte = (currentRow[b]-previousRow[b])&0xFF;
@ -329,7 +329,7 @@ std::vector<char> format::VideoBufferToPNG(const VideoBuffer & vidBuf)
unsigned char * compressedData = new unsigned char[compressedBufferSize];
int result;
z_stream zipStream;
z_stream zipStream;
zipStream.zalloc = Z_NULL;
zipStream.zfree = Z_NULL;
zipStream.opaque = Z_NULL;

View File

@ -57,7 +57,7 @@ void writeFile(std::string filename, std::vector<char> & fileData)
}
int main(int argc, char *argv[])
{
{
ui::Engine * engine;
std::string outputPrefix, inputFilename;
std::vector<char> inputFile;
@ -76,7 +76,7 @@ int main(int argc, char *argv[])
readFile(inputFilename, inputFile);
ui::Engine::Ref().g = new Graphics();
engine = &ui::Engine::Ref();
engine->Begin(WINDOWW, WINDOWH);

View File

@ -50,7 +50,7 @@ static NSString *getApplicationName(void)
dict = (const NSDictionary *)CFBundleGetInfoDictionary(CFBundleGetMainBundle());
if (dict)
appName = [dict objectForKey: @"CFBundleName"];
if (![appName length])
appName = [[NSProcessInfo processInfo] processName];
@ -136,10 +136,10 @@ static void setApplicationMenu(void)
NSMenuItem *menuItem;
NSString *title;
NSString *appName;
appName = getApplicationName();
appleMenu = [[NSMenu alloc] initWithTitle:@""];
/* Add menu items */
title = [@"About " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
@ -159,7 +159,7 @@ static void setApplicationMenu(void)
title = [@"Quit " stringByAppendingString:appName];
[appleMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
/* Put menu into the menubar */
menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[menuItem setSubmenu:appleMenu];
@ -181,17 +181,17 @@ static void setupWindowMenu(void)
NSMenuItem *menuItem;
windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
/* "Minimize" item */
menuItem = [[NSMenuItem alloc] initWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"];
[windowMenu addItem:menuItem];
[menuItem release];
/* Put menu into the menubar */
windowMenuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
[windowMenuItem setSubmenu:windowMenu];
[[NSApp mainMenu] addItem:windowMenuItem];
/* Tell the application object that this is now the window menu */
[NSApp setWindowsMenu:windowMenu];
@ -208,7 +208,7 @@ static void CustomApplicationMain (int argc, char **argv)
/* Ensure the application object is initialised */
[NSApplication sharedApplication];
#ifdef SDL_USE_CPS
{
CPSProcessSerNum PSN;
@ -228,10 +228,10 @@ static void CustomApplicationMain (int argc, char **argv)
/* Create SDLMain and make it the app delegate */
sdlMain = [[SDLMain alloc] init];
[NSApp setDelegate:sdlMain];
/* Start the main event loop */
[NSApp run];
[sdlMain release];
[pool release];
}
@ -337,27 +337,27 @@ static void CustomApplicationMain (int argc, char **argv)
bufferSize = selfLen + aStringLen - aRange.length;
buffer = (unichar *)NSAllocateMemoryPages(bufferSize*sizeof(unichar));
/* Get first part into buffer */
localRange.location = 0;
localRange.length = aRange.location;
[self getCharacters:buffer range:localRange];
/* Get middle part into buffer */
localRange.location = 0;
localRange.length = aStringLen;
[aString getCharacters:(buffer+aRange.location) range:localRange];
/* Get last part into buffer */
localRange.location = aRange.location + aRange.length;
localRange.length = selfLen - localRange.location;
[self getCharacters:(buffer+aRange.location+aStringLen) range:localRange];
/* Build output string */
result = [NSString stringWithCharacters:buffer length:bufferSize];
NSDeallocateMemoryPages(buffer, bufferSize);
return result;
}
@ -371,7 +371,7 @@ char * readClipboard()
NSArray *classes = [[NSArray alloc] initWithObjects:[NSString class], nil];
NSDictionary *options = [NSDictionary dictionary];
NSArray *clipboardItems = [clipboard readObjectsForClasses:classes options:options];
if(clipboardItems == nil || [clipboardItems count] == 0) return NULL;
NSString *newString = [clipboardItems objectAtIndex:0];

View File

@ -110,7 +110,7 @@ Client::Client():
}
catch (std::exception &e)
{
}
configFile.close();
firstRun = false;
@ -191,19 +191,19 @@ bool Client::DoInstallation()
char *AppDataPath = NULL;
iconname = (char*)malloc(strlen(currentfilename)+6);
sprintf(iconname, "%s,-102", currentfilename);
//Create Roaming application data folder
/*if(!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, AppDataPath)))
/*if(!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL, 0, AppDataPath)))
{
returnval = 0;
goto finalise;
}*/
AppDataPath = _getcwd(NULL, 0);
//Move Game executable into application data folder
//TODO: Implement
opencommand = (char*)malloc(strlen(currentfilename)+53+strlen(AppDataPath));
protocolcommand = (char*)malloc(strlen(currentfilename)+53+strlen(AppDataPath));
/*if((strlen(AppDataPath)+strlen(APPDATA_SUBDIR "\\Powder Toy"))<MAX_PATH)
@ -238,7 +238,7 @@ bool Client::DoInstallation()
goto finalise;
}
RegCloseKey(newkey);
//Set Protocol DefaultIcon
rresult = RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\Classes\\ptsave\\DefaultIcon", 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &newkey, NULL);
if (rresult != ERROR_SUCCESS) {
@ -251,8 +251,8 @@ bool Client::DoInstallation()
returnval = 0;
goto finalise;
}
RegCloseKey(newkey);
RegCloseKey(newkey);
//Set Protocol Launch command
rresult = RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\Classes\\ptsave\\shell\\open\\command", 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &newkey, NULL);
if (rresult != ERROR_SUCCESS) {
@ -335,7 +335,7 @@ bool Client::DoInstallation()
goto finalise;
}
RegCloseKey(newkey);
returnval = 1;
finalise:
@ -343,7 +343,7 @@ bool Client::DoInstallation()
free(opencommand);
free(protocolcommand);
free(currentfilename);
return returnval;
#elif defined(LIN)
#include "icondoc.h"
@ -449,7 +449,7 @@ bool Client::DoInstallation()
fclose(f);
success = system("xdg-icon-resource install --noupdate --context mimetypes --size 32 powdertoy-save-32.png application-vnd.powdertoy.save") && success;
success = system("xdg-icon-resource install --noupdate --context mimetypes --size 16 powdertoy-save-16.png application-vnd.powdertoy.save") && success;
success = system("xdg-icon-resource install --noupdate --novendor --size 48 powdertoy.png") && success;
success = system("xdg-icon-resource install --noupdate --novendor --size 48 powdertoy.png") && success;
success = system("xdg-icon-resource forceupdate") && success;
success = system("xdg-mime default powdertoy-tpt-open.desktop application/vnd.powdertoy.save") && success;
success = system("xdg-mime default powdertoy-tpt-ptsave.desktop x-scheme-handler/ptsave") && success;
@ -552,7 +552,7 @@ std::vector<std::string> Client::DirectorySearch(std::string directory, std::str
bool searchMatch = !search.size();
if(search.size() && tempfilename.find(search)!=std::string::npos)
searchMatch = true;
if(searchMatch && extensionMatch)
searchResults.push_back(filename);
}
@ -942,7 +942,7 @@ void Client::WritePrefs()
{
std::ofstream configFile;
configFile.open("powder.pref", std::ios::trunc);
if (configFile)
{
if (authUser.UserID)
@ -1145,7 +1145,7 @@ std::string Client::AddStamp(GameSave * saveData)
std::string filename = std::string(STAMPS_DIR PATH_SEP + saveID.str()+".stm").c_str();
MakeDirectory(STAMPS_DIR);
Json::Value stampInfo;
stampInfo["type"] = "stamp";
stampInfo["username"] = authUser.Username;
@ -1499,7 +1499,7 @@ RequestStatus Client::AddComment(int saveID, std::string comment)
{
std::stringstream userIDStream;
userIDStream << authUser.UserID;
const char *const postNames[] = { "Comment", NULL };
const char *const postDatas[] = { (char*)(comment.c_str()) };
size_t postLengths[] = { comment.length() };
@ -1664,7 +1664,7 @@ SaveInfo * Client::GetSave(int saveID, int saveDate)
for (Json::UInt j = 0; j < tagsArray.size(); j++)
tempTags.push_back(tagsArray[j].asString());
SaveInfo * tempSave = new SaveInfo(tempID, tempCreatedDate, tempUpdatedDate, tempScoreUp,
SaveInfo * tempSave = new SaveInfo(tempID, tempCreatedDate, tempUpdatedDate, tempScoreUp,
tempScoreDown, tempMyScore, tempUsername, tempName,
tempDescription, tempPublished, tempTags);
tempSave->Comments = tempComments;
@ -1809,7 +1809,7 @@ std::vector<std::pair<std::string, int> > * Client::GetTags(int start, int count
if(query.length())
urlStream << format::URLEncode(query);
}
data = http_simple_get((char *)urlStream.str().c_str(), &dataStatus, &dataLength);
if(dataStatus == 200 && data)
{
@ -2026,7 +2026,7 @@ void Client::MergeStampAuthorInfo(Json::Value stampAuthors)
return;
if (authors["username"] != stampAuthors["username"])
{
// 2nd arg of MergeAuthorInfo needs to be an array
// 2nd arg of MergeAuthorInfo needs to be an array
Json::Value toAdd;
toAdd.append(stampAuthors);
MergeAuthorInfo(toAdd);

View File

@ -2364,18 +2364,18 @@ char * GameSave::serialiseOPS(unsigned int & dataLength)
{
//Find the first particle in this position
i = partsPosFirstMap[y*fullW + x];
//Loop while there is a pmap entry
while (i)
{
//Turn pmap entry into a partsptr index
i = i>>8;
if (particles[i].type==PT_SOAP)
{
//Only save forward link for each particle, back links can be deduced from other forward links
//linkedIndex is index within saved particles + 1, 0 means not saved or no link
unsigned linkedIndex = 0;
if ((particles[i].ctype&2) && particles[i].tmp>=0 && particles[i].tmp<NPART)
{
@ -2385,7 +2385,7 @@ char * GameSave::serialiseOPS(unsigned int & dataLength)
soapLinkData[soapLinkDataLen++] = (linkedIndex&0x00FF00)>>8;
soapLinkData[soapLinkDataLen++] = (linkedIndex&0x0000FF);
}
//Get the pmap entry for the next particle in the same position
i = partsPosLink[i];
}

View File

@ -70,7 +70,7 @@ public:
class GameSave
{
public:
int blockWidth, blockHeight;
bool fromNewerVersion;
int majorVersion;
@ -88,7 +88,7 @@ public:
float ** velocityX;
float ** velocityY;
float ** ambientHeat;
//Simulation Options
bool waterEEnabled;
bool legacyEnable;
@ -142,14 +142,14 @@ public:
}
return *this;
}
inline GameSave& operator << (sign v)
{
if(signs.size()<MAXSIGNS && v.text.length())
signs.push_back(v);
return *this;
}
private:
bool expanded;
bool hasOriginalData;

View File

@ -69,7 +69,7 @@ RequestBroker::ProcessResponse APIRequest::Process(RequestBroker & rb)
}
}
}
else
else
{
#ifdef DEBUG
std::cout << typeid(*this).name() << " New Request for " << URL << std::endl;

View File

@ -8,7 +8,7 @@ public:
bool Post;
APIResultParser * Parser;
std::string URL;
std::map<std::string, std::string> PostData;
std::map<std::string, std::string> PostData;
void * HTTPContext;
APIRequest(std::string url, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0);
APIRequest(std::string url, std::map<std::string, std::string>, APIResultParser * parser, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0);

View File

@ -76,14 +76,14 @@ RequestBroker::ProcessResponse ImageRequest::Process(RequestBroker & rb)
{
#ifdef DEBUG
std::cout << typeid(*this).name() << " Request for " << URL << " failed with status " << status << std::endl;
#endif
#endif
free(data);
return RequestBroker::Failed;
}
}
}
else
else
{
//Check for ongoing requests
for(std::vector<Request*>::iterator iter = rb.activeRequests.begin(), end = rb.activeRequests.end(); iter != end; ++iter)
@ -110,7 +110,7 @@ RequestBroker::ProcessResponse ImageRequest::Process(RequestBroker & rb)
RequestTime = time(NULL);
}
}
if(image)
{

View File

@ -86,19 +86,19 @@ void RequestBroker::RenderThumbnail(GameSave * gameSave, int width, int height,
void RequestBroker::RenderThumbnail(GameSave * gameSave, bool decorations, bool fire, int width, int height, RequestListener * tListener)
{
ListenerHandle handle = AttachRequestListener(tListener);
ThumbRenderRequest * r = new ThumbRenderRequest(new GameSave(*gameSave), decorations, fire, width, height, handle);
pthread_mutex_lock(&requestQueueMutex);
requestQueue.push_back(r);
pthread_mutex_unlock(&requestQueueMutex);
assureRunning();
}
void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int height, RequestListener * tListener)
{
std::stringstream urlStream;
std::stringstream urlStream;
urlStream << "http://" << STATICSERVER << "/" << saveID;
if(saveDate)
{
@ -111,7 +111,7 @@ void RequestBroker::RetrieveThumbnail(int saveID, int saveDate, int width, int h
void RequestBroker::RetrieveAvatar(std::string username, int width, int height, RequestListener * tListener)
{
std::stringstream urlStream;
std::stringstream urlStream;
urlStream << "http://" << STATICSERVER << "/avatars/" << username << ".pti";
RetrieveImage(urlStream.str(), width, height, tListener);
@ -127,7 +127,7 @@ void RequestBroker::Start(Request * request, RequestListener * tListener, int id
requestQueue.push_back(request);
pthread_mutex_unlock(&requestQueueMutex);
assureRunning();
assureRunning();
}
void RequestBroker::RetrieveImage(std::string imageUrl, int width, int height, RequestListener * tListener)
@ -135,7 +135,7 @@ void RequestBroker::RetrieveImage(std::string imageUrl, int width, int height, R
ListenerHandle handle = AttachRequestListener(tListener);
ImageRequest * r = new ImageRequest(imageUrl, width, height, handle);
pthread_mutex_lock(&requestQueueMutex);
requestQueue.push_back(r);
pthread_mutex_unlock(&requestQueueMutex);
@ -167,7 +167,7 @@ void RequestBroker::FlushThumbQueue()
}
delete completeQueue.front();
completeQueue.pop();
}
}
pthread_mutex_unlock(&completeQueueMutex);
}
@ -231,7 +231,7 @@ void RequestBroker::thumbnailQueueProcessTH()
{
break;
}
else
else
{
activeRequests.push_back(*newReq);
newReq = requestQueue.erase(newReq);

View File

@ -21,7 +21,7 @@ class RequestBroker: public Singleton<RequestBroker>
friend class ThumbRenderRequest;
public:
class Request;
private:
private:
pthread_mutex_t listenersMutex;
pthread_mutex_t runningMutex;
@ -58,7 +58,7 @@ public:
void RetrieveThumbnail(int saveID, int width, int height, RequestListener * tListener);
void RetrieveAvatar(std::string username, int width, int height, RequestListener * tListener);
void Start(Request * request, RequestListener * tLIstener, int identifier = 0);
bool CheckRequestListener(ListenerHandle handle);
ListenerHandle AttachRequestListener(RequestListener * tListener);
void DetachRequestListener(RequestListener * tListener);

View File

@ -69,7 +69,7 @@ RequestBroker::ProcessResponse WebRequest::Process(RequestBroker & rb)
}
}
}
else
else
{
#ifdef DEBUG
std::cout << typeid(*this).name() << " New Request for " << URL << std::endl;

View File

@ -6,7 +6,7 @@ class WebRequest: public RequestBroker::Request
public:
bool Post;
std::string URL;
std::map<std::string, std::string> PostData;
std::map<std::string, std::string> PostData;
void * HTTPContext;
WebRequest(std::string url, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0);
WebRequest(std::string url, std::map<std::string, std::string>, ListenerHandle listener = ListenerHandle(0, (RequestListener*)0), int identifier = 0);

View File

@ -39,7 +39,7 @@ void ElementPopulationDebug::Draw()
maxValString = format::NumberToString<int>(maxAverage);
halfValString = format::NumberToString<int>(maxAverage/2);
g->fillrect(xStart-5, yBottom - 263, bars+10+Graphics::textwidth(maxValString.c_str())+10, 255 + 13, 0, 0, 0, 180);
@ -53,7 +53,7 @@ void ElementPopulationDebug::Draw()
int barX = bars;//*2;
g->draw_line(xStart+barX, yBottom+3, xStart+barX, yBottom+2, PIXR(sim->elements[i].Colour), PIXG(sim->elements[i].Colour), PIXB(sim->elements[i].Colour), 255);
if(sim->elementCount[i])
if(sim->elementCount[i])
{
if(barSize > 256)
{
@ -61,7 +61,7 @@ void ElementPopulationDebug::Draw()
g->blendpixel(xStart+barX, yBottom-barSize-3, PIXR(sim->elements[i].Colour), PIXG(sim->elements[i].Colour), PIXB(sim->elements[i].Colour), 255);
g->blendpixel(xStart+barX, yBottom-barSize-5, PIXR(sim->elements[i].Colour), PIXG(sim->elements[i].Colour), PIXB(sim->elements[i].Colour), 255);
g->blendpixel(xStart+barX, yBottom-barSize-7, PIXR(sim->elements[i].Colour), PIXG(sim->elements[i].Colour), PIXB(sim->elements[i].Colour), 255);
} else {
} else {
g->draw_line(xStart+barX, yBottom-barSize-3, xStart+barX, yBottom-barSize-2, 255, 255, 255, 180);
}

View File

@ -5,10 +5,10 @@ int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int
{
drawtext(x-1, y-1, s, 0, 0, 0, 120);
drawtext(x+1, y+1, s, 0, 0, 0, 120);
drawtext(x-1, y+1, s, 0, 0, 0, 120);
drawtext(x+1, y-1, s, 0, 0, 0, 120);
return drawtext(x, y, s, r, g, b, a);
}
@ -60,7 +60,7 @@ int PIXELMETHODS_CLASS::drawtext(int x, int y, const char *s, int r, int g, int
switch (s[1])
{
case 'w':
r = g = b = 255;
r = g = b = 255;
break;
case 'g':
r = g = b = 192;
@ -241,7 +241,7 @@ void PIXELMETHODS_CLASS::xor_bitmap(unsigned char * bitmap, int x, int y, int w,
{
//glEnable(GL_COLOR_LOGIC_OP);
//glLogicOp(GL_XOR);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, textTexture);

View File

@ -12,9 +12,9 @@ Graphics::Graphics():
// pthread_mutex_init (&gMutex, NULL);
LoadDefaults();
InitialiseTextures();
//Texture for main UI
}
@ -38,28 +38,28 @@ void Graphics::LoadDefaults()
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
void Graphics::InitialiseTextures()
void Graphics::InitialiseTextures()
{
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &vidBuf);
glBindTexture(GL_TEXTURE_2D, vidBuf);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WINDOWW, WINDOWH, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glBindTexture(GL_TEXTURE_2D, 0);
glGenTextures(1, &textTexture);
glBindTexture(GL_TEXTURE_2D, textTexture);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
}

View File

@ -5,10 +5,10 @@ int PIXELMETHODS_CLASS::drawtext_outline(int x, int y, const char *s, int r, int
{
drawtext(x-1, y-1, s, 0, 0, 0, 120);
drawtext(x+1, y+1, s, 0, 0, 0, 120);
drawtext(x-1, y+1, s, 0, 0, 0, 120);
drawtext(x+1, y-1, s, 0, 0, 0, 120);
return drawtext(x, y, s, r, g, b, a);
}

View File

@ -569,7 +569,7 @@ VideoBuffer * Renderer::WallIcon(int wallID, int width, int height)
for (i=0; i<(width/4)+j; i++)
{
if (!(i&j&1))
newTexture->SetPixel(i, j, PIXR(pc), PIXG(pc), PIXB(pc), 255);
newTexture->SetPixel(i, j, PIXR(pc), PIXG(pc), PIXB(pc), 255);
}
for (; i<width; i++)
{
@ -601,7 +601,7 @@ VideoBuffer * Renderer::WallIcon(int wallID, int width, int height)
for (; i<width; i++)
{
if (!(i&j&1))
newTexture->SetPixel(i, j, PIXR(pc), PIXG(pc), PIXB(pc), 255);
newTexture->SetPixel(i, j, PIXR(pc), PIXG(pc), PIXB(pc), 255);
}
}
}
@ -994,7 +994,7 @@ void Renderer::DrawSigns()
drawtext(x+3, y+3, text, 211, 211, 40, 255);
else
drawtext(x+3, y+3, text, 0, 191, 255, 255);
if (signs[i].ju != sign::None)
{
int x = signs[i].x;
@ -2537,7 +2537,7 @@ pixel Renderer::GetPixel(int x, int y)
if (x<0 || y<0 || x>=VIDXRES || y>=VIDYRES)
return 0;
#ifdef OGLR
return 0;
return 0;
#else
return vid[(y*VIDXRES)+x];
#endif
@ -2794,12 +2794,12 @@ Renderer::Renderer(Graphics * g, Simulation * sim):
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &textTexture);
glBindTexture(GL_TEXTURE_2D, textTexture);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
@ -2935,7 +2935,7 @@ unsigned int Renderer::GetColourMode()
VideoBuffer Renderer::DumpFrame()
{
#ifdef OGLR
#elif defined(OGLI)
#elif defined(OGLI)
VideoBuffer newBuffer(XRES, YRES);
std::copy(vid, vid+(XRES*YRES), newBuffer.Buffer);
return newBuffer;

View File

@ -7,12 +7,12 @@ namespace style {
ui::Colour Colour::InformationTitle = ui::Colour(140, 140, 255);
ui::Colour Colour::WarningTitle = ui::Colour(255, 216, 32);
ui::Colour Colour::ErrorTitle = ui::Colour(255, 64, 32);
ui::Colour Colour::ConfirmButton = ui::Colour(255, 255, 50);
ui::Colour Colour::ActiveBorder = ui::Colour(255, 255, 255);
ui::Colour Colour::InactiveBorder = ui::Colour(100, 100, 100);
ui::Colour Colour::ActiveBackground = ui::Colour(50, 50, 50);
ui::Colour Colour::InactiveBackground = ui::Colour(0, 0, 0);
}

View File

@ -11,17 +11,17 @@ namespace style
static ui::Colour InformationTitle;
static ui::Colour WarningTitle;
static ui::Colour ErrorTitle;
static ui::Colour ConfirmButton;
static ui::Colour ActiveBorder;
static ui::Colour InactiveBorder;
static ui::Colour ActiveBackground;
static ui::Colour InactiveBackground;
};
class Metrics
{
{
};
}

View File

@ -126,7 +126,7 @@ void ColourPickerActivity::OnMouseMove(int x, int y, int dx, int dy)
currentHue = (float(x)/float(255))*359.0f;
currentSaturation = 255-(y*2);
if(currentSaturation > 255)
currentSaturation = 255;
if(currentSaturation < 0)

View File

@ -46,7 +46,7 @@ ErrorMessage::ErrorMessage(std::string title, std::string message, ErrorMessage
AddComponent(okayButton);
SetOkayButton(okayButton);
SetCancelButton(okayButton);
MakeActiveWindow();
}

View File

@ -72,7 +72,7 @@ InformationMessage::InformationMessage(std::string title, std::string message, b
AddComponent(okayButton);
SetOkayButton(okayButton);
SetCancelButton(okayButton);
MakeActiveWindow();
}

View File

@ -52,7 +52,7 @@ SaveIDMessage::SaveIDMessage(int id):
// This button has multiple personalities
SetOkayButton(okayButton);
SetCancelButton(okayButton);
MakeActiveWindow();
}

View File

@ -39,7 +39,7 @@ public:
}
};
//Currently, reading is done on another thread, we can't render outside the main thread due to some bullshit with OpenGL
//Currently, reading is done on another thread, we can't render outside the main thread due to some bullshit with OpenGL
class LoadFilesTask: public Task
{
std::string directory;

View File

@ -24,7 +24,7 @@ public:
{
ui::Point newSize = rectSize_;
//Ensure the rect has odd dimensions so we can pull an integer radius with a 1x1 centre
//Ensure the rect has odd dimensions so we can pull an integer radius with a 1x1 centre
if(!(newSize.X % 2))
newSize.X += 1;
if(!(newSize.Y % 2))
@ -42,7 +42,7 @@ public:
{
if(newBitmap[(y*rectSize_.X)+x] >= 128)
origBitmap[(y*size.X)+x] = newBitmap[(y*rectSize_.X)+x];
}
}
}
SetRadius(radius);

View File

@ -16,7 +16,7 @@ void Brush::RenderRect(Renderer * ren, ui::Point position1, ui::Point position2)
position1.X += width;
width *= -1;
}
ren->xor_line(position1.X, position1.Y, position1.X+width, position1.Y);
if(height>0){
ren->xor_line(position1.X, position1.Y+height, position1.X+width, position1.Y+height);

View File

@ -42,13 +42,13 @@ public:
{
SetRadius(size_);
};
//Radius of the brush 0x0 - infxinf (Radius of 0x0 would be 1x1, radius of 1x1 would be 3x3)
ui::Point GetRadius()
{
return radius;
}
//Size of the brush bitmap mask, 1x1 - infxinf
ui::Point GetSize()
{

View File

@ -15,10 +15,10 @@ public:
std::vector<std::string> GetFavoritesList();
bool IsFavorite(std::string identifier);
bool AnyFavorites();
void AddFavorite(std::string identifier);
void RemoveFavorite(std::string identifier);
void SaveFavoritesToPrefs();
void LoadFavoritesFromPrefs();
};

View File

@ -1251,7 +1251,7 @@ void GameController::OpenLocalSaveWindow(bool asCurrent)
localSaveInfo["date"] = (Json::Value::UInt64)time(NULL);
Client::Ref().SaveAuthorInfo(&localSaveInfo);
gameSave->authors = localSaveInfo;
gameModel->SetSaveFile(&tempSave);
Client::Ref().MakeDirectory(LOCAL_SAVE_DIR);
std::vector<char> saveData = gameSave->Serialise();

View File

@ -206,7 +206,7 @@ void GameModel::UpdateQuickOptions()
{
QuickOption * option = *iter;
option->Update();
}
}
}
void GameModel::BuildQuickOptionMenu(GameController * controller)
@ -316,7 +316,7 @@ void GameModel::BuildMenus()
menuList[SC_WALL]->AddTool(tempTool);
//sim->wtypes[i]
}
//Build menu for tools
for (size_t i = 0; i < sim->tools.size(); i++)
{
@ -385,7 +385,7 @@ void GameModel::BuildMenus()
void GameModel::BuildFavoritesMenu()
{
menuList[SC_FAVORITES]->ClearTools();
std::vector<std::string> favList = Favorite::Ref().GetFavoritesList();
for (size_t i = 0; i < favList.size(); i++)
{
@ -718,7 +718,7 @@ void GameModel::SetSaveFile(SaveFile * newSave)
Client::Ref().OverwriteAuthorInfo(saveData->authors);
}
}
notifySaveChanged();
UpdateQuickOptions();
}

View File

@ -127,7 +127,7 @@ void PropertyWindow::SetProperty()
if (properties[property->GetOption().second].Type == StructProperty::ParticleType && (type = sim->GetParticleType(value)) != -1)
{
v = type;
#ifdef DEBUG
std::cout << "Got type from particle name" << std::endl;
#endif
@ -139,13 +139,13 @@ void PropertyWindow::SetProperty()
buffer >> v;
}
}
if (properties[property->GetOption().second].Name == "type" && (v < 0 || v >= PT_NUM || !sim->elements[v].Enabled))
{
new ErrorMessage("Could not set property", "Invalid particle type");
return;
}
#ifdef DEBUG
std::cout << "Got int value " << v << std::endl;
#endif

View File

@ -9,7 +9,7 @@ public:
{
}
virtual bool GetToggle()
virtual bool GetToggle()
{
return m->GetSimulation()->pretty_powder;
}
@ -27,7 +27,7 @@ public:
{
}
virtual bool GetToggle()
virtual bool GetToggle()
{
return m->GetGravityGrid();
}
@ -45,7 +45,7 @@ public:
{
}
virtual bool GetToggle()
virtual bool GetToggle()
{
return m->GetDecoration();
}
@ -63,7 +63,7 @@ public:
{
}
virtual bool GetToggle()
virtual bool GetToggle()
{
return m->GetNewtonianGrvity();
}
@ -81,7 +81,7 @@ public:
{
}
virtual bool GetToggle()
virtual bool GetToggle()
{
return m->GetAHeatEnable();
}

View File

@ -38,7 +38,7 @@ public:
OkayAction(SignWindow * prompt_) { prompt = prompt_; }
void ActionCallback(ui::Button * sender)
{
prompt->CloseActiveWindow();
prompt->CloseActiveWindow();
if(prompt->signID==-1 && prompt->textField->GetText().length())
{
prompt->sim->signs.push_back(sign(prompt->textField->GetText(), prompt->signPosition.X, prompt->signPosition.Y, (sign::Justification)prompt->justification->GetOption().second));
@ -120,7 +120,7 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi
okayButton->SetActionCallback(new OkayAction(this));
AddComponent(okayButton);
SetOkayButton(okayButton);
ui::Label * tempLabel = new ui::Label(ui::Point(8, 48), ui::Point(40, 15), "Pointer:");
okayButton->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
okayButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
@ -134,7 +134,7 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi
justification->AddOption(std::pair<std::string, int>("\x9D None", (int)sign::None));
justification->SetOption(1);
justification->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
textField = new ui::Textbox(ui::Point(8, 25), ui::Point(Size.X-16, 17), "", "[message]");
textField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
textField->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
@ -142,7 +142,7 @@ SignWindow::SignWindow(SignTool * tool_, Simulation * sim_, int signID_, ui::Poi
textField->SetActionCallback(new SignTextAction(this));
AddComponent(textField);
FocusComponent(textField);
if(signID!=-1)
{
messageLabel->SetText("Edit sign");
@ -252,7 +252,7 @@ void SignWindow::DoMouseDown(int x, int y, unsigned button)
void SignWindow::OnDraw()
{
Graphics * g = GetGraphics();
g->clearrect(Position.X-2, Position.Y-2, Size.X+3, Size.Y+3);
g->drawrect(Position.X, Position.Y, Size.X, Size.Y, 200, 200, 200, 255);
}

View File

@ -118,18 +118,18 @@ WindTool::WindTool(int id, string name, string description, int r, int g, int b,
void WindTool::DrawLine(Simulation * sim, Brush * brush, ui::Point position1, ui::Point position2, bool dragging)
{
int radiusX, radiusY, sizeX, sizeY;
float strength = dragging?0.01f:0.002f;
strength *= this->strength;
radiusX = brush->GetRadius().X;
radiusY = brush->GetRadius().Y;
sizeX = brush->GetSize().X;
sizeY = brush->GetSize().Y;
unsigned char *bitmap = brush->GetBitmap();
for(int y = 0; y < sizeY; y++)
{
for(int x = 0; x < sizeX; x++)

View File

@ -9,17 +9,17 @@ namespace ui
VerticalAlign(AlignMiddle),
HorizontalAlign(AlignCentre),
BackgroundHover(20, 20, 20),
BackgroundInactive(0, 0, 0),
BackgroundActive(255, 255, 255),
BackgroundDisabled(10, 10, 10),
TextHover(255, 255, 255),
TextInactive(255, 255, 255),
TextActive(0, 0, 0),
TextDisabled(100, 100, 100),
BorderHover(255, 255, 255),
BorderInactive(200, 200, 200),
BorderActive(235, 235, 235),
@ -27,7 +27,7 @@ namespace ui
Margin(1, 4),
Border(1),
icon(NoIcon)
{}

View File

@ -17,40 +17,40 @@ namespace ui
{
AlignLeft, AlignCentre, AlignRight
};
enum VerticalAlignment
{
AlignTop, AlignMiddle, AlignBottom
};
VerticalAlignment VerticalAlign;
HorizontalAlignment HorizontalAlign;
ui::Colour BackgroundHover;
ui::Colour BackgroundInactive;
ui::Colour BackgroundActive;
ui::Colour BackgroundDisabled;
ui::Colour TextHover;
ui::Colour TextInactive;
ui::Colour TextActive;
ui::Colour TextDisabled;
ui::Colour BorderHover;
ui::Colour BorderInactive;
ui::Colour BorderActive;
ui::Colour BorderFavorite;
ui::Colour BorderDisabled;
ui::Border Margin;
ui::Border Border;
Icon icon;
VideoBuffer * GetTexture();
void SetTexture(VideoBuffer * texture);
Appearance();
~Appearance();
};

View File

@ -39,7 +39,7 @@ public:
virtual void Tick(float dt);
virtual void OnResponseReady(void * imagePtr, int identifier);
virtual void DoAction();
void SetUsername(std::string username) { name = username; }

View File

@ -2,7 +2,7 @@
namespace ui
{
struct Border
{
#if ENABLE_FLOAT_UI
@ -10,12 +10,12 @@ namespace ui
#else
# define BORDER_T int
#endif
BORDER_T Top;
BORDER_T Right;
BORDER_T Bottom;
BORDER_T Left;
Border(BORDER_T all):
Top(all),
Right(all),
@ -23,7 +23,7 @@ namespace ui
Left(all)
{
}
Border(BORDER_T v, BORDER_T h):
Top(v),
Right(h),
@ -31,7 +31,7 @@ namespace ui
Left(h)
{
}
Border(BORDER_T top, BORDER_T right, BORDER_T bottom, BORDER_T left):
Top(top),
Right(right),
@ -44,17 +44,17 @@ namespace ui
{
return (Top == v && Right == v && Bottom == v && Left == v);
}
inline bool operator == (const Border& v) const
{
return (Top == v.Top && Right == v.Right && Bottom == v.Bottom && Left == v.Left);
}
inline bool operator != (const Border& v) const
{
return (Top != v.Top || Right != v.Right || Bottom != v.Bottom || Left != v.Left);
}
inline void operator = (const Border& v)
{
Top = v.Top;
@ -62,7 +62,7 @@ namespace ui
Bottom = v.Bottom;
Left = v.Left;
}
};
}

View File

@ -66,7 +66,7 @@ void Component::TextPosition(std::string displayText)
{
textPosition = ui::Point(0, 0);
int textWidth, textHeight = 10;
Graphics::textsize((char*)displayText.c_str(), textWidth, textHeight);
textSize.X = textWidth; textSize.Y = textHeight;
@ -76,10 +76,10 @@ void Component::TextPosition(std::string displayText)
{
textWidth += 13;
}
int textAreaWidth = Size.X-(Appearance.Margin.Right+Appearance.Margin.Left);
int textAreaHeight = Size.Y-(Appearance.Margin.Top+Appearance.Margin.Bottom);
switch(Appearance.VerticalAlign)
{
case ui::Appearance::AlignTop:
@ -92,7 +92,7 @@ void Component::TextPosition(std::string displayText)
textPosition.Y = Size.Y-(textHeight+Appearance.Margin.Bottom);
break;
}
switch(Appearance.HorizontalAlign)
{
case ui::Appearance::AlignLeft:
@ -137,10 +137,10 @@ void Component::SetParent(Panel* new_parent)
{
// remove ourself from parent component
_parent->RemoveChild(i, false);
// add ourself to the parent state
GetParentWindow()->AddComponent(this);
//done in this loop.
break;
}

View File

@ -30,7 +30,7 @@ public:
virtual void RemoveItem(int id);
virtual void SetItem(int id, std::string text);
virtual void Show(ui::Point position);
virtual void OnDraw();
virtual void OnDraw();
virtual void OnMouseDown(int x, int y, unsigned button);
virtual ~ContextMenu() {}
};

View File

@ -119,7 +119,7 @@ void DropDown::Draw(const Point& screenPos)
if(optionIndex!=-1)
g->drawtext(Position.X+textPosition.X, Position.Y+textPosition.Y, options[optionIndex].first, textColour.Red, textColour.Green, textColour.Blue, textColour.Alpha);
}
void DropDown::OnMouseEnter(int x, int y)
{
isMouseInside = true;
@ -137,7 +137,7 @@ void DropDown::OnMouseLeave(int x, int y)
}
return std::pair<std::string, int>("", -1);
}
void DropDown::SetOption(std::string option)
{
for (size_t i = 0; i < options.size(); i++)

View File

@ -11,7 +11,7 @@ namespace ui
class Window;
/* class Engine
*
*
* Controls the User Interface.
* Send user inputs to the Engine and the appropriate controls and components will interact.
*/
@ -35,7 +35,7 @@ namespace ui
void Begin(int width, int height);
inline bool Running() { return running_; }
inline bool Broken() { return break_; }
inline bool Broken() { return break_; }
inline long unsigned int LastTick() { return lastTick; }
inline void LastTick(long unsigned int tick) { lastTick = tick; }
void Exit();
@ -70,7 +70,7 @@ namespace ui
void SetMaxSize(int width, int height);
inline void SetSize(int width, int height);
//void SetState(Window* state);
//inline State* GetState() { return state_; }
inline Window* GetWindow() { return state_; }
@ -96,7 +96,7 @@ namespace ui
bool running_;
bool break_;
bool FastQuit;
long unsigned int lastTick;
int mouseb_;
int mousex_;

View File

@ -73,7 +73,7 @@ typedef enum {
SDLK_GREATER = 62,
SDLK_QUESTION = 63,
SDLK_AT = 64,
/*
/*
Skip uppercase letters
*/
SDLK_LEFTBRACKET = 91,

View File

@ -12,7 +12,7 @@
/* These are used for the renderer, which doesn't include the rest of SDL and only this file
* It still needs fake SDL_BUTTON_* constants to compile
*/
#define SDL_BUTTON(X) (1 << ((X)-1))
#define SDL_BUTTON_LEFT 1
#define SDL_BUTTON_MIDDLE 2

View File

@ -110,7 +110,7 @@ void Panel::Draw(const Point& screenPos)
ui::Engine::Ref().g->vid = myVid;
std::fill(myVid, myVid+(WINDOWW*WINDOWH), 0);
#endif
// attempt to draw all children
for (size_t i = 0; i < children.size(); ++i)
{
@ -169,7 +169,7 @@ void Panel::Tick(float dt)
{
// tick ourself first
XTick(dt);
// tick our children
for(unsigned i = 0; i < children.size(); ++i)
children[i]->Tick(dt);
@ -188,7 +188,7 @@ void Panel::OnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool
void Panel::OnMouseClick(int localx, int localy, unsigned button)
{
bool childclicked = false;
//check if clicked a child
for(int i = children.size()-1; i >= 0 ; --i)
{
@ -208,7 +208,7 @@ void Panel::OnMouseClick(int localx, int localy, unsigned button)
}
}
}
//if a child wasn't clicked, send click to ourself
if(!childclicked)
{
@ -244,7 +244,7 @@ void Panel::OnMouseHover(int localx, int localy)
}
}
}
// always allow hover on parent (?)
XOnMouseHover(localx, localy);
}
@ -268,7 +268,7 @@ void Panel::OnMouseMovedInside(int localx, int localy, int dx, int dy)
{
Point local (localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y)
, prevlocal (local.X - dx, local.Y - dy);
// mouse currently inside?
if( local.X >= 0 &&
local.Y >= 0 &&
@ -276,7 +276,7 @@ void Panel::OnMouseMovedInside(int localx, int localy, int dx, int dy)
local.Y < children[i]->Size.Y )
{
children[i]->OnMouseMovedInside(localx - children[i]->Position.X - ViewportPosition.X, localy - children[i]->Position.Y - ViewportPosition.Y, dx, dy);
// was the mouse outside?
if(!(prevlocal.X >= 0 &&
prevlocal.Y >= 0 &&
@ -297,11 +297,11 @@ void Panel::OnMouseMovedInside(int localx, int localy, int dx, int dy)
{
children[i]->OnMouseLeave(local.X, local.Y);
}
}
}
}
// always allow hover on parent (?)
XOnMouseMovedInside(localx, localy, dx, dy);
}
@ -321,7 +321,7 @@ void Panel::OnMouseLeave(int localx, int localy)
void Panel::OnMouseUnclick(int localx, int localy, unsigned button)
{
bool childunclicked = false;
//check if clicked a child
for(int i = children.size()-1; i >= 0 ; --i)
{
@ -340,7 +340,7 @@ void Panel::OnMouseUnclick(int localx, int localy, unsigned button)
}
}
}
//if a child wasn't clicked, send click to ourself
if (!childunclicked)
{

View File

@ -15,10 +15,10 @@ class Graphics;
namespace ui
{
/* class XComponent
*
*
* An eXtension of the Component class.
* Adds the ability to have child components.
*
*
* See sys::Component
*/
@ -30,7 +30,7 @@ class Component;
#ifdef OGLI
GLuint myVid, myVidTex;
#else
#else
pixel * myVid;
#endif
ui::Point InnerSize;
@ -38,29 +38,29 @@ class Component;
Panel(Point position, Point size);
virtual ~Panel();
/* Add a child component.
* Similar to XComponent::SetParent
*
*
* If the component is already parented, then this will become the new parent.
*/
void AddChild(Component* c);
// Remove child from component. This DOES NOT free the component from memory.
void RemoveChild(Component* c);
// Remove child from component. This WILL free the component from memory unless told otherwise.
void RemoveChild(unsigned idx, bool freeMem = true);
//Grab the number of children this component owns.
int GetChildCount();
//Get child of this component by index.
Component* GetChild(unsigned idx);
void Tick(float dt);
void Draw(const Point& screenPos);
void OnMouseHover(int localx, int localy);
void OnMouseMoved(int localx, int localy, int dx, int dy);
void OnMouseMovedInside(int localx, int localy, int dx, int dy);
@ -74,17 +74,17 @@ class Component;
void OnMouseWheelInside(int localx, int localy, int d);
void OnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt);
void OnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt);
protected:
// child components
std::vector<ui::Component*> children;
bool mouseInside;
//UI functions:
/*
void XTick(float dt);
void XDraw(const Point& screenPos);
void XOnMouseHover(int localx, int localy);
void XOnMouseMoved(int localx, int localy, int dx, int dy);
void XOnMouseMovedInside(int localx, int localy, int dx, int dy);
@ -99,50 +99,50 @@ class Component;
void XOnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt);
void XOnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt);
*/
// Overridable. Called by XComponent::Tick()
virtual void XTick(float dt);
// Overridable. Called by XComponent::Draw()
virtual void XDraw(const Point& screenPos);
// Overridable. Called by XComponent::XOnMouseHover()
virtual void XOnMouseHover(int localx, int localy);
// Overridable. Called by XComponent::OnMouseMoved()
virtual void XOnMouseMoved(int localx, int localy, int dx, int dy);
// Overridable. Called by XComponent::OnMouseMovedInside()
virtual void XOnMouseMovedInside(int localx, int localy, int dx, int dy);
// Overridable. Called by XComponent::OnMouseEnter()
virtual void XOnMouseEnter(int localx, int localy);
// Overridable. Called by XComponent::OnMouseLeave()
virtual void XOnMouseLeave(int localx, int localy);
// Overridable. Called by XComponent::OnMouseDown()
virtual void XOnMouseDown(int x, int y, unsigned button);
// Overridable. Called by XComponent::OnMouseUp()
virtual void XOnMouseUp(int x, int y, unsigned button);
// Overridable. Called by XComponent::OnMouseClick()
virtual void XOnMouseClick(int localx, int localy, unsigned button);
// Overridable. Called by XComponent::OnMouseUnclick()
virtual void XOnMouseUnclick(int localx, int localy, unsigned button);
// Overridable. Called by XComponent::OnMouseWheel()
virtual void XOnMouseWheel(int localx, int localy, int d);
// Overridable. Called by XComponent::OnMouseWheelInside()
virtual void XOnMouseWheelInside(int localx, int localy, int d);
// Overridable. Called by XComponent::OnKeyPress()
virtual void XOnKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool alt);
// Overridable. Called by XComponent::OnKeyRelease()
virtual void XOnKeyRelease(int key, Uint16 character, bool shift, bool ctrl, bool alt);
};

View File

@ -11,7 +11,7 @@ struct Point
#else
# define POINT_T int
#endif
POINT_T X;
POINT_T Y;

View File

@ -17,5 +17,5 @@ namespace ui
virtual std::string GetStatus();
virtual void Draw(const Point & screenPos);
virtual void Tick(float dt);
};
};
}

View File

@ -356,7 +356,7 @@ void SaveButton::OnMouseClick(int x, int y, unsigned int button)
selected = !selected;
DoSelection();
}
}
}

View File

@ -94,7 +94,7 @@ void ScrollPanel::XOnMouseMoved(int x, int y, int dx, int dy)
{
scrollPos = float(Size.Y-scrollHeight)*(float(offsetY)/float(maxOffset.Y));
}
if (scrollbarSelected)
{
if (x > 0)

View File

@ -229,15 +229,15 @@ void Window::DoDraw()
Graphics * g = ui::Engine::Ref().g;
char tempString[512];
char tempString2[512];
sprintf(tempString, "Position: L %d, R %d, T: %d, B: %d", focusedComponent_->Position.X, Size.X-(focusedComponent_->Position.X+focusedComponent_->Size.X), focusedComponent_->Position.Y, Size.Y-(focusedComponent_->Position.Y+focusedComponent_->Size.Y));
sprintf(tempString2, "Size: %d, %d", focusedComponent_->Size.X, focusedComponent_->Size.Y);
if (Graphics::textwidth(tempString)+xPos > WINDOWW)
xPos = WINDOWW-(Graphics::textwidth(tempString)+5);
if (Graphics::textwidth(tempString2)+xPos > WINDOWW)
xPos = WINDOWW-(Graphics::textwidth(tempString2)+5);
g->drawtext(xPos, focusedComponent_->Position.Y+Position.Y+1, tempString, 0, 0, 0, 200);
g->drawtext(xPos, focusedComponent_->Position.Y+Position.Y, tempString, 255, 255, 255, 255);
g->drawtext(xPos, focusedComponent_->Position.Y+Position.Y+13, tempString2, 0, 0, 0, 200);
@ -380,7 +380,7 @@ void Window::DoKeyPress(int key, Uint16 character, bool shift, bool ctrl, bool a
if (!stop)
OnKeyPress(key, character, shift, ctrl, alt);
if (key == SDLK_ESCAPE)
OnTryExit(Escape);
@ -435,7 +435,7 @@ void Window::DoMouseDown(int x_, int y_, unsigned button)
if (!clickState)
FocusComponent(NULL);
#ifdef DEBUG
if (debugMode)
return;

View File

@ -9,7 +9,7 @@
#include "gui/interface/Label.h"
#include "gui/interface/SaveButton.h"
#include "gui/interface/Keys.h"
#include "gui/dialogues/ErrorMessage.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "LocalBrowserController.h"

View File

@ -41,13 +41,13 @@ LoginView::LoginView():
{
targetSize = Size;
FocusComponent(usernameField);
infoLabel->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
infoLabel->Appearance.VerticalAlign = ui::Appearance::AlignTop;
infoLabel->SetMultiline(true);
infoLabel->Visible = false;
AddComponent(infoLabel);
AddComponent(loginButton);
SetOkayButton(loginButton);
loginButton->Appearance.HorizontalAlign = ui::Appearance::AlignRight;
@ -61,7 +61,7 @@ LoginView::LoginView():
AddComponent(titleLabel);
titleLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
titleLabel->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
AddComponent(usernameField);
usernameField->Appearance.icon = IconUsername;
usernameField->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
@ -127,7 +127,7 @@ void LoginView::OnTick(float dt)
ydiff = 1*isign(difference.Y);
Size.Y += ydiff;
}
loginButton->Position.Y = Size.Y-17;
cancelButton->Position.Y = Size.Y-17;
}

View File

@ -269,7 +269,7 @@ void PreviewView::commentBoxAutoHeight()
commentBoxPositionY = Size.Y-19;
commentBoxSizeX = Size.X-(XRES/2)-48;
commentBoxSizeY = 17;
if (commentWarningLabel && commentWarningLabel->Visible)
{
commentWarningLabel->Visible = false;
@ -616,7 +616,7 @@ void PreviewView::NotifyCommentBoxEnabledChanged(PreviewModel * sender)
submitCommentButton->SetActionCallback(new SubmitCommentAction(this));
//submitCommentButton->Enabled = false;
AddComponent(submitCommentButton);
commentWarningLabel = new ui::Label(ui::Point((XRES/2)+4, Size.Y-19), ui::Point(Size.X-(XRES/2)-48, 16), "If you see this it is a bug");
commentWarningLabel->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
commentWarningLabel->SetTextColour(ui::Colour(255, 0, 0));

View File

@ -63,7 +63,7 @@ class PreviewView: public ui::Window {
float commentBoxSizeX;
float commentBoxSizeY;
bool commentHelpText;
std::set<std::string> swearWords;
void displayComments();

View File

@ -191,7 +191,7 @@ void ProfileActivity::setUserInfo(UserInfo newInfo)
highestScore->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;
scrollPanel->AddChild(highestScore);
currentY += 2+highestScore->Size.Y;
// biograhy
ui::Label * bioTitle = new ui::Label(ui::Point(4, currentY), ui::Point(50, 15), "Biography:");
bioTitle->Appearance.HorizontalAlign = ui::Appearance::AlignLeft;

View File

@ -140,7 +140,7 @@ ServerSaveActivity::ServerSaveActivity(SaveInfo save, ServerSaveActivity::SaveUp
if(Client::Ref().GetAuthUser().Username != save.GetUserName())
{
//Save is not owned by the user, disable by default
publishedCheckbox->SetChecked(false);
publishedCheckbox->SetChecked(false);
}
else
{

View File

@ -26,7 +26,7 @@ void SearchModel::SetShowTags(bool show)
bool SearchModel::GetShowTags()
{
return showTags;
return showTags;
}
TH_ENTRY_POINT void * SearchModel::updateSaveListTHelper(void * obj)
@ -90,7 +90,7 @@ bool SearchModel::UpdateSaveList(int pageNumber, std::string query)
updateTagListWorking = true;
pthread_create(&updateTagListThread, 0, &SearchModel::updateTagListTHelper, this);
}
updateSaveListFinished = false;
updateSaveListWorking = true;
pthread_create(&updateSaveListThread, 0, &SearchModel::updateSaveListTHelper, this);
@ -152,7 +152,7 @@ void SearchModel::Update()
if (lastError == "Unspecified Error")
lastError = "";
}
resultCount = thResultCount;
notifyPageChanged();
notifySaveListChanged();

View File

@ -125,7 +125,7 @@ SearchView::SearchView():
favButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
favButton->Appearance.BorderInactive = ui::Colour(170,170,170);
AddComponent(favButton);
class ClearSearchAction : public ui::ButtonAction
{
SearchView * v;
@ -425,7 +425,7 @@ void SearchView::CheckAccess()
if(favButton->GetToggleState())
favButton->DoAction();
}
if (Client::Ref().GetAuthUser().UserID)
{
ownButton->Enabled = true;
@ -525,7 +525,7 @@ void SearchView::NotifyTagListChanged(SearchModel * sender)
int maxTagVotes = tags[0].second;
pair<string, int> tag = tags[i];
if (tagX == tagsX)
{
if(tagY == tagsY-1)

View File

@ -120,7 +120,7 @@ void TagsView::NotifyTagsChanged(TagsModel * sender)
tempButton->Appearance.icon = IconDelete;
tempButton->Appearance.Border = ui::Border(0);
tempButton->Appearance.Margin.Top += 2;
tempButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
tempButton->Appearance.HorizontalAlign = ui::Appearance::AlignCentre;
tempButton->Appearance.VerticalAlign = ui::Appearance::AlignMiddle;
tempButton->SetActionCallback(new DeleteTagAction(this, *iter));
tags.push_back(tempButton);

View File

@ -7,28 +7,28 @@
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================

View File

@ -6,28 +6,28 @@
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
@ -398,14 +398,14 @@ class JSON_API Exception;
/** Exceptions which the user cannot easily avoid.
*
* E.g. out-of-memory (when we use malloc), stack-overflow, malicious input
*
*
* \remark derived from Json::Exception
*/
class JSON_API RuntimeError;
/** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros.
*
* These are precondition-violations (user bugs) and internal errors (our bugs).
*
*
* \remark derived from Json::Exception
*/
class JSON_API LogicError;

View File

@ -6,28 +6,28 @@
// //////////////////////////////////////////////////////////////////////
/*
The JsonCpp library's source code, including accompanying documentation,
The JsonCpp library's source code, including accompanying documentation,
tests and demonstration applications, are licensed under the following
conditions...
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
The author (Baptiste Lepilleur) explicitly disclaims copyright in all
jurisdictions which recognize such a disclaimer. In such jurisdictions,
this software is released into the Public Domain.
In jurisdictions which do not recognize Public Domain property (e.g. Germany as of
2010), this software is Copyright (c) 2007-2010 by Baptiste Lepilleur, and is
released under the terms of the MIT License (see below).
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
In jurisdictions which recognize Public Domain property, the user of this
software may choose to accept it either as 1) Public Domain, 2) under the
conditions of the MIT License (see below), or 3) under the terms of dual
Public Domain/MIT License conditions described here, as they choose.
The MIT License is about as close to Public Domain as a license can get, and is
described in clear, concise terms at:
http://en.wikipedia.org/wiki/MIT_License
The full text of the MIT License follows:
========================================================================
@ -3971,7 +3971,7 @@ Value& Path::make(Value& root) const {
#define snprintf std::snprintf
#endif
#if defined(__BORLANDC__)
#if defined(__BORLANDC__)
#include <float.h>
#define isfinite _finite
#define snprintf _snprintf

View File

@ -17,7 +17,7 @@ public:
// push global table to the stack, so we can add the component APIs to it
lua_pushglobaltable(L);
luaL_newmetatable(L, T::className);
int metatable = lua_gettop(L);
@ -90,7 +90,7 @@ public:
}
}
static bool checkType (lua_State * L, int idx, const char *name)
static bool checkType (lua_State * L, int idx, const char *name)
{
// returns true if a userdata is of a certain type
int res;
@ -132,7 +132,7 @@ private:
T *obj = new T(L); // call constructor for T objects
userdataType *ud = static_cast<userdataType*>(lua_newuserdata(L, sizeof(userdataType)));
ud->pT = obj; // store pointer to object in userdata
obj->UserData = luaL_ref(L, LUA_REGISTRYINDEX);
lua_rawgeti(L, LUA_REGISTRYINDEX, obj->UserData);

View File

@ -14,7 +14,7 @@
#include "gui/dialogues/ErrorMessage.h"
#include "gui/dialogues/InformationMessage.h"
#include "gui/dialogues/TextPrompt.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "gui/dialogues/ConfirmPrompt.h"
#include "simulation/Simulation.h"
#include "simulation/Air.h"
#include "ToolClasses.h"
@ -805,7 +805,7 @@ void LuaScriptInterface::initSimulationAPI()
SETCONST(l, PMAPMASK);
//Declare FIELD_BLAH constants
std::vector<StructProperty> particlePropertiesV = Particle::GetProperties();
std::vector<StructProperty> particlePropertiesV = Particle::GetProperties();
particlePropertiesCount = 0;
particleProperties = new StructProperty[particlePropertiesV.size()];
for(std::vector<StructProperty>::iterator iter = particlePropertiesV.begin(), end = particlePropertiesV.end(); iter != end; ++iter)
@ -978,7 +978,7 @@ int LuaScriptInterface::simulation_partPosition(lua_State * l)
return 0;
}
}
if(argCount == 3)
{
luacon_sim->parts[particleID].x = lua_tonumber(l, 2);
@ -1068,7 +1068,7 @@ int LuaScriptInterface::simulation_partProperty(lua_State * l)
break;
}
return 0;
}
}
else
{
//Get
@ -1911,7 +1911,7 @@ int LuaScriptInterface::simulation_canMove(lua_State * l)
return luaL_error(l, "Invalid element ID (%d)", movingElement);
if (destinationElement < 0 || destinationElement >= PT_NUM)
return luaL_error(l, "Invalid element ID (%d)", destinationElement);
if (lua_gettop(l) < 3)
{
lua_pushnumber(l, luacon_sim->can_move[movingElement][destinationElement]);
@ -1959,8 +1959,8 @@ int BrushClosure(lua_State * l)
int x = lua_tointeger(l, lua_upvalueindex(7));
int y = lua_tointeger(l, lua_upvalueindex(8));
unsigned char *bitmap = (unsigned char *)lua_touserdata(l, lua_upvalueindex(9));
int yield_x, yield_y;
while (true)
{
@ -1985,12 +1985,12 @@ int BrushClosure(lua_State * l)
y++;
}
}
lua_pushnumber(l, x);
lua_replace(l, lua_upvalueindex(7));
lua_pushnumber(l, y);
lua_replace(l, lua_upvalueindex(8));
lua_pushnumber(l, yield_x);
lua_pushnumber(l, yield_y);
return 2;
@ -2014,11 +2014,11 @@ int LuaScriptInterface::simulation_brush(lua_State * l)
brushradiusY = size.Y;
}
int brushID = luaL_optint(l, 5, luacon_model->GetBrushID());
vector<Brush *> brushList = luacon_model->GetBrushList();
if (brushID < 0 || brushID >= (int)brushList.size())
return luaL_error(l, "Invalid brush id '%d'", brushID);
ui::Point tempRadius = brushList[brushID]->GetRadius();
brushList[brushID]->SetRadius(ui::Point(brushradiusX, brushradiusY));
lua_pushnumber(l, positionX);
@ -2037,7 +2037,7 @@ int LuaScriptInterface::simulation_brush(lua_State * l)
void *bitmapCopy = lua_newuserdata(l, bitmapSize);
memcpy(bitmapCopy, brushList[brushID]->GetBitmap(), bitmapSize);
brushList[brushID]->SetRadius(tempRadius);
lua_pushcclosure(l, BrushClosure, 9);
return 1;
}
@ -2556,7 +2556,7 @@ int LuaScriptInterface::elements_allocate(lua_State * l)
}
if (newID != -1)
{
{
lua_getglobal(l, "elements");
lua_pushinteger(l, newID);
lua_setfield(l, -2, identifier.c_str());
@ -2890,7 +2890,7 @@ int LuaScriptInterface::elements_free(lua_State * l)
int id;
luaL_checktype(l, 1, LUA_TNUMBER);
id = lua_tointeger(l, 1);
if(id < 0 || id >= PT_NUM || !luacon_sim->elements[id].Enabled)
return luaL_error(l, "Invalid element");
@ -2953,7 +2953,7 @@ int LuaScriptInterface::graphics_drawText(lua_State * l)
int g = luaL_optint(l, 5, 255);
int b = luaL_optint(l, 6, 255);
int a = luaL_optint(l, 7, 255);
if (r<0) r = 0;
else if (r>255) r = 255;
if (g<0) g = 0;
@ -3321,7 +3321,7 @@ int LuaScriptInterface::fileSystem_copy(lua_State * l)
std::istreambuf_iterator<char> begin_source(source);
std::istreambuf_iterator<char> end_source;
std::ostreambuf_iterator<char> begin_dest(dest);
std::ostreambuf_iterator<char> begin_dest(dest);
std::copy(begin_source, end_source, begin_dest);
source.close();

View File

@ -28,7 +28,7 @@ void auxiliar_newclass(lua_State *L, const char *classname, luaL_Reg *func) {
luaL_newmetatable(L, classname); /* mt */
/* create __index table to place methods */
lua_pushstring(L, "__index"); /* mt,"__index" */
lua_newtable(L); /* mt,"__index",it */
lua_newtable(L); /* mt,"__index",it */
/* put class name into class metatable */
lua_pushstring(L, "class"); /* mt,"__index",it,"class" */
lua_pushstring(L, classname); /* mt,"__index",it,"class",classname */
@ -86,7 +86,7 @@ int auxiliar_checkboolean(lua_State *L, int objidx) {
}
/*-------------------------------------------------------------------------*\
* Return userdata pointer if object belongs to a given class, abort with
* Return userdata pointer if object belongs to a given class, abort with
* error otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) {
@ -100,7 +100,7 @@ void *auxiliar_checkclass(lua_State *L, const char *classname, int objidx) {
}
/*-------------------------------------------------------------------------*\
* Return userdata pointer if object belongs to a given group, abort with
* Return userdata pointer if object belongs to a given group, abort with
* error otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_checkgroup(lua_State *L, const char *groupname, int objidx) {
@ -123,7 +123,7 @@ void auxiliar_setclass(lua_State *L, const char *classname, int objidx) {
}
/*-------------------------------------------------------------------------*\
* Get a userdata pointer if object belongs to a given group. Return NULL
* Get a userdata pointer if object belongs to a given group. Return NULL
* otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) {
@ -141,7 +141,7 @@ void *auxiliar_getgroupudata(lua_State *L, const char *groupname, int objidx) {
}
/*-------------------------------------------------------------------------*\
* Get a userdata pointer if object belongs to a given class. Return NULL
* Get a userdata pointer if object belongs to a given class. Return NULL
* otherwise
\*-------------------------------------------------------------------------*/
void *auxiliar_getclassudata(lua_State *L, const char *classname, int objidx) {

View File

@ -4,12 +4,12 @@
* Auxiliar routines for class hierarchy manipulation
* LuaSocket toolkit (but completely independent of other LuaSocket modules)
*
* A LuaSocket class is a name associated with Lua metatables. A LuaSocket
* group is a name associated with a class. A class can belong to any number
* A LuaSocket class is a name associated with Lua metatables. A LuaSocket
* group is a name associated with a class. A class can belong to any number
* of groups. This module provides the functionality to:
*
* - create new classes
* - add classes to groups
* - create new classes
* - add classes to groups
* - set the class of objects
* - check if an object belongs to a given class or group
* - get the userdata associated to objects
@ -26,7 +26,7 @@
* "class" with the class name.
*
* The mapping from class name to the corresponding metatable and the
* reverse mapping are done using lauxlib.
* reverse mapping are done using lauxlib.
*
* RCS ID: $Id: auxiliar.h,v 1.9 2005/10/07 04:40:59 diego Exp $
\*=========================================================================*/

View File

@ -36,7 +36,7 @@ int buffer_open(lua_State *L) {
}
/*-------------------------------------------------------------------------*\
* Initializes C structure
* Initializes C structure
\*-------------------------------------------------------------------------*/
void buffer_init(p_buffer buf, p_io io, p_timeout tm) {
buf->first = buf->last = 0;
@ -60,8 +60,8 @@ int buffer_meth_getstats(lua_State *L, p_buffer buf) {
* object:setstats() interface
\*-------------------------------------------------------------------------*/
int buffer_meth_setstats(lua_State *L, p_buffer buf) {
buf->received = (long) luaL_optnumber(L, 2, buf->received);
buf->sent = (long) luaL_optnumber(L, 3, buf->sent);
buf->received = (long) luaL_optnumber(L, 2, buf->received);
buf->sent = (long) luaL_optnumber(L, 3, buf->sent);
if (lua_isnumber(L, 4)) buf->birthday = timeout_gettime() - lua_tonumber(L, 4);
lua_pushnumber(L, 1);
return 1;
@ -90,7 +90,7 @@ int buffer_meth_send(lua_State *L, p_buffer buf) {
/* check if there was an error */
if (err != IO_DONE) {
lua_pushnil(L);
lua_pushstring(L, buf->io->error(buf->io->ctx, err));
lua_pushstring(L, buf->io->error(buf->io->ctx, err));
lua_pushnumber(L, sent+start-1);
} else {
lua_pushnumber(L, sent+start-1);
@ -117,7 +117,7 @@ int buffer_meth_receive(lua_State *L, p_buffer buf) {
#else
timeout_markstart(buf->tm);
#endif
/* initialize buffer with optional extra prefix
/* initialize buffer with optional extra prefix
* (useful for concatenating previous partial results) */
luaL_buffinit(L, &b);
luaL_addlstring(&b, part, size);
@ -125,9 +125,9 @@ int buffer_meth_receive(lua_State *L, p_buffer buf) {
if (!lua_isnumber(L, 2)) {
const char *p= luaL_optstring(L, 2, "*l");
if (p[0] == '*' && p[1] == 'l') err = recvline(buf, &b);
else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b);
else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b);
else luaL_argcheck(L, 0, 2, "invalid receive pattern");
/* get a fixed number of bytes (minus what was already partially
/* get a fixed number of bytes (minus what was already partially
* received) */
} else err = recvraw(buf, (size_t) lua_tonumber(L, 2)-size, &b);
/* check if there was an error */
@ -135,8 +135,8 @@ int buffer_meth_receive(lua_State *L, p_buffer buf) {
/* we can't push anyting in the stack before pushing the
* contents of the buffer. this is the reason for the complication */
luaL_pushresult(&b);
lua_pushstring(L, buf->io->error(buf->io->ctx, err));
lua_pushvalue(L, -2);
lua_pushstring(L, buf->io->error(buf->io->ctx, err));
lua_pushvalue(L, -2);
lua_pushnil(L);
lua_replace(L, -4);
} else {
@ -219,7 +219,7 @@ static int recvall(p_buffer buf, luaL_Buffer *b) {
}
/*-------------------------------------------------------------------------*\
* Reads a line terminated by a CR LF pair or just by a LF. The CR and LF
* Reads a line terminated by a CR LF pair or just by a LF. The CR and LF
* are not returned by the function and are discarded from the buffer
\*-------------------------------------------------------------------------*/
static int recvline(p_buffer buf, luaL_Buffer *b) {
@ -249,7 +249,7 @@ static int recvline(p_buffer buf, luaL_Buffer *b) {
static void buffer_skip(p_buffer buf, size_t count) {
buf->received += count;
buf->first += count;
if (buffer_isempty(buf))
if (buffer_isempty(buf))
buf->first = buf->last = 0;
}

View File

@ -1,13 +1,13 @@
#ifndef BUF_H
#define BUF_H
#define BUF_H
/*=========================================================================*\
* Input/Output interface for Lua programs
* LuaSocket toolkit
*
* Line patterns require buffering. Reading one character at a time involves
* too many system calls and is very slow. This module implements the
* LuaSocket interface for input/output on connected objects, as seen by
* Lua programs.
* LuaSocket interface for input/output on connected objects, as seen by
* Lua programs.
*
* Input is buffered. Output is *not* buffered because there was no simple
* way of making sure the buffered output data would ever be sent.

View File

@ -47,9 +47,9 @@ static int finalize(lua_State *L) {
} else return lua_gettop(L);
}
static int do_nothing(lua_State *L) {
static int do_nothing(lua_State *L) {
(void) L;
return 0;
return 0;
}
static int global_newtry(lua_State *L) {

View File

@ -16,14 +16,14 @@
*
* The idea is to nest function calls with the "try" function. This function
* checks the first value, and calls "error" on the second if the first is
* nil. Otherwise, it returns all values it received.
* nil. Otherwise, it returns all values it received.
*
* The protect function returns a new function that behaves exactly like the
* function it receives, but the new function doesn't throw exceptions: it
* returns nil followed by the error message instead.
*
* With these two function, it's easy to write functions that throw
* exceptions on error, but that don't interrupt the user script.
* exceptions on error, but that don't interrupt the user script.
*
* RCS ID: $Id: except.h,v 1.2 2005/09/29 06:11:41 diego Exp $
\*=========================================================================*/

View File

@ -51,7 +51,7 @@ static int inet_gethost(const char *address, struct hostent **hp) {
struct in_addr addr;
if (inet_aton(address, &addr))
return socket_gethostbyaddr((char *) &addr, sizeof(addr), hp);
else
else
return socket_gethostbyname(address, hp);
}
@ -61,7 +61,7 @@ static int inet_gethost(const char *address, struct hostent **hp) {
\*-------------------------------------------------------------------------*/
static int inet_global_tohostname(lua_State *L) {
const char *address = luaL_checkstring(L, 1);
struct hostent *hp = NULL;
struct hostent *hp = NULL;
int err = inet_gethost(address, &hp);
if (err != IO_DONE) {
lua_pushnil(L);
@ -80,7 +80,7 @@ static int inet_global_tohostname(lua_State *L) {
static int inet_global_toip(lua_State *L)
{
const char *address = luaL_checkstring(L, 1);
struct hostent *hp = NULL;
struct hostent *hp = NULL;
int err = inet_gethost(address, &hp);
if (err != IO_DONE) {
lua_pushnil(L);
@ -202,7 +202,7 @@ const char *inet_trycreate(p_socket ps, int type) {
/*-------------------------------------------------------------------------*\
* Tries to connect to remote address (address, port)
\*-------------------------------------------------------------------------*/
const char *inet_tryconnect(p_socket ps, const char *address,
const char *inet_tryconnect(p_socket ps, const char *address,
unsigned short port, p_timeout tm)
{
struct sockaddr_in remote;
@ -246,7 +246,7 @@ const char *inet_trybind(p_socket ps, const char *address, unsigned short port)
}
err = socket_bind(ps, (SA *) &local, sizeof(local));
if (err != IO_DONE) socket_destroy(ps);
return socket_strerror(err);
return socket_strerror(err);
}
/*-------------------------------------------------------------------------*\

View File

@ -1,12 +1,12 @@
#ifndef INET_H
#define INET_H
#ifndef INET_H
#define INET_H
/*=========================================================================*\
* Internet domain functions
* LuaSocket toolkit
*
* This module implements the creation and connection of internet domain
* sockets, on top of the socket.h interface, and the interface of with the
* resolver.
* resolver.
*
* The function inet_aton is provided for the platforms where it is not
* available. The module also implements the interface of the internet
@ -27,9 +27,9 @@
int inet_open(lua_State *L);
const char *inet_trycreate(p_socket ps, int type);
const char *inet_tryconnect(p_socket ps, const char *address,
const char *inet_tryconnect(p_socket ps, const char *address,
unsigned short port, p_timeout tm);
const char *inet_trybind(p_socket ps, const char *address,
const char *inet_trybind(p_socket ps, const char *address,
unsigned short port);
int inet_meth_getpeername(lua_State *L, p_socket ps);

View File

@ -27,6 +27,6 @@ const char *io_strerror(int err) {
case IO_DONE: return NULL;
case IO_CLOSED: return "closed";
case IO_TIMEOUT: return "timeout";
default: return "unknown error";
default: return "unknown error";
}
}

View File

@ -1,10 +1,10 @@
/*=========================================================================*\
* Common option interface
* Common option interface
* LuaSocket toolkit
*
* RCS ID: $Id: options.c,v 1.6 2005/11/20 07:20:23 diego Exp $
\*=========================================================================*/
#include <string.h>
#include <string.h>
#include <stdlib.h>
#include "auxiliar.h"
@ -17,7 +17,7 @@
\*=========================================================================*/
static int opt_setmembership(lua_State *L, p_socket ps, int level, int name);
static int opt_setboolean(lua_State *L, p_socket ps, int level, int name);
static int opt_set(lua_State *L, p_socket ps, int level, int name,
static int opt_set(lua_State *L, p_socket ps, int level, int name,
void *val, int len);
/*=========================================================================*\
@ -43,18 +43,18 @@ int opt_meth_setoption(lua_State *L, p_opt opt, p_socket ps)
/* enables reuse of local address */
int opt_reuseaddr(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEADDR);
return opt_setboolean(L, ps, SOL_SOCKET, SO_REUSEADDR);
}
/* disables the Naggle algorithm */
int opt_tcp_nodelay(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, IPPROTO_TCP, TCP_NODELAY);
return opt_setboolean(L, ps, IPPROTO_TCP, TCP_NODELAY);
}
int opt_keepalive(lua_State *L, p_socket ps)
{
return opt_setboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE);
return opt_setboolean(L, ps, SOL_SOCKET, SO_KEEPALIVE);
}
int opt_dontroute(lua_State *L, p_socket ps)
@ -78,12 +78,12 @@ int opt_linger(lua_State *L, p_socket ps)
if (!lua_istable(L, 3)) luaL_typerror(L, 3, lua_typename(L, LUA_TTABLE));
lua_pushstring(L, "on");
lua_gettable(L, 3);
if (!lua_isboolean(L, -1))
if (!lua_isboolean(L, -1))
luaL_argerror(L, 3, "boolean 'on' field expected");
li.l_onoff = (u_short) lua_toboolean(L, -1);
lua_pushstring(L, "timeout");
lua_gettable(L, 3);
if (!lua_isnumber(L, -1))
if (!lua_isnumber(L, -1))
luaL_argerror(L, 3, "number 'timeout' field expected");
li.l_linger = (u_short) lua_tonumber(L, -1);
return opt_set(L, ps, SOL_SOCKET, SO_LINGER, (char *) &li, sizeof(li));
@ -114,22 +114,22 @@ static int opt_setmembership(lua_State *L, p_socket ps, int level, int name)
if (!lua_istable(L, 3)) luaL_typerror(L, 3, lua_typename(L, LUA_TTABLE));
lua_pushstring(L, "multiaddr");
lua_gettable(L, 3);
if (!lua_isstring(L, -1))
if (!lua_isstring(L, -1))
luaL_argerror(L, 3, "string 'multiaddr' field expected");
if (!inet_aton(lua_tostring(L, -1), &val.imr_multiaddr))
if (!inet_aton(lua_tostring(L, -1), &val.imr_multiaddr))
luaL_argerror(L, 3, "invalid 'multiaddr' ip address");
lua_pushstring(L, "interface");
lua_gettable(L, 3);
if (!lua_isstring(L, -1))
if (!lua_isstring(L, -1))
luaL_argerror(L, 3, "string 'interface' field expected");
val.imr_interface.s_addr = htonl(INADDR_ANY);
if (strcmp(lua_tostring(L, -1), "*") &&
!inet_aton(lua_tostring(L, -1), &val.imr_interface))
!inet_aton(lua_tostring(L, -1), &val.imr_interface))
luaL_argerror(L, 3, "invalid 'interface' ip address");
return opt_set(L, ps, level, name, (char *) &val, sizeof(val));
}
static
static
int opt_set(lua_State *L, p_socket ps, int level, int name, void *val, int len)
{
if (setsockopt(*ps, level, name, (char *) val, len) < 0) {

View File

@ -1,11 +1,11 @@
#ifndef OPTIONS_H
#define OPTIONS_H
/*=========================================================================*\
* Common option interface
* Common option interface
* LuaSocket toolkit
*
* This module provides a common interface to socket options, used mainly by
* modules UDP and TCP.
* modules UDP and TCP.
*
* RCS ID: $Id: options.h,v 1.4 2005/10/07 04:40:59 diego Exp $
\*=========================================================================*/

View File

@ -15,10 +15,10 @@
\*=========================================================================*/
static t_socket getfd(lua_State *L);
static int dirty(lua_State *L);
static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd,
static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd,
int itab, fd_set *set);
static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set);
static void return_fd(lua_State *L, fd_set *set, t_socket max_fd,
static void return_fd(lua_State *L, fd_set *set, t_socket max_fd,
int itab, int tab, int start);
static void make_assoc(lua_State *L, int tab);
static int global_select(lua_State *L);
@ -89,9 +89,9 @@ static t_socket getfd(lua_State *L) {
if (!lua_isnil(L, -1)) {
lua_pushvalue(L, -2);
lua_call(L, 1, 1);
if (lua_isnumber(L, -1))
fd = (t_socket) lua_tonumber(L, -1);
}
if (lua_isnumber(L, -1))
fd = (t_socket) lua_tonumber(L, -1);
}
lua_pop(L, 1);
return fd;
}
@ -104,15 +104,15 @@ static int dirty(lua_State *L) {
lua_pushvalue(L, -2);
lua_call(L, 1, 1);
is = lua_toboolean(L, -1);
}
}
lua_pop(L, 1);
return is;
}
static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd,
static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd,
int itab, fd_set *set) {
int i = 1;
if (lua_isnil(L, tab))
if (lua_isnil(L, tab))
return max_fd;
while (1) {
t_socket fd;
@ -125,7 +125,7 @@ static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd,
fd = getfd(L);
if (fd != SOCKET_INVALID) {
FD_SET(fd, set);
if (max_fd == SOCKET_INVALID || max_fd < fd)
if (max_fd == SOCKET_INVALID || max_fd < fd)
max_fd = fd;
lua_pushnumber(L, fd);
lua_pushvalue(L, -2);
@ -139,9 +139,9 @@ static t_socket collect_fd(lua_State *L, int tab, t_socket max_fd,
static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) {
int ndirty = 0, i = 1;
if (lua_isnil(L, tab))
if (lua_isnil(L, tab))
return 0;
while (1) {
while (1) {
t_socket fd;
lua_pushnumber(L, i);
lua_gettable(L, tab);
@ -162,7 +162,7 @@ static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) {
return ndirty;
}
static void return_fd(lua_State *L, fd_set *set, t_socket max_fd,
static void return_fd(lua_State *L, fd_set *set, t_socket max_fd,
int itab, int tab, int start) {
t_socket fd;
for (fd = 0; fd < max_fd; fd++) {

View File

@ -4,9 +4,9 @@
* Select implementation
* LuaSocket toolkit
*
* Each object that can be passed to the select function has to export
* Each object that can be passed to the select function has to export
* method getfd() which returns the descriptor to be passed to the
* underlying select function. Another method, dirty(), should return
* underlying select function. Another method, dirty(), should return
* true if there is data ready for reading (required for buffered input).
*
* RCS ID: $Id: select.h,v 1.7 2004/06/16 01:02:07 diego Exp $

View File

@ -26,7 +26,7 @@
* The connect and accept functions accept a timeout and their
* implementations are somewhat complicated. We chose to move
* the timeout control into this module for these functions in
* order to simplify the modules that use them.
* order to simplify the modules that use them.
\*=========================================================================*/
#include "timeout.h"
@ -34,38 +34,38 @@
typedef struct sockaddr SA;
/*=========================================================================*\
* Functions bellow implement a comfortable platform independent
* Functions bellow implement a comfortable platform independent
* interface to sockets
\*=========================================================================*/
int socket_open(void);
int socket_close(void);
void socket_destroy(p_socket ps);
void socket_shutdown(p_socket ps, int how);
int socket_sendto(p_socket ps, const char *data, size_t count,
void socket_shutdown(p_socket ps, int how);
int socket_sendto(p_socket ps, const char *data, size_t count,
size_t *sent, SA *addr, socklen_t addr_len, p_timeout tm);
int socket_recvfrom(p_socket ps, char *data, size_t count,
int socket_recvfrom(p_socket ps, char *data, size_t count,
size_t *got, SA *addr, socklen_t *addr_len, p_timeout tm);
void socket_setnonblocking(p_socket ps);
void socket_setblocking(p_socket ps);
int socket_waitfd(p_socket ps, int sw, p_timeout tm);
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
p_timeout tm);
int socket_connect(p_socket ps, SA *addr, socklen_t addr_len, p_timeout tm);
int socket_connect(p_socket ps, SA *addr, socklen_t addr_len, p_timeout tm);
int socket_create(p_socket ps, int domain, int type, int protocol);
int socket_bind(p_socket ps, SA *addr, socklen_t addr_len);
int socket_bind(p_socket ps, SA *addr, socklen_t addr_len);
int socket_listen(p_socket ps, int backlog);
int socket_accept(p_socket ps, p_socket pa, SA *addr,
int socket_accept(p_socket ps, p_socket pa, SA *addr,
socklen_t *addr_len, p_timeout tm);
const char *socket_hoststrerror(int err);
const char *socket_strerror(int err);
/* these are perfect to use with the io abstraction module
/* these are perfect to use with the io abstraction module
and the buffered input module */
int socket_send(p_socket ps, const char *data, size_t count,
int socket_send(p_socket ps, const char *data, size_t count,
size_t *sent, p_timeout tm);
int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm);
const char *socket_ioerror(p_socket ps, int err);

View File

@ -1,10 +1,10 @@
/*=========================================================================*\
* TCP object
* TCP object
* LuaSocket toolkit
*
* RCS ID: $Id: tcp.c,v 1.41 2005/10/07 04:40:59 diego Exp $
\*=========================================================================*/
#include <string.h>
#include <string.h>
#include "auxiliar.h"
#include "socket.h"
@ -89,7 +89,7 @@ int tcp_open(lua_State *L)
auxiliar_add2group(L, "tcp{client}", "tcp{any}");
auxiliar_add2group(L, "tcp{server}", "tcp{any}");
/* define library functions */
luaL_openlib(L, NULL, func, 0);
luaL_openlib(L, NULL, func, 0);
return 0;
}
@ -142,7 +142,7 @@ static int meth_getfd(lua_State *L)
static int meth_setfd(lua_State *L)
{
p_tcp tcp = (p_tcp) auxiliar_checkgroup(L, "tcp{any}", 1);
tcp->sock = (t_socket) luaL_checknumber(L, 2);
tcp->sock = (t_socket) luaL_checknumber(L, 2);
return 0;
}
@ -154,8 +154,8 @@ static int meth_dirty(lua_State *L)
}
/*-------------------------------------------------------------------------*\
* Waits for and returns a client object attempting connection to the
* server object
* Waits for and returns a client object attempting connection to the
* server object
\*-------------------------------------------------------------------------*/
static int meth_accept(lua_State *L)
{
@ -170,20 +170,20 @@ static int meth_accept(lua_State *L)
/* initialize structure fields */
socket_setnonblocking(&sock);
clnt->sock = sock;
io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv,
io_init(&clnt->io, (p_send) socket_send, (p_recv) socket_recv,
(p_error) socket_ioerror, &clnt->sock);
timeout_init(&clnt->tm, -1, -1);
buffer_init(&clnt->buf, &clnt->io, &clnt->tm);
return 1;
} else {
lua_pushnil(L);
lua_pushnil(L);
lua_pushstring(L, socket_strerror(err));
return 2;
}
}
/*-------------------------------------------------------------------------*\
* Binds an object to an address
* Binds an object to an address
\*-------------------------------------------------------------------------*/
static int meth_bind(lua_State *L)
{
@ -223,7 +223,7 @@ static int meth_connect(lua_State *L)
}
/*-------------------------------------------------------------------------*\
* Closes socket used by object
* Closes socket used by object
\*-------------------------------------------------------------------------*/
static int meth_close(lua_State *L)
{
@ -308,14 +308,14 @@ static int meth_settimeout(lua_State *L)
* Library functions
\*=========================================================================*/
/*-------------------------------------------------------------------------*\
* Creates a master tcp object
* Creates a master tcp object
\*-------------------------------------------------------------------------*/
static int global_create(lua_State *L)
{
t_socket sock;
const char *err = inet_trycreate(&sock, SOCK_STREAM);
/* try to allocate a system socket */
if (!err) {
if (!err) {
/* allocate tcp object */
p_tcp tcp = (p_tcp) lua_newuserdata(L, sizeof(t_tcp));
/* set its type as master object */
@ -323,7 +323,7 @@ static int global_create(lua_State *L)
/* initialize remaining structure fields */
socket_setnonblocking(&sock);
tcp->sock = sock;
io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv,
io_init(&tcp->io, (p_send) socket_send, (p_recv) socket_recv,
(p_error) socket_ioerror, &tcp->sock);
timeout_init(&tcp->tm, -1, -1);
buffer_init(&tcp->buf, &tcp->io, &tcp->tm);

View File

@ -49,7 +49,7 @@ void timeout_init(p_timeout tm, double block, double total) {
/*-------------------------------------------------------------------------*\
* Determines how much time we have left for the next system call,
* if the previous call was successful
* if the previous call was successful
* Input
* tm: timeout control structure
* Returns
@ -104,7 +104,7 @@ double timeout_getretry(p_timeout tm) {
}
/*-------------------------------------------------------------------------*\
* Marks the operation start time in structure
* Marks the operation start time in structure
* Input
* tm: timeout control structure
\*-------------------------------------------------------------------------*/
@ -114,7 +114,7 @@ p_timeout timeout_markstart(p_timeout tm) {
}
/*-------------------------------------------------------------------------*\
* Gets time in s, relative to January 1, 1970 (UTC)
* Gets time in s, relative to January 1, 1970 (UTC)
* Returns
* time in s.
\*-------------------------------------------------------------------------*/
@ -156,7 +156,7 @@ int timeout_meth_settimeout(lua_State *L, p_timeout tm) {
const char *mode = luaL_optstring(L, 3, "b");
switch (*mode) {
case 'b':
tm->block = t;
tm->block = t;
break;
case 'r': case 't':
tm->total = t;

View File

@ -1,10 +1,10 @@
/*=========================================================================*\
* UDP object
* UDP object
* LuaSocket toolkit
*
* RCS ID: $Id: udp.c,v 1.29 2005/10/07 04:40:59 diego Exp $
\*=========================================================================*/
#include <string.h>
#include <string.h>
#include "auxiliar.h"
#include "socket.h"
@ -15,10 +15,10 @@
/* min and max macros */
#ifndef MIN
#define MIN(x, y) ((x) < (y) ? x : y)
#endif
#endif
#ifndef MAX
#define MAX(x, y) ((x) > (y) ? x : y)
#endif
#endif
/*=========================================================================*\
* Internal function prototypes
@ -92,7 +92,7 @@ int udp_open(lua_State *L)
auxiliar_add2group(L, "udp{connected}", "select{able}");
auxiliar_add2group(L, "udp{unconnected}", "select{able}");
/* define library functions */
luaL_openlib(L, NULL, func, 0);
luaL_openlib(L, NULL, func, 0);
return 0;
}
@ -139,12 +139,12 @@ static int meth_sendto(lua_State *L) {
struct sockaddr_in addr;
int err;
memset(&addr, 0, sizeof(addr));
if (!inet_aton(ip, &addr.sin_addr))
if (!inet_aton(ip, &addr.sin_addr))
luaL_argerror(L, 3, "invalid ip address");
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
timeout_markstart(tm);
err = socket_sendto(&udp->sock, data, count, &sent,
err = socket_sendto(&udp->sock, data, count, &sent,
(SA *) &addr, sizeof(addr), tm);
if (err != IO_DONE) {
lua_pushnil(L);
@ -189,7 +189,7 @@ static int meth_receivefrom(lua_State *L) {
p_timeout tm = &udp->tm;
timeout_markstart(tm);
count = MIN(count, sizeof(buffer));
err = socket_recvfrom(&udp->sock, buffer, count, &got,
err = socket_recvfrom(&udp->sock, buffer, count, &got,
(SA *) &addr, &addr_len, tm);
if (err == IO_DONE) {
lua_pushlstring(L, buffer, got);
@ -263,8 +263,8 @@ static int meth_setpeername(lua_State *L) {
p_timeout tm = &udp->tm;
const char *address = luaL_checkstring(L, 2);
int connecting = strcmp(address, "*");
unsigned short port = connecting ?
(unsigned short) luaL_checknumber(L, 3) :
unsigned short port = connecting ?
(unsigned short) luaL_checknumber(L, 3) :
(unsigned short) luaL_optnumber(L, 3, 0);
const char *err = inet_tryconnect(&udp->sock, address, port, tm);
if (err) {
@ -280,7 +280,7 @@ static int meth_setpeername(lua_State *L) {
}
/*-------------------------------------------------------------------------*\
* Closes socket used by object
* Closes socket used by object
\*-------------------------------------------------------------------------*/
static int meth_close(lua_State *L) {
p_udp udp = (p_udp) auxiliar_checkgroup(L, "udp{any}", 1);
@ -310,13 +310,13 @@ static int meth_setsockname(lua_State *L) {
* Library functions
\*=========================================================================*/
/*-------------------------------------------------------------------------*\
* Creates a master udp object
* Creates a master udp object
\*-------------------------------------------------------------------------*/
static int global_create(lua_State *L) {
t_socket sock;
const char *err = inet_trycreate(&sock, SOCK_DGRAM);
/* try to allocate a system socket */
if (!err) {
if (!err) {
/* allocate tcp object */
p_udp udp = (p_udp) lua_newuserdata(L, sizeof(t_udp));
auxiliar_setclass(L, "udp{unconnected}", -1);

View File

@ -8,7 +8,7 @@
* (AF_INET, SOCK_DGRAM).
*
* Two classes are defined: connected and unconnected. UDP objects are
* originally unconnected. They can be "connected" to a given address
* originally unconnected. They can be "connected" to a given address
* with a call to the setpeername function. The same function can be used to
* break the connection.
*

View File

@ -1,17 +1,17 @@
#ifndef WIN
/*=========================================================================*\
* Unix domain socket
* Unix domain socket
* LuaSocket toolkit
*
* RCS ID: $Id: unix.c,v 1.13 2006/03/13 07:16:39 diego Exp $
\*=========================================================================*/
#include <string.h>
#include <string.h>
#include "auxiliar.h"
#include "socket.h"
#include "options.h"
#include "unix.h"
#include <sys/un.h>
#include <sys/un.h>
/*=========================================================================*\
* Internal function prototypes
@ -141,7 +141,7 @@ static int meth_getfd(lua_State *L) {
/* this is very dangerous, but can be handy for those that are brave enough */
static int meth_setfd(lua_State *L) {
p_unix un = (p_unix) auxiliar_checkgroup(L, "unix{any}", 1);
un->sock = (t_socket) luaL_checknumber(L, 2);
un->sock = (t_socket) luaL_checknumber(L, 2);
return 0;
}
@ -152,8 +152,8 @@ static int meth_dirty(lua_State *L) {
}
/*-------------------------------------------------------------------------*\
* Waits for and returns a client object attempting connection to the
* server object
* Waits for and returns a client object attempting connection to the
* server object
\*-------------------------------------------------------------------------*/
static int meth_accept(lua_State *L) {
p_unix server = (p_unix) auxiliar_checkclass(L, "unix{server}", 1);
@ -167,20 +167,20 @@ static int meth_accept(lua_State *L) {
/* initialize structure fields */
socket_setnonblocking(&sock);
clnt->sock = sock;
io_init(&clnt->io, (p_send)socket_send, (p_recv)socket_recv,
io_init(&clnt->io, (p_send)socket_send, (p_recv)socket_recv,
(p_error) socket_ioerror, &clnt->sock);
timeout_init(&clnt->tm, -1, -1);
buffer_init(&clnt->buf, &clnt->io, &clnt->tm);
return 1;
} else {
lua_pushnil(L);
lua_pushnil(L);
lua_pushstring(L, socket_strerror(err));
return 2;
}
}
/*-------------------------------------------------------------------------*\
* Binds an object to an address
* Binds an object to an address
\*-------------------------------------------------------------------------*/
static const char *unix_trybind(p_unix un, const char *path) {
struct sockaddr_un local;
@ -191,16 +191,16 @@ static const char *unix_trybind(p_unix un, const char *path) {
strcpy(local.sun_path, path);
local.sun_family = AF_UNIX;
#ifdef UNIX_HAS_SUN_LEN
local.sun_len = sizeof(local.sun_family) + sizeof(local.sun_len)
local.sun_len = sizeof(local.sun_family) + sizeof(local.sun_len)
+ len + 1;
err = socket_bind(&un->sock, (SA *) &local, local.sun_len);
#else
err = socket_bind(&un->sock, (SA *) &local,
#else
err = socket_bind(&un->sock, (SA *) &local,
sizeof(local.sun_family) + len);
#endif
if (err != IO_DONE) socket_destroy(&un->sock);
return socket_strerror(err);
return socket_strerror(err);
}
static int meth_bind(lua_State *L) {
@ -230,11 +230,11 @@ static const char *unix_tryconnect(p_unix un, const char *path)
remote.sun_family = AF_UNIX;
timeout_markstart(&un->tm);
#ifdef UNIX_HAS_SUN_LEN
remote.sun_len = sizeof(remote.sun_family) + sizeof(remote.sun_len)
remote.sun_len = sizeof(remote.sun_family) + sizeof(remote.sun_len)
+ len + 1;
err = socket_connect(&un->sock, (SA *) &remote, remote.sun_len, &un->tm);
#else
err = socket_connect(&un->sock, (SA *) &remote,
err = socket_connect(&un->sock, (SA *) &remote,
sizeof(remote.sun_family) + len, &un->tm);
#endif
if (err != IO_DONE) socket_destroy(&un->sock);
@ -258,7 +258,7 @@ static int meth_connect(lua_State *L)
}
/*-------------------------------------------------------------------------*\
* Closes socket used by object
* Closes socket used by object
\*-------------------------------------------------------------------------*/
static int meth_close(lua_State *L)
{
@ -327,13 +327,13 @@ static int meth_settimeout(lua_State *L) {
* Library functions
\*=========================================================================*/
/*-------------------------------------------------------------------------*\
* Creates a master unix object
* Creates a master unix object
\*-------------------------------------------------------------------------*/
static int global_create(lua_State *L) {
t_socket sock;
int err = socket_create(&sock, AF_UNIX, SOCK_STREAM, 0);
/* try to allocate a system socket */
if (err == IO_DONE) {
if (err == IO_DONE) {
/* allocate unix object */
p_unix un = (p_unix) lua_newuserdata(L, sizeof(t_unix));
/* set its type as master object */
@ -341,7 +341,7 @@ static int global_create(lua_State *L) {
/* initialize remaining structure fields */
socket_setnonblocking(&sock);
un->sock = sock;
io_init(&un->io, (p_send) socket_send, (p_recv) socket_recv,
io_init(&un->io, (p_send) socket_send, (p_recv) socket_recv,
(p_error) socket_ioerror, &un->sock);
timeout_init(&un->tm, -1, -1);
buffer_init(&un->buf, &un->io, &un->tm);

View File

@ -5,7 +5,7 @@
* Unix domain object
* LuaSocket toolkit
*
* This module is just an example of how to extend LuaSocket with a new
* This module is just an example of how to extend LuaSocket with a new
* domain.
*
* RCS ID: $Id: unix.h,v 1.9 2006/03/13 07:16:39 diego Exp $

View File

@ -5,11 +5,11 @@
*
* The code is now interrupt-safe.
* The penalty of calling select to avoid busy-wait is only paid when
* the I/O call fail in the first place.
* the I/O call fail in the first place.
*
* RCS ID: $Id: usocket.c,v 1.38 2007/10/13 23:55:20 diego Exp $
\*=========================================================================*/
#include <string.h>
#include <string.h>
#include <signal.h>
#include "socket.h"
@ -74,7 +74,7 @@ int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
/*-------------------------------------------------------------------------*\
* Initializes module
* Initializes module
\*-------------------------------------------------------------------------*/
int socket_open(void) {
/* instals a handler to ignore sigpipe or it will crash us */
@ -83,7 +83,7 @@ int socket_open(void) {
}
/*-------------------------------------------------------------------------*\
* Close module
* Close module
\*-------------------------------------------------------------------------*/
int socket_close(void) {
return 1;
@ -103,7 +103,7 @@ void socket_destroy(p_socket ps) {
/*-------------------------------------------------------------------------*\
* Select with timeout control
\*-------------------------------------------------------------------------*/
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
p_timeout tm) {
int ret;
do {
@ -122,8 +122,8 @@ int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
\*-------------------------------------------------------------------------*/
int socket_create(p_socket ps, int domain, int type, int protocol) {
*ps = socket(domain, type, protocol);
if (*ps != SOCKET_INVALID) return IO_DONE;
else return errno;
if (*ps != SOCKET_INVALID) return IO_DONE;
else return errno;
}
/*-------------------------------------------------------------------------*\
@ -132,24 +132,24 @@ int socket_create(p_socket ps, int domain, int type, int protocol) {
int socket_bind(p_socket ps, SA *addr, socklen_t len) {
int err = IO_DONE;
socket_setblocking(ps);
if (bind(*ps, addr, len) < 0) err = errno;
if (bind(*ps, addr, len) < 0) err = errno;
socket_setnonblocking(ps);
return err;
}
/*-------------------------------------------------------------------------*\
*
*
\*-------------------------------------------------------------------------*/
int socket_listen(p_socket ps, int backlog) {
int err = IO_DONE;
int err = IO_DONE;
socket_setblocking(ps);
if (listen(*ps, backlog)) err = errno;
if (listen(*ps, backlog)) err = errno;
socket_setnonblocking(ps);
return err;
}
/*-------------------------------------------------------------------------*\
*
*
\*-------------------------------------------------------------------------*/
void socket_shutdown(p_socket ps, int how) {
socket_setblocking(ps);
@ -168,7 +168,7 @@ int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) {
do if (connect(*ps, addr, len) == 0) return IO_DONE;
while ((err = errno) == EINTR);
/* if connection failed immediately, return error code */
if (err != EINPROGRESS && err != EAGAIN) return err;
if (err != EINPROGRESS && err != EAGAIN) return err;
/* zero timeout case optimization */
if (timeout_iszero(tm)) return IO_TIMEOUT;
/* wait until we have the result of the connection attempt or timeout */
@ -185,7 +185,7 @@ int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) {
int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, p_timeout tm) {
SA daddr;
socklen_t dlen = sizeof(daddr);
if (*ps == SOCKET_INVALID) return IO_CLOSED;
if (*ps == SOCKET_INVALID) return IO_CLOSED;
if (!addr) addr = &daddr;
if (!len) len = &dlen;
for ( ;; ) {
@ -203,7 +203,7 @@ int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len, p_timeout
/*-------------------------------------------------------------------------*\
* Send with timeout
\*-------------------------------------------------------------------------*/
int socket_send(p_socket ps, const char *data, size_t count,
int socket_send(p_socket ps, const char *data, size_t count,
size_t *sent, p_timeout tm)
{
int err;
@ -219,7 +219,7 @@ int socket_send(p_socket ps, const char *data, size_t count,
return IO_DONE;
}
err = errno;
/* send can't really return 0, but EPIPE means the connection was
/* send can't really return 0, but EPIPE means the connection was
closed */
if (put == 0 || err == EPIPE) return IO_CLOSED;
/* we call was interrupted, just try again */
@ -236,14 +236,14 @@ int socket_send(p_socket ps, const char *data, size_t count,
/*-------------------------------------------------------------------------*\
* Sendto with timeout
\*-------------------------------------------------------------------------*/
int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent,
int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent,
SA *addr, socklen_t len, p_timeout tm)
{
int err;
*sent = 0;
if (*ps == SOCKET_INVALID) return IO_CLOSED;
for ( ;; ) {
long put = (long) sendto(*ps, data, count, 0, addr, len);
long put = (long) sendto(*ps, data, count, 0, addr, len);
if (put > 0) {
*sent = put;
return IO_DONE;
@ -273,8 +273,8 @@ int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm
err = errno;
if (taken == 0) return IO_CLOSED;
if (err == EINTR) continue;
if (err != EAGAIN) return err;
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
if (err != EAGAIN) return err;
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
}
return IO_UNKNOWN;
}
@ -282,7 +282,7 @@ int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm
/*-------------------------------------------------------------------------*\
* Recvfrom with timeout
\*-------------------------------------------------------------------------*/
int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
SA *addr, socklen_t *len, p_timeout tm) {
int err;
*got = 0;
@ -296,8 +296,8 @@ int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
err = errno;
if (taken == 0) return IO_CLOSED;
if (err == EINTR) continue;
if (err != EAGAIN) return err;
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
if (err != EAGAIN) return err;
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
}
return IO_UNKNOWN;
}
@ -321,7 +321,7 @@ void socket_setnonblocking(p_socket ps) {
}
/*-------------------------------------------------------------------------*\
* DNS helpers
* DNS helpers
\*-------------------------------------------------------------------------*/
int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) {
*hp = gethostbyaddr(addr, len, AF_INET);
@ -368,5 +368,5 @@ const char *socket_strerror(int err) {
const char *socket_ioerror(p_socket ps, int err) {
(void) ps;
return socket_strerror(err);
}
}
#endif

View File

@ -4,7 +4,7 @@
* LuaSocket toolkit
*
* The penalty of calling select to avoid busy-wait is only paid when
* the I/O call fail in the first place.
* the I/O call fail in the first place.
*
* RCS ID: $Id: wsocket.c,v 1.36 2007/06/11 23:44:54 diego Exp $
\*=========================================================================*/
@ -16,23 +16,23 @@
static const char *wstrerror(int err);
/*-------------------------------------------------------------------------*\
* Initializes module
* Initializes module
\*-------------------------------------------------------------------------*/
int socket_open(void) {
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 0);
WORD wVersionRequested = MAKEWORD(2, 0);
int err = WSAStartup(wVersionRequested, &wsaData );
if (err != 0) return 0;
if ((LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) &&
(LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)) {
WSACleanup();
return 0;
return 0;
}
return 1;
}
/*-------------------------------------------------------------------------*\
* Close module
* Close module
\*-------------------------------------------------------------------------*/
int socket_close(void) {
WSACleanup();
@ -53,10 +53,10 @@ int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
struct timeval tv, *tp = NULL;
double t;
if (timeout_iszero(tm)) return IO_TIMEOUT; /* optimize timeout == 0 case */
if (sw & WAITFD_R) {
FD_ZERO(&rfds);
if (sw & WAITFD_R) {
FD_ZERO(&rfds);
FD_SET(*ps, &rfds);
rp = &rfds;
rp = &rfds;
}
if (sw & WAITFD_W) { FD_ZERO(&wfds); FD_SET(*ps, &wfds); wp = &wfds; }
if (sw & WAITFD_C) { FD_ZERO(&efds); FD_SET(*ps, &efds); ep = &efds; }
@ -75,9 +75,9 @@ int socket_waitfd(p_socket ps, int sw, p_timeout tm) {
/*-------------------------------------------------------------------------*\
* Select with int timeout in ms
\*-------------------------------------------------------------------------*/
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
int socket_select(t_socket n, fd_set *rfds, fd_set *wfds, fd_set *efds,
p_timeout tm) {
struct timeval tv;
struct timeval tv;
double t = timeout_get(tm);
tv.tv_sec = (int) t;
tv.tv_usec = (int) ((t - tv.tv_sec) * 1.0e6);
@ -99,7 +99,7 @@ void socket_destroy(p_socket ps) {
}
/*-------------------------------------------------------------------------*\
*
*
\*-------------------------------------------------------------------------*/
void socket_shutdown(p_socket ps, int how) {
socket_setblocking(ps);
@ -137,10 +137,10 @@ int socket_connect(p_socket ps, SA *addr, socklen_t len, p_timeout tm) {
/* give windows time to set the error (yes, disgusting) */
Sleep(10);
/* find out why we failed */
getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
getsockopt(*ps, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
/* we KNOW there was an error. if 'why' is 0, we will return
* "unknown error", but it's not really our fault */
return err > 0? err: IO_UNKNOWN;
return err > 0? err: IO_UNKNOWN;
} else return err;
}
@ -157,7 +157,7 @@ int socket_bind(p_socket ps, SA *addr, socklen_t len) {
}
/*-------------------------------------------------------------------------*\
*
*
\*-------------------------------------------------------------------------*/
int socket_listen(p_socket ps, int backlog) {
int err = IO_DONE;
@ -170,7 +170,7 @@ int socket_listen(p_socket ps, int backlog) {
/*-------------------------------------------------------------------------*\
* Accept with timeout
\*-------------------------------------------------------------------------*/
int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len,
int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len,
p_timeout tm) {
SA daddr;
socklen_t dlen = sizeof(daddr);
@ -182,23 +182,23 @@ int socket_accept(p_socket ps, p_socket pa, SA *addr, socklen_t *len,
/* try to get client socket */
if ((*pa = accept(*ps, addr, len)) != SOCKET_INVALID) return IO_DONE;
/* find out why we failed */
err = WSAGetLastError();
err = WSAGetLastError();
/* if we failed because there was no connectoin, keep trying */
if (err != WSAEWOULDBLOCK && err != WSAECONNABORTED) return err;
/* call select to avoid busy wait */
if ((err = socket_waitfd(ps, WAITFD_R, tm)) != IO_DONE) return err;
}
}
/* can't reach here */
return IO_UNKNOWN;
return IO_UNKNOWN;
}
/*-------------------------------------------------------------------------*\
* Send with timeout
* On windows, if you try to send 10MB, the OS will buffer EVERYTHING
* this can take an awful lot of time and we will end up blocked.
* On windows, if you try to send 10MB, the OS will buffer EVERYTHING
* this can take an awful lot of time and we will end up blocked.
* Therefore, whoever calls this function should not pass a huge buffer.
\*-------------------------------------------------------------------------*/
int socket_send(p_socket ps, const char *data, size_t count,
int socket_send(p_socket ps, const char *data, size_t count,
size_t *sent, p_timeout tm)
{
int err;
@ -215,12 +215,12 @@ int socket_send(p_socket ps, const char *data, size_t count,
return IO_DONE;
}
/* deal with failure */
err = WSAGetLastError();
err = WSAGetLastError();
/* we can only proceed if there was no serious error */
if (err != WSAEWOULDBLOCK) return err;
/* avoid busy wait */
if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
}
}
/* can't reach here */
return IO_UNKNOWN;
}
@ -228,7 +228,7 @@ int socket_send(p_socket ps, const char *data, size_t count,
/*-------------------------------------------------------------------------*\
* Sendto with timeout
\*-------------------------------------------------------------------------*/
int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent,
int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent,
SA *addr, socklen_t len, p_timeout tm)
{
int err;
@ -240,10 +240,10 @@ int socket_sendto(p_socket ps, const char *data, size_t count, size_t *sent,
*sent = put;
return IO_DONE;
}
err = WSAGetLastError();
err = WSAGetLastError();
if (err != WSAEWOULDBLOCK) return err;
if ((err = socket_waitfd(ps, WAITFD_W, tm)) != IO_DONE) return err;
}
}
return IO_UNKNOWN;
}
@ -271,7 +271,7 @@ int socket_recv(p_socket ps, char *data, size_t count, size_t *got, p_timeout tm
/*-------------------------------------------------------------------------*\
* Recvfrom with timeout
\*-------------------------------------------------------------------------*/
int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
int socket_recvfrom(p_socket ps, char *data, size_t count, size_t *got,
SA *addr, socklen_t *len, p_timeout tm) {
int err;
*got = 0;
@ -307,7 +307,7 @@ void socket_setnonblocking(p_socket ps) {
}
/*-------------------------------------------------------------------------*\
* DNS helpers
* DNS helpers
\*-------------------------------------------------------------------------*/
int socket_gethostbyaddr(const char *addr, socklen_t len, struct hostent **hp) {
*hp = gethostbyaddr(addr, len, AF_INET);
@ -328,7 +328,7 @@ const char *socket_hoststrerror(int err) {
if (err <= 0) return io_strerror(err);
switch (err) {
case WSAHOST_NOT_FOUND: return "host not found";
default: return wstrerror(err);
default: return wstrerror(err);
}
}
@ -370,8 +370,8 @@ static const char *wstrerror(int err) {
case WSAESOCKTNOSUPPORT: return "Socket type not supported";
case WSAEOPNOTSUPP: return "Operation not supported";
case WSAEPFNOSUPPORT: return "Protocol family not supported";
case WSAEAFNOSUPPORT:
return "Address family not supported by protocol family";
case WSAEAFNOSUPPORT:
return "Address family not supported by protocol family";
case WSAEADDRINUSE: return "Address already in use";
case WSAEADDRNOTAVAIL: return "Cannot assign requested address";
case WSAENETDOWN: return "Network is down";
@ -390,12 +390,12 @@ static const char *wstrerror(int err) {
case WSAEPROCLIM: return "Too many processes";
case WSASYSNOTREADY: return "Network subsystem is unavailable";
case WSAVERNOTSUPPORTED: return "Winsock.dll version out of range";
case WSANOTINITIALISED:
case WSANOTINITIALISED:
return "Successful WSAStartup not yet performed";
case WSAEDISCON: return "Graceful shutdown in progress";
case WSAHOST_NOT_FOUND: return "Host not found";
case WSATRY_AGAIN: return "Nonauthoritative host not found";
case WSANO_RECOVERY: return "Nonrecoverable name lookup error";
case WSANO_RECOVERY: return "Nonrecoverable name lookup error";
case WSANO_DATA: return "Valid name, no data record of requested type";
default: return "Unknown error";
}

View File

@ -18,7 +18,7 @@ NSOpenGLContext* ensureContext(NSOpenGLContext* openGLContext, NSView *view) {
NSOpenGLContext* _openGLContext = openGLContext;
if (!_openGLContext) {
NSOpenGLPixelFormat* pixelFormat = defaultPixelFormat();
_openGLContext = [[NSOpenGLContext alloc]
_openGLContext = [[NSOpenGLContext alloc]
initWithFormat:pixelFormat
shareContext:nil];
[pixelFormat release];
@ -27,29 +27,29 @@ NSOpenGLContext* ensureContext(NSOpenGLContext* openGLContext, NSView *view) {
[_openGLContext setView:view];
}
[_openGLContext makeCurrentContext];
return _openGLContext;
}
ContextInfo* getContext(JNIEnv *env, jobject canvas)
ContextInfo* getContext(JNIEnv *env, jobject canvas)
{
if (!ctxID) {
jclass cls = env->GetObjectClass(canvas);
ctxID = env->GetFieldID(cls, "openGLContext", "J");
}
}
ContextInfo *ci = (ContextInfo *)(long)(env->GetLongField(canvas, ctxID));
if (!ci) {
ci = (ContextInfo *)calloc(sizeof(ContextInfo), 1);
ci->awt = (JAWT *)calloc(sizeof(JAWT), 1);
env->SetLongField(canvas, ctxID, (jlong)(long)ci);
}
return ci;
}
void freeContext(JNIEnv *env, jobject canvas, ContextInfo* ci)
void freeContext(JNIEnv *env, jobject canvas, ContextInfo* ci)
{
if (ci) {
free(ci->awt);
@ -61,18 +61,18 @@ void freeContext(JNIEnv *env, jobject canvas, ContextInfo* ci)
JNIEXPORT jboolean JNICALL Java_OpenGLCanvas_beginOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
// Lock the drawing surface
// You must lock EACH TIME before drawing
jint lock = ci->ds->Lock(ci->ds);
jint lock = ci->ds->Lock(ci->ds);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
assert((lock & JAWT_LOCK_ERROR) == 0);
// Get the drawing surface info
ci->dsi = ci->ds->GetDrawingSurfaceInfo(ci->ds);
// Check DrawingSurfaceInfo. This can be NULL on Mac OS X
// if the windowing system is not ready
if (ci->dsi != NULL) {
@ -83,32 +83,32 @@ JNIEXPORT jboolean JNICALL Java_OpenGLCanvas_beginOpenGL(JNIEnv *env, jobject ca
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
// Get the corresponding peer from the caller canvas
ci->view = ci->dsi_mac->cocoaViewRef;
ci->openGLContext = ensureContext(ci->openGLContext, ci->view);
return JNI_TRUE;
}
return JNI_FALSE;
}
JNIEXPORT void JNICALL Java_OpenGLCanvas_endOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
[ci->openGLContext flushBuffer];
// Free the DrawingSurfaceInfo
ci->ds->FreeDrawingSurfaceInfo(ci->dsi);
if (env->ExceptionOccurred()){
env->ExceptionDescribe();
}
// Unlock the drawing surface
// You must unlock EACH TIME when done drawing
ci->ds->Unlock(ci->ds);
ci->ds->Unlock(ci->ds);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
@ -117,37 +117,37 @@ JNIEXPORT void JNICALL Java_OpenGLCanvas_endOpenGL(JNIEnv *env, jobject canvas)
JNIEXPORT void JNICALL Java_OpenGLCanvas_updateOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
[ci->openGLContext update];
}
JNIEXPORT void JNICALL Java_OpenGLCanvas_allocOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
jboolean result = JNI_FALSE;
// get the AWT
ci->awt->version = JAWT_VERSION_1_4;
result = JAWT_GetAWT(env, ci->awt);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
assert(result != JNI_FALSE);
assert(result != JNI_FALSE);
// Get the drawing surface. This can be safely cached.
// Anything below the DS (DSI, contexts, etc)
// Anything below the DS (DSI, contexts, etc)
// can possibly change/go away and should not be cached.
ci->ds = ci->awt->GetDrawingSurface(env, canvas);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
assert(ci->ds != NULL);
NSLog(@"Alloc Context %d", ci);
}
JNIEXPORT void JNICALL Java_OpenGLCanvas_releaseOpenGL(JNIEnv *env, jobject canvas)
JNIEXPORT void JNICALL Java_OpenGLCanvas_releaseOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
NSLog(@"Release Context %d", ci);
@ -157,13 +157,13 @@ JNIEXPORT void JNICALL Java_OpenGLCanvas_releaseOpenGL(JNIEnv *env, jobject canv
}
[ci->openGLContext release];
}
// Free the drawing surface (if not caching it)
ci->awt->FreeDrawingSurface(ci->ds);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
freeContext(env, canvas, ci);
}
#endif

View File

@ -32,17 +32,17 @@ HGLRC ensureContext(JAWT_Win32DrawingSurfaceInfo* dsi_win, HGLRC hRC) {
if (1 && wglGetCurrentDC() != dsi_win->hdc) {
wglMakeCurrent( dsi_win->hdc, hRC );
}
return hRC;
}
ContextInfo* getContext(JNIEnv *env, jobject canvas)
ContextInfo* getContext(JNIEnv *env, jobject canvas)
{
ContextInfo *ci;
if (!ctxID) {
jclass cls = env->GetObjectClass(canvas);
ctxID = env->GetFieldID(cls, "openGLContext", "J");
}
}
ci = (ContextInfo *)(long)(env->GetLongField(canvas, ctxID));
@ -51,11 +51,11 @@ ContextInfo* getContext(JNIEnv *env, jobject canvas)
ci->awt = (JAWT *)calloc(sizeof(JAWT), 1);
env->SetLongField(canvas, ctxID, (jlong)(long)ci);
}
return ci;
}
void freeContext(JNIEnv *env, jobject canvas, ContextInfo* ci)
void freeContext(JNIEnv *env, jobject canvas, ContextInfo* ci)
{
if (ci) {
free(ci->awt);
@ -68,7 +68,7 @@ JNIEXPORT jboolean JNICALL Java_OpenGLCanvas_beginOpenGL(JNIEnv *env, jobject ca
{
jint lock;
ContextInfo *ci = getContext(env, canvas);
// Get the drawing surface. This can be safely cached -- not in win32
// Anything below the DS (DSI, contexts, etc)
// can possibly change/go away and should not be cached.
@ -85,10 +85,10 @@ JNIEXPORT jboolean JNICALL Java_OpenGLCanvas_beginOpenGL(JNIEnv *env, jobject ca
env->ExceptionDescribe();
}
assert((lock & JAWT_LOCK_ERROR) == 0);
// Get the drawing surface info
ci->dsi = ci->ds->GetDrawingSurfaceInfo(ci->ds);
// Check DrawingSurfaceInfo. This can be NULL on Mac OS X
// if the windowing system is not ready
if (ci->dsi != NULL) {
@ -105,14 +105,14 @@ JNIEXPORT jboolean JNICALL Java_OpenGLCanvas_beginOpenGL(JNIEnv *env, jobject ca
return JNI_TRUE;
}
return JNI_FALSE;
}
JNIEXPORT void JNICALL Java_OpenGLCanvas_endOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
SwapBuffers( ci->dsi_win->hdc );
// Free the DrawingSurfaceInfo
@ -120,10 +120,10 @@ JNIEXPORT void JNICALL Java_OpenGLCanvas_endOpenGL(JNIEnv *env, jobject canvas)
if (env->ExceptionOccurred()){
env->ExceptionDescribe();
}
// Unlock the drawing surface
// You must unlock EACH TIME when done drawing
ci->ds->Unlock(ci->ds);
ci->ds->Unlock(ci->ds);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
@ -145,19 +145,19 @@ JNIEXPORT void JNICALL Java_OpenGLCanvas_updateOpenGL(JNIEnv *env, jobject canva
JNIEXPORT void JNICALL Java_OpenGLCanvas_allocOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
jboolean result = JNI_FALSE;
// get the AWT
ci->awt->version = JAWT_VERSION_1_4;
result = JAWT_GetAWT(env, ci->awt);
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
}
assert(result != JNI_FALSE);
assert(result != JNI_FALSE);
}
JNIEXPORT void JNICALL Java_OpenGLCanvas_releaseOpenGL(JNIEnv *env, jobject canvas)
JNIEXPORT void JNICALL Java_OpenGLCanvas_releaseOpenGL(JNIEnv *env, jobject canvas)
{
ContextInfo *ci = getContext(env, canvas);
if (ci->hRC) {

View File

@ -20,12 +20,12 @@ int elapsedTime = 0, currentTime = 0, lastTime = 0, currentFrame = 0;
float fps = 0, delta = 1.0f;
JNIEXPORT void JNICALL Java_PowderToy_initialise(JNIEnv * env, jobject canvas)
{
{
ui::Engine::Ref().g = new Graphics();
engine = &ui::Engine::Ref();
engine->Begin(WINDOWW, WINDOWH);
gameController = new GameController();
engine->ShowWindow(gameController->GetView());
engine->SetFps(fps);

View File

@ -10,7 +10,7 @@
// March 9, 2002: Kaiser filter grabbed from Jonathan Blow's GD magazine mipmap sample code.
// Sept. 8, 2002: Comments cleaned up a bit.
// Dec. 31, 2008: v2.2: Bit more cleanup, released as public domain.
// June 4, 2012: v2.21: Switched to unlicense.org, integrated GCC fixes supplied by Peter Nagy <petern@crytek.com>, Anteru at anteru.net, and clay@coge.net,
// June 4, 2012: v2.21: Switched to unlicense.org, integrated GCC fixes supplied by Peter Nagy <petern@crytek.com>, Anteru at anteru.net, and clay@coge.net,
// added Codeblocks project (for testing with MinGW and GCC), VS2008 static code analysis pass.
#include <cstdlib>
#include <cmath>

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