empty_output_buffer (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; size_t bytes_to_write = OUTPUT_BUF_SIZE; #ifdef IPPJ_HUFF /* * The Intel IPP performance libraries do not necessarily fill up * the whole output buffer with each compression pass, so we only * want to write out the parts of the buffer that are full. */ if(! cinfo->progressive_mode) { bytes_to_write -= dest->pub.free_in_buffer; } #endif if (VSIFWriteL(dest->buffer, 1, bytes_to_write, dest->outfile) != bytes_to_write) ERREXIT(cinfo, JERR_FILE_WRITE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; }
int NITFDESExtractShapefile(NITFDES* psDES, const char* pszRadixFileName) { NITFSegmentInfo* psSegInfo; const char* apszExt[3]; int anOffset[4]; int iShpFile; char* pszFilename; if ( CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE_USE") == NULL ) return FALSE; psSegInfo = psDES->psFile->pasSegmentInfo + psDES->iSegment; apszExt[0] = CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE1_NAME"); anOffset[0] = atoi(CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE1_START")); apszExt[1] = CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE2_NAME"); anOffset[1] = atoi(CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE2_START")); apszExt[2] = CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE3_NAME"); anOffset[2] = atoi(CSLFetchNameValue(psDES->papszMetadata, "NITF_SHAPE3_START")); anOffset[3] = (int) psSegInfo->nSegmentSize; for(iShpFile = 0; iShpFile < 3; iShpFile ++) { if (!EQUAL(apszExt[iShpFile], "SHP") && !EQUAL(apszExt[iShpFile], "SHX") && !EQUAL(apszExt[iShpFile], "DBF")) return FALSE; if (anOffset[iShpFile] < 0 || anOffset[iShpFile] >= anOffset[iShpFile+1]) return FALSE; } pszFilename = (char*) VSIMalloc(strlen(pszRadixFileName) + 4 + 1); if (pszFilename == NULL) return FALSE; for(iShpFile = 0; iShpFile < 3; iShpFile ++) { VSILFILE* fp; GByte* pabyBuffer; int nSize = anOffset[iShpFile+1] - anOffset[iShpFile]; pabyBuffer = (GByte*) VSIMalloc(nSize); if (pabyBuffer == NULL) { VSIFree(pszFilename); return FALSE; } VSIFSeekL(psDES->psFile->fp, psSegInfo->nSegmentStart + anOffset[iShpFile], SEEK_SET); if (VSIFReadL(pabyBuffer, 1, nSize, psDES->psFile->fp) != nSize) { VSIFree(pabyBuffer); VSIFree(pszFilename); return FALSE; } sprintf(pszFilename, "%s.%s", pszRadixFileName, apszExt[iShpFile]); fp = VSIFOpenL(pszFilename, "wb"); if (fp == NULL) { VSIFree(pabyBuffer); VSIFree(pszFilename); return FALSE; } VSIFWriteL(pabyBuffer, 1, nSize, fp); VSIFCloseL(fp); VSIFree(pabyBuffer); } VSIFree(pszFilename); return TRUE; }
void GTMTrackLayer::WriteFeatureAttributes( OGRFeature *poFeature ) { char* psztrackname = nullptr; int type = 1; unsigned int color = 0; for (int i = 0; i < poFeatureDefn->GetFieldCount(); ++i) { OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn( i ); if( poFeature->IsFieldSetAndNotNull( i ) ) { const char* l_pszName = poFieldDefn->GetNameRef(); /* track name */ if (STARTS_WITH(l_pszName, "name")) { CPLFree(psztrackname); psztrackname = CPLStrdup( poFeature->GetFieldAsString( i ) ); } /* track type */ else if (STARTS_WITH(l_pszName, "type")) { type = poFeature->GetFieldAsInteger( i ); // Check if it is a valid type if (type < 1 || type > 30) type = 1; } /* track color */ else if (STARTS_WITH(l_pszName, "color")) { color = (unsigned int) poFeature->GetFieldAsInteger( i ); if (color > 0xFFFFFF) color = 0xFFFFFFF; } } } if (psztrackname == nullptr) psztrackname = CPLStrdup( "" ); const size_t trackNameLength = strlen(psztrackname); const size_t bufferSize = 14 + trackNameLength; void* pBuffer = CPLMalloc(bufferSize); void* pBufferAux = pBuffer; /* Write track string name size to buffer */ appendUShort(pBufferAux, (unsigned short) trackNameLength); pBufferAux = (char*)pBufferAux + 2; /* Write track name */ memcpy((char*)pBufferAux, psztrackname, trackNameLength); pBufferAux = (char*)pBufferAux + trackNameLength; /* Write track type */ appendUChar(pBufferAux, (unsigned char) type); pBufferAux = (char*)pBufferAux + 1; /* Write track color */ appendInt(pBufferAux, color); pBufferAux = (char*)pBufferAux + 4; /* Write track scale */ appendFloat(pBufferAux, 0); pBufferAux = (char*)pBufferAux + 4; /* Write track label */ appendUChar(pBufferAux, 0); pBufferAux = (char*)pBufferAux + 1; /* Write track layer */ appendUShort(pBufferAux, 0); VSIFWriteL(pBuffer, bufferSize, 1, poDS->getTmpTracksFP()); poDS->incNumTracks(); CPLFree(psztrackname); CPLFree(pBuffer); }
GDALDataset * RCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, CPL_UNUSED int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { const int nBands = poSrcDS->GetRasterCount(); const int nXSize = poSrcDS->GetRasterXSize(); const int nYSize = poSrcDS->GetRasterYSize(); const bool bASCII = CPLFetchBool(papszOptions, "ASCII", false); const bool bCompressed = CPLFetchBool(papszOptions, "COMPRESS", !bASCII); // Some some rudimentary checks. // Setup the filename to actually use. We prefix with // /vsigzip/ if we want compressed output. const CPLString osAdjustedFilename = std::string(bCompressed ? "/vsigzip/" : "") + pszFilename; // Create the file. VSILFILE *fp = VSIFOpenL(osAdjustedFilename, "wb"); if( fp == NULL ) { CPLError(CE_Failure, CPLE_OpenFailed, "Unable to create file %s.", pszFilename); return NULL; } // Write header with version, etc. if( bASCII ) { const char *pszHeader = "RDA2\nA\n"; VSIFWriteL(pszHeader, 1, strlen(pszHeader), fp); } else { const char *pszHeader = "RDX2\nX\n"; VSIFWriteL(pszHeader, 1, strlen(pszHeader), fp); } RWriteInteger(fp, bASCII, 2); RWriteInteger(fp, bASCII, 133377); RWriteInteger(fp, bASCII, 131840); // Establish the primary pairlist with one component object. RWriteInteger(fp, bASCII, 1026); RWriteInteger(fp, bASCII, 1); // Write the object name. Eventually we should derive this // from the filename, possible with override by a creation option. RWriteString(fp, bASCII, "gg"); // For now we write the raster as a numeric array with attributes (526). RWriteInteger(fp, bASCII, 526); RWriteInteger(fp, bASCII, nXSize * nYSize * nBands); // Write the raster data. CPLErr eErr = CE_None; double *padfScanline = static_cast<double *>(CPLMalloc(nXSize * sizeof(double))); for( int iBand = 0; iBand < nBands; iBand++ ) { GDALRasterBand *poBand = poSrcDS->GetRasterBand(iBand + 1); for( int iLine = 0; iLine < nYSize && eErr == CE_None; iLine++ ) { eErr = poBand->RasterIO(GF_Read, 0, iLine, nXSize, 1, padfScanline, nXSize, 1, GDT_Float64, sizeof(double), 0, NULL); if( bASCII ) { for( int iValue = 0; iValue < nXSize; iValue++ ) { char szValue[128] = { '\0' }; CPLsnprintf(szValue, sizeof(szValue), "%.16g\n", padfScanline[iValue]); VSIFWriteL(szValue, 1, strlen(szValue), fp); } } else { for( int iValue = 0; iValue < nXSize; iValue++ ) CPL_MSBPTR64(padfScanline + iValue); VSIFWriteL(padfScanline, 8, nXSize, fp); } if( eErr == CE_None && !pfnProgress((iLine + 1) / static_cast<double>(nYSize), NULL, pProgressData) ) { eErr = CE_Failure; CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated CreateCopy()"); } } } CPLFree(padfScanline); // Write out the dims attribute. RWriteInteger(fp, bASCII, 1026); RWriteInteger(fp, bASCII, 1); RWriteString(fp, bASCII, "dim"); RWriteInteger(fp, bASCII, 13); RWriteInteger(fp, bASCII, 3); RWriteInteger(fp, bASCII, nXSize); RWriteInteger(fp, bASCII, nYSize); RWriteInteger(fp, bASCII, nBands); RWriteInteger(fp, bASCII, 254); // Terminate overall pairlist. RWriteInteger(fp, bASCII, 254); // Cleanup. VSIFCloseL(fp); if( eErr != CE_None ) return NULL; // Re-open dataset, and copy any auxiliary pam information. GDALPamDataset *poDS = static_cast<GDALPamDataset *>(GDALOpen(pszFilename, GA_ReadOnly)); if( poDS ) poDS->CloneInfo(poSrcDS, GCIF_PAM_DEFAULT); return poDS; }
void GTMWaypointLayer::WriteFeatureAttributes( OGRFeature *poFeature, float altitude ) { char psNameField[] = " "; // 10 spaces char* pszcomment = nullptr; int icon = 48; int date = 0; for (int i = 0; i < poFeatureDefn->GetFieldCount(); ++i) { OGRFieldDefn *poFieldDefn = poFeatureDefn->GetFieldDefn( i ); if( poFeature->IsFieldSetAndNotNull( i ) ) { const char* l_pszName = poFieldDefn->GetNameRef(); /* Waypoint name */ if (STARTS_WITH(l_pszName, "name")) { strncpy (psNameField, poFeature->GetFieldAsString( i ), 10); CPLStrlcat (psNameField, " ", sizeof(psNameField)); } /* Waypoint comment */ else if (STARTS_WITH(l_pszName, "comment")) { CPLFree(pszcomment); pszcomment = CPLStrdup( poFeature->GetFieldAsString( i ) ); } /* Waypoint icon */ else if (STARTS_WITH(l_pszName, "icon")) { icon = poFeature->GetFieldAsInteger( i ); // Check if it is a valid icon if (icon < 1 || icon > 220) icon = 48; } /* Waypoint date */ else if (EQUAL(l_pszName, "time")) { struct tm brokendowndate; int year, month, day, hour, min, sec, TZFlag; if (poFeature->GetFieldAsDateTime( i, &year, &month, &day, &hour, &min, &sec, &TZFlag)) { brokendowndate.tm_year = year - 1900; brokendowndate.tm_mon = month - 1; brokendowndate.tm_mday = day; brokendowndate.tm_hour = hour; brokendowndate.tm_min = min; brokendowndate.tm_sec = sec; GIntBig unixTime = CPLYMDHMSToUnixTime(&brokendowndate); if (TZFlag != 0) unixTime -= (TZFlag - 100) * 15; if (unixTime <= GTM_EPOCH || (unixTime - GTM_EPOCH) != (int)(unixTime - GTM_EPOCH)) { CPLError(CE_Warning, CPLE_AppDefined, "%04d/%02d/%02d %02d:%02d:%02d is not a valid datetime for GTM", year, month, day, hour, min, sec); } else { date = (int)(unixTime - GTM_EPOCH); } } } } } if (pszcomment == nullptr) pszcomment = CPLStrdup( "" ); const size_t commentLength = strlen(pszcomment); const size_t bufferSize = 27 + commentLength; void* pBuffer = CPLMalloc(bufferSize); void* pBufferAux = pBuffer; /* Write waypoint name to buffer */ memcpy((char*)pBufferAux, psNameField, 10); /* Write waypoint string comment size to buffer */ pBufferAux = (char*)pBuffer+10; appendUShort(pBufferAux, (unsigned short) commentLength); /* Write waypoint string comment to buffer */ memcpy((char*)pBuffer+12, pszcomment, commentLength); /* Write icon to buffer */ pBufferAux = (char*)pBuffer+12+commentLength; appendUShort(pBufferAux, (unsigned short) icon); /* Write dslp to buffer */ pBufferAux = (char*)pBufferAux + 2; appendUChar(pBufferAux, 3); /* Date */ pBufferAux = (char*)pBufferAux + 1; appendInt(pBufferAux, date); /* wrot */ pBufferAux = (char*)pBufferAux + 4; appendUShort(pBufferAux, 0); /* walt */ pBufferAux = (char*)pBufferAux + 2; appendFloat(pBufferAux, altitude); /* wlayer */ pBufferAux = (char*)pBufferAux + 4; appendUShort(pBufferAux, 0); VSIFWriteL(pBuffer, bufferSize, 1, poDS->getOutputFP()); poDS->incNumWaypoints(); CPLFree(pszcomment); CPLFree(pBuffer); }
static GDALDataset * EpsilonDatasetCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, CPL_UNUSED int bStrict, char ** papszOptions, GDALProgressFunc pfnProgress, void * pProgressData ) { int nBands = poSrcDS->GetRasterCount(); if ((nBands != 1 && nBands != 3) || (nBands > 0 && poSrcDS->GetRasterBand(1)->GetColorTable() != NULL)) { CPLError(CE_Failure, CPLE_NotSupported, "The EPSILON driver only supports 1 band (grayscale) " "or 3 band (RGB) data"); return NULL; } /* -------------------------------------------------------------------- */ /* Fetch and check creation options */ /* -------------------------------------------------------------------- */ int nBlockXSize = atoi(CSLFetchNameValueDef(papszOptions, "BLOCKXSIZE", "256")); int nBlockYSize = atoi(CSLFetchNameValueDef(papszOptions, "BLOCKYSIZE", "256")); if ((nBlockXSize != 32 && nBlockXSize != 64 && nBlockXSize != 128 && nBlockXSize != 256 && nBlockXSize != 512 && nBlockXSize != 1024) || (nBlockYSize != 32 && nBlockYSize != 64 && nBlockYSize != 128 && nBlockYSize != 256 && nBlockYSize != 512 && nBlockYSize != 1024)) { CPLError(CE_Failure, CPLE_NotSupported, "Block size must be a power of 2 between 32 et 1024"); return NULL; } const char* pszFilter = CSLFetchNameValueDef(papszOptions, "FILTER", "daub97lift"); char** papszFBID = eps_get_fb_info(EPS_FB_ID); char** papszFBIDIter = papszFBID; int bFound = FALSE; int nIndexFB = 0; while(papszFBIDIter && *papszFBIDIter && !bFound) { if (strcmp(*papszFBIDIter, pszFilter) == 0) bFound = TRUE; else nIndexFB ++; papszFBIDIter ++; } eps_free_fb_info(papszFBID); if (!bFound) { CPLError(CE_Failure, CPLE_NotSupported, "FILTER='%s' not supported", pszFilter); return NULL; } int eMode = EPS_MODE_OTLPF; const char* pszMode = CSLFetchNameValueDef(papszOptions, "MODE", "OTLPF"); if (EQUAL(pszMode, "NORMAL")) eMode = EPS_MODE_NORMAL; else if (EQUAL(pszMode, "OTLPF")) eMode = EPS_MODE_OTLPF; else { CPLError(CE_Failure, CPLE_NotSupported, "MODE='%s' not supported", pszMode); return NULL; } char** papszFBType = eps_get_fb_info(EPS_FB_TYPE); int bIsBiOrthogonal = EQUAL(papszFBType[nIndexFB], "biorthogonal"); eps_free_fb_info(papszFBType); if (eMode == EPS_MODE_OTLPF && !bIsBiOrthogonal) { CPLError(CE_Failure, CPLE_NotSupported, "MODE=OTLPF can only be used with biorthogonal filters. " "Use MODE=NORMAL instead"); return NULL; } int bRasterliteOutput = CPLTestBool(CSLFetchNameValueDef(papszOptions, "RASTERLITE_OUTPUT", "NO")); int nYRatio = EPS_Y_RT; int nCbRatio = EPS_Cb_RT; int nCrRatio = EPS_Cr_RT; int eResample; if (CPLTestBool(CSLFetchNameValueDef(papszOptions, "RGB_RESAMPLE", "YES"))) eResample = EPS_RESAMPLE_420; else eResample = EPS_RESAMPLE_444; const char* pszTarget = CSLFetchNameValueDef(papszOptions, "TARGET", "96"); double dfReductionFactor = 1 - CPLAtof(pszTarget) / 100; if (dfReductionFactor > 1) dfReductionFactor = 1; else if (dfReductionFactor < 0) dfReductionFactor = 0; /* -------------------------------------------------------------------- */ /* Open file */ /* -------------------------------------------------------------------- */ VSILFILE* fp = VSIFOpenL(pszFilename, "wb"); if (fp == NULL) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot create %s", pszFilename); return NULL; } /* -------------------------------------------------------------------- */ /* Compute number of blocks, block size, etc... */ /* -------------------------------------------------------------------- */ int nXSize = poSrcDS->GetRasterXSize(); int nYSize = poSrcDS->GetRasterYSize(); if (eMode == EPS_MODE_OTLPF) { nBlockXSize ++; nBlockYSize ++; } int nXBlocks = (nXSize + nBlockXSize - 1) / nBlockXSize; int nYBlocks = (nYSize + nBlockYSize - 1) / nBlockYSize; int nBlocks = nXBlocks * nYBlocks; int nUncompressedFileSize = nXSize * nYSize * nBands; int nUncompressedBlockSize = nUncompressedFileSize / nBlocks; int nTargetBlockSize = (int) (dfReductionFactor * nUncompressedBlockSize); if (nBands == 1) nTargetBlockSize = MAX (nTargetBlockSize, EPS_MIN_GRAYSCALE_BUF + 1); else nTargetBlockSize = MAX (nTargetBlockSize, EPS_MIN_TRUECOLOR_BUF + 1); /* -------------------------------------------------------------------- */ /* Allocate work buffers */ /* -------------------------------------------------------------------- */ GByte* pabyBuffer = (GByte*)VSIMalloc3(nBlockXSize, nBlockYSize, nBands); if (pabyBuffer == NULL) { VSIFCloseL(fp); return NULL; } GByte* pabyOutBuf = (GByte*)VSIMalloc(nTargetBlockSize); if (pabyOutBuf == NULL) { VSIFree(pabyBuffer); VSIFCloseL(fp); return NULL; } GByte** apapbyRawBuffer[3]; int i, j; for(i=0;i<nBands;i++) { apapbyRawBuffer[i] = (GByte**) VSIMalloc(sizeof(GByte*) * nBlockYSize); for(j=0;j<nBlockYSize;j++) { apapbyRawBuffer[i][j] = pabyBuffer + (i * nBlockXSize + j) * nBlockYSize; } } if (bRasterliteOutput) { const char* pszHeader = RASTERLITE_WAVELET_HEADER; VSIFWriteL(pszHeader, 1, strlen(pszHeader) + 1, fp); } /* -------------------------------------------------------------------- */ /* Iterate over blocks */ /* -------------------------------------------------------------------- */ int nBlockXOff, nBlockYOff; CPLErr eErr = CE_None; for(nBlockYOff = 0; eErr == CE_None && nBlockYOff < nYBlocks; nBlockYOff ++) { for(nBlockXOff = 0; eErr == CE_None && nBlockXOff < nXBlocks; nBlockXOff ++) { int bMustMemset = FALSE; int nReqXSize = nBlockXSize, nReqYSize = nBlockYSize; if ((nBlockXOff+1) * nBlockXSize > nXSize) { bMustMemset = TRUE; nReqXSize = nXSize - nBlockXOff * nBlockXSize; } if ((nBlockYOff+1) * nBlockYSize > nYSize) { bMustMemset = TRUE; nReqYSize = nYSize - nBlockYOff * nBlockYSize; } if (bMustMemset) memset(pabyBuffer, 0, nBands * nBlockXSize * nBlockYSize); eErr = poSrcDS->RasterIO(GF_Read, nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, nReqXSize, nReqYSize, pabyBuffer, nReqXSize, nReqYSize, GDT_Byte, nBands, NULL, 1, nBlockXSize, nBlockXSize * nBlockYSize, NULL); int nOutBufSize = nTargetBlockSize; if (eErr == CE_None && nBands == 1) { if (EPS_OK != eps_encode_grayscale_block(apapbyRawBuffer[0], nXSize, nYSize, nReqXSize, nReqYSize, nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, pabyOutBuf, &nOutBufSize, (char*) pszFilter, eMode)) { CPLError( CE_Failure, CPLE_AppDefined, "Error occurred when encoding block (%d, %d)", nBlockXOff, nBlockYOff); eErr = CE_Failure; } } else if (eErr == CE_None) { if (EPS_OK != eps_encode_truecolor_block( apapbyRawBuffer[0], apapbyRawBuffer[1], apapbyRawBuffer[2], nXSize, nYSize, nReqXSize, nReqYSize, nBlockXOff * nBlockXSize, nBlockYOff * nBlockYSize, eResample, pabyOutBuf, &nOutBufSize, nYRatio, nCbRatio, nCrRatio, (char*) pszFilter, eMode)) { CPLError(CE_Failure, CPLE_AppDefined, "Error occurred when encoding block (%d, %d)", nBlockXOff, nBlockYOff); eErr = CE_Failure; } } if (eErr == CE_None) { if ((int)VSIFWriteL(pabyOutBuf, 1, nOutBufSize, fp) != nOutBufSize) eErr = CE_Failure; char chEPSMarker = EPS_MARKER; VSIFWriteL(&chEPSMarker, 1, 1, fp); if (pfnProgress && !pfnProgress( 1.0 * (nBlockYOff * nXBlocks + nBlockXOff + 1) / nBlocks, NULL, pProgressData)) { eErr = CE_Failure; } } } } if (bRasterliteOutput) { const char* pszFooter = RASTERLITE_WAVELET_FOOTER; VSIFWriteL(pszFooter, 1, strlen(pszFooter) + 1, fp); } /* -------------------------------------------------------------------- */ /* Cleanup work buffers */ /* -------------------------------------------------------------------- */ for(i=0;i<nBands;i++) { VSIFree(apapbyRawBuffer[i]); } VSIFree(pabyOutBuf); VSIFree(pabyBuffer); VSIFCloseL(fp); if (eErr != CE_None) return NULL; /* -------------------------------------------------------------------- */ /* Reopen the dataset, unless asked for not (Rasterlite optim) */ /* -------------------------------------------------------------------- */ return (GDALDataset*) GDALOpen(pszFilename, GA_ReadOnly); }
int DDFModule::Create( const char *pszFilename ) { CPLAssert( fpDDF == NULL ); /* -------------------------------------------------------------------- */ /* Create the file on disk. */ /* -------------------------------------------------------------------- */ fpDDF = VSIFOpenL( pszFilename, "wb+" ); if( fpDDF == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to create file %s, check path and permissions.", pszFilename ); return FALSE; } bReadOnly = FALSE; /* -------------------------------------------------------------------- */ /* Prepare all the field definition information. */ /* -------------------------------------------------------------------- */ int iField; _recLength = 24 + nFieldDefnCount * (_sizeFieldLength+_sizeFieldPos+_sizeFieldTag) + 1; _fieldAreaStart = _recLength; for( iField=0; iField < nFieldDefnCount; iField++ ) { int nLength; papoFieldDefns[iField]->GenerateDDREntry( this, NULL, &nLength ); _recLength += nLength; } /* -------------------------------------------------------------------- */ /* Setup 24 byte leader. */ /* -------------------------------------------------------------------- */ char achLeader[25]; snprintf( achLeader+0, sizeof(achLeader)-0, "%05d", (int) _recLength ); achLeader[5] = _interchangeLevel; achLeader[6] = _leaderIden; achLeader[7] = _inlineCodeExtensionIndicator; achLeader[8] = _versionNumber; achLeader[9] = _appIndicator; snprintf( achLeader+10, sizeof(achLeader)-10, "%02d", (int) _fieldControlLength ); snprintf( achLeader+12, sizeof(achLeader)-12, "%05d", (int) _fieldAreaStart ); strncpy( achLeader+17, _extendedCharSet, 3 ); snprintf( achLeader+20, sizeof(achLeader)-20, "%1d", (int) _sizeFieldLength ); snprintf( achLeader+21, sizeof(achLeader)-21, "%1d", (int) _sizeFieldPos ); achLeader[22] = '0'; snprintf( achLeader+23, sizeof(achLeader)-23, "%1d", (int) _sizeFieldTag ); int bRet = VSIFWriteL( achLeader, 24, 1, fpDDF ) > 0; /* -------------------------------------------------------------------- */ /* Write out directory entries. */ /* -------------------------------------------------------------------- */ int nOffset = 0; for( iField=0; iField < nFieldDefnCount; iField++ ) { char achDirEntry[255]; char szFormat[32]; int nLength; CPLAssert(_sizeFieldLength + _sizeFieldPos + _sizeFieldTag < (int)sizeof(achDirEntry)); papoFieldDefns[iField]->GenerateDDREntry( this, NULL, &nLength ); CPLAssert( (int)strlen(papoFieldDefns[iField]->GetName()) == _sizeFieldTag ); strcpy( achDirEntry, papoFieldDefns[iField]->GetName() ); snprintf(szFormat, sizeof(szFormat), "%%0%dd", (int)_sizeFieldLength); snprintf( achDirEntry + _sizeFieldTag, sizeof(achDirEntry) - _sizeFieldTag, szFormat, nLength ); snprintf(szFormat, sizeof(szFormat), "%%0%dd", (int)_sizeFieldPos); snprintf( achDirEntry + _sizeFieldTag + _sizeFieldLength, sizeof(achDirEntry) - _sizeFieldTag - _sizeFieldLength, szFormat, nOffset ); nOffset += nLength; bRet &= VSIFWriteL( achDirEntry, _sizeFieldLength + _sizeFieldPos + _sizeFieldTag, 1, fpDDF ) > 0; } char chUT = DDF_FIELD_TERMINATOR; bRet &= VSIFWriteL( &chUT, 1, 1, fpDDF ) > 0; /* -------------------------------------------------------------------- */ /* Write out the field descriptions themselves. */ /* -------------------------------------------------------------------- */ for( iField = 0; iField < nFieldDefnCount; iField++ ) { char *pachData = NULL; int nLength = 0; papoFieldDefns[iField]->GenerateDDREntry( this, &pachData, &nLength ); bRet &= VSIFWriteL( pachData, nLength, 1, fpDDF ) > 0; CPLFree( pachData ); } return bRet ? TRUE : FALSE; }
static void WriteDouble(VSILFILE* fp, double val) { CPL_LSBPTR64(&val); VSIFWriteL(&val, 8, 1, fp); }
GDALDataset *GS7BGDataset::CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int bStrict, CPL_UNUSED char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ) { if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; int nBands = poSrcDS->GetRasterCount(); if (nBands == 0) { CPLError( CE_Failure, CPLE_NotSupported, "Driver does not support source dataset with zero band.\n"); return NULL; } else if (nBands > 1) { if( bStrict ) { CPLError( CE_Failure, CPLE_NotSupported, "Unable to create copy, " "format only supports one raster band.\n" ); return NULL; } else CPLError( CE_Warning, CPLE_NotSupported, "Format only supports one " "raster band, first band will be copied.\n" ); } GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( 1 ); if( !pfnProgress( 0.0, NULL, pProgressData ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated\n" ); return NULL; } VSILFILE *fp = VSIFOpenL( pszFilename, "w+b" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file '%s' failed.\n", pszFilename ); return NULL; } GInt32 nXSize = poSrcBand->GetXSize(); GInt32 nYSize = poSrcBand->GetYSize(); double adfGeoTransform[6]; poSrcDS->GetGeoTransform( adfGeoTransform ); double dfMinX = adfGeoTransform[0] + adfGeoTransform[1] / 2; double dfMaxX = adfGeoTransform[1] * (nXSize - 0.5) + adfGeoTransform[0]; double dfMinY = adfGeoTransform[5] * (nYSize - 0.5) + adfGeoTransform[3]; double dfMaxY = adfGeoTransform[3] + adfGeoTransform[5] / 2; CPLErr eErr = WriteHeader( fp, nXSize, nYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, 0.0, 0.0 ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } /* -------------------------------------------------------------------- */ /* Copy band data. */ /* -------------------------------------------------------------------- */ double *pfData = (double *)VSI_MALLOC2_VERBOSE( nXSize, sizeof( double ) ); if( pfData == NULL ) { VSIFCloseL( fp ); return NULL; } int bSrcHasNDValue; double dfSrcNoDataValue = poSrcBand->GetNoDataValue( &bSrcHasNDValue ); double dfMinZ = DBL_MAX; double dfMaxZ = -DBL_MAX; for( GInt32 iRow = nYSize - 1; iRow >= 0; iRow-- ) { eErr = poSrcBand->RasterIO( GF_Read, 0, iRow, nXSize, 1, pfData, nXSize, 1, GDT_Float64, 0, 0, NULL ); if( eErr != CE_None ) { VSIFCloseL( fp ); VSIFree( pfData ); return NULL; } for( int iCol=0; iCol<nXSize; iCol++ ) { if( bSrcHasNDValue && pfData[iCol] == dfSrcNoDataValue ) { pfData[iCol] = dfDefaultNoDataValue; } else { if( pfData[iCol] > dfMaxZ ) dfMaxZ = pfData[iCol]; if( pfData[iCol] < dfMinZ ) dfMinZ = pfData[iCol]; } CPL_LSBPTR64( pfData+iCol ); } if( VSIFWriteL( (void *)pfData, sizeof( double ), nXSize, fp ) != static_cast<unsigned>(nXSize) ) { VSIFCloseL( fp ); VSIFree( pfData ); CPLError( CE_Failure, CPLE_FileIO, "Unable to write grid row. Disk full?\n" ); return NULL; } if( !pfnProgress( static_cast<double>(nYSize - iRow)/nYSize, NULL, pProgressData ) ) { VSIFCloseL( fp ); VSIFree( pfData ); CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); return NULL; } } VSIFree( pfData ); /* write out the min and max values */ eErr = WriteHeader( fp, nXSize, nYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, dfMinZ, dfMaxZ ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } VSIFCloseL( fp ); GDALPamDataset *poDS = (GDALPamDataset *)GDALOpen( pszFilename, GA_Update ); if (poDS) { poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); } return poDS; }
GDALDataset *GS7BGDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, CPL_UNUSED char **papszParmList ) { if( nXSize <= 0 || nYSize <= 0 ) { CPLError( CE_Failure, CPLE_IllegalArg, "Unable to create grid, both X and Y size must be " "non-negative.\n" ); return NULL; } if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_UInt16 && eType != GDT_Int16 && eType != GDT_Float64) { CPLError( CE_Failure, CPLE_AppDefined, "GS7BG Grid only supports Byte, Int16, " "Uint16, Float32, and Float64 datatypes. Unable to create with " "type %s.\n", GDALGetDataTypeName( eType ) ); return NULL; } if (nBands > 1) { CPLError( CE_Failure, CPLE_NotSupported, "Unable to create copy, " "format only supports one raster band.\n" ); return NULL; } VSILFILE *fp = VSIFOpenL( pszFilename, "w+b" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file '%s' failed.\n", pszFilename ); return NULL; } CPLErr eErr = WriteHeader( fp, nXSize, nYSize, 0.0, nXSize, 0.0, nYSize, 0.0, 0.0 ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } double dfVal = dfDefaultNoDataValue; CPL_LSBPTR64( &dfVal ); for( int iRow = 0; iRow < nYSize; iRow++ ) { for( int iCol=0; iCol<nXSize; iCol++ ) { if( VSIFWriteL( (void *)&dfVal, sizeof(double), 1, fp ) != 1 ) { VSIFCloseL( fp ); CPLError( CE_Failure, CPLE_FileIO, "Unable to write grid cell. Disk full?\n" ); return NULL; } } } VSIFCloseL( fp ); return (GDALDataset *)GDALOpen( pszFilename, GA_Update ); }
void GDALPamProxyDB::SaveDB() { /* -------------------------------------------------------------------- */ /* Open the database relating original names to proxy .aux.xml */ /* file names. */ /* -------------------------------------------------------------------- */ CPLString osDBName = CPLFormFilename( osProxyDBDir, "gdal_pam_proxy", "dat" ); void *hLock = CPLLockFile( osDBName, 1.0 ); // proceed even if lock fails - we need CPLBreakLockFile()! if( hLock == NULL ) { CPLError( CE_Warning, CPLE_AppDefined, "GDALPamProxyDB::SaveDB() - Failed to lock %s file, proceeding anyways.", osDBName.c_str() ); } FILE *fpDB = VSIFOpenL( osDBName, "w" ); if( fpDB == NULL ) { if( hLock ) CPLUnlockFile( hLock ); CPLError( CE_Failure, CPLE_AppDefined, "Failed to save %s Pam Proxy DB.\n%s", osDBName.c_str(), VSIStrerror( errno ) ); return; } /* -------------------------------------------------------------------- */ /* Write header. */ /* -------------------------------------------------------------------- */ GByte abyHeader[100]; memset( abyHeader, ' ', sizeof(abyHeader) ); strncpy( (char *) abyHeader, "GDAL_PROXY", 10 ); sprintf( (char *) abyHeader + 10, "%9d", nUpdateCounter ); VSIFWriteL( abyHeader, 1, 100, fpDB ); /* -------------------------------------------------------------------- */ /* Write names. */ /* -------------------------------------------------------------------- */ unsigned int i; for( i = 0; i < aosOriginalFiles.size(); i++ ) { size_t nBytesWritten; const char *pszProxyFile; VSIFWriteL( aosOriginalFiles[i].c_str(), 1, strlen(aosOriginalFiles[i].c_str())+1, fpDB ); pszProxyFile = CPLGetFilename(aosProxyFiles[i]); nBytesWritten = VSIFWriteL( pszProxyFile, 1, strlen(pszProxyFile)+1, fpDB ); if( nBytesWritten != strlen(pszProxyFile)+1 ) { CPLError( CE_Failure, CPLE_AppDefined, "Failed to write complete %s Pam Proxy DB.\n%s", osDBName.c_str(), VSIStrerror( errno ) ); VSIFCloseL( fpDB ); VSIUnlink( osDBName ); return; } } VSIFCloseL( fpDB ); if( hLock ) CPLUnlockFile( hLock ); }
bool LevellerDataset::write(double d) { CPL_LSBPTR64(&d); return (1 == VSIFWriteL(&d, sizeof(d), 1, m_fp)); }
bool LevellerDataset::write(size_t n) { CPL_LSBPTR32(&n); return (1 == VSIFWriteL(&n, sizeof(n), 1, m_fp)); }
bool LevellerDataset::write_byte(size_t n) { unsigned char uch = (unsigned char)n; return (1 == VSIFWriteL(&uch, 1, 1, m_fp)); }
bool LevellerDataset::write_header() { char szHeader[5]; strcpy(szHeader, "trrn"); szHeader[4] = 7; // TER v7 introduced w/ Lev 2.6. if(1 != VSIFWriteL(szHeader, 5, 1, m_fp) || !this->write_tag("hf_w", (size_t)nRasterXSize) || !this->write_tag("hf_b", (size_t)nRasterYSize)) { CPLError( CE_Failure, CPLE_FileIO, "Could not write header" ); return false; } m_dElevBase = 0.0; m_dElevScale = 1.0; if(m_pszProjection == NULL || m_pszProjection[0] == 0) { this->write_tag("csclass", LEV_COORDSYS_RASTER); } else { this->write_tag("coordsys_wkt", m_pszProjection); const UNITLABEL units_elev = this->id_to_code(m_szElevUnits); const int bHasECS = (units_elev != UNITLABEL_PIXEL && units_elev != UNITLABEL_UNKNOWN); this->write_tag("coordsys_haselevm", bHasECS); OGRSpatialReference sr(m_pszProjection); if(bHasECS) { if(!this->compute_elev_scaling(sr)) return false; // Raw-to-real units scaling. this->write_tag("coordsys_em_scale", m_dElevScale); //elev offset, in real units. this->write_tag("coordsys_em_base", m_dElevBase); this->write_tag("coordsys_em_units", units_elev); } if(sr.IsLocal()) { this->write_tag("csclass", LEV_COORDSYS_LOCAL); const double dfLinear = sr.GetLinearUnits(); const int n = this->meter_measure_to_code(dfLinear); this->write_tag("coordsys_units", n); } else { this->write_tag("csclass", LEV_COORDSYS_GEO); } if( m_adfTransform[2] != 0.0 || m_adfTransform[4] != 0.0) { CPLError( CE_Failure, CPLE_IllegalArg, "Cannot handle rotated geotransform" ); return false; } // todo: GDAL gridpost spacing is based on extent / rastersize // instead of extent / (rastersize-1) like Leveller. // We need to look into this and adjust accordingly. // Write north-south digital axis. this->write_tag("coordsys_da0_style", LEV_DA_PIXEL_SIZED); this->write_tag("coordsys_da0_fixedend", 0); this->write_tag("coordsys_da0_v0", m_adfTransform[3]); this->write_tag("coordsys_da0_v1", m_adfTransform[5]); // Write east-west digital axis. this->write_tag("coordsys_da1_style", LEV_DA_PIXEL_SIZED); this->write_tag("coordsys_da1_fixedend", 0); this->write_tag("coordsys_da1_v0", m_adfTransform[0]); this->write_tag("coordsys_da1_v1", m_adfTransform[1]); } this->write_tag_start("hf_data", sizeof(float) * nRasterXSize * nRasterYSize); return true; }
static void WriteInt(VSILFILE* fp, GInt32 val) { CPL_LSBPTR32(&val); VSIFWriteL(&val, 4, 1, fp); }
static void WriteFloat(VSILFILE* fp, float val) { CPL_LSBPTR32(&val); VSIFWriteL(&val, 4, 1, fp); }
CPLErr GS7BGRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff, void *pImage ) { if( eAccess == GA_ReadOnly ) { CPLError( CE_Failure, CPLE_NoWriteAccess, "Unable to write block, dataset opened read only.\n" ); return CE_Failure; } if( nBlockYOff < 0 || nBlockYOff > nRasterYSize - 1 || nBlockXOff != 0 ) return CE_Failure; GS7BGDataset *poGDS = (GS7BGDataset *) ( poDS ); if( pafRowMinZ == NULL || pafRowMaxZ == NULL || nMinZRow < 0 || nMaxZRow < 0 ) { pafRowMinZ = (double *)VSI_MALLOC2_VERBOSE( nRasterYSize,sizeof(double) ); if( pafRowMinZ == NULL ) { return CE_Failure; } pafRowMaxZ = (double *)VSI_MALLOC2_VERBOSE( nRasterYSize,sizeof(double) ); if( pafRowMaxZ == NULL ) { VSIFree( pafRowMinZ ); pafRowMinZ = NULL; return CE_Failure; } CPLErr eErr = ScanForMinMaxZ(); if( eErr != CE_None ) return eErr; } if( VSIFSeekL( poGDS->fp, GS7BGDataset::nHEADER_SIZE + sizeof(double) * nRasterXSize * (nRasterYSize - nBlockYOff - 1), SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to seek to beginning of grid row.\n" ); return CE_Failure; } double *pdfImage = (double *)pImage; pafRowMinZ[nBlockYOff] = DBL_MAX; pafRowMaxZ[nBlockYOff] = -DBL_MAX; for( int iPixel=0; iPixel<nBlockXSize; iPixel++ ) { if( pdfImage[iPixel] != poGDS->dfNoData_Value ) { if( pdfImage[iPixel] < pafRowMinZ[nBlockYOff] ) pafRowMinZ[nBlockYOff] = pdfImage[iPixel]; if( pdfImage[iPixel] > pafRowMaxZ[nBlockYOff] ) pafRowMaxZ[nBlockYOff] = pdfImage[iPixel]; } CPL_LSBPTR64( pdfImage+iPixel ); } if( VSIFWriteL( pImage, sizeof(double), nBlockXSize, poGDS->fp ) != static_cast<unsigned>(nBlockXSize) ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write block to grid file.\n" ); return CE_Failure; } /* Update min/max Z values as appropriate */ bool bHeaderNeedsUpdate = false; if( nMinZRow == nBlockYOff && pafRowMinZ[nBlockYOff] > dfMinZ ) { double dfNewMinZ = DBL_MAX; for( int iRow=0; iRow<nRasterYSize; iRow++ ) { if( pafRowMinZ[iRow] < dfNewMinZ ) { dfNewMinZ = pafRowMinZ[iRow]; nMinZRow = iRow; } } if( dfNewMinZ != dfMinZ ) { dfMinZ = dfNewMinZ; bHeaderNeedsUpdate = true; } } if( nMaxZRow == nBlockYOff && pafRowMaxZ[nBlockYOff] < dfMaxZ ) { double dfNewMaxZ = -DBL_MAX; for( int iRow=0; iRow<nRasterYSize; iRow++ ) { if( pafRowMaxZ[iRow] > dfNewMaxZ ) { dfNewMaxZ = pafRowMaxZ[iRow]; nMaxZRow = iRow; } } if( dfNewMaxZ != dfMaxZ ) { dfMaxZ = dfNewMaxZ; bHeaderNeedsUpdate = true; } } if( pafRowMinZ[nBlockYOff] < dfMinZ || pafRowMaxZ[nBlockYOff] > dfMaxZ ) { if( pafRowMinZ[nBlockYOff] < dfMinZ ) { dfMinZ = pafRowMinZ[nBlockYOff]; nMinZRow = nBlockYOff; } if( pafRowMaxZ[nBlockYOff] > dfMaxZ ) { dfMaxZ = pafRowMaxZ[nBlockYOff]; nMaxZRow = nBlockYOff; } bHeaderNeedsUpdate = true; } if( bHeaderNeedsUpdate && dfMaxZ > dfMinZ ) { CPLErr eErr = poGDS->WriteHeader( poGDS->fp, nRasterXSize, nRasterYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, dfMinZ, dfMaxZ ); return eErr; } return CE_None; }
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); signed char chDiff = (signed 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); signed char chDiff = (signed 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); }
CPLErr GS7BGDataset::WriteHeader( VSILFILE *fp, GInt32 nXSize, GInt32 nYSize, double dfMinX, double dfMaxX, double dfMinY, double dfMaxY, double dfMinZ, double dfMaxZ ) { if( VSIFSeekL( fp, 0, SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to seek to start of grid file.\n" ); return CE_Failure; } GInt32 nTemp = CPL_LSBWORD32(nHEADER_TAG); if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write header tag to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD32(sizeof(GInt32)); // Size of version section. if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write size to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD32(1); // Version if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write size to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD32(nGRID_TAG); // Mark start of grid if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write size to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD32(72); // Grid info size (the remainder of the header) if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write size to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD32(nYSize); if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write Y size to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD32(nXSize); if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write X size to grid file.\n" ); return CE_Failure; } double dfTemp = dfMinX; CPL_LSBPTR64(&dfTemp); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write minimum X value to grid file.\n" ); return CE_Failure; } dfTemp = dfMinY; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write minimum Y value to grid file.\n" ); return CE_Failure; } // Write node spacing in x direction dfTemp = (dfMaxX - dfMinX) / (nXSize - 1); CPL_LSBPTR64(&dfTemp); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write spacing in X value.\n" ); return CE_Failure; } // Write node spacing in y direction dfTemp = (dfMaxY - dfMinY) / (nYSize -1); CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write spacing in Y value.\n" ); return CE_Failure; } dfTemp = dfMinZ; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write minimum Z value to grid file.\n" ); return CE_Failure; } dfTemp = dfMaxZ; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write maximum Z value to grid file.\n" ); return CE_Failure; } dfTemp = 0; // Rotation value is zero CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write rotation value to grid file.\n" ); return CE_Failure; } dfTemp = dfDefaultNoDataValue; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, sizeof(double), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write cell blank value to grid file.\n" ); return CE_Failure; } // Only supports 1 band so go ahead and write band info here nTemp = CPL_LSBWORD32(nDATA_TAG); // Mark start of data if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to data tag to grid file.\n" ); return CE_Failure; } int nSize = nXSize * nYSize * (int)sizeof(double); nTemp = CPL_LSBWORD32(nSize); // Mark size of data if( VSIFWriteL( (void *)&nTemp, sizeof(GInt32), 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write data size to grid file.\n" ); return CE_Failure; } return CE_None; }
GDALDataset *GTXDataset::Create( const char * pszFilename, int nXSize, int nYSize, int /* nBands */, GDALDataType eType, char ** /* papszOptions */ ) { if( eType != GDT_Float32 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create gtx file with unsupported data type '%s'.", GDALGetDataTypeName( eType ) ); return NULL; } if( !EQUAL(CPLGetExtension(pszFilename),"gtx") ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create gtx file with extension other than gtx." ); return NULL; } /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( pszFilename, "wb" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Write out the header with stub georeferencing. */ /* -------------------------------------------------------------------- */ unsigned char header[40] = { '\0' }; double dfYOrigin = 0.0; memcpy( header + 0, &dfYOrigin, 8 ); CPL_MSBPTR64( header + 0 ); double dfXOrigin = 0.0; memcpy( header + 8, &dfXOrigin, 8 ); CPL_MSBPTR64( header + 8 ); double dfYSize = 0.01; memcpy( header + 16, &dfYSize, 8 ); CPL_MSBPTR64( header + 16 ); double dfXSize = 0.01; memcpy( header + 24, &dfXSize, 8 ); CPL_MSBPTR64( header + 24 ); GInt32 nYSize32 = nYSize; memcpy( header + 32, &nYSize32, 4 ); CPL_MSBPTR32( header + 32 ); GInt32 nXSize32 = nXSize; memcpy( header + 36, &nXSize32, 4 ); CPL_MSBPTR32( header + 36 ); CPL_IGNORE_RET_VAL(VSIFWriteL( header, 40, 1, fp )); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_Update ) ); }
OGRErr OGRCSVLayer::CreateFeature( OGRFeature *poNewFeature ) { int iField; if( !bInWriteMode ) { CPLError( CE_Failure, CPLE_AppDefined, "The CreateFeature() operation is not permitted on a read-only CSV." ); return OGRERR_FAILURE; } /* If we need rewind, it means that we have just written a feature before */ /* so there's no point seeking to the end of the file, as we're already */ /* at the end */ int bNeedSeekEnd = !bNeedRewindBeforeRead; bNeedRewindBeforeRead = TRUE; /* -------------------------------------------------------------------- */ /* Write field names if we haven't written them yet. */ /* Write .csvt file if needed */ /* -------------------------------------------------------------------- */ if( bNew ) { OGRErr eErr = WriteHeader(); if (eErr != OGRERR_NONE) return eErr; bNeedSeekEnd = FALSE; } if (fpCSV == NULL) return OGRERR_FAILURE; /* -------------------------------------------------------------------- */ /* Make sure we are at the end of the file. */ /* -------------------------------------------------------------------- */ if (bNeedSeekEnd) { if (bFirstFeatureAppendedDuringSession) { /* Add a newline character to the end of the file if necessary */ bFirstFeatureAppendedDuringSession = FALSE; VSIFSeekL( fpCSV, 0, SEEK_END ); VSIFSeekL( fpCSV, VSIFTellL(fpCSV) - 1, SEEK_SET); char chLast; VSIFReadL( &chLast, 1, 1, fpCSV ); VSIFSeekL( fpCSV, 0, SEEK_END ); if (chLast != '\n') { if( bUseCRLF ) VSIFPutcL( 13, fpCSV ); VSIFPutcL( '\n', fpCSV ); } } else { VSIFSeekL( fpCSV, 0, SEEK_END ); } } /* -------------------------------------------------------------------- */ /* Write out the geometry */ /* -------------------------------------------------------------------- */ if (eGeometryFormat == OGR_CSV_GEOM_AS_WKT) { OGRGeometry *poGeom = poNewFeature->GetGeometryRef(); char* pszWKT = NULL; if (poGeom && poGeom->exportToWkt(&pszWKT) == OGRERR_NONE) { VSIFPrintfL( fpCSV, "\"%s\"", pszWKT); } else { VSIFPrintfL( fpCSV, "\"\""); } CPLFree(pszWKT); if (poFeatureDefn->GetFieldCount() > 0) VSIFPrintfL( fpCSV, "%c", chDelimiter); } else if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ || eGeometryFormat == OGR_CSV_GEOM_AS_XY || eGeometryFormat == OGR_CSV_GEOM_AS_YX) { OGRGeometry *poGeom = poNewFeature->GetGeometryRef(); if (poGeom && wkbFlatten(poGeom->getGeometryType()) == wkbPoint) { OGRPoint* poPoint = (OGRPoint*) poGeom; char szBuffer[75]; if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ ) OGRMakeWktCoordinate(szBuffer, poPoint->getX(), poPoint->getY(), poPoint->getZ(), 3); else if (eGeometryFormat == OGR_CSV_GEOM_AS_XY ) OGRMakeWktCoordinate(szBuffer, poPoint->getX(), poPoint->getY(), 0, 2); else OGRMakeWktCoordinate(szBuffer, poPoint->getY(), poPoint->getX(), 0, 2); char* pc = szBuffer; while(*pc != '\0') { if (*pc == ' ') *pc = chDelimiter; pc ++; } VSIFPrintfL( fpCSV, "%s", szBuffer ); } else { VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ) VSIFPrintfL( fpCSV, "%c", chDelimiter ); } if (poFeatureDefn->GetFieldCount() > 0) VSIFPrintfL( fpCSV, "%c", chDelimiter ); } /* -------------------------------------------------------------------- */ /* Write out all the field values. */ /* -------------------------------------------------------------------- */ int bNonEmptyLine = FALSE; for( iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ ) { char *pszEscaped; if( iField > 0 ) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (poFeatureDefn->GetFieldDefn(iField)->GetType() == OFTReal) { pszEscaped = CPLStrdup(poNewFeature->GetFieldAsString(iField)); /* Use point as decimal separator */ char* pszComma = strchr(pszEscaped, ','); if (pszComma) *pszComma = '.'; } else { pszEscaped = CPLEscapeString( poNewFeature->GetFieldAsString(iField), -1, CPLES_CSV ); } int nLen = (int)strlen(pszEscaped); bNonEmptyLine |= (nLen != 0); VSIFWriteL( pszEscaped, 1, nLen, fpCSV ); CPLFree( pszEscaped ); } if( poFeatureDefn->GetFieldCount() == 1 && !bNonEmptyLine ) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if( bUseCRLF ) VSIFPutcL( 13, fpCSV ); VSIFPutcL( '\n', fpCSV ); return OGRERR_NONE; }
GDALDataset *PAuxDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszOptions ) { const char *pszInterleave = CSLFetchNameValue( papszOptions, "INTERLEAVE" ); if( pszInterleave == NULL ) pszInterleave = "BAND"; /* -------------------------------------------------------------------- */ /* Verify input options. */ /* -------------------------------------------------------------------- */ if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_UInt16 && eType != GDT_Int16 ) { CPLError( CE_Failure, CPLE_AppDefined, "Attempt to create PCI .Aux labelled dataset with an illegal\n" "data type (%s).\n", GDALGetDataTypeName(eType) ); return NULL; } /* -------------------------------------------------------------------- */ /* Sum the sizes of the band pixel types. */ /* -------------------------------------------------------------------- */ int nPixelSizeSum = 0; for( int iBand = 0; iBand < nBands; iBand++ ) nPixelSizeSum += (GDALGetDataTypeSize(eType)/8); /* -------------------------------------------------------------------- */ /* Try to create the file. */ /* -------------------------------------------------------------------- */ VSILFILE *fp = VSIFOpenL( pszFilename, "w" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Just write out a couple of bytes to establish the binary */ /* file, and then close it. */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFWriteL( reinterpret_cast<void *>( const_cast<char *>( "\0\0" ) ), 2, 1, fp )); CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); /* -------------------------------------------------------------------- */ /* Create the aux filename. */ /* -------------------------------------------------------------------- */ char *pszAuxFilename = reinterpret_cast<char *>( CPLMalloc( strlen( pszFilename ) + 5 ) ); strcpy( pszAuxFilename, pszFilename );; for( int i = static_cast<int>(strlen(pszAuxFilename))-1; i > 0; i-- ) { if( pszAuxFilename[i] == '.' ) { pszAuxFilename[i] = '\0'; break; } } strcat( pszAuxFilename, ".aux" ); /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ fp = VSIFOpenL( pszAuxFilename, "wt" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file `%s' failed.\n", pszAuxFilename ); return NULL; } CPLFree( pszAuxFilename ); /* -------------------------------------------------------------------- */ /* We need to write out the original filename but without any */ /* path components in the AuxilaryTarget line. Do so now. */ /* -------------------------------------------------------------------- */ int iStart = static_cast<int>(strlen(pszFilename))-1; while( iStart > 0 && pszFilename[iStart-1] != '/' && pszFilename[iStart-1] != '\\' ) iStart--; CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "AuxilaryTarget: %s\n", pszFilename + iStart )); /* -------------------------------------------------------------------- */ /* Write out the raw definition for the dataset as a whole. */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "RawDefinition: %d %d %d\n", nXSize, nYSize, nBands )); /* -------------------------------------------------------------------- */ /* Write out a definition for each band. We always write band */ /* sequential files for now as these are pretty efficiently */ /* handled by GDAL. */ /* -------------------------------------------------------------------- */ vsi_l_offset nImgOffset = 0; for( int iBand = 0; iBand < nBands; iBand++ ) { const char *pszTypeName; int nPixelOffset; int nLineOffset; vsi_l_offset nNextImgOffset; /* -------------------------------------------------------------------- */ /* Establish our file layout based on supplied interleaving. */ /* -------------------------------------------------------------------- */ if( EQUAL(pszInterleave,"LINE") ) { nPixelOffset = GDALGetDataTypeSize(eType)/8; nLineOffset = nXSize * nPixelSizeSum; nNextImgOffset = nImgOffset + nPixelOffset * nXSize; } else if( EQUAL(pszInterleave,"PIXEL") ) { nPixelOffset = nPixelSizeSum; nLineOffset = nXSize * nPixelOffset; nNextImgOffset = nImgOffset + (GDALGetDataTypeSize(eType)/8); } else /* default to band */ { nPixelOffset = GDALGetDataTypeSize(eType)/8; nLineOffset = nXSize * nPixelOffset; nNextImgOffset = nImgOffset + nYSize * (vsi_l_offset) nLineOffset; } /* -------------------------------------------------------------------- */ /* Write out line indicating layout. */ /* -------------------------------------------------------------------- */ if( eType == GDT_Float32 ) pszTypeName = "32R"; else if( eType == GDT_Int16 ) pszTypeName = "16S"; else if( eType == GDT_UInt16 ) pszTypeName = "16U"; else pszTypeName = "8U"; CPL_IGNORE_RET_VAL(VSIFPrintfL( fp, "ChanDefinition-%d: %s " CPL_FRMT_GIB " %d %d %s\n", iBand+1, pszTypeName, (GIntBig) nImgOffset, nPixelOffset, nLineOffset, #ifdef CPL_LSB "Swapped" #else "Unswapped" #endif )); nImgOffset = nNextImgOffset; } /* -------------------------------------------------------------------- */ /* Cleanup */ /* -------------------------------------------------------------------- */ CPL_IGNORE_RET_VAL(VSIFCloseL( fp )); return reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_Update ) ); }
OGRErr OGRCSVLayer::WriteHeader() { if( !bNew ) return OGRERR_NONE; /* -------------------------------------------------------------------- */ /* Write field names if we haven't written them yet. */ /* Write .csvt file if needed */ /* -------------------------------------------------------------------- */ bNew = FALSE; bHasFieldNames = TRUE; for(int iFile=0;iFile<((bCreateCSVT) ? 2 : 1);iFile++) { VSILFILE* fpCSVT = NULL; if (bCreateCSVT && iFile == 0) { char* pszDirName = CPLStrdup(CPLGetDirname(pszFilename)); char* pszBaseName = CPLStrdup(CPLGetBasename(pszFilename)); fpCSVT = VSIFOpenL(CPLFormFilename(pszDirName, pszBaseName, ".csvt"), "wb"); CPLFree(pszDirName); CPLFree(pszBaseName); } else { if( strncmp(pszFilename, "/vsistdout/", 11) == 0 || strncmp(pszFilename, "/vsizip/", 8) == 0 ) fpCSV = VSIFOpenL( pszFilename, "wb" ); else fpCSV = VSIFOpenL( pszFilename, "w+b" ); if( fpCSV == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to create %s:\n%s", pszFilename, VSIStrerror( errno ) ); return OGRERR_FAILURE; } } if (bWriteBOM && fpCSV) { VSIFWriteL("\xEF\xBB\xBF", 1, 3, fpCSV); } if (eGeometryFormat == OGR_CSV_GEOM_AS_WKT) { if (fpCSV) VSIFPrintfL( fpCSV, "%s", "WKT"); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", "String"); if (poFeatureDefn->GetFieldCount() > 0) { if (fpCSV) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", ","); } } else if (eGeometryFormat == OGR_CSV_GEOM_AS_XYZ) { if (fpCSV) VSIFPrintfL( fpCSV, "X%cY%cZ", chDelimiter, chDelimiter); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", "Real,Real,Real"); if (poFeatureDefn->GetFieldCount() > 0) { if (fpCSV) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", ","); } } else if (eGeometryFormat == OGR_CSV_GEOM_AS_XY) { if (fpCSV) VSIFPrintfL( fpCSV, "X%cY", chDelimiter); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", "Real,Real"); if (poFeatureDefn->GetFieldCount() > 0) { if (fpCSV) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", ","); } } else if (eGeometryFormat == OGR_CSV_GEOM_AS_YX) { if (fpCSV) VSIFPrintfL( fpCSV, "Y%cX", chDelimiter); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", "Real,Real"); if (poFeatureDefn->GetFieldCount() > 0) { if (fpCSV) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", ","); } } for( int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++ ) { char *pszEscaped; if( iField > 0 ) { if (fpCSV) VSIFPrintfL( fpCSV, "%c", chDelimiter ); if (fpCSVT) VSIFPrintfL( fpCSVT, "%s", ","); } pszEscaped = CPLEscapeString( poFeatureDefn->GetFieldDefn(iField)->GetNameRef(), -1, CPLES_CSV ); if (fpCSV) VSIFPrintfL( fpCSV, "%s", pszEscaped ); CPLFree( pszEscaped ); if (fpCSVT) { switch( poFeatureDefn->GetFieldDefn(iField)->GetType() ) { case OFTInteger: VSIFPrintfL( fpCSVT, "%s", "Integer"); break; case OFTReal: VSIFPrintfL( fpCSVT, "%s", "Real"); break; case OFTDate: VSIFPrintfL( fpCSVT, "%s", "Date"); break; case OFTTime: VSIFPrintfL( fpCSVT, "%s", "Time"); break; case OFTDateTime: VSIFPrintfL( fpCSVT, "%s", "DateTime"); break; default: VSIFPrintfL( fpCSVT, "%s", "String"); break; } int nWidth = poFeatureDefn->GetFieldDefn(iField)->GetWidth(); int nPrecision = poFeatureDefn->GetFieldDefn(iField)->GetPrecision(); if (nWidth != 0) { if (nPrecision != 0) VSIFPrintfL( fpCSVT, "(%d.%d)", nWidth, nPrecision); else VSIFPrintfL( fpCSVT, "(%d)", nWidth); } } } /* The CSV driver will not recognize single column tables, so add */ /* a fake second blank field */ if( poFeatureDefn->GetFieldCount() == 1 ) { if (fpCSV) VSIFPrintfL( fpCSV, "%c", chDelimiter ); } if( bUseCRLF ) { if (fpCSV) VSIFPutcL( 13, fpCSV ); if (fpCSVT) VSIFPutcL( 13, fpCSVT ); } if (fpCSV) VSIFPutcL( '\n', fpCSV ); if (fpCSVT) VSIFPutcL( '\n', fpCSVT ); if (fpCSVT) VSIFCloseL(fpCSVT); } if (fpCSV == NULL) return OGRERR_FAILURE; else return OGRERR_NONE; }
const char *DTEDCreate( const char *pszFilename, int nLevel, int nLLOriginLat, int nLLOriginLong ) { VSILFILE *fp; unsigned char achRecord[3601*2 + 12]; int nXSize, nYSize, nReferenceLat, iProfile; /* -------------------------------------------------------------------- */ /* Establish resolution. */ /* -------------------------------------------------------------------- */ if( nLevel == 0 ) { nXSize = 121; nYSize = 121; } else if( nLevel == 1 ) { nXSize = 1201; nYSize = 1201; } else if( nLevel == 2 ) { nXSize = 3601; nYSize = 3601; } else { return CPLSPrintf( "Illegal DTED Level value %d, only 0-2 allowed.", nLevel ); } nReferenceLat = nLLOriginLat < 0 ? - (nLLOriginLat + 1) : nLLOriginLat; if( nReferenceLat >= 80 ) nXSize = (nXSize - 1) / 6 + 1; else if( nReferenceLat >= 75 ) nXSize = (nXSize - 1) / 4 + 1; else if( nReferenceLat >= 70 ) nXSize = (nXSize - 1) / 3 + 1; else if( nReferenceLat >= 50 ) nXSize = (nXSize - 1) / 2 + 1; /* -------------------------------------------------------------------- */ /* Open the file. */ /* -------------------------------------------------------------------- */ fp = VSIFOpenL( pszFilename, "wb" ); if( fp == NULL ) { return CPLSPrintf( "Unable to create file `%s'.", pszFilename ); } /* -------------------------------------------------------------------- */ /* Format and write the UHL record. */ /* -------------------------------------------------------------------- */ memset( achRecord, ' ', DTED_UHL_SIZE ); DTEDFormat( achRecord, sizeof(achRecord), 0, "UHL1" ); DTEDFormatDMS( achRecord, sizeof(achRecord), 4, nLLOriginLong, "LONG", NULL ); DTEDFormatDMS( achRecord, sizeof(achRecord), 12, nLLOriginLat, "LAT", NULL ); DTEDFormat( achRecord, sizeof(achRecord), 20, "%04d", (3600 / (nXSize-1)) * 10 ); DTEDFormat( achRecord, sizeof(achRecord), 24, "%04d", (3600 / (nYSize-1)) * 10 ); DTEDFormat( achRecord, sizeof(achRecord), 28, "%4s", DTED_ABS_VERT_ACC ); DTEDFormat( achRecord, sizeof(achRecord), 32, "%-3s", DTED_SECURITY ); DTEDFormat( achRecord, sizeof(achRecord), 47, "%04d", nXSize ); DTEDFormat( achRecord, sizeof(achRecord), 51, "%04d", nYSize ); DTEDFormat( achRecord, sizeof(achRecord), 55, "%c", '0' ); if( VSIFWriteL( achRecord, DTED_UHL_SIZE, 1, fp ) != 1 ) return "UHL record write failed."; /* -------------------------------------------------------------------- */ /* Format and write the DSI record. */ /* -------------------------------------------------------------------- */ memset( achRecord, ' ', DTED_DSI_SIZE ); DTEDFormat( achRecord, sizeof(achRecord), 0, "DSI" ); DTEDFormat( achRecord, sizeof(achRecord), 3, "%1s", DTED_SECURITY ); DTEDFormat( achRecord, sizeof(achRecord), 59, "DTED%d", nLevel ); DTEDFormat( achRecord, sizeof(achRecord), 64, "%015d", 0 ); DTEDFormat( achRecord, sizeof(achRecord), 87, "%02d", DTED_EDITION ); DTEDFormat( achRecord, sizeof(achRecord), 89, "%c", 'A' ); DTEDFormat( achRecord, sizeof(achRecord), 90, "%04d", 0 ); DTEDFormat( achRecord, sizeof(achRecord), 94, "%04d", 0 ); DTEDFormat( achRecord, sizeof(achRecord), 98, "%04d", 0 ); DTEDFormat( achRecord, sizeof(achRecord), 126, "PRF89020B"); DTEDFormat( achRecord, sizeof(achRecord), 135, "00"); DTEDFormat( achRecord, sizeof(achRecord), 137, "0005"); DTEDFormat( achRecord, sizeof(achRecord), 141, "MSL" ); DTEDFormat( achRecord, sizeof(achRecord), 144, "WGS84" ); /* origin */ DTEDFormatDMS( achRecord, sizeof(achRecord), 185, nLLOriginLat, "LAT", "%02d%02d%02d.0%c" ); DTEDFormatDMS( achRecord, sizeof(achRecord), 194, nLLOriginLong, "LONG", "%03d%02d%02d.0%c" ); /* SW */ DTEDFormatDMS( achRecord, sizeof(achRecord), 204, nLLOriginLat, "LAT", "%02d%02d%02d%c" ); DTEDFormatDMS( achRecord, sizeof(achRecord), 211, nLLOriginLong, "LONG", NULL ); /* NW */ DTEDFormatDMS( achRecord, sizeof(achRecord), 219, nLLOriginLat+1, "LAT", "%02d%02d%02d%c" ); DTEDFormatDMS( achRecord, sizeof(achRecord), 226, nLLOriginLong, "LONG", NULL ); /* NE */ DTEDFormatDMS( achRecord, sizeof(achRecord), 234, nLLOriginLat+1, "LAT", "%02d%02d%02d%c" ); DTEDFormatDMS( achRecord, sizeof(achRecord), 241, nLLOriginLong+1, "LONG", NULL ); /* SE */ DTEDFormatDMS( achRecord, sizeof(achRecord), 249, nLLOriginLat, "LAT", "%02d%02d%02d%c" ); DTEDFormatDMS( achRecord, sizeof(achRecord), 256, nLLOriginLong+1, "LONG", NULL ); DTEDFormat( achRecord, sizeof(achRecord), 264, "0000000.0" ); DTEDFormat( achRecord, sizeof(achRecord), 264, "0000000.0" ); DTEDFormat( achRecord, sizeof(achRecord), 273, "%04d", (3600 / (nYSize-1)) * 10 ); DTEDFormat( achRecord, sizeof(achRecord), 277, "%04d", (3600 / (nXSize-1)) * 10 ); DTEDFormat( achRecord, sizeof(achRecord), 281, "%04d", nYSize ); DTEDFormat( achRecord, sizeof(achRecord), 285, "%04d", nXSize ); DTEDFormat( achRecord, sizeof(achRecord), 289, "%02d", 0 ); if( VSIFWriteL( achRecord, DTED_DSI_SIZE, 1, fp ) != 1 ) return "DSI record write failed."; /* -------------------------------------------------------------------- */ /* Create and write ACC record. */ /* -------------------------------------------------------------------- */ memset( achRecord, ' ', DTED_ACC_SIZE ); DTEDFormat( achRecord, sizeof(achRecord), 0, "ACC" ); DTEDFormat( achRecord, sizeof(achRecord), 3, "NA" ); DTEDFormat( achRecord, sizeof(achRecord), 7, "NA" ); DTEDFormat( achRecord, sizeof(achRecord), 11, "NA" ); DTEDFormat( achRecord, sizeof(achRecord), 15, "NA" ); DTEDFormat( achRecord, sizeof(achRecord), 55, "00" ); if( VSIFWriteL( achRecord, DTED_ACC_SIZE, 1, fp ) != 1 ) return "ACC record write failed."; /* -------------------------------------------------------------------- */ /* Write blank template profile data records. */ /* -------------------------------------------------------------------- */ memset( achRecord, 0, nYSize*2 + 12 ); memset( achRecord + 8, 0xff, nYSize*2 ); achRecord[0] = 0252; for( iProfile = 0; iProfile < nXSize; iProfile++ ) { achRecord[1] = 0; achRecord[2] = (GByte) (iProfile / 256); achRecord[3] = (GByte) (iProfile % 256); achRecord[4] = (GByte) (iProfile / 256); achRecord[5] = (GByte) (iProfile % 256); if( VSIFWriteL( achRecord, nYSize*2 + 12, 1, fp ) != 1 ) return "Data record write failed."; } if( VSIFCloseL( fp ) != 0 ) return "I/O error"; return NULL; }
static void msTransformToGeospatialPDF(imageObj *img, mapObj *map, cairo_renderer *r) { /* We need a GDAL 1.10 PDF driver at runtime, but as far as the C API is concerned, GDAL 1.9 is */ /* largely sufficient. */ #if defined(USE_GDAL) && defined(GDAL_VERSION_NUM) && GDAL_VERSION_NUM >= 1900 GDALDatasetH hDS = NULL; const char* pszGEO_ENCODING = NULL; GDALDriverH hPDFDriver = NULL; const char* pszVirtualIO = NULL; int bVirtualIO = FALSE; char* pszTmpFilename = NULL; VSILFILE* fp = NULL; if (map == NULL) return; pszGEO_ENCODING = msGetOutputFormatOption(img->format, "GEO_ENCODING", NULL); if (pszGEO_ENCODING == NULL) return; msGDALInitialize(); hPDFDriver = GDALGetDriverByName("PDF"); if (hPDFDriver == NULL) return; /* When compiled against libpoppler, the PDF driver is VirtualIO capable */ /* but not, when it is compiled against libpodofo. */ pszVirtualIO = GDALGetMetadataItem( hPDFDriver, GDAL_DCAP_VIRTUALIO, NULL ); if (pszVirtualIO) bVirtualIO = CSLTestBoolean(pszVirtualIO); if (bVirtualIO) pszTmpFilename = msTmpFile(map, NULL, "/vsimem/mscairopdf/", "pdf"); else pszTmpFilename = msTmpFile(map, map->mappath, NULL, "pdf"); /* Copy content of outputStream buffer into file */ fp = VSIFOpenL(pszTmpFilename, "wb"); if (fp == NULL) { msFree(pszTmpFilename); return; } VSIFWriteL(r->outputStream->data, 1, r->outputStream->size, fp); VSIFCloseL(fp); fp = NULL; hDS = GDALOpen(pszTmpFilename, GA_Update); if ( hDS != NULL ) { char* pszWKT = msProjectionObj2OGCWKT( &(map->projection) ); if( pszWKT != NULL ) { double adfGeoTransform[6]; int i; /* Add user-specified options */ for( i = 0; i < img->format->numformatoptions; i++ ) { const char* pszOption = img->format->formatoptions[i]; if( strncasecmp(pszOption,"METADATA_ITEM:",14) == 0 ) { char* pszKey = NULL; const char* pszValue = CPLParseNameValue(pszOption + 14, &pszKey); if( pszKey != NULL ) { GDALSetMetadataItem(hDS, pszKey, pszValue, NULL); CPLFree(pszKey); } } } /* We need to rescale the geotransform because GDAL will not necessary */ /* open the PDF with the DPI that was used to generate it */ memcpy(adfGeoTransform, map->gt.geotransform, 6 * sizeof(double)); adfGeoTransform[1] = adfGeoTransform[1] * map->width / GDALGetRasterXSize(hDS); adfGeoTransform[5] = adfGeoTransform[5] * map->height / GDALGetRasterYSize(hDS); GDALSetGeoTransform(hDS, adfGeoTransform); GDALSetProjection(hDS, pszWKT); msFree( pszWKT ); pszWKT = NULL; CPLSetThreadLocalConfigOption("GDAL_PDF_GEO_ENCODING", pszGEO_ENCODING); GDALClose(hDS); hDS = NULL; CPLSetThreadLocalConfigOption("GDAL_PDF_GEO_ENCODING", NULL); /* We need to replace the buffer with the content of the GDAL file */ fp = VSIFOpenL(pszTmpFilename, "rb"); if( fp != NULL ) { int nFileSize; VSIFSeekL(fp, 0, SEEK_END); nFileSize = (int)VSIFTellL(fp); msBufferResize(r->outputStream, nFileSize); VSIFSeekL(fp, 0, SEEK_SET); r->outputStream->size = VSIFReadL(r->outputStream->data, 1, nFileSize, fp); VSIFCloseL(fp); fp = NULL; } } } if ( hDS != NULL ) GDALClose(hDS); VSIUnlink(pszTmpFilename); msFree(pszTmpFilename); #endif }
static GDALDataset * VRTCreateCopy( const char * pszFilename, GDALDataset *poSrcDS, int /* bStrict */, char ** /* papszOptions */, GDALProgressFunc /* pfnProgress */, void * /* pProgressData */ ) { CPLAssert( NULL != poSrcDS ); /* -------------------------------------------------------------------- */ /* If the source dataset is a virtual dataset then just write */ /* it to disk as a special case to avoid extra layers of */ /* indirection. */ /* -------------------------------------------------------------------- */ if( poSrcDS->GetDriver() != NULL && EQUAL(poSrcDS->GetDriver()->GetDescription(),"VRT") ) { /* -------------------------------------------------------------------- */ /* Convert tree to a single block of XML text. */ /* -------------------------------------------------------------------- */ char *pszVRTPath = CPLStrdup(CPLGetPath(pszFilename)); reinterpret_cast<VRTDataset *>( poSrcDS )->UnsetPreservedRelativeFilenames(); CPLXMLNode *psDSTree = reinterpret_cast<VRTDataset *>( poSrcDS )->SerializeToXML( pszVRTPath ); char *pszXML = CPLSerializeXMLTree( psDSTree ); CPLDestroyXMLNode( psDSTree ); CPLFree( pszVRTPath ); /* -------------------------------------------------------------------- */ /* Write to disk. */ /* -------------------------------------------------------------------- */ GDALDataset* pCopyDS = NULL; if( 0 != strlen( pszFilename ) ) { VSILFILE *fpVRT = VSIFOpenL( pszFilename, "wb" ); if( fpVRT == NULL ) { CPLError(CE_Failure, CPLE_AppDefined, "Cannot create %s", pszFilename); CPLFree( pszXML ); return NULL; } bool bRet = VSIFWriteL( pszXML, strlen(pszXML), 1, fpVRT ) > 0; if( VSIFCloseL( fpVRT ) != 0 ) bRet = false; if( bRet ) pCopyDS = reinterpret_cast<GDALDataset *>( GDALOpen( pszFilename, GA_Update ) ); } else { /* No destination file is given, so pass serialized XML directly. */ pCopyDS = reinterpret_cast<GDALDataset *>( GDALOpen( pszXML, GA_Update ) ); } CPLFree( pszXML ); return pCopyDS; } /* -------------------------------------------------------------------- */ /* Create the virtual dataset. */ /* -------------------------------------------------------------------- */ VRTDataset *poVRTDS = reinterpret_cast<VRTDataset *>( VRTDataset::Create( pszFilename, poSrcDS->GetRasterXSize(), poSrcDS->GetRasterYSize(), 0, GDT_Byte, NULL ) ); if( poVRTDS == NULL ) return NULL; /* -------------------------------------------------------------------- */ /* Do we have a geotransform? */ /* -------------------------------------------------------------------- */ double adfGeoTransform[6] = { 0.0 }; if( poSrcDS->GetGeoTransform( adfGeoTransform ) == CE_None ) { poVRTDS->SetGeoTransform( adfGeoTransform ); } /* -------------------------------------------------------------------- */ /* Copy projection */ /* -------------------------------------------------------------------- */ poVRTDS->SetProjection( poSrcDS->GetProjectionRef() ); /* -------------------------------------------------------------------- */ /* Emit dataset level metadata. */ /* -------------------------------------------------------------------- */ poVRTDS->SetMetadata( poSrcDS->GetMetadata() ); /* -------------------------------------------------------------------- */ /* Copy any special domains that should be transportable. */ /* -------------------------------------------------------------------- */ char **papszMD = poSrcDS->GetMetadata( "RPC" ); if( papszMD ) poVRTDS->SetMetadata( papszMD, "RPC" ); papszMD = poSrcDS->GetMetadata( "IMD" ); if( papszMD ) poVRTDS->SetMetadata( papszMD, "IMD" ); papszMD = poSrcDS->GetMetadata( "GEOLOCATION" ); if( papszMD ) poVRTDS->SetMetadata( papszMD, "GEOLOCATION" ); /* -------------------------------------------------------------------- */ /* GCPs */ /* -------------------------------------------------------------------- */ if( poSrcDS->GetGCPCount() > 0 ) { poVRTDS->SetGCPs( poSrcDS->GetGCPCount(), poSrcDS->GetGCPs(), poSrcDS->GetGCPProjection() ); } /* -------------------------------------------------------------------- */ /* Loop over all the bands. */ /* -------------------------------------------------------------------- */ for( int iBand = 0; iBand < poSrcDS->GetRasterCount(); iBand++ ) { GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( iBand+1 ); /* -------------------------------------------------------------------- */ /* Create the band with the appropriate band type. */ /* -------------------------------------------------------------------- */ poVRTDS->AddBand( poSrcBand->GetRasterDataType(), NULL ); VRTSourcedRasterBand *poVRTBand = reinterpret_cast<VRTSourcedRasterBand *>( poVRTDS->GetRasterBand( iBand+1 ) ); /* -------------------------------------------------------------------- */ /* Setup source mapping. */ /* -------------------------------------------------------------------- */ poVRTBand->AddSimpleSource( poSrcBand ); /* -------------------------------------------------------------------- */ /* Emit various band level metadata. */ /* -------------------------------------------------------------------- */ poVRTBand->CopyCommonInfoFrom( poSrcBand ); /* -------------------------------------------------------------------- */ /* Add specific mask band. */ /* -------------------------------------------------------------------- */ if( (poSrcBand->GetMaskFlags() & (GMF_PER_DATASET | GMF_ALL_VALID | GMF_NODATA)) == 0) { VRTSourcedRasterBand* poVRTMaskBand = new VRTSourcedRasterBand( poVRTDS, 0, poSrcBand->GetMaskBand()->GetRasterDataType(), poSrcDS->GetRasterXSize(), poSrcDS->GetRasterYSize()); poVRTMaskBand->AddMaskBandSource( poSrcBand ); poVRTBand->SetMaskBand( poVRTMaskBand ); } } /* -------------------------------------------------------------------- */ /* Add dataset mask band */ /* -------------------------------------------------------------------- */ if( poSrcDS->GetRasterCount() != 0 && poSrcDS->GetRasterBand(1) != NULL && poSrcDS->GetRasterBand(1)->GetMaskFlags() == GMF_PER_DATASET ) { GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand(1); VRTSourcedRasterBand* poVRTMaskBand = new VRTSourcedRasterBand( poVRTDS, 0, poSrcBand->GetMaskBand()->GetRasterDataType(), poSrcDS->GetRasterXSize(), poSrcDS->GetRasterYSize() ); poVRTMaskBand->AddMaskBandSource( poSrcBand ); poVRTDS->SetMaskBand( poVRTMaskBand ); } poVRTDS->FlushCache(); return poVRTDS; }
OGRLayer * OGRShapeDataSource::ICreateLayer( const char * pszLayerName, OGRSpatialReference *poSRS, OGRwkbGeometryType eType, char ** papszOptions ) { SHPHandle hSHP; DBFHandle hDBF; int nShapeType; /* To ensure that existing layers are created */ GetLayerCount(); /* -------------------------------------------------------------------- */ /* Check that the layer doesn't already exist. */ /* -------------------------------------------------------------------- */ if (GetLayerByName(pszLayerName) != NULL) { CPLError( CE_Failure, CPLE_AppDefined, "Layer '%s' already exists", pszLayerName); return NULL; } /* -------------------------------------------------------------------- */ /* Verify we are in update mode. */ /* -------------------------------------------------------------------- */ if( !bDSUpdate ) { CPLError( CE_Failure, CPLE_NoWriteAccess, "Data source %s opened read-only.\n" "New layer %s cannot be created.\n", pszName, pszLayerName ); return NULL; } /* -------------------------------------------------------------------- */ /* Figure out what type of layer we need. */ /* -------------------------------------------------------------------- */ if( eType == wkbUnknown || eType == wkbLineString ) nShapeType = SHPT_ARC; else if( eType == wkbPoint ) nShapeType = SHPT_POINT; else if( eType == wkbPolygon ) nShapeType = SHPT_POLYGON; else if( eType == wkbMultiPoint ) nShapeType = SHPT_MULTIPOINT; else if( eType == wkbPoint25D ) nShapeType = SHPT_POINTZ; else if( eType == wkbLineString25D ) nShapeType = SHPT_ARCZ; else if( eType == wkbMultiLineString ) nShapeType = SHPT_ARC; else if( eType == wkbMultiLineString25D ) nShapeType = SHPT_ARCZ; else if( eType == wkbPolygon25D ) nShapeType = SHPT_POLYGONZ; else if( eType == wkbMultiPolygon ) nShapeType = SHPT_POLYGON; else if( eType == wkbMultiPolygon25D ) nShapeType = SHPT_POLYGONZ; else if( eType == wkbMultiPoint25D ) nShapeType = SHPT_MULTIPOINTZ; else if( eType == wkbNone ) nShapeType = SHPT_NULL; else nShapeType = -1; /* -------------------------------------------------------------------- */ /* Has the application overridden this with a special creation */ /* option? */ /* -------------------------------------------------------------------- */ const char *pszOverride = CSLFetchNameValue( papszOptions, "SHPT" ); if( pszOverride == NULL ) /* ignore */; else if( EQUAL(pszOverride,"POINT") ) { nShapeType = SHPT_POINT; eType = wkbPoint; } else if( EQUAL(pszOverride,"ARC") ) { nShapeType = SHPT_ARC; eType = wkbLineString; } else if( EQUAL(pszOverride,"POLYGON") ) { nShapeType = SHPT_POLYGON; eType = wkbPolygon; } else if( EQUAL(pszOverride,"MULTIPOINT") ) { nShapeType = SHPT_MULTIPOINT; eType = wkbMultiPoint; } else if( EQUAL(pszOverride,"POINTZ") ) { nShapeType = SHPT_POINTZ; eType = wkbPoint25D; } else if( EQUAL(pszOverride,"ARCZ") ) { nShapeType = SHPT_ARCZ; eType = wkbLineString25D; } else if( EQUAL(pszOverride,"POLYGONZ") ) { nShapeType = SHPT_POLYGONZ; eType = wkbPolygon25D; } else if( EQUAL(pszOverride,"MULTIPOINTZ") ) { nShapeType = SHPT_MULTIPOINTZ; eType = wkbMultiPoint25D; } else if( EQUAL(pszOverride,"NONE") || EQUAL(pszOverride,"NULL") ) { nShapeType = SHPT_NULL; eType = wkbNone; } else { CPLError( CE_Failure, CPLE_NotSupported, "Unknown SHPT value of `%s' passed to Shapefile layer\n" "creation. Creation aborted.\n", pszOverride ); return NULL; } if( nShapeType == -1 ) { CPLError( CE_Failure, CPLE_NotSupported, "Geometry type of `%s' not supported in shapefiles.\n" "Type can be overridden with a layer creation option\n" "of SHPT=POINT/ARC/POLYGON/MULTIPOINT/POINTZ/ARCZ/POLYGONZ/MULTIPOINTZ.\n", OGRGeometryTypeToName(eType) ); return NULL; } /* -------------------------------------------------------------------- */ /* What filename do we use, excluding the extension? */ /* -------------------------------------------------------------------- */ char *pszFilenameWithoutExt; if( bSingleFileDataSource && nLayers == 0 ) { char *pszPath = CPLStrdup(CPLGetPath(pszName)); char *pszFBasename = CPLStrdup(CPLGetBasename(pszName)); pszFilenameWithoutExt = CPLStrdup(CPLFormFilename(pszPath, pszFBasename, NULL)); CPLFree( pszFBasename ); CPLFree( pszPath ); } else if( bSingleFileDataSource ) { /* This is a very weird use case : the user creates/open a datasource */ /* made of a single shapefile 'foo.shp' and wants to add a new layer */ /* to it, 'bar'. So we create a new shapefile 'bar.shp' in the same */ /* directory as 'foo.shp' */ /* So technically, we will not be any longer a single file */ /* datasource ... Ahem ahem */ char *pszPath = CPLStrdup(CPLGetPath(pszName)); pszFilenameWithoutExt = CPLStrdup(CPLFormFilename(pszPath,pszLayerName,NULL)); CPLFree( pszPath ); } else pszFilenameWithoutExt = CPLStrdup(CPLFormFilename(pszName,pszLayerName,NULL)); /* -------------------------------------------------------------------- */ /* Create the shapefile. */ /* -------------------------------------------------------------------- */ char *pszFilename; int b2GBLimit = CSLTestBoolean(CSLFetchNameValueDef( papszOptions, "2GB_LIMIT", "FALSE" )); if( nShapeType != SHPT_NULL ) { pszFilename = CPLStrdup(CPLFormFilename( NULL, pszFilenameWithoutExt, "shp" )); hSHP = SHPCreateLL( pszFilename, nShapeType, (SAHooks*) VSI_SHP_GetHook(b2GBLimit) ); if( hSHP == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open Shapefile `%s'.\n", pszFilename ); CPLFree( pszFilename ); CPLFree( pszFilenameWithoutExt ); return NULL; } SHPSetFastModeReadObject( hSHP, TRUE ); CPLFree( pszFilename ); } else hSHP = NULL; /* -------------------------------------------------------------------- */ /* Has a specific LDID been specified by the caller? */ /* -------------------------------------------------------------------- */ const char *pszLDID = CSLFetchNameValue( papszOptions, "ENCODING" ); /* -------------------------------------------------------------------- */ /* Create a DBF file. */ /* -------------------------------------------------------------------- */ pszFilename = CPLStrdup(CPLFormFilename( NULL, pszFilenameWithoutExt, "dbf" )); if( pszLDID != NULL ) hDBF = DBFCreateLL( pszFilename, pszLDID, (SAHooks*) VSI_SHP_GetHook(b2GBLimit) ); else hDBF = DBFCreateLL( pszFilename, "LDID/87",(SAHooks*) VSI_SHP_GetHook(b2GBLimit) ); if( hDBF == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Failed to open Shape DBF file `%s'.\n", pszFilename ); CPLFree( pszFilename ); CPLFree( pszFilenameWithoutExt ); SHPClose(hSHP); return NULL; } CPLFree( pszFilename ); /* -------------------------------------------------------------------- */ /* Create the .prj file, if required. */ /* -------------------------------------------------------------------- */ if( poSRS != NULL ) { char *pszWKT = NULL; CPLString osPrjFile = CPLFormFilename( NULL, pszFilenameWithoutExt, "prj"); VSILFILE *fp; /* the shape layer needs it's own copy */ poSRS = poSRS->Clone(); poSRS->morphToESRI(); if( poSRS->exportToWkt( &pszWKT ) == OGRERR_NONE && (fp = VSIFOpenL( osPrjFile, "wt" )) != NULL ) { VSIFWriteL( pszWKT, strlen(pszWKT), 1, fp ); VSIFCloseL( fp ); } CPLFree( pszWKT ); poSRS->morphFromESRI(); } /* -------------------------------------------------------------------- */ /* Create the layer object. */ /* -------------------------------------------------------------------- */ OGRShapeLayer *poLayer; /* OGRShapeLayer constructor expects a filename with an extension (that could be */ /* random actually), otherwise this is going to cause problems with layer */ /* names that have a dot (not speaking about the one before the shp) */ pszFilename = CPLStrdup(CPLFormFilename( NULL, pszFilenameWithoutExt, "shp" )); poLayer = new OGRShapeLayer( this, pszFilename, hSHP, hDBF, poSRS, TRUE, TRUE, eType ); CPLFree( pszFilenameWithoutExt ); CPLFree( pszFilename ); poLayer->SetResizeAtClose( CSLFetchBoolean( papszOptions, "RESIZE", FALSE ) ); poLayer->CreateSpatialIndexAtClose( CSLFetchBoolean( papszOptions, "SPATIAL_INDEX", FALSE ) ); poLayer->SetModificationDate( CSLFetchNameValue( papszOptions, "DBF_DATE_LAST_UPDATE" ) ); /* -------------------------------------------------------------------- */ /* Add layer to data source layer list. */ /* -------------------------------------------------------------------- */ AddLayer(poLayer); return poLayer; }
GDALDataset * AAIGDataset::CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int /* bStrict */, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ) { const int nBands = poSrcDS->GetRasterCount(); const int nXSize = poSrcDS->GetRasterXSize(); const int nYSize = poSrcDS->GetRasterYSize(); // Some rudimentary checks. if( nBands != 1 ) { CPLError(CE_Failure, CPLE_NotSupported, "AAIG driver doesn't support %d bands. Must be 1 band.", nBands); return nullptr; } if( !pfnProgress(0.0, nullptr, pProgressData) ) return nullptr; // Create the dataset. VSILFILE *fpImage = VSIFOpenL(pszFilename, "wt"); if( fpImage == nullptr ) { CPLError(CE_Failure, CPLE_OpenFailed, "Unable to create file %s.", pszFilename); return nullptr; } // Write ASCII Grid file header. double adfGeoTransform[6] = {}; char szHeader[2000] = {}; const char *pszForceCellsize = CSLFetchNameValue(papszOptions, "FORCE_CELLSIZE"); poSrcDS->GetGeoTransform(adfGeoTransform); if( std::abs(adfGeoTransform[1] + adfGeoTransform[5]) < 0.0000001 || std::abs(adfGeoTransform[1]-adfGeoTransform[5]) < 0.0000001 || (pszForceCellsize && CPLTestBool(pszForceCellsize)) ) { CPLsnprintf( szHeader, sizeof(szHeader), "ncols %d\n" "nrows %d\n" "xllcorner %.12f\n" "yllcorner %.12f\n" "cellsize %.12f\n", nXSize, nYSize, adfGeoTransform[0], adfGeoTransform[3] - nYSize * adfGeoTransform[1], adfGeoTransform[1]); } else { if( pszForceCellsize == nullptr ) CPLError(CE_Warning, CPLE_AppDefined, "Producing a Golden Surfer style file with DX and DY " "instead of CELLSIZE since the input pixels are " "non-square. Use the FORCE_CELLSIZE=TRUE creation " "option to force use of DX for even though this will " "be distorted. Most ASCII Grid readers (ArcGIS " "included) do not support the DX and DY parameters."); CPLsnprintf( szHeader, sizeof(szHeader), "ncols %d\n" "nrows %d\n" "xllcorner %.12f\n" "yllcorner %.12f\n" "dx %.12f\n" "dy %.12f\n", nXSize, nYSize, adfGeoTransform[0], adfGeoTransform[3] + nYSize * adfGeoTransform[5], adfGeoTransform[1], fabs(adfGeoTransform[5])); } // Builds the format string used for printing float values. char szFormatFloat[32] = { '\0' }; strcpy(szFormatFloat, " %.20g"); const char *pszDecimalPrecision = CSLFetchNameValue(papszOptions, "DECIMAL_PRECISION"); const char *pszSignificantDigits = CSLFetchNameValue(papszOptions, "SIGNIFICANT_DIGITS"); bool bIgnoreSigDigits = false; if( pszDecimalPrecision && pszSignificantDigits ) { CPLError(CE_Warning, CPLE_AppDefined, "Conflicting precision arguments, using DECIMAL_PRECISION"); bIgnoreSigDigits = true; } int nPrecision; if ( pszSignificantDigits && !bIgnoreSigDigits ) { nPrecision = atoi(pszSignificantDigits); if (nPrecision >= 0) snprintf(szFormatFloat, sizeof(szFormatFloat), " %%.%dg", nPrecision); CPLDebug("AAIGrid", "Setting precision format: %s", szFormatFloat); } else if( pszDecimalPrecision ) { nPrecision = atoi(pszDecimalPrecision); if ( nPrecision >= 0 ) snprintf(szFormatFloat, sizeof(szFormatFloat), " %%.%df", nPrecision); CPLDebug("AAIGrid", "Setting precision format: %s", szFormatFloat); } // Handle nodata (optionally). GDALRasterBand *poBand = poSrcDS->GetRasterBand(1); const bool bReadAsInt = poBand->GetRasterDataType() == GDT_Byte || poBand->GetRasterDataType() == GDT_Int16 || poBand->GetRasterDataType() == GDT_UInt16 || poBand->GetRasterDataType() == GDT_Int32; // Write `nodata' value to header if it is exists in source dataset int bSuccess = FALSE; const double dfNoData = poBand->GetNoDataValue(&bSuccess); if ( bSuccess ) { snprintf(szHeader + strlen(szHeader), sizeof(szHeader) - strlen(szHeader), "%s", "NODATA_value "); if( bReadAsInt ) snprintf(szHeader + strlen(szHeader), sizeof(szHeader) - strlen(szHeader), "%d", static_cast<int>(dfNoData)); else CPLsnprintf(szHeader + strlen(szHeader), sizeof(szHeader) - strlen(szHeader), szFormatFloat, dfNoData); snprintf(szHeader + strlen(szHeader), sizeof(szHeader) - strlen(szHeader), "%s", "\n"); } if( VSIFWriteL(szHeader, strlen(szHeader), 1, fpImage) != 1) { CPL_IGNORE_RET_VAL(VSIFCloseL(fpImage)); return nullptr; } // Loop over image, copying image data. // Write scanlines to output file int *panScanline = bReadAsInt ? static_cast<int *>(CPLMalloc( nXSize * GDALGetDataTypeSizeBytes(GDT_Int32))) : nullptr; double *padfScanline = bReadAsInt ? nullptr : static_cast<double *>(CPLMalloc( nXSize * GDALGetDataTypeSizeBytes(GDT_Float64))); CPLErr eErr = CE_None; bool bHasOutputDecimalDot = false; for( int iLine = 0; eErr == CE_None && iLine < nYSize; iLine++ ) { CPLString osBuf; eErr = poBand->RasterIO( GF_Read, 0, iLine, nXSize, 1, bReadAsInt ? reinterpret_cast<void *>(panScanline) : reinterpret_cast<void *>(padfScanline), nXSize, 1, bReadAsInt ? GDT_Int32 : GDT_Float64, 0, 0, nullptr); if( bReadAsInt ) { for ( int iPixel = 0; iPixel < nXSize; iPixel++ ) { snprintf(szHeader, sizeof(szHeader), " %d", panScanline[iPixel]); osBuf += szHeader; if( (iPixel & 1023) == 0 || iPixel == nXSize - 1 ) { if ( VSIFWriteL(osBuf, static_cast<int>(osBuf.size()), 1, fpImage) != 1 ) { eErr = CE_Failure; CPLError(CE_Failure, CPLE_AppDefined, "Write failed, disk full?"); break; } osBuf = ""; } } } else { for ( int iPixel = 0; iPixel < nXSize; iPixel++ ) { CPLsnprintf(szHeader, sizeof(szHeader), szFormatFloat, padfScanline[iPixel]); // Make sure that as least one value has a decimal point (#6060) if( !bHasOutputDecimalDot ) { if( strchr(szHeader, '.') || strchr(szHeader, 'e') || strchr(szHeader, 'E') ) { bHasOutputDecimalDot = true; } else if( !CPLIsInf(padfScanline[iPixel]) && !CPLIsNan(padfScanline[iPixel]) ) { strcat(szHeader, ".0"); bHasOutputDecimalDot = true; } } osBuf += szHeader; if( (iPixel & 1023) == 0 || iPixel == nXSize - 1 ) { if ( VSIFWriteL(osBuf, static_cast<int>(osBuf.size()), 1, fpImage) != 1 ) { eErr = CE_Failure; CPLError(CE_Failure, CPLE_AppDefined, "Write failed, disk full?"); break; } osBuf = ""; } } } if( VSIFWriteL("\n", 1, 1, fpImage) != 1 ) eErr = CE_Failure; if( eErr == CE_None && !pfnProgress((iLine + 1) / static_cast<double>(nYSize), nullptr, pProgressData) ) { eErr = CE_Failure; CPLError(CE_Failure, CPLE_UserInterrupt, "User terminated CreateCopy()"); } } CPLFree(panScanline); CPLFree(padfScanline); if( VSIFCloseL(fpImage) != 0 ) eErr = CE_Failure; if( eErr != CE_None ) return nullptr; // Try to write projection file. const char *pszOriginalProjection = poSrcDS->GetProjectionRef(); if( !EQUAL(pszOriginalProjection, "") ) { char *pszDirname = CPLStrdup(CPLGetPath(pszFilename)); char *pszBasename = CPLStrdup(CPLGetBasename(pszFilename)); char *pszPrjFilename = CPLStrdup(CPLFormFilename(pszDirname, pszBasename, "prj")); VSILFILE *fp = VSIFOpenL(pszPrjFilename, "wt"); if (fp != nullptr) { OGRSpatialReference oSRS; oSRS.importFromWkt(pszOriginalProjection); oSRS.morphToESRI(); char *pszESRIProjection = nullptr; oSRS.exportToWkt(&pszESRIProjection); CPL_IGNORE_RET_VAL(VSIFWriteL(pszESRIProjection, 1, strlen(pszESRIProjection), fp)); CPL_IGNORE_RET_VAL(VSIFCloseL(fp)); CPLFree(pszESRIProjection); } else { CPLError(CE_Failure, CPLE_FileIO, "Unable to create file %s.", pszPrjFilename); } CPLFree(pszDirname); CPLFree(pszBasename); CPLFree(pszPrjFilename); } // Re-open dataset, and copy any auxiliary pam information. // If writing to stdout, we can't reopen it, so return // a fake dataset to make the caller happy. CPLPushErrorHandler(CPLQuietErrorHandler); GDALPamDataset *poDS = reinterpret_cast<GDALPamDataset *>(GDALOpen(pszFilename, GA_ReadOnly)); CPLPopErrorHandler(); if (poDS) { poDS->CloneInfo(poSrcDS, GCIF_PAM_DEFAULT); return poDS; } CPLErrorReset(); AAIGDataset *poAAIG_DS = new AAIGDataset(); poAAIG_DS->nRasterXSize = nXSize; poAAIG_DS->nRasterYSize = nYSize; poAAIG_DS->nBands = 1; poAAIG_DS->SetBand(1, new AAIGRasterBand(poAAIG_DS, 1)); return poAAIG_DS; }
static void WriteShort(VSILFILE* fp, GInt16 val) { CPL_LSBPTR16(&val); VSIFWriteL(&val, 2, 1, fp); }