Revision 106

View differences:

tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
  <modelVersion>4.0.0</modelVersion>
6
  <artifactId>org.gvsig.dwg.lib</artifactId>
7
  <packaging>jar</packaging>
8
  <name>${project.artifactId}</name>
9
  <description>
10
Library for read-only access DWG files
11

  
12
Supported versions:
13
- v12
14
- v14
15
- v15
16
- v2004
17

  
18
  </description>
19
  <parent>
20
      <groupId>org.gvsig</groupId>
21
      <artifactId>org.gvsig.dwg</artifactId>
22
      <version>2.0.32</version>
23
  </parent>
24

  
25
  <dependencies>
26
    <dependency>
27
      <groupId>org.gvsig</groupId>
28
      <artifactId>org.gvsig.tools.lib</artifactId>
29
      <scope>compile</scope>
30
    </dependency>
31
    <dependency>
32
      <groupId>org.gvsig</groupId>
33
      <artifactId>org.gvsig.projection.api</artifactId>
34
      <scope>compile</scope>
35
    </dependency>
36
    
37
    <dependency>
38
        <groupId>org.gvsig</groupId>
39
        <artifactId>org.gvsig.fmap.geometry.api</artifactId>
40
        <scope>compile</scope>
41
    </dependency>
42
    
43
  </dependencies>
44

  
45
</project>
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/DwgHeader.java
1
/* jdwglib. Java Library for reading Dwg files.
2
 * 
3
 * Author: Jose Morell Rama (jose.morell@gmail.com).
4
 * Port from the Pythoncad Dwg library by Art Haas.
5
 *
6
 * Copyright (C) 2005 Jose Morell, IVER TI S.A. and Generalitat Valenciana
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 * Jose Morell (jose.morell@gmail.com)
25
 * 
26
 * or
27
 *
28
 * IVER TI S.A.
29
 *  C/Salamanca, 50
30
 *  46005 Valencia
31
 *  Spain
32
 *  +34 963163400
33
 *  dac@iver.es
34
 */
35
package org.gvsig.dwg.lib;
36

  
37
/**
38
 * The DwgHeader class implements the Header of a DWG file
39
 * 
40
 * @author jmorell
41
 */
42
public class DwgHeader {
43
}
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/Point3D.java
1
/*
2
 *
3
 * Este codigo se distribuye bajo licencia GPL
4
 * de GNU. Para obtener una c?pia integra de esta
5
 * licencia acude a www.gnu.org.
6
 * 
7
 * Este software se distribuye "como es". AGIL
8
 * solo  pretende desarrollar herramientas para
9
 * la promoci?n del GIS Libre.
10
 * AGIL no se responsabiliza de las perdidas econ?micas o de 
11
 * informaci?n derivadas del uso de este software.
12
 */
13

  
14

  
15
package org.gvsig.dwg.lib.util;
16

  
17
/**
18
 *  3dim double point. A point is transformed different than a vector.
19
 *  The class is now declared final to allow a more aggresive optimization.
20
 *
21
 *  @see       dxfviewer.math.Vector3D;
22
 *
23
 *  @version   1.10,?01/13/99
24
 */
25
public final class Point3D {
26
  public double   x, y, z;     // coordinates, allowing direct access
27

  
28
  /**
29
   *
30
   */
31
  public Point3D() {
32
  }
33

  
34
  /**
35
   *  Copy constructor.
36
   *  @param  p    point to copy
37
   */
38
  public Point3D(Point3D p) {
39
	x = p.x;
40
	y = p.y;
41
	z = p.z;
42
  }
43

  
44
  /**
45
   *  @param   xx    x coord
46
   *  @param   yy    y coord
47
   *  @param   zz    z coord
48
   */
49
  public Point3D(double xx, double yy, double zz) {
50
	x = xx;
51
	y = yy;
52
	z = zz;
53
  }
54

  
55
  /**
56
   *  Scale.
57
   *  @param   f     scaling factor
58
   */
59
  public void scale(double f) {
60
	if (f != 1f) {
61
	  x *= f;
62
	  y *= f;
63
	  z *= f;
64
	}
65
  }
66

  
67
  /**
68
   *  Add a vector.
69
   *  @param  v      vector to add
70
   */
71
  public void add(Vector3D v) {
72
	x += v.x;
73
	y += v.y;
74
	z += v.z;
75
  }
76

  
77
  /**
78
   *  Get sum with vector.
79
   *  @param  v     vector to add
80
   *  @return this+v
81
   */
82
  public Point3D plus(Vector3D v) {
83
	Point3D ret = new Point3D(this);
84
	ret.add(v);
85
	return ret;
86
  }
87

  
88
  /**
89
   *  Substract a vector.
90
   *  @param  v     vector to substract
91
   */
92
  public void sub(Vector3D v) {
93
	x -= v.x;
94
	y -= v.y;
95
	z -= v.z;
96
  }
97

  
98
  /**
99
   *  Get difference with vector.
100
   *  @param  v     vector to substract
101
   *  @return this-v
102
   */
103
  public Point3D minus(Vector3D v) {
104
	Point3D ret = new Point3D(this);
105
	ret.sub(v);
106
	return ret;
107
  }
108

  
109
  /**
110
   *  Get difference with point.
111
   *  @param  p     point to substract
112
   *  @return this-p
113
   */
114
  public Vector3D minus(Point3D p) {
115
	Vector3D ret = new Vector3D(this);
116
	ret.sub(new Vector3D(p));
117
	return ret;
118
  }
119

  
120
  /**
121
   *  Output.
122
   *  @return  output string
123
   */
124
  public String toString() {
125
	return new String(new StringBuffer().append("[").append(x).append(",").append(y).append(",").append(z).append("]"));
126
  }
127
}
128

  
129

  
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/FMapUtil.java
1
/*
2
 * Created on 18-ene-2007 by azabala
3
 *
4
 */
5
package org.gvsig.dwg.lib.util;
6

  
7
import java.awt.geom.Point2D;
8
import java.util.Iterator;
9
import java.util.List;
10

  
11
import org.gvsig.dwg.lib.IDwgVertex;
12
import org.gvsig.fmap.geom.Geometry;
13
import org.gvsig.fmap.geom.GeometryLocator;
14
import org.gvsig.fmap.geom.GeometryManager;
15
import org.gvsig.fmap.geom.aggregate.MultiCurve;
16
import org.gvsig.fmap.geom.aggregate.MultiLine;
17
import org.gvsig.fmap.geom.exception.CreateGeometryException;
18
import org.gvsig.fmap.geom.primitive.Line;
19
import org.gvsig.fmap.geom.primitive.Point;
20
import org.gvsig.fmap.geom.primitive.Polygon;
21
import org.gvsig.fmap.geom.primitive.Surface;
22

  
23
/**
24
 * @author alzabord
25
 *
26
 */
