Revision 154

View differences:

1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/CMakeModules/FindGDAL.cmake
1
# Locate gdal
2
# This module defines
3
# GDAL_LIBRARY
4
# GDAL_FOUND, if false, do not try to link to gdal 
5
# GDAL_INCLUDE_DIR, where to find the headers
6
#
7
# $GDALDIR is an environment variable that would
8
# correspond to the ./configure --prefix=$GDAL_DIR
9
# used in building gdal.
10
#
11
# Created by Eric Wing. I'm not a gdal user, but OpenSceneGraph uses it 
12
# for osgTerrain so I whipped this module together for completeness.
13
# I actually don't know the conventions or where files are typically
14
# placed in distros.
15
# Any real gdal users are encouraged to correct this (but please don't
16
# break the OS X framework stuff when doing so which is what usually seems 
17
# to happen).
18

  
19
# This makes the presumption that you are include gdal.h like
20
# #include "gdal.h"
21

  
22
FIND_PATH(GDAL_INCLUDE_DIR gdal.h
23
  PATHS
24
  $ENV{GDAL_DIR}
25
  NO_DEFAULT_PATH
26
    PATH_SUFFIXES include
27
)
28

  
29
FIND_PATH(GDAL_INCLUDE_DIR gdal.h
30
    PATHS ${CMAKE_PREFIX_PATH} # Unofficial: We are proposing this.
31
    NO_DEFAULT_PATH
32
    PATH_SUFFIXES include
33
)
34

  
35
FIND_PATH(GDAL_INCLUDE_DIR gdal.h
36
  PATHS
37
  ~/Library/Frameworks/gdal.framework/Headers
38
  /Library/Frameworks/gdal.framework/Headers
39
  /usr/local/include/gdal
40
  /usr/local/include/GDAL
41
  /usr/local/include
42
  /usr/include/gdal
43
  /usr/include/GDAL
44
  /usr/include
45
  /sw/include/gdal 
46
  /sw/include/GDAL 
47
  /sw/include # Fink
48
  /opt/local/include/gdal
49
  /opt/local/include/GDAL
50
  /opt/local/include # DarwinPorts
51
  /opt/csw/include/gdal
52
  /opt/csw/include/GDAL
53
  /opt/csw/include # Blastwave
54
  /opt/include/gdal
55
  /opt/include/GDAL
56
  /opt/include
57
)
58

  
59
MARK_AS_ADVANCED(GDAL_INCLUDE_DIR)
60

  
61
FIND_LIBRARY(GDAL_LIBRARY 
62
  NAMES gdal_i gdal1.5.0 gdal1.4.0 gdal1.3.2 GDAL
63
  PATHS
64
  $ENV{GDAL_DIR}
65
  NO_DEFAULT_PATH
66
  PATH_SUFFIXES lib64 lib
67
)
68
FIND_LIBRARY(GDAL_LIBRARY 
69
  NAMES gdal_i gdal1.5.0 gdal1.4.0 gdal1.3.2 GDAL
70
  PATHS ${CMAKE_PREFIX_PATH} # Unofficial: We are proposing this.
71
    NO_DEFAULT_PATH
72
    PATH_SUFFIXES lib64 lib
73
)
74
FIND_LIBRARY(GDAL_LIBRARY 
75
  NAMES gdal_i gdal1.5.0 gdal1.4.0 gdal1.3.2 GDAL
76
  PATHS
77
    ~/Library/Frameworks
78
    /Library/Frameworks
79
    /usr/local
80
    /usr
81
    /sw
82
    /opt/local
83
    /opt/csw
84
    /opt
85
    /usr/freeware
86
    [HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Session\ Manager\\Environment;GDAL_ROOT]/lib
87
  PATH_SUFFIXES lib64 lib
88
)
89

  
90
MARK_AS_ADVANCED(GDAL_LIBRARY)
91

  
92
SET(GDAL_FOUND "NO")
93
IF(GDAL_LIBRARY AND GDAL_INCLUDE_DIR)
94
  SET(GDAL_FOUND "YES")
95
  SET(GDAL_LIBRARY_DEBUG ${GDAL_LIBRARY})
96
ENDIF(GDAL_LIBRARY AND GDAL_INCLUDE_DIR)
97

  
98

  
99

  
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/readme.txt
1
Notas de compilaci?n de la librer?a jgdal.
2

  
3
La compilaci?n de la librer?a jgdal se realiza autom?ticamente ejecutando el build.xml
4
del proyecto. Para ello el sistema tiene que tener instalado y accesible:
5

  
6
- CMake - Probado con la versi?n 2.4
7
- Compilador gcc - g++ en el caso de Linux - Compilado con gcc 4.1. Con la versi?n 3.3
8
	de gcc - g++ no compila correctamente.
9
- Entorno de desarrollo Visual Studio en caso de Windows con las variables de
10
	entorno cargadas. - Compilado con Visual Studio 2005
11
- Librer?a gdal instalada. Hasta el momento (0.6.3) se est? compilando con gdal 1.5.0 con 
12
	soporte para Grass y Modis (Hdf 4 y 5). Si el SDK est? en alguna ruta distinta a las que
13
	se incluyen en el archivo FindGDAL, habr? que a?adirla a dicho archivo o instalar el SDK
14
	en alguna de las indicadas.
15
- JDK de Java.
16

  
17
Con ejecutar el build.xml es suficiente para generar la librer?a y el jar.
18

  
19
*********************************************************
20
Cambios seg?n versiones a partir de la 0.6.1
21

  
22
0.6.1: Eliminaci?n de la comprobaci?n de direcciones de memoria negaticas ya que
23
		?stas se utilizan.
24

  
25
0.6.2: Versi?n en desarrollo. Migraci?n a CMake.
26

  
27
0.6.3: No se utiliza la captura de se?ales de las librer?as nativas ya que produce 
28
		inestabilidades en la librer?a. Soporte para grass y HDF 4 y 5. Grass solo en
29
		Linux.
30
			
31
0.6.4: Se incluyen comprobaciones de los par?metros que se pasan a JNI 
32
		y lanzamiento de excepciones desde la parte de java. 
33
		
34
0.7.0: Recubrimiento de la utilidad para reproyeccion gdalwarp.
35
		Incluido el recubrimiento del generador de overwiews gdaladdo.
36
		M?todo getMetadata con par?metro para poder seleccionar dominios de metadatos.
37
		Recubrimiento de la funcion GDALSetRaserColorInterpretation.
38
		
39
0.7.1: Resoluci?n de un bug en el m?todo createCopy de la clase GdalDriver.
40

  
41
0.7.2: Resoluci?n de bug en GdalDriver. El params de create debe admitir el valor de null
42

  
43
0.8.0: Llamada existsNoDataValue de GdalRasterBand
44
		
45
0.9.0: Quitadas las constantes de GdalWarp
46
		Quitado metodo setFormat de GdalWarp
47
		A?adido nuevo parametro al constructor de GdalWarp
48
		A?adido nuevo metodo a GdalWarp que devuelve los drivers reproyectables.
49

  
50
0.9.1: Agregado el control de excepciones a GdalWarp
51
		Corregido bug cuando params vale null en GdalDriver.java
52
		
53
0.9.2: Control de errores en el par?metro de salida para gdalwarp
54
       
