Example usage for org.apache.commons.math3.geometry.euclidean.threed Vector3D ZERO

List of usage examples for org.apache.commons.math3.geometry.euclidean.threed Vector3D ZERO

Introduction

In this page you can find the example usage for org.apache.commons.math3.geometry.euclidean.threed Vector3D ZERO.

Prototype

Vector3D ZERO

To view the source code for org.apache.commons.math3.geometry.euclidean.threed Vector3D ZERO.

Click Source Link

Document

Null vector (coordinates: 0, 0, 0).

Usage

From source file:fr.cs.examples.attitude.EarthObservation_day_night_switch_with_fixed_transitions.java

/** Program entry point.
 * @param args program arguments (unused here)
 *//*from ww  w. ja  va2s  . com*/
public static void main(String[] args) {
    try {

        // configure Orekit
        Autoconfiguration.configureOrekit();
        final SortedSet<String> output = new TreeSet<String>();

        //----------------------------------------
        //  Initial state definition : date, orbit
        //----------------------------------------
        final AbsoluteDate initialDate = new AbsoluteDate(2004, 01, 02, 00, 00, 00.000,
                TimeScalesFactory.getUTC());
        final Vector3D position = new Vector3D(-6142438.668, 3492467.560, -25767.25680);
        final Vector3D velocity = new Vector3D(505.8479685, 942.7809215, 7435.922231);
        final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
                FramesFactory.getEME2000(), initialDate, Constants.EIGEN5C_EARTH_MU);

        //------------------------------
        // Attitudes sequence definition
        //------------------------------
        final AttitudesSequence attitudesSequence = new AttitudesSequence();

        // Attitude laws definition
        //-------------------------

        // Mode : day
        final AttitudeProvider dayObservationLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(40), 0);

        // Mode : night
        final AttitudeProvider nightRestingLaw = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH);

        // Mode : day-night rdv 1
        final AttitudeProvider dayNightRdV1Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(20), 0);

        // Mode : day-night rdv 2
        final AttitudeProvider dayNightRdV2Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), 0, 0);

        // Mode : night-day rdv 1
        final AttitudeProvider nightDayRdV1Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), 0, 0);

        // Mode : night-day rdv 2
        final AttitudeProvider nightDayRdV2Law = new LofOffset(initialOrbit.getFrame(), LOFType.VVLH,
                RotationOrder.XYZ, FastMath.toRadians(20), FastMath.toRadians(20), 0);

        // Event detectors definition
        //---------------------------
        final PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
        final PVCoordinatesProvider earth = CelestialBodyFactory.getEarth();

        // Detectors : end day-night rdv 2
        final DateDetector endDayNightRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-day-night-2 night-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end day-night rdv 1
        final DateDetector endDayNightRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endDayNightRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-day-night-1 day-night-rdv2-mode");
                            endDayNightRdV2Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endDayNightRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse entry
        final EventDetector dayNightEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day-night rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-entry day-night-rdv1-mode");
                            endDayNightRdV1Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endDayNightRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 2
        final DateDetector endNightDayRdV2Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV2Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to day law");
                            System.out.println("# " + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                    / Constants.JULIAN_DAY) + " end-night-day-2 day-mode");
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detectors : end night-day rdv 1
        final DateDetector endNightDayRdV1Event_increase = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        final DateDetector endNightDayRdV1Event_decrease = new DateDetector(10, 1e-04)
                .withHandler(new EventHandler<DateDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final DateDetector detector,
                            final boolean increasing) {
                        if (!increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 2 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " end-night-day-1 night-day-rdv2-mode");
                            endNightDayRdV2Event_increase.addEventDate(s.getDate().shiftedBy(40));
                            endNightDayRdV2Event_decrease.addEventDate(s.getDate().shiftedBy(40));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(DateDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Detector : eclipse exit
        final EventDetector nightDayEvent = new EclipseDetector(sun, 696000000., earth,
                Constants.WGS84_EARTH_EQUATORIAL_RADIUS).withHandler(new EventHandler<EclipseDetector>() {
                    public Action eventOccurred(final SpacecraftState s, final EclipseDetector detector,
                            final boolean increasing) {
                        if (increasing) {
                            output.add(s.getDate() + ": switching to night-day rdv 1 law");
                            System.out
                                    .println("# "
                                            + (s.getDate().durationFrom(AbsoluteDate.J2000_EPOCH)
                                                    / Constants.JULIAN_DAY)
                                            + " eclipse-exit night-day-rdv1-mode");
                            endNightDayRdV1Event_increase.addEventDate(s.getDate().shiftedBy(20));
                            endNightDayRdV1Event_decrease.addEventDate(s.getDate().shiftedBy(20));
                        }
                        return Action.CONTINUE;
                    }

                    public SpacecraftState resetState(EclipseDetector detector, SpacecraftState oldState) {
                        return oldState;
                    }
                });

        // Attitude sequences definition
        //------------------------------
        attitudesSequence.addSwitchingCondition(dayObservationLaw, dayNightEvent, false, true, dayNightRdV1Law);
        attitudesSequence.addSwitchingCondition(dayNightRdV1Law, endDayNightRdV1Event_increase, true, false,
                dayNightRdV2Law);
        attitudesSequence.addSwitchingCondition(dayNightRdV1Law, endDayNightRdV1Event_decrease, false, true,
                dayNightRdV2Law);
        attitudesSequence.addSwitchingCondition(dayNightRdV2Law, endDayNightRdV2Event_increase, true, false,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(dayNightRdV2Law, endDayNightRdV2Event_decrease, false, true,
                nightRestingLaw);
        attitudesSequence.addSwitchingCondition(nightRestingLaw, nightDayEvent, true, false, nightDayRdV1Law);
        attitudesSequence.addSwitchingCondition(nightDayRdV1Law, endNightDayRdV1Event_increase, true, false,
                nightDayRdV2Law);
        attitudesSequence.addSwitchingCondition(nightDayRdV1Law, endNightDayRdV1Event_decrease, false, true,
                nightDayRdV2Law);
        attitudesSequence.addSwitchingCondition(nightDayRdV2Law, endNightDayRdV2Event_increase, true, false,
                dayObservationLaw);
        attitudesSequence.addSwitchingCondition(nightDayRdV2Law, endNightDayRdV2Event_decrease, false, true,
                dayObservationLaw);

        // Initialisation
        //---------------
        if (dayNightEvent.g(new SpacecraftState(initialOrbit)) >= 0) {
            // initial position is in daytime
            attitudesSequence.resetActiveProvider(dayObservationLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with day law");
        } else {
            // initial position is in nighttime
            attitudesSequence.resetActiveProvider(nightRestingLaw);
            System.out
                    .println("# " + (initialDate.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY)
                            + " begin with night law");
        }

        //----------------------
        // Propagator definition
        //----------------------

        // Propagator : consider the analytical Eckstein-Hechler model
        final Propagator propagator = new EcksteinHechlerPropagator(initialOrbit, attitudesSequence,
                Constants.EIGEN5C_EARTH_EQUATORIAL_RADIUS, Constants.EIGEN5C_EARTH_MU,
                Constants.EIGEN5C_EARTH_C20, Constants.EIGEN5C_EARTH_C30, Constants.EIGEN5C_EARTH_C40,
                Constants.EIGEN5C_EARTH_C50, Constants.EIGEN5C_EARTH_C60);
        // Register the switching events to the propagator
        attitudesSequence.registerSwitchEvents(propagator);

        propagator.setMasterMode(10.0, new OrekitFixedStepHandler() {
            private DecimalFormat f1 = new DecimalFormat("0.0000000000000000E00",
                    new DecimalFormatSymbols(Locale.US));
            private Vector3DFormat f2 = new Vector3DFormat(" ", " ", " ", f1);
            private PVCoordinatesProvider sun = CelestialBodyFactory.getSun();
            private PVCoordinatesProvider moon = CelestialBodyFactory.getMoon();
            private Frame eme2000 = FramesFactory.getEME2000();
            private Frame itrf2005 = FramesFactory.getITRF(IERSConventions.IERS_2010, true);

            private String printVector3D(final String name, final Vector3D v) {
                return name + " " + f2.format(v);
            }

            private String printRotation(final String name, final Rotation r) {
                return name + " " + f1.format(r.getQ1()) + " " + f1.format(r.getQ2()) + " "
                        + f1.format(r.getQ3()) + " " + f1.format(r.getQ0());
            }

            private String printRotation2(final String name, final Rotation r) {
                return name + " " + f1.format(-r.getQ1()) + " " + f1.format(-r.getQ2()) + " "
                        + f1.format(-r.getQ3()) + " " + f1.format(-r.getQ0());
            }

            public void init(final SpacecraftState s0, final AbsoluteDate t) {
            }

            public void handleStep(SpacecraftState currentState, boolean isLast) throws PropagationException {
                try {
                    // the Earth position in spacecraft should be along spacecraft Z axis
                    // during nigthtime and away from it during daytime due to roll and pitch offsets
                    final Vector3D earth = currentState.toTransform().transformPosition(Vector3D.ZERO);
                    final double pointingOffset = Vector3D.angle(earth, Vector3D.PLUS_K);

                    // the g function is the eclipse indicator, its an angle between Sun and Earth limb,
                    // positive when Sun is outside of Earth limb, negative when Sun is hidden by Earth limb
                    final double eclipseAngle = dayNightEvent.g(currentState);

                    final double endNightDayTimer1 = endNightDayRdV1Event_decrease.g(currentState);
                    final double endNightDayTimer2 = endNightDayRdV2Event_decrease.g(currentState);
                    final double endDayNightTimer1 = endDayNightRdV1Event_decrease.g(currentState);
                    final double endDayNightTimer2 = endDayNightRdV2Event_decrease.g(currentState);

                    output.add(currentState.getDate() + " " + FastMath.toDegrees(eclipseAngle) + " "
                            + endNightDayTimer1 + " " + endNightDayTimer2 + " " + endDayNightTimer1 + " "
                            + endDayNightTimer2 + " " + FastMath.toDegrees(pointingOffset));
                    final AbsoluteDate date = currentState.getDate();
                    final PVCoordinates pv = currentState.getPVCoordinates(eme2000);
                    final Rotation lvlhRot = new Rotation(pv.getPosition(), pv.getMomentum(), Vector3D.MINUS_K,
                            Vector3D.MINUS_J);
                    final Rotation earthRot = eme2000.getTransformTo(itrf2005, date).getRotation();
                    System.out.println("Scenario::setVectorMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printVector3D("sun", sun.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("moon", moon.getPVCoordinates(date, eme2000).getPosition()) + " "
                            + printVector3D("satPos", pv.getPosition()) + " "
                            + printVector3D("satVel", pv.getVelocity()) + " "
                            + printVector3D("orbMom", pv.getMomentum()));
                    System.out.println("Scenario::setQuatMap 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY) + " "
                            + printRotation("earthFrame", earthRot) + " "
                            + printRotation("LVLHFrame", lvlhRot));
                    System.out.println("Scenario::computeStep 0x960b7e0 "
                            + (date.durationFrom(AbsoluteDate.J2000_EPOCH) / Constants.JULIAN_DAY));
                    System.out.println("  -> " + printRotation2("", currentState.getAttitude().getRotation())
                            + " " + printVector3D("", currentState.getAttitude().getSpin()));
                } catch (OrekitException oe) {
                    throw new PropagationException(oe);
                }
            }
        });

        //----------
        // Propagate
        //----------

        // Propagate from the initial date for the fixed duration
        propagator.propagate(initialDate.shiftedBy(1.75 * 3600.));

        //--------------
        // Print results
        //--------------

        // we print the lines according to lexicographic order, which is chronological order here
        // to make sure out of orders calls between step handler and event handlers don't mess things up
        for (final String line : output) {
            System.out.println(line);
        }

    } catch (OrekitException oe) {
        System.err.println(oe.getMessage());
    }
}

From source file:nova.core.util.RayTracer.java

/**
 * Does an entity look ray trace to see which block the entity is looking at.
 * @param entity The entity/*w  w w . j av a2 s.  c o  m*/
 */
public RayTracer(Entity entity) {
    this(new Ray(entity.position()
            .add(entity.components.has(Living.class)
                    ? entity.components.get(Living.class).faceDisplacement.get()
                    : Vector3D.ZERO),
            entity.rotation().applyTo(Vector3DUtil.FORWARD)));
}

From source file:nova.core.wrapper.mc.forge.v17.wrapper.entity.forward.BWRigidBody.java

void updateTranslation(double deltaTime) {
    //Integrate velocity to displacement
    Vector3D displacement = velocity().scalarMultiply(deltaTime);
    mcEntity().moveEntity(displacement.getX(), displacement.getY(), displacement.getZ());

    //Integrate netForce to velocity
    setVelocity(velocity().add(netForce.scalarMultiply(1 / mass()).scalarMultiply(deltaTime)));

    //Clear net force
    netForce = Vector3D.ZERO;

    //Apply drag/*from  w w w. jav a2  s .  co m*/
    addForce(velocity().negate().scalarMultiply(drag()));
    if (!mcEntity().onGround) {
        //Apply gravity
        addForce(gravity().scalarMultiply(mass()));
    }
}

From source file:nova.core.wrapper.mc.forge.v17.wrapper.entity.forward.BWRigidBody.java

void updateRotation(double deltaTime) {

    //Integrate angular velocity to angular displacement
    Rotation angularVel = angularVelocity();
    Rotation deltaRotation = RotationUtil.slerp(Rotation.IDENTITY, angularVel, deltaTime);
    entity().transform().setRotation(entity().rotation().applyTo(deltaRotation));

    //Integrate torque to angular velocity
    Vector3D torque = netTorque.scalarMultiply(deltaTime);
    if (!Vector3D.ZERO.equals(torque)) {
        setAngularVelocity(angularVelocity().applyTo(new Rotation(Vector3DUtil.FORWARD, torque)));
    }/*from  w  w w.java  2 s.  c  o m*/

    //Clear net torque
    netTorque = Vector3D.ZERO;

    //Apply drag
    Vector3D eulerAngularVel = angularVelocity().applyInverseTo(Vector3DUtil.FORWARD);
    addTorque(eulerAngularVel.negate().scalarMultiply(angularDrag()));
}

From source file:nova.core.wrapper.mc.forge.v17.wrapper.entity.forward.MCEntityTransform.java

public MCEntityTransform(net.minecraft.entity.Entity wrapper) {
    this.wrapper = wrapper;
    this.setPivot(Vector3D.ZERO);
    this.setScale(Vector3DUtil.ONE);
}

From source file:org.jtrfp.trcl.CharDisplay.java

public CharDisplay(TR tr, RenderableSpacePartitioningGrid grid, double glSize, GLFont font) {
    super(tr);/*  w ww. ja  va2  s . com*/
    final Model model = new Model(false, tr);
    tex = new SelectableTexture(font.getTextures());
    Triangle[] tris = Triangle.quad2Triangles(new double[] { 0., glSize, glSize, 0. }, // x
            new double[] { 0., 0., glSize, glSize }, new double[] { 0, 0, 0, 0 },

            new double[] { 0, 1, 1, 0 }, // u
            new double[] { 0, 0, 1, 1 }, tex, RenderMode.DYNAMIC, Vector3D.ZERO, "CharDisplay");
    tris[0].setAlphaBlended(true);
    tris[1].setAlphaBlended(true);
    model.addTriangles(tris);
    setModel(model);
}

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 {//  w w w .j av  a2 s  . co 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.Crosshairs.java

public Crosshairs(TR tr) {
    super(tr);/*from w  ww  .j  a v a2 s.  co  m*/
    setImmuneToOpaqueDepthTest(true);
    // Crosshairs
    Model crossModel = null;
    final TextureManager tm = tr.gpu.get().textureManager.get();
    // Fallback
    final int NUM_FRAMES = 16;
    final double LUM_STEP = 200. / NUM_FRAMES;
    Texture[] greenThrobFrames = new Texture[NUM_FRAMES];
    for (int f = 0; f < NUM_FRAMES; f++) {
        greenThrobFrames[f] = greenThrobFrames[(NUM_FRAMES - 1) - f] = (Texture) tm.solidColor(
                new Color((int) (f * LUM_STEP * .8), (int) (f * LUM_STEP), (int) (f * LUM_STEP * .8), 170));
    } //end for(NUM_FRAMES)
    TextureDescription greenThrob = new AnimatedTexture(new Sequencer(80, greenThrobFrames.length, false),
            greenThrobFrames);/*tr.gpu.get().textureManager.get().getFallbackTexture();*/
    // TODO: Set crosshairs as a player-tracking object
    /*
     * The official crosshairs. We supply the 'green throb' TARGET.BIN has a
     * size range of [-8192,8192], a far cry from OpenGL's [-1,1] range.
     * Also has a Z offset of +204,800. Scaling down by 204800 and
     * subtracting 1 for a Z of zero we get correct size. In the real game
     * TARGET.BIN is apparently appended to the player ship model itself
     * such that the Z protrusion is real. Furthermore, enemies try to
     * attack the crosshairs instead of the plane, perhaps as a kludge for
     * motion-compensated aiming.
     */
    try {
        crossModel = tr.getResourceManager().getBINModel("TARGET.BIN", greenThrob, 1. / 204800., true,
                tr.getGlobalPaletteVL(), null);
    } catch (Exception e) {
        tr.showStopper(e);
    }
    final List<Triangle> tl = crossModel.getRawTriangleLists().get(0);
    for (Triangle t : tl)
        t.setCentroidNormal(Vector3D.ZERO);
    this.setRenderFlags((byte) 1);
    setModel(crossModel);
    this.movePositionBy(new Vector3D(0, 0, -1));
    installReactiveListeners(tr);
}

From source file:org.jtrfp.trcl.Dashboard.java

public Dashboard(TR tr) {
    super(tr);/*from w w  w  . jav  a  2  s.  c om*/
    setImmuneToOpaqueDepthTest(true);
    try {
        // Dashboard
        TextureDescription[] dashTexture = tr.getResourceManager().getSpecialRAWAsTextures("STATBAR.RAW",
                tr.getGlobalPalette(), tr.gpu.get().getGl(), 2, false);
        Model dashModel = new Model(false, tr);
        for (int seg = 0; seg < 5; seg++) {
            final double segWidth = 2. / 5.;
            final double x = -1 + segWidth * seg;

            Triangle[] tris = Triangle.quad2Triangles(new double[] { x, x + segWidth, x + segWidth, x },
                    new double[] { .36, .36, 1, 1 }, new double[] { Z, Z, Z, Z }, new double[] { 0, 1, 1, 0 },
                    new double[] { 0, 0, 1, 1 }, dashTexture[seg], RenderMode.DYNAMIC, Vector3D.ZERO,
                    "Dashboard");
            tris[0].setAlphaBlended(true);
            tris[1].setAlphaBlended(true);
            dashModel.addTriangles(tris);
        } // end for(segs)
        setModel(dashModel);
    } catch (Exception e) {
        tr.showStopper(e);
    }
}

From source file:org.jtrfp.trcl.flow.Mission.java

public void enterTunnel(Tunnel tunnel) {
    final Game game = tr.getGame();
    final OverworldSystem overworldSystem = game.getCurrentMission().getOverworldSystem();
    currentTunnel = tunnel;// ww  w .ja v  a  2s.c  o m
    game.getCurrentMission().notifyTunnelFound(tunnel);
    setMissionMode(new TunnelMode());
    //Turn off overworld
    overworldSystem.deactivate();
    //Turn on tunnel
    tunnel.activate();
    //Move player to tunnel
    tr.mainRenderer.get().getSkyCube().setSkyCubeGen(Tunnel.TUNNEL_SKYCUBE_GEN);
    //Ensure chamber mode is off
    overworldSystem.setChamberMode(false);
    overworldSystem.setTunnelMode(true);
    //Update debug data
    tr.getReporter().report("org.jtrfp.Tunnel.isInTunnel?", "true");

    final ProjectileFactory[] pfs = tr.getResourceManager().getProjectileFactories();
    for (ProjectileFactory pf : pfs) {
        Projectile[] projectiles = pf.getProjectiles();
        for (Projectile proj : projectiles) {
            ((WorldObject) proj).getBehavior().probeForBehavior(LoopingPositionBehavior.class).setEnable(false);
        } //end for(projectiles)
    } //end for(projectileFactories)
    final Player player = tr.getGame().getPlayer();
    player.setActive(false);
    player.resetVelocityRotMomentum();
    final Behavior playerBehavior = player.getBehavior();
    playerBehavior.probeForBehavior(CollidesWithTunnelWalls.class).setEnable(true);
    playerBehavior.probeForBehavior(MovesByVelocity.class).setVelocity(Vector3D.ZERO);
    playerBehavior.probeForBehavior(LoopingPositionBehavior.class).setEnable(false);
    playerBehavior.probeForBehavior(HeadingXAlwaysPositiveBehavior.class).setEnable(true);
    playerBehavior.probeForBehavior(CollidesWithTerrain.class).setEnable(false);
    //entranceObject.getBehavior().probeForBehaviors(TELsubmitter, TunnelEntryListener.class);
    tunnel.dispatchTunnelEntryNotifications();
    player.setPosition(Tunnel.TUNNEL_START_POS.toArray());
    player.setDirection(Tunnel.TUNNEL_START_DIRECTION);
    player.notifyPositionChange();
    /*
    final NAVObjective navObjective = getNavObjectiveToRemove();
    if(navObjective!=null && navTargeted){
        final Mission m = game.getCurrentMission();
        if(!(onlyRemoveIfCurrent&&navObjective!=m.currentNAVObjective()))m.removeNAVObjective(navObjective);
    }//end if(have NAV to remove
    */
    player.setActive(true);
}