COpenALSound::COpenALSound()
{
	maxSounds = configHandler.GetInt("MaxSounds",16);
	noSound = false;
	cur = 0;
	if (!noSound) {
		ALCdevice *device = alcOpenDevice(NULL);
		if (device != NULL) {
			ALCcontext *context = alcCreateContext(device, NULL);
			if (context != NULL)
				alcMakeContextCurrent(context);
			else {
				handleerror(0, "Could not create audio context","OpenAL error",MBF_OK);
				noSound = true;
				alcCloseDevice(device);
				return;
			}
		} else {
			handleerror(0,"Could not create audio device","OpenAL error",MBF_OK);
			noSound = true;
			return;
		}
	}

	// Generate sound sources
	Sources = new ALuint[maxSounds];
	for (int a=0;a<maxSounds;a++) Sources[a]=0;

	// Set distance model (sound attenuation)
	alDistanceModel (AL_INVERSE_DISTANCE);

	posScale.x = 0.02f;
	posScale.y = 0.02f;
	posScale.z = 0.0005f;
}
Example #2
0
static bool glwindow(char* title, int width, int height, int bits, bool fsflag,int frequency)
{
	if ((SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1)) {
		handleerror(NULL,"Could not initialize SDL.","ERROR",MBF_OK|MBF_EXCL);
		return false;
	}

	// Sets window manager properties
	SDL_WM_SetIcon(SDL_LoadBMP("spring.bmp"),NULL);
	SDL_WM_SetCaption(title, title);

	int sdlflags = SDL_OPENGL | SDL_RESIZABLE;

	conditionally_set_flag(sdlflags, SDL_FULLSCREEN, fsflag);
	
	// FIXME: Might want to set color and depth sizes, too  -- johannes
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);

	FSAA = MultisampleTest();

	screen = SDL_SetVideoMode(width,height,bits,sdlflags);
	if (!screen) {
		handleerror(NULL,"Could not set video mode","ERROR",MBF_OK|MBF_EXCL);
		return false;
	}
	if (FSAA)
		FSAA = MultisampleVerify();
	
	setupgl();
	resizescene(screen->w,screen->h);

	return true;
}
CGlobalAI::CGlobalAI(int team, const char* dll)
: team(team)
{
	ai=0;

	if (!filesystem.GetFilesize(dll)) {
		handleerror(NULL,dll,"Could not find AI lib",MBF_OK|MBF_EXCL);
		return;
	}

	lib = SharedLib::instantiate(dll);
	
	GetGlobalAiVersion = (GETGLOBALAIVERSION)lib->FindAddress("GetGlobalAiVersion");
	if (GetGlobalAiVersion==0){
		handleerror(NULL,dll,"Incorrect Global AI dll",MBF_OK|MBF_EXCL);
		return;
	}
	
	int i=GetGlobalAiVersion();

	if (i!=GLOBAL_AI_INTERFACE_VERSION){
		handleerror(NULL,dll,"Incorrect Global AI dll version",MBF_OK|MBF_EXCL);
		return;
	}

	GetNewAI = (GETNEWAI)lib->FindAddress("GetNewAI");
	ReleaseAI = (RELEASEAI)lib->FindAddress("ReleaseAI");

	ai=GetNewAI();
	gh=new CGroupHandler(team);
	callback=new CGlobalAICallback(this);
	ai->InitAI(callback,team);
}
Example #4
0
int CNet::InitServer(int portnum)
{
    connected=true;
    waitOnCon=true;
    imServer=true;

    if ((mySocket= socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET ) { /* create socket */
        handleerror(NULL,"Error initializing socket as server.","SHUTDOWN ERROR",MBF_OK | MBF_INFO);
        connected=false;
        exit(0);
    }

    sockaddr_in saMe;

    saMe.sin_family = AF_INET;
    saMe.sin_addr.s_addr = INADDR_ANY; // Let WinSock assign address
    saMe.sin_port = htons(portnum);	   // Use port passed from user

    if (bind(mySocket,(struct sockaddr *)&saMe,sizeof(struct sockaddr_in)) == SOCKET_ERROR) {
        closesocket(mySocket);
        handleerror(NULL,"Error binding socket as server.","SHUTDOWN ERROR",MBF_OK | MBF_INFO);
        exit(0);
    }

#ifdef _WIN32
    u_long u=1;
    ioctlsocket(mySocket,FIONBIO,&u);
#else
    fcntl(mySocket, F_SETFL, O_NONBLOCK);
#endif
    return 0;
}
Example #5
0
// On msvc main() is declared as a non-throwing function. 
// Moving the catch clause to a seperate function makes it possible to re-throw the exception for the installed crash reporter
int Run(int argc, char *argv[])
{
// It's nice to be able to disable catching when you're debugging
#ifndef NO_CATCH_EXCEPTIONS
	try {
		SpringApp app;
		return app.Run (argc,argv);
	}
	catch (const content_error& e) {
		handleerror(NULL, e.what(), "Incorrect/Missing content:", MBF_OK | MBF_EXCL);
	#ifdef _MSC_VER
		info->AddLine ("Content error: %s\n",  e.what());
	#endif
		return -1;
	}
	catch (const std::exception& e) {
		handleerror(NULL, e.what(), "Fatal Error", MBF_OK | MBF_EXCL);
	#ifdef _MSC_VER
		info->AddLine ("Fatal error: %s\n",  e.what());
		throw; // let the error handler catch it
	#endif
		return -1;
	}
#else
	SpringApp app;
	return app.Run (argc, argv);
#endif
}
Example #6
0
// On msvc main() is declared as a non-throwing function.
// Moving the catch clause to a seperate function makes it possible to re-throw the exception for the installed crash reporter
int Run(int argc, char *argv[])
{
#ifdef __MINGW32__
	// For the MinGW backtrace() implementation we need to know the stack end.
	{
		extern void* stack_end;
		char here;
		stack_end = (void*) &here;
	}
#endif

#ifdef STREFLOP_H
	// Set single precision floating point math.
	streflop_init<streflop::Simple>();
#endif
	good_fpu_control_registers("::Run");

// It's nice to be able to disable catching when you're debugging
#ifndef NO_CATCH_EXCEPTIONS
	try {
		SpringApp app;
		return app.Run (argc,argv);
	}
	catch (const content_error& e) {
		SDL_Quit();
		logOutput.RemoveAllSubscribers();
		logOutput.Print ("Content error: %s\n",  e.what());
		handleerror(NULL, e.what(), "Incorrect/Missing content:", MBF_OK | MBF_EXCL);
		return -1;
	}
	catch (const std::exception& e) {
		SDL_Quit();
	#ifdef _MSC_VER
		logOutput.Print ("Fatal error: %s\n",  e.what());
		logOutput.RemoveAllSubscribers();
		throw; // let the error handler catch it
	#else
		logOutput.RemoveAllSubscribers();
		handleerror(NULL, e.what(), "Fatal Error", MBF_OK | MBF_EXCL);
		return -1;
	#endif
	}
	catch (const char* e) {
		SDL_Quit();
	#ifdef _MSC_VER
		logOutput.Print ("Fatal error: %s\n",  e);
		logOutput.RemoveAllSubscribers();
		throw; // let the error handler catch it
	#else
		logOutput.RemoveAllSubscribers();
		handleerror(NULL, e, "Fatal Error", MBF_OK | MBF_EXCL);
		return -1;
	#endif
	}
#else
	SpringApp app;
	return app.Run (argc, argv);
#endif
}
static void AIException(const char *what)
{
	static char msg[512];
	if(what) {
		SNPRINTF(msg, sizeof(msg), "An exception occured in the global ai dll: \'%s\',\n please contact the author of the AI.",	what);
		handleerror(0,msg, "Exception in global AI",0);
	} else
		handleerror(0,"An unhandled exception occured in the global ai dll, please contact the author of the ai.","Error in global ai",0);
	exit(-1);
}
static bool ReadWAV (const char *name, Uint8 *buf, int size, ALuint albuffer)
{
	WAVHeader *header = (WAVHeader *)buf;

	if (memcmp (header->riff, "RIFF",4) || memcmp (header->wavefmt, "WAVEfmt", 7)) {
		handleerror(0, "ReadWAV: invalid header.", name, 0);
		return false;
	}

#define hswabword(c) header->c = swabword(header->c)
#define hswabdword(c) header->c = swabdword(header->c)
	hswabword(format_tag);
	hswabword(channels);
	hswabword(BlockAlign);
	hswabword(BitsPerSample);

	hswabdword(totalLength);
	hswabdword(length);
	hswabdword(SamplesPerSec);
	hswabdword(AvgBytesPerSec);
	hswabdword(datalen);
#undef hswabword
#undef hswabdword

	if (header->format_tag != 1) { // Microsoft PCM format?
		handleerror(0,"ReadWAV: invalid format tag.", name, 0);
		return false;
	}

	ALenum format;
	if (header->channels == 1) {
		if (header->BitsPerSample == 8) format = AL_FORMAT_MONO8;
		else if (header->BitsPerSample == 16) format = AL_FORMAT_MONO16;
		else {
			handleerror(0,"ReadWAV: invalid number of bits per sample (mono).",name,0);
			return false;
		}
	}
	else if(header->channels == 2) {
		if (header->BitsPerSample == 8) format = AL_FORMAT_STEREO8;
		else if (header->BitsPerSample == 16) format = AL_FORMAT_STEREO16;
		else {
			handleerror(0,"ReadWAV: invalid number of bits per sample (stereo).", name,0);
			return false;
		}
	}
	else {
		handleerror(0,"ReadWAV (%s): invalid number of channels.", name,0);
		return false;
	}

	alBufferData(albuffer,format,buf+sizeof(WAVHeader),header->datalen > size-sizeof(WAVHeader) ? size-sizeof(WAVHeader) : header->datalen,header->SamplesPerSec);
	return CheckError("ReadWAV");
}
Example #9
0
void CGroup::SetNewAI(AIKey aiKey)
{
	eventHandler.GroupChanged(id);
	if(ai) {
		ReleaseAI(currentAiKey.aiNumber,ai);
		ai = 0;
	}
	if(lib) {
		delete lib;
		lib = 0;
	}

	currentAiKey=aiKey;
	if(aiKey.dllName=="default"){
		return;
	}

	lib = SharedLib::Instantiate(aiKey.dllName);
	if (lib==0)
		handleerror(NULL,aiKey.dllName.c_str(),"Could not find AI dll",MBF_OK|MBF_EXCL);

	GetGroupAiVersion = (GETGROUPAIVERSION)lib->FindAddress("GetGroupAiVersion");
	if (GetGroupAiVersion==0)
		handleerror(NULL,aiKey.dllName.c_str(),"Incorrect AI dll",MBF_OK|MBF_EXCL);

	int i=GetGroupAiVersion();

	if (i!=AI_INTERFACE_VERSION)
		handleerror(NULL,aiKey.dllName.c_str(),"Incorrect AI dll version",MBF_OK|MBF_EXCL);

	GetNewAI = (GETNEWAI)lib->FindAddress("GetNewAI");
	ReleaseAI = (RELEASEAI)lib->FindAddress("ReleaseAI");
	IsUnitSuited = (ISUNITSUITED)lib->FindAddress("IsUnitSuited");

	ai=GetNewAI(currentAiKey.aiNumber);
	ai->InitAi(callback);

	CUnitSet unitBackup=units;

	for(CUnitSet::iterator ui=unitBackup.begin();ui!=unitBackup.end();++ui)
	{
		if(IsUnitSuited(currentAiKey.aiNumber,(*ui)->unitDef))
		{
			if(ai->AddUnit((*ui)->id))
			{
				continue;
			}
		}
		units.erase(*ui);
		(*ui)->group=0;
	}
}
Example #10
0
CGlobalAI::CGlobalAI(int team, const char* dll)
: team(team), cheatevents(false)
{
	ai=0;

	if (!filesystem.GetFilesize(dll)) {
		handleerror(NULL,dll,"Could not find AI lib",MBF_OK|MBF_EXCL);
		return;
	}

	lib = SharedLib::Instantiate(dll);

	// check if presents C interface
	_IsCInterface = (ISCINTERFACE)lib->FindAddress("IsCInterface");
	if( _IsCInterface != 0 )
	{
		// presents C interface
        logOutput << dll <<  " has C interface\n";
		IsCInterface = true;
		AbicProxy* ai=new AbicProxy; // keep as AbicProxy, so InitAI works ok
		this->ai = ai;
		gh=new CGroupHandler(team);
		callback=new CGlobalAICallback(this);
		ai->InitAI(dll,callback,team);
	}
	else
	{
		// presents C++ interface
        logOutput << dll <<  " has C++ interface\n";
	
		GetGlobalAiVersion = (GETGLOBALAIVERSION)lib->FindAddress("GetGlobalAiVersion");
		if (GetGlobalAiVersion==0){
			handleerror(NULL,dll,"Incorrect Global AI dll",MBF_OK|MBF_EXCL);
			return;
		}
		
		int i=GetGlobalAiVersion();

		if (i!=GLOBAL_AI_INTERFACE_VERSION){
			handleerror(NULL,dll,"Incorrect Global AI dll version",MBF_OK|MBF_EXCL);
			return;
		}

		GetNewAI = (GETNEWAI)lib->FindAddress("GetNewAI");
		ReleaseAI = (RELEASEAI)lib->FindAddress("ReleaseAI");

		ai=GetNewAI();
		gh=new CGroupHandler(team);
		callback=new CGlobalAICallback(this);
		ai->InitAI(callback,team);
	}
}
Example #11
0
	void InitSyncify()
	{
		if(syncifyInitialized)
			return;
		codeType=CodeType_Mixed;

#ifdef _WIN32
		SyncedMem=VirtualAlloc(0,SUPER_BLOCK_SIZE,MEM_RESERVE,PAGE_READWRITE);		//only reserves mem, will need to commit mem as needed
		UnsyncedMem=VirtualAlloc(0,SUPER_BLOCK_SIZE,MEM_RESERVE,PAGE_READWRITE);
#else
		// As far as I know theres no such thing as reserving/committing memory on linux.
		// Kernel keeps track of which pages are actually used (ie. have to be in RAM/swap)
		// and which are only "reserved". So this reserves the memory and there's nothing
		// to do in HeapExpand1() and HeapExpand2().
		// void * mmap (void *ADDRESS, size_t LENGTH, int PROTECT, int FLAGS, int FILEDES, off_t OFFSET);
		SyncedMem   = mmap(0, SUPER_BLOCK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
		UnsyncedMem = mmap(0, SUPER_BLOCK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
		if (SyncedMem == MAP_FAILED || UnsyncedMem == MAP_FAILED)
			handleerror(0, strerror(errno), "Syncify: mmap failed", 0);
#endif

		heap1=new BGet();
		heap1->bectl(HeapExpand1,ALLOC_BLOCK_SIZE);
		heap2=new BGet();
		heap2->bectl(HeapExpand2,ALLOC_BLOCK_SIZE);

		syncifyInitialized=true;
	}
Example #12
0
	CMyMath()
	{
#ifdef STREFLOP_H
		// This must be put here too because it's executed before the streflop_init in main().
		// Set single precision floating point math.
		streflop_init<streflop::Simple>();
#endif

		for(int a=0;a<NUM_HEADINGS;++a){
			float ang=(a-(NUM_HEADINGS/2))*2*PI/NUM_HEADINGS;
			float2 v;
			v.x=sin(ang);
			v.y=cos(ang);
			headingToVectorTable[a]=v;
		}
		unsigned checksum = 0;
		for (int a = 0; a < NUM_HEADINGS; ++a) {
			checksum = 33 * checksum + *(unsigned*)&headingToVectorTable[a].x;
			checksum *= 33;
			checksum = 33 * checksum + *(unsigned*)&headingToVectorTable[a].y;
		}
#ifdef STREFLOP_H
		if (checksum != HEADING_CHECKSUM)
			handleerror(0, "Invalid headingToVectorTable checksum. Most likely"
					" your streflop library was not compiled with the correct"
					" options, or you are not using streflop at all.",
					"Sync Error", 0);
#endif // STREFLOP_H
	}
Example #13
0
void CNet::SendRawPacket(int conn, unsigned char* data, int length, int packetNum)
{
    Connection* c=&connections[conn];

    *(int*)&tempbuf[0]=packetNum;
    *(int*)&tempbuf[4]=c->lastInOrder;
    int hsize=9;
    if(!c->waitingPackets.empty() && c->waitingPackets.find(c->lastInOrder+1)==c->waitingPackets.end()) {
        tempbuf[8]=1;
        *(int*)&tempbuf[9]=c->waitingPackets.begin()->first-1;
        hsize=13;
    } else {
        tempbuf[8]=0;
    }

    memcpy(&tempbuf[hsize],data,length);
//	if(rand()&7)
    if(sendto(mySocket,(char*)tempbuf,length+hsize,0,(sockaddr*)&c->addr,sizeof(c->addr))==SOCKET_ERROR) {
        if (IsFakeError())
            return;
        char test[100];
        sprintf(test,"Error sending data. %d",WSAGetLastError());
        handleerror(NULL,test,"SHUTDOWN ERROR", MBF_OK | MBF_INFO);
        exit(0);
    }
}
Example #14
0
	CMyMath()
	{
		// This must be put here too because it's executed before the streflop_init in main().
		// Set single precision floating point math.
		streflop_init<streflop::Simple>();

		for(int a=0;a<1024;++a){
			float ang=(a-512)*2*PI/1024;
			float2 v;
			v.x=sin(ang);
			v.y=cos(ang);
			headingToVectorTable[a]=v;
		}
		unsigned checksum = 0;
		for (int a = 0; a < 1024; ++a) {
			checksum = 33 * checksum + *(unsigned*)&headingToVectorTable[a].x;
			checksum *= 33;
			checksum = 33 * checksum + *(unsigned*)&headingToVectorTable[a].y;
		}
// 		fprintf(stderr, "headingToVectorTable checksum: %08x\n", checksum);
		assert(checksum == 0x617a9968);

		// release mode check
		if (checksum != 0x617a9968)
			handleerror(0, "invalid headingToVectorTable checksum", "Sync Error", 0);
	}
ALuint COpenALSound::LoadALBuffer(const std::string& path)
{
	Uint8* buf = 0;
	ALuint buffer;
	alGenBuffers(1, &buffer);

	if (!CheckError("error generating OpenAL sound buffer"))
		return 0;

	CFileHandler file(path);

	if (file.FileExists()) {
		buf = SAFE_NEW Uint8[file.FileSize()];
		file.Read(buf, file.FileSize());
	} else {
		if (hardFail) {
			handleerror(0, "Couldn't open wav file", path.c_str(),0);
		}
		alDeleteBuffers(1, &buffer);
		return 0;
	}

	const bool success = ReadWAV(path.c_str(), buf, file.FileSize(), buffer);
	delete[] buf;

	if (!success) {
		alDeleteBuffers(1, &buffer);
		return 0;
	}

	return buffer;
}
Example #16
0
/**
 * @brief main
 * @return exit code
 * @param argc argument count
 * @param argv array of argument strings
 *
 * Main entry point function
 */
int main(int argc, char* argv[])
{
// PROFILE builds exit on execv ...
// HEADLESS run mostly in parallel for testing purposes, 100% omp threads wouldn't help then
#if !defined(PROFILE) && !defined(HEADLESS)
	bool restart = false;
	restart |= SetNvOptimusProfile(argv);
	restart |= SetOpenMpEnvVars(argv);

  #ifndef WIN32
	if (restart) {
		std::vector<std::string> args(argc-1);
		for (int i=1; i<argc; i++) {
			args[i-1] = argv[i];
		}
		const std::string err = Platform::ExecuteProcess(argv[0], args);
		ErrorMessageBox(err, "Execv error:", MBF_OK | MBF_EXCL);
	}
  #endif
#endif
	int ret = Run(argc, argv);
	std::string exe = EngineTypeHandler::GetRestartExecutable();
	if (exe != "") {
		std::vector<std::string> args;
		for (int i=1; i<argc; i++)
			args.push_back(argv[i]);
		if (!EngineTypeHandler::RestartEngine(exe, args)) {
			handleerror(NULL, EngineTypeHandler::GetRestartErrorMessage(), "Missing engine type", MBF_OK | MBF_EXCL);
		}
	}
	return ret;
}
Example #17
0
/**
 * @return whether setting the video mode was successful
 *
 * Sets SDL video mode options/settings
 */
bool SpringApp::SetSDLVideoMode ()
{
    int sdlflags = SDL_OPENGL | SDL_RESIZABLE;

    conditionally_set_flag(sdlflags, SDL_FULLSCREEN, fullscreen);

    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
#ifdef __APPLE__
    const int defaultDepthSize = 32;
#else
    const int defaultDepthSize = 16;
#endif
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, configHandler.GetInt("DepthBufferBits", defaultDepthSize));
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    FSAA = MultisampleTest();

    SDL_Surface *screen = SDL_SetVideoMode(screenWidth,screenHeight,0,sdlflags);
    if (!screen) {
        handleerror(NULL,"Could not set video mode","ERROR",MBF_OK|MBF_EXCL);
        return false;
    }
    if (FSAA)
        FSAA = MultisampleVerify();

    return true;
}
Example #18
0
/** Create a CglList for selecting the map. */
void CPreGame::ShowMapList()
{
	CglList* list = SAFE_NEW CglList("Select map", SelectMap, 2);
	std::vector<std::string> found = filesystem.FindFiles("maps/","{*.sm3,*.smf}");
	std::vector<std::string> arFound = archiveScanner->GetMaps();
	if (found.begin() == found.end() && arFound.begin() == arFound.end()) {
		handleerror(0, "Couldn't find any map files", "PreGame error", 0);
		return;
	}

	std::set<std::string> mapSet; // use a set to sort them
	for (std::vector<std::string>::iterator it = found.begin(); it != found.end(); it++) {
		std::string fn(filesystem.GetFilename(*it));
		mapSet.insert(fn.c_str());
	}
	for (std::vector<std::string>::iterator it = arFound.begin(); it != arFound.end(); it++) {
		mapSet.insert((*it).c_str());
	}

	list->AddItem("Random map", "Random map"); // always first
	for (std::set<std::string>::iterator sit = mapSet.begin(); sit != mapSet.end(); ++sit) {
		list->AddItem(sit->c_str(), sit->c_str());
	}
	showList = list;
}
ALuint COpenALSound::LoadALBuffer(const string& path)
{
	if (noSound)
		return 0;
	Uint8 *buf;
	ALuint buffer;
	alGenBuffers(1,&buffer);
	if (!CheckError("error generating OpenAL sound buffer"))
		return 0;
	CFileHandler file("Sounds/"+path);
	if(file.FileExists()){
		buf = new Uint8[file.FileSize()];
		file.Read(buf, file.FileSize());
	} else {
		handleerror(0, "Couldnt open wav file",path.c_str(),0);
		alDeleteBuffers(1, &buffer);
		return 0;
	}
	bool success=ReadWAV (path.c_str(), buf, file.FileSize(), buffer);
	delete[] buf;

	if (!success) {
		alDeleteBuffers(1, &buffer);
		return 0;
	}
	return buffer;
}
Example #20
0
//自猜
int baiduapi_mkdir(const char *path, mode_t mode)
{
    (void) mode;
    char buff[2048];
    char fullpath[PATHLEN];
    snprintf(fullpath, sizeof(fullpath) - 1, "%s%s", basepath, path);
    snprintf(buff, sizeof(buff) - 1,
             "https://pcs.baidu.com/rest/2.0/pcs/file?"
             "method=mkdir&"
             "access_token=%s&"
             "path=%s"
             , Access_Token, URLEncode(fullpath));
    FILE *tpfile = tmpfile();

    if (!tpfile) {
        int lasterrno = errno;
        errorlog("create temp file error:%s\n", strerror(errno));
        return -lasterrno;
    }

    Http *r = Httpinit(buff);

    if (r == NULL) {
        int lasterrno = errno;
        errorlog("can't resolve domain:%s\n", strerror(errno));
        fclose(tpfile);
        return -lasterrno;
    }

    r->method = get;
    r->writefunc = savetofile;
    r->writeprame = tpfile;

    if ((errno = request(r)) != CURLE_OK) {
        errorlog("network error:%d\n", errno);
        fclose(tpfile);
        Httpdestroy(r);
        return -EPROTO;
    }

    Httpdestroy(r);
    json_object *json_get = json_object_from_FILE(tpfile);
    fclose(tpfile);

    if (json_get == NULL) {
        errorlog("json_object_from_FILE filed!\n");
        return -EPROTO;
    }

    json_object *jerror_code;
    if (json_object_object_get_ex(json_get, "error_code",&jerror_code)) {
        int errorno = json_object_get_int(jerror_code) ;
        json_object_put(json_get);
        return handleerror(errorno);
    }

    json_object_put(json_get);
    return 0;
}
// see if the AI hasn't modified any parts of this callback
// (still completely insecure ofcourse, but it filters out the easiest way of cheating)
void CAICallback::verify()
{
	CGlobalAI *gai = globalAI->ais [team];
	if (gai && (((group && gai->gh != group->handler) || gai->team != team))) {
		handleerror (0, "AI has modified spring components(possible cheat)", "Spring is closing:", MBF_OK | MBF_EXCL);
		exit (-1);
	}
}
Example #22
0
bool CDxSound::ReadWAV (const char *name, Uint8 *buf, int fileSize, Uint8 **soundData, Uint32* bufferSize, WAVEFORMATEX& wf)
{
	WAVHeader *header = (WAVHeader *)buf;

	if (memcmp (header->riff, "RIFF",4) || memcmp (header->wavefmt, "WAVEfmt", 7)) {
		if (hardFail) {
			handleerror(0, "ReadWAV: invalid header.", name, 0);
		}
		return false;
	}

#define hswabword(c) header->c = swabword(header->c)
#define hswabdword(c) header->c = swabdword(header->c)
	hswabword(format_tag);
	hswabword(channels);
	hswabword(BlockAlign);
	hswabword(BitsPerSample);

	hswabdword(totalLength);
	hswabdword(length);
	hswabdword(SamplesPerSec);
	hswabdword(AvgBytesPerSec);
	hswabdword(datalen);
#undef hswabword
#undef hswabdword

	if (header->format_tag != 1) { // Microsoft PCM format?
		if (hardFail) {
			handleerror(0,"ReadWAV: invalid format tag.", name, 0);
		}
		return false;
	}

	wf.cbSize = 0;
	wf.wFormatTag = WAVE_FORMAT_PCM;
	wf.nChannels = header->channels;
	wf.nSamplesPerSec = header->SamplesPerSec;
	wf.wBitsPerSample = header->BitsPerSample;
	wf.nBlockAlign = header->channels * header->BitsPerSample / 8;
	wf.nAvgBytesPerSec = header->SamplesPerSec * wf.nBlockAlign;
	
	*bufferSize = header->datalen > fileSize-sizeof(WAVHeader) ? fileSize-sizeof(WAVHeader) : header->datalen;
	*soundData = buf + sizeof(WAVHeader);

	return true;
}
Example #23
0
CNet::CNet()
{
    Uint64 t;
    t = SDL_GetTicks();
    curTime=float(t)/1000.f;
    Uint16 wVersionRequested;
#ifdef _WIN32
    WSADATA wsaData;
    int err;

    wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 ) {
        handleerror(NULL,"Couldnt initialize winsock.","SHUTDOWN ERROR",MBF_OK | MBF_INFO);
        return;
    }
    /* Confirm that the WinSock DLL supports 2.2.*/
    /* Note that if the DLL supports versions greater    */
    /* than 2.2 in addition to 2.2, it will still return */
    /* 2.2 in wVersion since that is the version we      */
    /* requested.                                        */
    if ( LOBYTE( wsaData.wVersion ) != 2 ||
            HIBYTE( wsaData.wVersion ) != 2 ) {
        handleerror(NULL,"Wrong WSA version.","SHUTDOWN ERROR",MBF_OK | MBF_INFO);
        WSACleanup( );
        return;
    }
#endif
    connected=false;

    for(int a=0; a<gs->activePlayers; a++) {
        connections[a].active=false;
        connections[a].localConnection=0;
    }

    imServer=false;
    onlyLocal=false;
    inInitialConnect=false;

    recordDemo=0;
    playbackDemo=0;
    mySocket=0;
}
Example #24
0
/**
 * @brief Initializes the SpringApp instance
 * @return whether initialization was successful
 */
bool SpringApp::Initialize ()
{
    if (!ParseCmdLine ())
        return false;

#ifdef WIN32
    // Initialize crash reporting
    Install( (LPGETLOGFILE) crashCallback, "*****@*****.**", "TA Spring Crashreport");
#endif

    // Initialize class system
    creg::ClassBinder::InitializeClasses ();

#ifndef NO_LUA
    // Initialize lua bindings
    CLuaBinder lua;
    if (!lua.LoadScript("testscript.lua"))
        handleerror(NULL, lua.lastError.c_str(), "lua",MBF_OK|MBF_EXCL);
#endif

    InitVFS ();

    if (!InitWindow ("RtsSpring"))
    {
        SDL_Quit ();
        return false;
    }
    // Global structures
    ENTER_SYNCED;
    gs=new CGlobalSyncedStuff();
    ENTER_UNSYNCED;
    gu=new CGlobalUnsyncedStuff();

    InitOpenGL();

    palette.Init();

    // Initialize keyboard
    SDL_EnableUNICODE(1);
    SDL_EnableKeyRepeat (SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    SDL_SetModState (KMOD_NONE);

    keys = new Uint8[SDLK_LAST];
    memset (keys,0,sizeof(Uint8)*SDLK_LAST);

    // Initialize font
    font = new CglFont(32,223);
    LoadExtensions();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    SDL_GL_SwapBuffers();

    CreateGameSetup ();

    return true;
}
Example #25
0
	void AssertMixedMode(char* file,int line)
	{
		if(codeType!=CodeType_Mixed){
			char text[500];
			sprintf(text,"Code not in mixed mode in %s line %i",file,line);
			handleerror(0,text,"Assertion failure",0);

			int* a=0;
			*a=0;			//make sure we crash for easy access to call stack etc
		}
	}
void CGroupHandler::TestDll(string name)
{
	typedef int (* GETGROUPAIVERSION)();
	typedef void (* GETAINAME)(char* c);
	
	SharedLib *lib;
	GETGROUPAIVERSION GetGroupAiVersion;
	GETAINAME GetAiName;

	lib = SharedLib::instantiate(name);
	if (!lib){
		handleerror(NULL,name.c_str(),"Cant load dll",MBF_OK|MBF_EXCL);
		return;
	}

	GetGroupAiVersion = (GETGROUPAIVERSION)lib->FindAddress("GetGroupAiVersion");
	if (!GetGroupAiVersion){
		handleerror(NULL,name.c_str(),"Incorrect AI dll",MBF_OK|MBF_EXCL);
		return;
	}

	int i=GetGroupAiVersion();

	if (i!=AI_INTERFACE_VERSION){
		handleerror(NULL,name.c_str(),"Incorrect AI dll version",MBF_OK|MBF_EXCL);
		return;
	}
	
	GetAiName = (GETAINAME)lib->FindAddress("GetAiName");
	if (!GetAiName){
		handleerror(NULL,name.c_str(),"Incorrect AI dll",MBF_OK|MBF_EXCL);
		return;
	}

	char c[500];
	GetAiName(c);

	availableAI[name]=c;
//	(*info) << name.c_str() << " " << c << "\n";
	delete lib;
}
void CScriptHandler::StartLua()
{
#ifndef NO_LUA
	std::vector<string> files = CFileHandler::FindFiles("startscripts/", "*.lua");
	for (std::vector<string>::iterator i = files.begin(); i != files.end(); ++i) {
		CLuaBinder* lua = new CLuaBinder();
		if (!lua->LoadScript(*i)) 
			handleerror(NULL, lua->lastError.c_str(), "Lua", MBF_OK|MBF_EXCL);
		lua_binders.push_back(lua);
	}
#endif
}
Example #28
0
/**
 * @return whether window initialization succeeded
 * @param title char* string with window title
 * 
 * Initializes the game window
 */
bool SpringApp::InitWindow (const char* title)
{
	if ((SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1)) {
		handleerror(NULL,"Could not initialize SDL.","ERROR",MBF_OK|MBF_EXCL);
		return false;
	}

	// Sets window manager properties
	SDL_WM_SetIcon(SDL_LoadBMP("spring.bmp"),NULL);
	SDL_WM_SetCaption(title, title);

	return SetSDLVideoMode ();
}
void CScriptHandler::LoadScriptFile(const std::string& file)
{
	char buffer[16000];
	const int returned = vfsHandler->LoadFile(std::string("startscripts/"+file), buffer);
	if (returned > 0)
	{
		CLuaBinder* lua = SAFE_NEW CLuaBinder();
		if (!lua->LoadScript(file, buffer, returned))
			handleerror(NULL, lua->lastError.c_str(), "Lua", MBF_OK|MBF_EXCL);
		lua_binders.push_back(lua);
	}
	else
		throw std::runtime_error("scriptfile not found: " + file);
}
void CScriptHandler::StartLua()
{
#ifndef NO_LUA
	std::vector<std::string> files = vfsHandler->GetFilesInDir("startscripts");
	for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); ++i) {
		char buffer[16000];
		const int returned = vfsHandler->LoadFile(std::string("startscripts/"+*i), buffer);
		CLuaBinder* lua = SAFE_NEW CLuaBinder();
		if (!lua->LoadScript(*i, buffer, returned))
			handleerror(NULL, lua->lastError.c_str(), "Lua", MBF_OK|MBF_EXCL);
		lua_binders.push_back(lua);
	}
#endif
}