27
public class FMapUtil {
28

  
29
    private static final GeometryManager gManager = GeometryLocator
30
            .getGeometryManager();
31

  
32
    public static Line ptsToLine(List<double[]> pts, int subType)
33
            throws CreateGeometryException {
34

  
35
        if (pts.size() < 2) {
36
            throw new IllegalArgumentException();
37
        }
38
        try {
39
            boolean is3D = subType == Geometry.SUBTYPES.GEOM3D || subType == Geometry.SUBTYPES.GEOM3DM;
40
            Line line = gManager.createLine(subType);
41
            for (double[] p : pts) {
42
                if( is3D ) {
43
                    if( p.length<3 ) {
44
                        line.addVertex(p[0],p[1],0);            
45
                    } else {
46
                        line.addVertex(p[0],p[1],p[2]);            
47
                    }
48
                } else {
49
                    line.addVertex(p[0],p[1]);            
50
                }
51
            }
52
            return line;
53
        } catch(RuntimeException ex) {
54
            throw ex;
55
        }
56
    }
57

  
58
    public static Surface ptsToPolygon(List<double[]> pts, int subType)
59
            throws CreateGeometryException {
60

  
61
        if (pts.size() < 3) {
62
            throw new IllegalArgumentException();
63
        }
64

  
65
        boolean is3D = subType == Geometry.SUBTYPES.GEOM3D || subType == Geometry.SUBTYPES.GEOM3DM;
66
        Polygon polygon = gManager.createPolygon(subType);
67
        for (double[] p : pts) {
68
            if( is3D ) {
69
                polygon.addVertex(p[0],p[1],p[2]);            
70
            } else {
71
                polygon.addVertex(p[0],p[1]);            
72
            }
73
        }
74
        return polygon;
75
    }
76

  
77
    public static Point createPoint(int subType, double[] point) throws CreateGeometryException {
78
        Point result = gManager.createPoint(point[0], point[1], subType);
79
        if (subType == Geometry.SUBTYPES.GEOM3D) {
80
            result.setCoordinateAt(Geometry.DIMENSIONS.Z, point[2]);
81
        }
82
        return result;
83
    }
84

  
85
    public static Point createPoint(int subType, Point2D point) throws CreateGeometryException {
86
        Point result = gManager.createPoint(point.getX(), point.getY(), subType);
87
        return result;
88
    }
89

  
90
    public static Point createPoint(int subType, IDwgVertex dwgvertex) throws CreateGeometryException {
91
        double[] point = dwgvertex.getPoint();
92
        Point result = gManager.createPoint(point[0], point[1], subType);
93
        if (subType == Geometry.SUBTYPES.GEOM3D) {
94
            result.setCoordinateAt(Geometry.DIMENSIONS.Z, point[2]);
95
        }
96
        return result;
97
    }
98

  
99
    /**
100
     * Devuelve la distancia desde angle1 a angle2. Angulo en radianes de
101
     * diferencia entre angle1 y angle2 en sentido antihorario
102
     *
103
     * @param angle1 angulo en radianes. Debe ser positivo y no dar ninguna
104
     * vuelta a la circunferencia
105
     * @param angle2 angulo en radianes. Debe ser positivo y no dar ninguna
106
     * vuelta a la circunferencia
107
     *
108
     * @return distancia entre los �ngulos
109
     */
110
    public static double angleDistance(double angle1, double angle2) {
111
        if (angle1 < angle2) {
112
            return angle2 - angle1;
113
        } else {
114
            return ((Math.PI * 2) - angle1) + angle2;
115
        }
116
    }
117
}
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/ArcFromBulgeCalculator.java
1
/* jdwglib. Java Library for reading Dwg files.
2
 * 
3
 * Author: Jose Morell Rama (jose.morell@gmail.com).
4
 * Port from the Pythoncad Dwg library by Art Haas.
5
 *
6
 * Copyright (C) 2005 Jose Morell, IVER TI S.A. and Generalitat Valenciana
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 * Jose Morell (jose.morell@gmail.com)
25
 * 
26
 * or
27
 *
28
 * IVER TI S.A.
29
 *  C/Salamanca, 50
30
 *  46005 Valencia
31
 *  Spain
32
 *  +34 963163400
33
 *  dac@iver.es
34
 */
35
package org.gvsig.dwg.lib.util;
36

  
37
import java.awt.geom.Point2D;
38
import java.util.Vector;
39

  
40
/**
41
 * This class calculates an arc given by a start and end points and a bulge
42
 * 
43
 * @author jmorell
44
 */
