Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libFMap / src / com / iver / cit / gvsig / fmap / operations / strategies / ShpStrategy.java @ 10665

History | View | Annotate | Download (22.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.util.BitSet;
48
import java.util.List;
49

    
50
import javax.print.attribute.PrintRequestAttributeSet;
51

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

    
56
import com.hardcode.driverManager.DriverLoadException;
57
import com.hardcode.gdbms.driver.exceptions.InitializeDriverException;
58
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
59
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
60
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
61
import com.iver.cit.gvsig.fmap.ViewPort;
62
import com.iver.cit.gvsig.fmap.core.FShape;
63
import com.iver.cit.gvsig.fmap.core.IGeometry;
64
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
65
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
66
import com.iver.cit.gvsig.fmap.drivers.DriverAttributes;
67
import com.iver.cit.gvsig.fmap.drivers.VectorialDriver;
68
import com.iver.cit.gvsig.fmap.layers.FBitSet;
69
import com.iver.cit.gvsig.fmap.layers.FLayer;
70
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
71
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
72
import com.iver.cit.gvsig.fmap.layers.SpatialCache;
73
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
74
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
75
import com.iver.cit.gvsig.fmap.layers.layerOperations.Selectable;
76
import com.iver.cit.gvsig.fmap.layers.layerOperations.SingleLayer;
77
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegendInfo;
78
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
79
import com.iver.utiles.swing.threads.Cancellable;
80
import com.iver.utiles.swing.threads.CancellableMonitorable;
81
import com.vividsolutions.jts.geom.Geometry;
82
import com.vividsolutions.jts.geom.IntersectionMatrix;
83

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

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

    
101
        /**
102
         * @see com.iver.cit.gvsig.fmap.operations.LayerOperations#draw(java.awt.image.BufferedImage,
103
         *      java.awt.Graphics2D, ISymbol)
104
         */
105
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
106
                        Cancellable cancel) throws ReadDriverException {
107
                try {
108
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
109
                        if (adapter.getShapeCount() <= 0) {
110
//                                logger.info("Layer:" + getCapa().getName() + " sin 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 geometrico en mismo BufferedImage
215
                        //provoca ralentizaci?n brutal. Lo evitamos separando los setRGB en otro BufferedImage y juntandolos luego.
216
                        boolean MAC_OS_X = System.getProperty("os.name").toLowerCase().startsWith("mac os x");
217
                        BufferedImage auxBI = null;
218
                        if (MAC_OS_X) {
219
                                auxBI = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
220
                        }
221

    
222

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

    
244
                                        if (bitSet.get(i)) {
245
                                                symbol = symbol.getSymbolForSelection();
246
                                        }
247

    
248
                                        if (symbol == null)
249
                                                continue;
250

    
251
                                        boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
252

    
253
                                        if (bPoint
254
                                                        || ((bounds.getHeight() > viewPort.getDist1pixel()) || (bounds
255
                                                                        .getWidth() > viewPort.getDist1pixel()))) {
256
                                                geom = adapter.getShape(i);
257

    
258
                                                // PRUEBA DE VELOCIDAD
259
                                                // geom = ShapeFactory.createPolygon2D(new
260
                                                // GeneralPathX(bounds));
261

    
262

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

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

    
293
                                        } else {
294
                                                Point2D.Double pOrig = new Point2D.Double(bounds
295
                                                                .getMinX(), bounds.getMinY());
296
                                                Point2D pDest, pDest2;
297

    
298
                                                pDest = viewPort.getAffineTransform().transform(pOrig,
299
                                                                null);
300
                                                pDest2 = g.getTransform().transform(pDest, null);
301

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

    
319
                        if (MAC_OS_X) {
320
                                g.drawImage(auxBI,0,0,null);
321
                        }
322

    
323
                        // logger.debug("getCapa().getRecordset().stop()");
324
                        ((FLyrVect) getCapa()).getSource().getRecordset().stop();
325

    
326
                        long t2 = System.currentTimeMillis();
327
                        // logger.debug("adapter.stop()");
328
                        adapter.stop();
329

    
330
                        // System.out.println(t2 - t1);
331
                } catch (ExpansionFileReadException e) {
332
                        throw new ReadDriverException(getCapa().getName(),e);
333
                } catch (InitializeDriverException e) {
334
                        throw new ReadDriverException(getCapa().getName(),e);
335
                }
336
        }
337

    
338
        /**
339
         * M?todo utilizado para dibujar sobre el graphics que se pasa como
340
         * par?metro, pensado para utilizarse para imprimir.
341
         *
342
         * @param g
343
         *            Graphics2D
344
         * @param viewPort
345
         *            ViewPort.
346
         * @param cancel
347
         */
348
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel, PrintRequestAttributeSet printProperties)
349
                        throws ReadDriverException {
350
                // super.draw(null, g, viewPort, cancel); // Quiero ejecutar el draw del
351
                // padre, que es el que va sin acelaraci?n!!
352
                try {
353
                        ReadableVectorial adapter = ((SingleLayer) getCapa()).getSource();
354
                        if (adapter.getShapeCount() <= 0) {
355
//                                logger.info("Layer:" + getCapa().getName() + " sin registros");
356
                                return;
357
                        }
358
                        FLyrVect lyr = (FLyrVect) getCapa();
359
                        lyr.beforePrinting(printProperties);
360

    
361
                        Selectable selectable = lyr.getRecordset();
362
                        ICoordTrans ct = getCapa().getCoordTrans();
363
                        BitSet bitSet = selectable.getSelection();
364
                        BoundedShapes shapeBounds = (BoundedShapes) adapter.getDriver();
365
                        VectorialDriver driver = (VectorialDriver) adapter
366
                                        .getDriver();
367
                        // logger.debug("adapter.start() -> Layer:" + getCapa().getName());
368
                        adapter.start();
369
                        IGeometry geom;
370
                        if (adapter.getShapeCount() > 0) {
371
                                geom = adapter.getShape(0);
372
                        }
373
                        VectorialLegend l = (VectorialLegend) ((ClassifiableVectorial) getCapa())
374
                                        .getLegend();
375

    
376
                        Rectangle2D extent = viewPort.getAdjustedExtent();
377
                        // AffineTransform at = viewPort.getAffineTransform();
378

    
379
                        int sc;
380

    
381
                        Rectangle2D bounds;
382

    
383
                        sc = adapter.getShapeCount();
384

    
385
                        //long t1 = System.currentTimeMillis();
386
                        // logger.debug("getCapa().getRecordset().start()");
387
                        ((AlphanumericData) getCapa()).getRecordset().start();
388

    
389
                        // TODO: A revisar si es o no conveniente este sistema
390
                        // de comunicaci?n con los drivers.
391
                        DriverAttributes attr = adapter.getDriverAttributes();
392
                        boolean bMustClone = false;
393
                        if (attr != null) {
394
                                if (attr.isLoadedInMemory()) {
395
                                        bMustClone = attr.isLoadedInMemory();
396
                                }
397
                        }
398

    
399
                        List lstIndexes = null;
400

    
401
                        boolean bUseSpatialIndex = false;
402
                        if (lyr.getISpatialIndex() != null) {
403
                                if (isSpatialIndexNecessary(extent)) {
404
                                        lstIndexes = lyr.getISpatialIndex().query(extent);
405
                                        if (ct != null) {
406
                                                Rectangle2D newExtent = ct.getInverted()
407
                                                                .convert(extent);
408
                                                lstIndexes = lyr.getISpatialIndex().query(newExtent);
409
                                        } else {
410
                                                lstIndexes = lyr.getISpatialIndex().query(extent);
411
                                        }
412
                                        sc = lstIndexes.size();
413
                                        bUseSpatialIndex = true;
414
                                }// if
415
                        }// if
416

    
417
                        int i;
418
                        for (int aux = 0; aux < sc; aux++) {
419
                                if (bUseSpatialIndex) {
420
                                        Integer idRec = (Integer) lstIndexes.get(aux);
421
                                        i = idRec.intValue();
422
                                } else {
423
                                        i = aux;
424
                                }
425

    
426
                                bounds = shapeBounds.getShapeBounds(i);
427

    
428
                                if (ct != null) {
429
                                        bounds = ct.convert(bounds);
430
                                }
431

    
432
                                if (XRectangle2D.intersectInclusive(extent, bounds)) {
433
                                        ISymbol symbol = l.getSymbol(i);
434
                                        if (symbol == null)
435
                                                continue;
436
                                        if (bitSet.get(i)) {
437
                                                symbol = symbol.getSymbolForSelection();
438
                                        }
439

    
440
                                        //boolean bPoint = (shapeBounds.getShapeType(i) == FShape.POINT);
441

    
442
                                        geom = driver.getShape(i);
443

    
444
                                        // PRUEBA DE VELOCIDAD
445
                                        // geom = ShapeFactory.createPolygon2D(new
446
                                        // GeneralPathX(bounds));
447

    
448
                                        // JMVIVO: Clonamos siempre que sea necesario y no
449
                                        // solo si hay que reproyectar. Porque el FGeometry.draw
450
                                        // va a aplicar la transformacion sobre la geometria original
451
                                                if (bMustClone)
452
                                                        geom = geom.cloneGeometry();
453

    
454
                                        if (ct != null) {
455
                                                geom.reProject(ct);
456
                                        }
457

    
458
                                        geom.draw(g, viewPort, symbol);
459

    
460
                                }
461
                        }
462

    
463
                        // logger.debug("getCapa().getRecordset().stop()");
464
                        ((AlphanumericData) getCapa()).getRecordset().stop();
465

    
466
                        //long t2 = System.currentTimeMillis();
467
                        // logger.debug("adapter.stop()");
468
                        adapter.stop();
469
                        lyr.afterPrinting();
470
                        // System.out.println(t2 - t1);
471
                } catch (ExpansionFileReadException e) {
472
                        throw new ReadDriverException(getCapa().getName(),e);
473
                } catch (InitializeDriverException e) {
474
                        throw new ReadDriverException(getCapa().getName(),e);
475
                }
476

    
477

    
478
        }
479

    
480
        public FBitSet queryByShape(IGeometry g, int relationship)
481
                        throws ReadDriverException, VisitorException {
482
                return queryByShape(g, relationship, null);
483
        }
484

    
485
        /*
486
         * (non-Javadoc)
487
         *
488
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByShape(com.iver.cit.gvsig.fmap.core.IGeometry,
489
         *      int)
490
         */
491
        public FBitSet queryByShape(IGeometry g, int relationship,
492
                        CancellableMonitorable cancel) throws ReadDriverException, VisitorException {
493
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
494
                FLyrVect lyr = (FLyrVect) capa;
495
                // if (lyr.getSpatialIndex() == null) AZABALA
496
                if (lyr.getISpatialIndex() == null)
497
                        return super.queryByShape(g, relationship, null);
498

    
499
                long t1 = System.currentTimeMillis();
500
                ReadableVectorial va = lyr.getSource();
501
                ICoordTrans ct = lyr.getCoordTrans();
502
                Rectangle2D bounds = g.getBounds2D();
503
                List lstRecs = lyr.getISpatialIndex().query(bounds);
504
                Integer idRec;
505
                FBitSet bitset = new FBitSet();
506
                Geometry jtsShape = g.toJTSGeometry();
507
                IntersectionMatrix m;
508
                int index;
509
                try {
510
                        va.start();
511

    
512
                        for (int i = 0; i < lstRecs.size(); i++) {
513
                                if (cancel != null) {
514
                                        cancel.reportStep();
515
                                        if (cancel.isCanceled()) {
516
                                                break;
517
                                        }
518
                                }
519
                                idRec = (Integer) lstRecs.get(i);
520
                                index = idRec.intValue();
521
                                IGeometry geom = va.getShape(index);
522
                                if(geom == null)
523
                                        continue;
524
                                if (ct != null) {
525
                                        geom.reProject(ct);
526
                                }
527
                                Geometry jtsGeom = geom.toJTSGeometry();
528
                                switch (relationship) {
529
                                case CONTAINS:
530
                                        m = jtsShape.relate(jtsGeom);
531
                                        if (m.isContains()) {
532
                                                bitset.set(index, true);
533
                                        }
534
                                        break;
535

    
536
                                case CROSSES:
537
                                        m = jtsShape.relate(jtsGeom);
538
                                        if (m.isCrosses(jtsGeom.getDimension(), jtsShape
539
                                                        .getDimension())) {
540
                                                bitset.set(index, true);
541
                                        }
542
                                        break;
543

    
544
                                case DISJOINT:
545
                                        // TODO: CREO QUE EL DISJOINT NO SE PUEDE METER AQUI
546
                                        m = jtsShape.relate(jtsGeom);
547
                                        if (m.isDisjoint()) {
548
                                                bitset.set(index, true);
549
                                        }
550
                                        break;
551

    
552
                                case EQUALS:
553
                                        m = jtsShape.relate(jtsGeom);
554
                                        if (m.isEquals(jtsGeom.getDimension(), jtsShape
555
                                                        .getDimension())) {
556
                                                bitset.set(index, true);
557
                                        }
558
                                        break;
559

    
560
                                case INTERSECTS:
561
                                        m = jtsShape.relate(jtsGeom);
562
                                        if (m.isIntersects()) {
563
                                                bitset.set(index, true);
564
                                        }
565
                                        break;
566

    
567
                                case OVERLAPS:
568
                                        m = jtsShape.relate(jtsGeom);
569
                                        if (m.isOverlaps(jtsGeom.getDimension(), jtsShape
570
                                                        .getDimension())) {
571
                                                bitset.set(index, true);
572
                                        }
573

    
574
                                        break;
575

    
576
                                case TOUCHES:
577
                                        m = jtsShape.relate(jtsGeom);
578
                                        if (m.isTouches(jtsGeom.getDimension(), jtsShape
579
                                                        .getDimension())) {
580
                                                bitset.set(index, true);
581
                                        }
582

    
583
                                        break;
584

    
585
                                case WITHIN:
586
                                        m = jtsShape.relate(jtsGeom);
587
                                        if (m.isWithin()) {
588
                                                bitset.set(index, true);
589
                                        }
590

    
591
                                        break;
592
                                }
593
                        }
594
                        va.stop();
595
                } catch (ExpansionFileReadException e) {
596
                        throw new ReadDriverException(getCapa().getName(),e);
597
                } catch (InitializeDriverException e) {
598
                        throw new ReadDriverException(getCapa().getName(),e);
599
                }
600
                long t2 = System.currentTimeMillis();
601
//                logger.info("queryByShape optimizado sobre la capa " + lyr.getName()
602
//                                + ". " + (t2 - t1) + " mseg.");
603
                return bitset;
604
        }
605

    
606
        public FBitSet queryByRect(Rectangle2D rect, CancellableMonitorable cancel)
607
                        throws ReadDriverException, VisitorException {
608
                // Si hay un ?ndice espacial, lo usamos para hacer el query.
609
                FLyrVect lyr = (FLyrVect) capa;
610
                if (lyr.getISpatialIndex() == null)
611
                        return super.queryByRect(rect, cancel);
612

    
613
                ReadableVectorial va = lyr.getSource();
614
                ICoordTrans ct = lyr.getCoordTrans();
615
                Rectangle2D bounds = rect;
616
                List lstRecs = lyr.getISpatialIndex().query(bounds);
617
                Integer idRec;
618
                FBitSet bitset = new FBitSet();
619
                int index;
620
                try {
621
                        va.start();
622
                        DriverAttributes attr = va.getDriverAttributes();
623
                        boolean bMustClone = false;
624
                        if (attr != null) {
625
                                if (attr.isLoadedInMemory()) {
626
                                        bMustClone = attr.isLoadedInMemory();
627
                                }
628
                        }
629

    
630
                        for (int i = 0; i < lstRecs.size(); i++) {
631
                                if (cancel != null) {
632
                                        cancel.reportStep();
633
                                        if (cancel.isCanceled()) {
634
                                                va.stop();
635
                                                return bitset;
636
                                        }
637
                                }
638
                                idRec = (Integer) lstRecs.get(i);
639
                                index = idRec.intValue();
640
                                IGeometry geom = va.getShape(index);
641
                                if(geom == null)//azabala
642
                                        continue;
643
                                if (ct != null) {
644
                                        if (bMustClone)
645
                                                geom = geom.cloneGeometry();
646
                                        geom.reProject(ct);
647
                                }
648
                                if (geom.intersects(rect))
649
                                        bitset.set(index, true);
650
                        }
651
                        va.stop();
652
                } catch (ExpansionFileReadException e) {
653
                        throw new ReadDriverException(getCapa().getName(),e);
654
                } catch (InitializeDriverException e) {
655
                        throw new ReadDriverException(getCapa().getName(),e);
656
                }
657
                return bitset;
658

    
659
        }
660

    
661
        public void process(FeatureVisitor visitor, Rectangle2D rectangle)
662
                        throws ReadDriverException, ExpansionFileReadException, VisitorException {
663
                process(visitor, rectangle, null);
664
        }
665

    
666
        /**
667
         * Processes (by calling visitor.process() method) only those features of
668
         * the vectorial layer associated which intersects given rectangle2d.
669
         * @throws ExpansionFileReadException
670
         *
671
         */
672

    
673
        public void process(FeatureVisitor visitor, Rectangle2D rectangle,
674
                        CancellableMonitorable cancel) throws ReadDriverException, ExpansionFileReadException, VisitorException {
675
                if (visitor.start(capa)) {
676
                        FLyrVect lyr = (FLyrVect) capa;
677
                        // if we dont have spatial index or...
678
                        if (lyr.getISpatialIndex() == null) {
679
                                super.process(visitor, rectangle, cancel);
680
                                return;
681
                        }
682
                        // if spatial index is not worthy
683
                                if (!isSpatialIndexNecessary(rectangle)) {
684
                                        super.process(visitor, rectangle, cancel);
685
                                        return;
686
                                }
687

    
688
                        ReadableVectorial va = lyr.getSource();
689
                        ICoordTrans ct = lyr.getCoordTrans();
690
                        Rectangle2D bounds = rectangle;
691
                        List lstRecs = lyr.getISpatialIndex().query(bounds);
692
                        Integer idRec;
693
                        int index;
694
                                try {
695
                                        va.start();
696
                                }catch (InitializeDriverException e) {
697
                                        throw new ReadDriverException(getCapa().getName(),e);
698
                                }
699
                                DriverAttributes attr = va.getDriverAttributes();
700
                                boolean bMustClone = false;
701
                                if (attr != null) {
702
                                        if (attr.isLoadedInMemory()) {
703
                                                bMustClone = attr.isLoadedInMemory();
704
                                        }
705
                                }
706

    
707
                                for (int i = 0; i < lstRecs.size(); i++) {
708
                                        if (cancel != null) {
709
                                                cancel.reportStep();
710
                                        }
711
                                        if (verifyCancelation(cancel, va, visitor))
712
                                                return;
713
                                        idRec = (Integer) lstRecs.get(i);
714
                                        index = idRec.intValue();
715
                                        IGeometry geom = va.getShape(index);
716
                                        if(geom == null)//azabala
717
                                                continue;
718
                                        if (ct != null) {
719
                                                if (bMustClone)
720
                                                        geom = geom.cloneGeometry();
721
                                                geom.reProject(ct);
722
                                        }
723
                                        if (geom.intersects(rectangle))
724
                                                visitor.visit(geom, index);
725
                                }// for
726
                                va.stop();
727

    
728
                }// if visitor.start
729
        }
730

    
731
        /*
732
         * (non-Javadoc)
733
         *
734
         * @see com.iver.cit.gvsig.fmap.operations.strategies.Strategy#queryByPoint(java.awt.geom.Point2D,
735
         *      double)
736
         */
737
        public FBitSet queryByPoint(Point2D p, double tolerance,
738
                        CancellableMonitorable cancel) throws ReadDriverException, VisitorException {
739
                // TODO: OJO!!!!. Est? implementado como un rectangulo.
740
                // Lo correcto deber?a ser calculando las distancias reales
741
                // es decir, con un c?rculo.
742
                Rectangle2D recPoint = new Rectangle2D.Double(p.getX()
743
                                - (tolerance / 2), p.getY() - (tolerance / 2), tolerance,
744
                                tolerance);
745
                return queryByRect(recPoint, cancel);
746
        }
747
}