Statistics
| Revision:

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

History | View | Annotate | Download (22 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.AlphanumericData;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
74
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
75
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
76
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegendInfo;
77
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
78
import com.iver.utiles.swing.threads.Cancellable;
79
import com.iver.utiles.swing.threads.CancellableMonitorable;
80
import com.vividsolutions.jts.geom.Geometry;
81
import com.vividsolutions.jts.geom.IntersectionMatrix;
82

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

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

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

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

    
135
                        if (l instanceof ClassifiedLegendInfo) {
136
                                ClassifiedLegendInfo clsfLegend = (ClassifiedLegendInfo) l;
137
                                ISymbol[] symbs = clsfLegend.getSymbols();
138
                                // double rSym = 0;
139
                                // double maxRSym = -1;
140

    
141
                                for (int i = 0; i < symbs.length; i++) {
142
                                        // TODO: REVISAR LOS SIMBOLOS Y SUS TAMA?OS
143

    
144
                                        /*
145
                                         * Style2D pointSymbol = symbs[i].getPointStyle2D(); if
146
                                         * (pointSymbol instanceof MarkStyle2D) { MarkStyle2D mrk2D =
147
                                         * (MarkStyle2D) pointSymbol; rSym =
148
                                         * viewPort.toMapDistance(mrk2D.getSize()); if (maxRSym <
149
                                         * rSym) maxRSym = rSym; }
150
                                         */
151
                                }
152
                        }
153

    
154
                        Rectangle2D extent = viewPort.getAdjustedExtent();
155
                        // AffineTransform at = viewPort.getAffineTransform();
156

    
157
                        int sc;
158

    
159
                        Rectangle2D bounds;
160

    
161
                        long t1 = System.currentTimeMillis();
162
                        // logger.debug("getCapa().getRecordset().start()");
163
                        ((FLyrVect) getCapa()).getRecordset().start();
164

    
165
                        // TODO: A revisar si es o no conveniente este sistema
166
                        // de comunicaci?n con los drivers.
167
                        DriverAttributes attr = adapter.getDriverAttributes();
168
                        boolean bMustClone = false;
169
                        if (attr != null) {
170
                                if (attr.isLoadedInMemory()) {
171
                                        bMustClone = attr.isLoadedInMemory();
172
                                }
173
                        }
174

    
175
                        List lstIndexes = null;
176

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

    
209
                        // SpatialCache cache = lyr.createSpatialCache();
210
                        lyr.getSpatialCache().clearAll();
211
                        SpatialCache cache = lyr.getSpatialCache();
212
                        int i;
213

    
214
                        // En OS X con renderer Quartz (JRE<6), mezclar setRGB con dibujado
215
                        // geometrico en mismo BufferedImage
216
                        // provoca ralentizaci?n brutal. Lo evitamos separando los setRGB en
217
                        // otro BufferedImage y juntandolos luego.
218
                        boolean MAC_OS_X = System.getProperty("os.name").toLowerCase()
219
                                        .startsWith("mac os x");
220
                        BufferedImage auxBI = null;
221
                        if (MAC_OS_X) {
222
                                auxBI = new BufferedImage(image.getWidth(), image.getHeight(),
223
                                                image.getType());
224
                        }
225

    
226
                        for (int aux = 0; aux < sc; aux++) {
227
                                // Salimos si alguien cancela
228
                                if (cancel != null) {
229
                                        // azabala (por si acaso, al arreglar bug de process)
230
                                        if (cancel.isCanceled()) {
231
                                                break;
232
                                        }
233
                                }
234
                                if (bUseSpatialIndex) {
235
                                        Integer idRec = (Integer) lstIndexes.get(aux);
236
                                        i = idRec.intValue();
237
                                } else {
238
                                        i = aux;
239
                                }
240
                                bounds = shapeBounds.getShapeBounds(i);
241
                                if (ct != null) {
242
                                        bounds = ct.convert(bounds);
243
                                }
244
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
245
                                        ISymbol symbol = l.getSymbol(i);
246

    
247
                                        if (bitSet.get(i)) {
248
                                                symbol = symbol.getSymbolForSelection();
249
                                        }
250

    
251
                                        if (symbol == null)
252
                                                continue;
253

    
254
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
255

    
256
                                        if (bPoint
257
                                                        || ((bounds.getHeight() > viewPort.getDist1pixel()) || (bounds
258
                                                                        .getWidth() > viewPort.getDist1pixel()))) {
259
                                                geom = adapter.getShape(i);
260

    
261
                                                // PRUEBA DE VELOCIDAD
262
                                                // geom = ShapeFactory.createPolygon2D(new
263
                                                // GeneralPathX(bounds));
264

    
265
                                                
266
                                                //JMVIVO: OJO, No colnamos siempre porque
267
                                                // el FGeometry.drawInt (a diferencia del
268
                                                // FGeometry.draw) clona siempre la geometria
269
                                                // antes de pintarla (para transforma a enteros)
270
                                                if (ct != null) {
271
                                                        if (bMustClone)
272
                                                                geom = geom.cloneGeometry();
273
                                                        geom.reProject(ct);
274
                                                }
275
                                                if (lyr.isSpatialCacheEnabled()) {
276
                                                        if (cache.getMaxFeatures() >= cache.size()) {
277
                                                                // Ya reproyectado todo
278
                                                                cache.insert(bounds, geom);
279
                                                        }
280
                                                }
281

    
282
                                                // FJP: CAMBIO: Sabemos que vamos a dibujar sobre una
283
                                                // imagen, con coordenadas enteras, as?
284
                                                // que lo tenemos en cuenta.
285
                                                // ANTES: geom.draw(g, viewPort, symbol);
286
                                                // AHORA:
287
                                                geom.drawInts(g, viewPort, symbol);
288
                                                // geom.draw(g, viewPort, symbol);
289
                                                /*
290
                                                 * if (lyr.isEditing()) { if (bitSet.get(i)) { Handler[]
291
                                                 * handlers = geom.getHandlers(IGeometry.SELECTHANDLER);
292
                                                 * FGraphicUtilities.DrawHandlers(g,
293
                                                 * viewPort.getAffineTransform(), handlers); } }
294
                                                 */
295

    
296
                                        } else {
297
                                                Point2D.Double pOrig = new Point2D.Double(bounds
298
                                                                .getMinX(), bounds.getMinY());
299
                                                Point2D pDest, pDest2;
300

    
301
                                                pDest = viewPort.getAffineTransform().transform(pOrig,
302
                                                                null);
303
                                                pDest2 = g.getTransform().transform(pDest, null);
304

    
305
                                                int pixX = (int) pDest2.getX();
306
                                                int pixY = (int) pDest2.getY();
307
                                                if (symbol == null)
308
                                                        continue;
309
                                                if ((pixX > 0) && (pixX < image.getWidth())) {
310
                                                        if ((pixY > 0) && (pixY < image.getHeight())) {
311
                                                                if (MAC_OS_X) {
312
                                                                        auxBI.setRGB(pixX, pixY, symbol
313
                                                                                        .getOnePointRgb());
314
                                                                } else {
315
                                                                        image.setRGB(pixX, pixY, symbol
316
                                                                                        .getOnePointRgb());
317
                                                                }
318
                                                        }
319
                                                }
320
                                        }
321
                                }
322
                        }