45
public class ArcFromBulgeCalculator {
46
	private double[] coord1, coord2;
47
	private double[] center;
48
	private double radio, empieza, acaba;
49
	private double bulge;
50
	private double d, dd, aci;
51
	private double[] coordAux;
52
	
53
	/**
54
	 * This method calculates an arc given by a start and end points and a bulge
55
	 * 
56
	 * @param p1 Start point of the arc given by a Point2D
57
	 * @param p2 End point of the arc given by a Point2D
58
	 * @param bulge Bulge of the arc given by a double value 
59
	 */
60
	public ArcFromBulgeCalculator(double[] p1, double[] p2, double bulge) {
61
		this.bulge = bulge;
62
		if (bulge < 0.0) {
63
			coord1 = p2;
64
			coord2 = p1;
65
		} else {
66
			coord1 = p1;
67
			coord2 = p2;
68
		}
69
		calParams();
70
	}
71
	
72
	private void calParams() {
73
		d = Math.sqrt((coord2[0]-coord1[0])*(coord2[0]-coord1[0]) + 
74
				(coord2[1]-coord1[1])*(coord2[1]-coord1[1]));
75
		coordAux = new double[]{(coord1[0]+coord2[0])/2.0, (coord1[1]+coord2[1])/2.0};
76
		double b = Math.abs(bulge);
77
		double beta = Math.atan(b);
78
		double alfa = beta*4.0;
79
		double landa = alfa/2.0;
80
		dd = (d/2.0)/(Math.tan(landa));
81
		radio = (d/2.0)/(Math.sin(landa));		
82
		aci = Math.atan((coord2[0]-coord1[0])/(coord2[1]-coord1[1]));
83
		double aciDegree = aci*180.0/Math.PI;
84
		if (coord2[1] > coord1[1]) {
85
			aci += Math.PI;
86
			aciDegree = aci*180.0/Math.PI;
87
		}
88
		center = new double[]{coordAux[0] + dd*Math.sin(aci+(Math.PI/2.0)), coordAux[1] + dd*Math.cos(aci+(Math.PI/2.0))};
89
		calEA(alfa);
90
	}
91
	
92
	private void calEA(double alfa){
93
		empieza = Math.atan2(coord1[1]-center[1], coord1[0]-center[0]);
94
		acaba = (empieza + alfa);
95
		empieza = empieza*180.0/Math.PI;
96
		acaba = acaba*180.0/Math.PI;
97
	}
98
	
99
	/**
100
	 * This method calculates an arc in a Gis geometry model. This arc is represented in
101
	 * this model by a Vector of Point2D. The distance between points in the arc is given
102
	 * as an argument
103
	 * 
104
	 * @param inc Distance between points in the arc
105
	 * @return Vector Vector with the set of Point2D that represents the arc
106
	 */
107
	public Vector getPoints(double inc) {
108
		Vector arc = new Vector();
109
		double angulo;
110
		int iempieza = (int) empieza + 1;
111
		int iacaba = (int) acaba;
112
		if (empieza <= acaba) {
113
			addNode(arc, empieza);
114
			for (angulo = iempieza; angulo <= iacaba; angulo += inc) {
115
				addNode(arc, angulo);
116
			}
117
			addNode(arc, acaba);
118
		} else {
119
			addNode(arc, empieza);
120
			for (angulo = iempieza ; angulo <= 360; angulo += inc) {
121
				addNode(arc, angulo);
122
			}
123
			for (angulo = 1; angulo <= iacaba; angulo += inc) {
124
				addNode(arc, angulo);
125
			}
126
			addNode(arc, angulo);
127
		}
128
		Point2D aux = (Point2D)arc.get(arc.size()-1);
129
		double aux1 = Math.abs(aux.getX()-coord2[0]);
130
		double aux2 = Math.abs(aux.getY()-coord2[1]);
131
		return arc;
132
	}
133
	
134
	/**
135
	 * Method that allows to obtain a set of points located in the central zone of 
136
	 * this arc object
137
	 */
138
	public Vector getCentralPoint() {
139
		Vector arc = new Vector();
140
		if (empieza <= acaba) {
141
			addNode(arc, (empieza+acaba)/2.0);
142
		} else {
143
			addNode(arc, empieza);
144
			double alfa = 360-empieza;
145
			double beta = acaba;
146
			double an = alfa + beta;
147
			double mid = an/2.0;
148
			if (mid<=alfa) {
149
				addNode(arc, empieza+mid);
150
			} else {
151
				addNode(arc, mid-alfa);
152
			}
153
		}
154
		return arc;
155
	}
156
	
157
	private void addNode(Vector arc, double angulo) {
158
		double yy = center[1] + radio * Math.sin(angulo*Math.PI/180.0);
159
		double xx = center[0] + radio * Math.cos(angulo*Math.PI/180.0);		
160
		arc.add(new Point2D.Double(xx,yy));
161
	}
162
}
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/GisModelCurveCalculator.java
1
/* jdwglib. Java Library for reading Dwg files.
2
 * 
3
 * Author: Jose Morell Rama (jose.morell@gmail.com).
4
 * Port from the Pythoncad Dwg library by Art Haas.
5
 *
6
 * Copyright (C) 2005 Jose Morell, IVER TI S.A. and Generalitat Valenciana
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 * Jose Morell (jose.morell@gmail.com)
25
 * 
26
 * or
27
 *
28
 * IVER TI S.A.
29
 *  C/Salamanca, 50
30
 *  46005 Valencia
31
 *  Spain
32
 *  +34 963163400
33
 *  dac@iver.es
34
 */
35
package org.gvsig.dwg.lib.util;
36

  
37
import java.awt.geom.Point2D;
38
import java.util.ArrayList;
39
import java.util.List;
40
import java.util.Vector;
41

  
42
/**
43
 * This class allows to obtain arcs and circles given by the most usual parameters, in a
44
 * Gis geometry model. In this model, an arc or a circle is given by a set of points that
45
 * defines it shape
46
 * 
47
 * @author jmorell
48
 */
49
public class GisModelCurveCalculator {
50
    
51
    /**
52
     * This method calculates an array of Point2D that represents a circle. The distance
53
     * between it points is 1 angular unit 
54
     * 
55
     * @param c Point2D that represents the center of the circle
56
     * @param r double value that represents the radius of the circle
57
     * @return Point2D[] An array of Point2D that represents the shape of the circle
58
     */
59
	public static List calculateGisModelCircle(Point2D c, double r) {
60
		List pts = new ArrayList();
61
		int angulo = 0;
62
		for (angulo=0; angulo<360; angulo++) {
63
			double[] pt = new double[]{c.getX(), c.getY()};
64
			pt[0] = pt[0] + r * Math.sin(angulo*Math.PI/(double)180.0);
65
			pt[1] = pt[1] + r * Math.cos(angulo*Math.PI/(double)180.0);
66
			
67
			pts.add(pt);
68
		}
69
		return pts;
70
	}
71
	
72
    /**
73
     * This method calculates an array of Point2D that represents a ellipse. The distance
74
     * between it points is 1 angular unit 
75
     * 
76
     * @param center Point2D that represents the center of the ellipse
77
     * @param majorAxisVector Point2D that represents the vector for the major axis
78
     * @param axisRatio double value that represents the axis ratio
79
	 * @param initAngle double value that represents the start angle of the ellipse arc
80
	 * @param endAngle double value that represents the end angle of the ellipse arc
81
     * @return Point2D[] An array of Point2D that represents the shape of the ellipse
82
     */
83
	public static List calculateGisModelEllipse(Point2D center, Point2D majorAxisVector, double axisRatio, double initAngle, double endAngle) {
84
		Point2D majorPoint = new Point2D.Double(center.getX()+majorAxisVector.getX(), center.getY()+majorAxisVector.getY());
85
		double orientation  = Math.atan(majorAxisVector.getY()/majorAxisVector.getX());
86
	    double semiMajorAxisLength = center.distance(majorPoint);
87
		double semiMinorAxisLength = semiMajorAxisLength*axisRatio;
88
	    double eccentricity = Math.sqrt(1-((Math.pow(semiMinorAxisLength, 2))/(Math.pow(semiMajorAxisLength, 2))));
89
		int isa = (int)initAngle;
90
		int iea = (int)endAngle;
91
		double angulo;
92
		List pts = new ArrayList();
93
		if (initAngle <= endAngle) {
94
			angulo = initAngle;
95
			double r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
96
		    double x = r*Math.cos(angulo*Math.PI/(double)180.0);
97
		    double y = r*Math.sin(angulo*Math.PI/(double)180.0);
98
		    double xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
99
		    double yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
100
			
101
			double[] pt = new double[]{center.getX() + xrot, center.getY() + yrot };
102
			pts.add(pt);
103
			
104
			for (int i=1; i<=(iea-isa)+1; i++) {
105
				angulo = (double)(isa+i);
106
				r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
107
			    x = r*Math.cos(angulo*Math.PI/(double)180.0);
108
			    y = r*Math.sin(angulo*Math.PI/(double)180.0);
109
			    xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
110
			    yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
111
			    
112
			    pt = new double[]{center.getX() + xrot, center.getY() + yrot};
113
			    pts.add(pt);
114
			}
115
			
116
			angulo = endAngle;
117
			r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
118
		    x = r*Math.cos(angulo*Math.PI/(double)180.0);
119
		    y = r*Math.sin(angulo*Math.PI/(double)180.0);
120
		    xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
121
		    yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
122
		    
123
		    
124
		    pt = new double[]{center.getX() + xrot, center.getY() + yrot};
125
		    pts.add(pt);
126
		    
127
		} else {
128
			angulo = initAngle;
129
			double r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
130
		    double x = r*Math.cos(angulo*Math.PI/(double)180.0);
131
		    double y = r*Math.sin(angulo*Math.PI/(double)180.0);
132
		    double xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
133
		    double yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
134
		    
135
		  
136
			double[] pt = new double[]{center.getX() + r*Math.cos(angulo*Math.PI/(double)180.0), center.getY() + r*Math.sin(angulo*Math.PI/(double)180.0)};
137
		    pts.add(pt);
138
		    
139
		    for (int i=1; i<=(360-isa); i++) {
140
				angulo = (double)(isa+i);
141
				r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
142
			    x = r*Math.cos(angulo*Math.PI/(double)180.0);
143
			    y = r*Math.sin(angulo*Math.PI/(double)180.0);
144
			    xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
145
			    yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
146
			    
147
			    pt = new double[]{center.getX() + xrot, center.getY() + yrot};
148
			    pts.add(pt);
149
			}
150
		    
151
		    
152
			for (int i=(360-isa)+1; i<=(360-isa)+iea; i++) {
153
				angulo = (double)(i-(360-isa));
154
				r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
155
			    x = r*Math.cos(angulo*Math.PI/(double)180.0);
156
			    y = r*Math.sin(angulo*Math.PI/(double)180.0);
157
			    xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
158
			    yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
159
			    
160
			    pt = new double[]{center.getX() + xrot, center.getY() + yrot};
161
			    pts.add(pt);
162
			    
163
			}
164
			
165
			angulo = endAngle;
166
			r = semiMinorAxisLength/Math.sqrt(1-((Math.pow(eccentricity, 2))*(Math.pow(Math.cos(angulo*Math.PI/(double)180.0), 2))));
167
		    x = r*Math.cos(angulo*Math.PI/(double)180.0);
168
		    y = r*Math.sin(angulo*Math.PI/(double)180.0);
169
		    xrot = x*Math.cos(orientation) - y*Math.sin(orientation);
170
		    yrot = x*Math.sin(orientation) + y*Math.cos(orientation);
171
		    
172
		    pt = new double[]{center.getX() + xrot, center.getY() + yrot};
173
		    pts.add(pt);
174
		}
175
		return pts;
176
	}
177
	
178
	/**
179
     * This method calculates an array of Point2D that represents an arc. The distance
180
     * between it points is 1 angular unit 
181
	 * 
182
     * @param c Point2D that represents the center of the arc
183
     * @param r double value that represents the radius of the arc
184
	 * @param sa double value that represents the start angle of the arc
185
	 * @param ea double value that represents the end angle of the arc
186
     * @return Point2D[] An array of Point2D that represents the shape of the arc
187
	 */
188
	public static List calculateGisModelArc(double[] center, double r, double sa, double ea) {
189
		int isa = (int)sa;
190
		int iea = (int)ea;
191
		double angulo;
192
		List pts = new ArrayList();
193
		if (sa <= ea) {
194
			angulo = sa;
195
			pts.add(new double[]{center[0] + r * Math.cos(angulo*Math.PI/(double)180.0), 
196
					center[1] + r * Math.sin(angulo*Math.PI/(double)180.0)});
197
			for (int i=1; i <= (iea-isa)+1; i++) {
198
				angulo = (double)(isa+i);
199
				double x = center[0] + r * Math.cos(angulo*Math.PI/(double)180.0);
200
				double y = center[1] + r * Math.sin(angulo*Math.PI/(double)180.0);
201
				pts.add(new double[]{x, y});
202
			}
203
			angulo = ea;
204
			double x = center[0] + r * Math.cos(angulo*Math.PI/(double)180.0);
205
			double y = center[1] + r * Math.sin(angulo*Math.PI/(double)180.0);
206
			pts.add(new double[]{x, y});
207
		} else {
208
			angulo = sa;
209
			double x = center[0] + r * Math.cos(angulo*Math.PI/(double)180.0);
210
			double y = center[1] + r * Math.sin(angulo*Math.PI/(double)180.0);
211
			pts.add(new double[]{x, y});
212
			for (int i=1; i <= (360-isa); i++) {
213
				angulo = (double)(isa+i);
214
				x = center[0] + r * Math.cos(angulo*Math.PI/(double)180.0);
215
				y = center[1] + r * Math.sin(angulo*Math.PI/(double)180.0); 
216
				pts.add(new double[]{x, y});
217
			}
218
			
219
			for (int i=( 360-isa)+1; i <= (360-isa)+iea; i++) {
220
				angulo = (double)(i-(360-isa));
221
				x = center[0] + r * Math.cos(angulo*Math.PI/(double)180.0);
222
				y = center[1] + r * Math.sin(angulo*Math.PI/(double)180.0);
223
				pts.add(new double[]{x, y});
224
			}
225
			angulo = ea;
226
			x = center[0] + r * Math.cos(angulo*Math.PI/(double)180.0);
227
			y = center[1] + r * Math.sin(angulo*Math.PI/(double)180.0);
228
			pts.add(new double[]{x, y});
229
		}
230
		return pts;
231
	}
232
	
233
	/**
234
	 * This method applies an array of bulges to an array of Point2D that defines a
235
	 * polyline. The result is a polyline with the input points with the addition of the
236
	 * points that define the new arcs added to the polyline
237
	 * 
238
	 * @param newPts Base points of the polyline
239
	 * @param bulges Array of bulge parameters
240
	 * @return Polyline with a new set of arcs added and defined by the bulge parameters
241
	 */
242
	public static List calculateGisModelBulge(List newPts, double[] bulges) {
243
		Vector ptspol = new Vector();
244
		double[] init = null;
245
		double[] end = null;
246
		for (int j=0; j<newPts.size(); j++) {
247
			init = (double[]) newPts.get(j);
248
			if (j != newPts.size()-1) 
249
				end = (double[]) newPts.get(j+1);
250
			if (bulges[j]==0 || j== newPts.size()-1 || 
251
				(init[0] == end[0] && init[1] == end[1])) {
252
				ptspol.add(init);
253
			} else {
254
				ArcFromBulgeCalculator arcCalculator = new ArcFromBulgeCalculator(init, end, bulges[j]);
255
				Vector arc = arcCalculator.getPoints(1);
256
				if (bulges[j]<0) {
257
					for (int k=arc.size()-1; k>=0; k--) {
258
						ptspol.add(arc.get(k));
259
					}
260
					ptspol.remove(ptspol.size()-1);
261
				} else {
262
					for (int k=0;k<arc.size();k++) {
263
						ptspol.add(arc.get(k));
264
					}
265
					ptspol.remove(ptspol.size()-1);
266
				}
267
			}
268
		}
269
		List points = new ArrayList();
270
		for (int j=0;j<ptspol.size();j++) {
271
			points.add(ptspol.get(j));
272
		}
273
		return points;
274
	}
275
}
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/HexUtil.java
1
package org.gvsig.dwg.lib.util;
2

  
3
import java.util.BitSet;
4

  
5
/**
6
 * Number in hexadecimal format are used throughout Freenet.
7
 * 
8
 * <p>Unless otherwise stated, the conventions follow the rules outlined in the 
9
 * Java Language Specification.</p>
10
 * 
11
 * @author syoung
12
 */