55
*********************************************************
56

  
57
NOTAS DE COMPILACI?N:
58

  
59
Linux:
60
* Es necesario que haya instalado un gdal. Seg?n la versi?n de la librer?a, puede requerir
61
que gdal est? compilado con diferentes soportes.
62

  
63

  
64

  
65
Windows:
66
* Es necesario que haya un Visual Studio instalado con sus variables de entorno cargadas por
67
defecto en el sistema para poder acceder al copilador por linea de comandos.
68
* Es necesario que haya un CMake en el sistema con sus variable de entorno cargadas en el
69
sistema para generar los Makefiles.
70
* Es necesario que la variable JAVA_HOME exista y apunte a un Jdk.
71
* Es necesario indicar la variable de entorno JAVA_HOME al ejecutar el ant desde eclipse 
72
para que se puedan encontrar los includes JNI. La direcci?n de estos includes se guardar?
73
en las variables JAVA_INCLUDE_PATH y JAVA_INCLUDE_PATH2.
74
* En el archivo de configuraci?n para la compilaci?n de la librer?a gdal, es necesario
75
que se utilice la opci?n STDCALL. Tambi?n se tiene que deshabilitar el soporte para ODBC.
76
Comentar la linea ODBC_SUPPORTED=YES. Importante, comentar la linea, no poner valor =NO.
77
* En el caso de que se haya compilado la librer?a con soporte externo (tal como HDF4, HDF5...)
78
es necesario que las librer?as de las que depende gdal est?n accesibles.
79

  
80
* SOPORTE PARA HDF4:
81
	- La librer?a 1.5.0 de gdal se tiene que compilar con el sdk 4.2r2 de HDF4. La versi?n
82
	4.2r1 est? compilada con Visual Studio 6.0 y no soporta VS 2005. La versi?n 4.2r3 da un
83
	error en la compilaci?n de gdal posiblemente porque este ?ltimo no est? actualizado.
84

  
85
* SOPORTE PARA HDF5:
86
	- Al igual que ocurre con HDF4, gdal 1.5.0 no soporta la ?ltima versi?n hasta la fecha
87
	de HDF5 (1.8.0) por lo que hay que utilizar la (1.6.7) que si que soporta Visual Studio
88
	2005. Tambi?n es conveniente utilizar una version de szip compatible con Visual Studio
89
	2005.
90
 
91
		
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/CMakeLists.txt
1
set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS TRUE)
2

  
3
IF(WIN32)
4
    CMAKE_MINIMUM_REQUIRED(VERSION 2.4.6 FATAL_ERROR)
5
ELSE(WIN32)
6
    IF(APPLE)
7
        CMAKE_MINIMUM_REQUIRED(VERSION 2.6.0 FATAL_ERROR)
8
    ELSE(APPLE)
9
        CMAKE_MINIMUM_REQUIRED(VERSION 2.4.4 FATAL_ERROR)
10
    ENDIF(APPLE)
11
ENDIF(WIN32)
12

  
13
if(COMMAND cmake_policy)
14
    # Works around warnings libraries linked against that don't
15
    # have absolute paths (e.g. -lpthreads)
16
    cmake_policy(SET CMP0003 NEW)
17

  
18
    # Works around warnings about escaped quotes in ADD_DEFINITIONS
19
    # statements.
20
    cmake_policy(SET CMP0005 NEW)
21

  
22
    # cmake-2.6.1 introduces policy cmp0008 decide how to treat full path libraries that do not appear to be valid library file names
23
    # quote from cvslog "Such libraries worked by accident in the VS IDE and Xcode generators in CMake 2.4 and below."
24
    if(${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} GREATER 4 AND ${CMAKE_PATCH_VERSION} GREATER 0)
25
        cmake_policy(SET CMP0008 OLD)
26
    endif()
