Statistics
| Revision:

svn-gvsig-desktop / tags / v1_1_Build_1002 / libraries / libFMap / src / com / iver / cit / gvsig / fmap / operations / strategies / ShpStrategy.java @ 12070

History | View | Annotate | Download (23.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.cit.gvsig.fmap.operations.strategies;
42

    
43
import java.awt.Graphics2D;
44
import java.awt.geom.Point2D;
45
import java.awt.geom.Rectangle2D;
46
import java.awt.image.BufferedImage;
47
import java.io.IOException;
48
import java.util.BitSet;
49
import java.util.List;
50

    
51
import javax.print.attribute.PrintRequestAttributeSet;
52

    
53
import org.apache.log4j.Logger;
54
import org.cresques.cts.ICoordTrans;
55
import org.geotools.resources.geometry.XRectangle2D;
56

    
57
import com.hardcode.driverManager.DriverLoadException;
58
import com.iver.cit.gvsig.fmap.DriverException;
59
import com.iver.cit.gvsig.fmap.ViewPort;
60
import com.iver.cit.gvsig.fmap.core.FShape;
61
import com.iver.cit.gvsig.fmap.core.IGeometry;
62
import com.iver.cit.gvsig.fmap.core.ISymbol;
63
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
64
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
65
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
66
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
67
import com.iver.cit.gvsig.fmap.layers.FBitSet;
68
import com.iver.cit.gvsig.fmap.layers.FLayer;
69
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
70
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
71
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
72
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
74
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
75
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
76
import com.iver.utiles.swing.threads.Cancellable;
77
import com.iver.utiles.swing.threads.CancellableMonitorable;
78
import com.vividsolutions.jts.geom.Geometry;
79
import com.vividsolutions.jts.geom.IntersectionMatrix;
80

    
81
/**
82
 * Esta clase definir? las operaciones de la interfaz FLyrVect de la manera m?s
83
 * ?ptima para los ficheros shp.
84
 */
85
public class ShpStrategy extends DefaultStrategy {
86
        private static Logger logger = Logger
87
                        .getLogger(ShpStrategy.class.getName());
88

    
89
        /**
90
         * Crea una ShpStrategy.
91
         *
92
         * @param capa
93
         */
94
        public ShpStrategy(FLayer capa) {
95
                super(capa);
96
        }
97

    
98
        /**
99
         * @see com.iver.cit.gvsig.fmap.operations.LayerOperations#draw(java.awt.image.BufferedImage,
100
         *      java.awt.Graphics2D, ISymbol)
101
         */
102
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
103
                        Cancellable cancel) throws DriverException {
104
                try {
105
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
106
                        if (adapter.getShapeCount() <= 0) {
107
                                // logger.info("Layer:" + getCapa().getName() + " sin
108
                                // registros");
109
                                return;
110
                        }
111

    
112
                        // Selectable selection = (Selectable) getCapa();
113
                        FLyrVect lyr = (FLyrVect) getCapa();
114
                        Selectable selectable = lyr.getRecordset();
115
                        ICoordTrans ct = getCapa().getCoordTrans();
116
                        FBitSet bitSet = selectable.getSelection();
117
                        BoundedShapes shapeBounds;
118
                        if (adapter instanceof BoundedShapes)
119
                                shapeBounds = (BoundedShapes) adapter;
120
                        else
121
                                shapeBounds = (BoundedShapes) adapter.getDriver();
122
                        // VectorialFileDriver driver = (VectorialFileDriver)
123
                        // adapter.getDriver();
124
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
125
                        adapter.start();
126
                        IGeometry geom;
127
                        // if (adapter.getShapeCount() > 0) {
128
                        // geom = adapter.getShape(0);
129
                        // }
130
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
131
                                        .getLegend();
132

    
133
//                        if (l instanceof ClassifiedLegendInfo) {
134
//                                ClassifiedLegendInfo clsfLegend = (ClassifiedLegendInfo) l;
135
//                                ISymbol[] symbs = clsfLegend.getSymbols();
136
//                                // double rSym = 0;
137
//                                // double maxRSym = -1;
138
//
139
//                                for (int i = 0; i < symbs.length; i++) {
140
//                                        // TODO: REVISAR LOS SIMBOLOS Y SUS TAMA?OS
141
//
142
//                                        /*
143
//                                         * Style2D pointSymbol = symbs[i].getPointStyle2D(); if
144
//                                         * (pointSymbol instanceof MarkStyle2D) { MarkStyle2D mrk2D =
145
//                                         * (MarkStyle2D) pointSymbol; rSym =
146
//                                         * viewPort.toMapDistance(mrk2D.getSize()); if (maxRSym <
147
//                                         * rSym) maxRSym = rSym; }
148
//                                         */
149
//                                }
150
//                        }
151

    
152
                        Rectangle2D extent = viewPort.getAdjustedExtent();
153
                        // AffineTransform at = viewPort.getAffineTransform();
154

    
155
                        int sc;
156

    
157
                        Rectangle2D bounds;
158

    
159
                        long t1 = System.currentTimeMillis();
160
                        // logger.debug("getCapa().getRecordset().start()");
161

    
162
                        //CHEMA
163
                        // En teorioa el al hacer el adapter.start()
164
                        // deja abierta las fuentes de datos
165
                        // geometrica y alfanumerica (cuando no son la misma
166
                        // excepto cuando se ha hecho una operacion de 'join' de la tabla
167
                        // (join de las tablas de gvsig(gdbms) no join de sql), entoces
168
                        // el origen alfanumerico no es el mismo en el source
169
                        // que en la capa.
170
                        //
171
                        //((FLyrVect) getCapa()).getRecordset().start();
172
                        if (lyr.isJoined()){
173
                                lyr.getRecordset().start();
174
                        }
175
                        //CHEMA
176

    
177
                        // TODO: A revisar si es o no conveniente este sistema
178
                        // de comunicaci?n con los drivers.
179
                        DriverAttributes attr = adapter.getDriverAttributes();
180
                        boolean bMustClone = false;
181
                        if (attr != null) {
182
                                if (attr.isLoadedInMemory()) {
183
                                        bMustClone = attr.isLoadedInMemory();
184
                                }
185
                        }
186

    
187
                        List lstIndexes = null;
188

    
189
                        // If area of needed extent is less than fullExtent / 4,
190
                        // it will be worthy to use SpatialIndex.
191
                        // Otherwhise, we will not use it.
192
                        boolean bUseSpatialIndex = false;
193
                        sc = adapter.getShapeCount();
194
                        // if (lyr.getSpatialIndex() != null) AZABALA
195
                        // long t11 = System.currentTimeMillis();
196
                        if (lyr.getISpatialIndex() != null) {
197
                                if (isSpatialIndexNecessary(extent)) {
198
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
199
                                        // If the layer is reprojected, spatial index was created
200
                                        // in its own projection, so we must to apply an inverse
201
                                        // transform
202
                                        if (ct != null) {
203
                                                Rectangle2D newExtent = ct.getInverted()
204
                                                                .convert(extent);
205
                                                // Rectangle2D newExtent = ct.convert(extent);
206
                                                // lstIndexes = lyr.getISpatialIndex().query(extent);
207
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
208
                                        } else {
209
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
210
                                        }
211
                                        sc = lstIndexes.size();
212
                                        bUseSpatialIndex = true;
213
                                }// if
214
                        }// if
215
                        /*
216
                         * long t12 = System.currentTimeMillis(); System.out.println("Tiempo
217
                         * en mirar el ?ndice espacial y recuperar los ?ndices:" +
218
                         * (t12-t11)); System.out.println("Numero de ?ndices:" + sc);
219
                         */
220

    
221
                        // SpatialCache cache = lyr.createSpatialCache();
222
                        lyr.getSpatialCache().clearAll();
223
                        SpatialCache cache = lyr.getSpatialCache();
224
                        int i;
225

    
226
                        // En OS X con renderer Quartz (JRE<6), mezclar setRGB con dibujado
227
                        // geometrico en mismo BufferedImage
228
                        // provoca ralentizaci?n brutal. Lo evitamos separando los setRGB en
229
                        // otro BufferedImage y juntandolos luego.
230
                        boolean MAC_OS_X = System.getProperty("os.name").toLowerCase()
231
                                        .startsWith("mac os x");
232
                        BufferedImage auxBI = null;
233
                        if (MAC_OS_X) {
234
                                auxBI = new BufferedImage(image.getWidth(), image.getHeight(),
235
                                                image.getType());
236
                        }
237
                        for (int aux = 0; aux < sc; aux++) {
238
                                // Salimos si alguien cancela
239

    
240
                                if (cancel != null) {
241
                                        // azabala (por si acaso, al arreglar bug de process)
242
                                        if (cancel.isCanceled()) {
243
                                                return;
244
                                        }
245
                                }
246
                                if (bUseSpatialIndex) {
247
                                        Integer idRec = (Integer) lstIndexes.get(aux);
248
                                        i = idRec.intValue();
249
                                } else {
250
                                        i = aux;
251
                                }
252
                                if (getCapa().isEditing())
253
                                        bounds=adapter.getShape(i).getBounds2D();
254
                                else
255
                                        bounds = shapeBounds.getShapeBounds(i);
256
                                if (ct != null) {
257
                                        bounds = ct.convert(bounds);
258
                                }
259
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
260
                                        ISymbol symbol = l.getSymbol(i);
261

    
262
                                        if (bitSet.get(i)) {
263
                                                symbol = symbol.getSymbolForSelection();
264
                                        }
265

    
266
                                        if (symbol == null)
267
                                                continue;
268

    
269
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
270

    
271
                                        if (bPoint
272
                                                        || ((bounds.getHeight() > viewPort.getDist1pixel()) || (bounds
273
                                                                        .getWidth() > viewPort.getDist1pixel()))) {
274
                                                geom = adapter.getShape(i);
275

    
276
                                                // PRUEBA DE VELOCIDAD
277
                                                // geom = ShapeFactory.createPolygon2D(new
278
                                                // GeneralPathX(bounds));
279

    
280

    
281
                                                //JMVIVO: OJO, No colnamos siempre porque
282
                                                // el FGeometry.drawInt (a diferencia del
283
                                                // FGeometry.draw) clona siempre la geometria
284
                                                // antes de pintarla (para transforma a enteros)
285
                                                if (ct != null) {
286
                                                        if (bMustClone)
287
                                                                geom = geom.cloneGeometry();
288
                                                        geom.reProject(ct);
289
                                                }
290
                                                if (lyr.isSpatialCacheEnabled()) {
291
                                                        if (cache.getMaxFeatures() >= cache.size()) {
292
                                                                // Ya reproyectado todo
293
                                                                cache.insert(bounds, geom);
294
                                                        }
295
                                                }
296

    
297
                                                // FJP: CAMBIO: Sabemos que vamos a dibujar sobre una
298
                                                // imagen, con coordenadas enteras, as?
299
                                                // que lo tenemos en cuenta.
300
                                                // ANTES: geom.draw(g, viewPort, symbol);
301
                                                // AHORA:
302
                                                geom.drawInts(g, viewPort, symbol);
303
                                                // geom.draw(g, viewPort, symbol);
304
                                                /*
305
                                                 * if (lyr.isEditing()) { if (bitSet.get(i)) { Handler[]
306
                                                 * handlers = geom.getHandlers(IGeometry.SELECTHANDLER);
307
                                                 * FGraphicUtilities.DrawHandlers(g,
308
                                                 * viewPort.getAffineTransform(), handlers); } }
309
                                                 */
310

    
311
                                        } else {
312
                                                Point2D.Double pOrig = new Point2D.Double(bounds
313
                                                                .getMinX(), bounds.getMinY());
314
                                                Point2D pDest, pDest2;
315

    
316
                                                pDest = viewPort.getAffineTransform().transform(pOrig,
317
                                                                null);
318
                                                pDest2 = g.getTransform().transform(pDest, null);
319

    
320
                                                int pixX = (int) pDest2.getX();
321
                                                int pixY = (int) pDest2.getY();
322
                                                if (symbol == null)
323
                                                        continue;
324
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
325
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
326
                                                                if (MAC_OS_X) {
327
                                                                        auxBI.setRGB(pixX, pixY, symbol
328
                                                                                        .getOnePointRgb());
329
                                                                } else {
330
                                                                        image.setRGB(pixX, pixY, symbol
331
                                                                                        .getOnePointRgb());
332
                                                                }
333
                                                        }
334
                                                }
335
                                        }
336
                                }
337
                        }
338

    
339
                        if (MAC_OS_X) {
340
                                g.drawImage(auxBI, 0, 0, null);
341
                        }
342

    
343
                        // logger.debug("getCapa().getRecordset().stop()");
344
                        //CHEMA
345
                        // Cerramos la fuente alfanumerica cuando se ha hecho
346
                        // una operacion de 'join'
347
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
348
                        if (lyr.isJoined()){
349
                                lyr.getRecordset().stop();
350
                        }
351
                        //CHEMA
352

    
353
                        long t2 = System.currentTimeMillis();
354
                        // logger.debug("adapter.stop()");
355
                        adapter.stop();
356

    
357
                        // System.out.println(t2 - t1);
358
                } catch (DriverIOException e) {
359
                        throw new DriverException(e);
360
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
361
                        throw new DriverException(e);
362
                } catch (DriverException e) {
363
                        throw new DriverException(e);
364
                } catch (IOException e) {
365
                        throw new DriverException(e);
366
                } catch (DriverLoadException e) {
367
                        // TODO Auto-generated catch block
368
                        e.printStackTrace();
369
                }
370
        }
371

    
372
        /**
373
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
374
         * par?metro, pensado para utilizarse para imprimir.
375
         *
376
         * @param g
377
         *            Graphics2D
378
         * @param viewPort
379
         *            ViewPort.
380
         * @param cancel
381
         *
382
         * @throws DriverException
383
         */
384
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
385
                        PrintRequestAttributeSet printProperties) throws DriverException {
386
                // super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del
387
                // padre, que es el que va sin acelaraci?n!!
388
                try {
389
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
390
                        if (adapter.getShapeCount() <= 0) {
391
                                // logger.info("Layer:" + getCapa().getName() + " sin
392
                                // registros");
393
                                return;
394
                        }
395
                        FLyrVect lyr = (FLyrVect) getCapa();
396
                        lyr.beforePrinting(printProperties);
397

    
398
                        Selectable selectable = lyr.getRecordset();
399
                        ICoordTrans ct = getCapa().getCoordTrans();
400
                        BitSet bitSet = selectable.getSelection();
401
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
402
                        VectorialDriver driver = (VectorialDriver) adapter
403
                                        .getDriver();
404
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
405
                        adapter.start();
406
                        IGeometry geom;
407
                        if (adapter.getShapeCount() > 0) {
408
                                geom = adapter.getShape(0);
409
                        }
410
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
411
                                        .getLegend();
412

    
413
                        Rectangle2D extent = viewPort.getAdjustedExtent();
414
                        // AffineTransform at = viewPort.getAffineTransform();
415

    
416
                        int sc;
417

    
418
                        Rectangle2D bounds;
419

    
420
                        sc = adapter.getShapeCount();
421

    
422
                        long t1 = System.currentTimeMillis();
423
                        // logger.debug("getCapa().getRecordset().start()");
424

    
425
                        //CHEMA
426
                        // En teorioa el al hacer el adapter.start()
427
                        // deja abierta las fuentes de datos
428
                        // geometrica y alfanumerica (cuando no son la misma
429
                        // excepto cuando se ha hecho una operacion de 'join' de la tabla
430
                        // (join de las tablas de gvsig(gdbms) no join de sql), entoces
431
                        // el origen alfanumerico no es el mismo en el source
432
                        // que en la capa.
433
                        //
434
                        //((FLyrVect) getCapa()).getRecordset().start();
435
                        if (lyr.isJoined()){
436
                                lyr.getRecordset().start();
437
                        }
438
                        //CHEMA
439

    
440

    
441
                        // TODO: A revisar si es o no conveniente este sistema
442
                        // de comunicaci?n con los drivers.
443
                        DriverAttributes attr = adapter.getDriverAttributes();
444
                        boolean bMustClone = false;
445
                        if (attr != null) {
446
                                if (attr.isLoadedInMemory()) {
447
                                        bMustClone = attr.isLoadedInMemory();
448
                                }
449
                        }
450

    
451
                        List lstIndexes = null;
452

    
453
                        boolean bUseSpatialIndex = false;
454
                        if (lyr.getISpatialIndex() != null) {
455
                                if (isSpatialIndexNecessary(extent)) {
456
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
457
                                        if (ct != null) {
458
                                                Rectangle2D newExtent = ct.getInverted()
459
                                                                .convert(extent);
460
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
461
                                        } else {
462
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
463
                                        }
464
                                        sc = lstIndexes.size();
465
                                        bUseSpatialIndex = true;
466
                                }// if
467
                        }// if
468

    
469
                        int i;
470
                        for (int aux = 0; aux < sc; aux++) {
471
                                if (bUseSpatialIndex) {
472
                                        Integer idRec = (Integer) lstIndexes.get(aux);
473
                                        i = idRec.intValue();
474
                                } else {
475
                                        i = aux;
476
                                }
477

    
478
                                bounds = shapeBounds.getShapeBounds(i);
479

    
480
                                if (ct != null) {
481
                                        bounds = ct.convert(bounds);
482
                                }
483

    
484
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
485
                                        ISymbol symbol = l.getSymbol(i);
486
                                        if (symbol == null)
487
                                                continue;
488
                                        if (bitSet.get(i)) {
489
                                                symbol = symbol.getSymbolForSelection();
490
                                        }
491

    
492
                                        //boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
493

    
494
                                        geom = driver.getShape(i);
495

    
496
                                        // PRUEBA DE VELOCIDAD
497
                                        // geom = ShapeFactory.createPolygon2D(new
498
                                        // GeneralPathX(bounds));
499

    
500
                                        // JMVIVO: Clonamos siempre que sea necesario y no
501
                                        // solo si hay que reproyectar. Porque el FGeometry.draw
502
                                        // va a aplicar la transformacion sobre la geometria original
503
                                        if (bMustClone)
504
                                                geom = geom.cloneGeometry();
505

    
506
                                        if (ct != null) {
507
                                                geom.reProject(ct);
508
                                        }
509

    
510
                                        geom.draw(g, viewPort, symbol);
511

    
512
                                }
513
                        }
514

    
515
                        // logger.debug("getCapa().getRecordset().stop()");
516
                        //CHEMA
517
                        // Cerramos la fuente alfanumerica cuando se ha hecho
518
                        // una operacion de 'join'
519
                        //((FLyrVect) getCapa()).getSource().getRecordset().stop();
520
                        if (lyr.isJoined()){
521
                                lyr.getRecordset().stop();
522
                        }
523
                        //CHEMA
524

    
525
                        long t2 = System.currentTimeMillis();
526
                        // logger.debug("adapter.stop()");
527
                        adapter.stop();
528
                        lyr.afterPrinting();
529
                        // System.out.println(t2 - t1);
530
                } catch (DriverIOException e) {
531
                        throw new DriverException(e);
532
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
533
                        throw new DriverException(e);
534
                } catch (DriverException e) {
535
                        throw new DriverException(e);
536
                } catch (IOException e) {
537
                        throw new DriverException(e);
538
                }
539

    
540
        }
541

    
542
        public FBitSet queryByShape(IGeometry g, int relationship)
543
                        throws DriverException, VisitException {
544
                return queryByShape(g, relationship, null);
545
        }
546

    
547
        /*
548
         * (non-Javadoc)
549
         *
550
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry,
551
         *      int)
552
         */
553
        public FBitSet queryByShape(IGeometry g, int relationship,
554
                        CancellableMonitorable cancel) throws DriverException,
555
                        VisitException {
556
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
557
                FLyrVect lyr = (FLyrVect) capa;
558
                // if (lyr.getSpatialIndex() == null) AZABALA
559
                if (lyr.getISpatialIndex() == null)
560
                        return super.queryByShape(g, relationship, null);
561

    
562
                long t1 = System.currentTimeMillis();
563
                ReadableVectorial va = lyr.getSource();
564
                ICoordTrans ct = lyr.getCoordTrans();
565
                Rectangle2D bounds = g.getBounds2D();
566
                List lstRecs = lyr.getISpatialIndex().query(bounds);
567
                Integer idRec;
568
                FBitSet bitset = new FBitSet();
569
                Geometry jtsShape = g.toJTSGeometry();
570
                IntersectionMatrix m;
571
                int index;
572
                try {
573
                        va.start();
574

    
575
                        for (int i = 0; i < lstRecs.size(); i++) {
576
                                if (cancel != null) {
577
                                        cancel.reportStep();
578
                                        if (cancel.isCanceled()) {
579
                                                break;
580
                                        }
581
                                }
582
                                idRec = (Integer) lstRecs.get(i);
583
                                index = idRec.intValue();
584
                                IGeometry geom = va.getShape(index);
585
                                if (geom == null)
586
                                        continue;
587
                                if (ct != null) {
588
                                        geom.reProject(ct);
589
                                }
590
                                Geometry jtsGeom = geom.toJTSGeometry();
591
                                switch (relationship) {
592
                                case CONTAINS:
593
                                        m = jtsShape.relate(jtsGeom);
594
                                        if (m.isContains()) {
595
                                                bitset.set(index, true);
596
                                        }
597
                                        break;
598

    
599
                                case CROSSES:
600
                                        m = jtsShape.relate(jtsGeom);
601
                                        if (m.isCrosses(jtsGeom.getDimension(), jtsShape
602
                                                        .getDimension())) {
603
                                                bitset.set(index, true);
604
                                        }
605
                                        break;
606

    
607
                                case DISJOINT:
608
                                        // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
609
                                        m = jtsShape.relate(jtsGeom);
610
                                        if (m.isDisjoint()) {
611
                                                bitset.set(index, true);
612
                                        }
613
                                        break;
614

    
615
                                case EQUALS:
616
                                        m = jtsShape.relate(jtsGeom);
617
                                        if (m.isEquals(jtsGeom.getDimension(), jtsShape
618
                                                        .getDimension())) {
619
                                                bitset.set(index, true);
620
                                        }
621
                                        break;
622

    
623
                                case INTERSECTS:
624
                                        m = jtsShape.relate(jtsGeom);
625
                                        if (m.isIntersects()) {
626
                                                bitset.set(index, true);
627
                                        }
628
                                        break;
629

    
630
                                case OVERLAPS:
631
                                        m = jtsShape.relate(jtsGeom);
632
                                        if (m.isOverlaps(jtsGeom.getDimension(), jtsShape
633
                                                        .getDimension())) {
634
                                                bitset.set(index, true);
635
                                        }
636

    
637
                                        break;
638

    
639
                                case TOUCHES:
640
                                        m = jtsShape.relate(jtsGeom);
641
                                        if (m.isTouches(jtsGeom.getDimension(), jtsShape
642
                                                        .getDimension())) {
643
                                                bitset.set(index, true);
644
                                        }
645

    
646
                                        break;
647

    
648
                                case WITHIN:
649
                                        m = jtsShape.relate(jtsGeom);
650
                                        if (m.isWithin()) {
651
                                                bitset.set(index, true);
652
                                        }
653

    
654
                                        break;
655
                                }
656
                        }
657
                        va.stop();
658
                } catch (DriverIOException e) {
659
                        // TODO Auto-generated catch block
660
                        e.printStackTrace();
661
                }
662
                long t2 = System.currentTimeMillis();
663
                // logger.info("queryByShape optimizado sobre la capa " + lyr.getName()
664
                // + ". " + (t2 - t1) + " mseg.");
665
                return bitset;
666
        }
667

    
668
        public FBitSet queryByRect(Rectangle2D rect, CancellableMonitorable cancel)
669
                        throws DriverException {
670
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
671
                FLyrVect lyr = (FLyrVect) capa;
672
                if (lyr.getISpatialIndex() == null)
673
                        return super.queryByRect(rect, cancel);
674

    
675
                ReadableVectorial va = lyr.getSource();
676
                ICoordTrans ct = lyr.getCoordTrans();
677
                Rectangle2D bounds = rect;
678
                List lstRecs = lyr.getISpatialIndex().query(bounds);
679
                Integer idRec;
680
                FBitSet bitset = new FBitSet();
681
                int index;
682
                try {
683
                        va.start();
684
                        DriverAttributes attr = va.getDriverAttributes();
685
                        boolean bMustClone = false;
686
                        if (attr != null) {
687
                                if (attr.isLoadedInMemory()) {
688
                                        bMustClone = attr.isLoadedInMemory();
689
                                }
690
                        }
691

    
692
                        for (int i = 0; i < lstRecs.size(); i++) {
693
                                if (cancel != null) {
694
                                        cancel.reportStep();
695
                                        if (cancel.isCanceled()) {
696
                                                va.stop();
697
                                                return bitset;
698
                                        }
699
                                }
700
                                idRec = (Integer) lstRecs.get(i);
701
                                index = idRec.intValue();
702
                                IGeometry geom = va.getShape(index);
703
                                if (geom == null)// azabala
704
                                        continue;
705
                                if (ct != null) {
706
                                        if (bMustClone)
707
                                                geom = geom.cloneGeometry();
708
                                        geom.reProject(ct);
709
                                }
710
                                if (geom.intersects(rect))
711
                                        bitset.set(index, true);
712
                        }
713
                        va.stop();
714
                } catch (DriverIOException e) {
715
                        // TODO Auto-generated catch block
716
                        e.printStackTrace();
717
                }
718
                return bitset;
719

    
720
        }