13
public class HexUtil {
14
	private HexUtil() {		
15
	}	
16
	
17

  
18
	/**
19
	 * Converts a byte array into a string of upper case hex chars.
20
	 * 
21
	 * @param bs
22
	 *            A byte array
23
	 * @param off
24
	 *            The index of the first byte to read
25
	 * @param length
26
	 *            The number of bytes to read.
27
	 * @return the string of hex chars.
28
	 */
29
	public static final String bytesToHex(byte[] bs, int off, int length) {
30
		StringBuffer sb = new StringBuffer(length * 2);
31
		bytesToHexAppend(bs, off, length, sb);
32
		return sb.toString();
33
	}
34

  
35
	public static final void bytesToHexAppend(
36
		byte[] bs,
37
		int off,
38
		int length,
39
		StringBuffer sb) {
40
		sb.ensureCapacity(sb.length() + length * 2);
41
		for (int i = off; i < (off + length) && i < bs.length; i++) {
42
			sb.append(Character.forDigit((bs[i] >>> 4) & 0xf, 16));
43
			sb.append(Character.forDigit(bs[i] & 0xf, 16));
44
		}
45
	}
46

  
47
	public static final String bytesToHex(byte[] bs) {
48
		return bytesToHex(bs, 0, bs.length);
49
	}
50

  
51
	public static final byte[] hexToBytes(String s) {
52
		return hexToBytes(s, 0);
53
	}
54

  
55
	public static final byte[] hexToBytes(String s, int off) {
56
		byte[] bs = new byte[off + (1 + s.length()) / 2];
57
		hexToBytes(s, bs, off);
58
		return bs;
59
	}
60

  
61
	/**
62
	 * Converts a String of hex characters into an array of bytes.
63
	 * 
64
	 * @param s
65
	 *            A string of hex characters (upper case or lower) of even
66
	 *            length.
67
	 * @param out
68
	 *            A byte array of length at least s.length()/2 + off
69
	 * @param off
70
	 *            The first byte to write of the array
71
	 */
72
	public static final void hexToBytes(String s, byte[] out, int off)
73
		throws NumberFormatException, IndexOutOfBoundsException {
74
		int slen = s.length();
75
		if ((slen % 2) != 0) {
76
			s = '0' + s;
77
		}
78

  
79
		if (out.length < off + slen / 2) {
80
			throw new IndexOutOfBoundsException(
81
				"Output buffer too small for input ("
82
					+ out.length
83
					+ "<"
84
					+ off
85
					+ slen / 2
86
					+ ")");
87
		}
88

  
89
		// Safe to assume the string is even length
90
		byte b1, b2;
91
		for (int i = 0; i < slen; i += 2) {
92
			b1 = (byte) Character.digit(s.charAt(i), 16);
93
			b2 = (byte) Character.digit(s.charAt(i + 1), 16);
94
			if (b1 < 0 || b2 < 0) {
95
				throw new NumberFormatException();
96
			}
97
			out[off + i / 2] = (byte) (b1 << 4 | b2);
98
		}
99
	}
100

  
101
	/**
102
	 * Pack the bits in ba into a byte[].
103
	 */
104
	public final static byte[] bitsToBytes(BitSet ba, int size) {
105
		int bytesAlloc = countBytesForBits(size);
106
		byte[] b = new byte[bytesAlloc];
107
		StringBuffer sb = new StringBuffer();
108
		for(int i=0;i<b.length;i++) {
109
			short s = 0;
110
			for(int j=0;j<8;j++) {
111
				int idx = i*8+j;
112
				boolean val = 
113
					idx > size ? false :
114
						ba.get(idx);
115
				s |= val ? (1<<j) : 0;
116
				sb.append(val ? '1' : '0');
117
			}
118
			if(s > 255) throw new IllegalStateException("WTF? s = "+s);
119
			b[i] = (byte)s;
120
		}
121
		return b;
122
	}
123

  
124
	/**
125
	 * Pack the bits in ba into a byte[] then convert that
126
	 * to a hex string and return it.
127
	 */
128
	public final static String bitsToHexString(BitSet ba, int size) {
129
		return bytesToHex(bitsToBytes(ba, size));
130
	}
131

  
132

  
133
	/**
134
	 * @return the number of bytes required to represent the
135
	 * bitset
136
	 */
137
	public static int countBytesForBits(int size) {
138
		// Brackets matter here! == takes precedence over the rest
139
		return (size/8) + ((size % 8) == 0 ? 0:1);
140
	}
141

  
142

  
143
	/**
144
	 * Read bits from a byte array into a bitset
145
	 * @param b the byte[] to read from
146
	 * @param ba the bitset to write to
147
	 */
148
	public static void bytesToBits(byte[] b, BitSet ba, int maxSize) {
149
		int x = 0;
150
		for(int i=0;i<b.length;i++) {
151
			for(int j=0;j<8;j++) {
152
				if(x > maxSize) break;
153
				int mask = 1 << j;
154
				boolean value = (mask & b[i]) != 0;
155
				ba.set(x, value);
156
				x++;
157
			}
158
		}
159
	}
160

  
161

  
162
	/**
163
	 * Read a hex string of bits and write it into a bitset
164
	 * @param s hex string of the stored bits
165
	 * @param ba the bitset to store the bits in
166
	 * @param length the maximum number of bits to store 
167
	 */
168
	public static void hexToBits(String s, BitSet ba, int length) {
169
		byte[] b = hexToBytes(s);
170
		bytesToBits(b, ba, length);
171
	}
172
}
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/AcadExtrusionCalculator.java
1
/* jdwglib. Java Library for reading Dwg files.
2
 * 
3
 * Author: Jose Morell Rama (jose.morell@gmail.com).
4
 * Port from the Pythoncad Dwg library by Art Haas.
5
 *
6
 * Copyright (C) 2005 Jose Morell, IVER TI S.A. and Generalitat Valenciana
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 * Jose Morell (jose.morell@gmail.com)
25
 * 
26
 * or
27
 *
28
 * IVER TI S.A.
29
 *  C/Salamanca, 50
30
 *  46005 Valencia
31
 *  Spain
32
 *  +34 963163400
33
 *  dac@iver.es
34
 */
