void ElementAdapter::Output (GS::OChannel& oChannel)
{
	if ((DBERROR (outputManager == NULL)) || (DBERROR (outputAdapterFactory == NULL)) || (DBERROR (element == NULL)) || (DBERROR (dbInfo == NULL))) {
		return;
	}

	switch (element->header.typeID) {
        case API_WallID:
			{
				GSAPI::IAPIOutputAdapter<API_WallType>* wallAdapter = outputAdapterFactory->GetAdapter (element->wall, *dbInfo, attributeProxy, attributeOutputType);
				*wallAdapter >> oChannel;
			}
			break;

		case API_WindowID:
		case API_DoorID:
			{
				GSAPI::IAPIOutputAdapter<API_WindowType>* windowAdapter = outputAdapterFactory->GetAdapter (element->window, *dbInfo, attributeProxy, attributeOutputType);
				*windowAdapter >> oChannel;
			}
			break;

        default:                    break;
	}
}
Ejemplo n.º 2
0
// Initialise the DXInput system
BOOL DInpInitialise(void)
{
	HRESULT			hr; 
//	DIDATAFORMAT	sDataFormat;

	// Create the direct input object;
	hr = DirectInputCreate(hInstance, DIRECTINPUT_VERSION, &psDI, NULL); 
	if (FAILED(hr))
	{
		DBERROR(("DXInpInitialise: couldn't create DI object"));
		return FALSE;
	}

	hr = psDI->lpVtbl->CreateDevice(psDI, &GUID_SysMouse, &psDIMouse, NULL);
	if (FAILED(hr))
	{
		DBERROR(("DXInpInitialise: couldn't create mouse object"));
		return FALSE;
	}

/*	memcpy(&sDataFormat, &c_dfDIMouse, sizeof(DIDATAFORMAT));
	sDataFormat.dwFlags = DIDF_ABSAXIS;
	sDataFormat.dwSize = sizeof(DIDATAFORMAT);
	sDataFormat.dwObjSize = sizeof(DIOBJECTDATAFORMAT);
	sDataFormat.dwDataSize = 0;
	sDataFormat.dwNumObjs = 0;
	sDataFormat.rgodf = NULL;*/
	hr = psDIMouse->lpVtbl->SetDataFormat(psDIMouse, &c_dfDIMouse);//&sDataFormat);
	if (FAILED(hr))
	{
		DBERROR(("DXInpInitialise: couldn't set mouse format"));
		return FALSE;
	}
 
	hr = psDIMouse->lpVtbl->SetCooperativeLevel(psDIMouse, hWndMain,
				   DISCL_EXCLUSIVE | DISCL_FOREGROUND);
 	if (FAILED(hr))
	{
		DBERROR(("DXInpInitialise: couldn't set mouse cooperative level"));
		return FALSE;
	}

	DIMouseAcquired = FALSE;
	if (!DInpMouseAcc(DINP_MOUSEACQUIRE))
	{
		DBERROR(("DXInpInitialise: couldn't acquire mouse"));
		return FALSE;
	}

	mickeyScale = DINP_MOUSESCALE;
	mickeyX = (SDWORD)screenWidth * mickeyScale / 2;
	mickeyY = (SDWORD)screenHeight * mickeyScale / 2;

	return TRUE;
}
Ejemplo n.º 3
0
BOOL
queue_Init( QUEUE ** ppQueue, int iMaxElements, int iElementSize,
				QUEUE_CLEAR_FUNC pfClearFunc )
{
	int			i;
	QUEUE_NODE	*psNode;

	/* allocate queue */
	(*ppQueue) = (QUEUE *) MALLOC( sizeof(QUEUE) );
	
	if ( (*ppQueue) == NULL )
	{
		DBERROR( ("queue_Init: couldn't allocate memory for queue") );
		return FALSE;
	}

	/* set up free node list */
	(*ppQueue)->psFreeNodeList = NULL;
	for ( i=0; i<iMaxElements; i++ )
	{
		/* allocate node */
		psNode = (QUEUE_NODE *) MALLOC( sizeof(QUEUE_NODE) );

		if ( (*ppQueue) == NULL )
		{
			DBERROR( ("queue_Init: couldn't allocate memory for queue node") );
			return FALSE;
		}

		/* init node */
		psNode->psElement = NULL;
		psNode->iPriority  = LOW_PRIORITY;

		/* add to head of list */
		psNode->psPrev = NULL;
		psNode->psNext = (*ppQueue)->psFreeNodeList;
		(*ppQueue)->psFreeNodeList = psNode;
	}

	/* init node counts */
	(*ppQueue)->iFreeNodes  = iMaxElements;
	(*ppQueue)->iQueueNodes = 0;

	/* init queue list */
	(*ppQueue)->psNodeQHead = NULL;
	(*ppQueue)->psCurNode   = NULL;

	/* init other queue struct members */
	(*ppQueue)->iElementSize = iElementSize;
	(*ppQueue)->iMaxElements = iMaxElements;
	(*ppQueue)->pfClearFunc  = pfClearFunc;

	return TRUE;
}
void WallAdapter::Output (GS::OChannel& oChannel)
{
	if ((DBERROR (outputManager == NULL)) || (DBERROR (outputAdapterFactory == NULL)) || (DBERROR (element == NULL)) || (DBERROR (dbInfo == NULL))) {
		return;
	}

	const API_PenType& pen = attributeProxy->GetProxiedAttribute (*dbInfo, API_PenID, element->contPen).pen;
	oChannel << "Wall (guid:" << APIGuid2GSGuid (element->head.guid).ToUniString ().ToCStr () <<
				" begC:(" << element->begC.x << ", " << element->begC.y << ")" <<
				" endC:(" << element->endC.x << ", " << element->endC.y << ")" <<
				" color:(R" << static_cast<int> (pen.rgb.f_red * 255.0) <<
				", G" << static_cast<int> (pen.rgb.f_green * 255.0) <<
				", B" << static_cast<int> (pen.rgb.f_blue * 255.0) << "))\n";
}
Ejemplo n.º 5
0
UWORD
anim_GetAnimID( char *szName )
{
	BASEANIM	*psAnim;
	char		*cPos = strstr( szName, ".ani" );

	if ( cPos == NULL )
	{
		DBERROR( ("anim_GetAnimID: %s isn't .ani file\n") );
		return NO_ANIM;
	}

	/* find matching anim string in list */
	psAnim = g_animGlobals.psAnimList;
	while( psAnim != NULL &&
			stricmp( psAnim->szFileName, szName ) != 0 )
	{
		psAnim = psAnim->psNext;
	}

	if ( psAnim != NULL )
	{
		return psAnim->uwID;
	}
	else
	{
		return NO_ANIM;
	}
}
Ejemplo n.º 6
0
static int read_security_type(tSDL_vnc *vnc) {
    if (vnc->versionMinor < 7) {
        // Read security type (simple)
        CHECKED_READ(vnc, vnc->buffer, 4, "security type");
        vnc->security_type=vnc->buffer[3];
        DBMESSAGE("Security type (read): %i\n", vnc->security_type);
        return 1;
    }

    // Addition for RFB 003 008

    CHECKED_READ(vnc, vnc->buffer, 1, "security type");

    // Security Type List! Receive number of supported Security Types
    int nSecTypes = vnc->buffer[0];
    if (nSecTypes == 0) {
        DBERROR("Server offered an empty list of security types.\n");
        return 0;
    }
        
    // Receive Security Type List (Buffer overflow possible!)
    int result = Recv(vnc->socket,vnc->buffer,nSecTypes,0);
        
    // Find supported one...
    vnc->security_type = 0;
    int i;
    for (i = 0; i < result; i++) {
        vnc->security_type = vnc->buffer[i];
        // Break if supported type (currently 1 or 2) found
        if ((vnc->security_type == 1) || (vnc->security_type == 2)) break;
    }
    
    // Select it
    DBMESSAGE("Security type (select): %i\n", vnc->security_type);
    vnc->buffer[0] = vnc->security_type;
        
    result = send(vnc->socket,vnc->buffer,1,0);
    if (result != 1) {
        DBERROR("Write error on security type selection.\n");
        return 0;
    }

    return 1;
}
Ejemplo n.º 7
0
BASEANIM *
anim_LoadFromBuffer( UBYTE *pBuffer, UDWORD size )
{
	if ( ParseResourceFile( pBuffer, size ) == FALSE )
	{
		DBERROR( ("anim_LoadFromBuffer: couldn't parse file\n") );
		return NULL;
	}

	/* loaded anim is at head of list */
	return g_animGlobals.psAnimList;
}
Ejemplo n.º 8
0
// Construct the back constraint function.
GPCMBackConstraintMLP::GPCMBackConstraintMLP(
    GPCMParams &params,                     // Parameters of this kernel.
    GPCMOptions &options,                   // Loaded options used for creating other kernels.
    GPCMOptimization *optimization,         // Optimization object to add new variables to.
    MatrixXd &dataMatrix,                   // Matrix of Y values.
    MatrixXd &X                             // Matrix of X values.
    ) : GPCMBackConstraint(params,options,optimization,dataMatrix,X)
{
    // Get number of hidden and observed units.
    int inputUnits = dataMatrix.cols();
    int outputUnits = X.cols();
    int hiddenUnits = atoi(params["hidden_units"][0].c_str());
    if (!params["activation_function"][0].compare("linear"))
        activationFunction = Linear;
    else if (!params["activation_function"][0].compare("logistic"))
        activationFunction = Logistic;
    else
        DBERROR("Unknown activation function " << params["activation_function"][0] << " requested for MLP!");

    // Initialize matrices.
    W1grad.resize(inputUnits,hiddenUnits);
    W1.setRandom(inputUnits,hiddenUnits);
    W1.array() -= 0.5;
    W1 *= 1.0/sqrt((double)(inputUnits+1));
    b1grad.resize(1,hiddenUnits);
    b1.setRandom(1,hiddenUnits);
    b1.array() -= 0.5;
    b1 *= 1.0/sqrt((double)(inputUnits+1));
    W2grad.resize(hiddenUnits,outputUnits);
    W2.setRandom(hiddenUnits,outputUnits);
    W2.array() -= 0.5;
    W2 *= 1.0/sqrt((double)(hiddenUnits+1));
    b2grad.resize(1,outputUnits);
    b2.setRandom(1,outputUnits);
    b2.array() -= 0.5;
    b2 *= 1.0/sqrt((double)(hiddenUnits+1));

    // Register variables.
    optimization->addVariable(VarXformNone,&W1,&W1grad,"Layer 1 weight");
    optimization->addVariable(VarXformNone,&b1,&b1grad,"Layer 1 bias");
    optimization->addVariable(VarXformNone,&W2,&W2grad,"Layer 2 weight");
    optimization->addVariable(VarXformNone,&b2,&b2grad,"Layer 2 bias");

    // Create initialization algorithm.
    algorithm = GPCMOptAlgorithm::createAlgorithm(params["init_optimizer"][0]);
    // Set number of iterations.
    maxIterations = atoi(params["init_optimizer_iterations"][0].c_str());

    // Set type.
    name = "mlp";
    type = BackConstraintMLP;
}
Ejemplo n.º 9
0
void
anim_SetVals( char szFileName[], UWORD uwAnimID )
{
	/* get track pointer from resource */
	BASEANIM	*psAnim = resGetData( "ANI", szFileName );

	if ( psAnim == NULL )
	{
		DBERROR( ("anim_SetVals: can't find anim %s\n", szFileName) );
	}

	/* set anim vals */
	psAnim->uwID = uwAnimID;
	strcpy( psAnim->szFileName, szFileName );
}
Ejemplo n.º 10
0
// Create optimization algorithm.
GPCMOptAlgorithm *GPCMOptAlgorithm::createAlgorithm(
    std::string algorithm,                  // Desired algorithm type.
    bool bSilent                            // Whether to suppress all printouts.
    )
{
    // Create optimization algorithm.
    if (!algorithm.compare("lbfgs_nlopt"))
        return new GPCMOptAlgorithmNLOPT(bSilent,GPCM_OPTNL_LBFGS);
    else if (!algorithm.compare("slsqp_nlopt"))
        return new GPCMOptAlgorithmNLOPT(bSilent,GPCM_OPTNL_SLSQP);
    else if (!algorithm.compare("auglag_nlopt"))
        return new GPCMOptAlgorithmNLOPT(bSilent,GPCM_OPTNL_AUGLAG);
    else
        DBERROR("Unknown optimization algorithm " << algorithm << " requested!");
    return NULL;
}
Ejemplo n.º 11
0
static int handleHextile(tSDL_vnc *vnc) {
    DBMESSAGE("Hextile encoding.\n");
    //
    if (!(vnc->tilebuffer)) {
        // Create new tilebuffer
        vnc->tilebuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,16,16,32,vnc->rmask,vnc->gmask,vnc->bmask,0);
        if (vnc->tilebuffer) {
            SDL_SetAlpha(vnc->tilebuffer,0,0);
            DBMESSAGE("Created new tilebuffer.\n");
        } else {
            DBERROR("Error creating tilebuffer.\n");
            return 0;
        }
    }
    return 1;
}
Ejemplo n.º 12
0
int pie_ReloadTexPage(char *filename,UBYTE *pBuffer)
{
	char			fname[MAX_FILE_PATH];
	int				i;
	iSprite			s;

	/* Ensure upper case for tex file names */
	ASSERT ((strlen(filename)<MAX_FILE_PATH,"Texture file path too long"));

	/* Get a copy of the name */
	// if we convert it to upper case ... the resource loading will not work
	for (i = 0; i < (int)strlen(filename); i++)
	{
		fname[i] = filename[i];
	}
	/* Terminate it */
	fname[i] = '\0';

	/* Back to beginning */
	i = 0;
	/* Have we already loaded this one then? */
	while (stricmp(fname,_TEX_PAGE[i].name) != 0)
	{
		i++;
		if (i>=_TEX_INDEX) 
		{
				DBERROR(("Texture not in resources\n",filename));
				return -1;
		}
	}
	//got the old texture page so load bmp straight in
	s.width = _TEX_PAGE[i].tex.width;
	s.height = _TEX_PAGE[i].tex.height;
	s.bmp = _TEX_PAGE[i].tex.bmp;

	pie_PCXLoadMemToBuffer(pBuffer,&s,NULL); 

 	if(pie_GetRenderEngine() == ENGINE_GLIDE)
	{
		gl_Reload8bitTexturePage(s.bmp,(UWORD)s.width,(UWORD)s.height,_TEX_PAGE[i].textPage3dfx);
	}
	else if(pie_GetRenderEngine() == ENGINE_D3D)
	{
		dtm_LoadTexSurface(&_TEX_PAGE[i].tex, i);
	}
	return i;
}
Ejemplo n.º 13
0
BOOL
anim_EndScript( void )
{
	BASEANIM	*psAnim;

	/* get pointer to current anim */
	psAnim = g_animGlobals.psAnimList;

	if ( g_animGlobals.uwCurState != psAnim->uwStates )
	{
		DBERROR( ("anim_End3D: states in current anim not consistent with header\n") );
		return FALSE;
	}

	/* update globals */
	g_animGlobals.uwCurObj++;

	return TRUE;
}
Ejemplo n.º 14
0
BOOL
anim_Init( GETSHAPEFUNC pGetShapeFunc )
{
	int		iSizeAnim2D = sizeof(ANIM2D),
			iSizeAnim3D = sizeof(ANIM3D);

	/* ensure ANIM2D and ANIM3D structs same size */
	if ( iSizeAnim2D != iSizeAnim3D )
	{
		DBERROR( ("anim_Init: ANIM2D and ANIM3D structs not same size in anim.h!") );
	}

	/* init globals */
	g_animGlobals.psAnimList    = NULL;
	g_animGlobals.uwCurObj      = 0;
	g_animGlobals.uwCurState    = 0;
	g_animGlobals.pGetShapeFunc = pGetShapeFunc;

	return TRUE;
}
Ejemplo n.º 15
0
// Global function for creating new latent prior term.
GPCMLatentPrior *GPCMLatentPrior::createLatentPrior(
    GPCMParams &params,                     // Parameters of these dynamics.
    GPCMOptions &options,                   // Loaded options.
    GPCMOptimization *optimization,         // Optimization object to add new variables to.
    MatrixXd &X,                            // Pointer to latent positions matrix.
    MatrixXd &Xgrad,                        // Pointer to latent gradients matrix.
    std::vector<int> &sequence,             // Pointer to sequence indices.
    GPCMTask *task,                         // Pointer to the task.
    GPCMController *controller              // Pointer to the controller object.
    )
{
    std::string type = params["type"][0];
    // Create and return the desired dynamics.
    if (!type.compare("none"))
        return NULL;
    else if (!type.compare("connectivity"))
        return new GPCMConnectivity(params,options,optimization,X,Xgrad,sequence,task,controller);
    else
        DBERROR("Unknown value term " << type << " requested.");
    return NULL;
}
Ejemplo n.º 16
0
/* Sets the game difficulty level */
void	setDifficultyLevel(DIFFICULTY_LEVEL lev)
{
	switch(lev)
	{
	case	DL_EASY:
		fDifPlayerModifier = FRACTCONST(120,100);
		fDifEnemyModifier = FRACTCONST(100,100);
		break;
	case	DL_NORMAL:
		fDifPlayerModifier = FRACTCONST(100,100);
		fDifEnemyModifier = FRACTCONST(100,100);
		break;
	case	DL_HARD:
		fDifPlayerModifier = FRACTCONST(80,100);
		fDifEnemyModifier = FRACTCONST(100,100);
		break;
    case    DL_TOUGH:
        fDifPlayerModifier = FRACTCONST(80,100);
		fDifEnemyModifier = FRACTCONST(120,100);
        break;
	case	DL_KILLER:
		fDifPlayerModifier = FRACTCONST(80,100);
		fDifEnemyModifier = FRACTCONST(160,100);
		break;
	case	DL_DOUBLE:
		fDifPlayerModifier = FRACTCONST(100,100);
		fDifEnemyModifier = FRACTCONST(50,100);
		break;
	case	DL_BBAKER:
		fDifPlayerModifier = FRACTCONST(999,100);	// 10 times
		fDifEnemyModifier = FRACTCONST(1,100);		// almost nothing
		break;

	default:
		DBERROR(("Invalid difficulty level selected - forcing NORMAL"));
		break;
	}
	presDifLevel = lev;
}
Ejemplo n.º 17
0
// ////////////////////////////////////////////////////////////////////////////
// load keymaps from registry.
BOOL loadKeyMap(void)
{
	KEY_STATUS	status;
	KEY_CODE	metaCode;
	KEY_CODE	subCode;
	KEY_ACTION	action;
	STRING		name[128];
	FILE		*pFileHandle;
	SDWORD		count;
	UDWORD		funcmap;
	char		ver[8];

	// throw away any keymaps!!
	keyClearMappings();
	
	pFileHandle = fopen("keymap.map", "rb");								// check file exists
	if (pFileHandle == NULL)
	{
		return FALSE;														// failed
	}

	if (fread(&count, sizeof(UDWORD), 1, pFileHandle) != 1)			
	{
		DBERROR(("Read failed for keymap load"));
		fclose(pFileHandle);
		return FALSE;
	}

	// get version number.
	// if not from current version, create a new one..
	if(fread(&ver,8,1,pFileHandle) !=1)
	{
		fclose(pFileHandle);
		return FALSE;
	}
	if(strncmp(&ver,buildTime,8) != 0)	// check 
	{
		fclose(pFileHandle);
		return FALSE;	
	}

	for(; count>0;count--)
	{
		// name
		if (fread(&name, 128, 1, pFileHandle) != 1)					
		{
			DBERROR(("Read failed for keymap load"));
			fclose(pFileHandle);
			return FALSE;
		}

		// status
		if (fread(&status, sizeof(KEY_STATUS), 1, pFileHandle) != 1)					
		{
			DBERROR(("Read failed for keymap load"));
			fclose(pFileHandle);
			return FALSE;
		}
		// metakey
		if (fread(&metaCode, sizeof(KEY_CODE), 1, pFileHandle) != 1)					
		{
			DBERROR(("Read failed for keymap load"));
			fclose(pFileHandle);
			return FALSE;
		}
		// subkey
		if (fread(&subCode, sizeof(KEY_CODE), 1, pFileHandle) != 1)				
		{
			DBERROR(("Read failed for keymap load"));
			fclose(pFileHandle);
			return FALSE;
		}
		// action
		if (fread(&action, sizeof(KEY_ACTION), 1, pFileHandle) != 1)				
		{
			DBERROR(("Read failed for keymap load"));
			fclose(pFileHandle);
			return FALSE;
		}
		// function
		if (fread(&funcmap, sizeof(UDWORD), 1, pFileHandle) != 1)				
		{
			DBERROR(("Read failed for keymap load"));
			fclose(pFileHandle);
			return FALSE;
		}

		// add mapping
		keyAddMapping( status, metaCode, subCode, action, keyMapSaveTable[funcmap],(char*)&name);
	}

	if (fclose(pFileHandle) != 0)
	{
		DBERROR(("Close failed for load key map."));
		return FALSE;
	}
	return TRUE;

}
Ejemplo n.º 18
0
int WINAPI WinMain(
    HINSTANCE  hInstance,		// handle to current instance
    HINSTANCE  hPrevInstance,	// handle to previous instance
    LPSTR  lpCmdLine,			// pointer to command line
    int  nShowCmd)		 		// show state of window
{
	FRAME_STATUS	frameRet;
	BOOL			quit = FALSE;
	BOOL			Restart = FALSE;
	BOOL			paused = FALSE;//, firstTime = TRUE;
	BOOL			bGlide = FALSE;
	BOOL			bVidMem = FALSE;
	SDWORD			dispBitDepth = DISP_BITDEPTH;
	SDWORD			introVideoControl = 3;
	GAMECODE		loopStatus;
	iColour*		psPaletteBuffer;
	SDWORD			pSize;

	(void)nShowCmd;
//	(void)lpCmdLine;
	(void)hPrevInstance;

	// initialise all the command line states
	clStartWindowed = FALSE;
	clIntroVideo = FALSE;

	// save debugging info to disk
	DBOUTPUTFILE("debug.txt");

	if (!pie_CheckForDX6())
	{
		DBERROR(("Unable to create DirectX 6 interface.\nPlease ensure DirectX 6 or later is installed."));
		return -1;
	}

	war_SetDefaultStates();

	war_SetRendMode(REND_MODE_HAL);

	if (InitGlideDLL())	// In ivis02/3dfxdyn.c - returns FALSE if no glide2x.dll is not found
	{
		bGlideFound = TRUE;
		war_SetRendMode(REND_MODE_GLIDE);//default to glide this will be over writen by Registry or Command line if found
	}

   
init://jump here from the end if re_initialising


	// initialise memory stuff, moved out of frameinit by ajl. 
	if (!memInitialise())
	{
		return FALSE;
	}

	if (!blkInitialise())
	{
		return FALSE;
	}


	loadRenderMode();//get the registry entry for clRendMode

	bDisableLobby = FALSE;

	// parse the command line
//	if (bDisableLobby || !NetPlay.bLobbyLaunched)
//	{
		if(!reInit)
		{
			if(!ParseCommandLine(lpCmdLine,bGlideFound))
			{
				return -1;
			}
		}
//	}

	// find out if the lobby stuff has been disabled
//	bDisableLobby = checkDisableLobby();
	if (!bDisableLobby &&
		!lobbyInitialise())			// ajl. Init net stuff. Lobby can modify startup conditions like commandline.
	{
		return -1;
	}

	reInit = FALSE;//just so we dont restart again

#ifdef USE_FILE_PATH
	_chdir(FILE_PATH);
#endif

	//always start windowed toggle to fullscreen later
	if (war_GetRendMode() == REND_MODE_HAL)
	{
		bGlide = FALSE;
		bVidMem = TRUE;
		dispBitDepth = DISP_HARDBITDEPTH;
	}
	else if (war_GetRendMode() == REND_MODE_REF)
	{
		bGlide = FALSE;
		bVidMem = TRUE;
		dispBitDepth = DISP_HARDBITDEPTH;
	}
	else if (war_GetRendMode() == REND_MODE_RGB)
	{
		bGlide = FALSE;
		bVidMem = FALSE;
		dispBitDepth = DISP_HARDBITDEPTH;
	}
	else if (war_GetRendMode() == REND_MODE_GLIDE)
	{
		bGlide = TRUE;
		bVidMem = FALSE;
		dispBitDepth = DISP_HARDBITDEPTH;
	}
	else
	{
		bGlide = FALSE;
		bVidMem = FALSE;
		dispBitDepth = DISP_BITDEPTH;
	}

//	frameDDEnumerate();

	if (!frameInitialise(hInstance, "Warzone 2100",
									DISP_WIDTH,DISP_HEIGHT,dispBitDepth, !clStartWindowed, bVidMem, bGlide))
	{
		return -1;
	}
	if (!wdgLoadAllWDGCatalogs())
	{
		return -1;
	}

	pie_SetFogStatus(FALSE);
	pie_ScreenFlip(CLEAR_BLACK);
	pie_ScreenFlip(CLEAR_BLACK);

	if (war_GetRendMode() == REND_MODE_GLIDE)
	{
		dbg_SetMessageBoxCallback(fxMBCallback);
		dbg_SetErrorBoxCallback(fxMBCallback);
		dbg_SetAssertCallback(fxMBCallback);
	}

	if(gameStatus == GS_VIDEO_MODE) 
	{
		introVideoControl = 0;//play video
		gameStatus = GS_TITLE_SCREEN;
	}

	//load palette
	psPaletteBuffer = (iColour*)MALLOC(256 * sizeof(iColour)+1);
	if (psPaletteBuffer == NULL)
	{
		DBERROR(("Out of memory"));
		return -1;
	}
	if (!loadFileToBuffer("palette.bin", (UBYTE*)psPaletteBuffer, (256 * sizeof(iColour)+1),(UDWORD*)&pSize))
	{
		DBERROR(("Couldn't load palette data"));
		return -1;
	}
	pal_AddNewPalette(psPaletteBuffer);
	FREE(psPaletteBuffer);

	if (war_GetRendMode() == REND_MODE_GLIDE)
	{
		pie_LoadBackDrop(SCREEN_RANDOMBDROP,TRUE);
	}
	else
	{
		pie_LoadBackDrop(SCREEN_RANDOMBDROP,FALSE);
	}
	pie_SetFogStatus(FALSE);
	pie_ScreenFlip(CLEAR_BLACK);

	quit = FALSE;

	/* check CDROM drive available */
	if ( cdspan_CheckCDAvailable() == FALSE )
	{
		DBERROR( ("Cannot detect CDROM drive\n") );
		quit = TRUE;
	}

	if (!systemInitialise())
	{
		return -1;
	}
	
// If windowed mode not requested then toggle to full screen. Doing
// it here rather than in the call to frameInitialise fixes a problem
// where machines with an NVidia and a 3DFX would kill the 3dfx display. (Definitly a HACK, PD)
/*	if(!clStartWindowed)
	{
		screenToggleMode();
	}
*/
	//set all the pause states to false
	setAllPauseStates(FALSE);

	while (!quit)
	{
// Do the game mode specific initialisation.
		switch(gameStatus)
		{
			case GS_TITLE_SCREEN:
				screen_RestartBackDrop();


				if (!frontendInitialise("wrf\\frontend.wrf"))
				{
					goto exit;
				}

				frontendInitialised = TRUE;
				frontendInitVars();
				//if intro required set up the video
				if (introVideoControl <= 1)
				{
					seq_ClearSeqList();
					seq_AddSeqToList("eidos-logo.rpl",NULL, NULL, FALSE,0);
					seq_AddSeqToList("pumpkin.rpl",NULL, NULL, FALSE,0);
					seq_AddSeqToList("titles.rpl",NULL, NULL, FALSE,0);
					seq_AddSeqToList("devastation.rpl",NULL,"devastation.txa", FALSE,0);

					seq_StartNextFullScreenVideo();
					introVideoControl = 2;
				}
				break;

			case GS_SAVEGAMELOAD:
				screen_RestartBackDrop();
				gameStatus = GS_NORMAL;
				// load up a save game
				if (!loadGameInit(saveGameName,FALSE))
				{
					goto exit;
				}
				/*if (!levLoadData(pLevelName, saveGameName)) {
					return -1;
				}*/
				screen_StopBackDrop();
				break;
			case GS_NORMAL:
				if (!levLoadData(pLevelName, NULL, 0)) {
					goto exit;
				}
				//after data is loaded check the research stats are valid
				if (!checkResearchStats())
				{
					DBERROR(("Invalid Research Stats"));
					goto exit;
				}
				//and check the structure stats are valid
				if (!checkStructureStats())
				{
					DBERROR(("Invalid Structure Stats"));
					goto exit;
				}

				//set a flag for the trigger/event system to indicate initialisation is complete
				gameInitialised = TRUE;
				screen_StopBackDrop();
				break;
			case GS_VIDEO_MODE:
				DBERROR(("Video_mode no longer valid"));
				if (introVideoControl == 0)
				{
					videoInitialised = TRUE;
				}
				break;

			default:
				DBERROR(("Unknown game status on startup!"));
		}

		
		DBPRINTF(("Entering main loop\n"));

		Restart = FALSE;
		//firstTime = TRUE;

		while (!Restart)
		{
			frameRet = frameUpdate();
			
			if (pie_GetRenderEngine() == ENGINE_D3D)
			{
				if ( frameRet == FRAME_SETFOCUS )
				{
					D3DTestCooperativeLevel( TRUE );
				}
				else
				{
					D3DTestCooperativeLevel( FALSE );
				}
			}

			switch (frameRet)
			{
			case FRAME_KILLFOCUS:
				paused = TRUE;
				gameTimeStop();
				if (pie_GetRenderEngine() == ENGINE_GLIDE)
				{
					if (!gl_Deactivate())
					{
						quit = TRUE;
						Restart = TRUE;
					}
				}
				mixer_SaveIngameVols();
				mixer_RestoreWinVols();
				audio_StopAll();
				break;
			case FRAME_SETFOCUS:
				paused = FALSE;
				gameTimeStart();
				if (!dispModeChange())
				{
					quit = TRUE;
					Restart = TRUE;
				}
				if (pie_GetRenderEngine() == ENGINE_GLIDE)
				{
					if (!gl_Reactivate())
					{
						quit = TRUE;
						Restart = TRUE;
					}
				}
				else if (pie_GetRenderEngine() == ENGINE_D3D)
				{
					dtm_RestoreTextures();
				}
				mixer_SaveWinVols();
				mixer_RestoreIngameVols();
				break;
			case FRAME_QUIT:
				quit = TRUE;
				Restart = TRUE;
				break;
			}

			lastStatus = gameStatus;

			if ((!paused) && (!quit))
			{
				switch(gameStatus)
				{
				case	GS_TITLE_SCREEN:
					pie_SetSwirlyBoxes(TRUE);
					if (loop_GetVideoStatus())
					{
						videoLoop();
					}
					else
					{
						switch(titleLoop()) {
							case TITLECODE_QUITGAME:
								DBPRINTF(("TITLECODE_QUITGAME\n"));
								Restart = TRUE;
								quit = TRUE;
								break;

	//						case TITLECODE_ATTRACT:
	//							DBPRINTF(("TITLECODE_ATTRACT\n"));
	//							break;

							case TITLECODE_SAVEGAMELOAD:
								DBPRINTF(("TITLECODE_SAVEGAMELOAD\n"));
								gameStatus = GS_SAVEGAMELOAD;
								Restart = TRUE;
								break;
							case TITLECODE_STARTGAME:
								DBPRINTF(("TITLECODE_STARTGAME\n"));
								gameStatus = GS_NORMAL;
								Restart = TRUE;
								break;

							case TITLECODE_SHOWINTRO:	
								DBPRINTF(("TITLECODE_SHOWINTRO\n"));
								seq_ClearSeqList();
								seq_AddSeqToList("eidos-logo.rpl",NULL,NULL, FALSE,0);
								seq_AddSeqToList("pumpkin.rpl",NULL,NULL, FALSE,0);
								seq_AddSeqToList("titles.rpl",NULL,NULL, FALSE,0);
								seq_AddSeqToList("devastation.rpl",NULL,"devastation.txa", FALSE,0);
								seq_StartNextFullScreenVideo();
								introVideoControl = 2;//play the video but dont init the sound system
								break;

							case TITLECODE_CONTINUE:
								break;

							default:
								DBERROR(("Unknown code returned by titleLoop"));
						}
					}
					pie_SetSwirlyBoxes(FALSE);
					break;
			
/*				case GS_SAVEGAMELOAD:
					if (loopNewLevel)
					{
						//the start of a campaign/expand mission
						DBPRINTF(("GAMECODE_NEWLEVEL\n"));
						loopNewLevel = FALSE;
						// gameStatus is unchanged, just loading additional data
						Restart = TRUE;
					}
					break;
*/
				case	GS_NORMAL:
					if (loop_GetVideoStatus())
					{
						videoLoop();
					}
					else
					{
						loopStatus = gameLoop();
						switch(loopStatus) {
							case GAMECODE_QUITGAME:
								DBPRINTF(("GAMECODE_QUITGAME\n"));
								gameStatus = GS_TITLE_SCREEN;
								Restart = TRUE;
/*#ifdef NON_INTERACT
								quit = TRUE;
#endif*/

								if(NetPlay.bLobbyLaunched)
								{
//									changeTitleMode(QUIT);
									quit = TRUE;
								}
								break;
							case GAMECODE_FASTEXIT:
								DBPRINTF(("GAMECODE_FASTEXIT\n"));
								Restart = TRUE;
								quit = TRUE;
								break;

							case GAMECODE_LOADGAME:
								DBPRINTF(("GAMECODE_LOADGAME\n"));
								Restart = TRUE;
								gameStatus = GS_SAVEGAMELOAD;
								break;

							case GAMECODE_PLAYVIDEO:
								DBPRINTF(("GAMECODE_PLAYVIDEO\n"));
//dont schange mode any more								gameStatus = GS_VIDEO_MODE;
								Restart = FALSE;
								break;

							case GAMECODE_NEWLEVEL:
								DBPRINTF(("GAMECODE_NEWLEVEL\n"));
								// gameStatus is unchanged, just loading additional data
								Restart = TRUE;
								break;

							case GAMECODE_RESTARTGAME:
								DBPRINTF(("GAMECODE_RESTARTGAME\n"));
								Restart = TRUE;
								break;

							case GAMECODE_CONTINUE:
								break;

							default:
								DBERROR(("Unknown code returned by gameLoop"));
						}
					}
					break;

				case	GS_VIDEO_MODE:
				DBERROR(("Video_mode no longer valid"));
					if (loop_GetVideoStatus())
					{
						videoLoop();
					}
					else
					{
						if (introVideoControl <= 1)
						{
								seq_ClearSeqList();

								seq_AddSeqToList("factory.rpl",NULL,NULL, FALSE,0);
								seq_StartNextFullScreenVideo();//"sequences\\factory.rpl","sequences\\factory.wav");
								introVideoControl = 2;
						}
						else
						{
								DBPRINTF(("VIDEO_QUIT\n"));
								if (introVideoControl == 2)//finished playing intro video
								{
									gameStatus = GS_TITLE_SCREEN;
									if (videoInitialised)
									{
										Restart = TRUE;
									}
									introVideoControl = 3;
								}
								else
								{
									gameStatus = GS_NORMAL;
								}
						}
					}

					break;
		
				default:
					DBERROR(("Weirdy game status I'm afraid!!"));
					break;
				}

				gameTimeUpdate();
			}
		}	// End of !Restart loop.

// Do game mode specific shutdown.	
		switch(lastStatus) {
			case GS_TITLE_SCREEN:
				if (!frontendShutdown())
				{
					goto exit;
				}
				frontendInitialised = FALSE;
				break;

/*			case GS_SAVEGAMELOAD:
				//get the next level to load up
				gameStatus = GS_NORMAL;
				break;*/
			case GS_NORMAL:
				if (loopStatus != GAMECODE_NEWLEVEL)
				{
					initLoadingScreen(TRUE,FALSE);	// returning to f.e. do a loader.render not active
					pie_EnableFog(FALSE);//dont let the normal loop code set status on
					fogStatus = 0;
					if (loopStatus != GAMECODE_LOADGAME)
					{
						levReleaseAll();
					}
				}
				gameInitialised = FALSE;
				break;

			case	GS_VIDEO_MODE:
				DBERROR(("Video_mode no longer valid"));
				if (videoInitialised)
				{
					videoInitialised = FALSE;
				}
				break;

			default:
				DBERROR(("Unknown game status on shutdown!"));
				break;
		}
	
	} // End of !quit loop.

	DBPRINTF(("Shuting down application\n"));

	systemShutdown();

	pal_ShutDown();

	frameShutDown();

	ShutdownGlideDLL();

	if (reInit) goto init;

	PostQuitMessage(0);

	return 0;

exit:

	DBPRINTF(("Shutting down after fail\n"));

	systemShutdown();

	pal_ShutDown();

	frameShutDown();

	ShutdownGlideDLL();

	PostQuitMessage(1);

	return 1;

}
Ejemplo n.º 19
0
GPWithRankPrior::GPWithRankPrior(GPCMOptions &inOptions, bool bLoadTrainedModel, bool bRunHighDimensionalOptimization)
{
 	GPCMOptions options;
	//#########  initialization_script
	if (!inOptions["model"]["initialization_script"].empty())
    {
        // Options are replaced with the options of the initialization script.
        GPCMScriptParser parser(inOptions["model"]["initialization_script"][0],inOptions["dir"]["dir"][0]);
        options = parser.getOptions();

        // We necessarily want to load the trained model.
        bLoadTrainedModel = true;
        options["data"]["initialization_file"] = options["result"]["mat_file"];
        options["data"]["initialization_file"][0].insert(0,options["dir"]["dir"][0]);

        // Override options.
        for (GPCMOptions::iterator itr = inOptions.begin(); itr != inOptions.end(); itr++)
        {
            for (GPCMParams::iterator pitr = itr->second.begin(); pitr != itr->second.end(); pitr++)
            {
                options[itr->first][pitr->first] = pitr->second;
            }
        }
    }
    else if (bLoadTrainedModel)
    { // Set initialization file if we are loading a trained model.
        options = inOptions;
        options["data"]["initialization_file"] = options["result"]["mat_file"];
        options["data"]["initialization_file"][0].insert(0,options["dir"]["dir"][0]);
    }
    else
    {
        options = inOptions;
    }

    GPWithRankPrior *initModel = NULL;
    mbHighDimensionalOptimization = bRunHighDimensionalOptimization;
    
	if (!bRunHighDimensionalOptimization &&
        !inOptions["embedding"]["training_latent_dimensions"].empty() &&
        options["data"]["initialization_file"].empty())
    {
        // Launch high-dimensional pre-training.
        DBPRINTLN("Launching high dimensional optimization...");
        initModel = new GPWithRankPrior(options, false, true);
        initModel->optimize();
        DBPRINTLN("High dimensional optimization complete.");
    }
 	
	//create data reader
	std::string datatype = options["data"]["type"][0];
    std::vector<std::string> data = options["data"]["path"];
   
	GPCMDataReader *datareader = NULL;
    if (!datatype.compare("bvh_motion"))			// Read BVH motion data.
        datareader = new GPCMDataReaderBVH();
    else if (!datatype.compare("bvh_motion_quat"))  // Read BVH motion data but use quaternion representation.
        datareader = new GPCMDataReaderBVHQuat();
    else if (!datatype.compare("annotation"))		// Read ANN annotation data.
        datareader = new GPCMDataReaderANN();
    else											// Unknown data.
        DBERROR("Unknown data type " << datatype << " specified!");

	std::vector<double> noise(data.size());
    for (unsigned i = 0; i < data.size(); i++)
    {
        if (options["data"]["noise"].size() > i)
            noise[i] = atof(options["data"]["noise"][i].c_str());
        else
            noise[i] = 0.0;
    }
	// append absloute path
	for (std::vector<std::string>::iterator itr = data.begin(); itr != data.end(); itr++)
    {
        itr->insert(0,options["dir"]["dir"][0]);
    }
	datareader->load(data,noise);

	mDataMatrix = datareader->getYMatrix();
	mSequence   = datareader->getSequence();

	delete datareader;

	bool bValidate = !options["optimization"]["validate_gradients"][0].compare("true");

	int maxIterations;
    if (!options["optimization"]["iterations_lowdim"].empty() && !bRunHighDimensionalOptimization)
        maxIterations = atoi(options["optimization"]["iterations_lowdim"][0].c_str());
    else
        maxIterations = atoi(options["optimization"]["iterations"][0].c_str());

	bool bUseEM = !options["model"]["learn_scales"][0].compare("em");
 
	int outerIterations = 1;
    if (bUseEM)
        outerIterations = atoi(options["optimization"]["outer_iterations"][0].c_str());
	
	if (!options["data"]["initialization_file"].empty())
        mbRunOptimization = false;
    else
        mbRunOptimization = true;
	
	mOptimization = new GPCMOptimization( bValidate, bUseEM, options["optimization"]["algorithm"][0],maxIterations,false);
	mLatDim  = 1;
	if (bRunHighDimensionalOptimization)
		mLatDim = atoi(options["embedding"]["training_latent_dimensions"][0].c_str());
    else
        mLatDim = atoi(options["embedding"]["latent_dimensions"][0].c_str());
    if (mLatDim > mDataMatrix.cols()) mLatDim = mDataMatrix.cols();
    mX.resize(mDataMatrix.rows(),mLatDim);
    mXGrad.resize(mDataMatrix.rows(),mLatDim);

	
//	std::string inittype = options["initialization"]["method"][0];
    // Optionally filter the data matrix.
    MatrixXd filteredDataMatrix;
    if (!options["initialization"]["prefiltering"].empty())
        filteredDataMatrix = filterData(mDataMatrix,mSequence,atof(options["initialization"]["prefiltering"][0].c_str()));
    else
        filteredDataMatrix = mDataMatrix;

    mBackConstraint = GPCMBackConstraint::createBackConstraint(options["back_constraints"],options,
        mOptimization,mDataMatrix,mX);
	 
	MatrixXd *Xptr = &mX;

    MatrixXd *Xgradptr = &mXGrad;
	mReconstructionGP = new GPCMGaussianProcess(options["model"],options,
		mOptimization,NULL,mDataMatrix,mY,&Xptr,&Xgradptr,1,false,true);
//	if(!mbHighDimensionalOptimization)
	GPCMEmbedPPCA(mX,mDataMatrix);
//	else 
//		mX = mY;

	if(mBackConstraint!= nullptr)
		mBackConstraint->initialize();

	if (mBackConstraint == nullptr)
 		mOptimization->addVariable(VarXformNone,&mX,&mXGrad,"X");

	if (bRunHighDimensionalOptimization && !options["model"]["rank_prior_wt"].empty())
        mRankPrior = new GPCMRankPrior(atof(options["model"]["rank_prior_wt"][0].c_str()),mX,mXGrad);
    else 
        mRankPrior = nullptr;
  
  	
	//----------------------------------------------------------------------------------------------
	if (initModel)
    {
        this->copySettings(*initModel);
        delete initModel;
    }

    else if (!options["data"]["initialization_file"].empty())
    {
        // If we have an initialization file, load that now.
        GPCMMatReader *reader = new GPCMMatReader(options["data"]["initialization_file"][0]);
        load(reader->getStruct("model"));
        delete reader;
    }

	recompute(true);
}
Ejemplo n.º 20
0
BOOL
anim_Create3D( char szPieFileName[], UWORD uwStates,
				UWORD uwFrameRate, UWORD uwObj, UBYTE ubType, UWORD uwID )
{
	ANIM3D		*psAnim3D;
	iIMDShape	*psFrames;
	UWORD		uwFrames, i;

	/* allocate anim */
	if ( (psAnim3D = MALLOC(sizeof(ANIM3D))) == NULL )
	{
		return FALSE;
	}

	/* get local pointer to shape */
	psAnim3D->psFrames = (g_animGlobals.pGetShapeFunc) (szPieFileName);

	/* count frames in imd */
	psFrames = psAnim3D->psFrames;
	uwFrames = 0;
	while ( psFrames != NULL )
	{
#ifdef DEBUG
		if (psFrames==0xcdcdcdcd)
		{
			printf("bad pointer in Create 3D !!!!  -[%s]\n", szPieFileName);
		}
#endif
		uwFrames++;
		psFrames = psFrames->next;
	}

	/* check frame count matches script */
	if ( ubType == ANIM_3D_TRANS && uwObj != uwFrames )
	{
		DBERROR( ("anim_Create3D: frames in pie %s != script objects %i\n",
					szPieFileName, uwObj ) );
		return FALSE;
	}

	/* get pointers to individual frames */
	psAnim3D->apFrame = MALLOC( uwFrames*sizeof(iIMDShape *) );
	psFrames = psAnim3D->psFrames;
	for ( i=0; i<uwFrames; i++ )
	{
		psAnim3D->apFrame[i] = psFrames;
		psFrames = psFrames->next;
	}

	/* init members */
	psAnim3D->animType = ubType;
	anim_InitBaseMembers( (BASEANIM * ) psAnim3D, uwStates,
							uwFrameRate, uwObj, ubType, uwID );

	/* add to head of list */
	psAnim3D->psNext = g_animGlobals.psAnimList;
	g_animGlobals.psAnimList = (BASEANIM * ) psAnim3D;

	/* update globals */
	g_animGlobals.uwCurObj = 0;

	return TRUE;
}
Ejemplo n.º 21
0
int iV_TexLoadNew( char *path, char *filename, int type,
					iBool palkeep, iBool bColourKeyed )
{
	char			fname[MAX_FILE_PATH];
	int				i;
	iSprite			*s;
	TEXTUREPAGE *TextPage;		// pointer to the resource texture page structure   ... palette stuff is BACK !!!!!




// If we are in the BSP or PIEBIN tool, then just added it into the array and exit
#ifdef PIETOOL
	return pie_AddBMPtoTexPages(NULL, filename, type, bColourKeyed, TRUE);
#endif


	/* If it's not a resource - use old way!  - PSX does not need this check because it MUST have been loaded allready by the resource loader */
	if(!resPresent("TEXPAGE",filename))
	{
		DBERROR(("Texture not in resources; %s.\n",	filename));
		return(iV_TexLoad( path, filename, type,
					palkeep, bColourKeyed ));
	}


	/* Ensure upper case for tex file names */
	ASSERT ((strlen(filename)<MAX_FILE_PATH,"Texture file path too long"));

	/* Get a copy of the name */
	// if we convert it to upper case ... the resource loading will not work

	for (i = 0; i < (int)strlen(filename); i++)
	{
		fname[i] = filename[i];
	}


	/* Terminate it */
	fname[i] = '\0';

	/* Back to beginning */
	i = 0;

	/* Have we already loaded this one then? */
	while (i<_TEX_INDEX) 
	{
		if (stricmp(fname,_TEX_PAGE[i].name) == 0)
		{
			/* Send back 3dfx texpage number if we're on 3dfx - they're NOT the same */
		 	if(rendSurface.usr == REND_GLIDE_3DFX)
			{
				return(_TEX_PAGE[i].textPage3dfx);
			}
			else
			{
				/* Otherwise send back the software one */
				return i;
			}
		}
		i++;
	}

	/* Get a pointer to the texpage in memory - we KNOW it's there from the check at start */
	TextPage = (TEXTUREPAGE *)resGetData("TEXPAGE",filename);
	s = TextPage->Texture;

	return pie_AddBMPtoTexPages(s, fname, type, bColourKeyed, TRUE);

}
Ejemplo n.º 22
0
// ////////////////////////////////////////////////////////////////////////
// handle the playback buffer.
BOOL NETqueueIncomingAudio( LPBYTE lpbSoundData, DWORD dwSoundBytes,BOOL bStream)
{ 
    LPVOID lpvPtr1,lpvPtr2=NULL; 
    DWORD dwBytes1,dwBytes2=0; 
	

    HRESULT hr; 

	if(!NetPlay.bAllowCapturePlay)
	{
		return FALSE;
	}

    // Obtain memory address of write block. This will be in two parts
    // if the block wraps around.
	if(!bStream)
	{
		// clear out and start again
		hr = IDirectSoundBuffer_Lock(lpDirectSoundBuffer,
									0,			//offset
									dwSoundBytes,		//size (ignored)
									&lpvPtr1,&dwBytes1,
									NULL,NULL,
									DSBLOCK_ENTIREBUFFER); 
	}
	else	// stream nicely
	{

		hr = IDirectSoundBuffer_Lock(lpDirectSoundBuffer,
									0,			//offset
									dwSoundBytes,		//size
									&lpvPtr1,&dwBytes1,
									&lpvPtr2,&dwBytes2,
									DSBLOCK_FROMWRITECURSOR ); 
	}
    
	if(DS_OK == hr) 
	{     	
		if(bStream)
		{	
			// clear out unwanted stuff.
			CopyMemory(lpvPtr1, lpbSoundData, dwBytes1); // Write to pointers. 
			if (NULL != lpvPtr2)
			{ 
				CopyMemory(lpvPtr2, (lpbSoundData+dwBytes1), dwBytes2);
			}
		}	
		else	// not streaming
		{
			CopyMemory(lpvPtr1, lpbSoundData, dwSoundBytes);
	        ZeroMemory( ((UBYTE *)lpvPtr1)+dwSoundBytes,(playbackBuff.dwBufferBytes)-dwSoundBytes);	// remove old stuff
		}		

		hr = IDirectSoundBuffer_Unlock(lpDirectSoundBuffer, lpvPtr1, dwBytes1, lpvPtr2,dwBytes2); 
		if(DS_OK == hr)																		// Success. 
		{
			IDirectSoundBuffer_Play(lpDirectSoundBuffer,0,0,0); //DSBPLAY_LOOPING );								// now play the sound         
			if(hr == DS_OK)
			{
				return TRUE;
			}
			DBERROR(("NETPLAY: failed to play incoming sample"));
        } 
    } 
    return FALSE; 
}
Ejemplo n.º 23
0
int pie_AddBMPtoTexPages(iSprite* s, char* filename, int type, iBool bColourKeyed, iBool bResource)
{
	int				i3d;
	int				i;

	/* Get next available texture page */
	i = _TEX_INDEX;
	/* Have we used up too many? */
	if (_TEX_INDEX >= iV_TEX_MAX) 
	{
		iV_DEBUG1("tex[TexLoad] = too many texture pages '%s'\n",buffer);
		return -1;
	}

	/* Stick the name into the tex page structures */
	strcpy(_TEX_PAGE[i].name,filename);

	/* Store away all the info */
	/* DID come from a resource */
	_TEX_PAGE[i].bResource = bResource;
	// Default values
	_TEX_PAGE[i].tex.bmp = NULL;
	_TEX_PAGE[i].tex.width = 256;
	_TEX_PAGE[i].tex.height = 256;
	_TEX_PAGE[i].tex.xshift = 0;

	if (s!=NULL)
	{
		_TEX_PAGE[i].tex.bmp = s->bmp;
		_TEX_PAGE[i].tex.width = s->width;
		_TEX_PAGE[i].tex.height = s->height;
		_TEX_PAGE[i].tex.xshift = _tex_get_top_bit(s->width);
	}
	_TEX_PAGE[i].tex.bColourKeyed = bColourKeyed;
	_TEX_PAGE[i].type = type;

	if ( rendSurface.usr >= REND_D3D_RGB &&
		 rendSurface.usr <= REND_D3D_REF )
	{
		/* set pie texture pointer */
		if ( dtm_LoadTexSurface( &_TEX_PAGE[i].tex, i) == FALSE )
		{
			return -1;
		}
	}

	/* Now some extra stuff if we're running on a 3dfx? */
	if(rendSurface.usr == REND_GLIDE_3DFX)
	{
		if(iV_TexSizeIsLegal(s->width,s->height)) {
			/* Bang it down to the card if we're on a 3dfx */
			i3d = gl_downLoad8bitTexturePage(s->bmp,(UWORD)s->width,(UWORD)s->height);
			/* Update 'real' texpage number in texpage structure */
		} else {
// If it's an illegal texture page size then chuck a message and default to TPage 1.
			DBERROR(("Illegal size for texture. [%s , (%d,%d)]\n",
					filename,s->width,s->height));
			i3d = 1;
		}
		_TEX_PAGE[i].textPage3dfx = i3d;
	}
	/* Send back the texpage number so we can store it in the IMD */

	_TEX_INDEX++;

	if (pie_GetRenderEngine() == ENGINE_GLIDE)
	{
		return(i3d);
	}
	else
	{
		return (i);
	}
}
Ejemplo n.º 24
0
BOOL scrSkCanBuildTemplate(void)
{
	STRUCTURE *psStructure;
	DROID_TEMPLATE *psTempl;

	SDWORD player, structure, templ;

	if (!stackPopParams(3,VAL_INT, &player,ST_STRUCTURE, &structure, ST_TEMPLATE, &templ))
	{
		return FALSE;
	}

	psTempl =  (DROID_TEMPLATE*) templ;
	psStructure = (STRUCTURE *) structure;

	// is factory big enough?
	if(!validTemplateForFactory(psTempl, psStructure) )
	{
		goto failTempl;
	}

	if ((asBodyStats + psTempl->asParts[COMP_BODY])->size > ((FACTORY*)psStructure->pFunctionality)->capacity  )
	{
		goto failTempl;
	}

	// is every component from template available?
	// body available.
	if( apCompLists[player][COMP_BODY][psTempl->asParts[COMP_BODY]] != AVAILABLE )
	{
		goto failTempl;
	}

	// propulsion method available.
	if( apCompLists[player][COMP_PROPULSION][psTempl->asParts[COMP_PROPULSION]] != AVAILABLE )
	{
		goto failTempl;
	}

	// weapon/sensor

	switch (droidTemplateType(psTempl))
	{
	case DROID_CYBORG:		        // cyborg-type thang.. no need to check weapon.
	case DROID_CYBORG_SUPER:		// super cyborg-type thang
		break;
	case DROID_WEAPON:
		if( apCompLists[player][COMP_WEAPON][ psTempl->asWeaps[0] ] != AVAILABLE )
		{
			goto failTempl;
		}
		break;
	case DROID_SENSOR:
		if( apCompLists[player][COMP_SENSOR][psTempl->asParts[COMP_SENSOR]] != AVAILABLE )
		{
			goto failTempl;
		}
		break;
	case DROID_ECM:
		if( apCompLists[player][COMP_ECM][psTempl->asParts[COMP_ECM]] != AVAILABLE )
		{
			goto failTempl;
		}	
		break;
	case DROID_REPAIR:
		if( apCompLists[player][COMP_REPAIRUNIT][psTempl->asParts[COMP_REPAIRUNIT]] != AVAILABLE )
		{
			goto failTempl;
		}
		break;	

	case DROID_COMMAND:
	case DROID_CONSTRUCT:	        // Constructor droid
	case DROID_PERSON:		        // person
    case DROID_CYBORG_CONSTRUCT:	// cyborg-construct thang
    case DROID_CYBORG_REPAIR:		// cyborg-repair thang
	case DROID_TRANSPORTER:	        // guess what this is!
	case DROID_DEFAULT:		        // Default droid
	case DROID_ANY:		
	default:
		DBERROR(("scrSkCanBuildTemplate: Unhandled template type"));
		break;
	}

	if (!stackPushResult(VAL_BOOL, TRUE))		// yes
	{
		return FALSE;
	}
	return TRUE;

failTempl:
	if (!stackPushResult(VAL_BOOL, FALSE))		// no
	{
		return FALSE;
	}
	return TRUE;
}
Ejemplo n.º 25
0
// ////////////////////////////////////////////////////////////////////////////
// save current keymaps to registry
BOOL saveKeyMap(void)
{
	KEY_MAPPING	*psMapping;
	FILE		*pFileHandle;
	SDWORD		count;
	STRING		name[128];

	pFileHandle = fopen("keymap.map", "wb");								// open the file
	if (!pFileHandle)
	{
		DBERROR(("Couldn't open keymap file"));
		return FALSE;
	}
	
	// write out number of entries.
	count =0;
	for(psMapping = keyMappings; psMapping; psMapping = psMapping->psNext)
	{
		count++;
	}
	if (fwrite(&count, sizeof(SDWORD), 1, pFileHandle) != 1)		
	{
		DBERROR(("Keymap Write failed"));
		return FALSE;
	}

	// version data
	if (fwrite(&buildTime, 8, 1, pFileHandle) != 1)		
	{
		DBERROR(("version Write failed"));
		return FALSE;
	}

	for(psMapping = keyMappings; psMapping; psMapping = psMapping->psNext)
	{
		// save this map.
		// name
		strcpy(name,psMapping->pName);
		if (fwrite(&name, 128 , 1, pFileHandle) != 1)		
		{
			DBERROR(("Keymap Write failed"));
			return FALSE;
		}
		
		// status
		if (fwrite(&psMapping->status, sizeof(KEY_STATUS), 1, pFileHandle) != 1)		
		{
			DBERROR(("Keymap Write failed"));
			return FALSE;
		}

		// metakey
		if (fwrite(&psMapping->metaKeyCode, sizeof(KEY_CODE), 1, pFileHandle) != 1)		
		{
			DBERROR(("Keymap Write failed"));
			return FALSE;
		}

		// subkey
		if (fwrite(&psMapping->subKeyCode, sizeof(KEY_CODE), 1, pFileHandle) != 1)		
		{
			DBERROR(("Keymap Write failed"));
			return FALSE;
		}

		// action
		if (fwrite(&psMapping->action, sizeof(KEY_ACTION), 1, pFileHandle) != 1)		
		{
			DBERROR(("Keymap Write failed"));
			return FALSE;
		}

		// function to map to!
		for(count = 0;  keyMapSaveTable[count] != NULL
					 && keyMapSaveTable[count] != psMapping->function;
			count++);
		if(keyMapSaveTable[count] == NULL)
		{
			DBERROR(("can't find keymapped function in the keymap save table!!"));
		}
	
		if (fwrite(&count, sizeof(UDWORD), 1, pFileHandle) != 1)		
		{
			DBERROR(("Keymap Write failed"));
			return FALSE;
		}
	}

	if (fclose(pFileHandle) != 0)
	{
		DBERROR(("Close failed for Keymap save"));
		return FALSE;
	}

	DBPRINTF(("Keymap written ok.\n"));
	return TRUE;	// saved ok.
}
Ejemplo n.º 26
0
/* Function to create a heap
 * Takes the size of the objects to be managed by the heap,
 * the initial number of objects to allocate and the number of
 * objects to allocate when the heap is extended.
 * Returns an initialised OBJ_HEAP structure.
 */
BOOL heapCreate(OBJ_HEAP **ppsHeap, UDWORD size, UDWORD init, UDWORD ext)
{
/*	UDWORD		i;
	FREE_OBJECT	*psCurr;
	UBYTE		*pBase;*/

#if DEBUG_HEAP
	int			Heap;
#endif
	ASSERT((size >= sizeof(FREE_OBJECT),
		"heapCreate: object is too small to be stored in free list"));

#if DEBUG_HEAP
	/* Increase the object size to store the call position */
	size += sizeof(HEAP_OBJHDR);

#endif

	/* Allocate the heap object and its memory */
	*ppsHeap = (OBJ_HEAP *)MALLOC(sizeof(OBJ_HEAP));
	if (*ppsHeap == NULL)
	{
		DBERROR(("heapCreate: Out of memory"));
		return FALSE;
	}
	(*ppsHeap)->pMemory = (UBYTE *)MALLOC(size * init);

/*
	if (PTRVALID((*ppsHeap)->pMemory,size*init)==FALSE)
	{
		DBPRINTF(("Allocated heap memory is not valid!\n"));
	}
	else
	{
		DBPRINTF(("valid\n"));
	}
*/

	if ((*ppsHeap)->pMemory == NULL)
	{
		DBERROR(("heapCreate: Out of memory"));
		return FALSE;
	}

	/* Initialise the object */
	(*ppsHeap)->objSize = size;
	(*ppsHeap)->initAlloc = init;
	(*ppsHeap)->extAlloc = ext;
	(*ppsHeap)->psExt = NULL;
	(*ppsHeap)->psBlkHeap = memGetBlockHeap();
#if DEBUG_HEAP
	(*ppsHeap)->maxUsage = 0;
	(*ppsHeap)->currUsage = 0;
	(*ppsHeap)->pFile = pCFile;
	(*ppsHeap)->line = cPos;
	(*ppsHeap)->psInUse = NULL;

	// Keep a list of all the heaps allocated
	for (Heap=0;Heap<MAXDEBUGHEAPS;Heap++)
	{
		if (HeapDebugList[Heap] == NULL)	// found an empty one
		{
			HeapDebugList[Heap]=*ppsHeap;
			break;
		}
	}
	if (HeapDebugList[Heap]!=*ppsHeap)
	{
		DBERROR(("heapCreate: MAXDEBUGHEAPS too small"));
	}

#endif

	// Now create the free object list
	heapCreateFreeList(*ppsHeap);
/*
	if (PTRVALID((*ppsHeap)->pMemory,10)==FALSE)
	{
		DBPRINTF(("Allocated heap memory is not valid!\n"));
	}
	else
	{
		DBPRINTF(("valid\n"));
	}
*/
	/*
#if DEBUG_MALLOC
	// Initialise the memory to a fixed value to check for memory overwrites
	memset((*ppsHeap)->pMemory, FREE_BYTE, size * init);
#endif

	// Now create the free object list
	(*ppsHeap)->psFree = (FREE_OBJECT *)((*ppsHeap)->pMemory);
	pBase = (*ppsHeap)->pMemory;
	for(i=0; i<init; i++)
	{
		psCurr = (FREE_OBJECT *)(pBase + i*size);
		psCurr->psNext = (FREE_OBJECT *)((UBYTE *)psCurr + size);
	}
	psCurr->psNext = NULL;
	*/

	return TRUE;
}
Ejemplo n.º 27
0
int HandleServerMessage(tSDL_vnc *vnc)
{
 int i, num_pixels, num_rectangles, num_subrectangles, hx, hy, bx, by, cx, cy, rowindex, bitindex, byteindex;
 int result, bytes_to_read, bytes_read;
 tSDL_vnc_serverMessage serverMessage;
 tSDL_vnc_serverUpdate serverUpdate;
 tSDL_vnc_serverRectangle serverRectangle;
 tSDL_vnc_serverColormap serverColormap;
 tSDL_vnc_serverText serverText;
 tSDL_vnc_serverCopyrect serverCopyrect;
 tSDL_vnc_serverRRE serverRRE;
 tSDL_vnc_serverRREdata serverRREdata;
 tSDL_vnc_serverCoRRE serverCoRRE;
 tSDL_vnc_serverCoRREdata serverCoRREdata;
 tSDL_vnc_serverHextile serverHextile;
 tSDL_vnc_serverHextileBg serverHextileBg;
 tSDL_vnc_serverHextileFg serverHextileFg;
 tSDL_vnc_serverHextileSubrects serverHextileSubrects;
 tSDL_vnc_serverHextileColored serverHextileColored;
 tSDL_vnc_serverHextileRect serverHextileRect;
 unsigned char *target;
 unsigned int *uitarget;
 unsigned char *cursormask;
 SDL_Rect trec, srec;

 DBMESSAGE ("HandleServerMessage\n");
 /* Read message type */
 result = Recv(vnc->socket,&serverMessage,1,0);
 if (result==1) {
  switch (serverMessage.messagetype) {

   case 0:
    DBMESSAGE ("Message: update\n");
    result = Recv(vnc->socket,&serverUpdate,3,0);
    if (result==3) {

     /* ??? Protocol sais U16, TightVNC server sends U8 */
     serverUpdate.rectangles=serverUpdate.rectangles & 0x00ff;
     DBMESSAGE ("Number of rectangles: %u (%04x)\n",serverUpdate.rectangles,serverUpdate.rectangles);

     num_rectangles=0;
     while (num_rectangles<serverUpdate.rectangles) {
      num_rectangles++;
      result = Recv(vnc->socket,&serverRectangle,12,0);
      if (result==12) {
       serverRectangle.x=swap_16(serverRectangle.x);
       serverRectangle.y=swap_16(serverRectangle.y);
       serverRectangle.width=swap_16(serverRectangle.width);
       serverRectangle.height=swap_16(serverRectangle.height);
       serverRectangle.encoding=swap_32(serverRectangle.encoding);
       //
       DBMESSAGE ("Rectangle %i of %i: @ %u,%u size %u,%u encoding %u\n",num_rectangles,serverUpdate.rectangles,serverRectangle.x,serverRectangle.y,serverRectangle.width,serverRectangle.height,serverRectangle.encoding);
       
       /* Sanity check values */
       if (serverRectangle.x>vnc->serverFormat.width) {
        DBMESSAGE("Bad rectangle: x=%u setting to 0\n",serverRectangle.x);
        serverRectangle.x=0;
       }
       if (serverRectangle.y>vnc->serverFormat.height) {
        DBMESSAGE("Bad rectangle: y=%u setting to 0\n",serverRectangle.y);
        serverRectangle.y=0;
       }
       if ((serverRectangle.width<=0) || (serverRectangle.width>vnc->serverFormat.width)) {
        DBMESSAGE("Bad rectangle: width=%u setting to 1\n",serverRectangle.width);
        serverRectangle.width=1;
       }
       if ((serverRectangle.height<=0) || (serverRectangle.height>vnc->serverFormat.height)) {
        DBMESSAGE("Bad rectangle: height=%u setting to 1\n",serverRectangle.height);
        serverRectangle.height=1;
       }
       
       /* Do we have a scratchbuffer */
       if (vnc->scratchbuffer) {
        /* Check size */
        if ( (!(vnc->scratchbuffer->w == serverRectangle.width)) || (!(vnc->scratchbuffer->h == serverRectangle.height)) ) {
         /* Clean out existing scratchbuffer */
         SDL_FreeSurface(vnc->scratchbuffer);
         vnc->scratchbuffer=NULL;
         DBMESSAGE ("Deleted existing scratchbuffer.\n");
        }
       }
       if (!(vnc->scratchbuffer)) {
        /* Create new scratchbuffer */
        vnc->scratchbuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,serverRectangle.width,serverRectangle.height,32,
                                         vnc->rmask,vnc->gmask,vnc->bmask,0);
        if (vnc->scratchbuffer) {                                  
         SDL_SetAlpha(vnc->scratchbuffer,0,0);
         DBMESSAGE ("Created new scratchbuffer.\n");
        } else {
         DBERROR ("Error creating scratchbuffer.\n");
         return 0;
        }
       }
       
       /* Rectangle Data */
       switch (serverRectangle.encoding) {

        case 0:
          DBMESSAGE ("RAW encoding.\n");
          bytes_to_read = serverRectangle.width*serverRectangle.height*4;
          result = Recv(vnc->socket,(unsigned char *)vnc->scratchbuffer->pixels,bytes_to_read,0);
          if (result==bytes_to_read) {
           DBMESSAGE ("Blitting %i bytes of raw pixel data.\n",bytes_to_read);
           trec.x=serverRectangle.x;
           trec.y=serverRectangle.y;
           trec.w=serverRectangle.width;
           trec.h=serverRectangle.height;
  	   SDL_LockMutex(vnc->mutex);
           SDL_BlitSurface(vnc->scratchbuffer, NULL, vnc->framebuffer, &trec);
           GrowUpdateRegion(vnc,&trec);
  	   SDL_UnlockMutex(vnc->mutex);
           DBMESSAGE ("Blitted raw pixel data.\n");
          } else {
           DBERROR ("Error on pixel data. Got %i of %i bytes.\n",result,bytes_to_read);
           return 0;
          }
         break;

        case 1:
          DBMESSAGE ("CopyRect encoding.\n");
          result = Recv(vnc->socket,&serverCopyrect,4,0);
          if (result==4) {    
           serverCopyrect.x=swap_16(serverCopyrect.x);
           serverCopyrect.y=swap_16(serverCopyrect.y);
           //
           DBMESSAGE ("Copyrect from %u,%u\n",serverCopyrect.x,serverCopyrect.y);
           //
           srec.x=serverCopyrect.x;
           srec.y=serverCopyrect.y;
           srec.w=serverRectangle.width;
           srec.h=serverRectangle.height;
           trec.x=serverRectangle.x;
           trec.y=serverRectangle.y;
           trec.w=serverRectangle.width;
           trec.h=serverRectangle.height;
    	   SDL_LockMutex(vnc->mutex);
           SDL_BlitSurface(vnc->framebuffer, &srec, vnc->scratchbuffer, NULL);
           SDL_BlitSurface(vnc->scratchbuffer, NULL, vnc->framebuffer, &trec);
           GrowUpdateRegion(vnc,&trec);
  	   SDL_UnlockMutex(vnc->mutex);
           DBMESSAGE ("Blitted copyrect pixels.\n");
          } else {
           DBERROR ("Error on copyrect data. Got %i of %i bytes.\n",result,4);
           return 0;
          }
         break;

        case 2:         
          DBMESSAGE ("RRE encoding.\n");
          result = Recv(vnc->socket,&serverRRE,8,0);
          if (result==8) {    
           serverRRE.number=swap_32(serverRRE.number);
           //
           DBMESSAGE ("RRE of %u rectangles. Background color 0x%06x\n",serverRRE.number,serverRRE.background);
           SDL_FillRect(vnc->scratchbuffer, NULL, serverRRE.background);
           /* Draw subrectangles */
           num_subrectangles=0;
           while (num_subrectangles<serverRRE.number) {
            num_subrectangles++;
            result = Recv(vnc->socket,&serverRREdata,12,0);
            if (result==12) {
             serverRREdata.x=swap_16(serverRREdata.x);
             serverRREdata.y=swap_16(serverRREdata.y);
             serverRREdata.width=swap_16(serverRREdata.width);
             serverRREdata.height=swap_16(serverRREdata.height);
             srec.x=serverRREdata.x;
             srec.y=serverRREdata.y;
             srec.w=serverRREdata.width;
             srec.h=serverRREdata.height;
	     SDL_FillRect(vnc->scratchbuffer,&srec,serverRREdata.color);
            } else {
             DBERROR ("Error on RRE data. Got %i of %i bytes.\n",result,12);
             return 0;
            } 
           }
           DBMESSAGE ("Drawn %i subrectangles.\n", num_subrectangles);
           trec.x=serverRectangle.x;
           trec.y=serverRectangle.y;
           trec.w=serverRectangle.width;
           trec.h=serverRectangle.height;
    	   SDL_LockMutex(vnc->mutex);
           SDL_BlitSurface(vnc->scratchbuffer, NULL, vnc->framebuffer, &trec);
           GrowUpdateRegion(vnc,&trec);
           SDL_UnlockMutex(vnc->mutex);
           DBMESSAGE ("Blitted RRE pixels.\n");
          } else {
           DBERROR ("Error on RRE header. Got %i of %i bytes.\n",result,8);
           return 0;
          }          
         break;

        case 4:         
          DBMESSAGE ("CoRRE encoding.\n");
          result = Recv(vnc->socket,&serverCoRRE,8,0);
          if (result==8) {    
           serverCoRRE.number=swap_32(serverCoRRE.number);
           //
           DBMESSAGE ("CoRRE of %u rectangles. Background color 0x%06x\n",serverCoRRE.number,serverCoRRE.background);
           SDL_FillRect(vnc->scratchbuffer, NULL, serverCoRRE.background);
           /* Draw subrectangles */
           num_subrectangles=0;
           while (num_subrectangles<serverCoRRE.number) {
            num_subrectangles++;
            result = Recv(vnc->socket,&serverCoRREdata,8,0);
            if (result==8) {
             srec.x=serverCoRREdata.x;
             srec.y=serverCoRREdata.y;
             srec.w=serverCoRREdata.width;
             srec.h=serverCoRREdata.height;
	     SDL_FillRect(vnc->scratchbuffer,&srec,serverCoRREdata.color);
            } else {
             DBERROR ("Error on CoRRE data. Got %i of %i bytes.\n",result,8);
             return 0;
            } 
           }
           DBMESSAGE ("Drawn %i subrectangles.\n", num_subrectangles);
           trec.x=serverRectangle.x;
           trec.y=serverRectangle.y;
           trec.w=serverRectangle.width;
           trec.h=serverRectangle.height;
    	   SDL_LockMutex(vnc->mutex);
           SDL_BlitSurface(vnc->scratchbuffer, NULL, vnc->framebuffer, &trec);
           GrowUpdateRegion(vnc,&trec);
           SDL_UnlockMutex(vnc->mutex);
           DBMESSAGE ("Blitted CoRRE pixels.\n");
          } else {
           DBERROR ("Error on CoRRE header. Got %i of %i bytes.\n",result,8);
           return 0;
          }          
         break;

        case 5:
          DBMESSAGE ("Hextile encoding.\n");
          //
          if (!(vnc->tilebuffer)) {
           /* Create new tilebuffer */
           vnc->tilebuffer = SDL_CreateRGBSurface(SDL_SWSURFACE,16,16,32,
                                                   vnc->rmask,vnc->gmask,vnc->bmask,0);
           if (vnc->tilebuffer) {                                  
            SDL_SetAlpha(vnc->tilebuffer,0,0);
            DBMESSAGE ("Created new tilebuffer.\n");
           } else {
            DBERROR ("Error creating tilebuffer.\n");
            return 0;
           }
          }
          //
          /* Iterate over all tiles */
          // row loop
          for (hy=0; hy<serverRectangle.height; hy += 16) {
           /* Determine height of tile */
           if ((hy+16)>serverRectangle.height) {
            by=serverRectangle.height % 16;
           } else {
            by=16;
           }
           // column loop
           for (hx=0; hx<serverRectangle.width; hx += 16) {
            /* Determine width of tile */
            if ((hx+16)>serverRectangle.width) {
             bx=serverRectangle.width % 16;
            } else {
             bx=16;
            }
            result = Recv(vnc->socket,&serverHextile,1,0);
            if (result==1) {    
             if (serverHextile.mode & 1) {
              /* Read raw data for tile in lines */
              bytes_to_read = bx*by*4;
              if ((bx==16) && (by==16)) {
               // complete tile
               result = Recv(vnc->socket,(unsigned char *)vnc->tilebuffer->pixels,bytes_to_read,0);
              } else {
               // partial tile
               result = 0;
               target=(unsigned char *)vnc->tilebuffer->pixels;
               rowindex=by;
               while (rowindex) {
                result +=  Recv(vnc->socket,target,bx*4,0);
                target += 16*4;
                rowindex--;
               }
              }
              if (result==bytes_to_read) {
               trec.x=hx;
               trec.y=hy;
               trec.w=16;
               trec.h=16;
               SDL_BlitSurface(vnc->tilebuffer, NULL, vnc->scratchbuffer, &trec);
              } else {
               DBERROR ("Error on pixel data. Got %i of %i bytes.\n",result,bytes_to_read);
               return 0;
              }            
             } else {
              /* no raw data */
              if (serverHextile.mode & 2) {
               /* Read background */
               result = Recv(vnc->socket,&serverHextileBg,4,0);
               if (result==4) {
                /* All OK */
               } else {
                DBERROR ("Error on Hextile background. Got %i of %i bytes.\n",result,4);
                return 0;
               }    
              }
              SDL_FillRect(vnc->tilebuffer,NULL,serverHextileBg.color);              
              if (serverHextile.mode & 4) {
               /* Read foreground */
               result = Recv(vnc->socket,&serverHextileFg,4,0);
               if (result==4) {
                /* All OK */
               } else {
                DBERROR ("Error on Hextile foreground. Got %i of %i bytes.\n",result,4);
                return 0;
               }    
              }
              if (serverHextile.mode & 8) {
               result = Recv(vnc->socket,&serverHextileSubrects,1,0);
               if (result==1) {
                /* All OK */
               } else {
                DBERROR ("Error on Hextile subrects. Got %i of %i bytes.\n",result,1);
                return 0;
               }
               /* Read subrects */
               num_subrectangles=0;
               while (num_subrectangles<serverHextileSubrects.number) {
                num_subrectangles++;
                // 
                /* Check color mode */
                if (serverHextile.mode & 16) {
                 /* Colored subrect */
                 result = Recv(vnc->socket,&serverHextileColored,6,0);
                 if (result==6) {
                  /* Render colored subrect */
                  srec.x=(serverHextileColored.xy >> 4) & 0x0f;
                  srec.y=serverHextileColored.xy & 0x0f;
                  srec.w=((serverHextileColored.wh >> 4) & 0x0f)+1;
                  srec.h=(serverHextileColored.wh & 0x0f)+1;
                  SDL_FillRect(vnc->tilebuffer,&srec,serverHextileColored.color);
                 } else {
                  DBERROR ("Error on Hextile color subrect data. Got %i of %i bytes.\n",result,6);
                  return 0;
                 }
                } else {
                 /* Non-colored Subrect */
                 result = Recv(vnc->socket,&serverHextileRect,2,0);
                 if (result==2) {
                  /* Render colored subrect */
                  srec.x=(serverHextileRect.xy >> 4) & 0x0f;
                  srec.y=serverHextileRect.xy & 0x0f;
                  srec.w=((serverHextileRect.wh >> 4) & 0x0f)+1;
                  srec.h=(serverHextileRect.wh & 0x0f)+1;
                  SDL_FillRect(vnc->tilebuffer,&srec,serverHextileFg.color);
                 } else {
                  DBERROR ("Error on Hextile subrect data. Got %i of %i bytes.\n",result,2);
                  return 0;
                 }
                } // color mode check
               } // subrect loop
               //
              } // have subrects
              /* Draw tile */
              trec.x=hx;
              trec.y=hy;
              trec.w=16;
              trec.h=16;
              SDL_BlitSurface(vnc->tilebuffer, NULL, vnc->scratchbuffer, &trec);
             } // raw data check
            } else {