323

    
324
                        if (MAC_OS_X) {
325
                                g.drawImage(auxBI, 0, 0, null);
326
                        }
327

    
328
                        // logger.debug("getCapa().getRecordset().stop()");
329
                        ((FLyrVect) getCapa()).getSource().getRecordset().stop();
330

    
331
                        long t2 = System.currentTimeMillis();
332
                        // logger.debug("adapter.stop()");
333
                        adapter.stop();
334

    
335
                        // System.out.println(t2 - t1);
336
                } catch (DriverIOException e) {
337
                        throw new DriverException(e);
338
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
339
                        throw new DriverException(e);
340
                } catch (DriverException e) {
341
                        throw new DriverException(e);
342
                } catch (IOException e) {
343
                        throw new DriverException(e);
344
                } catch (DriverLoadException e) {
345
                        // TODO Auto-generated catch block
346
                        e.printStackTrace();
347
                }
348
        }
349

    
350
        /**
351
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
352
         * par?metro, pensado para utilizarse para imprimir.
353
         *
354
         * @param g
355
         *            Graphics2D
356
         * @param viewPort
357
         *            ViewPort.
358
         * @param cancel
359
         *
360
         * @throws DriverException
361
         */
362
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
363
                        PrintRequestAttributeSet printProperties) throws DriverException {
364
                // super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del
365
                // padre, que es el que va sin acelaraci?n!!
366
                try {
367
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
368
                        if (adapter.getShapeCount() <= 0) {
369
                                // logger.info("Layer:" + getCapa().getName() + " sin
370
                                // registros");
371
                                return;
372
                        }
373
                        FLyrVect lyr = (FLyrVect) getCapa();
374
                        lyr.beforePrinting(printProperties);
375

    
376
                        Selectable selectable = lyr.getRecordset();
377
                        ICoordTrans ct = getCapa().getCoordTrans();
378
                        BitSet bitSet = selectable.getSelection();
379
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
380
                        VectorialDriver driver = (VectorialDriver) adapter
381
                                        .getDriver();
382
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
383
                        adapter.start();
384
                        IGeometry geom;
385
                        if (adapter.getShapeCount() > 0) {
386
                                geom = adapter.getShape(0);
387
                        }
388
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
389
                                        .getLegend();
390

    
391
                        Rectangle2D extent = viewPort.getAdjustedExtent();
392
                        // AffineTransform at = viewPort.getAffineTransform();
393

    
394
                        int sc;
395

    
396
                        Rectangle2D bounds;
397

    
398
                        sc = adapter.getShapeCount();
399

    
400
                        long t1 = System.currentTimeMillis();
401
                        // logger.debug("getCapa().getRecordset().start()");
402
                        ((AlphanumericData) getCapa()).getRecordset().start();
403

    
404
                        // TODO: A revisar si es o no conveniente este sistema
405
                        // de comunicaci?n con los drivers.
406
                        DriverAttributes attr = adapter.getDriverAttributes();
407
                        boolean bMustClone = false;
408
                        if (attr != null) {
409
                                if (attr.isLoadedInMemory()) {
410
                                        bMustClone = attr.isLoadedInMemory();
411
                                }
412
                        }
413

    
414
                        List lstIndexes = null;
415

    
416
                        boolean bUseSpatialIndex = false;
417
                        if (lyr.getISpatialIndex() != null) {
418
                                if (isSpatialIndexNecessary(extent)) {
419
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
420
                                        if (ct != null) {
421
                                                Rectangle2D newExtent = ct.getInverted()
422
                                                                .convert(extent);
423
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
424
                                        } else {
425
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
426
                                        }
427
                                        sc = lstIndexes.size();
428
                                        bUseSpatialIndex = true;
429
                                }// if
430
                        }// if
431

    
432
                        int i;
433
                        for (int aux = 0; aux < sc; aux++) {
434
                                if (bUseSpatialIndex) {
435
                                        Integer idRec = (Integer) lstIndexes.get(aux);
436
                                        i = idRec.intValue();
437
                                } else {
438
                                        i = aux;
439
                                }
440

    
441
                                bounds = shapeBounds.getShapeBounds(i);
442

    
443
                                if (ct != null) {
444
                                        bounds = ct.convert(bounds);
445
                                }
446

    
447
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
448
                                        ISymbol symbol = l.getSymbol(i);
449
                                        if (symbol == null)
450
                                                continue;
451
                                        if (bitSet.get(i)) {
452
                                                symbol = symbol.getSymbolForSelection();
453
                                        }
454

    
455
                                        //boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
456

    
457
                                        geom = driver.getShape(i);
458

    
459
                                        // PRUEBA DE VELOCIDAD
460
                                        // geom = ShapeFactory.createPolygon2D(new
461
                                        // GeneralPathX(bounds));
462
                                        
463
                                        // JMVIVO: Clonamos siempre que sea necesario y no
464
                                        // solo si hay que reproyectar. Porque el FGeometry.draw
465
                                        // va a aplicar la transformacion sobre la geometria original
466
                                        if (bMustClone)
467
                                                geom = geom.cloneGeometry();
468

    
469
                                        if (ct != null) {
470
                                                geom.reProject(ct);
471
                                        }
472

    
473
                                        geom.draw(g, viewPort, symbol);
474

    
475
                                }
476
                        }
477

    
478
                        // logger.debug("getCapa().getRecordset().stop()");
479
                        ((AlphanumericData) getCapa()).getRecordset().stop();
480

    
481
                        long t2 = System.currentTimeMillis();
482
                        // logger.debug("adapter.stop()");
483
                        adapter.stop();
484
                        lyr.afterPrinting();
485
                        // System.out.println(t2 - t1);
486
                } catch (DriverIOException e) {
487
                        throw new DriverException(e);
488
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
489
                        throw new DriverException(e);
490
                } catch (DriverException e) {
491
                        throw new DriverException(e);
492
                } catch (IOException e) {
493
                        throw new DriverException(e);
494
                }
495

    
496
        }
497

    
498
        public FBitSet queryByShape(IGeometry g, int relationship)
499
                        throws DriverException, VisitException {
500
                return queryByShape(g, relationship, null);
501
        }
502

    
503
        /*
504
         * (non-Javadoc)
505
         *
506
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry,
507
         *      int)
508
         */
509
        public FBitSet queryByShape(IGeometry g, int relationship,
510
                        CancellableMonitorable cancel) throws DriverException,
511
                        VisitException {
512
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
513
                FLyrVect lyr = (FLyrVect) capa;
514
                // if (lyr.getSpatialIndex() == null) AZABALA
515
                if (lyr.getISpatialIndex() == null)
516
                        return super.queryByShape(g, relationship, null);
517

    
518
                long t1 = System.currentTimeMillis();
519
                ReadableVectorial va = lyr.getSource();
520
                ICoordTrans ct = lyr.getCoordTrans();
521
                Rectangle2D bounds = g.getBounds2D();
522
                List lstRecs = lyr.getISpatialIndex().query(bounds);
523
                Integer idRec;
524
                FBitSet bitset = new FBitSet();
525
                Geometry jtsShape = g.toJTSGeometry();
526
                IntersectionMatrix m;
527
                int index;
528
                try {
529
                        va.start();
530

    
531
                        for (int i = 0; i < lstRecs.size(); i++) {
532
                                if (cancel != null) {
533
                                        cancel.reportStep();
534
                                        if (cancel.isCanceled()) {
535
                                                break;
536
                                        }
537
                                }
538
                                idRec = (Integer) lstRecs.get(i);
539
                                index = idRec.intValue();
540
                                IGeometry geom = va.getShape(index);
541
                                if (geom == null)
542
                                        continue;
543
                                if (ct != null) {
544
                                        geom.reProject(ct);
545
                                }
546
                                Geometry jtsGeom = geom.toJTSGeometry();
547
                                switch (relationship) {
548
                                case CONTAINS:
549
                                        m = jtsShape.relate(jtsGeom);
550
                                        if (m.isContains()) {
551
                                                bitset.set(index, true);
552
                                        }
553
                                        break;
554

    
555
                                case CROSSES:
556
                                        m = jtsShape.relate(jtsGeom);
557
                                        if (m.isCrosses(jtsGeom.getDimension(), jtsShape
558
                                                        .getDimension())) {
559
                                                bitset.set(index, true);
560
                                        }
561
                                        break;
562

    
563
                                case DISJOINT:
564
                                        // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
565
                                        m = jtsShape.relate(jtsGeom);
566
                                        if (m.isDisjoint()) {
567
                                                bitset.set(index, true);
568
                                        }
569
                                        break;
570

    
571
                                case EQUALS:
572
                                        m = jtsShape.relate(jtsGeom);
573
                                        if (m.isEquals(jtsGeom.getDimension(), jtsShape
574
                                                        .getDimension())) {
575
                                                bitset.set(index, true);
576
                                        }
577
                                        break;
578

    
579
                                case INTERSECTS:
580
                                        m = jtsShape.relate(jtsGeom);
581
                                        if (m.isIntersects()) {
582
                                                bitset.set(index, true);
583
                                        }
584
                                        break;
585

    
586
                                case OVERLAPS:
587
                                        m = jtsShape.relate(jtsGeom);
588
                                        if (m.isOverlaps(jtsGeom.getDimension(), jtsShape
589
                                                        .getDimension())) {
590
                                                bitset.set(index, true);
591
                                        }
592

    
593
                                        break;
594

    
595
                                case TOUCHES:
596
                                        m = jtsShape.relate(jtsGeom);
597
                                        if (m.isTouches(jtsGeom.getDimension(), jtsShape
598
                                                        .getDimension())) {
599
                                                bitset.set(index, true);
600
                                        }
601

    
602
                                        break;
603

    
604
                                case WITHIN:
605
                                        m = jtsShape.relate(jtsGeom);
606
                                        if (m.isWithin()) {
607
                                                bitset.set(index, true);
608
                                        }
609

    
610
                                        break;
611
                                }
612
                        }
613
                        va.stop();
614
                } catch (DriverIOException e) {
615
                        // TODO Auto-generated catch block
616
                        e.printStackTrace();
617
                }
618
                long t2 = System.currentTimeMillis();
619
                // logger.info("queryByShape optimizado sobre la capa " + lyr.getName()
620
                // + ". " + (t2 - t1) + " mseg.");
621
                return bitset;
622
        }