27
endif()
28

  
29
PROJECT(jgdal)
30

  
31
SET(JGDAL_VERSION_MAJOR "0")
32
SET(JGDAL_VERSION_MINOR "9")
33
SET(JGDAL_VERSION_PATCH "2")
34
SET(VERSION "")#${JGDAL_VERSION_MAJOR}${JGDAL_VERSION_MINOR}${JGDAL_VERSION_PATCH}")
35
IF(WIN32)
36
SET(VERSION "${JGDAL_VERSION_MAJOR}${JGDAL_VERSION_MINOR}${JGDAL_VERSION_PATCH}")
37
ENDIF(WIN32)
38
SET(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/../build/CMakeModules;${CMAKE_SOURCE_DIR}/CMakeModules;${CMAKE_MODULE_PATH}")
39

  
40
FIND_PACKAGE(DepMan REQUIRED) 
41
INCLUDE(GeneralMacros) 
42

  
43
CONFIGURE_DEFAULTS()
44

  
45
IF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
46
  SET(CMAKE_INSTALL_PREFIX
47
    ${DEPMAN_PATH} CACHE PATH "depman path install prefix" FORCE
48
    )
49
ENDIF(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
50

  
51
FIND_PACKAGE(JNI REQUIRED) 
52
FIND_PACKAGE(GDAL REQUIRED) 
53

  
54
ADD_SUBDIRECTORY(src/main/native)
55

  
56
CONFIGURE_END()
57

  
58

  
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/build.xml
1
	<project name="libjni-gdal" default="main" basedir=".">
2
	<description>
3
		Compila la librería jgdal
4
	</description>
5
		
6
	<property name="src-java" location="src/main/java" />
7
	<property name="src-tet-java" location="src/test/java" />
8
	<property name="jar-dist" location="jar-dist" />
9
	<property name="build" location="bin/" />
10
	<property name="cmake_build" location="BMCMake/" />
11
	<property environment="env"/>
12
	<condition property="jgdal_version" value="0.9.2">
13
		<os family="unix"/>
14
	</condition>
15
	<condition property="jgdal_version" value="092">
16
		<os family="windows"/>
17
	</condition>
18
	<property name="jgdal-jar" location="jgdal-0.9.2.jar" />
19
	<condition property="cmake_generator" value="'Unix Makefiles'">
20
		<os family="unix"/>
21
	</condition>
22
	<condition property="cmake_generator" value="'NMake Makefiles'">
23
		<os family="windows"/>
24
	</condition>		
25

  
26
	<target name="main" description="compile java code, make jars, prepare and compile natives" depends="clean,jar,prepare-natives,compile-natives">
27
	</target>
28

  
29
	<target name="jar" description="makes jar file">
30
		<mkdir dir="${build}" />
31
		<javac srcdir="${src-java}" destdir="${build}" debug="true" />
32
		<mkdir dir="${jar-dist}" />
33
		<jar jarfile="${jgdal-jar}" basedir="${build}" includes="es/gva/cit/**, org/gvsig/**" />
34
		<move file="${jgdal-jar}" todir="${jar-dist}" />
35
	</target>
36

  
37
	<target name="prepare-natives" description="prepares the natives to be compiled">
38
		<mkdir dir="${cmake_build}"/>
39
		<delete file="${cmake_build}/CMakeCache.txt"/>
40
		<exec dir="${cmake_build}" executable="cmake" os="Linux" >
41
			<arg line=".." />
42
			<arg line="-G${cmake_generator}" />
43
			<arg line="-DCMAKE_BUILD_TYPE=Release" />
44
			<arg line="-DJGDAL_VERSION=${jgdal_version}" />
45
		</exec>
46
		<exec dir="${cmake_build}" executable="cmake" os="Windows 98,Windows 2000,Windows XP,Windows NT (Unknown)">
47
			<arg line=".." />
48
			<arg line="-G${cmake_generator}" />
49
			<arg line="-DCMAKE_BUILD_TYPE=Release" />
50
			<arg line="-DJGDAL_VERSION=${jgdal_version}" />
51
			<arg line="-DHDF4=true"/>
52
			<arg line="-DHDF5=true"/>
53
		</exec>
54
	</target>
55

  
56
	<target name="compile-natives" description="compiles natives">
57
		<exec dir="${cmake_build}" executable="make" os="Linux">
58
			<arg line="install" />
59
		</exec>
60
		<exec dir="${cmake_build}" executable="nmake" os="Windows 98,Windows 2000,Windows XP,Windows NT (Unknown)">
61
			<arg line="install" />
62
		</exec>
63
	</target>
64
		
65
	<target name="clean" description="clean distribution">
66
		<delete dir="jar-dist"/>
67
		<delete dir="lib-dist"/>
68
		<delete dir="BMCMake"/>
69
	</target>
70

  
71

  
72
</project>
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/.classpath
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" path="src/main/java"/>
4
	<classpathentry kind="src" path="src/test/java"/>
5
	<classpathentry kind="src" path="src/main/resources"/>
6
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
7
	<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
8
	<classpathentry kind="output" path="bin"/>
9
</classpath>
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/.project
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>libjni-gdal</name>
4
	<comment></comment>
5
	<projects>
6
	</projects>
7
	<buildSpec>
8
		<buildCommand>
9
			<name>org.eclipse.jdt.core.javabuilder</name>
10
			<arguments>
11
			</arguments>
12
		</buildCommand>
13
	</buildSpec>
14
	<natures>
15
		<nature>org.eclipse.jdt.core.javanature</nature>
16
	</natures>
17
</projectDescription>
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/test/java/es/gva/cit/jgdal/TestWarpDataset.java
1
package es.gva.cit.jgdal;
2

  
3
import java.io.File;
4
import java.io.IOException;
5

  
6
import junit.framework.TestCase;
7

  
8
public class TestWarpDataset extends TestCase {
9
	private GdalWarp warp    = null;
10
	private String   baseDir = "./test-images/";
11
	private String   src     = baseDir + "testGdalWarp.tif";
12
	private String   dst     = baseDir + "warpedImage.tif";
13
	private String   frm     = "GTiff";
14
	private String   t_srs   = "EPSG:23030";
15

  
16
	public void start() {
17
		setUp();
18
		testStack();
19
	}
20

  
21
	public void setUp() {
22
		warp = new GdalWarp();
23
		File f = new File(src);
24
		Gdal dataset = new Gdal();
25

  
26
		try {
27
			assertTrue("El fichero no existe", f.exists());
28
			assertTrue("El fichero no se puede leer", f.canRead());
29
			dataset.open(src, Gdal.GA_ReadOnly);
30
			GdalRasterBand band = dataset.getRasterBand(1);
31
			band.readRaster(0, 0, 10, 10, 10, 10, Gdal.GDT_Byte);
32
		} catch (GdalException e) {
33
			new AssertionError("Fallo en gdal al acceder al fichero fuente");
34
		} catch (IOException e) {
35
			new AssertionError("Fallo en gdal al acceder al fichero fuente");
36
			e.printStackTrace();
37
		}
38
	}
39

  
40
	public void testStack() {
41
		assertNotNull(t_srs);
42
		
43
		warp.warp(t_srs, src, dst, frm);
44
		System.err.println("Proceso completado al " + warp.getPercent() + " %");
45
		
46
		File f = new File(dst);
47

  
48
		assertTrue("El fichero destino no existe", f.exists());
49
		assertTrue("El fichero destino no se puede leer", f.canRead());
50
	}
51
}
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/test/java/es/gva/cit/jgdal/TestReadData.java
1
package es.gva.cit.jgdal;
2

  
3
import java.io.IOException;
4

  
5
import junit.framework.TestCase;
6

  
7
/**
8
 * Test de acceso a datos de la imagen. 
9
 * @author Miguel ?ngel Qierol Carratal? <miguelangel.querol@iver.es>
10
 *
11
 */
12
public class TestReadData extends TestCase{
13

  
14
	private Gdal gdal = null;
15
	private String baseDir = "./test-images/";
16
	private String file1 = baseDir + "testGdal.tif";
17
	private String[] metadata = null;
18
	
19
	public void start(){
20
		try {
21
			setUp();
22
			testStack();
23
		} catch (GdalException e) {
24
			e.printStackTrace();
25
		} catch (IOException e) {
26
			e.printStackTrace();
27
		}
28
		
29
	}
30
	
31
	public void setUp() throws GdalException, IOException{
32
		gdal = new Gdal();
33
		gdal.open(file1, Gdal.GA_Update);
34
	}
35
	
36
	public void testStack() throws GdalException, IOException{
37
		//Llamada sin dominio
38
		metadata = gdal.getMetadata();
39
		assertNotNull("No se han devuelto metadatos", metadata);
40
		for (int i = 0 ; i<metadata.length ; i++){
41
			System.out.println("Metadato: " + metadata[i]);
42
		}
43
		
44
		//Llamada con dominio "Image Structure Metadata"
45
		metadata = gdal.getMetadata("Image Structure Metadata");
46
		assertNotNull("No se han devuelto metadatos", metadata);
47
		for (int i = 0 ; i<metadata.length ; i++){
48
			System.out.println("Metadato: " + metadata[i]);
49
		}
50
		
51
		//Comprobaci?n del tama?o de la imagen
52
		assertEquals(842, gdal.getRasterXSize());
53
		assertEquals(1023, gdal.getRasterYSize());
54
		
55
		//Comprobaci?n del n?mero de bandas
56
		assertEquals(4, gdal.getRasterCount());
57
		
58
		//Comprobaci?n del driver de la imagen
59
		assertEquals("GTiff", gdal.getDriverShortName());
60
		
61
		//Comprobaci?n del acceso a las bandas
62
		for (int i = 0 ; i < gdal.getRasterCount() ; i++){
63
			assertNotNull(gdal.getRasterBand(i+1));
64
		}
65
		
66
		gdal.close();
67
		gdal = null;
68
		System.gc();
69
	}
70
}
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/test/java/es/gva/cit/jgdal/TestReadBandData.java
1
package es.gva.cit.jgdal;
2

  
3
import java.io.IOException;
4

  
5
import junit.framework.TestCase;
6

  
7
/**
8
 * Test de acceso a datos de las bandas de una imagen.
9
 * @author Miguel ?ngel Querol Carratal? <miguelangel.querol@iver.es>
10
 *
11
 */
12
public class TestReadBandData extends TestCase{
13
	private Gdal gdal = null;
14
	private GdalRasterBand band = null;
15
	private String baseDir = "./test-images/";
16
	private String file1 = baseDir + "testGdal.tif";
17
	
18
	public void start(){
19
		try {
20
			setUp();
21
			testStack();
22
		} catch (GdalException e) {
23
			e.printStackTrace();
24
		} catch (IOException e) {
25
			e.printStackTrace();
26
		}
27
		
28
	}
29
	
30
	public void setUp() throws GdalException, IOException{
31
		gdal = new Gdal();
32
		gdal.open(file1, Gdal.GA_Update);
33
	}
34
	
35
	public void testStack() throws GdalException, IOException{
36
		//Llamada sin dominio
37
		String[] metadata = gdal.getMetadata();
38
		assertNotNull("No se han devuelto metadatos", metadata);
39
		for (int i = 0 ; i<metadata.length ; i++){
40
			System.out.println("Metadato: " + metadata[i]);
41
		}
42
		
43
		//Llamada con dominio "Image Structure Metadata"
44
		metadata = gdal.getMetadata("Image Structure Metadata");
45
		assertNotNull("No se han devuelto metadatos", metadata);
46
		for (int i = 0 ; i<metadata.length ; i++){
47
			System.out.println("Metadato: " + metadata[i]);
48
		}
49
		
50
		//Comprobaci?n del tama?o de la imagen
51
		assertEquals(842, gdal.getRasterXSize());
52
		assertEquals(1023, gdal.getRasterYSize());
53
		
54
		//Comprobaci?n del n?mero de bandas
55
		assertEquals(4, gdal.getRasterCount());
56
		
57
		//Comprobaci?n del driver de la imagen
58
		assertEquals("GTiff", gdal.getDriverShortName());
59
		
60
		//Comprobaci?n del acceso a las bandas
61
		for (int i = 0 ; i < gdal.getRasterCount() ; i++){
62
			assertNotNull(gdal.getRasterBand(i+1));
63
		}
64
	}
65
}
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/test/java/org/gvsig/addo/TestBuildOverviews.java
1
package org.gvsig.addo;
2

  
3
import java.io.IOException;
4

  
5
import junit.framework.TestCase;
6
import es.gva.cit.jgdal.Gdal;
7
import es.gva.cit.jgdal.GdalException;
8

  
9
/**
10
 * Test para la generacion de overviews sobre una imagen raster.
11
 * Registra un listener para mostrar el incremento de la tarea.
12
 *
13
 * 18-nov-2007
14
 * @author Nacho Brodin (nachobrodin@gmail.com)
15
 */
16
public class TestBuildOverviews extends TestCase implements IOverviewIncrement {
17
	private int value = 0;
18

  
19
	private Jaddo addo = null;
20
	private Gdal gdal = null;
21
	private String path = "./test-images/testGdalWarp.tif";
22
	
23
	public void start(){
24
		setUp();
25
		testStack();
26
	}
27
	
28
	
29
	public void setUp(){
30
		addo = new Jaddo();
31
		addo.setIncrementListener(this);
32
		gdal = new Gdal();
33
	}
34
	
35
	
36
	public void testStack(){
37
		try {
38
			addo.buildOverviews(Jaddo.AVERAGE, path, new int[]{2, 4, 8, 16});
39
			gdal.open(path, Gdal.GA_ReadOnly);
40
			assertTrue("No hay overviews!!", gdal.getRasterBand(1).getOverviewCount()>0);
41
		} catch (BuildingOverviewsException e) {
42
			System.err.println(e);
43
		} catch (WritingException e) {
44
			System.err.println(e);
45
		} catch (GdalException e) {
46
			e.printStackTrace();
47
		} catch (IOException e) {
48
			e.printStackTrace();
49
		}
50
		
51
	}
52

  
53
	public int getPercent() {
54
		return value;
55
	}
56

  
57
	public void setPercent(int value) {
58
		this.value = value;
59
		System.out.println("Increment:" + value);
60
	}
61
}
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/main/native/CMakeLists.txt
1
add_subdirectory(jgdal)
2

  
3

  
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/main/native/jgdal/ogrsfdriverregistrar_interfaz.cpp
1
 /**********************************************************************
2
 * $Id: ogrsfdriverregistrar_interfaz.cpp 7765 2006-10-03 07:05:18Z nacho $
3
 *
4
 * Name:     ogrsfdriverregistrar_interfaz.c
5
 * Project:  JGDAL. Interface java to gdal (Frank Warmerdam).
6
 * Purpose:  
7
 * Author:   Nacho Brodin, brodin_ign@gva.es
8
 *
9
 **********************************************************************/
10
/* gvSIG. Sistema de Informaci�n Geogr�fica de la Generalitat Valenciana
11
*
12
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
13
*
14
* This program is free software; you can redistribute it and/or
15
* modify it under the terms of the GNU General Public License
16
* as published by the Free Software Foundation; either version 2
17
* of the License, or (at your option) any later version.
18
*
19
* This program is distributed in the hope that it will be useful,
20
* but WITHOUT ANY WARRANTY; without even the implied warranty of
21
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
* GNU General Public License for more details.
23
*
24
* You should have received a copy of the GNU General Public License
25
* along with this program; if not, write to the Free Software
26
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
27
*
28
* For more information, contact:
29
*
30
*  Generalitat Valenciana
31
*   Conselleria d'Infraestructures i Transport
32
*   Av. Blasco Ib��ez, 50
33
*   46010 VALENCIA
34
*   SPAIN
35
*
36
*      +34 963862235
37
*   gvsig@gva.es
38
*      www.gvsig.gva.es
39
*
40
*    or
41
*
42
*   IVER T.I. S.A
43
*   Salamanca 50
44
*   46005 Valencia
45
*   Spain
46
*
47
*   +34 963163400
48
*   dac@iver.es
49
*/
50

  
51

  
52
#include <jni.h>
53
#include "ogr_api.h"
54
#include "ogrsf_frmts.h"
55

  
56

  
57
/******************************************************************************/
58
//									open
59
/******************************************************************************/
60

  
61
JNIEXPORT jlong JNICALL Java_es_gva_cit_jogr_OGRSFDriverRegistrar_openNat
62
  (JNIEnv *env, jobject obj, jstring fte, jint bUpdate){
63
  	
64
  	OGRDataSource       *poDS;
65
    OGRSFDriver         *poDriver;
66
    long				driver=0;
67
    long				dataset=0;
68
    const char 			*pszFilename;
69
    jclass 				clase;
70
  	jfieldID 			id_campo;
71
    
72
    pszFilename = env->GetStringUTFChars( fte, 0);
73
        
74
	poDS = OGRSFDriverRegistrar::Open( pszFilename, bUpdate, &poDriver );
75
	
76
    if( poDS == NULL )return -1;
77
    if(poDriver!=NULL)
78
	    driver = (long)&(*poDriver);
79

  
80
    clase = env->GetObjectClass(obj);
81
    id_campo = env->GetFieldID( clase, "driver", "J");
82
    env->SetLongField( obj, id_campo, (jlong)driver);    
83
    dataset = (long)&(*poDS);
84
    env->ReleaseStringUTFChars( fte, pszFilename);
85
   
86
    return (jlong)dataset;
87
  	
88
  }
89
  
90
/******************************************************************************/
91
//									getDriverCount
92
/******************************************************************************/
93

  
94
JNIEXPORT jint JNICALL Java_es_gva_cit_jogr_JNIBase_getDriverCountNat
95
  (JNIEnv *env, jobject obj, jlong cPtr){
96
  	
97
  	int res=-1;
98
  	OGRSFDriverRegistrar *drvreg  = (OGRSFDriverRegistrar *) 0 ;
99
  
100
  	drvreg = *(OGRSFDriverRegistrar **)&cPtr;
101
  	if(drvreg!=NULL)
102
	  	res = drvreg->GetDriverCount();
103
	  	  
104
  	return res;
105
  	
106
  }
107
  
108
/******************************************************************************/
109
//									getRegistrar
110
/******************************************************************************/
111

  
112
  JNIEXPORT jlong JNICALL Java_es_gva_cit_jogr_OGRSFDriverRegistrar_getRegistrarNat
113
  (JNIEnv *env, jobject obj){
114
  	
115
  	long ptro;
116
  	OGRSFDriverRegistrar    *poR = OGRSFDriverRegistrar::GetRegistrar();
117
  	ptro = (long)&(*poR);
118
  	
119
  	return (jlong)ptro;
120
  }	
121
  
122
/******************************************************************************/
123
//									getDriver
124
/******************************************************************************/
125
  
126
  
127
  JNIEXPORT jlong JNICALL Java_es_gva_cit_jogr_OGRSFDriverRegistrar_getDriverNat
128
  (JNIEnv *env, jobject obj, jlong cPtr, jint i){
129
  	
130
  	OGRSFDriverRegistrar 	*drvreg  = (OGRSFDriverRegistrar *) 0 ;
131
  	OGRSFDriver 			*drv;
132
  	long					driver=0;
133
  	
134
  	drvreg = *(OGRSFDriverRegistrar **)&cPtr;
135
  	if(drvreg!=NULL){
136
	  	drv = drvreg->GetDriver(i);
137
	  	driver = (long)&(*drv);
138
  	}
139
  	return (jlong)driver;
140
  	
141
  	
142
  }
143
  
144
  
145
/******************************************************************************/
146
//								~OGRSFDriverRegistrar
147
/******************************************************************************/
148
 
149
  JNIEXPORT void JNICALL Java_es_gva_cit_jogr_OGRSFDriverRegistrar_FreeOGRSFDriverRegistrarNat
150
  (JNIEnv *env, jobject obj, jlong cPtr){
151
  	
152
  	OGRSFDriverRegistrar *df = (OGRSFDriverRegistrar *) 0 ;
153
  	
154
  	df = *(OGRSFDriverRegistrar **)&cPtr;
155
  	if(df!=NULL){
156
  		delete df;
157
  	}
158
  }
159

  
1.10/tags/gvSIG_3D_Animation_1_10_build_17/libraries/libjni-gdal/src/main/native/jgdal/warpfunc.cpp
1
/******************************************************************************
2
 * $Id: gdalwarp.cpp,v 1.27 2006/09/27 13:06:13 dron Exp $
3
 *
4
 * Project:  High Performance Image Reprojector
5
 * Purpose:  Test program for high performance warper API.
6
 * Author:   Frank Warmerdam <warmerdam@pobox.com>
7
 *
8
 ******************************************************************************
9
 * Copyright (c) 2002, i3 - information integration and imaging
10
 *                          Fort Collin, CO
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a
13
 * copy of this software and associated documentation files (the "Software"),
14
 * to deal in the Software without restriction, including without limitation
15
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
16
 * and/or sell copies of the Software, and to permit persons to whom the
17
 * Software is furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included
20
 * in all copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28
 * DEALINGS IN THE SOFTWARE.
29
 ******************************************************************************
30
 *
31
 * $Log: gdalwarp.cpp,v $
32
 * Revision 1.27.1 2007/04/02 11:35:08  maquerol
33
 * main() function converted into an accesible warpFunction.
34
 *
35
 * Revision 1.27  2006/09/27 13:06:13  dron
36
 * Memory leak fixed.
37
 *
38
 * Revision 1.26  2006/07/06 20:30:11  fwarmerdam
39
 * use GDALSuggestedWarpOutput2() to avoid approximation implicit in using gt
40
 *
41
 * Revision 1.25  2006/06/29 21:10:29  fwarmerdam
42
 * Avoid a few memory leaks.
43
 *
44
 * Revision 1.24  2006/06/02 17:31:49  fwarmerdam
45
 * Modified -ts to allow width or height to be zero meaning, it should
46
 * be computed to retain square pixels.
47
 *
48
 * Revision 1.23  2006/05/29 17:32:15  fwarmerdam
49
 * added preliminary support for controlling longitude wrapping on input dataset
50
 *
51
 * Revision 1.22  2006/04/25 14:28:33  fwarmerdam
52
 * Check for no usable sources, avoid warning.
53
 *
54
 * Revision 1.21  2006/03/21 21:34:43  fwarmerdam
55
 * cleanup headers
56
 *
57
 * Revision 1.20  2006/01/05 19:51:10  fwarmerdam
58
 * fixed checking of targetsrs
59
 *
60
 * Revision 1.19  2005/12/19 20:20:00  fwarmerdam
61
 * preliminary support for multiple input files
62
 *
63
 * Revision 1.18  2005/09/13 01:57:31  fwarmerdam
64
 * Fixed usage message.
65
 *
66
 * Revision 1.17  2005/09/13 01:24:45  fwarmerdam
67
 * Set UNIFIED_SRC_NODATA by default for -srcnodata switch.
68
 *
69
 * Revision 1.16  2005/09/12 18:06:25  fwarmerdam
70
 * Added quotes around -srcnodata and -dstnodata in usage message.
71
 *
72
 * Revision 1.15  2004/12/26 16:14:53  fwarmerdam
73
 * added -tps flag
74
 *
75
 * Revision 1.14  2004/11/29 15:01:55  fwarmerdam
76
 * Fixed typo in printf as per Bug 691.
77
 *
78
 * Revision 1.13  2004/11/14 04:57:04  fwarmerdam
79
 * added -srcalpha switch, and automatic alpha detection
80
 *
81
 * Revision 1.12  2004/11/05 06:15:08  fwarmerdam
82
 * Don't double free the warpoptions array.
83
 *
84
 * Revision 1.11  2004/11/05 05:53:43  fwarmerdam
85
 * Avoid various memory leaks.
86
 *
87
 * Revision 1.10  2004/10/07 15:53:42  fwarmerdam
88
 * added preliminary alpha band support
89
 */
90
#include <jni.h>
91
#include "gdalwarper.h"
92
#include "cpl_string.h"
93
#include "ogr_spatialref.h"
94
#include "gdal.h"
95
//#include "../include/gdalwarp_interfaz.h"
96

  
97
CPL_CVSID("$Id: gdalwarp.cpp,v 1.27 2006/09/27 13:06:13 dron Exp $");
98

  
99
static CPLString InsertCenterLong( GDALDatasetH hDS, CPLString osWKT );
100

  
101
static GDALDatasetH
102
GDALWarpCreateOutput( char **papszSrcFiles, const char *pszFilename,
103
											const char *pszFormat, const char *pszSourceSRS,
104
											const char *pszTargetSRS, int nOrder,
105
											char **papszCreateOptions, GDALDataType eDT );
106

  
107
int CPL_STDCALL GDALFuncTermProgress( double dfComplete, const char *pszMessage,
108
											void * pProgressArg );
109

  
110
void CPL_STDCALL statusCallBack(int nPercent);
111

  
112
static double	       dfMinX=0.0, dfMinY=0.0, dfMaxX=0.0, dfMaxY=0.0;
113
static double	       dfXRes=0.0, dfYRes=0.0;
114
static int             nForcePixels=0, nForceLines=0, bQuiet = FALSE;
115
static int             bEnableDstAlpha = FALSE, bEnableSrcAlpha = FALSE;
116

  
117
static int             bVRT = FALSE;
118

  
119

  
120
/************************************************************************/
121
/*                             SanitizeSRS                              */
122
/************************************************************************/
123

  
124
char *SanitizeSRS( const char *pszUserInput )
125

  
126
{
127
		OGRSpatialReferenceH hSRS;
128
		char *pszResult = NULL;
129

  
130
		CPLErrorReset();
131

  
132
		hSRS = OSRNewSpatialReference( NULL );
133
		if( OSRSetFromUserInput( hSRS, pszUserInput ) == OGRERR_NONE )
134
				OSRExportToWkt( hSRS, &pszResult );
135
		else
136
		{
137
				CPLError( CE_Failure, CPLE_AppDefined,
138
									"Translating source or target SRS failed:\n%s",
139
									pszUserInput );
140
				exit( 1 );
141
		}
142

  
143
		OSRDestroySpatialReference( hSRS );
144

  
145
		return pszResult;
146
}
147

  
148

  
149
/************************************************************************/
150
/*                              WarpFunction()                          */
151
/************************************************************************/
152

  
153
int launchException(JNIEnv *env, char *msg) {
154
	env->ExceptionDescribe();
155
	env->ExceptionClear();
156

  
157
	jclass newExcCls = env->FindClass("es/gva/cit/jgdal/GdalException");
158
	if (newExcCls == 0)
159
		return CE_Failure;
160

  
161
	env->ThrowNew(newExcCls, msg);
162
	return CE_Failure;
163
}
164

  
165
int warpFunction(JNIEnv *env, char * s_srs, char * t_srs, char *source, char * dest, char *format) {
166
	GDALDatasetH hDstDS;
167
	const char *pszFormat = "GTiff";
168
	char *pszTargetSRS = NULL;
169
	char *pszSourceSRS = NULL;
170
	char **papszSrcFiles = NULL;
171
	char *pszDstFilename = NULL;
172
	int bCreateOutput = FALSE, i, nOrder = 0;
173
	void *hTransformArg, *hGenImgProjArg = NULL, *hApproxArg = NULL;
174
	char **papszWarpOptions = NULL;
175
	double dfErrorThreshold = 0.125;
176
	double dfWarpMemoryLimit = 0.0;
177
	GDALTransformerFunc pfnTransformer = NULL;
178
	char **papszCreateOptions = NULL;
179
	GDALDataType eOutputType = GDT_Unknown, eWorkingType = GDT_Unknown;
180
	GDALResampleAlg eResampleAlg = GRA_NearestNeighbour;
181
	const char *pszSrcNodata = NULL;
182
	const char *pszDstNodata = NULL;
183
	int bMulti = FALSE;
184
	char error[1024];
185
        int result = 4;
186

  
187
	GDALAllRegister();
188

  
189
/* -------------------------------------------------------------------- */
190
/*      Parse arguments.                                                */
191
/* -------------------------------------------------------------------- */
192
	pszTargetSRS = SanitizeSRS(t_srs);
193
	if (s_srs != NULL)
194
		pszSourceSRS = SanitizeSRS(s_srs);
195

  
196
	papszSrcFiles = CSLAddString(papszSrcFiles, source);
197
	papszSrcFiles = CSLAddString(papszSrcFiles, dest);
198
	if (format != NULL)
199
		pszFormat = format;
200
	bCreateOutput = FALSE;
201

  
202
/* -------------------------------------------------------------------- */
203
/*      The last filename in the file list is really our destination    */
204
/*      file.                                                           */
205
/* -------------------------------------------------------------------- */
206
	if (CSLCount(papszSrcFiles) > 1) {
207
		pszDstFilename = papszSrcFiles[CSLCount(papszSrcFiles) - 1];
208
		papszSrcFiles[CSLCount(papszSrcFiles) - 1] = NULL;
209
	}
210

  
211
/* -------------------------------------------------------------------- */
212
/*      Does the output dataset already exist?                          */
213
/* -------------------------------------------------------------------- */
214
	CPLPushErrorHandler(CPLQuietErrorHandler);
215
	hDstDS = GDALOpen(pszDstFilename, GA_Update);
216
	CPLPopErrorHandler();
217

  
218
	if (hDstDS != NULL && bCreateOutput) {
219
		sprintf(error, "warpfunc.cpp (218): Output dataset %s exists, "
220
			"but some commandline options were provided indicating a new dataset "
221
			"should be created.  Please delete existing dataset and run again.", pszDstFilename);
222
		return launchException(env, error);
223
	}
224

  
225
/* -------------------------------------------------------------------- */
226
/*      If not, we need to create it.                                   */
227
/* -------------------------------------------------------------------- */
228
	int bInitDestSetForFirst = FALSE;
229

  
230
	if (hDstDS == NULL) {
231
		hDstDS = GDALWarpCreateOutput(papszSrcFiles, pszDstFilename, pszFormat,
232
				pszSourceSRS, pszTargetSRS, nOrder, papszCreateOptions, eOutputType);
233
		bCreateOutput = TRUE;
234

  
235
		if (CSLFetchNameValue(papszWarpOptions, "INIT_DEST") == NULL && pszDstNodata == NULL) {
236
			papszWarpOptions = CSLSetNameValue(papszWarpOptions, "INIT_DEST", "0");
237
			bInitDestSetForFirst = TRUE;
238
		} else {
239
			if (CSLFetchNameValue(papszWarpOptions, "INIT_DEST") == NULL) {
240
				papszWarpOptions = CSLSetNameValue(papszWarpOptions, "INIT_DEST", "NO_DATA");
241
				bInitDestSetForFirst = TRUE;
242
			}
243
		}
244

  
245
		CSLDestroy(papszCreateOptions);
246
		papszCreateOptions = NULL;
247
	}
248

  
249
	if (hDstDS == NULL)
250
		return launchException(env, "warpfunc.cpp (249):");
251

  
252
	if (pszTargetSRS == NULL)
253
		pszTargetSRS = CPLStrdup(GDALGetProjectionRef(hDstDS));
254

  
255
/* -------------------------------------------------------------------- */
256
/*      Loop over all source files, processing each in turn.            */
257
/* -------------------------------------------------------------------- */
258
	for (int iSrc = 0; papszSrcFiles[iSrc] != NULL; iSrc++) {
259
		CPLString osThisSourceSRS;
260
		GDALDatasetH hSrcDS;
261

  
262
		if (pszSourceSRS != NULL)
263
			osThisSourceSRS = pszSourceSRS;
264

  
265
/* -------------------------------------------------------------------- */
266
/*      Open this file.                                                 */
267
/* -------------------------------------------------------------------- */
268
		hSrcDS = GDALOpen(papszSrcFiles[iSrc], GA_ReadOnly);
269

  
270
		if (hSrcDS == NULL)
271
			return launchException(env, "warpfunc.cpp (270):");
272

  
273
		// Processing input file papszSrcFiles[iSrc]
274
		if (strlen(osThisSourceSRS) == 0) {
275
			if (GDALGetProjectionRef(hSrcDS) != NULL && strlen(GDALGetProjectionRef(hSrcDS)) > 0) {
276
				osThisSourceSRS = GDALGetProjectionRef(hSrcDS);
277
			} else {
278
				if (GDALGetGCPProjection(hSrcDS) != NULL && strlen(GDALGetGCPProjection(hSrcDS)) > 0 && GDALGetGCPCount(hSrcDS) > 1) {
279
					osThisSourceSRS = GDALGetGCPProjection(hSrcDS);
280
				} else {
281
					osThisSourceSRS = "";
282
				}
283
			}
284

  
285
			if (pszTargetSRS != NULL && strlen(pszTargetSRS) > 0 && strlen(osThisSourceSRS) == 0) {
286
				return launchException(env, "warpfunc.cpp (285): A target coordinate system was specified, "
287
					"but there is no source coordinate system.  Consider using -s_srs option to provide a "
288
					"source coordinate system. Operation terminated.");
289
			}
290
		}
291

  
292
/* -------------------------------------------------------------------- */
293
/*      Do we have a source alpha band?                                 */
294
/* -------------------------------------------------------------------- */
295
		if (GDALGetRasterColorInterpretation(GDALGetRasterBand(hSrcDS, GDALGetRasterCount(hSrcDS))) == GCI_AlphaBand && !bEnableSrcAlpha) {
296
			// Using band GDALGetRasterCount(hSrcDS) of source image as alpha
297
			bEnableSrcAlpha = TRUE;
298
		}
299

  
300
/* -------------------------------------------------------------------- */
301
/*      If the source coordinate system is geographic, try and          */
302
/*      insert a CENTER_LONG extension parameter on the GEOGCS to       */
303
/*      handle wrapping better.                                         */
304
/* -------------------------------------------------------------------- */
305
		if (EQUALN(osThisSourceSRS.c_str(), "GEOGCS[", 7))
306
			osThisSourceSRS = InsertCenterLong(hSrcDS, osThisSourceSRS);
307

  
308
/* -------------------------------------------------------------------- */
309
/*      Create a transformation object from the source to               */
310
/*      destination coordinate system.                                  */
311
/* -------------------------------------------------------------------- */
312
		hTransformArg = hGenImgProjArg = GDALCreateGenImgProjTransformer(hSrcDS, osThisSourceSRS, hDstDS,
313
				pszTargetSRS, TRUE, 1000.0, nOrder);
314

  
315
		if (hTransformArg == NULL)
316
			return launchException(env, "warpfunc.cpp (315):");
317

  
318
		pfnTransformer = GDALGenImgProjTransform;
319

  
320
/* -------------------------------------------------------------------- */
321
/*      Warp the transformer with a linear approximator unless the      */
322
/*      acceptable error is zero.                                       */
323
/* -------------------------------------------------------------------- */
324
		if (dfErrorThreshold != 0.0) {
325
			hTransformArg = hApproxArg = GDALCreateApproxTransformer(GDALGenImgProjTransform, hGenImgProjArg, dfErrorThreshold);
326
			pfnTransformer = GDALApproxTransform;
327
		}
328

  
329
/* -------------------------------------------------------------------- */
330
/*      Clear temporary INIT_DEST settings after the first image.       */
331
/* -------------------------------------------------------------------- */
332
		if (bInitDestSetForFirst && iSrc == 1)
333
			papszWarpOptions = CSLSetNameValue(papszWarpOptions, "INIT_DEST", NULL);
334

  
335
/* -------------------------------------------------------------------- */
336
/*      Setup warp options.                                             */
337
/* -------------------------------------------------------------------- */
338
		GDALWarpOptions *psWO = GDALCreateWarpOptions();
339

  
340
		psWO->papszWarpOptions = CSLDuplicate(papszWarpOptions);
341
		psWO->eWorkingDataType = eWorkingType;
342
		psWO->eResampleAlg = eResampleAlg;
343

  
344
		psWO->hSrcDS = hSrcDS;
345
		psWO->hDstDS = hDstDS;
346

  
347
		psWO->pfnTransformer = pfnTransformer;
348
		psWO->pTransformerArg = hTransformArg;
349

  
350
		if (!bQuiet)
351
			psWO->pfnProgress = GDALFuncTermProgress;
352

  
353
		if (dfWarpMemoryLimit != 0.0)
354
			psWO->dfWarpMemoryLimit = dfWarpMemoryLimit;
355

  
356
/* -------------------------------------------------------------------- */
357
/*      Setup band mapping.                                             */
358
/* -------------------------------------------------------------------- */
359
		if (bEnableSrcAlpha)
360
			psWO->nBandCount = GDALGetRasterCount(hSrcDS) - 1;
361
		else
362
			psWO->nBandCount = GDALGetRasterCount(hSrcDS);
363

  
364
		psWO->panSrcBands = (int *) CPLMalloc(psWO->nBandCount * sizeof(int));
365
		psWO->panDstBands = (int *) CPLMalloc(psWO->nBandCount * sizeof(int));
366

  
367
		for (i = 0; i < psWO->nBandCount; i++) {
368
			psWO->panSrcBands[i] = i + 1;
369
			psWO->panDstBands[i] = i + 1;
370
		}
371

  
372
/* -------------------------------------------------------------------- */
373
/*      Setup alpha bands used if any.                                  */
374
/* -------------------------------------------------------------------- */
375
		if (bEnableSrcAlpha)
376
			psWO->nSrcAlphaBand = GDALGetRasterCount(hSrcDS);
377

  
378
		if (!bEnableDstAlpha && GDALGetRasterCount(hDstDS) == psWO->nBandCount + 1 &&
379
				GDALGetRasterColorInterpretation(GDALGetRasterBand(hDstDS, GDALGetRasterCount(hDstDS))) == GCI_AlphaBand) {
380
			// Using band GDALGetRasterCount(hDstDS) of destination image as alpha
381
			bEnableDstAlpha = TRUE;
382
		}
383

  
384
		if (bEnableDstAlpha)
385
			psWO->nDstAlphaBand = GDALGetRasterCount(hDstDS);
386

  
387
/* -------------------------------------------------------------------- */
388
/*      Setup NODATA options.                                           */
389
/* -------------------------------------------------------------------- */
390
		if (pszSrcNodata != NULL) {
391
			char **papszTokens = CSLTokenizeString(pszSrcNodata);
392
			int nTokenCount = CSLCount(papszTokens);
393

  
394
			psWO->padfSrcNoDataReal = (double *) CPLMalloc(psWO->nBandCount * sizeof(double));
395
			psWO->padfSrcNoDataImag = (double *) CPLMalloc(psWO->nBandCount * sizeof(double));
396

  
397
			for (i = 0; i < psWO->nBandCount; i++) {
398
				if (i < nTokenCount) {
399
					CPLStringToComplex(papszTokens[i], psWO->padfSrcNoDataReal + i, psWO->padfSrcNoDataImag + i);
400
				} else {
401
					psWO->padfSrcNoDataReal[i] = psWO->padfSrcNoDataReal[i - 1];
402
					psWO->padfSrcNoDataImag[i] = psWO->padfSrcNoDataImag[i - 1];
403
				}
404
			}
405

  
406
			CSLDestroy(papszTokens);
407

  
408
			psWO->papszWarpOptions = CSLSetNameValue(psWO->papszWarpOptions, "UNIFIED_SRC_NODATA", "YES");
409
		}
410

  
411
/* -------------------------------------------------------------------- */
412
/*      If the output dataset was created, and we have a destination    */
413
/*      nodata value, go through marking the bands with the information.*/
414
/* -------------------------------------------------------------------- */
415
		if (pszDstNodata != NULL && bCreateOutput) {
416
			char **papszTokens = CSLTokenizeString(pszDstNodata);
417
			int nTokenCount = CSLCount(papszTokens);
418

  
419
			psWO->padfDstNoDataReal = (double *) CPLMalloc(psWO->nBandCount * sizeof(double));
420
			psWO->padfDstNoDataImag = (double *) CPLMalloc(psWO->nBandCount * sizeof(double));
421

  
422
			for (i = 0; i < psWO->nBandCount; i++) {
423
				if (i < nTokenCount) {
424
					CPLStringToComplex(papszTokens[i], psWO->padfDstNoDataReal + i, psWO->padfDstNoDataImag + i);
425
				} else {
426
					psWO->padfDstNoDataReal[i] = psWO->padfDstNoDataReal[i - 1];
427
					psWO->padfDstNoDataImag[i] = psWO->padfDstNoDataImag[i - 1];
428
				}
429

  
430
				if (bCreateOutput) {
431
					GDALSetRasterNoDataValue(GDALGetRasterBand(hDstDS, psWO->panDstBands[i]), psWO->padfDstNoDataReal[i]);
432
				}
433
			}
434

  
435
			CSLDestroy(papszTokens);
436
		}
437

  
438
/* -------------------------------------------------------------------- */
439
/*      If we are producing VRT output, then just initialize it with    */
440
/*      the warp options and write out now rather than proceeding       */
441
/*      with the operations.                                            */
442
/* -------------------------------------------------------------------- */
443
		if (bVRT) {
444
			if (GDALInitializeWarpedVRT(hDstDS, psWO) != CE_None)
445
				return launchException(env, "warpfunc.cpp (444):");
446

  
447
			GDALClose(hDstDS);
448
			GDALClose(hSrcDS);
449

  
450
			//GDALDumpOpenDatasets( stderr );
451

  
452
			GDALDestroyDriverManager();
453

  
454
			return CE_None;
455
		}
456

  
457
/* -------------------------------------------------------------------- */
458
/*      Initialize and execute the warp.                                */
459
/* -------------------------------------------------------------------- */
460
		GDALWarpOperation oWO;
461
		result = CE_None;
462
		if (oWO.Initialize(psWO) == CE_None) {
463
			if (bMulti) {
464
				result = oWO.ChunkAndWarpMulti(0, 0, GDALGetRasterXSize(hDstDS), GDALGetRasterYSize(hDstDS));
465
			} else {
466
				result = oWO.ChunkAndWarpImage(0, 0, GDALGetRasterXSize(hDstDS), GDALGetRasterYSize(hDstDS));
467
			}
468
		} else
469
			result = CE_Failure;
470

  
471
/* -------------------------------------------------------------------- */
472
/*      Cleanup                                                         */
473
/* -------------------------------------------------------------------- */
474
		if (hApproxArg != NULL)
475
			GDALDestroyApproxTransformer(hApproxArg);
476

  
477
		if (hGenImgProjArg != NULL)
478
			GDALDestroyGenImgProjTransformer(hGenImgProjArg);
479

  
480
		GDALDestroyWarpOptions(psWO);
481

  
482
		GDALClose(hSrcDS);
483
	}
484

  
485
/* -------------------------------------------------------------------- */
486
/*      Final Cleanup.                                                  */
487
/* -------------------------------------------------------------------- */
488
	GDALClose(hDstDS);
489

  
490
	CPLFree(pszTargetSRS);
491
	CPLFree(pszDstFilename);
492
	CSLDestroy(papszSrcFiles);
493
	CSLDestroy(papszWarpOptions);
494

  
495
	GDALDestroyDriverManager();
496

  
497
	return result;
498
}
499

  
500

  
501

  
502

  
503
/************************************************************************/
504
/*                        GDALWarpCreateOutput()                        */
505
/*                                                                      */
506
/*      Create the output file based on various commandline options,    */
507
/*      and the input file.                                             */
508
/************************************************************************/
509

  
510
static GDALDatasetH
511
GDALWarpCreateOutput( char **papszSrcFiles, const char *pszFilename,
512
											const char *pszFormat, const char *pszSourceSRS,
513
											const char *pszTargetSRS, int nOrder,
514
											char **papszCreateOptions, GDALDataType eDT )
515

  
516

  
517
{
518
		GDALDriverH hDriver;
519
		GDALDatasetH hDstDS;
520
		void *hTransformArg;
521
		GDALColorTableH hCT = NULL;
522
		double dfWrkMinX=0, dfWrkMaxX=0, dfWrkMinY=0, dfWrkMaxY=0;
523
		double dfWrkResX=0, dfWrkResY=0;
524
		int nDstBandCount = 0;
525

  
526
/* -------------------------------------------------------------------- */
527
/*      Find the output driver.                                         */
528
/* -------------------------------------------------------------------- */
529
		hDriver = GDALGetDriverByName( pszFormat );
530
		if( hDriver == NULL
531
				|| GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) == NULL )
532
		{
533
				int	iDr;
534

  
535
				printf( "Output driver `%s' not recognised or does not support\n",
536
								pszFormat );
537
				printf( "direct output file creation.  The following format drivers are configured\n"
538
								"and support direct output:\n" );
539

  
540
				for( iDr = 0; iDr < GDALGetDriverCount(); iDr++ )
541
				{
542
						GDALDriverH hDriver = GDALGetDriver(iDr);
543

  
544
						if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL) != NULL )
545
						{
546
								printf( "  %s: %s\n",
547
												GDALGetDriverShortName( hDriver  ),
548
												GDALGetDriverLongName( hDriver ) );
549
						}
550
				}
551
				printf( "\n" );
552
				exit( 1 );
553
		}