721

    
722
        public void process(FeatureVisitor visitor, Rectangle2D rectangle)
723
                        throws DriverException, VisitException {
724
                process(visitor, rectangle, null);
725
        }
726

    
727
        /**
728
         * Processes (by calling visitor.process() method) only those features of
729
         * the vectorial layer associated which intersects given rectangle2d.
730
         *
731
         */
732

    
733
        public void process(FeatureVisitor visitor, Rectangle2D rectangle,
734
                        CancellableMonitorable cancel) throws DriverException,
735
                        VisitException {
736
                if (visitor.start(capa)) {
737
                        FLyrVect lyr = (FLyrVect) capa;
738
                        // if we dont have spatial index or...
739
                        if (lyr.getISpatialIndex() == null) {
740
                                super.process(visitor, rectangle, cancel);
741
                                return;
742
                        }
743
                        // if spatial index is not worthy
744
                        if (!isSpatialIndexNecessary(rectangle)) {
745
                                super.process(visitor, rectangle, cancel);
746
                                return;
747
                        }
748

    
749
                        ReadableVectorial va = lyr.getSource();
750
                        ICoordTrans ct = lyr.getCoordTrans();
751
                        Rectangle2D bounds = rectangle;
752
                        List lstRecs = lyr.getISpatialIndex().query(bounds);
753
                        Integer idRec;
754
                        int index;
755
                        try {
756
                                va.start();
757
                                DriverAttributes attr = va.getDriverAttributes();
758
                                boolean bMustClone = false;
759
                                if (attr != null) {
760
                                        if (attr.isLoadedInMemory()) {
761
                                                bMustClone = attr.isLoadedInMemory();
762
                                        }
763
                                }
764

    
765
                                for (int i = 0; i < lstRecs.size(); i++) {
766
                                        if (cancel != null) {
767
                                                cancel.reportStep();
768
                                        }
769
                                        if (verifyCancelation(cancel, va, visitor))
770
                                                return;
771
                                        idRec = (Integer) lstRecs.get(i);
772
                                        index = idRec.intValue();
773
                                        IGeometry geom = va.getShape(index);
774
                                        if (geom == null)// azabala
775
                                                continue;
776
                                        if (ct != null) {
777
                                                if (bMustClone)
778
                                                        geom = geom.cloneGeometry();
779
                                                geom.reProject(ct);
780
                                        }
781
                                        if (geom.intersects(rectangle))
782
                                                visitor.visit(geom, index);
783
                                }// for
784
                                va.stop();
785
                        } catch (DriverIOException e) {
786
                                // TODO Auto-generated catch block
787
                                e.printStackTrace();
788
                        }
789
                }// if visitor.start
790
        }
791

    
792
        /*
793
         * (non-Javadoc)
794
         *
795
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D,
796
         *      double)
797
         */
798
        public FBitSet queryByPoint(Point2D p, double tolerance,
799
                        CancellableMonitorable cancel) throws DriverException {
800
                // TODO: OJO!!!!. Est? implementado como un rectangulo.
801
                // Lo correcto deber?a ser calculando las distancias reales
802
                // es decir, con un c?rculo.
803
                Rectangle2D recPoint = new Rectangle2D.Double(p.getX()
804
                                - (tolerance / 2), p.getY() - (tolerance / 2), tolerance,
805
                                tolerance);
806
                return queryByRect(recPoint, cancel);
807
        }
808
}