623

    
624
        public FBitSet queryByRect(Rectangle2D rect, CancellableMonitorable cancel)
625
                        throws DriverException {
626
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
627
                FLyrVect lyr = (FLyrVect) capa;
628
                if (lyr.getISpatialIndex() == null)
629
                        return super.queryByRect(rect, cancel);
630

    
631
                ReadableVectorial va = lyr.getSource();
632
                ICoordTrans ct = lyr.getCoordTrans();
633
                Rectangle2D bounds = rect;
634
                List lstRecs = lyr.getISpatialIndex().query(bounds);
635
                Integer idRec;
636
                FBitSet bitset = new FBitSet();
637
                int index;
638
                try {
639
                        va.start();
640
                        DriverAttributes attr = va.getDriverAttributes();
641
                        boolean bMustClone = false;
642
                        if (attr != null) {
643
                                if (attr.isLoadedInMemory()) {
644
                                        bMustClone = attr.isLoadedInMemory();
645
                                }
646
                        }
647

    
648
                        for (int i = 0; i < lstRecs.size(); i++) {
649
                                if (cancel != null) {
650
                                        cancel.reportStep();
651
                                        if (cancel.isCanceled()) {
652
                                                va.stop();
653
                                                return bitset;
654
                                        }
655
                                }
656
                                idRec = (Integer) lstRecs.get(i);
657
                                index = idRec.intValue();
658
                                IGeometry geom = va.getShape(index);
659
                                if (geom == null)// azabala
660
                                        continue;
661
                                if (ct != null) {
662
                                        if (bMustClone)
663
                                                geom = geom.cloneGeometry();
664
                                        geom.reProject(ct);
665
                                }
666
                                if (geom.intersects(rect))
667
                                        bitset.set(index, true);
668
                        }
669
                        va.stop();
670
                } catch (DriverIOException e) {
671
                        // TODO Auto-generated catch block
672
                        e.printStackTrace();
673
                }
674
                return bitset;
675

    
676
        }
677

    
678
        public void process(FeatureVisitor visitor, Rectangle2D rectangle)
679
                        throws DriverException, VisitException {
680
                process(visitor, rectangle, null);
681
        }
682

    
683
        /**
684
         * Processes (by calling visitor.process() method) only those features of
685
         * the vectorial layer associated which intersects given rectangle2d.
686
         *
687
         */
688

    
689
        public void process(FeatureVisitor visitor, Rectangle2D rectangle,
690
                        CancellableMonitorable cancel) throws DriverException,
691
                        VisitException {
692
                if (visitor.start(capa)) {
693
                        FLyrVect lyr = (FLyrVect) capa;
694
                        // if we dont have spatial index or...
695
                        if (lyr.getISpatialIndex() == null) {
696
                                super.process(visitor, rectangle, cancel);
697
                                return;
698
                        }
699
                        // if spatial index is not worthy
700
                        if (!isSpatialIndexNecessary(rectangle)) {
701
                                super.process(visitor, rectangle, cancel);
702
                                return;
703
                        }
704

    
705
                        ReadableVectorial va = lyr.getSource();
706
                        ICoordTrans ct = lyr.getCoordTrans();
707
                        Rectangle2D bounds = rectangle;
708
                        List lstRecs = lyr.getISpatialIndex().query(bounds);
709
                        Integer idRec;
710
                        int index;
711
                        try {
712
                                va.start();
713
                                DriverAttributes attr = va.getDriverAttributes();
714
                                boolean bMustClone = false;
715
                                if (attr != null) {
716
                                        if (attr.isLoadedInMemory()) {
717
                                                bMustClone = attr.isLoadedInMemory();
718
                                        }
719
                                }
720

    
721
                                for (int i = 0; i < lstRecs.size(); i++) {
722
                                        if (cancel != null) {
723
                                                cancel.reportStep();
724
                                        }
725
                                        if (verifyCancelation(cancel, va, visitor))
726
                                                return;
727
                                        idRec = (Integer) lstRecs.get(i);
728
                                        index = idRec.intValue();
729
                                        IGeometry geom = va.getShape(index);
730
                                        if (geom == null)// azabala
731
                                                continue;
732
                                        if (ct != null) {
733
                                                if (bMustClone)
734
                                                        geom = geom.cloneGeometry();
735
                                                geom.reProject(ct);
736
                                        }
737
                                        if (geom.intersects(rectangle))
738
                                                visitor.visit(geom, index);
739
                                }// for
740
                                va.stop();
741
                        } catch (DriverIOException e) {
742
                                // TODO Auto-generated catch block
743
                                e.printStackTrace();
744
                        }
745
                }// if visitor.start
746
        }
747

    
748
        /*
749
         * (non-Javadoc)
750
         *
751
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D,
752
         *      double)
753
         */
754
        public FBitSet queryByPoint(Point2D p, double tolerance,
755
                        CancellableMonitorable cancel) throws DriverException {
756
                // TODO: OJO!!!!. Est? implementado como un rectangulo.
757
                // Lo correcto deber?a ser calculando las distancias reales
758
                // es decir, con un c?rculo.
759
                Rectangle2D recPoint = new Rectangle2D.Double(p.getX()
760
                                - (tolerance / 2), p.getY() - (tolerance / 2), tolerance,
761
                                tolerance);
762
                return queryByRect(recPoint, cancel);
763
        }
764
}