554

  
555
/* -------------------------------------------------------------------- */
556
/*      For virtual output files, we have to set a special subclass     */
557
/*      of dataset to create.                                           */
558
/* -------------------------------------------------------------------- */
559
		if( bVRT )
560
				papszCreateOptions =
561
						CSLSetNameValue( papszCreateOptions, "SUBCLASS",
562
														 "VRTWarpedDataset" );
563

  
564
/* -------------------------------------------------------------------- */
565
/*      Loop over all input files to collect extents.                   */
566
/* -------------------------------------------------------------------- */
567
		int iSrc;
568

  
569
		for( iSrc = 0; papszSrcFiles[iSrc] != NULL; iSrc++ )
570
		{
571
				GDALDatasetH hSrcDS;
572
				const char *pszThisSourceSRS = pszSourceSRS;
573

  
574
				hSrcDS = GDALOpen( papszSrcFiles[iSrc], GA_ReadOnly );
575
				if( hSrcDS == NULL )
576
						exit( 1 );
577

  
578
				if( eDT == GDT_Unknown )
579
						eDT = GDALGetRasterDataType(GDALGetRasterBand(hSrcDS,1));
580

  
581
/* -------------------------------------------------------------------- */
582
/*      If we are processing the first file, and it has a color         */
583
/*      table, then we will copy it to the destination file.            */
584
/* -------------------------------------------------------------------- */
585
				if( iSrc == 0 )
586
				{
587
						nDstBandCount = GDALGetRasterCount(hSrcDS);
588
						hCT = GDALGetRasterColorTable( GDALGetRasterBand(hSrcDS,1) );
589
						if( hCT != NULL )
590
						{
591
								hCT = GDALCloneColorTable( hCT );
592
								printf( "Copying color table from %s to new file.\n",
593
												papszSrcFiles[iSrc] );
594
						}
595
				}
596

  
597
/* -------------------------------------------------------------------- */
598
/*      Get the sourcesrs from the dataset, if not set already.         */
599
/* -------------------------------------------------------------------- */
600
				if( pszThisSourceSRS == NULL )
601
				{
602
						if( GDALGetProjectionRef( hSrcDS ) != NULL
603
								&& strlen(GDALGetProjectionRef( hSrcDS )) > 0 )
604
								pszThisSourceSRS = GDALGetProjectionRef( hSrcDS );
605

  
606
						else if( GDALGetGCPProjection( hSrcDS ) != NULL
607
										 && strlen(GDALGetGCPProjection(hSrcDS)) > 0
608
										 && GDALGetGCPCount( hSrcDS ) > 1 )
609
								pszThisSourceSRS = GDALGetGCPProjection( hSrcDS );
610
						else
611
								pszThisSourceSRS = "";
612
				}
613

  
614
				if( pszTargetSRS == NULL )
615
						pszTargetSRS = pszThisSourceSRS;
616

  
617
/* -------------------------------------------------------------------- */
618
/*      Create a transformation object from the source to               */
619
/*      destination coordinate system.                                  */
620
/* -------------------------------------------------------------------- */
621
				hTransformArg =
622
						GDALCreateGenImgProjTransformer( hSrcDS, pszThisSourceSRS,
623
																						 NULL, pszTargetSRS,
624
																						 TRUE, 1000.0, nOrder );
625

  
626
				if( hTransformArg == NULL )
627
						return NULL;
628

  
629
/* -------------------------------------------------------------------- */
630
/*      Get approximate output definition.                              */
631
/* -------------------------------------------------------------------- */
632
				double adfThisGeoTransform[6];
633
				double adfExtent[4];
634
				int    nThisPixels, nThisLines;
635

  
636
				if( GDALSuggestedWarpOutput2( hSrcDS,
637
																			GDALGenImgProjTransform, hTransformArg,
638
																			adfThisGeoTransform,
639
																			&nThisPixels, &nThisLines,
640
																			adfExtent, 0 ) != CE_None )
641
						return NULL;
642

  
643
/* -------------------------------------------------------------------- */
644
/*      Expand the working bounds to include this region, ensure the    */
645
/*      working resolution is no more than this resolution.             */
646
/* -------------------------------------------------------------------- */
647
				if( dfWrkMaxX == 0.0 && dfWrkMinX == 0.0 )
648
				{
649
						dfWrkMinX = adfExtent[0];
650
						dfWrkMaxX = adfExtent[2];
651
						dfWrkMaxY = adfExtent[3];
652
						dfWrkMinY = adfExtent[1];
653
						dfWrkResX = adfThisGeoTransform[1];
654
						dfWrkResY = ABS(adfThisGeoTransform[5]);
655
				}
656
				else
657
				{
658
						dfWrkMinX = MIN(dfWrkMinX,adfExtent[0]);
659
						dfWrkMaxX = MAX(dfWrkMaxX,adfExtent[2]);
660
						dfWrkMaxY = MAX(dfWrkMaxY,adfExtent[3]);
661
						dfWrkMinY = MIN(dfWrkMinY,adfExtent[1]);
662
						dfWrkResX = MIN(dfWrkResX,adfThisGeoTransform[1]);
663
						dfWrkResY = MIN(dfWrkResY,ABS(adfThisGeoTransform[5]));
664
				}
665

  
666
				GDALDestroyGenImgProjTransformer( hTransformArg );
667

  
668
				GDALClose( hSrcDS );
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff