nsresult
nsHTMLEditorLog::PrintSelection()
{
  nsCOMPtr<nsISelection> selection;
  nsresult result;
  PRInt32 rangeCount;

  result = GetSelection(getter_AddRefs(selection));

  NS_ENSURE_SUCCESS(result, result);

  result = selection->GetRangeCount(&rangeCount);

  NS_ENSURE_SUCCESS(result, result);

  Write("selRanges = [ ");

  PRInt32 i, j;
  nsCOMPtr<nsIDOMRange> range;
  nsCOMPtr<nsIDOMNode> startNode;
  nsCOMPtr<nsIDOMNode> endNode;
  PRInt32 startOffset, endOffset;

  for (i = 0; i < rangeCount; i++)
  {
    result = selection->GetRangeAt(i, getter_AddRefs(range));

    NS_ENSURE_SUCCESS(result, result);
    
    result = range->GetStartContainer(getter_AddRefs(startNode));

    NS_ENSURE_SUCCESS(result, result);

    NS_ENSURE_TRUE(startNode, NS_ERROR_NULL_POINTER);

    result = range->GetStartOffset(&startOffset);

    NS_ENSURE_SUCCESS(result, result);

    result = range->GetEndContainer(getter_AddRefs(endNode));

    NS_ENSURE_SUCCESS(result, result);

    NS_ENSURE_TRUE(endNode, NS_ERROR_NULL_POINTER);

    result = range->GetEndOffset(&endOffset);

    NS_ENSURE_SUCCESS(result, result);

    PRInt32 *offsetArray = 0;
    PRInt32 arrayLength = 0;

    result = GetNodeTreeOffsets(startNode, &offsetArray, &arrayLength);

    NS_ENSURE_SUCCESS(result, result);

    if (i != 0)
      Write(",\n              ");

    Write("[ [[");

    for (j = 0; j < arrayLength; j++)
    {
      if (j != 0)
        Write(", ");
      WriteInt(offsetArray[j]);
    }

    Write("], ");
    WriteInt(startOffset);
    Write("], ");

    if (startNode != endNode)
    {
      delete []offsetArray;
      offsetArray = 0;
      arrayLength = 0;

      result = GetNodeTreeOffsets(endNode, &offsetArray, &arrayLength);

      NS_ENSURE_SUCCESS(result, result);
    }

    Write("[[");

    for (j = 0; j < arrayLength; j++)
    {
      if (j != 0)
        Write(", ");
      WriteInt(offsetArray[j]);
    }

    delete []offsetArray;

    Write("], ");
    WriteInt(endOffset);
    Write("] ]");
  }

  Write(" ];\nEditorSetSelectionFromOffsets(selRanges);\n");

  Flush();

  return NS_OK;
}
Example #2
0
void
CConfigFile::WriteBool(const char* section, const char* key, bool value)
{
    WriteInt(section, key, value);
}
Example #3
0
void OTGWBase::GetVersion()
{
	char szCmd[30];
	strcpy(szCmd, "PR=A\r\n");
	WriteInt((const unsigned char*)&szCmd, (const unsigned char)strlen(szCmd));
}
Example #4
0
GDALDataset* HF2Dataset::CreateCopy( const char * pszFilename,
                                     GDALDataset *poSrcDS, 
                                     int bStrict, char ** papszOptions, 
                                     GDALProgressFunc pfnProgress,
                                     void * pProgressData )
{
/* -------------------------------------------------------------------- */
/*      Some some rudimentary checks                                    */
/* -------------------------------------------------------------------- */
    int nBands = poSrcDS->GetRasterCount();
    if (nBands == 0)
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "HF2 driver does not support source dataset with zero band.\n");
        return NULL;
    }

    if (nBands != 1)
    {
        CPLError( (bStrict) ? CE_Failure : CE_Warning, CPLE_NotSupported, 
                  "HF2 driver only uses the first band of the dataset.\n");
        if (bStrict)
            return NULL;
    }

    if( pfnProgress && !pfnProgress( 0.0, NULL, pProgressData ) )
        return NULL;

/* -------------------------------------------------------------------- */
/*      Get source dataset info                                         */
/* -------------------------------------------------------------------- */

    int nXSize = poSrcDS->GetRasterXSize();
    int nYSize = poSrcDS->GetRasterYSize();
    double adfGeoTransform[6];
    poSrcDS->GetGeoTransform(adfGeoTransform);
    int bHasGeoTransform = !(adfGeoTransform[0] == 0 &&
                             adfGeoTransform[1] == 1 &&
                             adfGeoTransform[2] == 0 &&
                             adfGeoTransform[3] == 0 &&
                             adfGeoTransform[4] == 0 &&
                             adfGeoTransform[5] == 1);
    if (adfGeoTransform[2] != 0 || adfGeoTransform[4] != 0)
    {
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "HF2 driver does not support CreateCopy() from skewed or rotated dataset.\n");
        return NULL;
    }

    GDALDataType eSrcDT = poSrcDS->GetRasterBand(1)->GetRasterDataType();
    GDALDataType eReqDT;
    float fVertPres = (float) 0.01;
    if (eSrcDT == GDT_Byte || eSrcDT == GDT_Int16)
    {
        fVertPres = 1;
        eReqDT = GDT_Int16;
    }
    else
        eReqDT = GDT_Float32;

/* -------------------------------------------------------------------- */
/*      Read creation options                                           */
/* -------------------------------------------------------------------- */
    const char* pszCompressed = CSLFetchNameValue(papszOptions, "COMPRESS");
    int bCompress = FALSE;
    if (pszCompressed)
        bCompress = CSLTestBoolean(pszCompressed);
    
    const char* pszVerticalPrecision = CSLFetchNameValue(papszOptions, "VERTICAL_PRECISION");
    if (pszVerticalPrecision)
    {
        fVertPres = (float) CPLAtofM(pszVerticalPrecision);
        if (fVertPres <= 0)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Unsupported value for VERTICAL_PRECISION. Defaulting to 0.01");
            fVertPres = (float) 0.01;
        }
        if (eReqDT == GDT_Int16 && fVertPres > 1)
            eReqDT = GDT_Float32;
    }

    const char* pszBlockSize = CSLFetchNameValue(papszOptions, "BLOCKSIZE");
    int nTileSize = 256;
    if (pszBlockSize)
    {
        nTileSize = atoi(pszBlockSize);
        if (nTileSize < 8 || nTileSize > 4096)
        {
            CPLError(CE_Warning, CPLE_AppDefined,
                     "Unsupported value for BLOCKSIZE. Defaulting to 256");
            nTileSize = 256;
        }
    }

/* -------------------------------------------------------------------- */
/*      Parse source dataset georeferencing info                        */
/* -------------------------------------------------------------------- */

    int nExtendedHeaderLen = 0;
    if (bHasGeoTransform)
        nExtendedHeaderLen += 58;
    const char* pszProjectionRef = poSrcDS->GetProjectionRef();
    int nDatumCode = -2;
    int nUTMZone = 0;
    int bNorth = FALSE;
    int nEPSGCode = 0;
    int nExtentUnits = 1;
    if (pszProjectionRef != NULL && pszProjectionRef[0] != '\0')
    {
        OGRSpatialReference oSRS;
        char* pszTemp = (char*) pszProjectionRef;
        if (oSRS.importFromWkt(&pszTemp) == OGRERR_NONE)
        {
            const char* pszValue = NULL;
            if( oSRS.GetAuthorityName( "GEOGCS|DATUM" ) != NULL
                && EQUAL(oSRS.GetAuthorityName( "GEOGCS|DATUM" ),"EPSG") )
                nDatumCode = atoi(oSRS.GetAuthorityCode( "GEOGCS|DATUM" ));
            else if ((pszValue = oSRS.GetAttrValue("GEOGCS|DATUM")) != NULL)
            {
                if (strstr(pszValue, "WGS") && strstr(pszValue, "84"))
                    nDatumCode = 6326;
            }

            nUTMZone = oSRS.GetUTMZone(&bNorth);
        }
        if( oSRS.GetAuthorityName( "PROJCS" ) != NULL
            && EQUAL(oSRS.GetAuthorityName( "PROJCS" ),"EPSG") )
            nEPSGCode = atoi(oSRS.GetAuthorityCode( "PROJCS" ));

        if( oSRS.IsGeographic() )
        {
            nExtentUnits = 0;
        }
        else
        {
            double dfLinear = oSRS.GetLinearUnits();

            if( ABS(dfLinear - 0.3048) < 0.0000001 )
                nExtentUnits = 2;
            else if( ABS(dfLinear - CPLAtof(SRS_UL_US_FOOT_CONV)) < 0.00000001 )
                nExtentUnits = 3;
            else
                nExtentUnits = 1;
        }
    }
    if (nDatumCode != -2)
        nExtendedHeaderLen += 26;
    if (nUTMZone != 0)
        nExtendedHeaderLen += 26;
    if (nEPSGCode)
        nExtendedHeaderLen += 26;

/* -------------------------------------------------------------------- */
/*      Create target file                                              */
/* -------------------------------------------------------------------- */

    CPLString osFilename;
    if (bCompress)
    {
        osFilename = "/vsigzip/";
        osFilename += pszFilename;
    }
    else
        osFilename = pszFilename;
    VSILFILE* fp = VSIFOpenL(osFilename.c_str(), "wb");
    if (fp == NULL)
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Cannot create %s", pszFilename );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Write header                                                    */
/* -------------------------------------------------------------------- */

    VSIFWriteL("HF2\0", 4, 1, fp);
    WriteShort(fp, 0);
    WriteInt(fp, nXSize);
    WriteInt(fp, nYSize);
    WriteShort(fp, (GInt16) nTileSize);
    WriteFloat(fp, fVertPres);
    float fHorizScale = (float) ((fabs(adfGeoTransform[1]) + fabs(adfGeoTransform[5])) / 2);
    WriteFloat(fp, fHorizScale);
    WriteInt(fp, nExtendedHeaderLen);

/* -------------------------------------------------------------------- */
/*      Write extended header                                           */
/* -------------------------------------------------------------------- */

    char szBlockName[16 + 1];
    if (bHasGeoTransform)
    {
        VSIFWriteL("bin\0", 4, 1, fp);
        memset(szBlockName, 0, 16 + 1);
        strcpy(szBlockName, "georef-extents");
        VSIFWriteL(szBlockName, 16, 1, fp);
        WriteInt(fp, 34);
        WriteShort(fp, (GInt16) nExtentUnits);
        WriteDouble(fp, adfGeoTransform[0]);
        WriteDouble(fp, adfGeoTransform[0] + nXSize * adfGeoTransform[1]);
        WriteDouble(fp, adfGeoTransform[3] + nYSize * adfGeoTransform[5]);
        WriteDouble(fp, adfGeoTransform[3]);
    }
    if (nUTMZone != 0)
    {
        VSIFWriteL("bin\0", 4, 1, fp);
        memset(szBlockName, 0, 16 + 1);
        strcpy(szBlockName, "georef-utm");
        VSIFWriteL(szBlockName, 16, 1, fp);
        WriteInt(fp, 2);
        WriteShort(fp, (GInt16) ((bNorth) ? nUTMZone : -nUTMZone));
    }
    if (nDatumCode != -2)
    {
        VSIFWriteL("bin\0", 4, 1, fp);
        memset(szBlockName, 0, 16 + 1);
        strcpy(szBlockName, "georef-datum");
        VSIFWriteL(szBlockName, 16, 1, fp);
        WriteInt(fp, 2);
        WriteShort(fp, (GInt16) nDatumCode);
    }
    if (nEPSGCode != 0)
    {
        VSIFWriteL("bin\0", 4, 1, fp);
        memset(szBlockName, 0, 16 + 1);
        strcpy(szBlockName, "georef-epsg-prj");
        VSIFWriteL(szBlockName, 16, 1, fp);
        WriteInt(fp, 2);
        WriteShort(fp, (GInt16) nEPSGCode);
    }

/* -------------------------------------------------------------------- */
/*      Copy imagery                                                    */
/* -------------------------------------------------------------------- */
    int nXBlocks = (nXSize + nTileSize - 1) / nTileSize;
    int nYBlocks = (nYSize + nTileSize - 1) / nTileSize;

    void* pTileBuffer = (void*) VSIMalloc(nTileSize * nTileSize * (GDALGetDataTypeSize(eReqDT) / 8));
    if (pTileBuffer == NULL)
    {
        CPLError( CE_Failure, CPLE_OutOfMemory, "Out of memory");
        VSIFCloseL(fp);
        return NULL;
    }

    int i, j, k, l;
    CPLErr eErr = CE_None;
    for(j=0;j<nYBlocks && eErr == CE_None;j++)
    {
        for(i=0;i<nXBlocks && eErr == CE_None;i++)
        {
            int nReqXSize = MIN(nTileSize, nXSize - i * nTileSize);
            int nReqYSize = MIN(nTileSize, nYSize - j * nTileSize);
            eErr = poSrcDS->GetRasterBand(1)->RasterIO(GF_Read,
                                                i * nTileSize, MAX(0, nYSize - (j + 1) * nTileSize),
                                                nReqXSize, nReqYSize,
                                                pTileBuffer, nReqXSize, nReqYSize,
                                                eReqDT, 0, 0, NULL);
            if (eErr != CE_None)
                break;

            if (eReqDT == GDT_Int16)
            {
                WriteFloat(fp, 1); /* scale */
                WriteFloat(fp, 0); /* offset */
                for(k=0;k<nReqYSize;k++)
                {
                    int nLastVal = ((short*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + 0];
                    GByte nWordSize = 1;
                    for(l=1;l<nReqXSize;l++)
                    {
                        int nVal = ((short*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + l];
                        int nDiff = nVal - nLastVal;
                        if (nDiff < -32768 || nDiff > 32767)
                        {
                            nWordSize = 4;
                            break;
                        }
                        if (nDiff < -128 || nDiff > 127)
                            nWordSize = 2;
                        nLastVal = nVal;
                    }

                    VSIFWriteL(&nWordSize, 1, 1, fp);
                    nLastVal = ((short*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + 0];
                    WriteInt(fp, nLastVal);
                    for(l=1;l<nReqXSize;l++)
                    {
                        int nVal = ((short*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + l];
                        int nDiff = nVal - nLastVal;
                        if (nWordSize == 1)
                        {
                            CPLAssert(nDiff >= -128 && nDiff <= 127);
                            char chDiff = (char)nDiff;
                            VSIFWriteL(&chDiff, 1, 1, fp);
                        }
                        else if (nWordSize == 2)
                        {
                            CPLAssert(nDiff >= -32768 && nDiff <= 32767);
                            WriteShort(fp, (short)nDiff);
                        }
                        else
                        {
                            WriteInt(fp, nDiff);
                        }
                        nLastVal = nVal;
                    }
                }
            }
            else
            {
                float fMinVal = ((float*)pTileBuffer)[0];
                float fMaxVal = fMinVal;
                for(k=1;k<nReqYSize*nReqXSize;k++)
                {
                    float fVal = ((float*)pTileBuffer)[k];
                    if (fVal < fMinVal) fMinVal = fVal;
                    if (fVal > fMaxVal) fMaxVal = fVal;
                }

                float fIntRange = (fMaxVal - fMinVal) / fVertPres;
                float fScale = (fMinVal == fMaxVal) ? 1 : (fMaxVal - fMinVal) / fIntRange;
                float fOffset = fMinVal;
                WriteFloat(fp, fScale); /* scale */
                WriteFloat(fp, fOffset); /* offset */
                for(k=0;k<nReqYSize;k++)
                {
                    float fLastVal = ((float*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + 0];
                    float fIntLastVal = (fLastVal - fOffset) / fScale;
                    CPLAssert(fIntLastVal >= -2147483648.0f && fIntLastVal <= 2147483647.0f);
                    int nLastVal = (int)fIntLastVal;
                    GByte nWordSize = 1;
                    for(l=1;l<nReqXSize;l++)
                    {
                        float fVal = ((float*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + l];
                        float fIntVal = (fVal - fOffset) / fScale;
                        CPLAssert(fIntVal >= -2147483648.0f && fIntVal <= 2147483647.0f);
                        int nVal = (int)fIntVal;
                        int nDiff = nVal - nLastVal;
                        CPLAssert((int)((GIntBig)nVal - nLastVal) == nDiff);
                        if (nDiff < -32768 || nDiff > 32767)
                        {
                            nWordSize = 4;
                            break;
                        }
                        if (nDiff < -128 || nDiff > 127)
                            nWordSize = 2;
                        nLastVal = nVal;
                    }

                    VSIFWriteL(&nWordSize, 1, 1, fp);
                    fLastVal = ((float*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + 0];
                    fIntLastVal = (fLastVal - fOffset) / fScale;
                    nLastVal = (int)fIntLastVal;
                    WriteInt(fp, nLastVal);
                    for(l=1;l<nReqXSize;l++)
                    {
                        float fVal = ((float*)pTileBuffer)[(nReqYSize - k - 1) * nReqXSize + l];
                        float fIntVal = (fVal - fOffset) / fScale;
                        int nVal = (int)fIntVal;
                        int nDiff = nVal - nLastVal;
                        CPLAssert((int)((GIntBig)nVal - nLastVal) == nDiff);
                        if (nWordSize == 1)
                        {
                            CPLAssert(nDiff >= -128 && nDiff <= 127);
                            char chDiff = (char)nDiff;
                            VSIFWriteL(&chDiff, 1, 1, fp);
                        }
                        else if (nWordSize == 2)
                        {
                            CPLAssert(nDiff >= -32768 && nDiff <= 32767);
                            WriteShort(fp, (short)nDiff);
                        }
                        else
                        {
                            WriteInt(fp, nDiff);
                        }
                        nLastVal = nVal;
                    }
                }
            }

            if( pfnProgress && !pfnProgress( (j * nXBlocks + i + 1) * 1.0 / (nXBlocks * nYBlocks), NULL, pProgressData ) )
            {
                eErr = CE_Failure;
                break;
            }
        }
    }

    CPLFree(pTileBuffer);

    VSIFCloseL(fp);

    if (eErr != CE_None)
        return NULL;

    return (GDALDataset*) GDALOpen(osFilename.c_str(), GA_ReadOnly);
}
Example #5
0
/*
================
idSaveGame::WriteRenderEntity
================
*/
void idSaveGame::WriteRenderEntity( const renderEntity_t &renderEntity ) {
	int i;

	WriteModel( renderEntity.hModel );

	WriteInt( renderEntity.entityNum );
	WriteInt( renderEntity.bodyId );

	WriteBounds( renderEntity.bounds );

	// callback is set by class's Restore function

	WriteInt( renderEntity.suppressSurfaceInViewID );
	WriteInt( renderEntity.suppressShadowInViewID );
	WriteInt( renderEntity.suppressShadowInLightID );
	WriteInt( renderEntity.allowSurfaceInViewID );

	WriteVec3( renderEntity.origin );
	WriteMat3( renderEntity.axis );

	WriteMaterial( renderEntity.customShader );
	WriteMaterial( renderEntity.referenceShader );
	WriteSkin( renderEntity.customSkin );

	if ( renderEntity.referenceSound != NULL ) {
		WriteInt( renderEntity.referenceSound->Index() );
	} else {
		WriteInt( 0 );
	}

	for( i = 0; i < MAX_ENTITY_SHADER_PARMS; i++ ) {
		WriteFloat( renderEntity.shaderParms[ i ] );
	}

	for( i = 0; i < MAX_RENDERENTITY_GUI; i++ ) {
		WriteUserInterface( renderEntity.gui[ i ], renderEntity.gui[ i ] ? renderEntity.gui[ i ]->IsUniqued() : false );
	}

	WriteFloat( renderEntity.modelDepthHack );

	WriteBool( renderEntity.noSelfShadow );
	WriteBool( renderEntity.noShadow );
	WriteBool( renderEntity.noDynamicInteractions );
	WriteBool( renderEntity.weaponDepthHack );

	WriteInt( renderEntity.forceUpdate );

#ifdef _D3XP
	WriteInt( renderEntity.timeGroup );
	WriteInt( renderEntity.xrayIndex );
#endif
}
Example #6
0
// Read a int from the ini file, increase it and then write it back to the ini file
BOOL CIni::IncreaseInt(LPCTSTR lpSection, LPCTSTR lpKey, int nIncrease, int nBase) const
{
	int nVal = GetInt(lpSection, lpKey, 0, nBase);
	nVal += nIncrease;
	return WriteInt(lpSection, lpKey, nVal, nBase);
}
Example #7
0
bool CRFLinkBase::ParseLine(const std::string &sLine)
{
	m_LastReceivedTime = mytime(NULL);

	std::vector<std::string> results;
	StringSplit(sLine, ";", results);
	if (results.size() < 2)
		return false; //not needed

	bool bHideDebugLog = (
		(sLine.find("PONG") != std::string::npos)||
		(sLine.find("PING") != std::string::npos)
		);

	int RFLink_ID = atoi(results[0].c_str());
	if (RFLink_ID != 20)
	{
		return false; //only accept RFLink->Master messages
	}

#ifdef ENABLE_LOGGING
	if (!bHideDebugLog)
		_log.Log(LOG_NORM, "RFLink: %s", sLine.c_str());
#endif

	//std::string Sensor_ID = results[1];
	if (results.size() >2)
	{
		//Status reply
		std::string Name_ID = results[2];
		if ((Name_ID.find("Nodo RadioFrequencyLink") != std::string::npos) || (Name_ID.find("RFLink Gateway") != std::string::npos))
		{
			_log.Log(LOG_STATUS, "RFLink: Controller Initialized!...");
			WriteInt("10;VERSION;\n");  // 20;3C;VER=1.1;REV=37;BUILD=01;

			//Enable DEBUG
			//write("10;RFDEBUG=ON;\n");

			//Enable Undecoded DEBUG
			//write("10;RFUDEBUG=ON;\n");
			return true;
		}
		if (Name_ID.find("VER") != std::string::npos) {
			//_log.Log(LOG_STATUS, "RFLink: %s", sLine.c_str());
			int versionlo = 0;
			int versionhi = 0;
			int revision = 0;
			int build = 0;
			if (results[2].find("VER") != std::string::npos) {
				versionhi = RFLinkGetIntStringValue(results[2]);
				versionlo = RFLinkGetIntDecStringValue(results[2]);
			}
			if (results[3].find("REV") != std::string::npos){
				revision = RFLinkGetIntStringValue(results[3]);
			}
			if (results[4].find("BUILD") != std::string::npos) {
				build = RFLinkGetIntStringValue(results[4]);
			}
			_log.Log(LOG_STATUS, "RFLink Detected, Version: %d.%d Revision: %d Build: %d", versionhi, versionlo, revision, build);

			mytime(&m_LastHeartbeatReceive);  // keep heartbeat happy
			mytime(&m_LastHeartbeat);  // keep heartbeat happy
			m_LastReceivedTime = m_LastHeartbeat;

			m_bTXokay = true; // variable to indicate an OK was received
			return true;
		}
		if (Name_ID.find("PONG") != std::string::npos) {
			//_log.Log(LOG_STATUS, "RFLink: PONG received!...");
			mytime(&m_LastHeartbeatReceive);  // keep heartbeat happy
			mytime(&m_LastHeartbeat);  // keep heartbeat happy
			m_LastReceivedTime = m_LastHeartbeat;

			m_bTXokay = true; // variable to indicate an OK was received
			return true;
		}
		if (Name_ID.find("OK") != std::string::npos) {
			//_log.Log(LOG_STATUS, "RFLink: OK received!...");
			mytime(&m_LastHeartbeatReceive);  // keep heartbeat happy
			mytime(&m_LastHeartbeat);  // keep heartbeat happy
			m_LastReceivedTime = m_LastHeartbeat;

			m_bTXokay = true; // variable to indicate an OK was received
			return true;
		}
		else if (Name_ID.find("CMD UNKNOWN") != std::string::npos) {
			_log.Log(LOG_ERROR, "RFLink: Error/Unknown command received!...");
			m_bTXokay = true; // variable to indicate an ERROR was received
			return true;
		}
	}
	if (results.size() < 4)
		return true;

	if (results[3].find("ID=") == std::string::npos)
		return false; //??

	mytime(&m_LastHeartbeatReceive);  // keep heartbeat happy
	mytime(&m_LastHeartbeat);  // keep heartbeat happy
	//_log.Log(LOG_STATUS, "RFLink: t1=%d t2=%d", m_LastHeartbeat, m_LastHeartbeatReceive);
	m_LastReceivedTime = m_LastHeartbeat;

	std::stringstream ss;
	unsigned int ID;
	ss << std::hex << results[3].substr(3);
	ss >> ID;

	int Node_ID = (ID & 0xFF00) >> 8;
	int Child_ID = ID & 0xFF;

	bool bHaveTemp = false; float temp = 0;
	bool bHaveHum = false; int humidity = 0;
	bool bHaveHumStatus = false; int humstatus = 0;
	bool bHaveBaro = false; float baro = 0;
	int baroforecast = 0;
	bool bHaveRain = false; float raincounter = 0;
	bool bHaveLux = false; float lux = 0;
	bool bHaveUV = false; float uv = 0;
    
	bool bHaveWindDir = false; int windir = 0;
	bool bHaveWindSpeed = false; float windspeed = 0;
	bool bHaveWindGust = false; float windgust = 0;
	bool bHaveWindTemp = false; float windtemp = 0;
	bool bHaveWindChill = false; float windchill = 0;

	bool bHaveRGB = false; int rgb = 0;
	bool bHaveRGBW = false; int rgbw = 0;
	bool bHaveSound = false; int sound = 0;
	bool bHaveCO2 = false; int co2 = 0;
	bool bHaveBlind = false; int blind = 0;   

	bool bHaveKWatt = false; float kwatt = 0;   
	bool bHaveWatt = false; float watt = 0;   
	bool bHaveDistance = false; float distance = 0;   
	bool bHaveMeter = false; float meter = 0;   
	bool bHaveVoltage = false; float voltage = 0;   
	bool bHaveCurrent = false; float current = 0;   
	bool bHaveImpedance = false; float impedance = 0;   
	bool bHaveSwitch = false; int switchunit = 0; 
	bool bHaveSwitchCmd = false; std::string switchcmd = ""; int switchlevel = 0;

	int BatteryLevel = 255;
	std::string tmpstr;
	int iTemp;
	for (size_t ii = 4; ii < results.size(); ii++)
	{
		if (results[ii].find("TEMP") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveTemp = true;
			if ((iTemp & 0x8000) == 0x8000) {
				//negative temp
				iTemp = -(iTemp & 0xFFF);
			}
			temp = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("HUM") != std::string::npos)
		{
			bHaveHum = true;
			humidity = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("HSTATUS") != std::string::npos)
		{
			bHaveHumStatus = true;
			humstatus = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("BARO") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveBaro = true;
			baro = float(iTemp);
		}
		else if (results[ii].find("BFORECAST") != std::string::npos)
		{
			baroforecast = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("RAIN") != std::string::npos)
		{
			bHaveRain = true;
			iTemp = RFLinkGetHexStringValue(results[ii]);
			raincounter = float(iTemp) / 10.0f; 
		}
		else if (results[ii].find("LUX") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveLux = true;
			lux = float(iTemp);
		}
		else if (results[ii].find("UV") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveUV = true;
			uv = float(iTemp);
		}
		else if (results[ii].find("BAT") != std::string::npos)
		{
			tmpstr = RFLinkGetStringValue(results[ii]);
			BatteryLevel = (tmpstr == "OK") ? 100 : 0;
		}
		else if (results[ii].find("WINDIR") != std::string::npos)
		{
			bHaveWindDir = true;
			windir = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("WINSP") != std::string::npos)
		{
			bHaveWindSpeed = true;
			iTemp = RFLinkGetHexStringValue(results[ii]); // received value is km/u
			windspeed = (float(iTemp) * 0.0277778f);   //convert to m/s
		}
		else if (results[ii].find("WINGS") != std::string::npos)
		{
			bHaveWindGust = true;
			iTemp = RFLinkGetHexStringValue(results[ii]); // received value is km/u
			windgust = (float(iTemp) * 0.0277778f);    //convert to m/s
		}
		else if (results[ii].find("WINTMP") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveWindTemp = true;
			if ((iTemp & 0x8000) == 0x8000) {
				//negative temp
				iTemp = -(iTemp & 0xFFF);
			}
			windtemp = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("WINCHL") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveWindChill = true;
			if ((iTemp & 0x8000) == 0x8000) {
				//negative temp
				iTemp = -(iTemp & 0xFFF);
			}
			windchill = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("SOUND") != std::string::npos)
		{
			bHaveSound = true;
			sound = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("CO2") != std::string::npos)
		{
			bHaveCO2 = true;
			co2 = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("RGBW") != std::string::npos)
		{
			bHaveRGBW = true;
			rgbw = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("RGB") != std::string::npos)
		{
			bHaveRGB = true;
			rgb = RFLinkGetIntStringValue(results[ii]);
		}
		else if (results[ii].find("BLIND") != std::string::npos)
		{
			bHaveBlind = true;
			blind = RFLinkGetIntStringValue(results[ii]);
		}

		else if (results[ii].find("KWATT") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveKWatt = true;
			kwatt = float(iTemp) / 1000.0f;
		}
		else if (results[ii].find("WATT") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveWatt = true;
			watt = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("DIST") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveDistance = true;
			distance = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("METER") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveMeter = true;
			meter = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("VOLT") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveVoltage = true;
			voltage = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("CURRENT") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveCurrent = true;
			current = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("IMPEDANCE") != std::string::npos)
		{
			iTemp = RFLinkGetHexStringValue(results[ii]);
			bHaveCurrent = true;
			current = float(iTemp) / 10.0f;
		}
		else if (results[ii].find("SWITCH") != std::string::npos)
		{
			bHaveSwitch = true;
			switchunit = RFLinkGetHexStringValue(results[ii]);
		}
		else if (results[ii].find("CMD") != std::string::npos)
		{
			bHaveSwitchCmd = true;
			switchcmd = RFLinkGetStringValue(results[ii]);
		}
		else if (results[ii].find("SMOKEALERT") != std::string::npos)
		{
			bHaveSwitch = true;
			switchunit = 1;
			bHaveSwitchCmd = true;
			switchcmd = RFLinkGetStringValue(results[ii]);
		}
	}

	std::string tmp_Name = results[2];
	if (bHaveTemp&&bHaveHum&&bHaveBaro)
	{
		SendTempHumBaroSensor(ID, BatteryLevel, temp, humidity, baro, baroforecast, tmp_Name);
	}
	else if (bHaveTemp&&bHaveHum)
	{
		SendTempHumSensor(ID, BatteryLevel, temp, humidity, tmp_Name);
	}
	else if (bHaveTemp)
	{
		SendTempSensor(ID, BatteryLevel, temp, tmp_Name);
	}
	else if (bHaveHum)
	{
		SendHumiditySensor(ID, BatteryLevel, humidity, tmp_Name);
	}
	else if (bHaveBaro)
	{
		SendBaroSensor(Node_ID, Child_ID, BatteryLevel, baro, baroforecast, tmp_Name);
	}

	if (bHaveLux)
	{
		SendLuxSensor(Node_ID, Child_ID, BatteryLevel, lux, tmp_Name);
	}

	if (bHaveUV)
	{
  		SendUVSensor(Node_ID, Child_ID, BatteryLevel, uv, tmp_Name);
	}
    
	if (bHaveRain)
	{
		SendRainSensor(ID, BatteryLevel, float(raincounter), tmp_Name);
	}

	if (bHaveWindDir && bHaveWindSpeed && bHaveWindGust && bHaveWindChill)
	{
		SendWind(ID, BatteryLevel, float(windir), windspeed, windgust, windtemp, windchill, bHaveWindTemp, tmp_Name);
	}
	else if (bHaveWindDir && bHaveWindGust)
	{
		SendWind(ID, BatteryLevel, float(windir), windspeed, windgust, windtemp, windchill, bHaveWindTemp, tmp_Name);
	}
	else if (bHaveWindSpeed)
	{
		SendWind(ID, BatteryLevel, float(windir), windspeed, windgust, windtemp, windchill, bHaveWindTemp, tmp_Name);
	}
    
	if (bHaveCO2)
	{
		SendAirQualitySensor((ID & 0xFF00) >> 8, ID & 0xFF, BatteryLevel, co2, tmp_Name);
	}
	if (bHaveSound)
	{
		SendSoundSensor(ID, BatteryLevel, sound, tmp_Name);
	}

	if (bHaveRGB)
	{
		//RRGGBB
		SendRGBWSwitch(Node_ID, Child_ID, BatteryLevel, rgb, false, tmp_Name);
	}
	if (bHaveRGBW)
	{
		//RRGGBBWW
		SendRGBWSwitch(Node_ID, Child_ID, BatteryLevel, rgbw, true, tmp_Name);
	}
	if (bHaveBlind)
	{
		SendBlindSensor(Node_ID, Child_ID, BatteryLevel, blind, tmp_Name);
	}

	if (bHaveKWatt&bHaveWatt)
	{
		SendKwhMeterOldWay(Node_ID, Child_ID, BatteryLevel, watt / 100.0f, kwatt, tmp_Name);
	}
	else if (bHaveKWatt)
	{
		SendKwhMeterOldWay(Node_ID, Child_ID, BatteryLevel, watt / 100.0f, kwatt, tmp_Name);
	}
	else if (bHaveWatt)
	{
		SendKwhMeterOldWay(Node_ID, Child_ID, BatteryLevel, watt / 100.0f, kwatt, tmp_Name);
	}
	if (bHaveDistance)
	{
		SendDistanceSensor(Node_ID, Child_ID, BatteryLevel, distance, tmp_Name);
	}
	if (bHaveMeter)
	{
		SendMeterSensor(Node_ID, Child_ID, BatteryLevel, meter, tmp_Name);
	}
	if (bHaveVoltage)
	{
		SendVoltageSensor(Node_ID, Child_ID, BatteryLevel, voltage, tmp_Name);
	}
	if (bHaveCurrent)
	{
		SendCurrentSensor(ID, BatteryLevel, current, 0, 0, tmp_Name);
	}
	if (bHaveImpedance)
	{
		SendPercentageSensor(Node_ID, Child_ID, BatteryLevel, impedance, tmp_Name);
	}
	if (bHaveSwitch && bHaveSwitchCmd)
	{
		std::string switchType = results[2];
		SendSwitchInt(ID, switchunit, BatteryLevel, switchType, switchcmd, switchlevel);
	}

    return true;
}
Example #8
0
bool CRFLinkBase::WriteToHardware(const char *pdata, const unsigned char length)
{
	const _tGeneralSwitch *pSwitch = reinterpret_cast<const _tGeneralSwitch*>(pdata);

	if ((pSwitch->type != pTypeGeneralSwitch) && (pSwitch->type != pTypeLimitlessLights))
		return false; //only allowed to control regular switches and MiLight

	//_log.Log(LOG_ERROR, "RFLink: switch type: %d", pSwitch->subtype);
	std::string switchtype = GetGeneralRFLinkFromInt(rfswitches, pSwitch->subtype);
	if (switchtype.empty())
	{
		_log.Log(LOG_ERROR, "RFLink: trying to send unknown switch type: %d", pSwitch->subtype);
		return false;
	}
	//_log.Log(LOG_ERROR, "RFLink: subtype: %d", pSwitch->subtype);

	if (pSwitch->type == pTypeGeneralSwitch) {
		std::string switchcmnd = GetGeneralRFLinkFromInt(rfswitchcommands, pSwitch->cmnd);

        // check setlevel command
        if (pSwitch->cmnd == gswitch_sSetLevel) {
           // Get device level to set
			float fvalue = (15.0f / 100.0f)*float(pSwitch->level);
			if (fvalue > 15.0f)
				fvalue = 15.0f; //99 is fully on
			int svalue = round(fvalue);        
			//_log.Log(LOG_ERROR, "RFLink: level: %d", svalue);
	        char buffer[50] = {0};
			sprintf(buffer, "%d", svalue);
			switchcmnd = buffer;
	    }    
    
		if (switchcmnd.empty()) {
			_log.Log(LOG_ERROR, "RFLink: trying to send unknown switch command: %d", pSwitch->cmnd);
			return false;
		}

		//Build send string
		std::stringstream sstr;
		//10;NewKaku;00c142;1;ON;     => protocol;address;button number;action (ON/OFF/ALLON/ALLOFF/15 -11-15 for dim level)

		sstr << "10;" << switchtype << ";" << std::hex << std::nouppercase << std::setw(6) << std::setfill('0') << pSwitch->id << ";" << std::hex << std::nouppercase << pSwitch->unitcode << ";" << switchcmnd;
//#ifdef _DEBUG
		_log.Log(LOG_STATUS, "RFLink Sending: %s", sstr.str().c_str());
//#endif
		sstr << "\n";
		m_bTXokay = false; // clear OK flag
		WriteInt(sstr.str());
		time_t atime = mytime(NULL);
		time_t btime = mytime(NULL);
    
		// Wait for an OK response from RFLink to make sure the command was executed
		while (m_bTXokay == false) {
			if (btime-atime > 4) {
				_log.Log(LOG_ERROR, "RFLink: TX time out...");
				return false;
			}
			btime = mytime(NULL);
		}
		return true;
	}
	else {		// RFLink Milight extension
		_tLimitlessLights *pLed = (_tLimitlessLights*)pdata;

		//_log.Log(LOG_ERROR, "RFLink: ledtype: %d", pLed->type);			// type limitlessled
		//_log.Log(LOG_ERROR, "RFLink: subtype: %d", pLed->subtype);		// rgbw/rgb/white?
		//_log.Log(LOG_ERROR, "RFLink: id: %d", pLed->id);				// id
		//_log.Log(LOG_ERROR, "RFLink: unit: %d", pLed->dunit);			// unit 0=All, 1=Group1,2=Group2,3=Group3,4=Group4
		//_log.Log(LOG_ERROR, "RFLink: command: %d", pLed->command);		// command
		//_log.Log(LOG_ERROR, "RFLink: value: %d", pLed->value);			// brightness/color value

		const int m_LEDType = pLed->type;
		std::string switchtype = GetGeneralRFLinkFromInt(rfswitches, 0x57);
		std::string switchcmnd = GetGeneralRFLinkFromInt(rfswitchcommands, pLed->command);
		unsigned int m_colorbright = 0;

		switch (pLed->command){
		case Limitless_LedOn:
			switchcmnd = "ON";
			break;
		case Limitless_LedOff:
			switchcmnd = "OFF";
			break;
		case Limitless_SetRGBColour:
			{
			m_colorbright = m_colorbright & 0xff;
			m_colorbright = (((unsigned char)pLed->value) << 8) + m_colorbright;
			switchcmnd = "COLOR";
			}
			break;
		case Limitless_DiscoSpeedSlower:
			switchcmnd = "DISCO-";
			break;
		case Limitless_DiscoSpeedFaster:
			switchcmnd = "DISCO+";
			break;
		case Limitless_DiscoMode:
			switchcmnd = "MODE";
			break;
		case Limitless_SetColorToWhite:
			switchcmnd = "ALLON";
			break;
		case Limitless_SetBrightnessLevel:
			{
			//brightness (0-100) converted to 0x00-0xff
			int m_brightness = (unsigned char)pLed->value;
			m_brightness = (m_brightness * 255) / 100;
			m_brightness = m_brightness & 0xff;
			m_colorbright = m_colorbright & 0xff00;
			m_colorbright = m_colorbright + (unsigned char)m_brightness;
			switchcmnd = "BRIGHT";
			}
			break;

		// need work:
		case Limitless_SetBrightUp:
			switchcmnd = "BRIGHT";
			break;
		case Limitless_SetBrightDown:
			switchcmnd = "BRIGHT";
			break;
		case Limitless_DiscoSpeedFasterLong:
			switchcmnd = "DISCO+";
			break;
		case Limitless_RGBDiscoNext:
			switchcmnd = "DISCO+";
			break;
		case Limitless_RGBDiscoPrevious:
			switchcmnd = "DISCO-";
			break;
		default: 
			_log.Log(LOG_ERROR, "RFLink: trying to send unknown led switch command: %d", pLed->command);
			return false;
		}

		//Build send string
		std::stringstream sstr;
		//10;MiLightv1;1234;01;5566;ON;     => protocol;address;unit number;color&brightness;action (ON/OFF/ALLON/ALLOFF etc)

		sstr << "10;" << switchtype << ";" << std::hex << std::nouppercase << std::setw(4) << std::setfill('0') << pLed->id << ";" << std::setw(2) << std::setfill('0') << int(pLed->dunit) << ";" << std::hex << std::nouppercase << std::setw(4) << m_colorbright << ";" << switchcmnd;
		//#ifdef _DEBUG
		_log.Log(LOG_STATUS, "RFLink Sending: %s", sstr.str().c_str());
		//#endif
		sstr << "\n";
		m_bTXokay = false; // clear OK flag
		WriteInt(sstr.str());
		time_t atime = mytime(NULL);
		time_t btime = mytime(NULL);

		// Wait for an OK response from RFLink to make sure the command was executed
		while (m_bTXokay == false) {
			if (btime - atime > 4) {
				_log.Log(LOG_ERROR, "RFLink: TX time out...");
				return false;
			}
			btime = mytime(NULL);
		}
		return true;
	}
}
Example #9
0
// Write a boolean value to the ini file
BOOL CIni::WriteBool(LPCTSTR lpSection, LPCTSTR lpKey, BOOL bValue) const
{
	return WriteInt(lpSection, lpKey, bValue ? 1 : 0, BASE_DECIMAL);
}
Example #10
0
void NIBWriter::WriteData()
{
    fwrite("NIBArchive", 10, 1, fpOut);
    int headerPos = ftell(fpOut);

    NIBHeader header = { 0 };
    fwrite(&header, sizeof(header), 1, fpOut);


    //  Write out class names
    StringCombiner classNames;
    header._classNamesOffset = ftell(fpOut);

    for ( int i = 0; i < _outputObjects.size(); i ++ ) {
        XIBObject *pObject = _outputObjects[i];
        if (pObject->_outputClassName == NULL) {
            printf("Unable to find class mapping for required object <%s>\n", pObject->_node.name());
            TELEMETRY_EVENT_DATA(L"MissingClassMapping", pObject->_node.name());
            TELEMETRY_FLUSH();

            exit(-1);
        }
        pObject->_outputClassNameIdx = classNames.AddString(pObject->_outputClassName);
        pObject->_outputObjectIdx = i;
    }

    for ( int i = 0; i < classNames._numStrings; i ++ ) {
        char *pName = classNames._stringTable[i];
        int len = strlen(pName) + 1;
        WriteInt(len, 2);
        if ( len == 0x1b ) {
            int filler = 6;
            fwrite(&filler, 1, 4, fpOut);
        }
        fwrite(pName, 1, len, fpOut);

        header._numClassNames ++;
    }

    //  Write out key names
    StringCombiner keyNames;
    header._keyNamesOffset = ftell(fpOut);
    for ( int i = 0; i < _outputObjects.size(); i ++ ) {
        XIBObject *pObject = _outputObjects[i];

        for ( int j = 0; j < pObject->_outputMembers.size(); j ++ ) {
            pObject->_outputMembers[j]->_outputNameIdx = keyNames.AddString(pObject->_outputMembers[j]->_name);
        }
    }

    for ( int i = 0; i < keyNames._numStrings; i ++ ) {
        char *pName = keyNames._stringTable[i];
        int len = strlen(pName) + 1;
        WriteInt(len, 1);
        fwrite(pName, 1, len, fpOut);

        header._numKeyNames ++;
    }

    //  Write out items
    header._itemsOffset = ftell(fpOut);
    for ( int i = 0; i < _outputObjects.size(); i ++ ) {
        XIBObject *pObject = _outputObjects[i];

        pObject->_outputMembersIdx = header._numItems;

        for ( int j = 0; j < pObject->_outputMembers.size(); j ++ ) {
            XIBMember *cur = pObject->_outputMembers[j];

            //  Write out name index
            WriteInt(cur->_outputNameIdx, 1);
            /*(
            printf("%s\n", cur->_name);
            if ( strcmp(cur->_name, "UICenter") == 0 ) {
                printf("Hi\n");
            }
            */

            //  Write out item type + data
            cur->_obj->WriteData(this);
            header._numItems ++;
        }
    }

    //  Write out objects
    header._objectsOffset = ftell(fpOut);
    for ( int i = 0; i < _outputObjects.size(); i ++ ) {
        XIBObject *pObject = _outputObjects[i];

        //  Write out class name index
        WriteInt(pObject->_outputClassNameIdx, 1);

        //  Item index
        WriteInt(pObject->_outputMembersIdx, 1);

        //  Item count
        WriteInt(pObject->_outputMembers.size(), 1);

        header._numObjects ++;
    }

    fseek(fpOut, headerPos, SEEK_SET);
    fwrite(&header, sizeof(header), 1, fpOut);
}
Example #11
0
void CSimpleFile::WriteString(CString Str)
{
	int Len = Str.GetLength();
	WriteInt(Len);
	Write(CT2CA(Str).m_psz, Len);
}
void
SocketConnection::WriteToBuffer(MapNode *mapnode,
                                bool write,
                                int id,
                                int& totalLen,
                                int &totalSize)
{
    /// loop through mapnode
    /// don't do anything for pure mapnode structures..
    if(mapnode->Type() != 0)
    {
        if(write)
            (totalLen < 256)? WriteUnsignedChar((unsigned char)id) : WriteInt(id);
        else
             ++totalLen;

        if(mapnode->Type() == MapNode::BOOL_TYPE)
        {
            if(write)
                WriteChar( mapnode->AsBool()? 1 : 0);
            else
                totalSize += srcFormat.CharSize();
        }
        else if(mapnode->Type() == MapNode::CHAR_TYPE)
        {
            if(write)
                WriteChar( mapnode->AsChar() );
            else
                totalSize += srcFormat.CharSize();
        }
        else if(mapnode->Type() == MapNode::UNSIGNED_CHAR_TYPE)
        {
            if(write)
                WriteUnsignedChar( mapnode->AsUnsignedChar() );
            else
                totalSize += srcFormat.CharSize();
        }
        else if(mapnode->Type() == MapNode::INT_TYPE)
        {
            if(write)
                WriteInt( mapnode->AsInt() );
            else
                totalSize += srcFormat.IntSize();
        }
        else if(mapnode->Type() == MapNode::FLOAT_TYPE)
        {
            if(write)
                WriteFloat( mapnode->AsFloat() );
            else
                totalSize += srcFormat.FloatSize();
        }
        else if(mapnode->Type() == MapNode::DOUBLE_TYPE)
        {
            if(write)
                WriteDouble( mapnode->AsDouble() );
            else
                totalSize += srcFormat.DoubleSize();
        }
        else if(mapnode->Type() == MapNode::LONG_TYPE)
        {
            if(write)
                WriteLong( mapnode->AsLong() );
            else
                totalSize += srcFormat.LongSize();
        }
        else if(mapnode->Type() == MapNode::STRING_TYPE)
        {
            if(write)
                WriteString( mapnode->AsString() );
            else
                totalSize += srcFormat.CharSize()*(mapnode->AsString().size() + 1);
        }
        else if(mapnode->Type() == MapNode::BOOL_VECTOR_TYPE)
        {
            const boolVector& vec = mapnode->AsBoolVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteChar( vec[i]? 1 : 0);
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.CharSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::CHAR_VECTOR_TYPE)
        {
            const charVector& vec = mapnode->AsCharVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteChar( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.CharSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::UNSIGNED_CHAR_VECTOR_TYPE)
        {
            const unsignedCharVector& vec = mapnode->AsUnsignedCharVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteUnsignedChar( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.CharSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::INT_VECTOR_TYPE)
        {
            const intVector& vec = mapnode->AsIntVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteInt( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.IntSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::FLOAT_VECTOR_TYPE)
        {
            const floatVector& vec = mapnode->AsFloatVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteFloat( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.FloatSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::DOUBLE_VECTOR_TYPE)
        {
            const doubleVector& vec = mapnode->AsDoubleVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteDouble( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.DoubleSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::LONG_VECTOR_TYPE)
        {
            const longVector& vec = mapnode->AsLongVector();

//            if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteLong( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    totalSize += (vec.size()*srcFormat.LongSize());
                }
            }
        }
        else if(mapnode->Type() == MapNode::STRING_VECTOR_TYPE)
        {
            const stringVector& vec = mapnode->AsStringVector();
            //std::cout << "String vector type : " << vec.size() << std::endl;
            //if(vec.size() > 0)
            {
                if(write)
                {
                    WriteInt(vec.size());
                    for(int i = 0; i < vec.size(); ++i)
                        WriteString( vec[i] );
                }
                else
                {
                    //std::cout << mapnode->TypeName() << " " << str << std::endl;
                    totalSize += srcFormat.IntSize();
                    for(int i = 0; i < vec.size(); ++i)
                        totalSize += (vec[i].size() + 1)*srcFormat.CharSize();
                }
            }
        }
        else
        {
            std::cout << "not handled: "
                      << mapnode->TypeName()
                      << std::endl;
        }
    }

    stringVector names;
    mapnode->GetEntryNames(names);
    for(int i = 0; i < names.size(); ++i)
    {
        //std::cout << "** " << names[i] << std::endl;
        std::string& name = names[i];
        MapNode* mc = mapnode->GetEntry(names[i]);

        if(mc->Type() == 0)
        {
            //JSONNode& child = data->operator [](name);
            //WriteToBuffer(mc,&child,write,0,totalLen,totalSize);
            WriteToBuffer(mc,write,0,totalLen,totalSize);
        }
        else
        {
            int id = atoi(name.c_str());//data->operator [](name).GetInt();
            //std::cout << name << " " << id << " " << names[i] << std::endl;
            WriteToBuffer(mc,write,id,totalLen,totalSize);
        }
    }
}
Example #13
0
bool ParticleEffect2D::Save(Serializer& dest) const
{
    if (!sprite_)
        return false;

    XMLFile xmlFile(context_);
    XMLElement rootElem = xmlFile.CreateRoot("particleEmitterConfig");

    String fileName = GetFileNameAndExtension(sprite_->GetName());
    rootElem.CreateChild("texture").SetAttribute("name", fileName);

    WriteVector2(rootElem, "sourcePosition", Vector2::ZERO);
    WriteVector2(rootElem, "sourcePositionVariance", sourcePositionVariance_);

    WriteFloat(rootElem, "speed", speed_);
    WriteFloat(rootElem, "speedVariance", speedVariance_);

    WriteFloat(rootElem, "particleLifeSpan", particleLifeSpan_);
    WriteFloat(rootElem, "particleLifespanVariance", particleLifespanVariance_);

    WriteFloat(rootElem, "angle", angle_);
    WriteFloat(rootElem, "angleVariance", angleVariance_);

    WriteVector2(rootElem, "gravity", gravity_);

    WriteFloat(rootElem, "radialAcceleration", radialAcceleration_);
    WriteFloat(rootElem, "tangentialAcceleration", tangentialAcceleration_);

    WriteFloat(rootElem, "radialAccelVariance", radialAccelVariance_);
    WriteFloat(rootElem, "tangentialAccelVariance", tangentialAccelVariance_);

    WriteColor(rootElem, "startColor", startColor_);
    WriteColor(rootElem, "startColorVariance", startColorVariance_);

    WriteColor(rootElem, "finishColor", finishColor_);
    WriteColor(rootElem, "finishColorVariance", finishColorVariance_);

    WriteInt(rootElem, "maxParticles", maxParticles_);

    WriteFloat(rootElem, "startParticleSize", startParticleSize_);
    WriteFloat(rootElem, "startParticleSizeVariance", startParticleSizeVariance_);

    WriteFloat(rootElem, "finishParticleSize", finishParticleSize_);
    // Typo in pex file
    WriteFloat(rootElem, "FinishParticleSizeVariance", finishParticleSizeVariance_);

    float duration = duration_;
    if (duration == M_INFINITY)
        duration = -1.0f;
    WriteFloat(rootElem, "duration", duration);
    WriteInt(rootElem, "emitterType", (int)emitterType_);

    WriteFloat(rootElem, "maxRadius", maxRadius_);
    WriteFloat(rootElem, "maxRadiusVariance", maxRadiusVariance_);
    WriteFloat(rootElem, "minRadius", minRadius_);
    WriteFloat(rootElem, "minRadiusVariance", minRadiusVariance_);

    WriteFloat(rootElem, "rotatePerSecond", rotatePerSecond_);
    WriteFloat(rootElem, "rotatePerSecondVariance", rotatePerSecondVariance_);

    WriteInt(rootElem, "blendFuncSource", srcBlendFuncs[blendMode_]);
    WriteInt(rootElem, "blendFuncDestination", destBlendFuncs[blendMode_]);

    WriteFloat(rootElem, "rotationStart", rotationStart_);
    WriteFloat(rootElem, "rotationStartVariance", rotationStartVariance_);

    WriteFloat(rootElem, "rotationEnd", rotationEnd_);
    WriteFloat(rootElem, "rotationEndVariance", rotationEndVariance_);

    return xmlFile.Save(dest);
}
Example #14
0
Settings::~Settings()
{
  LangStyle*ls;
  for (ls=languages; ls->name; ls++) {
    int i;
    SaveStyles(style_reg, ls->name, ls->styles);
    style_reg->writeStringEntry(ls->name,"FileMask",ls->mask?ls->mask:"");
    style_reg->writeStringEntry(ls->name,"ShebangApps",ls->apps?ls->apps:"");
    style_reg->writeIntEntry(ls->name,"TabPolicy", ls->tabs);
    style_reg->writeIntEntry(ls->name,"TabWidth", ls->tabwidth);
    for (i=0; ls->words[i]; i++) {
      char key[32];
      snprintf(key, sizeof(key)-1, "words_%d", i+1);
#ifdef FOX_1_6
    // fox 1.6 will choke reading string entries > 2000 chars
    char buf[1952];
    memset(buf,0,sizeof(buf));
    strncpy(buf, ls->words[i], sizeof(buf)-1);
    style_reg->writeStringEntry(ls->name,key,buf);
#else
    style_reg->writeStringEntry(ls->name,key,ls->words[i]);
#endif
    }
  }
  SaveStyles(style_reg, global_sect, GlobalStyle);
  SaveStyle(style_reg, global_sect,&WhiteSpaceStyle);
  SaveStyle(style_reg, global_sect,&CaretLineStyle);
  SaveStyle(style_reg, global_sect,&RightMarginStyle);

  reg->deleteSection(keys_sect);
  reg->deleteSection(tbar_sect);

  WriteInt(ShowStatusBar);
  WriteInt(ShowWhiteSpace);
  WriteInt(ShowOutputPane);
  bool InvertColors=ColorFuncs::ColorsInverted();
  WriteInt(InvertColors);
  WriteInt(SplitView);
  WriteInt(OutputPaneHeight);
  WriteInt(ShowLineNumbers);
  WriteInt(ShowToolbar);
  WriteInt(SmartHome);
  WriteInt(WrapAwareHomeEnd);
  WriteInt(AutoIndent);
  WriteInt(BraceMatch);
  WriteInt(UseTabs);
  WriteInt(CaretPastEOL);
  WriteInt(TabWidth);
  WriteInt(IndentWidth);
  WriteInt(CaretWidth);
  WriteInt(RightEdgeColumn);
  WriteInt(ShowRightEdge);
  WriteInt(ShowIndentGuides);
  WriteInt(ShowCaretLine);
  WriteInt(SmoothScroll);
  WriteInt(WheelLines);
  WriteInt(SearchWrap);
  WriteInt(SearchGui);
  WriteInt(SearchVerbose);
  WriteInt(SearchOptions);
  WriteInt(ZoomFactor);
  WriteInt(MaxFiles);
  WriteInt(PromptCloseMultiMenu);
  WriteInt(PromptCloseMultiExit);
  WriteInt(WatchExternChanges);
  WriteInt(Autosave);
  WriteInt(AutosaveInterval);
  WriteInt(SaveBeforeFilterSel);
  WriteInt(SaveBeforeInsCmd);
  WriteInt(SaveBeforeExecCmd);
  WriteInt(WhitespaceShowsEOL);
  WriteInt(DefaultFileFormat);
  WriteInt(WrapToolbar);
  WriteInt(WordWrap);
  WriteInt(ToolbarButtonSize);
  WriteInt(Left);
  WriteInt(Top);
  WriteInt(Width);
  WriteInt(Height);
  WriteInt(Maximize);
  WriteInt(FontSize);
  WriteInt(FontAscent);
  WriteInt(FontDescent);
  WriteInt(DefaultToAscii);
  WriteInt(DefaultToSbcs);
  WriteInt(KeepFileFilter);
  WriteInt(FileFilterIndex);
  WriteInt(FileOpenMulti);
  WriteInt(TabTitleMaxWidth);

  if (!(DocTabPosition && strchr("TBLR",DocTabPosition))) { DocTabPosition='T'; }
  char dtp[2]={DocTabPosition,'\0'};
  reg->writeStringEntry(view_sect,"DocTabPosition",dtp);

  if (!(DocTabsPacked && strchr("UPA",DocTabsPacked))) { DocTabsPacked='T'; }
  dtp[0]=DocTabsPacked;
  reg->writeStringEntry(view_sect,"DocTabsPacked",dtp);

  WriteStr(FontName);
  WriteStr(FileFilters);
  WriteStr(ShellCommand);

  FreeAllKeywordLists();

  mnumgr->WriteMenuSpecs(reg,keys_sect);
  mnumgr->WriteToolbarButtons(reg,tbar_sect);
  mnumgr->WritePopupMenu(reg,popup_sect);
  SaveErrorPatterns(reg);
  SaveSysIncPaths(reg);

  if (!style_reg->unparseFile(style_file)) {
    FXMessageBox::error(app,MBOX_OK,
      _("Configuration error"), "%s \n%s\n%s", _("Failed to save settings to"),
      style_file.text(), SystemErrorStr()
    );
  }
  delete style_reg;
  ini_sort(style_file.text());
}