List of usage examples for org.apache.commons.math3.geometry.euclidean.threed Vector3D normalize
public Vector3D normalize() throws MathArithmeticException
From source file:org.jtrfp.trcl.core.ResourceManager.java
public Model getBINModel(String name, TextureDescription defaultTexture, double scale, boolean cache, ColorPaletteVectorList palette, ColorPaletteVectorList ESTuTvPalette) throws FileLoadException, IOException, IllegalAccessException { if (name == null) throw new NullPointerException("Name is intolerably null"); if (palette == null) throw new NullPointerException("Palette is intolerably null"); if (modelCache.containsKey(name) && cache) return modelCache.get(name); //The models like to set up two line segments where there should be one. //This set is for identifying and culling redundant segs. final HashSet<Integer> alreadyVisitedLineSegs = new HashSet<Integer>(); boolean hasAlpha = false; try {//www .j a va2 s . c o m BINFile.AnimationControl ac = null; Model result = new Model(true, tr); ac = aniBinNameMap.get(name); if (ac == null) { InputStream is = getInputStreamFromResource("MODELS\\" + name); //TODO: InputStream not guaranteed to close when exception is thrown. Wrap in try{}, close it, and re-throw. ac = new BINFile.AnimationControl(is);//This will throw an exception on and escape to the static model block is.close(); aniBinNameMap.put(name, ac); } System.out.println("Recognized as animation control file."); //Build the Model from the BINFile.Model Model[] frames = new Model[ac.getNumFrames()]; for (int i = 0; i < frames.length; i++) { frames[i] = getBINModel(ac.getBinFiles().get(i), defaultTexture, scale, cache, palette, ESTuTvPalette); } result.setDebugName(name + " triangles: " + frames[0].getRawTriangleLists().get(0).size()); //Consolidate the frames to one model for (int i = 0; i < frames.length; i++) { result.addFrame(frames[i]); } result.setFrameDelayInMillis((int) (((double) ac.getDelay() / 65535.) * 1000.)); //result.finalizeModel(); if (cache) modelCache.put(name, result); return result; } //end try{} catch (UnrecognizedFormatException e) {//ok fail. Static model try { BINFile.Model m = null; Model result = new Model(false, tr); result.setDebugName(name); m = modBinNameMap.get(name); if (m == null) { InputStream is = getInputStreamFromResource("MODELS\\" + name); m = new BINFile.Model(is); modBinNameMap.put(name, m); } //end if(null) final double cpScalar = (scale * TR.crossPlatformScalar * 256.) / (double) m.getScale(); System.out.println("Recognized as model file."); List<org.jtrfp.trcl.gpu.Vertex> vertices = new ArrayList<org.jtrfp.trcl.gpu.Vertex>(); for (BINFile.Model.Vertex binVtx : m.getVertices()) { vertices.add(new org.jtrfp.trcl.gpu.Vertex().setPosition(new Vector3D(binVtx.getX() * cpScalar, binVtx.getY() * cpScalar, binVtx.getZ() * cpScalar))); } //end try{} TextureDescription currentTexture = null; final double[] u = new double[4]; final double[] v = new double[4]; for (ThirdPartyParseable b : m.getDataBlocks()) { //Sort out types of block if (b instanceof TextureBlock) { TextureBlock tb = (TextureBlock) b; if (hasAlpha) currentTexture = getRAWAsTexture(tb.getTextureFileName(), palette, ESTuTvPalette, hasAlpha); else { currentTexture = getRAWAsTexture(tb.getTextureFileName(), palette, ESTuTvPalette, false); } System.out.println( "ResourceManager: TextureBlock specifies texture: " + tb.getTextureFileName()); } //end if(TextureBlock) else if (b instanceof FaceBlock) { //System.out.println("FaceBlock found: "+b.getClass().getSimpleName()); FaceBlock block = (FaceBlock) b; List<FaceBlockVertex> vertIndices = block.getVertices(); if (currentTexture == null) { System.out.println("Warning: Face texture not specified. Using fallback texture."); currentTexture = defaultTexture; } /* * "The two vb_tex_coord values map the vertices of the face to the texture. * They are both in the range of 0x0 to 0xFF00, with u=0x0, v=0x0 being the upper * left corner of the texture, and u=0xFF00, v=0xFF00 being the lower right corner." * - http://www.viaregio.de/pieper/mtm/bin_file_format.shtml */ //// Note: It appears that Stefan's 0xFF0000 approach works rather than the 0xFF00 value. typo? if (vertIndices.size() == 4) {//Quads org.jtrfp.trcl.gpu.Vertex[] vtx = new org.jtrfp.trcl.gpu.Vertex[4]; for (int i = 0; i < 4; i++) { vtx[i] = vertices.get(vertIndices.get(i).getVertexIndex() % (b instanceof FaceBlock05 ? 10 : Integer.MAX_VALUE)); } Vector3D blockNormal = new Vector3D(block.getNormalX(), block.getNormalY(), block.getNormalZ()); if (blockNormal.getNorm() == 0) blockNormal = new Vector3D(1, 0, 0);//Use filler if zero norm. if (vertIndices.get(0) instanceof FaceBlockVertexWithUV) { for (int i = 0; i < 4; i++) { final FaceBlockVertexWithUV fbvi = (FaceBlockVertexWithUV) vertIndices.get(i); u[i] = (double) (fbvi).getTextureCoordinateU() / (double) 0xFF0000; v[i] = (double) (fbvi).getTextureCoordinateV() / (double) 0xFF0000; } //end for(4) } else { u[0] = BOX_U[0]; v[0] = BOX_V[0]; u[1] = BOX_U[1]; v[1] = BOX_V[1]; u[2] = BOX_U[2]; v[2] = BOX_V[2]; u[3] = BOX_U[3]; v[3] = BOX_V[3]; } Triangle[] tris = Triangle.quad2Triangles(vtx, new Vector2D[] { new Vector2D(u[0], 1. - v[0]), new Vector2D(u[1], 1. - v[1]), new Vector2D(u[2], 1. - v[2]), new Vector2D(u[3], 1. - v[3]) }, currentTexture, RenderMode.DYNAMIC, hasAlpha, blockNormal.normalize(), "quad.BINmodel" + name); result.addTriangle(tris[0]); result.addTriangle(tris[1]); } else if (vertIndices.size() == 3)//Triangles { Triangle t = new Triangle(currentTexture); try { t.setCentroidNormal( new Vector3D(block.getNormalX(), block.getNormalY(), block.getNormalZ()) .normalize()); } catch (MathArithmeticException ee) { t.setCentroidNormal(Vector3D.ZERO); } t.setAlphaBlended(hasAlpha); t.setRenderMode(RenderMode.DYNAMIC); for (int vi = 0; vi < 3; vi++) { final org.jtrfp.trcl.gpu.Vertex vtx = vertices .get(vertIndices.get(vi).getVertexIndex() - (b instanceof FaceBlock05 ? m.getUnknown2() : 0)); t.setVertex(vtx, vi); if (b instanceof FaceBlock05 || !(vertIndices.get(0) instanceof FaceBlockVertexWithUV)) t.setUV(new Vector2D(BOX_U[vi], BOX_V[vi]), vi); else { t.setUV(new Vector2D( (double) ((FaceBlockVertexWithUV) vertIndices.get(vi)) .getTextureCoordinateU() / (double) 0xFF0000, 1. - (double) ((FaceBlockVertexWithUV) vertIndices.get(vi)) .getTextureCoordinateV() / (double) 0xFF0000), vi); } } //end for(vi) if (currentTexture == null) { System.err.println("WARNING: Texture never set for " + name + ". Using fallback."); currentTexture = tr.gpu.get().textureManager.get().getFallbackTexture(); } result.addTriangle(t); } //end if(3 vertices) else { System.err.println("ResourceManager: FaceBlock has " + vertIndices.size() + " vertices. Only 3 or 4 supported."); } } //end if(FaceBlock) else if (b instanceof ColorBlock) { final ColorBlock cb = (ColorBlock) b; final byte[] bytes = cb.getBytes(); final Color color = new Color(bytes[0] & 0xFF, bytes[1] & 0xFF, bytes[2] & 0xFF); currentTexture = tr.gpu.get().textureManager.get().solidColor(color); } else if (b instanceof FaceBlock19) { System.out.println(b.getClass().getSimpleName() + " (solid colored faces) not yet implemented. Skipping..."); } else if (b instanceof FaceBlock05) { } //TODO else if (b instanceof LineSegmentBlock) { LineSegmentBlock block = (LineSegmentBlock) b; org.jtrfp.trcl.gpu.Vertex v1 = vertices.get(block.getVertexID1()); org.jtrfp.trcl.gpu.Vertex v2 = vertices.get(block.getVertexID2()); if (!alreadyVisitedLineSegs.contains(v1.hashCode() * v2.hashCode())) { Triangle[] newTris = new Triangle[6]; LineSegment.buildTriPipe(v1.getPosition(), v2.getPosition(), tr.gpu.get().textureManager.get().getDefaultTriPipeTexture(), 200, newTris, 0); result.addTriangles(newTris); alreadyVisitedLineSegs.add(v1.hashCode() * v2.hashCode()); } //end if(not already visited) } //end if(LineSegmentBlock) else if (b instanceof Unknown12) { System.out.println("Found unknown12. Assuming this is a tag for a transparent texture..."); hasAlpha = true; } else if (b instanceof AnimatedTextureBlock) { System.out.println("Found animated texture block."); AnimatedTextureBlock block = (AnimatedTextureBlock) b; List<String> frames = block.getFrameNames(); double timeBetweenFramesInMillis = ((double) block.getDelay() / 65535.) * 1000.; Texture[] subTextures = new Texture[frames.size()]; for (int ti = 0; ti < frames.size(); ti++) { if (!hasAlpha) subTextures[ti] = (Texture) getRAWAsTexture(frames.get(ti), palette, ESTuTvPalette, false); else subTextures[ti] = (Texture) getRAWAsTexture(frames.get(ti), palette, ESTuTvPalette, true); //subTextures[ti]=tex instanceof Texture?new DummyTRFutureTask<Texture>((Texture)tex):(Texture)Texture.getFallbackTexture(); } //end for(frames) //fDelay, nFrames,interp currentTexture = new AnimatedTexture( new Sequencer((int) timeBetweenFramesInMillis, subTextures.length, false), subTextures); } else if (b instanceof EOFBlock) { System.out.println("...That's all, end of BIN"); } else { System.out.println("Failed to identify DataBlock: " + b.getClass().getName()); } } //end for(dataBlocks) //result.finalizeModel(); result.setDebugName(name); //if(result.getTriangleList()==null && result.getTransparentTriangleList()==null) // throw new RuntimeException("Resulting BIN has no triangleList"); if (cache) modelCache.put(name, result); return result; } //end try{} catch (UnrecognizedFormatException ee) { //Not-good fail throw new UnrecognizedFormatException( "Can't figure out what this is: " + name + ". Giving up. Expect trouble ahead."); } } //end catch(ok fail) //Bad fail. }
From source file:org.jtrfp.trcl.obj.Debris.java
public void reset(Vector3D pos, Vector3D newVelocity) { getBehavior().probeForBehavior(LimitedLifeSpan.class).reset(lifespan()); setHeading(newVelocity.normalize()); setPosition(pos.toArray());//from www. j av a2s.c om setVisible(true); setActive(true); getBehavior().probeForBehavior(RotationalMomentumBehavior.class).setEquatorialMomentum(.2 * Math.random()) .setLateralMomentum(.2 * Math.random()).setPolarMomentum(.2 * Math.random()); getBehavior().probeForBehavior(Velocible.class).setVelocity(newVelocity); getBehavior().probeForBehavior(DeathBehavior.class).reset(); }
From source file:org.jtrfp.trcl.obj.ProjectileBillboard.java
public void reset(double[] newPos, Vector3D newVelocity, WorldObject objectOfOrigin) { this.objectOfOrigin = new WeakReference<WorldObject>(objectOfOrigin); getBehavior().probeForBehavior(LimitedLifeSpan.class).reset(LIFESPAN_MILLIS); setHeading(newVelocity.normalize()); setPosition(newPos[0], newPos[1], newPos[2]); setVisible(true);/*w w w . j a v a 2s. c o m*/ setActive(true); getBehavior().probeForBehavior(Velocible.class).setVelocity(newVelocity); getBehavior().probeForBehavior(ProjectileBehavior.class).reset(newVelocity.normalize(), newVelocity.getNorm()); }
From source file:org.jtrfp.trcl.obj.ProjectileObject3D.java
@Override public void reset(double[] newPos, Vector3D newVelocity, WorldObject objectOfOrigin) { this.objectOfOrigin = new WeakReference<WorldObject>(objectOfOrigin); if (newVelocity.getNorm() != 0) setHeading(newVelocity.normalize()); else {// www. j a v a2 s . com setHeading(Vector3D.PLUS_I); newVelocity = Vector3D.PLUS_I; } //meh. assert !Vect3D.isAnyNaN(newPos); setPosition(newPos[0], newPos[1], newPos[2]); getBehavior().probeForBehavior(Velocible.class).setVelocity(newVelocity); getBehavior().probeForBehavior(ProjectileBehavior.class).reset(newVelocity.normalize(), newVelocity.getNorm()); setActive(true); setVisible(true); }
From source file:org.jtrfp.trcl.obj.TunnelExitObject.java
public TunnelExitObject(TR tr, Tunnel tun) { super(tr);/* www.j a v a2s . co m*/ addBehavior(new TunnelExitBehavior()); final DirectionVector v = tun.getSourceTunnel().getExit(); final double EXIT_Y_NUDGE = 0; final InterpolatingAltitudeMap map = tr.getGame().getCurrentMission().getOverworldSystem().getAltitudeMap(); final double exitY = map.heightAt(TR.legacy2Modern(v.getZ()), TR.legacy2Modern(v.getX())) + EXIT_Y_NUDGE; this.exitLocation = new Vector3D(TR.legacy2Modern(v.getZ()), exitY, TR.legacy2Modern(v.getX())); this.tun = tun; exitHeading = map.normalAt(exitLocation.getZ() / TR.mapSquareSize, exitLocation.getX() / TR.mapSquareSize); Vector3D horiz = exitHeading.crossProduct(Vector3D.MINUS_J); if (horiz.getNorm() == 0) { horiz = Vector3D.PLUS_I; } else horiz = horiz.normalize(); exitTop = exitHeading.crossProduct(horiz.negate()).normalize().negate(); exitLocation = exitLocation.add(exitHeading.scalarMultiply(10000)); this.tr = tr; setVisible(false); try { Model m = tr.getResourceManager().getBINModel("SHIP.BIN", tr.getGlobalPaletteVL(), null, tr.gpu.get().getGl()); setModel(m); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.orekit.forces.BoxAndSolarArraySpacecraft.java
/** Build a spacecraft model with best lightning of solar array. * <p>//w ww.j a va 2 s . c om * The spacecraft body is described by an array of surface vectors. Each facet of * the body is describe by a vector normal to the facet (pointing outward of the spacecraft) * and whose norm is the surface area in m. * </p> * <p> * Solar arrays orientation will be such that at each time the Sun direction * will always be in the solar array meridian plane defined by solar array * rotation axis and solar array normal vector. * </p> * @param facets body facets (only the facets with strictly positive area will be stored) * @param sun sun model * @param solarArrayArea area of the solar array (m) * @param solarArrayAxis solar array rotation axis in satellite frame * @param dragCoeff drag coefficient (used only for drag) * @param absorptionCoeff absorption coefficient between 0.0 an 1.0 * (used only for radiation pressure) * @param reflectionCoeff specular reflection coefficient between 0.0 an 1.0 * (used only for radiation pressure) */ public BoxAndSolarArraySpacecraft(final Facet[] facets, final PVCoordinatesProvider sun, final double solarArrayArea, final Vector3D solarArrayAxis, final double dragCoeff, final double absorptionCoeff, final double reflectionCoeff) { this.facets = filter(facets); this.sun = sun; this.solarArrayArea = solarArrayArea; this.referenceDate = null; this.rotationRate = 0; this.saZ = solarArrayAxis.normalize(); this.saY = null; this.saX = null; this.dragCoeff = dragCoeff; this.absorptionCoeff = absorptionCoeff; this.specularReflectionCoeff = reflectionCoeff; this.diffuseReflectionCoeff = 1 - (absorptionCoeff + reflectionCoeff); }
From source file:org.orekit.forces.BoxAndSolarArraySpacecraft.java
/** Build a spacecraft model with linear rotation of solar array. * <p>//from w w w . j a va 2s.c o m * The spacecraft body is described by an array of surface vectors. Each facet of * the body is describe by a vector normal to the facet (pointing outward of the spacecraft) * and whose norm is the surface area in m. * </p> * <p> * Solar arrays orientation will be a regular rotation from the * reference orientation at reference date and using a constant * rotation rate. * </p> * @param facets body facets (only the facets with strictly positive area will be stored) * @param sun sun model * @param solarArrayArea area of the solar array (m) * @param solarArrayAxis solar array rotation axis in satellite frame * @param referenceDate reference date for the solar array rotation * @param referenceNormal direction of the solar array normal at reference date * in spacecraft frame * @param rotationRate rotation rate of the solar array, may be 0 (rad/s) * @param dragCoeff drag coefficient (used only for drag) * @param absorptionCoeff absorption coefficient between 0.0 an 1.0 * (used only for radiation pressure) * @param reflectionCoeff specular reflection coefficient between 0.0 an 1.0 * (used only for radiation pressure) */ public BoxAndSolarArraySpacecraft(final Facet[] facets, final PVCoordinatesProvider sun, final double solarArrayArea, final Vector3D solarArrayAxis, final AbsoluteDate referenceDate, final Vector3D referenceNormal, final double rotationRate, final double dragCoeff, final double absorptionCoeff, final double reflectionCoeff) { this.facets = filter(facets.clone()); this.sun = sun; this.solarArrayArea = solarArrayArea; this.referenceDate = referenceDate; this.rotationRate = rotationRate; this.saZ = solarArrayAxis.normalize(); this.saY = Vector3D.crossProduct(saZ, referenceNormal).normalize(); this.saX = Vector3D.crossProduct(saY, saZ); this.dragCoeff = dragCoeff; this.absorptionCoeff = absorptionCoeff; this.specularReflectionCoeff = reflectionCoeff; this.diffuseReflectionCoeff = 1 - (absorptionCoeff + reflectionCoeff); }
From source file:org.orekit.forces.drag.HarrisPriester.java
/** Get the local density. * @param sunInEarth position of the Sun in Earth frame (m) * @param posInEarth target position in Earth frame (m) * @return the local density (kg/m)// ww w. ja va 2 s . c om * @exception OrekitException if altitude is below the model minimal altitude */ public double getDensity(final Vector3D sunInEarth, final Vector3D posInEarth) throws OrekitException { final double posAlt = getHeight(posInEarth); // Check for height boundaries if (posAlt < getMinAlt()) { throw new OrekitException(OrekitMessages.ALTITUDE_BELOW_ALLOWED_THRESHOLD, posAlt, getMinAlt()); } if (posAlt > getMaxAlt()) { return 0.; } // Diurnal bulge apex direction final Vector3D sunDir = sunInEarth.normalize(); final Vector3D bulDir = new Vector3D(sunDir.getX() * COSLAG - sunDir.getY() * SINLAG, sunDir.getX() * SINLAG + sunDir.getY() * COSLAG, sunDir.getZ()); // Cosine of angle Psi between the diurnal bulge apex and the satellite final double cosPsi = bulDir.normalize().dotProduct(posInEarth.normalize()); // (1 + cos(Psi))/2 = cos(Psi/2) final double c2Psi2 = (1. + cosPsi) / 2.; final double cPsi2 = FastMath.sqrt(c2Psi2); final double cosPow = (cPsi2 > MIN_COS) ? c2Psi2 * FastMath.pow(cPsi2, n - 2) : 0.; // Search altitude index in density table int ia = 0; while (ia < tabAltRho.length - 2 && posAlt > tabAltRho[ia + 1][0]) { ia++; } // Fractional satellite height final double dH = (tabAltRho[ia][0] - posAlt) / (tabAltRho[ia][0] - tabAltRho[ia + 1][0]); // Min exponential density interpolation final double rhoMin = tabAltRho[ia][1] * FastMath.pow(tabAltRho[ia + 1][1] / tabAltRho[ia][1], dH); if (Precision.equals(cosPow, 0.)) { return rhoMin; } else { // Max exponential density interpolation final double rhoMax = tabAltRho[ia][2] * FastMath.pow(tabAltRho[ia + 1][2] / tabAltRho[ia][2], dH); return rhoMin + (rhoMax - rhoMin) * cosPow; } }
From source file:org.orekit.forces.maneuvers.ConstantThrustManeuver.java
/** Simple constructor for a constant direction and constant thrust. * @param date maneuver date/*from www .jav a2 s . c o m*/ * @param duration the duration of the thrust (s) (if negative, * the date is considered to be the stop date) * @param thrust the thrust force (N) * @param isp engine specific impulse (s) * @param direction the acceleration direction in satellite frame. */ public ConstantThrustManeuver(final AbsoluteDate date, final double duration, final double thrust, final double isp, final Vector3D direction) { super(THRUST, FLOW_RATE); if (duration >= 0) { this.startDate = date; this.endDate = date.shiftedBy(duration); } else { this.endDate = date; this.startDate = endDate.shiftedBy(duration); } this.thrust = thrust; this.flowRate = -thrust / (Constants.G0_STANDARD_GRAVITY * isp); this.direction = direction.normalize(); firing = false; }
From source file:org.orekit.forces.maneuvers.SmallManeuverAnalyticalModelTest.java
private BoundedPropagator getEphemeris(final Orbit orbit, final double mass, final AbsoluteDate t0, final Vector3D dV, final double f, final double isp) throws OrekitException { AttitudeProvider law = new LofOffset(orbit.getFrame(), LOFType.LVLH); final SpacecraftState initialState = new SpacecraftState(orbit, law.getAttitude(orbit, orbit.getDate(), orbit.getFrame()), mass); // set up numerical propagator final double dP = 1.0; double[][] tolerances = NumericalPropagator.tolerances(dP, orbit, orbit.getType()); AdaptiveStepsizeIntegrator integrator = new DormandPrince853Integrator(0.001, 1000, tolerances[0], tolerances[1]);//ww w.j a va 2s.com integrator.setInitialStepSize(orbit.getKeplerianPeriod() / 100.0); final NumericalPropagator propagator = new NumericalPropagator(integrator); propagator.setOrbitType(orbit.getType()); propagator.setInitialState(initialState); propagator.setAttitudeProvider(law); if (dV.getNorm() > 1.0e-6) { // set up maneuver final double vExhaust = Constants.G0_STANDARD_GRAVITY * isp; final double dt = -(mass * vExhaust / f) * FastMath.expm1(-dV.getNorm() / vExhaust); final ConstantThrustManeuver maneuver = new ConstantThrustManeuver(t0, dt, f, isp, dV.normalize()); propagator.addForceModel(maneuver); } propagator.setEphemerisMode(); propagator.propagate(t0.shiftedBy(5 * orbit.getKeplerianPeriod())); return propagator.getGeneratedEphemeris(); }