35
package org.gvsig.dwg.lib.util;
36

  
37
import java.lang.Math;
38

  
39
/**
40
 * This class allows to apply the extrusion transformation of Autocad given by an array
41
 * of doubles to a point given by an array of doubles too. 
42
 * 
43
 * @author azabala
44
 */
45
/*
46
 * The maths behind all this stuff, and the reasons to do this could be complex.
47
 * 
48
 * Some links:
49
 * http://www.autodesk.com/techpubs/autocad/acadr14/dxf/object_coordinate_systems_40ocs41_al_u05_c.htm
50
 * http://www.autodesk.com/techpubs/autocad/acadr14/dxf/arbitrary_axis_algorithm_al_u05_c.htm 
51
 * http://personales.unican.es/togoresr/Sco-en.html
52
 * 
53
 * In ACAD, 3D entities has their coordinates in World Coordinate System (WCS: utm, etc.)
54
 * but 2D entities has their coordinates in an Object Coordinate System (OCS).
55
 * 
56
 * To work with the coordinates saved in the file, we must to transform them (extrude) from OCS
57
 * to WCS
58
 * 
59

  
60
 * */
61
public class AcadExtrusionCalculator {
62
    
63
	public static Matrix4D computeTransform(double[] extrusion, double[] coord)
64
    {
65
        
66
        Vector3D Ax = null;
67
        if(extrusion[0] == 0d && extrusion[1] == 0d && extrusion[2] > 0d && coord[2] == 0d)
68
        	return null;
69
        if((extrusion[0] >= 0f ? extrusion[0]:-extrusion[0]) < 0.015625F
70
        		&&
71
            (extrusion[1] >= 0f ? extrusion[1]:-extrusion[1]) < 0.015625F){
72
         
73
        	Ax = new Vector3D(extrusion[2], 0f, -extrusion[0]);
74
         }else{
75
        	 Ax = new Vector3D(-extrusion[1],extrusion[0], 0f);
76
         }
77
        double len = Ax.length();
78
        Ax.scale(1d / len);
79
        Vector3D upward = new Vector3D(extrusion[0], extrusion[1], extrusion[2]);
80
        Vector3D Ay = upward.cross(Ax);
81
  			
82
        Matrix4D aaa = new Matrix4D(Ax.x, Ay.x, upward.x, coord[2] * upward.x, 
83
  										Ax.y, Ay.y, upward.y, coord[2] * upward.y,
84
  										Ax.z, Ay.z, upward.z, coord[2] * upward.z, 
85
  											0.0F, 0.0F, 0.0F, 1.0F);
86
  	
87
        //Creo que la transformacion comentada es para pasar de WCS a OCS, y no al reves
88
        
89
        /*
90
        Matrix4D aaa = new Matrix4D(Ax.x, Ax.y, Ax.z, 0f, 
91
									Ay.x, Ay.y, Ay.z, 0f,
92
									upward.x, upward.y, upward.z, 0f,
93
									coord[2] * upward.x, coord[2] * upward.y, coord[2] * upward.z, 1f);
94
        
95
        */
96
        return aaa;
97
    }
98
	
99
	public static double[] extrude2(double[] coord_in, double[] xtru){
100
		
101
		//antes de cambiar el plano, aplicamos una extrusion con valor
102
		//la altura del punto
103
//		coord_in[0] += (xtru[0] * coord_in[2]);
104
//		coord_in[1] += (xtru[1] * coord_in[2]);
105
//		coord_in[2] += (xtru[2] * coord_in[2]);
106
		
107
		
108
		
109
		Matrix4D transform = computeTransform(xtru, coord_in);
110
		if(transform == null)//xtru es el eje Z
111
			return coord_in;
112
		Point3D p = new Point3D(coord_in[0], coord_in[1], coord_in[2]);
113
		transform.transform(p);
114
		return new double[]{p.x, p.y, p.z};
115
		
116
	}
117
	
118
	
119
	
120
	/*
121
    
122
   llamamos a finalConv, y este llama a extrude internamente
123
   
124
    static DrawAble finalConv(DrawAble dl, DxfEntity entity, boolean doTransform)
125
    {
126
        if(dl == null)
127
            return null;
128
        DrawAble dr;
129
        if(doTransform)
130
        {
131
            if(entity.getExtrusion() != 0.0F)
132
                dr = dl.extrude(entity.getExtrusion());
133
            else
134
                dr = dl;
135
            Matrix4D mat = entity.calcArbitMat();
136
            if(mat != null)
137
                dr.transformBy(mat);
138
        } else
139
        if(entity.getExtrusion() != 0.0F)
140
            dr = dl.extrude(entity.getExtrusion(), entity.getUpwardVector());
141
        else
142
            dr = dl;
143
        return dr;
144
    }
145
    
146
     public DrawAble extrude(float dist, Vector3D up)
147
    {
148
        if(dist == 0.0F)
149
            return this;
150
        Vector3D ex = new Vector3D(dist * up.x, dist * up.y, dist * up.z);
151
        DrawSet set = new DrawSet(2 + nrPoints);
152
        DrawLines second = new DrawLines(nrPoints);
153
        set.setLayer(super.layer);
154
        set.setColor(super.color);
155
        second.setLayer(super.layer);
156
        second.setColor(super.color);
157
        set.addDrawable(this);
158
        for(int i = 0; i < nrPoints; i++)
159
        {
160
            second.addPoint(line[i].x + ex.x, line[i].y + ex.y, line[i].z + ex.z);
161
            DrawLines conn = new DrawLines(2);
162
            conn.setLayer(super.layer);
163
            conn.setColor(super.color);
164
            conn.addPoint(line[i]);
165
            conn.addPoint(second.line[i]);
166
            set.addDrawable(conn);
167
        }
168

  
169
        if(isClosed)
170
            second.close();
171
        set.addDrawable(second);
172
        return set;
173
    }
174

  
175
    
176
    
177
*/
178
}
tags/org.gvsig.dwg-2.0.32/org.gvsig.dwg.lib/src/main/java/org/gvsig/dwg/lib/util/ByteUtils.java
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 org.gvsig.dwg.lib.util;
42
import java.math.BigInteger;
43

  
44

  
45
/**
46
 * Clase que engloba m?todos para trabajar con bytes. 
47
 *
48
 * @author Vicente Caballero Navarro
49
 */
50
public class ByteUtils {
51
	public static final int SIZE_BOOL = 1;
52
	public static final int SIZE_SHORT = 2;
53
	public static final int SIZE_INT = 4;
54
	public static final int SIZE_LONG = 8;
55
	public static final int SIZE_DOUBLE = 8;
56

  
57
	/** A nibble->char mapping for printing out bytes. */
58
	public static final char[] digits = {
59
			'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
60
			'e', 'f'
61
		};
62

  
63
	/**
64
	 * Return the <code>int</code> represented by the bytes in
65
	 * <code>data</code> staring at offset <code>offset[0]</code>.
66
	 *
67
	 * @param data the array from which to read
68
	 * @param offset A single element array whose first element is the index in
69
	 * 		  data from which to begin reading on function entry, and which on
70
	 * 		  function exit has been incremented by the number of bytes read.
71
	 *
72
	 * @return the value of the <code>int</code> decoded
73
	 */
74
	public static final int bytesToInt(byte[] data, int[] offset) {
75
		/**
76
		 * TODO: We use network-order within OceanStore, but temporarily
77
		 * supporting intel-order to work with some JNI code until JNI code is
78
		 * set to interoperate with network-order.
79
		 */
80
		int result = 0;
81

  
82
		for (int i = 0; i < SIZE_INT; ++i) {
83
			result <<= 8;
84
			result |= byteToUnsignedInt(data[offset[0]++]);
85
		}
86

  
87
		return result;
88
	}
89

  
90
	/**
91
	 * Write the bytes representing <code>i</code> into the byte array
92
	 * <code>data</code>, starting at index <code>offset [0]</code>, and
93
	 * increment <code>offset [0]</code> by the number of bytes written; if
94
	 * <code>data == null</code>, increment <code>offset [0]</code> by the
95
	 * number of bytes that would have been written otherwise.
96
	 *
97
	 * @param i the <code>int</code> to encode
98
	 * @param data The byte array to store into, or <code>null</code>.
99
	 * @param offset A single element array whose first element is the index in
100
	 * 		  data to begin writing at on function entry, and which on
101
	 * 		  function exit has been incremented by the number of bytes
102
	 * 		  written.
103
	 */
104
	public static final void intToBytes(int i, byte[] data, int[] offset) {
105
		/**
106
		 * TODO: We use network-order within OceanStore, but temporarily
107
		 * supporting intel-order to work with some JNI code until JNI code is
108
		 * set to interoperate with network-order.
109
		 */
110
		if (data != null) {
111
			for (int j = (offset[0] + SIZE_INT) - 1; j >= offset[0]; --j) {
112
				data[j] = (byte) i;
113
				i >>= 8;
114
			}
115
		}
116

  
117
		offset[0] += SIZE_INT;
118
	}
119

  
120
	/**
121
	 * Return the <code>short</code> represented by the bytes in
122
	 * <code>data</code> staring at offset <code>offset[0]</code>.
123
	 *
124
	 * @param data the array from which to read
125
	 * @param offset A single element array whose first element is the index in
126
	 * 		  data from which to begin reading on function entry, and which on
127
	 * 		  function exit has been incremented by the number of bytes read.
128
	 *
129
	 * @return the value of the <code>short</code> decoded
130
	 */
131
	public static final short bytesToShort(byte[] data, int[] offset) {
132
		/**
133
		 * TODO: We use network-order within OceanStore, but temporarily
134
		 * supporting intel-order to work with some JNI code until JNI code is
135
		 * set to interoperate with network-order.
136
		 */
137
		short result = 0;
138

  
139
		for (int i = 0; i < SIZE_SHORT; ++i) {
140
			result <<= 8;
141
			result |= (short) byteToUnsignedInt(data[offset[0]++]);
142
		}
143

  
144
		return result;
145
	}
146

  
147
	/**
148
	 * Write the bytes representing <code>s</code> into the byte array
149
	 * <code>data</code>, starting at index <code>offset [0]</code>, and
150
	 * increment <code>offset [0]</code> by the number of bytes written; if
151
	 * <code>data == null</code>, increment <code>offset [0]</code> by the
152
	 * number of bytes that would have been written otherwise.
153
	 *
154
	 * @param s the <code>short</code> to encode
155
	 * @param data The byte array to store into, or <code>null</code>.
156
	 * @param offset A single element array whose first element is the index in
157
	 * 		  data to begin writing at on function entry, and which on
158
	 * 		  function exit has been incremented by the number of bytes
159
	 * 		  written.
160
	 */
161
	public static final void shortToBytes(short s, byte[] data, int[] offset) {
162
		/**
163
		 * TODO: We use network-order within OceanStore, but temporarily
164
		 * supporting intel-order to work with some JNI code until JNI code is
165
		 * set to interoperate with network-order.
166
		 */
167
		if (data != null) {
168
			data[offset[0] + 1] = (byte) s;
169
			data[offset[0]] = (byte) (s >> 8);
170
		}
171

  
172
		offset[0] += SIZE_SHORT;
173
	}
174

  
175
	/**
176
	 * Return the <code>long</code> represented by the bytes in
177
	 * <code>data</code> staring at offset <code>offset[0]</code>.
178
	 *
179
	 * @param data the array from which to read
180
	 * @param offset A single element array whose first element is the index in
181
	 * 		  data from which to begin reading on  function entry, and which
182
	 * 		  on function exit has been incremented by the number of bytes
183
	 * 		  read.
184
	 *
185
	 * @return the value of the <code>long</code> decoded
186
	 */
187
	public static final long bytesToLong(byte[] data, int[] offset) {
188
		long result = 0;
189

  
190
		for (int i = 0; i < SIZE_LONG; ++i) {
191
			result <<= 8;
192

  
193
			int res = byteToUnsignedInt(data[offset[0]++]);
194
			result = result | res;
195
		}
196

  
197
		return result;
198
	}
199

  
200
	/**
201
	 * Write the bytes representing <code>l</code> into the byte array
202
	 * <code>data</code>, starting at index <code>offset [0]</code>, and
203
	 * increment <code>offset [0]</code> by the number of bytes written; if
204
	 * <code>data == null</code>, increment <code>offset [0]</code> by the
205
	 * number of bytes that would have been written otherwise.
206
	 *
207
	 * @param l the <code>long</code> to encode
208
	 * @param data The byte array to store into, or <code>null</code>.
209
	 * @param offset A single element array whose first element is the index in
210
	 * 		  data to begin writing at on function entry, and which on
211
	 * 		  function exit has been incremented by the number of bytes
212
	 * 		  written.
213
	 */
214
	public static final void longToBytes(long l, byte[] data, int[] offset) {
215
		/**
216
		 * TODO: We use network-order within OceanStore, but temporarily
217
		 * supporting intel-order to work with some JNI code until JNI code is
218
		 * set to interoperate with network-order.
219
		 */
220
		if (data != null) {
221
			for (int j = (offset[0] + SIZE_LONG) - 1; j >= offset[0]; --j) {
222
				data[j] = (byte) l;
223
				l >>= 8;
224
			}
225
		}
226

  
227
		offset[0] += SIZE_LONG;
228
	}
229

  
230
	/**
231
	 * Return the <code>double</code> represented by the bytes in
232
	 * <code>data</code> staring at offset <code>offset[0]</code>.
233
	 *
234
	 * @param data the array from which to read
235
	 * @param offset A single element array whose first element is the index in
236
	 * 		  data from which to begin reading on  function entry, and which
237
	 * 		  on function exit has been incremented by the number of bytes
238
	 * 		  read.
239
	 *
240
	 * @return the value of the <code>double</code> decoded
241
	 */
242
	public static final double bytesToDouble(byte[] data, int[] offset) {
243
		long bits = bytesToLong(data, offset);
244

  
245
		return Double.longBitsToDouble(bits);
246
	}
247

  
248
	/**
249
	 * Write the bytes representing <code>d</code> into the byte array
250
	 * <code>data</code>, starting at index <code>offset [0]</code>, and
251
	 * increment <code>offset [0]</code> by the number of bytes written; if
252
	 * <code>data == null</code>, increment <code>offset [0]</code> by the
253
	 * number of bytes that would have been written otherwise.
254
	 *
255
	 * @param d the <code>double</code> to encode
256
	 * @param data The byte array to store into, or <code>null</code>.
257
	 * @param offset A single element array whose first element is the index in
258
	 * 		  data to begin writing at on function entry, and which on
259
	 * 		  function exit has been incremented by the number of bytes
260
	 * 		  written.
261
	 */
262
	public static final void doubleToBytes(double d, byte[] data, int[] offset) {
263
		long bits = Double.doubleToLongBits(d);
264
		longToBytes(bits, data, offset);
265
	}
266

  
267
	/**
268
	 * Return the <code>String</code> represented by the bytes in
269
	 * <code>data</code> staring at offset <code>offset[0]</code>. This method
270
	 * relies on the user using the corresponding <code>stringToBytes</code>
271
	 * method to encode the <code>String</code>, so that it may properly
272
	 * retrieve the <code>String</code> length.
273
	 *
274
	 * @param data the array from which to read
275
	 * @param offset A single element array whose first element is the index in
276
	 * 		  data from which to begin reading on function entry, and which on
277
	 * 		  function exit has been incremented by the number of bytes read.
278
	 *
279
	 * @return the value of the <code>String</code> decoded
280
	 */
281
	public static final String bytesToString(byte[] data, int[] offset) {
282
		offset[0] = 0;
283

  
284
		int length = bytesToInt(data, offset);
285
		String st = null;
286

  
287
		if ((length < 0) || (length > data.length)) {
288
			st = new String(data);
289
		} else {
290
			st = new String(data, offset[0], length);
291
		}
292

  
293
		offset[0] += length;
294

  
295
		return st;
296
	}
297

  
298
	/**
299
	 * Write the bytes representing <code>s</code> into the byte array
300
	 * <code>data</code>, starting at index <code>offset [0]</code>, and
301
	 * increment <code>offset [0]</code> by the number of bytes written; if
302
	 * <code>data == null</code>, increment <code>offset [0]</code> by the
303
	 * number of bytes that would have been written otherwise.
304
	 *
305
	 * @param s the <code>String</code> to encode
306
	 * @param data The byte array to store into, or <code>null</code>.
307
	 * @param offset A single element array whose first element is the index in
308
	 * 		  data to begin writing at on function entry, and which on
309
	 * 		  function exit has been incremented by the number of bytes
310
	 * 		  written.
311
	 */
312
	public static final void stringToBytes(String s, byte[] data, int[] offset) {
313
		byte[] s_bytes = s.getBytes();
314

  
315
		if (data != null) {
316
			intToBytes(s_bytes.length, data, offset);
317
			memcpy(data, offset[0], s_bytes, 0, s_bytes.length);
318
		} else {
319
			offset[0] += SIZE_INT;
320
		}
321

  
322
		offset[0] += s_bytes.length;
323
	}
324

  
325
	/**
326
	 * Return the <code>boolean</code> represented by the bytes in
327
	 * <code>data</code> staring at offset <code>offset[0]</code>.
328
	 *
329
	 * @param data the array from which to read
330
	 * @param offset A single element array whose first element is the index in
331
	 * 		  data from which to begin reading on  function entry, and which
332
	 * 		  on function exit has been incremented by the number of bytes
333
	 * 		  read.
334
	 *
335
	 * @return the value of the <code>boolean</code> decoded
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff