Пример #1
0
//Segment one full file name into directory part and file name part.
//pDir and pFileName must be long enough to contain the result.
//If the full name's level is zero,that no subdirectory in the full name,
//the pDir[0] will contain the file system identifier to indicate this.
//If the full name only contain a directory,i.e,the last character of
//the full name is a slash character,then the pFileName[0] will be set to 0.
BOOL wGetPathName(WCHAR* pFullName,WCHAR* pDir,WCHAR* pFileName)
{
         WCHAR       DirName[MAX_FILE_NAME_LEN];
         WCHAR       FileName[13];
         WCHAR       tmp;
         int         i = 0;
         int         j = 0;
 
         if((NULL == pFullName) || (NULL == pDir) || (NULL == pFileName))  //Invalid parameters.
         {
                   return FALSE;
         }
         if(!wNameIsValid(pFullName))  //Not a valid file name.
         {
                   return FALSE;
         }
         //strcpy((CHAR*)&DirName[0],(CHAR*)pFullName);
         wstrcpy(DirName,pFullName);
         i = wstrlen(pFullName);
         i -= 1;
         if(pFullName[i] == '\\') //The last character is a splitter,means only dir name present.
         {
                   //DirName[i] = 0;      //Eliminate the slash.
                   //strcpy((CHAR*)pDir,(CHAR*)&DirName[0]);
                   wstrcpy(pDir,&DirName[0]);
                   pFileName[0] = 0;
                   return TRUE;
         }
         j = 0;
         while(pFullName[i] != '\\')  //Get the file name part.
         {
                   FileName[j ++] = pFullName[i --];
         }
         DirName[i + 1]  = 0;  //Keep the slash.
         FileName[j] = 0;
         //Now reverse the file name string.
         for(i = 0;i < (j / 2);i ++)
         {
                   tmp = FileName[i];
                   FileName[i] = FileName[j - i - 1];
                   FileName[j - i - 1] = tmp;
         }
         //strcpy((CHAR*)pDir,(CHAR*)&DirName[0]);
         wstrcpy(pDir,&DirName[0]);
         //strcpy((CHAR*)pFileName,(CHAR*)&FileName[0]);
         wstrcpy(pFileName,&FileName[0]);
         return TRUE;
}
Пример #2
0
	EngineObjectReg::EngineObjectReg(const wchar* objName, CreateObjFn fn)
		: CreateFn(fn), InstNum(0)
	{
		assert(objName && objName[0] && objName[1] );

		unsigned int nameLen = wstrlen(objName);

		ObjName = new wchar[nameLen+1];
		if (objName[0] == _W('C') && isupper(objName[1]) )
			wstrcpy(ObjName, &objName[1]); // remove beginning C from names like CTexture
		else
			wstrcpy(ObjName, objName);

		Next = g_first_obj;
		g_first_obj = this;
	};
Пример #3
0
bool CClassManager::LoadNewLibrary(const wchar* szLibraryName)
{
	if (!szLibraryName || !*szLibraryName) return false;

	wchar BinPath[MAX_PATH];

	bool bAbsolutePath = false;
	for(unsigned int i = wstrlen(szLibraryName); i>0; i--)
	{
		if (szLibraryName[i]=='\\' || szLibraryName[i]=='/')
		{
			bAbsolutePath = true;
			break;
		}
	}

	if (bAbsolutePath)
	{
		// check extension and copy
		if (wstrlen(szLibraryName)<5 || szLibraryName[wstrlen(szLibraryName)-5]!='.')
#if defined(WIN32)		
			wsprintf(BinPath, 259, _W("%s.wp3d"), szLibraryName);
#elif defined (LINUX)
			wsprintf(BinPath, 259, _W("%s.lp3d"), szLibraryName);
#endif
		else
			wstrcpy(BinPath, szLibraryName); // copy abspath with extension
	}
Пример #4
0
//------------------------------------------
FSFILE* CFS_Sqlite::Open(const wchar* szPath, const wchar* szMode){
	wchar szPhPath[MAX_PATH];

	// construct physical path
	wstrcpy(szPhPath, I_GetBinaryPath());
	wstrcat(szPhPath, _W("../data/"));
	wstrcat(szPhPath, szPath);

	//FILE* fp = wfopen(szPhPath, szMode);
	// TODO: implement!
	// don't forget to create if write mode and doesn't exist
	// on error / not found return NULL
	return NULL; // until implemented
	
	FSFILE* ret = new FSFILE;
	ret->bArchive = false;
	ret->nOffset = ret->nRelOffset = 0;

	//fseek(fp, 0, SEEK_END);
	ret->nLen =  0; // TODO: implement!
	//fseek(fp, 0, SEEK_SET);

	//ret->pFileData = fp;

	return ret;
}
Пример #5
0
//------------------------------------------
FSFILE* CFS_Stdio::Open(const wchar* szPath, const wchar* szMode){
	wchar szPhPath[MAX_PATH];

	// construct physical path
	wstrcpy(szPhPath, I_GetBinaryPath());
	wstrcat(szPhPath, _W("../data/"));
	wstrcat(szPhPath, szPath);

	FILE* fp = wfopen(szPhPath, szMode);
	if (!fp) 
	{
		// if we are opening for write mode, make sure path to file is created
		if (szMode[0]=='w')
		{
			wchar szdir[MAX_PATH];
			wstrcpy(szdir, szPhPath);
			for (unsigned int i=0;i<wstrlen(szdir);i++)
				if (szdir[i]=='/'||szdir[i]=='\\') { 
					szdir[i]=0;
#ifdef WIN32
				CreateDirectory(szdir, NULL) ? 0 : 1;
#else
				mkdir(szdir,777);
#endif
				szdir[i]=szPhPath[i];
			}
			fp = wfopen(szPhPath, szMode); // try to open again
			if (!fp) return NULL;
		}
		else
			return NULL;
	}

	FSFILE* ret = new FSFILE;
	ret->bArchive = false;
	ret->nOffset = ret->nRelOffset = 0;

	fseek(fp, 0, SEEK_END);
	ret->nLen =  ftell(fp);
	fseek(fp, 0, SEEK_SET);

	ret->pFileData = fp;

	return ret;
}
Пример #6
0
static void		printf_c(wchar_t chr, char **str)
{
	if (chr <= 0x7F)
		**str = chr;
	else if (chr <= 0x7FF)
	{
		**str = (chr >> 6) + 0xC0;
		**str = wstrcpy((chr & 0x3F) + 0x80, str);
	}
Пример #7
0
	//------------------------------------------
	const wchar* CEngine::GetBuildString()
	{
		static wchar bs[256];
		wchar platform[16];
#if defined(_WIN32)
# if defined(_WIN64)
		wstrcpy(platform, _W("Win64") );
# else
		wstrcpy(platform, _W("Win32") );
# endif
#elif LINUX
		wstrcpy(platform, _W("Linux") );
#elif __MACOSX__
		wstrcpy(platform, _W("Mac") );
#else
		wstrcpy(platform, _W("Other platform") );
#endif

		wsprintf( bs, 255, _W("%s (build %d, %s) <%s>"), _W(P3DNAME), GetBuildNum(), _W(__DATE__), platform );
		return bs;
	}
Пример #8
0
//Get the desired level subdirectory from a full name.
//pSubDir will contain the sub-directory name if successfully,so it must long
//enough to contain the result.
BOOL wGetSubDirectory(WCHAR* pFullName,DWORD dwLevel,WCHAR* pSubDir)
{
         BOOL       bResult         = FALSE;
         DWORD      dwTotalLevel    = 0;
         DWORD      i = 0;
         DWORD      j = 0;
         WCHAR      buffer[256];  //Contain sub-directory name temporary.
 
         if((NULL == pFullName) || (NULL == pSubDir) || (0 == dwLevel))  //Level shoud not be zero.
         {
                   return FALSE;
         }
         if(!wGetFullNameLevel(pFullName,&dwTotalLevel))
         {
                   return FALSE;
         }
         if(dwLevel > dwTotalLevel)  //Exceed the total level.
         {
                   return FALSE;
         }
         dwTotalLevel = 0;
         while(pFullName[i])
         {
                   if(pFullName[i] == '\\')  //Splitter encountered.
                   {
                            j = 0;
                            i ++;  //Skip the slash.
                            while((pFullName[i] != '\\') && (pFullName[i]))
                            {
                                     buffer[j] = pFullName[i];
                                     i ++;
                                     j ++;
                            }
                            buffer[j] = 0;               //Set the terminator.
                            dwTotalLevel += 1;
                            if(dwLevel == dwTotalLevel)  //Subdirectory found.
                            {
                                     bResult = TRUE;
                                     break;
                            }
                            i --;  //If the slash is skiped,the next sub-directory maybe eliminated.
                   }
                   i ++;
         }
         if(bResult)
         {
                   //strcpy((CHAR*)pSubDir,(CHAR*)&buffer[0]);
                   wstrcpy(pSubDir,&buffer[0]);
         }
         return bResult;
}
Пример #9
0
//------------------------------------------
bool CFS_Stdio::Exists(const wchar* file){
	assert(file!=NULL && file[0]!=0);

	wchar szPhPath[MAX_PATH];

	// construct physical path
	wstrcpy(szPhPath, file);

	struct _stat mystat;
	if (!wstat(szPhPath,&mystat))
		return true;
	else
		return false;
}
Пример #10
0
//------------------------------------------
tArray<sFSSearchResult> CFS_Sqlite::GetContentOfCategory(const wchar *path)
{
	// TODO: implement!
	tArray<sFSSearchResult> ret;

	// construct physical path
	wchar szPhPath[MAX_PATH];
	wsprintf(szPhPath, MAX_PATH-1, _W("%s../data/%s/*"), I_GetBinaryPath(), path );

#ifdef _WIN32

	WIN32_FIND_DATA wfd;
	ZeroMemory(&wfd, sizeof(wfd));
	HANDLE hFind = FindFirstFile(szPhPath, &wfd);
	if ( hFind == INVALID_HANDLE_VALUE )
		return ret;

	do 
	{
		if (!*wfd.cFileName || wfd.cFileName[0]==_W('.')) continue;

		sFSSearchResult sr;

		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			sr.Type = FSI_DIR;
		else
			sr.Type = FSI_FILE;

		assert( wstrlen(wfd.cFileName)<64 );
		wstrcpy(sr.Name, wfd.cFileName);

		ret.AddEx(sr);
	} while ( FindNextFile(hFind, &wfd) );

	FindClose(hFind);

#else
	// TODO:!!
#error todo
#endif
	return ret;
}
Пример #11
0
BOOL cursor_window_get_string_16(CursorWindow* thiz,INT32 row,INT32 col, WCHAR** value)
{
    CursorWindowFieldSlot* field = NULL;
    CursorWindowRowChunk* chunk=NULL;
    INT32 row_in_chunk=0;
    return_val_if_fail(thiz , FALSE);
    return_val_if_fail(_cursor_window_locate_field(thiz,row,col,&row_in_chunk,&chunk,&field),FALSE);
    return_val_if_fail(field->type==FIELD_TYPE_STRING_16||field->type==FIELD_TYPE_NULL,FALSE);
    if (field->data.buffer.size==0 ||  field->data.buffer.buf==NULL)
    {
        *value = NULL;
        return TRUE;
    }

    *value = TG_CALLOC_V2(field->data.buffer.size);
    return_val_if_fail(*value , FALSE);
    wstrcpy(*value,(const WCHAR*)field->data.buffer.buf);

    return TRUE;

}
Пример #12
0
IMAGELIB_ERROR_CODE imagelib_start_decode_by_file(const WCHAR* _pathname,IMAGELIB_SESSION** _session)
{
	IMAGE_INSTANCE *instance = NULL;
	IMAGELIB_SESSION*  session =NULL;
	IMAGELIB_ERROR_CODE error_code;
	char utf_pathname[UTA_MAX_PATHNAME_LEN*2+1];
	if(_pathname == NULL)
		return IMAGELIB_RAM_EXECPTION;
	UnicodeToUtf8(utf_pathname,_pathname);
	error_code =image_open_by_filename(utf_pathname, "rb",NULL,&instance);
	if(error_code != IMAGELIB_SUCCESS)
	{
		*_session = NULL;
		return error_code;
	}
	session = IMAGE_MALLOC(sizeof(IMAGELIB_SESSION));
	if(session == NULL)
	{
		*_session = NULL;
		return IMAGELIB_RAM_EXECPTION;
	}
	session->error_code = error_code;
	session->pathname = IMAGE_MALLOC((wstrlen(_pathname)+1)*2);
	if(session->pathname== NULL)
	{
		*_session = NULL;
		IMAGE_FREE(session);
		return IMAGELIB_RAM_EXECPTION;
	}
	session->decode_sem = NULL;
	wstrcpy(session->pathname,_pathname);
	session->instance_p = (IMAGELIB_INSTANCE_P)instance;
	session->state= IMAGELIB_OPENED;
	*_session=session;
	session->decode_sem = create_sem(1);
	return IMAGELIB_SUCCESS;
}
Пример #13
0
int main(int argc, char** argv)
{
  int result = 0;
  RapiConnection* connection = NULL;
  HRESULT hr;
  char *shortcut, *target;
  WCHAR* wide_shortcut = NULL;
  WCHAR* wide_target = NULL;
  WCHAR *tmp, *tmp_quote;
  int tmpsize;

  if (!handle_parameters(argc, argv, &shortcut, &target))
    goto exit;

  if ((connection = rapi_connection_from_path(devpath)) == NULL)
  {
    fprintf(stderr, "%s: Could not find configuration at path '%s'\n", 
            argv[0],
            devpath?devpath:"(Default)");
    goto exit;
  }
  rapi_connection_select(connection);
  hr = CeRapiInit();

  if (FAILED(hr))
  {
    fprintf(stderr, "%s: Unable to initialize RAPI: %s\n", 
            argv[0],
        synce_strerror(hr));
    result = 1;
    goto exit;
  }


  convert_to_backward_slashes(shortcut);
  wide_shortcut = wstr_from_current(shortcut);
  wide_shortcut = adjust_remote_path(wide_shortcut, true);

  convert_to_backward_slashes(target);
  wide_target = wstr_from_current(target);
  wide_target = adjust_remote_path(wide_target, true);
  /* Wrap target in quotes.  This is required for paths with spaces (for some reason) */
  tmp_quote = wstr_from_current("\"");
  tmpsize = (wstrlen(wide_target) + 3) * sizeof(WCHAR);
  tmp = malloc(tmpsize);
  if (!tmp)
    goto exit;
  wstrcpy(tmp,tmp_quote);
  if (!wstr_append(tmp,wide_target,tmpsize))
    goto exit;
  if (!wstr_append(tmp,tmp_quote,tmpsize))
    goto exit;
  wstr_free_string(wide_target);
  wstr_free_string(tmp_quote);
  wide_target = tmp;
  
  BOOL res = CeSHCreateShortcut(wide_shortcut, wide_target);
  if (!res)
  {
    fprintf(stderr, "%s: Unable to create shortcut to '%s' at '%s': %s\n",
            argv[0],target,shortcut,
        synce_strerror(hr));
    result = 1;
    goto exit;
  }

 exit:
  wstr_free_string(wide_shortcut);
  wstr_free_string(wide_target);
  
  if (shortcut)
    free(shortcut);
  
  if (target)
    free(target);

  CeRapiUninit();
  rapi_connection_destroy(connection);
  
  return result;
}
Пример #14
0
int maincsm_onmessage(CSM_RAM* data, GBS_MSG* msg)
{
	if (msg->msg == MSG_IPC)
	{
		IPC_REQ *ipc = (IPC_REQ*)msg->data0;
		if (ipc)
		{
			if (strcmp(ipc->name_to, IPC_MY_NAME) == 0)
			{
				if (msg->submess != data->id)
				{
					LockSched();
					CloseCSM(msg->submess);
					SUBPROC((void*)CreateClipperGUI);
					UnlockSched();
				}
			}
		}
	}
	if (msg->msg == MSG_RECONFIGURE_REQ)
	{
		if (strcmp_nocase(successed_config_filename, (char *)msg->data0) == 0)
			InitConfig();
	}
	if (total < cfg_max_history)
	{
		static WSHDR *clip;
		if (not_reading)
		{
			clip = GetClipBoard();
			not_reading = 0;
		}
		else
		{
			if (clip != GetClipBoard())
			{
				clip = GetClipBoard();
				if (total)
				{
					CLIPBOARD_LIST *p = top;
					while (1)
					{
						if (p->next) p = p->next;
						else break;
					}
					p->next = malloc(sizeof(CLIPBOARD_LIST));
					p = p->next;
					last->next = p;
					
					p->prev = last;
					p->next = NULL;
					
					p->ws = AllocWS(clip->wsbody[0] + 1);
					wstrcpy(p->ws, clip);
					last = p;
					
				}
				else
				{
					top = malloc(sizeof(CLIPBOARD_LIST));
					top->prev = NULL;
					top->next = NULL;
					last = top;
					top->ws = AllocWS(clip->wsbody[0] + 1);
					wstrcpy(top->ws, clip);
				}
				total++;
			}
		}
	}
	return 1;
}
Пример #15
0
CClassManager::CClassManager()
{
	wstrcpy(m_szBinPath, _W("./"));
	m_nLastInitID=0;
}
Пример #16
0
void
GenerateSOL (BYTE control)
{
	COUNT i;
	DWORD rand_val;
	PPLANET_DESC pCurDesc;

	switch (control)
	{
		case INIT_NPCS:
			init_probe ();
			break;
		case REINIT_NPCS:
			if (GET_GAME_STATE (CHMMR_BOMB_STATE) != 3)
				GenerateRandomIP (REINIT_NPCS);
			else
			{
				GLOBAL (BattleGroupRef) = 0;
				ReinitQueue (&GLOBAL (npc_built_ship_q));
			}
			break;
		case GENERATE_ENERGY:
			generate_energy_nodes ();
			break;
		case GENERATE_LIFE:
			generate_tractors ();
			break;
		case GENERATE_ORBITAL:
			generate_orbital ();
			break;
		case GENERATE_NAME:
			i = pSolarSysState->pBaseDesc - pSolarSysState->PlanetDesc;
			wstrcpy (GLOBAL_SIS (PlanetName), GAME_STRING (PLANET_NUMBER_BASE + i));
			SET_GAME_STATE (BATTLE_PLANET,
					pSolarSysState->PlanetDesc[i].data_index);
			break;
		case GENERATE_MOONS:
		{
			GenerateRandomIP (GENERATE_MOONS);

			i = pSolarSysState->pBaseDesc - pSolarSysState->PlanetDesc;
			switch (i)
			{
				case 2: /* moons of EARTH */
				{
					COUNT angle;

					pSolarSysState->MoonDesc[0].data_index = (BYTE)~0;
					pSolarSysState->MoonDesc[0].radius = MIN_MOON_RADIUS;
					angle = HALF_CIRCLE + QUADRANT;
					pSolarSysState->MoonDesc[0].location.x =
							COSINE (angle, pSolarSysState->MoonDesc[0].radius);
					pSolarSysState->MoonDesc[0].location.y =
							SINE (angle, pSolarSysState->MoonDesc[0].radius);

					pSolarSysState->MoonDesc[1].data_index = SELENIC_WORLD;
					pSolarSysState->MoonDesc[1].radius = MIN_MOON_RADIUS
							+ (MAX_MOONS - 1) * MOON_DELTA;
					rand_val = Random ();
					angle = NORMALIZE_ANGLE (LOWORD (rand_val));
					pSolarSysState->MoonDesc[1].location.x =
							COSINE (angle, pSolarSysState->MoonDesc[1].radius);
					pSolarSysState->MoonDesc[1].location.y =
							SINE (angle, pSolarSysState->MoonDesc[1].radius);
					break;
				}
				case 4: /* moons of JUPITER */
					pSolarSysState->MoonDesc[0].data_index = RADIOACTIVE_WORLD;
					pSolarSysState->MoonDesc[1].data_index = HALIDE_WORLD;
					pSolarSysState->MoonDesc[2].data_index = CYANIC_WORLD;
					pSolarSysState->MoonDesc[3].data_index = PELLUCID_WORLD;
					break;
				case 5: /* moons of SATURN */
					pSolarSysState->MoonDesc[0].data_index = ALKALI_WORLD;
					break;
				case 7: /* moons of NEPTUNE */
					pSolarSysState->MoonDesc[0].data_index = VINYLOGOUS_WORLD;
					break;
			}
			break;
		}
		case GENERATE_PLANETS:
		{
#define SOL_SEED 334241042L
			SeedRandom (SOL_SEED);

			pSolarSysState->SunDesc[0].NumPlanets = 9;
			for (i = 0, pCurDesc = pSolarSysState->PlanetDesc; i < 9; ++i, ++pCurDesc)
			{
				COUNT angle;
				UWORD word_val;

				pCurDesc->rand_seed = rand_val = Random ();
				word_val = LOWORD (rand_val);
				angle = NORMALIZE_ANGLE ((COUNT)HIBYTE (word_val));

				switch (i)
				{
					case 0: /* MERCURY */
						pCurDesc->data_index = METAL_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 39L / 100;
						pCurDesc->NumPlanets = 0;
						break;
					case 1: /* VENUS */
						pCurDesc->data_index = PRIMORDIAL_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 72L / 100;
						pCurDesc->NumPlanets = 0;
						angle = NORMALIZE_ANGLE (FULL_CIRCLE - angle);
						break;
					case 2: /* EARTH */
						pCurDesc->data_index = WATER_WORLD | PLANET_SHIELDED;
						pCurDesc->radius = EARTH_RADIUS;
						pCurDesc->NumPlanets = 2;
						break;
					case 3: /* MARS */
						pCurDesc->data_index = DUST_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 152L / 100;
						pCurDesc->NumPlanets = 0;
						break;
					case 4: /* JUPITER */
						pCurDesc->data_index = RED_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 500L /* 520L */ / 100;
						pCurDesc->NumPlanets = 4;
						break;
					case 5: /* SATURN */
						pCurDesc->data_index = ORA_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 750L /* 952L */ / 100;
						pCurDesc->NumPlanets = 1;
						break;
					case 6: /* URANUS */
						pCurDesc->data_index = GRN_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 1000L /* 1916L */ / 100;
						pCurDesc->NumPlanets = 0;
						break;
					case 7: /* NEPTUNE */
						pCurDesc->data_index = BLU_GAS_GIANT;
						pCurDesc->radius = EARTH_RADIUS * 1250L /* 2999L */ / 100;
						pCurDesc->NumPlanets = 1;
						break;
					case 8: /* PLUTO */
						pCurDesc->data_index = PELLUCID_WORLD;
						pCurDesc->radius = EARTH_RADIUS * 1550L /* 3937L */ / 100;
						pCurDesc->NumPlanets = 0;
						angle = FULL_CIRCLE - OCTANT;
						break;
				}

				pCurDesc->location.x =
						COSINE (angle, pCurDesc->radius);
				pCurDesc->location.y =
						SINE (angle, pCurDesc->radius);
			}
			break;
		}
		default:
			GenerateRandomIP (control);
			break;
	}
}
Пример #17
0
	//------------------------------------------
	bool CEngine::Initialize(const wchar* settings/*="game.ini"*/, bool customWindow/*=false*/, sDisplayProperties *dp/*=NULL*/){
		assertd(s_bInit==false, "DOUBLE ENGINE INITIALIZATION!");

		s_bInit = true; //predict :-P

		// initialize random generator
		srand( (unsigned int)milisec() );

		cInternalWindow()->BeginSplash();

		// memory leaks detection
#if defined(_DEBUG) && defined(_MSC_VER) && _MSC_VER >= 800
		_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
		//_CrtSetBreakAlloc(23296);
#endif

		// ---------------------------------------------------
		// QUEUE TESTS
		CON(MSG_INFO, _W("------- Command Queue Test -------"));
		CCommandQueue q;
		DWORD tim;
		for (int t=0; t<10; t++)
		{
			tim = GetTickCount();
			// FILL IN QUEUE
			for (int i=0; i<20000; i++)
			{
					sE2RCanvasDesc *cd;
					q.Enqueue(NULL, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)cd, sizeof(sE2RCanvasDesc));
					cd->handle = 0;
			}
			CON(MSG_INFO, _W("Iteration #%d: Enqueue %d ms"), t, GetTickCount()-tim );

			// DEQUEUE
			unsigned int cqi; const void* optr; IQueueCommandReceiver *recv;
			tim = GetTickCount();
			while (q.Dequeue(cqi, optr, recv))
			{
				switch(cqi)
				{
				case CQI_ENGINE2RENDERER_CANVAS_CREATE:
					{
						sE2RCanvasDesc *cd = (sE2RCanvasDesc *)optr;
					}
					break;
				}
			}
			CON(MSG_INFO, _W("Iteration #%d: Dequeue %d ms"), t, GetTickCount()-tim );
		}
		CON(MSG_INFO, _W("----------------------------------"));
		// ---------------------------------------------------


		// --- WRITE INFO ABOUT LIBRARIES AND MODULES
		I_DebugPrint( ConsoleMsg );

		CON(MSG_INFO, _W("= %s %s build %d initialization ="), _W(P3DNAME), sizeof(void*)==8?_W("x64"):_W("x86"), GetBuildNum());
		if (sizeof(wchar)>1) 
			CON(MSG_INFO, _W("Unicode support \x263A"));
		else
			CON(MSG_INFO, _W("Multibyte character set"));

		// --- LOAD SETTINGS
		m_szSettings = new wchar[wstrlen(settings)+1];
		wstrcpy(m_szSettings, settings);

		cConfig()->Load(m_szSettings);
		//cConfig()->Save(m_szSettings);

		// --- INITIALIZE SCRIPT SYSTEM
		CON(MSG_INFO, _W("Script system initialization"));
		cScriptEngine()->Initialize();

		// --- LOAD KEY BINDINGS
		cInputManager()->Assign(_W("GUI_CURSOR"), WE_MOUSE_MOTION, 0);
		cInputManager()->Assign(_W("GUI_SELECT"), WE_MOUSE_DOWN, 0);

		cInputManager()->Save(_W("keys.ini")); // TODO: FIXME: What about load? :D

		// --- CREATE MAIN WINDOW
		Vec2i mainWindowSize(800,600);
		bool initFullscreen = false;
		if (customWindow)
		{
			// use primary screen resolution for frame buffer
			// TODO: multiplatform
#ifdef _WIN32
			mainWindowSize.x = GetSystemMetrics(SM_CXSCREEN);
			mainWindowSize.y = GetSystemMetrics(SM_CYSCREEN);
#endif
		}
		else
		{
			if (dp) 
			{
				// use user-defined resolution
				initFullscreen = dp->Fullscreen;
				mainWindowSize.x = dp->HorRes;
				mainWindowSize.y = dp->VertRes;
			}
			else
			{
				// use settings
				initFullscreen = svFullscreen.GetBool();
				mainWindowSize.x = svResolutionX.GetInt();
				mainWindowSize.y = svResolutionY.GetInt();
			}
		}
		cInternalWindow()->Create(mainWindowSize);

		//Init the internal input system
		cInternalInput()->Init( cInternalWindow()->GetHandle() );
		//Init the Filesystem
		cFilesystem()->Init();

		
		// --- LOAD SELECTED MODULES
		s_pRenderer = (IRenderer*)I_GetModule(_W("renderer"), svRenderer.GetString());
		if (!s_pRenderer) CON(MSG_ERR_FATAL, _W("Cannot load renderer module. It is a core module, cannot continue!"));
		s_pSound = (ISoundEngine*)I_GetModule(_W("sound"), svSound.GetString());
		if (!s_pSound) CON(MSG_ERR_FATAL, _W("Cannot load sound module. It is a core module, cannot continue!"));
		s_pPhys = (IPhysEngine*)I_GetModule(_W("physics"), svPhysics.GetString());
		if (!s_pPhys) CON(MSG_ERR_FATAL, _W("Cannot load phys module. It is a core module, cannot continue!"));
		s_pFS = (IFileSystem*)I_GetModule(_W("filesystem"), svFileSystem.GetString());
		if (!s_pFS) CON(MSG_ERR_FATAL, _W("Cannot load filesystem module. It is a core module, cannot continue!"));
		s_pGUI = (IGUI*)I_GetModule(_W("gui"), svGUI.GetString());
		if (!s_pGUI) CON(MSG_ERR_FATAL, _W("Cannot load GUI module. It is a core module, cannot continue!"));
		m_bModulesLoaded=true;

		// ==== INITIALIZE MODULES ====
		s_pRenderer->Initialize(this, &m_queueRenderer);

		bool ret = s_pRenderer->iGraphicsDevice()->Initialize(mainWindowSize.x, mainWindowSize.y, initFullscreen, cInternalWindow()->GetHandle());
		if (!ret)
		{
			CON(MSG_ERR_FATAL, _W("Failed to initialize graphics device!"));
		}

		// ===== SERIALIZATION DEBUG AND TEST =======
		Scene scene;
		//scene.Save(s_pFS, _W("scenes/test.robject"), iConsole());
		
		//CModel model;

		/*model = (Model*)cObjectManager()->CreateObject( _W("Model") );
		MeshData md;
          MeshSubset ms;
//           Material m;
//		  ms.Material = m;
		  ms.NumTriangles = 1;
		  ms.StartIndex = 0;
		  //ms.StartVertex = 0;
		 md.Subsets.AddEx(ms);
		 md.Indices.AddEx(0);
		 md.Indices.AddEx(1);
		 md.Indices.AddEx(2);
		 md.NumIndices = 3;
		  MeshVertexData mvd;
		  mvd.Usage = _W("P3DVU_POSITION");
		  mvd.DataSize = 3;
		  mvd.Float3.AddEx(Vec3Param(0.0f, 0.0f, 0.0f));
		  mvd.Float3.AddEx(Vec3Param(0.0f, 1.0f, 0.0f));
		  mvd.Float3.AddEx(Vec3Param(1.0f, 1.0f , 0.0f));
		 md.DataStreams.AddEx(mvd);
		 md.NumVerts = 3;
		model->LODs.AddEx(md);

		model->Save(s_pFS, _W("triangle.robject"), iConsole());
		model->PreCache();*/
		// ===========================================

		bool initOK=true;
		initOK &= s_pSound->Initialize(this);
		initOK &= s_pPhys->Initialize(this);
		initOK &= s_pFS->Initialize(this);
		initOK &= s_pGUI->Initialize(this);

		if (!initOK)
			CON(MSG_ERR_FATAL, _W("Failed to initialize some core module(s)! Cannot continue. For more details see console.htm."));

		cSceneManager()->Create();

		cConsole()->InitializeGUI(); // at this time, coz it uses GUI module and it must be initialized ;)

		// FIXME: register engine to script, temporary here
		/*using namespace luabind;
		lua_State* L = cScriptEngine()->GetLVM();
		module(L)
		[
			class_<CEngine>("Engine")
			.scope
			[
				def("GetBuildNum", &CEngine::GetBuildNum )
			]
		];*/

		// load bootstrap script
		cScriptEngine()->LoadScript(_W("scripts/bootstrap.rscript"));

		// DEBUG TESTING OF QUEUE TO RENDERER
		sE2RCanvasDesc* canvas;
		EnqueueMessage( MC_RENDERER, this, CQI_ENGINE2RENDERER_CANVAS_CREATE, (void*&)canvas, sizeof(sE2RCanvasDesc) );
		canvas->handle = cInternalWindow()->GetHandle();
		canvas->size = Vec2i(800,600);
		canvas->windowed = !initFullscreen;

		//Sleep(10000);
		cInternalWindow()->EndSplash();
		cInternalWindow()->SetVisible(true);

		
		//Filesystem test
		/*UINT oSize;
		void *lData=0;
		if(cFilesystem()->Load(_W("scripts.bootstrap"), &lData, oSize)==P3D_FILERESULT_OK)
			cFilesystem()->FreeLoadedData(lData);
		const char* testStr = "this is a test string";
		cFilesystem()->Save(_W("scripts.fstest"), testStr, sizeof(char)*strlen(testStr));*/

		return true;
	}