Exemple #1
0
void Player::update(sf::Time frametime, Input input) {
  //First update velocity x
  
  _acc += frametime;
  while(_acc >= sf::milliseconds(GameConstant::SIMULATION_TIME_PER_UPDATE)) {
    _acc -= sf::milliseconds(GameConstant::SIMULATION_TIME_PER_UPDATE);
    float seconds = GameConstant::SIMULATION_TIME_PER_UPDATE / 1000.0;
    //Update velocity X
    if (input.Left) 
      _velocity.x = std::max(_velocity.x - 2 * _acceleration.x * seconds, -_max_walk_speed);
    else if(input.Right) {
      _velocity.x =  std::min(_velocity.x + 2* _acceleration.x * seconds, _max_walk_speed);
    }
  
    //Update velocity Y
    if(_noclip && input.Up)
      _velocity.y = std::max(_velocity.y - 2 * _acceleration.y * seconds, -_max_fall_speed);
    else if(_noclip && input.Down) 
      _velocity.y = std::min(_velocity.y + 2 * _acceleration.y * seconds, _max_fall_speed);
    else if(input.Up && !_is_flying) 
      _velocity.y -= _jump_force;
  
    //Now we can update position

    //First apply some friction
    if(_velocity.x > 0) 
      _velocity.x = std::max(0.F, _velocity.x - (_acceleration.x) * seconds);
    else if(_velocity.x < 0)
      _velocity.x = std::min(0.F, _velocity.x + (_acceleration.x) * seconds);
  
    if(_noclip && _velocity.y > 0) 
      _velocity.y = std::max(0.F, _velocity.y - (_acceleration.y) * seconds);
    else if(_noclip && _velocity.y < 0)
      _velocity.y = std::min(0.F, _velocity.y + (_acceleration.y) * seconds);
    else
      _velocity.y = std::min(_velocity.y + (_acceleration.y) * seconds, _max_fall_speed);
    
    //Update position and check for collision
    if(_velocity.x != 0){
      _position.x += _velocity.x * seconds;
    
      Cube *c = _world->getCollidingCube(getBbox());
      if( c != NULL){
	if(_velocity.x < 0)
	  _position.x = c->getBbox().left + c->getBbox().width;
	else
	  _position.x = c->getBbox().left - getBbox().width;
	_velocity.x = 0;
      }
    }
  
    if(_velocity.y != 0){
      _position.y += _velocity.y * seconds;
      _is_flying = true;
      Cube *c = _world->getCollidingCube(getBbox());
      if( c != NULL){
	if(_velocity.y < 0)
	  _position.y = c->getBbox().top + c->getBbox().height;
	else{
	  _position.y = c->getBbox().top - getBbox().height;
	  _is_flying = false;
	}
	_velocity.y = 0;
      }
    }
  }

}
 /**
  * Constructs a UniversalGroundMap object from a cube
  * 
  * @param cube The Cube to create the UniversalGroundMap from
  */
 UniversalGroundMap::UniversalGroundMap(Cube &cube) {
   Init(*cube.Label());
 }
inline
void
op_reshape::apply(Cube<typename T1::elem_type>& out, const OpCube<T1,op_reshape>& in)
{
    arma_extra_debug_sigprint();

    typedef typename T1::elem_type eT;

    const unwrap_cube<T1> A_tmp(in.m);
    const Cube<eT>& A   = A_tmp.M;

    const uword in_n_rows   = in.aux_uword_a;
    const uword in_n_cols   = in.aux_uword_b;
    const uword in_n_slices = in.aux_uword_c;
    const uword in_dim      = in.aux_uword_d;

    const uword in_n_elem = in_n_rows * in_n_cols * in_n_slices;

    if(A.n_elem == in_n_elem)
    {
        if(in_dim == 0)
        {
            if(&out != &A)
            {
                out.set_size(in_n_rows, in_n_cols, in_n_slices);
                arrayops::copy( out.memptr(), A.memptr(), out.n_elem );
            }
            else  // &out == &A, i.e. inplace resize
            {
                const bool same_size = ( (out.n_rows == in_n_rows) && (out.n_cols == in_n_cols) && (out.n_slices == in_n_slices) );

                if(same_size == false)
                {
                    arma_debug_check
                    (
                        (out.mem_state == 3),
                        "reshape(): size can't be changed as template based size specification is in use"
                    );

                    out.delete_mat();

                    access::rw(out.n_rows)       = in_n_rows;
                    access::rw(out.n_cols)       = in_n_cols;
                    access::rw(out.n_elem_slice) = in_n_rows * in_n_cols;
                    access::rw(out.n_slices)     = in_n_slices;

                    out.create_mat();
                }
            }
        }
        else
        {
            unwrap_cube_check< Cube<eT> > B_tmp(A, out);
            const Cube<eT>& B           = B_tmp.M;

            out.set_size(in_n_rows, in_n_cols, in_n_slices);

            eT* out_mem = out.memptr();
            uword i = 0;

            const uword B_n_rows   = B.n_rows;
            const uword B_n_cols   = B.n_cols;
            const uword B_n_slices = B.n_slices;

            for(uword slice=0; slice<B_n_slices; ++slice)
                for(uword row=0; row<B_n_rows; ++row)
                    for(uword col=0; col<B_n_cols; ++col)
                    {
                        out_mem[i] = B.at(row,col,slice);
                        ++i;
                    }
        }
    }
    else
    {
        const unwrap_cube_check< Cube<eT> > B_tmp(A, out);
        const Cube<eT>& B                 = B_tmp.M;

        const uword n_elem_to_copy = (std::min)(B.n_elem, in_n_elem);

        out.set_size(in_n_rows, in_n_cols, in_n_slices);

        eT* out_mem = out.memptr();

        if(in_dim == 0)
        {
            arrayops::copy( out_mem, B.memptr(), n_elem_to_copy );
        }
        else
        {
            uword row   = 0;
            uword col   = 0;
            uword slice = 0;

            const uword B_n_rows = B.n_rows;
            const uword B_n_cols = B.n_cols;

            for(uword i=0; i<n_elem_to_copy; ++i)
            {
                out_mem[i] = B.at(row,col,slice);

                ++col;

                if(col >= B_n_cols)
                {
                    col = 0;
                    ++row;

                    if(row >= B_n_rows)
                    {
                        row = 0;
                        ++slice;
                    }
                }
            }
        }

        for(uword i=n_elem_to_copy; i<in_n_elem; ++i)
        {
            out_mem[i] = eT(0);
        }

    }
}
Exemple #4
0
void IsisMain ()
{
    stretch.ClearPairs();

    for (int i=0; i<6; i++) {
        gapCount[i] = 0;
        suspectGapCount[i] = 0;
        invalidCount[i] = 0;
        lisCount[i] = 0;
        hisCount[i] = 0;
        validCount[i] = 0;
    }

    void TranslateHiriseEdrLabels (Filename &labelFile, Cube *);
    void SaveHiriseCalibrationData (ProcessImportPds &process, Cube *,
                                    Pvl &pdsLabel);
    void SaveHiriseAncillaryData (ProcessImportPds &process, Cube *);
    void FixDns8 (Buffer &buf);
    void FixDns16 (Buffer &buf);

    ProcessImportPds p;
    Pvl pdsLabel;
    UserInterface &ui = Application::GetUserInterface();

    // Get the input filename and make sure it is a HiRISE EDR
    Filename inFile = ui.GetFilename("FROM");
    iString id;
    bool projected;
    try {
        Pvl lab(inFile.Expanded());
        id = (string) lab.FindKeyword ("DATA_SET_ID");
        projected = lab.HasObject("IMAGE_MAP_PROJECTION");
    }
    catch (iException &e) {
        string msg = "Unable to read [DATA_SET_ID] from input file [" +
                     inFile.Expanded() + "]";
        throw iException::Message(iException::Io,msg, _FILEINFO_);
    }

    //Checks if in file is rdr
    if( projected ) {
        string msg = "[" + inFile.Name() + "] appears to be an rdr file.";
        msg += " Use pds2isis.";
        throw iException::Message(iException::User,msg, _FILEINFO_);
    }

    id.ConvertWhiteSpace();
    id.Compress();
    id.Trim(" ");
    if (id != "MRO-M-HIRISE-2-EDR-V1.0") {
        string msg = "Input file [" + inFile.Expanded() + "] does not appear to be " +
                     "in HiRISE EDR format. DATA_SET_ID is [" + id + "]";
        throw iException::Message(iException::Io,msg, _FILEINFO_);
    }

    p.SetPdsFile (inFile.Expanded(), "", pdsLabel);

    // Make sure the data we need for the BLOBs is saved by the Process
    p.SaveFileHeader();
    p.SaveDataPrefix();
    p.SaveDataSuffix();

    // Let the Process create the output file but override any commandline
    // output bit type and min/max. It has to be 16bit for the rest of hi2isis
    // to run.
    // Setting the min/max to the 16 bit min/max keeps all the dns (including
    // the 8 bit special pixels from changing their value when they are mapped
    // to the 16 bit output.
    CubeAttributeOutput &outAtt = ui.GetOutputAttribute("TO");
    outAtt.PixelType (Isis::SignedWord);
    outAtt.Minimum((double)VALID_MIN2);
    outAtt.Maximum((double)VALID_MAX2);
    Cube *ocube = p.SetOutputCube(ui.GetFilename("TO"), outAtt);
    p.StartProcess ();
    TranslateHiriseEdrLabels (inFile, ocube);

    // Pull out the lookup table so we can apply it in the second pass
    // and remove it from the labels.
    // Add the UNLUTTED keyword to the instrument group so we know
    // if the lut has been used to convert back to 14 bit data
    PvlGroup &instgrp = ocube->GetGroup("Instrument");
    PvlKeyword lutKey = instgrp["LookupTable"];
    PvlSequence lutSeq;
    lutSeq = lutKey;

    // Set up the Stretch object with the info from the lookup table
    // If the first entry is (0,0) then no lut was applied.
    if ((lutKey.IsNull()) ||
            (lutSeq.Size()==1 && lutSeq[0][0]=="0" && lutSeq[0][1]=="0")) {
        stretch.AddPair(0.0, 0.0);
        stretch.AddPair(65536.0, 65536.0);
        instgrp.AddKeyword(PvlKeyword("Unlutted","TRUE"));
        instgrp.DeleteKeyword ("LookupTable");
    }
    // The user wants it unlutted
    else if (ui.GetBoolean("UNLUT")) {
        for (int i=0; i<lutSeq.Size(); i++) {
            stretch.AddPair(i, (((double)lutSeq[i][0] + (double)lutSeq[i][1]) / 2.0));
        }
        instgrp.AddKeyword(PvlKeyword("Unlutted","TRUE"));
        instgrp.DeleteKeyword ("LookupTable");
    }
    // The user does not want the data unlutted
    else {
        stretch.AddPair(0.0, 0.0);
        stretch.AddPair(65536.0, 65536.0);
        instgrp.AddKeyword(PvlKeyword("Unlutted","FALSE"));
    }
    ocube->PutGroup(instgrp);

    // Save the calibration and ancillary data as BLOBs. Both get run thru the
    // lookup table just like the image data.
    SaveHiriseCalibrationData (p, ocube, pdsLabel);
    SaveHiriseAncillaryData (p, ocube);

    // Save off the input bit type so we know how to process it on the
    // second pass below.
    Isis::PixelType inType = p.PixelType();

    // All finished with the ImportPds object
    p.EndProcess ();


    // Make another pass thru the data using the output file in read/write mode
    // This allows us to correct gaps, remap special pixels and accumulate some
    // counts
    lsbGap = ui.GetBoolean("LSBGAP");
    ProcessByLine p2;
    string ioFile = ui.GetFilename("TO");
    CubeAttributeInput att;
    p2.SetInputCube(ioFile, att, ReadWrite);
    p2.Progress()->SetText("Converting special pixels");
    section = 4;
    p2.StartProcess((inType == Isis::UnsignedByte) ? FixDns8 : FixDns16);
    p2.EndProcess();


    // Log the results of the image conversion
    PvlGroup results("Results");
    results += PvlKeyword ("From", inFile.Expanded());

    results += PvlKeyword ("CalibrationBufferGaps", gapCount[0]);
    results += PvlKeyword ("CalibrationBufferLIS", lisCount[0]);
    results += PvlKeyword ("CalibrationBufferHIS", hisCount[0]);
    results += PvlKeyword ("CalibrationBufferPossibleGaps", suspectGapCount[0]);
    results += PvlKeyword ("CalibrationBufferInvalid", invalidCount[0]);
    results += PvlKeyword ("CalibrationBufferValid", validCount[0]);

    results += PvlKeyword ("CalibrationImageGaps", gapCount[1]);
    results += PvlKeyword ("CalibrationImageLIS", lisCount[1]);
    results += PvlKeyword ("CalibrationImageHIS", hisCount[1]);
    results += PvlKeyword ("CalibrationImagePossibleGaps", suspectGapCount[1]);
    results += PvlKeyword ("CalibrationImageInvalid", invalidCount[1]);
    results += PvlKeyword ("CalibrationImageValid", validCount[1]);

    results += PvlKeyword ("CalibrationDarkGaps", gapCount[2]);
    results += PvlKeyword ("CalibrationDarkLIS", lisCount[2]);
    results += PvlKeyword ("CalibrationDarkHIS", hisCount[2]);
    results += PvlKeyword ("CalibrationDarkPossibleGaps", suspectGapCount[2]);
    results += PvlKeyword ("CalibrationDarkInvalid", invalidCount[2]);
    results += PvlKeyword ("CalibrationDarkValid", validCount[2]);

    results += PvlKeyword ("ObservationBufferGaps", gapCount[3]);
    results += PvlKeyword ("ObservationBufferLIS", lisCount[3]);
    results += PvlKeyword ("ObservationBufferHIS", hisCount[3]);
    results += PvlKeyword ("ObservationBufferPossibleGaps", suspectGapCount[3]);
    results += PvlKeyword ("ObservationBufferInvalid", invalidCount[3]);
    results += PvlKeyword ("ObservationBufferValid", validCount[3]);

    results += PvlKeyword ("ObservationImageGaps", gapCount[4]);
    results += PvlKeyword ("ObservationImageLIS", lisCount[4]);
    results += PvlKeyword ("ObservationImageHIS", hisCount[4]);
    results += PvlKeyword ("ObservationImagePossibleGaps", suspectGapCount[4]);
    results += PvlKeyword ("ObservationImageInvalid", invalidCount[4]);
    results += PvlKeyword ("ObservationImageValid", validCount[4]);

    results += PvlKeyword ("ObservationDarkGaps", gapCount[5]);
    results += PvlKeyword ("ObservationDarkLIS", lisCount[5]);
    results += PvlKeyword ("ObservationDarkHIS", hisCount[5]);
    results += PvlKeyword ("ObservationDarkPossibleGaps", suspectGapCount[5]);
    results += PvlKeyword ("ObservationDarkInvalid", invalidCount[5]);
    results += PvlKeyword ("ObservationDarkValid", validCount[5]);

    // Write the results to the log
    Application::Log(results);

    return;
}
Exemple #5
0
void IsisMain() {

  //get the number of samples to skip from the left and right ends
  // of the prefix and suffix data
  UserInterface &ui = Application::GetUserInterface();

  int imageLeft      = 0;
  int imageRight     = 0;
  int rampLeft       = 0;
  int rampRight      = 0;
  int calLeftBuffer  = 0;
  int calRightBuffer = 0;
  int calLeftDark    = 0;
  int calRightDark   = 0;
  int leftBuffer     = 0;
  int rightBuffer    = 0;
  int leftDark       = 0;
  int rightDark      = 0;

  if(ui.GetBoolean("USEOFFSETS")) {
    imageLeft      = ui.GetInteger("LEFTIMAGE");
    imageRight     = ui.GetInteger("RIGHTIMAGE");
    rampLeft       = ui.GetInteger("LEFTIMAGE");
    rampRight      = ui.GetInteger("RIGHTIMAGE");
    calLeftBuffer  = ui.GetInteger("LEFTCALBUFFER");
    calRightBuffer = ui.GetInteger("LEFTCALBUFFER");
    calLeftDark    = ui.GetInteger("LEFTCALDARK");
    calRightDark   = ui.GetInteger("RIGHTCALDARK");
    leftBuffer     = ui.GetInteger("LEFTBUFFER");
    rightBuffer    = ui.GetInteger("RIGHTBUFFER");
    leftDark       = ui.GetInteger("LEFTDARK");
    rightDark      = ui.GetInteger("RIGHTDARK");
  }


  Isis::FileName fromFile = ui.GetFileName("FROM");
  Isis::Cube inputCube;
  inputCube.open(fromFile.expanded());

  //Check to make sure we got the cube properly
  if(!inputCube.isOpen()) {
    QString msg = "Could not open FROM cube " + fromFile.expanded();
    throw IException(IException::User, msg, _FILEINFO_);
  }

  Process p;
  Cube *icube = p.SetInputCube("FROM");

  // Get statistics from the cube prefix and suffix data
  Table hifix("HiRISE Ancillary");
  icube->read(hifix);
  Statistics darkStats, bufStats, rampDarkStats;
  int tdi = icube->group("Instrument")["Tdi"];
  int binning_mode = icube->group("Instrument")["Summing"];

  //This gets us the statistics for the dark and buffer pixels
  // alongside of the image itself
  for(int rec = 2; rec < hifix.Records(); rec++) {
    vector<int> dark = hifix[rec]["DarkPixels"];
    vector<int> buf = hifix[rec]["BufferPixels"];
    if(buf.size() <= (unsigned int)(leftBuffer + rightBuffer)) {
      ThrowException(buf.size(), leftBuffer, rightBuffer, "image buffer");
    }
    if(dark.size() <= (unsigned int)(leftDark + rightDark)) {
      ThrowException(dark.size(), leftDark, rightDark, "image dark reference");
    }

    for(int i = leftDark; i < (int)dark.size() - rightDark; i++) {
      double d;
      if(dark[i] == NULL2) d = NULL8;
      else if(dark[i] == LOW_REPR_SAT2) d = LOW_REPR_SAT8;
      else if(dark[i] == LOW_INSTR_SAT2) d = LOW_INSTR_SAT8;
      else if(dark[i] == HIGH_INSTR_SAT2) d = HIGH_INSTR_SAT8;
      else if(dark[i] == HIGH_REPR_SAT2) d = HIGH_REPR_SAT8;
      else d = dark[i];
      darkStats.AddData(&d, 1);
    }


    for(int i = leftBuffer; i < (int)buf.size() - rightBuffer; i++) {
      double d;
      if(buf[i] == NULL2) d = NULL8;
      else if(buf[i] == LOW_REPR_SAT2) d = LOW_REPR_SAT8;
      else if(buf[i] == LOW_INSTR_SAT2) d = LOW_INSTR_SAT8;
      else if(buf[i] == HIGH_INSTR_SAT2) d = HIGH_INSTR_SAT8;
      else if(buf[i] == HIGH_REPR_SAT2) d = HIGH_REPR_SAT8;
      else d = buf[i];
      bufStats.AddData(&d, 1);
    }
  }

  // Get statistics from the calibration image

  //Calculate boundaries of the reverse readout lines,
  // Masked lines, and ramp lines.

  //There are always 20 reverse readout lines
  int reverseReadoutLines = 20;

  //Number of mask pixels depends on Binning mode
  int maskLines;
  maskLines = 20 / binning_mode;

  //mask lines go after reverse lines
  maskLines += reverseReadoutLines;

// Actual starting line, number Ramp lines
  int rampStart = maskLines;
  int rampLines = tdi / binning_mode;

  Table calimg("HiRISE Calibration Image");
  icube->read(calimg);
  Statistics calStats;
  //Statistics for the Reverse readout lines of the cal image
  Statistics reverseStats;
  //Statistics for the masked lines of the cal image
  Statistics maskStats;
  //Statistics for the ramped lines of the cal image
  Statistics rampStats;

  //Iterate through the calibration image

  //Add in reverse data
  for(int rec = 2 ; rec <= 18 ; rec++) { //Lines [2,18]
    vector<int> lineBuffer = calimg[rec]["Calibration"];
    for(unsigned int i = 2 ; i < lineBuffer.size() - 1 ; i++) { //Samples [2, * -1]
      double d = lineBuffer[i];
      if(lineBuffer[i] == NULL2) {
        d = NULL8;
      }
      else if(lineBuffer[i] == LOW_REPR_SAT2)  {
        d = LOW_REPR_SAT8;
      }
      else if(lineBuffer[i] == LOW_INSTR_SAT2) {
        d = LOW_INSTR_SAT8;
      }
      else if(lineBuffer[i] == HIGH_INSTR_SAT2) {
        d = HIGH_INSTR_SAT8;
      }
      else if(lineBuffer[i] == HIGH_REPR_SAT2) {
        d = HIGH_REPR_SAT8;
      }
      reverseStats.AddData(&d, 1);
    }
  }

  //Add in the mask data
  for(int rec = 22 ; rec < maskLines - 1 ; rec++) {//Lines [22, 38] !!!!dependant on bin
    vector<int> lineBuffer = calimg[rec]["Calibration"];
    for(int i = 2 ; i < (int)lineBuffer.size() - 1 ; i++) { //Samples [2, *-1]
      double d = lineBuffer[i];
      if(d == NULL2) {
        d = NULL8;
      }
      else if(d == LOW_REPR_SAT2)  {
        d = LOW_REPR_SAT8;
      }
      else if(d == LOW_INSTR_SAT2) {
        d = LOW_INSTR_SAT8;
      }
      else if(d == HIGH_INSTR_SAT2) {
        d = HIGH_INSTR_SAT8;
      }
      else if(d == HIGH_REPR_SAT2) {
        d = HIGH_REPR_SAT8;
      }
      maskStats.AddData(&d, 1);
    }
  }

  //Add in the ramp data
  for(int rec = maskLines + 2; rec < calimg.Records() - 1; rec++) {
    vector<int> buf = calimg[rec]["Calibration"];
    //loop through all but the first and last sample of the calibration image
    for(int i = rampLeft; i < (int)buf.size() - rampRight; i++) {
      double d;
      if(buf[i] == NULL2) d = NULL8;
      else if(buf[i] == LOW_REPR_SAT2) d = LOW_REPR_SAT8;
      else if(buf[i] == LOW_INSTR_SAT2) d = LOW_INSTR_SAT8;
      else if(buf[i] == HIGH_INSTR_SAT2) d = HIGH_INSTR_SAT8;
      else if(buf[i] == HIGH_REPR_SAT2) d = HIGH_REPR_SAT8;
      else d = buf[i];
      //Determine which group of stats to add to
      rampStats.AddData(&d, 1);
    }
  }

  // Get statistics from the calibration prefix and suffix data
  Table calfix("HiRISE Calibration Ancillary");
  icube->read(calfix);
  Statistics calDarkStats, calBufStats;
  int rampLine0 = rampStart + 1;
  int rampLineN = (rampStart + rampLines - 1) - 1;
  rampLineN = calfix.Records() - 1;
  for(int rec = 0; rec < calfix.Records(); rec++) {
    vector<int> dark = calfix[rec]["DarkPixels"];
    vector<int> buf = calfix[rec]["BufferPixels"];
    if(buf.size() <= (unsigned int)(calLeftBuffer + calRightBuffer)) {
      ThrowException(buf.size(), calLeftBuffer, calRightBuffer, "calibration buffer");
    }
    if(dark.size() <= (unsigned int)(calLeftDark + calRightDark)) {
      ThrowException(dark.size(), calLeftDark, calRightDark, "calibration dark reference");
    }
    for(int i = calLeftDark; i < (int)dark.size() - calRightDark; i++) {
      double d;
      if(dark[i] == NULL2) d = NULL8;
      else if(dark[i] == LOW_REPR_SAT2) d = LOW_REPR_SAT8;
      else if(dark[i] == LOW_INSTR_SAT2) d = LOW_INSTR_SAT8;
      else if(dark[i] == HIGH_INSTR_SAT2) d = HIGH_INSTR_SAT8;
      else if(dark[i] == HIGH_REPR_SAT2) d = HIGH_REPR_SAT8;
      else d = dark[i];
      calDarkStats.AddData(&d, 1);
      if((rec > rampLine0) && (rec < rampLineN)) {
        rampDarkStats.AddData(&d, 1);
      }
    }
    for(int i = calLeftBuffer; i < (int)buf.size() - calRightBuffer; i++) {
      double d;
      if(buf[i] == NULL2) d = NULL8;
      else if(buf[i] == LOW_REPR_SAT2) d = LOW_REPR_SAT8;
      else if(buf[i] == LOW_INSTR_SAT2) d = LOW_INSTR_SAT8;
      else if(buf[i] == HIGH_INSTR_SAT2) d = HIGH_INSTR_SAT8;
      else if(buf[i] == HIGH_REPR_SAT2) d = HIGH_REPR_SAT8;
      else d = buf[i];
      calBufStats.AddData(&d, 1);
    }
  }

  Statistics linesPostrampStats;
  Statistics imageStats;
  Isis::LineManager imageBuffer(inputCube);
  imageBuffer.begin();

  Buffer out(imageBuffer.SampleDimension() - (imageLeft + imageRight),
             imageBuffer.LineDimension(),
             imageBuffer.BandDimension(),
             imageBuffer.PixelType());


  for(int postRampLine = 0 ; postRampLine < LINES_POSTRAMP ; postRampLine++) {
    inputCube.read(imageBuffer);
    for(int postRampSamp = 0 ; postRampSamp < out.SampleDimension() ; postRampSamp++) {
      out[postRampSamp] = imageBuffer[postRampSamp + imageLeft];
    }
    linesPostrampStats.AddData(out.DoubleBuffer(), out.size());
    imageBuffer++;
  }

  for(int imageLine = LINES_POSTRAMP; imageLine < inputCube.lineCount(); imageLine++) {
    inputCube.read(imageBuffer);
    for(int imageSample = 0 ; imageSample < out.SampleDimension(); imageSample++) {
      out[imageSample] = imageBuffer[imageSample + imageLeft];
    }
    imageStats.AddData(out.DoubleBuffer(), out.size());
    imageBuffer++;
  }


  // Generate the statistics in pvl form
  const int NUM_GROUPS = 10;
  PvlGroup groups[NUM_GROUPS];
  groups[0] = PvlStats(linesPostrampStats, "IMAGE_POSTRAMP");
  groups[1] = PvlStats(imageStats, "IMAGE");
  groups[2] = PvlStats(darkStats, "IMAGE_DARK");
  groups[3] = PvlStats(bufStats, "IMAGE_BUFFER");
  groups[4] = PvlStats(reverseStats, "CAL_REVERSE");
  groups[5] = PvlStats(maskStats, "CAL_MASK");
  groups[6] = PvlStats(rampStats, "CAL_RAMP");
  groups[7] = PvlStats(calDarkStats, "CAL_DARK");
  groups[8] = PvlStats(rampDarkStats, "CAL_DARK_RAMP");
  groups[9] = PvlStats(calBufStats, "CAL_BUFFER");

  // Write the results to the output file if the user specified one
  if(ui.WasEntered("TO")) {
    Pvl temp;
    for(int i = 0 ; i < NUM_GROUPS ; i++) {
      temp.addGroup(groups[i]);
    }
    temp.write(ui.GetFileName("TO"));
  }
  else {
    // Log the results
    for(int i = 0 ; i < NUM_GROUPS ; i++) {
      Application::Log(groups[i]);
    }
  }
}
Exemple #6
0
void selectRandomPath()
{
	if (rage_count == 0) // select random path
	{
		rage_path = rand()%6;
		rage_count += 1;
		world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,2.5));
	}
	else // continue executing code
	{
		rage_count++;
		if (rage_count < 10 || jump)
		{
			if (rage_path == 4)
			{
				jump = true;
			}
			if (rage_path == 0 || rage_path == 1 || rage_path == 4)
			{
				world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,2.5));
				rotation.getMatrix().setMatrix(world.getMatrix().rotateY(-0.07));
				world.getMatrix().setMatrix(world.getMatrix().multiply(rotation.getMatrix()));
			}
			else if (rage_path == 2 || rage_path == 3 || rage_path == 4)
			{
				world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,2.5));
				rotation.getMatrix().setMatrix(world.getMatrix().rotateY(0.07));
				world.getMatrix().setMatrix(world.getMatrix().multiply(rotation.getMatrix()));
			}
			else
			{
				world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,2.5));
			}
			
			if (jump)
			{
				j_x += 0.1;
				float y = -(j_x*j_x);
				if (j_x >= 0) y = y*-1;

				if (j_x > -j_start)
				{
					jump = false;
					j_x = j_start;
				}
				else
					world.getMatrix().setMatrix(world.getMatrix().translate(0.0,y,0.0));
			}
		}
		else
		{
			world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,2.5));
			rage_count = 0;
		}
	}
}
Exemple #7
0
void processMovement()
{
	float y;
	if (!toggle_rage)
	{
		if (keys[W])
		{
			world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,1.1));
		}
		if (keys[S])
		{
			world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,-1.1));
		}
	}
	else
	{
		if (keys[W])
		{
			world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,1.1));
			toggle_rage = false;
		}
		if (keys[S])
		{
			world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,-1.1));
			toggle_rage = false;
		}
		else {
			//world.getMatrix().setMatrix(world.getMatrix().translate(0.0,0,1.1));
			selectRandomPath();
		}
	}
	if (keys[A])
	{
		rotation.getMatrix().setMatrix(world.getMatrix().rotateY(-0.05));
		world.getMatrix().setMatrix(world.getMatrix().multiply(rotation.getMatrix()));
	}
	if (keys[D])
	{
		rotation.getMatrix().setMatrix(world.getMatrix().rotateY(0.05));
		world.getMatrix().setMatrix(world.getMatrix().multiply(rotation.getMatrix()));
	}
	if (jump)
	{
		j_x += 0.1;
		y = -(j_x*j_x);
		if (j_x >= 0) y = y*-1;

		if (j_x > -j_start)
			jump = false;
		else
			world.getMatrix().setMatrix(world.getMatrix().translate(0.0,y,0.0));
	}
}
Exemple #8
0
// Main moccal routine
void IsisMain() {
  // We will be processing by line
  ProcessByLine p;

  // Setup the input and make sure it is a ctx file
  UserInterface &ui = Application::GetUserInterface();

  Isis::Pvl lab(ui.GetFileName("FROM"));
  Isis::PvlGroup &inst =
    lab.findGroup("Instrument", Pvl::Traverse);

  QString instId = inst["InstrumentId"];
  if(instId != "CTX") {
    QString msg = "This is not a CTX image.  Ctxcal requires a CTX image.";
    throw IException(IException::User, msg, _FILEINFO_);
  }

  Cube *icube = p.SetInputCube("FROM", OneBand);

  Cube flatFile;
  if(ui.WasEntered("FLATFILE")) {
    flatFile.open(ui.GetFileName("FLATFILE"));
  }
  else {
    FileName flat = FileName("$mro/calibration/ctxFlat_????.cub").highestVersion();
    flatFile.open(flat.expanded());
  }
  flat = new Brick(5000, 1, 1, flatFile.pixelType());
  flat->SetBasePosition(1, 1, 1);
  flatFile.read(*flat);

  // If it is already calibrated then complain
  if(icube->hasGroup("Radiometry")) {
    QString msg = "The CTX image [" + icube->fileName() + "] has already "
                 "been radiometrically calibrated";
    throw IException(IException::User, msg, _FILEINFO_);
  }

  // Get label parameters we will need for calibration equation
  iTime startTime((QString) inst["StartTime"]);
  double etStart = startTime.Et();

  //  Read exposure and convert to milliseconds
  exposure = inst["LineExposureDuration"];
  //exposure *= 1000.;

  sum = inst["SpatialSumming"];
  //  If firstSamp > 0, adjust by 38 to account for prefix pixels.
  firstSamp = inst["SampleFirstPixel"];
  if(firstSamp > 0) firstSamp -= 38;

  //  Read dark current info, if no dc exit?
  Table dcTable("Ctx Prefix Dark Pixels");
  icube->read(dcTable);
  //  TODO::  make sure dc records match cube nlines.

  //  If summing mode = 1 , average odd & even dc pixels separately for
  //  a & b channels.
  //  If summing mode != 1, average all dc pixels and use for both


  for(int rec = 0; rec < dcTable.Records(); rec++) {
    vector<int> darks = dcTable[rec]["DarkPixels"];

    bool aChannel = true;
    double dcASum = 0.;
    double dcBSum = 0.;
    int dcACount = 0;
    int dcBCount = 0;

    double dcSum = 0;
    int dcCount = 0;

    for(int i = 0; i < (int)darks.size(); i++) {

      if(sum == 1) {
        if(aChannel == true) {
          dcASum += (double)darks.at(i);
          dcACount++;
        }
        else {
          dcBSum += (double)darks.at(i);
          dcBCount++;
        }
        aChannel = !aChannel;
      }
      else if(sum > 1) {
        dcSum += (double)darks.at(i);
        dcCount ++;
      }
    }
    if(sum == 1) {
      dcA.push_back(dcASum / (double)dcACount);
      dcB.push_back(dcBSum / (double)dcBCount);
    }
    else {
      dc.push_back(dcSum / (double)dcCount);
    }
  }

  // See if the user wants counts/ms or i/f
  //    iof = conversion factor from counts/ms to i/f
  bool convertIOF = ui.GetBoolean("IOF");
  if(convertIOF) {
    // Get the distance between Mars and the Sun at the given time in
    // Astronomical Units (AU)
    QString bspKernel = p.MissionData("base", "/kernels/spk/de???.bsp", true);
    furnsh_c(bspKernel.toAscii().data());
    QString pckKernel = p.MissionData("base", "/kernels/pck/pck?????.tpc", true);
    furnsh_c(pckKernel.toAscii().data());
    double sunpos[6], lt;
    spkezr_c("sun", etStart, "iau_mars", "LT+S", "mars", sunpos, &lt);
    double dist1 = vnorm_c(sunpos);
    unload_c(bspKernel.toAscii().data());
    unload_c(pckKernel.toAscii().data());

    double dist = 2.07E8;
    double w0 = 3660.5;
    double w1 = w0 * ((dist * dist) / (dist1 * dist1));
    if(exposure *w1 == 0.0) {
      QString msg = icube->fileName() + ": exposure or w1 has value of 0.0 ";
      throw IException(IException::User, msg, _FILEINFO_);
    }
    iof = 1.0 / (exposure * w1);
  }
  else {
    iof = 1.0;
  }

  // Setup the output cube
  Cube *ocube = p.SetOutputCube("TO");

  // Add the radiometry group
  PvlGroup calgrp("Radiometry");

  calgrp += PvlKeyword("FlatFile", flatFile.fileName());
  calgrp += PvlKeyword("iof", toString(iof));


  ocube->putGroup(calgrp);

  // Start the line-by-line calibration sequence
  p.StartProcess(Calibrate);
  p.EndProcess();

}
Exemple #9
0
void IsisMain() {
  // We will be processing by line
  ProcessByTile p;
  p.SetTileSize(128, 128);

  // Setup the input and output cubes
  Cube* info = p.SetInputCube("FROM");
  PvlKeyword &status = info ->group("RESEAUS")["STATUS"];
  UserInterface &ui = Application::GetUserInterface();
  QString in = ui.GetFileName("FROM");

  QString spacecraft = (info->group("Instrument")["SpacecraftName"]);
  QString instrument = (info->group("Instrument")["InstrumentId"]);
  Apollo apollo(spacecraft, instrument);
  if (spacecraft.mid(0,6) != "APOLLO") {
    QString msg = "This application is for use with Apollo spacecrafts only. ";
    throw IException(IException::Unknown, msg, _FILEINFO_);
  }

  // Check reseau status and make sure it is not nominal or removed
  if ((QString)status == "Nominal") {
    QString msg = "Input file [" + in +
          "] appears to have nominal reseau status. You must run findrx first.";
    throw IException(IException::User,msg, _FILEINFO_);
  }
  if ((QString)status == "Removed") {
    QString msg = "Input file [" + in +
          "] appears to already have reseaus removed.";
    throw IException(IException::User,msg, _FILEINFO_);
  }

  status = "Removed";

  p.SetOutputCube ("TO");

  // Start the processing
  p.StartProcess(cpy);
  p.EndProcess();

  dim = apollo.ReseauDimension();

  // Get other user entered options
  QString out= ui.GetFileName("TO");
  resvalid = ui.GetBoolean("RESVALID");
  action = ui.GetString("ACTION");

  // Open the output cube
  Cube cube;
  cube.open(out, "rw");

  PvlGroup &res = cube.label()->findGroup("RESEAUS",Pvl::Traverse);

  // Get reseau line, sample, type, and valid Keywords
  PvlKeyword lines = res.findKeyword("LINE");
  PvlKeyword samps = res.findKeyword("SAMPLE");
  PvlKeyword type = res.findKeyword("TYPE");
  PvlKeyword valid = res.findKeyword("VALID");
  int numres = lines.size();

  Brick brick(dim,dim,1,cube.pixelType());
  int width = ui.GetInteger("WIDTH");
  for (int res=0; res<numres; res++) {
    if ((resvalid == 0 || toInt(valid[res]) == 1)) {
      int baseSamp = (int)(toDouble(samps[res])+0.5) - (dim/2);
      int baseLine = (int)(toDouble(lines[res])+0.5) - (dim/2);
      brick.SetBasePosition(baseSamp,baseLine,1);
      cube.read(brick);
      if (action == "NULL") {
        // set the three pixels surrounding the reseau to null
        for (int i=0; i<dim; i++) {
          for (int j=(width-1)/-2; j<=width/2; j++) {
            // vertical lines
            brick[dim*i+dim/2+j] = Isis::Null;
            // horizontal lines
            brick[dim*(dim/2+j)+i] = Isis::Null;
          }
        }
      }
      else if (action == "PATCH") {
        for (int i = 0; i < dim; i++) {
          for (int j=(width-1)/-2; j<=width/2; j++) {
            // vertical lines
            brick[dim*i+dim/2+j] = (brick[dim*i+dim/2-width+j] + brick[dim*i+dim/2+width+j])/2.0;
            // horizontal lines
            brick[dim*(dim/2+j)+i] = (brick[dim*(dim/2-width+j)+i]+brick[dim*(dim/2+width+j)+i])/2.0;
          }
        }
      }
    }
    cube.write(brick);
  }
  cube.close();
}
Exemple #10
0
void updateHaptics(void)
{
    double timeV = 0.0;

    cLabel* label = new cLabel();
    cLabel* label2 = new cLabel();
    rootLabels->addChild(label);
    rootLabels->addChild(label2);
    label->setPos(0, 0, 0);
    label2->setPos(0, -20, 0);
    label->m_fontColor.set(1.0, 1.0, 1.0);
    label2->m_fontColor.set(1.0, 1.0, 1.0);

    // main haptic simulation loop
    while(simulationRunning)
    {
        float deltaTime = pClock.getCurrentTimeSeconds() - lastTime;
        lastTime = pClock.getCurrentTimeSeconds();

        cVector3d equilibrium (0.0, 0.0, 0.0);
        cVector3d pos0 (0.0, 0.0, 0.0), pos1 (0.0, 0.0, 0.0);

        // for each device
        int i=0;
        while (i < numHapticDevices)
        {
            // read position of haptic device
            cVector3d newPosition;
            hapticDevices[i]->getPosition(newPosition);
            newPosition = deviceToWorld(newPosition, i);

            ((i == 0)? pos0 : pos1) = newPosition;

            // read orientation of haptic device
            cMatrix3d newRotation;
            hapticDevices[i]->getRotation(newRotation);

            // update position and orientation of cursor
            cursors[i]->setPos(newPosition);
            cursors[i]->setRot(newRotation);

            // read linear velocity from device
            cVector3d linearVelocity;
            hapticDevices[i]->getLinearVelocity(linearVelocity);

            // update arrow
//            velocityVectors[i]->m_pointA = newPosition;
//            velocityVectors[i]->m_pointB = cAdd(newPosition, linearVelocity);

            // read user button status
            bool buttonStatus;
            hapticDevices[i]->getUserSwitch(0, buttonStatus);

            // adjustthe  color of the cursor according to the status of
            // the user switch (ON = TRUE / OFF = FALSE)
            if (i == 0)
                cursors[i]->m_material = matCursor2;
            else
                cursors[i]->m_material = matCursor1;

            // increment counter
            i++;
        }

        double f0, f1;
        f0 = pos0.length();
        f1 = pos1.length();

        f0 = f0/(f0 + f1);
        f1 = 1.0 - f0;

        equilibrium = pos1 + (pos0 - pos1)*f0;

        // Update the position of the sun
        cVector3d dir = pos1 - pos0;
        double dist = dir.length();
        dir.normalize();

        double vibrationSpeed = 20.0;
        double vibrationAmount = 0.02;

        //sun->setPos(sun->getPos()*(1.0 - deltaTime*speed) + equilibrium*(deltaTime*speed));
        //timeV += deltaTime*vibrationSpeed*(0.7 - cAbs(f0 - 0.5)*2.0);
        sun->setPos(equilibrium /*+ vibrationAmount*dir*cSinRad(timeV)*/);

        // Update logic
        if (!calibrationFinished) {
            label->m_string = "Calibrating, please move the haptic devices around in order to determine their limitations in movement.";
            label2->m_string = "Press 'c' to finish calibration.";

            if (sun->getPos().x < min.x)
                min.x = sun->getPos().x;
            if (sun->getPos().y < min.y)
                min.y = sun->getPos().y;
            if (sun->getPos().z < min.z)
                min.z = sun->getPos().z;

            if (sun->getPos().x > max.x)
                max.x = sun->getPos().x;
            if (sun->getPos().y > max.y)
                max.y = sun->getPos().y;
            if (sun->getPos().z > max.z)
                max.z = sun->getPos().z;
        } else if (logic->isReady()) {
            if (logic->gameIsOver() && !scoreDisplayed) {
                std::stringstream strs;
                strs << logic->playTime();
                std::string playString = strs.str();

                // define its position, color and string message
                label->m_string = "Congratulation! Your Time: " + playString;
                label2->m_string = "Press 'r' to restart!";

                for (i = 0; i < numHapticDevices; i++) {
                    cVector3d zero(0.0, 0.0, 0.0);
                    hapticDevices[i]->setForce(zero);
                }

                scoreDisplayed = true;
            } else if (!scoreDisplayed) {
                label->m_string = "";
                label2->m_string = "";

                logic->update(deltaTime);

            }

            for (i = 0; i < numHapticDevices; i++) {
                // compute a reaction force
                cVector3d newForce (0,0,0);

                cVector3d devicePosition;
                hapticDevices[i]->getPosition(devicePosition);
                devicePosition = deviceToWorld(devicePosition, i);

                double k = 0.4;
                if (test == 1) k = 0.3;
                double dist = (devicePosition - sun->getPos()).length();
                //dist=dist-0.1;

                newForce = k*(devicePosition - sun->getPos())/(dist*dist*dist);
                //double intensity = (newForce.length())*1.0;
                //newForce.normalize();
                //newForce *= intensity;

    //            newForce = k*(devicePosition - sun->getPos())/(dist*dist*dist);

                if (i == 0) {  // Device on positive X (RIGHT)
                    newForce.x *= -1.0;
                    newForce.y *= -1.0;
                }

                // send computed force to haptic device
    //            bool status = true;
    //            if (hapticDevices[i]->getUserSwitch(0))
    //                printf("button pressed\n");

                // Check if the sphere is in the target area. If so, vibrate
                cVector3d vibrationForce(0.0, 0.0, 0.0);
                if (logic->sphereInTarget() && !logic->gameIsOver()) {
                    Cube* target = logic->getTarget();
                    double dist = target->getPos().distance(sun->getPos());
                    double factor = 1.0 - dist/(target->size/2.0);
                    timeV += deltaTime * (0.5 + factor/2.0);

                    double f = 2*cSinRad(40*timeV);
                    vibrationForce = cVector3d(f, f, f);
                }

                newForce += vibrationForce;
                if (test <= 2 || i == 0)
                    hapticDevices[i]->setForce(newForce);
                else {
                    cVector3d zero;
                    zero.zero();
                    hapticDevices[i]->setForce(zero);
                }
          }
        }
    }
    
    // exit haptics thread
    simulationFinished = true;
}
Exemple #11
0
void IsisMain(){

  UserInterface &ui = Application::GetUserInterface();

  ProcessByLine proc;
  Cube *cube = proc.SetInputCube("FROM");
  BigInt npixels(cube->Lines() * cube->Samples());
  
//  Initialize the cleaner routine
  try {
    delete iclean;
    iclean = new HiImageClean(*cube);
  } 
  catch (iException &ie) {
    std::string message = "Error attempting to initialize HiRISE cleaner object";
    throw (iException::Message(iException::Programmer,message,_FILEINFO_));
  }
  catch (...) {
    std::string message = "Unknown error occured attempting to initialize "
                          "HiRISE cleaner object";
    throw (iException::Message(iException::Programmer,message,_FILEINFO_));
  }

//  For IR10, channel 1 lets restrict the last 3100 lines of dark current
  PvlGroup &instrument = cube->GetGroup("Instrument");
  std::string ccd = (std::string) instrument["CcdId"];
  int channel = instrument["ChannelNumber"];
  if ((ccd == "IR10") && (channel  == 1)) {
    int bin = instrument["Summing"];
    int lastLine = cube->Lines() - ((3100/bin) + iclean->getFilterWidth()/2);
    if (lastLine > 1) { iclean->setLastGoodLine(lastLine); }
  }

#if defined(DEBUG)
  std::cout << "Lines: " << cube->Lines() << "   GoodLines: " 
            << iclean->getLastGoodLine() << std::endl;    
#endif

//  Get the output file reference for label update
  Cube *ocube = proc.SetOutputCube("TO");
  proc.StartProcess(cleanImage);
  iclean->propagateBlobs(ocube);
  proc.EndProcess();

//  Write statistics to file if requested
  if (ui.WasEntered("CLEANSTATS")) {
    std::string darkfile = ui.GetFilename("CLEANSTATS");
    std::ofstream dfile;
    dfile.open(darkfile.c_str(), std::ios::out | std::ios::trunc);
    dfile << *iclean;
    dfile.close();
  }

//  Dump stats to standard out
  Pvl p;
  PvlGroup grp;
  iclean->PvlImageStats(grp);
  p.AddGroup(grp);
  Application::Log(grp);
  BigInt nNulled = iclean->TotalNulled();

  delete iclean;
  iclean = 0;

// Check for calibration problems
  if (nNulled != 0) {
    double tpixels((double) nNulled / (double) npixels);
    std::ostringstream mess;
    mess << "There were " << nNulled << " of " << npixels << " ("
         << std::setw(6) << std::setprecision(2) << (tpixels * 100.0)
         << "%) due to insufficient calibration data (LUTTED or Gaps)" 
         << std::ends;
    throw (iException::Message(iException::Math,mess.str(),_FILEINFO_));
  }
}
void IsisMain() {

    // Use a regular Process
    Process p;

    // Get user parameters and error check
    UserInterface &ui = Application::GetUserInterface();
    QString from = ui.GetFileName("FROM");
    QString to = FileName(ui.GetFileName("TO")).expanded();
//TO DO: UNCOMMENT THIS LINE ONCE HRSC IS WORKING IN SS
//  double HRSCNadirCenterTime = ui.GetDouble("HRSC_NADIRCENTERTIME");

    // Open input cube and Make sure this is a lev1 image (ie, not map projected)
    Cube cube;
    cube.open(from);

    if (cube.isProjected()) {
        QString msg = "Input images is a map projected cube ... not a level 1 image";
        throw IException(IException::User, msg, _FILEINFO_);
    }

    // Initialize the camera
    Cube *input = p.SetInputCube("FROM");
    Pvl *cubeHeader = input->label();
    Camera *cam = input->camera();
    CameraDetectorMap *detectorMap = cam->DetectorMap();
    CameraFocalPlaneMap *focalMap = cam->FocalPlaneMap();
    CameraDistortionMap *distortionMap = cam->DistortionMap();
    CameraGroundMap *groundMap = cam->GroundMap();

    // Make sure the image contains the InstrumentPointing (aka CK) blob/table
    PvlGroup test = cube.label()->findGroup("Kernels", Pvl::Traverse);
    QString InstrumentPointing = (QString) test["InstrumentPointing"];
    if (InstrumentPointing != "Table") {
        QString msg = "Input image does not contain needed SPICE blobs...run spiceinit with attach=yes.";
        throw IException(IException::User, msg, _FILEINFO_);
    }

    // Open output line scanner keyword file
    ofstream toStrm;
    toStrm.open(to.toAscii().data(), ios::trunc);
    if (toStrm.bad()) {
        QString msg = "Unable to open output TO file";
        throw IException(IException::User, msg, _FILEINFO_);
    }

    // Get required keywords from instrument and band groups
    PvlGroup inst = cube.label()->findGroup("Instrument", Pvl::Traverse);
    QString instrumentId = (QString) inst["InstrumentId"];

    bool     isMocNA = false;
//TO DO: UNCOMMENT THIS LINES ONCE MOC IS WORKING IN SS
//  bool     isMocWARed = false;
    bool     isHiRise = false;
    bool     isCTX = false;
    bool     isLroNACL = false;
    bool     isLroNACR = false;
    bool     isHRSC = false;
//TO DO: UNCOMMENT THESE LINE ONCE MOC IS WORKING IN SS
//  if (instrumentId == "MOC") {
//    PvlGroup band = cube.label()->findGroup("BandBin", Pvl::Traverse);
//    QString filter = (QString) band["FilterName"];
//
//    if (strcmp(filter.toAscii().data(), "BROAD_BAND") == 0)
//      isMocNA = true;
//    else if (strcmp(filter.toAscii().data(), "RED") == 0)
//      isMocWARed = true;
//    else if (strcmp(filter.toAscii().data(), "BLUE") == 0) {
//      QString msg = "MOC WA Blue filter images not supported for Socet Set mapping";
//      throw IException(IException::User, msg, _FILEINFO_);
//    }
//  }
//  else if (instrumentId == "IdealCamera") {
//TO DO: DELETE THIS LINE ONCE MOC IS WORKING IN SS
    if (instrumentId == "IdealCamera") {
        PvlGroup orig = cube.label()->findGroup("OriginalInstrument",  Pvl::Traverse);
        QString origInstrumentId = (QString) orig["InstrumentId"];
        if (origInstrumentId == "HIRISE") {
            isHiRise = true;
        }
        else {
            QString msg = "Unsupported instrument: " + origInstrumentId;
            throw IException(IException::User, msg, _FILEINFO_);
        }
    }
    else if (instrumentId == "HIRISE") {
        isHiRise = true;
    }
    else if (instrumentId == "CTX") {
        isCTX = true;
    }
    else if (instrumentId == "NACL") {
        isLroNACL = true;
    }
    else if (instrumentId == "NACR") {
        isLroNACR = true;
    }
//TO DO: UNCOMMENT THIS LINE ONCE HRSC IS WORKING IN SS
//  else if (instrumentId == "HRSC") isHRSC = true;
    else {
        QString msg = "Unsupported instrument: " + instrumentId;
        throw IException(IException::User, msg, _FILEINFO_);
    }

    int ikCode = cam->naifIkCode();

    // Get Focal Length.
    // NOTE:
    //   For MOC Wide Angle, cam->focal_length returns the focal length
    //      in pixels, so we must convert from pixels to mm using the PIXEL_SIZE
    //      of 0.007 mm gotten from $ISIS3DATA/mgs/kernels/ik/moc20.ti.  (The
    //      PIXEL_PITCH value gotten from cam->PixelPitch is 1.0 since the
    //      focal length used by ISIS in this case is in pixels)
    //      For reference: the MOC WA blue filter pixel size needs an adjustment
    //      of 1.000452 (see p_scale in MocWideAngleDistortionMap.cpp), so that
    //      the final blue filter pixel size = (0.007 / 1.000452)
    //
    //   For all other cameras, cam->focal_length returns the focal
    //      length in mm, as needed by Socet Set

    double focal = cam->FocalLength();  // focal length returned in mm

//TO DO: UNCOMMENT THESE LINES ONCE HRSC and MOC IS WORKING IN SS
//  if (isMocWARed)
//    focal = focal * 0.007;  // pixel to mm conversion
//  else if (isHRSC)
//  {
//    switch (ikCode) {
//      case -41219:                   //S1: fwd stereo
//        focal = 184.88;
//        break;
//      case -41218:                   //IR: infra-red
//        focal = 181.57;
//        break;
//      case -41217:                   //P1: fwd photo
//        focal = 179.16;
//        break;
//      case -41216:                   // GREEN
//        focal = 175.31;
//        break;
//      case -41215:                   // NADIR
//        focal = 175.01;
//        break;
//      case -41214:                   // BLUE
//        focal = 175.53;
//        break;
//      case -41213:                   // P2: aft photo
//        focal = 179.19;
//        break;
//      case -41212:                   // RED
//        focal = 181.77;
//        break;
//      case -41211:                   // S2: aft stereo
//        focal = 184.88;
//        break;
//      default:
//        break;
//    }
//  }

    // Get instrument summing modes
    int csum = (int) detectorMap->SampleScaleFactor();
    int dsum = (int) detectorMap->LineScaleFactor();

    if (isLroNACL || isLroNACR || isHRSC)
        dsum = csum;

    // Calculate location of boresight in image space, these are zero-based values
    //
    // Note: For MOC NA, the boresight is at the image center
    //       For MOC WA, MRO HiRISE, MRO CTX, LRO_NACL, LRO_NACR and HRSC the
    //       boresight is not at the detector center, but the boresight is at the
    //       center of a NOPROJ'ED MRO HIRISE image

    // Get line/samp of boresight pixel in detector space (summing == 1)
    focalMap->SetFocalPlane(0.0, 0.0);
    double detectorBoresightSample = focalMap->DetectorSample();
    double detectorBoresightLine = focalMap->DetectorLine();

    // Convert sample of boresight pixel in detector into image space
    // (summing, etc., is accounted for.)
    detectorMap->SetDetector(detectorBoresightSample, detectorBoresightLine);
    double boresightSample = detectorMap->ParentSample();

    // Set Atmospheric correction coefficients to 0
    double atmco[4] = {0.0, 0.0, 0.0, 0.0};

    // Get totalLines, totalSamples and account for summed images
    int totalLines = cube.lineCount();
    int totalSamples = cube.sampleCount();

    // Get the Interval Time in seconds and calculate
    // scan duration in seconds
    double scanDuration = 0.0;
    double intTime = 0.0;

//TO DO: UNCOMMENT THESE LINES ONCE HRSC IS WORKING IN SS
//  int numIntTimes = 0.0;
//  vector<LineRateChange> lineRates;
//  if (isHRSC) {
//    numIntTimes = GetHRSCLineRates(&cube, lineRates, totalLines, HRSCNadirCenterTime);
//    if (numIntTimes == 1) {
//      LineRateChange lrc = lineRates.at(0);
//      intTime = lrc.GetLineScanRate();
//    }
//    if (numIntTimes <= 0) {
//      QString msg = "HRSC: Invalid number of scan times";
//      throw IException(IException::Programmer, msg, _FILEINFO_);
//    }
//    else
//      scanDuration = GetHRSCScanDuration(lineRates, totalLines);
//  }
//  else {
//
//  TO DO: indent the following two lines when HRSC is working in SS
    intTime = detectorMap->LineRate();  //LineRate is in seconds
    scanDuration = intTime * totalLines;
//TO DO: UNCOMMENT THIS LINE ONCE HRSC IS WORKING IN SS
//  }

    // For reference, this is the code if calculating interval time
    // via LineExposureDuration keyword off image labels:
    //
    // if (isMocNA || isMocWARed)
    //   intTime = exposureDuration * (double) dsum / 1000.0;
    // else if (isHiRise)
    //   intTime = exposureDuration * (double) dsum / 1000000.0;

    // Get along and cross scan pixel size for NA and WA sensors.
    // NOTE:
    //     1) The MOC WA pixel size is gotten from moc20.ti and is 7 microns
    //         HRSC pixel size is from the Instrument Addendum file
    //     2) For others, cam->PixelPitch() returns the pixel pitch (size) in mm.
    double alongScanPxSize = 0.0;
    double crossScanPxSize = 0.0;
//TO DO: UNCOMMENT THESE LINES ONCE MOC IS WORKING IN SS
//  if (isMocWARed || isHRSC) {
//    alongScanPxSize = csum * 0.007;
//    crossScanPxSize = dsum * 0.007;
//  }
//  else {
//
//  TO DO: indent the following 24 lines when HRSC is working in SS
    crossScanPxSize = dsum * cam->PixelPitch();

    // Get the ephemeris time, ground position and undistorted focal plane X
    // coordinate at the center line/samp of image
    cam->SetImage(cube.sampleCount() / 2.0, cube.lineCount() / 2.0);

    double tMid = cam->time().Et();

    const double latCenter = cam->UniversalLatitude();
    const double lonCenter = cam->UniversalLongitude();
    const double radiusCenter = cam->LocalRadius().meters();

    double uXCenter = distortionMap->UndistortedFocalPlaneX();

    // from the ground position at the image center, increment the ephemeris
    // time by the line rate and map the ground position into the sensor in
    // undistorted focal plane coordinates

    cam->setTime(iTime(tMid + intTime));
    double uX, uY;
    groundMap->GetXY(latCenter, lonCenter, radiusCenter, &uX, &uY);

    // the along scan pixel size is the difference in focal plane X coordinates
    alongScanPxSize = abs(uXCenter - uX);

//TO DO: UNCOMMENT THIS LINE ONCE MOC and HRSC IS WORKING IN SS
//  }

    // Now that we have totalLines, totalSamples, alongScanPxSize and
    // crossScanPxSize, fill the Interior Orientation Coefficient arrays
    double ioCoefLine[10];
    double ioCoefSample[10];
    for (int i = 0; i <= 9; i++) {
        ioCoefLine[i] = 0.0;
        ioCoefSample[i] = 0.0;
    }

    ioCoefLine[0] = totalLines / 2.0;
    ioCoefLine[1] = 1.0 / alongScanPxSize;

    ioCoefSample[0] = totalSamples / 2.0;
    ioCoefSample[2] = 1.0 / crossScanPxSize;

    // Update the Rectification Terms found in the base sensor class
    double rectificationTerms[6];
    rectificationTerms[0] = totalLines / 2.0;
    rectificationTerms[1] = 0.0;
    rectificationTerms[2] = 1.0;
    rectificationTerms[3] = totalSamples / 2.0;
    rectificationTerms[4] = 1.0;
    rectificationTerms[5] = 0.0;

    // Fill the triangulation parameters array
    double triParams[18];
    for (int i = 0; i <= 17; i++)
        triParams[i] = 0.0;

    triParams[15] = focal;

    // Set the Center Ground Point at the SOCET Set image, in radians
    double centerGp[3];
    double radii[3] = {0.0, 0.0, 0.0};
    Distance Dradii[3];

    cam->radii(Dradii);
    radii[0] = Dradii[0].kilometers();
    radii[1] = Dradii[1].kilometers();
    radii[2] = Dradii[2].kilometers();

    cam->SetImage(boresightSample, totalLines / 2.0);

    centerGp[0] = DEG2RAD *
                  TProjection::ToPlanetographic(cam->UniversalLatitude(), radii[0], radii[2]);
    centerGp[1] = DEG2RAD * TProjection::To180Domain(cam->UniversalLongitude());
    centerGp[2] = 0.0;
    //**** NOTE: in the import_pushbroom SOCET SET program, centerGp[2] will be set to the SS
    //**** project's gp_origin_z

    // Now get keyword values that depend on ephemeris data.

    // First get the ephemeris time and camera Lat Lon at image center line, boresight sample.
    double centerLine = double(totalLines) / 2.0;

    cam->SetImage(boresightSample, centerLine); //set to boresight of image
    double etCenter = cam->time().Et();

    // Get the sensor position at the image center in ographic lat,
    // +E lon domain 180 coordinates, radians, height in meters
    double sensorPosition[3] = {0.0, 0.0, 0.0};
    double ocentricLat, e360Lon;
    cam->subSpacecraftPoint(ocentricLat, e360Lon);
    sensorPosition[0] = DEG2RAD * TProjection::ToPlanetographic(ocentricLat, radii[0], radii[2]);
    sensorPosition[1] = DEG2RAD * TProjection::To180Domain(e360Lon);
    sensorPosition[2] = cam->SpacecraftAltitude() * 1000.0;

    // Build the ephem data.  If the image label contains the InstrumentPosition
    // table, use it as a guide for number and spacing of Ephem points.
    // Otherwise (i.e, for dejittered HiRISE images), the number and spacing of
    // ephem points based on hardcoded dtEphem value

    // Using the InstrumentPosition table as a guide build the ephem data
    QList< QList<double> > ephemPts;
    QList< QList<double> > ephemRates;

    PvlGroup kernels = cube.label()->findGroup("Kernels", Pvl::Traverse);
    QString InstrumentPosition = (QString) kernels["InstrumentPosition"];

    int numEphem = 0;      // number of ephemeris points
    double dtEphem = 0.0;  // delta time of ephemeris points, seconds
    if (InstrumentPosition == "Table") {
        // Labels contain SPK blob
        // set up Ephem pts/rates number and spacing
        Table tablePosition("InstrumentPosition", cubeHeader->fileName());
        numEphem = tablePosition.Records();

        // increase the number of ephem nodes by 20%.  This is somewhat random but
        // generally intended to compensate for having equally time spaced nodes
        // instead of of the potentially more efficient placement used by spiceinit
        numEphem = int(double(numEphem) * 1.2);

        // if numEphem calcutated from SPICE blobs is too sparse for SOCET Set,
        // mulitiply it by a factor of 30
        // (30X was settled upon emperically.  In the future, make this an input parameter)
        if (numEphem <= 10) numEphem = tablePosition.Records() * 30;

        // make the number of nodes odd
        numEphem  = (numEphem % 2) == 1 ? numEphem : numEphem + 1;

        // SOCET has a max number of ephem pts of 10000, and we're going to add twenty...
        if (numEphem > 10000 - 20) numEphem = 9979;

        dtEphem = scanDuration / double(numEphem);

        //build the tables of values
        double et = etCenter - (((numEphem - 1) / 2) * dtEphem);
        for (int i = 0; i < numEphem; i++) {
            cam->setTime(iTime(et));
            SpiceRotation *bodyRot = cam->bodyRotation();
            vector<double> pos = bodyRot->ReferenceVector(cam->instrumentPosition()->Coordinate());
//TO DO: UNCOMMENT THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
            //vector<double> vel = bodyRot->ReferenceVector(cam->instrumentPosition()->Velocity());

            //Add the ephemeris position and velocity to their respective lists, in meters and meters/sec
            QList<double> ephemPt;
            QList<double> ephemRate;
            ephemPts.append(ephemPt << pos[0] * 1000 << pos[1] * 1000 << pos[2] * 1000);
//TO DO: UNCOMMENT THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
            //ephemRates.append(ephemRate << vel[0] * 1000 << vel[1] * 1000 << vel[2] * 1000);

            et += dtEphem;
        }

//TO DO: WHEN VELOCITY BLOBS ARE CORRECT IN ISIS, linearlly interpolate 10 nodes rather than 11
//       (need 11 now for computation of velocity at first and last ephemeris point)
        // linearlly interpolate 11 additional nodes before line 1 (SOCET requires this)
        for (int i = 0; i < 11; i++) {
            double vec[3] = {0.0, 0.0, 0.0};
            vec[0] = ephemPts[0][0] + (ephemPts[0][0] - ephemPts[1][0]);
            vec[1] = ephemPts[0][1] + (ephemPts[0][1] - ephemPts[1][1]);
            vec[2] = ephemPts[0][2] + (ephemPts[0][2] - ephemPts[1][2]);
            QList<double> ephemPt;
            ephemPts.prepend (ephemPt << vec[0] << vec[1] << vec[2]);

//TO DO: UNCOMMENT THE FOLLOWING LINES WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
            //vec[0] = ephemRates[0][0] + (ephemRates[0][0] - ephemRates[1][0]);
            //vec[1] = ephemRates[0][1] + (ephemRates[0][1] - ephemRates[1][1]);
            //vec[2] = ephemRates[0][2] + (ephemRates[0][2] - ephemRates[1][2]);
            //QList<double> ephemRate;
            //ephemRates.prepend (ephemRate << vec[0] << vec[1] << vec[2]);
        }

//TO DO: WHEN VELOCITY BLOBS ARE CORRECT IN ISIS, linearlly interpolate 10 nodes rather than 11
//       (need 11 now for computation of velocity at first and last ephemeris point)
        // linearlly interpolate 11 additional nodes after the last line (SOCET requires this)
        for (int i = 0; i < 11; i++) {
            double vec[3] = {0.0, 0.0, 0.0};
            int index = ephemPts.size() - 1;
            vec[0] = ephemPts[index][0] + (ephemPts[index][0] - ephemPts[index - 1][0]);
            vec[1] = ephemPts[index][1] + (ephemPts[index][1] - ephemPts[index - 1][1]);
            vec[2] = ephemPts[index][2] + (ephemPts[index][2] - ephemPts[index - 1][2]);
            QList<double> ephemPt;
            ephemPts.append(ephemPt << vec[0] << vec[1] << vec[2]);

//TO DO: UNCOMMENT THE FOLLOWING LINES WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
            //vec[0] = ephemRates[index][0] + (ephemRates[index][0] - ephemRates[index - 1][0]);
            //vec[1] = ephemRates[index][1] + (ephemRates[index][1] - ephemRates[index - 1][1]);
            //vec[2] = ephemRates[index][2] + (ephemRates[index][2] - ephemRates[index - 1][2]);
            //QList<double> ephemRate;
            //ephemRates.append(ephemRate << vec[0] << vec[1] << vec[2]);
        }

        numEphem += 20;

//TO DO: DELETE THE FOLLOWING LINES WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
        // Compute the spacecraft velocity at each ephemeris point
        double deltaTime = 2.0 * dtEphem;
        for (int i = 0; i < numEphem; i++) {
            double vec[3] = {0.0, 0.0, 0.0};
            vec[0] = (ephemPts[i+2][0] - ephemPts[i][0]) / deltaTime;
            vec[1] = (ephemPts[i+2][1] - ephemPts[i][1]) / deltaTime;
            vec[2] = (ephemPts[i+2][2] - ephemPts[i][2]) / deltaTime;
            QList<double> ephemRate;
            ephemRates.append(ephemRate << vec[0] << vec[1] << vec[2]);
        }

    }
    else {
        // Calculate the number of ephemeris points that are needed, based on the
        // value of dtEphem (Delta-Time-Ephemeris).  SOCET SET needs the ephemeris
        // points to exceed the image range for interpolation.  For now, attempt a
        // padding of 10 ephemeris points on either side of the image.

        if (isMocNA || isHiRise || isCTX || isLroNACL || isLroNACR || isHRSC)
            // Try increment of every 300 image lines
            dtEphem = 300 * intTime;  // Make this a user definable increment?
        else // Set increment for WA images to one second
            dtEphem = 1.0;

        // Pad by 10 ephem pts on each side of the image
        numEphem = (int)(scanDuration / dtEphem) + 20;

        // if numEphem is even, make it odd so that the number of ephemeris points
        // is equal on either side of T_CENTER
        if ((numEphem % 2) == 0)
            numEphem++;

//TO DO: DELETE THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
        numEphem = numEphem + 2; // Add two for calcuation of velocity vectors...

        // Find the ephemeris time for the first ephemeris point, and from that, get
        // to_ephem needed by SOCET (to_ephem is relative to etCenter)
        double et = etCenter - (((numEphem - 1) / 2) * dtEphem);
        for (int i = 0; i < numEphem; i++) {
            cam->setTime(iTime(et));
            SpiceRotation *bodyRot = cam->bodyRotation();
            vector<double> pos = bodyRot->ReferenceVector(cam->instrumentPosition()->Coordinate());
//TO DO: UNCOMMENT THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
            //vector<double> vel = bodyRot->ReferenceVector(cam->instrumentPosition()->Velocity());

            //Add the ephemeris position and velocity to their respective lists, in meters and meters/sec
            QList<double> ephemPt;
            QList<double> ephemRate;
            ephemPts.append(ephemPt << pos[0] * 1000 << pos[1] * 1000 << pos[2] * 1000);
//TO DO: UNCOMMENT THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
            //ephemRates.append(ephemRate << vel[0] * 1000 << vel[1] * 1000 << vel[2] * 1000);

            et += dtEphem;
        }
//TO DO: DELETE THE FOLLOWING LINES WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
        // Compute the spacecraft velocity at each ephemeris point
        // (We must do this when blobs are not attached because the Spice Class
        // stores in memory the same data that would be in a blob...even when reading NAIF kernels)
        double deltaTime = 2.0 * dtEphem;
        numEphem = numEphem - 2; // set numEphem back to the number we need output
        for (int i = 0; i < numEphem; i++) {
            double vec[3] = {0.0, 0.0, 0.0};
            vec[0] = (ephemPts[i+2][0] - ephemPts[i][0]) / deltaTime;
            vec[1] = (ephemPts[i+2][1] - ephemPts[i][1]) / deltaTime;
            vec[2] = (ephemPts[i+2][2] - ephemPts[i][2]) / deltaTime;
            QList<double> ephemRate;
            ephemRates.append(ephemRate << vec[0] << vec[1] << vec[2]);
        }
    }

    //update ephem stats
    double etFirstEphem = etCenter - (((numEphem - 1) / 2) * dtEphem);
    double t0Ephem = etFirstEphem - etCenter;

    // Using the intrumentPointing table as a guide build the quarternions
    // for simplicity sake we'll leave the mountingAngles as identity
    // and store the complete rotation from body fixed to camera in the
    // quarternions

    //set up quaternions number and spacing
    Table tablePointing("InstrumentPointing", cubeHeader->fileName());

    //number of quaternions
    int numQuaternions = tablePointing.Records();

    // increase the number of quaternions nodes by 20%. This is somewhat random but
    // generally intended to compensate for having equally time spaced nodes
    // instead of of the potentially more efficient placement used by spiceinit
    numQuaternions = (int)(numQuaternions * 1.2);

    // if numQuaternions calcutated from SPICE blobs is too sparse for SOCET Set,
    // mulitiply it by a factor of 30
    // (30X was settled upon emperically.  In the future, make this an input parameter)
    if (numQuaternions <= 10) numQuaternions = tablePointing.Records() * 30;

    //make the number of nodes odd
    numQuaternions = (numQuaternions % 2) == 1 ? numQuaternions : numQuaternions + 1;

    // SOCET has a max number of quaternions of 20000, and we're going to add twenty...
    if (numQuaternions > 20000 - 20) numQuaternions = 19179;

    double dtQuat = scanDuration / double(numQuaternions);

    // build the tables of values
    QList< QList<double> > quaternions;
    double et = etCenter - (((numQuaternions - 1) / 2) * dtQuat);

    for (int i = 0; i < numQuaternions; i++) {
        cam->setTime(iTime(et));
        vector<double> j2000ToBodyFixedMatrixVector = cam->bodyRotation()->Matrix();
        vector<double> j2000ToCameraMatrixVector = cam->instrumentRotation()->Matrix();
        double quaternion[4] = {0.0, 0.0, 0.0, 0.0};

        double j2000ToBodyFixedRotationMatrix[3][3], //rotation from J2000 to target (aka body, planet)
               j2000ToCameraRotationMatrix[3][3], //rotation from J2000 to spacecraft
               cameraToBodyFixedRotationMatrix[3][3]; //rotation from camera to target

        // reformat vectors to 3x3 rotation matricies
        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
                j2000ToBodyFixedRotationMatrix[j][k] = j2000ToBodyFixedMatrixVector[3 * j + k];
                j2000ToCameraRotationMatrix[j][k] = j2000ToCameraMatrixVector[3 * j + k];
            }
        }

        // get the quaternion
        mxmt_c(j2000ToBodyFixedRotationMatrix, j2000ToCameraRotationMatrix,
               cameraToBodyFixedRotationMatrix);
        m2q_c(cameraToBodyFixedRotationMatrix, quaternion);

        // add the quaternion to the list of quaternions
        QList<double> quat;
        quaternions.append(quat << quaternion[1] << quaternion[2] << quaternion[3] <<
                           quaternion[0]);
        //note also that the order is changed to match socet

        et += dtQuat;
    }

    // linearlly interpolate 10 additional nodes before the first quaternion (SOCET requires this)
    for (int i = 0; i < 10; i++) {
        double vec[4] = {0.0, 0.0, 0.0, 0.0};
        vec[0] = quaternions[0][0] + (quaternions[0][0] - quaternions[1][0]);
        vec[1] = quaternions[0][1] + (quaternions[0][1] - quaternions[1][1]);
        vec[2] = quaternions[0][2] + (quaternions[0][2] - quaternions[1][2]);
        vec[3] = quaternions[0][3] + (quaternions[0][3] - quaternions[1][3]);
        QList<double> quat;
        quaternions.prepend (quat << vec[0] << vec[1] << vec[2] << vec[3]);
    }

    // linearlly interpolate 10 additional nodes after the last quaternion (SOCET requires this)
    for (int i = 0; i < 10; i++) {
        double vec[4] = {0.0, 0.0, 0.0, 0.0};
        int index = quaternions.size() - 1;
        vec[0] = quaternions[index][0] + (quaternions[index][0] - quaternions[index - 1][0]);
        vec[1] = quaternions[index][1] + (quaternions[index][1] - quaternions[index - 1][1]);
        vec[2] = quaternions[index][2] + (quaternions[index][2] - quaternions[index - 1][2]);
        vec[3] = quaternions[index][3] + (quaternions[index][3] - quaternions[index - 1][3]);
        QList<double> quat;
        quaternions.append(quat << vec[0] << vec[1] << vec[2] << vec[3]);
    }

    //update quaternions stats
    numQuaternions += 20;

    //ephemeris time of the first quarternion
    double et0Quat = etCenter - (((numQuaternions - 1) / 2) * dtQuat);

    //quadrtic time of the first quarternion
    double qt0Quat = et0Quat - etCenter;

    //query remaing transformation parameters from Camera Classes
    //transformation to distortionless focal plane
    double zDirection = distortionMap->ZDirection();

    //transformation from DistortionlessFocalPlane to FocalPlane
    vector<double> opticalDistCoefs = distortionMap->OpticalDistortionCoefficients();

    // For instruments with less than 3 distortion coefficients, set the
    // unused ones to 0.0
    opticalDistCoefs.resize(3, 0);

    //transformation from focal plane to detector
    const double *iTransS = focalMap->TransS();
    const double *iTransL = focalMap->TransL();
    double detectorSampleOrigin = focalMap->DetectorSampleOrigin();
    double detectorLineOrigin = focalMap->DetectorLineOrigin();

    //transformation from dectector to cube
    double startingSample = detectorMap->AdjustedStartingSample();
    double startingLine = detectorMap->AdjustedStartingLine();
    double sampleSumming = detectorMap->SampleScaleFactor();
    double etStart = ((LineScanCameraDetectorMap *)detectorMap)->StartTime();
    double lineOffset = focalMap->DetectorLineOffset();

    // We are done with computing keyword values, so output the Line Scanner
    // Keyword file.

    // This is the SOCET SET base sensor class keywords portion of support file:
    toStrm.setf(ios::scientific);
    toStrm << "RECTIFICATION_TERMS" << endl;
    toStrm << "        " << setprecision(14) << rectificationTerms[0] << " " <<
           rectificationTerms[1] << " " << rectificationTerms[2] << endl;
    toStrm << "        " << rectificationTerms[3] << " " << rectificationTerms[4] <<
           " " << rectificationTerms[5] << endl;

    toStrm << "GROUND_ZERO ";
    toStrm << centerGp[0] << " " << centerGp[1] << " " << centerGp[2] << endl;

    toStrm << "LOAD_PT ";
    toStrm << centerGp[0] << " " << centerGp[1] << " " << centerGp[2] << endl;

    toStrm << "COORD_SYSTEM 1" << endl;

    toStrm << "IMAGE_MOTION 0" << endl;

    // This is the line scanner sensor model portion of support file:
    toStrm << "SENSOR_TYPE USGSAstroLineScanner" << endl;
    toStrm << "SENSOR_MODE UNKNOWN" << endl;

    toStrm << "FOCAL " << focal << endl;

    toStrm << "ATMCO";
    for (int i = 0; i < 4; i++) toStrm << " " << atmco[i];
    toStrm << endl;

    toStrm << "IOCOEF_LINE";
    for (int i = 0; i < 10; i++) toStrm << " " << ioCoefLine[i];
    toStrm << endl;

    toStrm << "IOCOEF_SAMPLE";
    for (int i = 0; i < 10; i++) toStrm << " " << ioCoefSample[i];
    toStrm << endl;

    toStrm << "ABERR    0" << endl;
    toStrm << "ATMREF   0" << endl;
    toStrm << "PLATFORM   1" << endl;
    toStrm << "SOURCE_FLAG  1" << endl;
    toStrm << "SINGLE_EPHEMERIDE  0" << endl;

    //Note, for TRI_PARAMETERS, we print the first element separate from the rest so that the array
    //starts in the first column.  Otherwise, SOCET Set will treat the array as a comment
    toStrm << "TRI_PARAMETERS" << endl;
    toStrm << triParams[0];
    for (int i = 1; i < 18; i++) toStrm << " " << triParams[i];
    toStrm << endl;

    toStrm << setprecision(25) << "T_CENTER  ";
    double tCenter = 0.0;
//TO DO: UNCOMMENT THESE LINES ONCE HRSC IS WORKING IN SS
//  if (isHRSC) {
//    tCenter = etCenter - HRSCNadirCenterTime;
//    toStrm << tCenter << endl;
//  }
//  else
    toStrm << tCenter << endl;

    toStrm << "DT_EPHEM  " << dtEphem << endl;

    toStrm << "T0_EPHEM  ";
//TO DO: UNCOMMENT THESE LINES ONCE HRSC IS WORKING IN SS
//  if (isHRSC) {
//    double t = tCenter + t0Ephem;
//    toStrm << t << endl;
//  }
//  else
    toStrm << t0Ephem << endl;

    toStrm << "NUMBER_OF_EPHEM   " << numEphem << endl;

    toStrm << "EPHEM_PTS" << endl;
//TO DO: DELETE THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
    for (int i = 1; i <= numEphem; i++) {
//TO DO: UNCOMMENT THE FOLLOWING LINE WHEN VELOCITY BLOBS ARE CORRECT IN ISIS
        //for (int i = 0; i < numEphem; i++) {
        toStrm << " " << ephemPts[i][0];
        toStrm << " " << ephemPts[i][1];
        toStrm << " " << ephemPts[i][2] << endl;
    }

    toStrm  << "\n\nEPHEM_RATES" << endl;
    for (int i = 0; i < numEphem; i++) {
        toStrm << " " << ephemRates[i][0];
        toStrm << " " << ephemRates[i][1];
        toStrm << " " << ephemRates[i][2] << endl;
    }

    toStrm << "\n\nDT_QUAT " << dtQuat << endl;
    toStrm << "T0_QUAT " << qt0Quat << endl;
    toStrm << "NUMBER_OF_QUATERNIONS  " << numQuaternions << endl;
    toStrm << "QUATERNIONS" << endl;
    for (int i = 0; i < numQuaternions; i++) {
        toStrm << " " << quaternions[i][0];
        toStrm << " " << quaternions[i][1];
        toStrm << " " << quaternions[i][2];
        toStrm << " " << quaternions[i][3] << endl;
    }

    toStrm << "\n\nSCAN_DURATION " << scanDuration << endl;

    //  UNCOMMENT toStrm << "\nNUMBER_OF_INT_TIMES " << numIntTimes << endl;
    //
    //  if (isHRSC) {
    //    toStrm  << "INT_TIMES" << endl;
    //    for (int i = 0; i < numIntTimes; i++) {
    //      LineRateChange lr = lineRates.at(i);
    //      toStrm << " " << lr.GetStartEt();
    //      toStrm << " " << lr.GetLineScanRate();
    //      toStrm << " " << lr.GetStartLine() << endl;
    //    }
    //  }
    //  else
    toStrm << "INT_TIME " << intTime << endl;

    toStrm << "\nALONG_SCAN_PIXEL_SIZE  " << alongScanPxSize << endl;
    toStrm << "CROSS_SCAN_PIXEL_SIZE  " << crossScanPxSize << endl;

    toStrm << "\nCENTER_GP";
    for (int i = 0; i < 3; i++) toStrm << " " << centerGp[i];
    toStrm << endl;

    toStrm << "SENSOR_POSITION";
    for (int i = 0; i < 3; i++) toStrm << " " << sensorPosition[i];
    toStrm << endl;

    toStrm << "MOUNTING_ANGLES";
    double mountingAngles[3] = {0.0, 0.0, 0.0};
    for (int i = 0; i < 3; i++) toStrm << " " << mountingAngles[i];
    toStrm << endl;

    toStrm << "\nTOTAL_LINES " << totalLines << endl;
    toStrm << "TOTAL_SAMPLES " << totalSamples << endl;
    toStrm << "\n\n\n" << endl;

    toStrm << "IKCODE  " << ikCode << endl;
    toStrm << "ISIS_Z_DIRECTION  " << zDirection << endl;

    toStrm << "OPTICAL_DIST_COEF";
    for (int i = 0; i < 3; i++) toStrm << " " << opticalDistCoefs[i];
    toStrm << endl;

    toStrm << "ITRANSS";
    for (int i = 0; i < 3; i++) toStrm << " " << iTransS[i];
    toStrm << endl;

    toStrm << "ITRANSL";
    for (int i = 0; i < 3; i++) toStrm << " " << iTransL[i];
    toStrm << endl;

    toStrm << "DETECTOR_SAMPLE_ORIGIN " << detectorSampleOrigin << endl;
    toStrm << "DETECTOR_LINE_ORIGIN " << detectorLineOrigin << endl;
    toStrm << "DETECTOR_LINE_OFFSET  " << lineOffset << endl;
    toStrm << "DETECTOR_SAMPLE_SUMMING  " << sampleSumming << endl;

    toStrm << "STARTING_SAMPLE " << startingSample << endl;
    toStrm << "STARTING_LINE " << startingLine << endl;
    toStrm << "STARTING_EPHEMERIS_TIME " << setprecision(25) << etStart << endl;
    toStrm << "CENTER_EPHEMERIS_TIME " << etCenter << endl;

} // end main
Exemple #13
0
void IsisMain() {
  Process p;
  Cube *icube = p.SetInputCube("FROM");

  // Setup the histogram
  UserInterface &ui = Application::GetUserInterface();
  Histogram hist(*icube,1,p.Progress());
  if (ui.WasEntered("MINIMUM")) {
    hist.SetValidRange(ui.GetDouble("MINIMUM"),ui.GetDouble("MAXIMUM"));
  }
  if (ui.WasEntered("NBINS")) {
    hist.SetBins(ui.GetInteger("NBINS"));
  }

  // Loop and accumulate histogram
  p.Progress()->SetText("Gathering Histogram");
  p.Progress()->SetMaximumSteps(icube->Lines());
  p.Progress()->CheckStatus();
  LineManager line(*icube);
  for (int i=1; i<=icube->Lines(); i++) {
    line.SetLine(i);
    icube->Read(line);
    hist.AddData(line.DoubleBuffer(),line.size());
    p.Progress()->CheckStatus();
  }

  if(!ui.IsInteractive() || ui.WasEntered("TO")) {
    // Write the results

    if (!ui.WasEntered("TO")) {
      string msg = "The [TO] parameter must be entered";
      throw iException::Message(iException::User,msg,_FILEINFO_);
    }
    string outfile = ui.GetFilename("TO");
    ofstream fout;
    fout.open (outfile.c_str());
   
    fout << "Cube:           " << ui.GetFilename("FROM") << endl;
    fout << "Band:           " << icube->Bands() << endl;
    fout << "Average:        " << hist.Average() << endl;
    fout << "Std Deviation:  " << hist.StandardDeviation() << endl;
    fout << "Variance:       " << hist.Variance() << endl;
    fout << "Median:         " << hist.Median() << endl;
    fout << "Mode:           " << hist.Mode() << endl;
    fout << "Skew:           " << hist.Skew() << endl;
    fout << "Minimum:        " << hist.Minimum() << endl;
    fout << "Maximum:        " << hist.Maximum() << endl;
    fout << endl;
    fout << "Total Pixels:    " << hist.TotalPixels() << endl;
    fout << "Valid Pixels:    " << hist.ValidPixels() << endl;
    fout << "Null Pixels:     " << hist.NullPixels() << endl;
    fout << "Lis Pixels:      " << hist.LisPixels() << endl;
    fout << "Lrs Pixels:      " << hist.LrsPixels() << endl;
    fout << "His Pixels:      " << hist.HisPixels() << endl;
    fout << "Hrs Pixels:      " << hist.HrsPixels() << endl;
   
    //  Write histogram in tabular format
    fout << endl;
    fout << endl;
    fout << "DN,Pixels,CumulativePixels,Percent,CumulativePercent" << endl;
   
    Isis::BigInt total = 0;
    double cumpct = 0.0;
   
    for (int i=0; i<hist.Bins(); i++) {
      if (hist.BinCount(i) > 0) {
        total += hist.BinCount(i);
        double pct = (double)hist.BinCount(i) / hist.ValidPixels() * 100.;
        cumpct += pct;
   
        fout << hist.BinMiddle(i) << ",";
        fout << hist.BinCount(i) << ",";
        fout << total << ",";
        fout << pct << ",";
        fout << cumpct << endl;
      }
    }
    fout.close();
  }
  // If we are in gui mode, create a histogram plot
  if (ui.IsInteractive()) {
    // Set the title for the dialog
    string title;
    if (ui.WasEntered("TITLE")) {
      title = ui.GetString("TITLE");
    }
    else {
      title = "Histogram Plot for " + Filename(ui.GetAsString("FROM")).Name();
    }

    // Create the QHistogram, set the title & load the Isis::Histogram into it

    Qisis::HistogramToolWindow *plot = new Qisis::HistogramToolWindow(title.c_str(), ui.TheGui());

    // Set the xaxis title if they entered one
    if (ui.WasEntered("XAXIS")) {
      string xaxis(ui.GetString("XAXIS"));
      plot->setAxisLabel(QwtPlot::xBottom,xaxis.c_str());
    }

    // Set the yLeft axis title if they entered one
    if (ui.WasEntered("Y1AXIS")) {
      string yaxis(ui.GetString("Y1AXIS"));
      plot->setAxisLabel(QwtPlot::yLeft,yaxis.c_str());
    }

    // Set the yRight axis title if they entered one
    if (ui.WasEntered("Y2AXIS")) {
      string y2axis(ui.GetString("Y2AXIS"));
      plot->setAxisLabel(QwtPlot::yRight,y2axis.c_str());
    }

    //Transfer data from histogram to the plotcurve
    std::vector<double> xarray,yarray,y2array;
    double cumpct = 0.0;
    for (int i=0; i<hist.Bins(); i++) {
      if (hist.BinCount(i) > 0) {
        xarray.push_back(hist.BinMiddle(i));
        yarray.push_back(hist.BinCount(i));

        double pct = (double)hist.BinCount(i) / hist.ValidPixels() * 100.;
        cumpct += pct;
        y2array.push_back(cumpct);
      }
    }

    Qisis::HistogramItem *histCurve = new Qisis::HistogramItem();
    histCurve->setColor(Qt::darkCyan);
    histCurve->setTitle("Frequency");

    Qisis::PlotToolCurve *cdfCurve = new Qisis::PlotToolCurve();
    cdfCurve->setStyle(QwtPlotCurve::Lines);
    cdfCurve->setTitle("Percentage");

    QPen *pen = new QPen(Qt::red);
    pen->setWidth(2);
    histCurve->setYAxis(QwtPlot::yLeft);
    cdfCurve->setYAxis(QwtPlot::yRight);
    cdfCurve->setPen(*pen);

    //These are all variables needed in the following for loop.
    //----------------------------------------------
    QwtArray<QwtDoubleInterval> intervals(xarray.size());
    QwtArray<double> values(yarray.size());
    double maxYValue = DBL_MIN;
    double minYValue = DBL_MAX;
    // --------------------------------------------- 

    for(unsigned int y = 0; y < yarray.size(); y++) {

      intervals[y] = QwtDoubleInterval(xarray[y], xarray[y] + hist.BinSize());
  
      values[y] = yarray[y];  
      if(values[y] > maxYValue) maxYValue = values[y]; 
      if(values[y] < minYValue) minYValue = values[y];
    }
    
    histCurve->setData(QwtIntervalData(intervals, values));
    cdfCurve->setData(&xarray[0],&y2array[0],xarray.size());

    plot->add(histCurve);
    plot->add(cdfCurve);
    plot->fillTable();

    plot->setScale(QwtPlot::yLeft,0,maxYValue);
    plot->setScale(QwtPlot::xBottom,hist.Minimum(),hist.Maximum());

    QLabel *label = new QLabel("  Average = " + QString::number(hist.Average()) + '\n' +
    "\n  Minimum = " + QString::number(hist.Minimum()) + '\n' +
    "\n  Maximum = " + QString::number(hist.Maximum()) + '\n' +
    "\n  Stand. Dev.= " + QString::number(hist.StandardDeviation()) + '\n' +
    "\n  Variance = " + QString::number(hist.Variance()) + '\n' +
    "\n  Median = " + QString::number(hist.Median()) + '\n' +
    "\n  Mode = " + QString::number(hist.Mode()) +'\n' +
    "\n  Skew = " + QString::number(hist.Skew()), plot);
    plot->getDockWidget()->setWidget(label);
 
    plot->showWindow();
  }
  p.EndProcess();
}
Exemple #14
0
int main()
{
	Cube myCube;
	Face myFace1;
	Face myFace2;
	Face  myFace3;
	Face myFace4;
	Face  myFace5;
	Face  myFace6;
	Tile  r0c0;
	Tile r0c1;
	Tile r0c2;
	Tile r1c0;
	Tile r1c1;
	Tile r1c2;
	Tile r2c0;
	Tile r2c1;
	Tile r2c2;

	for(int i = 0; i < 6; i ++){
			/*string activeIndex = to_string(i);
			r0c0 = Tile(activeIndex);
			r0c1 =  Tile(activeIndex);
			r0c2 = Tile(activeIndex);
			r1c0 =  Tile(activeIndex);
			r1c1 = Tile(activeIndex);
			r1c2 =  Tile(activeIndex);
			r2c0 =  Tile(activeIndex);
			r2c1 =  Tile(activeIndex);
			r2c2 = Tile(activeIndex);*/

			if (i==0){
			r0c0 = Tile("G");
			r0c1 = Tile("G");
			r0c2 = Tile("G");
			r1c0 = Tile("G");
			r1c1 = Tile("G");
			r1c2 = Tile("G");
			r2c0 = Tile("G");
			r2c1 = Tile("G");
			r2c2 = Tile("G");
			}

			
			if (i==1){
			r0c0 = Tile("O");
			r0c1 = Tile("O");
			r0c2 = Tile("O");
			r1c0 = Tile("O");
			r1c1 = Tile("O");
			r1c2 = Tile("O");
			r2c0 = Tile("O");
			r2c1 = Tile("O");
			r2c2 = Tile("O");
			}

			
			if (i==2){
			r0c0 = Tile("Y");
			r0c1 = Tile("Y");
			r0c2 = Tile("Y");
			r1c0 = Tile("Y");
			r1c1 = Tile("Y");
			r1c2 = Tile("Y");
			r2c0 = Tile("Y");
			r2c1 = Tile("Y");
			r2c2 = Tile("Y");
			}

			
			if (i==3){
			r0c0 = Tile("R");
			r0c1 = Tile("R");
			r0c2 = Tile("R");
			r1c0 = Tile("R");
			r1c1 = Tile("R");
			r1c2 = Tile("R");
			r2c0 = Tile("R");
			r2c1 = Tile("R");
			r2c2 = Tile("R");
			}

			
			if (i==4){
			r0c0 = Tile("W");
			r0c1 = Tile("W");
			r0c2 = Tile("W");
			r1c0 = Tile("W");
			r1c1 = Tile("W");
			r1c2 = Tile("W");
			r2c0 = Tile("W");
			r2c1 = Tile("W");
			r2c2 = Tile("W");
			}

			
			if (i==5){
			r0c0 = Tile("B");
			r0c1 = Tile("B");
			r0c2 = Tile("B");
			r1c0 = Tile("B");
			r1c1 = Tile("B");
			r1c2 = Tile("B");
			r2c0 = Tile("B");
			r2c1 = Tile("B");
			r2c2 = Tile("B");
			}
			

			if(i == 0) myFace1 =  Face(r0c0, r0c1, r0c2, r1c0, r1c1, r1c2, r2c0, r2c1, r2c2);
			else if(i==1)myFace2 =  Face(r0c0, r0c1, r0c2, r1c0, r1c1, r1c2, r2c0, r2c1, r2c2);
			else if(i==2)myFace3 =  Face(r0c0, r0c1, r0c2, r1c0, r1c1, r1c2, r2c0, r2c1, r2c2);
			else if(i==3)myFace4 =  Face(r0c0, r0c1, r0c2, r1c0, r1c1, r1c2, r2c0, r2c1, r2c2);
			else if(i == 4)myFace5 =  Face(r0c0, r0c1, r0c2, r1c0, r1c1, r1c2, r2c0, r2c1, r2c2);
			else myFace6 = Face(r0c0, r0c1, r0c2, r1c0, r1c1, r1c2, r2c0, r2c1, r2c2);
		}
	
	myCube = Cube(myFace1, myFace2,myFace3,myFace4,myFace5,myFace6);
	bool cont = true;
	cout<<"1 - F, 2 - Fi, 3 - L, 4 - Li, 5 - R, 6 - Ri, \n 7 - U, 8 - Ui, 9 - D, 10 - Di, 11 - Print, 12 - RotateCW, \n 13 - RotateCCW, 14 - RotateFW, 15 - Rotate BW, 16 - RotateSideCCW, 17 - RotateSideCW 18 - Step1Move \n 19 - Step2Move 20 - Step3aMove 21 - Step3bMove 22 - Step4Move \n 23 - Step5Move 24 - Step6Move 25 - Solve Top, 26 - Solve Cube, 27 - Exit 28 - Print Instructions\n";
	while(cont){
	int k; cin>>k;
	//if(k == 1) myCube.spinF();
	//if(k == 2) myCube.spinFi();
	//if(k == 3) myCube.spinL();
	//if(k == 4) myCube.spinLi();
	//if(k == 5) myCube.spinR();
	//if(k == 6) myCube.spinRi();
	//if(k == 7) myCube.spinT();
	//if(k == 8) myCube.spinTi();
	//if(k == 9) myCube.spinD();
	//if(k == 10) myCube.spinDi();
	//if(k == 11) myCube.printCube();
	//if(k == 12) myCube.setTop(4);
	//if(k == 13) myCube.setTop(2);
	//if(k == 14) myCube.setTop(1);
	//if(k == 15) myCube.setTop(3);
	//else if (k==16) cont = false;

	// printCube with each action for testing purposes

	if(k == 1) {myCube.spinF(); myCube.printCube();}
	if(k == 2) {myCube.spinFi(); myCube.printCube();}
	if(k == 3) {myCube.spinL(); myCube.printCube();}
	if(k == 4) {myCube.spinLi(); myCube.printCube();}
	if(k == 5) {myCube.spinR(); myCube.printCube();}
	if(k == 6) {myCube.spinRi(); myCube.printCube();}
	if(k == 7) {myCube.spinU(); myCube.printCube();}
	if(k == 8) {myCube.spinUi(); myCube.printCube();}
	if(k == 9) {myCube.spinD(); myCube.printCube();}
	if(k == 10) {myCube.spinDi(); myCube.printCube();}
	if(k == 11) myCube.printCube(); 
	if(k == 12) {myCube.setTop(4); myCube.printCube();}
	if(k == 13) {myCube.setTop(2); myCube.printCube();}
	if(k == 14) {myCube.setTop(1); myCube.printCube();}
	if(k == 15) {myCube.setTop(3); myCube.printCube();}
	if(k == 16) {myCube.rotate(2); myCube.printCube();}
	if(k == 17) {myCube.rotate(1); myCube.printCube();}
	if(k == 18) {myCube.step1Move(); myCube.printCube();}
	if(k == 19) {myCube.step2Move(); myCube.printCube();}
	if(k == 20) {myCube.step3aMove(); myCube.printCube();}
	if(k == 21) {myCube.step3bMove(); myCube.printCube();}
	if(k == 22) {myCube.step4Move(); myCube.printCube();}
	if(k == 23) {myCube.step5Move(); myCube.printCube();}
	if(k == 24) {myCube.step6Move(); myCube.printCube();}
	if(k == 25) {myCube.solveTop(); myCube.printCube();}
	if(k == 26) {myCube.solveCube(); myCube.printCube();}
	if(k == 28) myCube.printVector();
	else if(k==27) cont = false;
	}
	system("pause");
	return 0;
	}
Exemple #15
0
int main(int argc, char *argv[])
{
	GLfloat ambient[]         = {0.5,0.5,0.5,1.0};					// default ambient color for all light sources

	glutInit(&argc, argv);											// initialize GLUT
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);		// open an OpenGL context with double buffering, RGB colors, and depth buffering
	glutInitWindowSize(512, 512);									// set initial window size
	glutCreateWindow("Final Project");								// open window and set window title
	if (is_fullscreen)
		glutFullScreen();

	glEnable(GL_NORMALIZE);
	glEnable(GL_DEPTH_TEST);										// enable z-buffer
	glClearColor(0.0, 0.0, 0.0, 0.0);								// set clear color to black

	glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);				// set the default ambient color
	glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);		// allow glColor to set ambient and diffuse colors of geometry

	// Generate light source:
	glEnable(GL_LIGHTING);											// enables lighting; this changes the behavior of glColor
	glEnable(GL_LIGHT0);											// enable a light source; otherwise you will only see ambient light
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	glDisable(GL_TEXTURE_2D);

	glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
	glLightfv(GL_LIGHT0, GL_SPECULAR, light0_specular);
	glLightfv(GL_LIGHT0, GL_SHININESS, light0_shininess);
	glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
	
	// Install callback functions:
	glutDisplayFunc(window::displayCallback);
	glutReshapeFunc(window::reshapeCallback);
	glutIdleFunc(window::idleCallback);

	glutMouseFunc(processMouse);
	glutMotionFunc(processMotion);
	glutKeyboardFunc(keyDown);
	glutKeyboardUpFunc(keyUp);

	// Initialize cube matrix:
	character.getMatrix().identity();
	all.getMatrix().identity();
	cube.getMatrix().identity();
	cube1.getMatrix().identity();
	cube2.getMatrix().identity();
	dragon.getMatrix().identity();
	base.getMatrix().identity();
	temp.getMatrix().identity();
	world.getMatrix().identity();
	terrain.getMatrix().identity();
	rotation.getMatrix().identity();

	// Shaders
	shader = new Shader(toon_vert,toon_frag,true);
	camera.lookAt(p,l,up);

	cout << "Loading .obj files" << endl;
	objReader.readObj("cow.obj", nVerts, &vertices, &normals, &texcoords, nIndices, &indices);

	cout << "Loading texture files" << endl;
	loadTexture(texture_array,"desert_front.ppm", SKYFRONT);
	loadTexture(texture_array,"desert_back.ppm", SKYBACK);
	loadTexture(texture_array,"desert_left.ppm", SKYLEFT);
	loadTexture(texture_array,"desert_right.ppm", SKYRIGHT);
	loadTexture(texture_array,"desert_top.ppm", SKYUP);

	cout << "Generating terrain1" << endl;
	TerrainHelper th1;
	th1.terrainLoad(800,800,1);
	th1.terrainScale(0,TERRAIN_ONE_HEIGHT);
	TERRAIN_ONE_ID = th1.terrainCreateDL(0,0,0);

	cout << "Generating terrain2" << endl;
	TerrainHelper th2;
	th2.terrainLoad(800,800,1);
	th2.terrainScale(0, TERRAIN_TWO_HEIGHT);
	TERRAIN_TWO_ID = th2.terrainCreateDL(0,0,0);

	cout << "Generating terrain3" << endl;
	TerrainHelper th3;
	th3.terrainLoad(800, 800,1);
	th3.terrainScale(0,TERRAIN_THREE_HEIGHT);
	TERRAIN_THREE_ID = th3.terrainCreateDL(0,0,0);

	CURRENT_TERRAIN_ID = TERRAIN_ONE_ID;

	cout << "Creating world" << endl;
	createWorld();

	//cout << "initializing particles" << endl;
	//initParticles(0.0,0.0,0.0);

	glutMainLoop();
	return 0;
}
Exemple #16
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
				   LPSTR, int )
{
	HANDLE ghInstance;
	WNDCLASS wcex;
	HWND hwnd;
	TCHAR WindowTitle[] = _T("Cube");
    TCHAR WindowClassName[] = _T("AppClass");
	if (!hPrevInstance)
	{
		wcex.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW;
		wcex.lpfnWndProc = WndProc;
		wcex.lpszClassName = WindowClassName;
		wcex.hInstance = hInstance;
		wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
		wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
		wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName = 0;
		wcex.cbClsExtra = 0;
		wcex.cbWndExtra = 0;

		if (!RegisterClass(&wcex))
			return 0;
	}

	ghInstance = hInstance;

	if (NULL==(hwnd = CreateWindow(WindowClassName, WindowTitle, 
		WS_CAPTION | WS_SYSMENU,			
		CW_USEDEFAULT, 0, WIDTH, HEIGHT, 
		NULL, NULL, hInstance, NULL)))
	{
		return 0;
	}
	if (SUCCEEDED(cube.device.InitialDirect3D(hwnd)))
	{
		if (SUCCEEDED(cube.InitialObject()))
		{
			if (SUCCEEDED(cube.device.shader.InitialShader()))
			 {	   
				ShowWindow(hwnd, SW_SHOWDEFAULT);
				UpdateWindow(hwnd);
				MSG msg;
				ZeroMemory(&msg, sizeof(msg));
				while (WM_QUIT!=msg.message)
				{
					if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
					{
						TranslateMessage(&msg);
						DispatchMessage(&msg);
					}
					 else
					{
						cube.Draw();
					}
				}
			}
		}
	}
	return 0;
}
Exemple #17
0
void processMotion(int x, int y)
{
	xf = (float)x/((float)window::width/2.0) - 1;
	yf = 1 - (float)y/((float)window::height/2.0);
	if (pressedLeft)
	{
		zf = findZ(xf,yf);
		Vector3 prev = Vector3(prevX,prevY,prevZ);
		Vector3 curr = Vector3(xf,yf,zf);
		
		Vector3 p = prev.normalize();
		Vector3 c = curr.normalize();
		prev.set(p.get(0), p.get(1), p.get(2));
		curr.set(c.get(0), c.get(1), c.get(2));

		theta = getTheta(prev, curr);
		Vector3 axis3 = prev.cross(prev, curr);
		Vector3 a = axis3.normalize();
		axis3.set(a.get(0), a.get(1), a.get(2));

		Vector4 axis4 = Vector4(axis3.get(0), axis3.get(1), axis3.get(2), 0);

		temp.getMatrix().setMatrix(temp.getMatrix().rotateAA(axis4,theta));
	}
	else if (pressedMiddle)
	{
		temp.getMatrix().identity();
		temp.getMatrix().setMatrix(temp.getMatrix().translate((xf-prevX)*15,(yf-prevY)*15,0));
	}
	else if (pressedRight)
	{
		float s;
		if (prevY < yf)
		{
			s = 1-(yf-prevY)*-2;
			temp.getMatrix().identity();
			temp.getMatrix().setMatrix(temp.getMatrix().scale(s,s,s));
		}
		else
		{
			float s = 1+(yf-prevY)*0.5;
			if (s < 0)
			{
				s = 0.0001;
			}
			temp.getMatrix().identity();
			temp.getMatrix().setMatrix(temp.getMatrix().scale(s,s,s));
		}
	}
}
void init()
{

	glClearColor(1.0,1.0,1.0,0.0);						//sets the clear colour to yellow
					//glClear(GL_COLOR_BUFFER_BIT) in the display function//will clear the buffer to this colour.

	// Shaders
	if(!myShader.load("BasicView", "glslfiles/basicTransformations.vert", "glslfiles/basicTransformations.frag"))
	{
		cout << "failed to load shader" << endl;
	}							
	if (!cubeShader.load("BasicView", "glslfiles/cubeShader.vert", "glslfiles/cubeShader.frag"))
	{
		cout << "failed to load shader" << endl;
	}
	cubeOne.setDim(15);
	cubeOne.constructGeometry(&cubeShader);
	worldCube.setDim(1000);
	worldCube.constructGeometry(&cubeShader);

	glEnable(GL_TEXTURE_2D);

	
	copter.loadModel(myShader);
	prop.loadModel(myShader);
	world.loadModel(myShader);
	ground.loadModel(myShader);
	houseOne.loadModel(myShader, "TestModels/dododododhouse2.obj", glm::vec3(50, 44, 50), 
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 0);
	houseTwo.loadModel(myShader, "TestModels/pyramidhouse2.obj", glm::vec3(-1250, 44, 1000),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 0);
	houseThree.loadModel(myShader, "TestModels/pyramidhouse2.obj", glm::vec3(-500, 44, -500),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 0);
	houseFour.loadModel(myShader, "TestModels/pyramidhouse2.obj", glm::vec3(1200, 44, 1200),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 0);
	houseFive.loadModel(myShader, "TestModels/dododododhouse2.obj", glm::vec3(50, 44, -1150),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 0);
	houseSix.loadModel(myShader, "TestModels/dododododhouse2.obj", glm::vec3(-900, 44, -500),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 0);
	treeOne.loadModel(myShader, "TestModels/tree.obj", glm::vec3(250, 20, 250),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeTwo.loadModel(myShader, "TestModels/tree.obj", glm::vec3(350, 20, 250),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeThree.loadModel(myShader, "TestModels/tree.obj", glm::vec3(300, 20, 250),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeFour.loadModel(myShader, "TestModels/tree.obj", glm::vec3(0, 20, 750),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeFive.loadModel(myShader, "TestModels/tree.obj", glm::vec3(200, 20, 180),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeOne.loadModel(myShader, "TestModels/tree.obj", glm::vec3(-900, 20, 580),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeTwo.loadModel(myShader, "TestModels/tree.obj", glm::vec3(1040, 20, 1050),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeThree.loadModel(myShader, "TestModels/tree.obj", glm::vec3(-1260, 20, -250),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeFour.loadModel(myShader, "TestModels/tree.obj", glm::vec3(1270, 20, 250),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	treeFive.loadModel(myShader, "TestModels/tree.obj", glm::vec3(-230, 20, 250),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	leafOne.loadModel(myShader, "TestModels/leaf.obj", glm::vec3(150, -10, 580),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	leafTwo.loadModel(myShader, "TestModels/leaf.obj", glm::vec3(170, -10, 530),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	leafThree.loadModel(myShader, "TestModels/leaf.obj", glm::vec3(150, -10, 550),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	leafFour.loadModel(myShader, "TestModels/leaf.obj", glm::vec3(150, -10, 510),
		glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, glm::vec4{ 0.8, 0.8, 0.8, 1.0 }, 50);
	
	houses.push_back(houseOne);
	houses.push_back(houseTwo);
	houses.push_back(houseThree);
	houses.push_back(houseFour);
	houses.push_back(houseFive);
	houses.push_back(houseSix);
	trees.push_back(treeOne);
	trees.push_back(treeTwo);
	trees.push_back(treeThree);
	trees.push_back(treeFour);
	trees.push_back(treeFive);
	trees.push_back(treeSix);
	trees.push_back(treeSeven);
	trees.push_back(treeEight);
	trees.push_back(treeNine);
	trees.push_back(treeTen);
	leafs.push_back(leafOne);
	leafs.push_back(leafTwo);
	leafs.push_back(leafThree);
	leafs.push_back(leafFour);
	glEnable(GL_DEPTH_TEST);

	
}
Exemple #19
0
void keyDown(unsigned char key, int x, int y) {
	Vector3 v;
	switch (key)
	{
		case ' ':
			if (!jump)
			{
				j_x = j_start;
				jump = true;
			}
			break;
		case 'w':
			keys[W] = true;
			break;
		case 's':
			keys[S] = true;
			break;
		case 'a':
			keys[A] = true;
			break;
		case 'd':
			keys[D] = true;
			break;
		case 'v':
			toggle_view = !toggle_view;
			if (toggle_view)
			{
				v = Vector3(0,10,5);
				camera.lookAt(v,l,up);
				camera.getE().print();
				camera.getMatrix().print();
			}
			else
			{
				camera.lookAt(p,l,up);
				camera.getE().print();
				camera.getMatrix().print();
			}
			break;
		/*case '1':
			light0Toggle = !light0Toggle;
			if (light0Toggle)
				glEnable(GL_LIGHT0);
			else
				glDisable(GL_LIGHT0);
			break;*/
		case 'r':
			toggle_rage = !toggle_rage;
			rage_count = 0;
			break;
		case 'p':
			world.getMatrix().identity();
			break;
		case 'h':
			toggle_shader = !toggle_shader;
			break;
		case 't':
			toggle_texture = !toggle_texture;
			if (toggle_texture)
				glEnable(GL_TEXTURE_2D);
			else
				glDisable(GL_TEXTURE_2D);
			break;
		case 'f':
			is_fullscreen = !is_fullscreen;
			if (is_fullscreen)
				glutFullScreen();
			else
				glutReshapeWindow(512, 512);
			break;
		case 'u':
			debug = !debug;
			break;
		case '1':
			CURRENT_TERRAIN_ID = TERRAIN_ONE_ID;
			//CURRENT_TERRAIN_HEIGHT = 2;
			break;
		case '2':
			CURRENT_TERRAIN_ID = TERRAIN_TWO_ID;
			//CURRENT_TERRAIN_HEIGHT = 2;
			break;
		case '3':
			CURRENT_TERRAIN_ID = TERRAIN_THREE_ID;
			//CURRENT_TERRAIN_HEIGHT = 2;
			break;
		case 27:
			//if (shader)
			//	delete shader;
			//glDeleteLists(terrainListID, 1);
			exit(0);
			break;
	}
}
Exemple #20
0
void IsisMain() {
  Process p;
  Cube *icube = p.SetInputCube("FROM");
  Camera *cam = icube->camera();

  UserInterface &ui = Application::GetUserInterface();

  QString from = ui.GetFileName("FROM");
  int sinc = ui.GetInteger("SINC");
  int linc = ui.GetInteger("LINC");
  CameraStatistics camStats(cam, sinc, linc, from);

  // Send the Output to the log area
  Pvl statsPvl = camStats.toPvl();
  for (int i = 0; i < statsPvl.groups(); i++) {
    Application::Log(statsPvl.group(i));
  }

  if(ui.WasEntered("TO")) {
    QString outfile = FileName(ui.GetFileName("TO")).expanded();
    bool exists = FileName(outfile).fileExists();
    bool append = ui.GetBoolean("APPEND");

    // If the user chose a format of PVL, then write to the output file ("TO")
    if(ui.GetString("FORMAT") == "PVL") {
      (append) ? statsPvl.append(outfile) : statsPvl.write(outfile);
    }
    else {
      // Create a flatfile of the data with columhn headings the flatfile is
      // comma-delimited and can be imported in to spreadsheets
      ofstream os;
      bool writeHeader = true;
      if(append) {
        os.open(outfile.toAscii().data(), ios::app);
        if(exists) {
          writeHeader = false;
        }
      }
      else {
        os.open(outfile.toAscii().data(), ios::out);
      }

      // if new file or append and no file exists then write header
      if(writeHeader) {
        os << "Filename," <<
           "LatitudeMinimum," <<
           "LatitudeMaximum," <<
           "LatitudeAverage," <<
           "LatitudeStandardDeviation," <<
           "LongitudeMinimum," <<
           "LongitudeMaximum," <<
           "LongitudeAverage," <<
           "LongitudeStandardDeviation," <<
           "SampleResolutionMinimum," <<
           "SampleResolutionMaximum," <<
           "SampleResolutionAverage," <<
           "SampleResolutionStandardDeviation," <<
           "LineResolutionMinimum," <<
           "LineResolutionMaximum," <<
           "LineResolutionAverage," <<
           "LineResolutionStandardDeviation," <<
           "ResolutionMinimum," <<
           "ResolutionMaximum," <<
           "ResolutionAverage," <<
           "ResolutionStandardDeviation," <<
           "AspectRatioMinimum," <<
           "AspectRatioMaximum," <<
           "AspectRatioAverage," <<
           "AspectRatioStandardDeviation," <<
           "PhaseMinimum," <<
           "PhaseMaximum," <<
           "PhaseAverage," <<
           "PhaseStandardDeviation," <<
           "EmissionMinimum," <<
           "EmissionMaximum," <<
           "EmissionAverage," <<
           "EmissionStandardDeviation," <<
           "IncidenceMinimum," <<
           "IncidenceMaximum," <<
           "IncidenceAverage," <<
           "IncidenceStandardDeviation," <<
           "LocalSolarTimeMinimum," <<
           "LocalSolarTimeMaximum," <<
           "LocalSolarTimeAverage," <<
           "LocalSolarTimeStandardDeviation," <<
           "LocalRadiusMaximum," <<
           "LocalRadiusMaximum," <<
           "LocalRadiusAverage," <<
           "LocalRadiusStandardDeviation," <<
           "NorthAzimuthMinimum," <<
           "NorthAzimuthMaximum," <<
           "NorthAzimuthAverage," <<
           "NorthAzimuthStandardDeviation," << endl;
      }
      os << FileName(from).expanded() << ",";
      //call the function to write out the values for each group
      writeFlat(os, camStats.getLatStat());
      writeFlat(os, camStats.getLonStat());
      writeFlat(os, camStats.getSampleResStat());
      writeFlat(os, camStats.getLineResStat());
      writeFlat(os, camStats.getResStat());
      writeFlat(os, camStats.getAspectRatioStat());
      writeFlat(os, camStats.getPhaseStat());
      writeFlat(os, camStats.getEmissionStat());
      writeFlat(os, camStats.getIncidenceStat());
      writeFlat(os, camStats.getLocalSolarTimeStat());
      writeFlat(os, camStats.getLocalRaduisStat());
      writeFlat(os, camStats.getNorthAzimuthStat());
      os << endl;
    }
  }

  if(ui.GetBoolean("ATTACH")) {

    QString cam_name = "CameraStatistics";

    //Creates new CameraStatistics Table
    TableField fname("Name", Isis::TableField::Text, 20);
    TableField fmin("Minimum", Isis::TableField::Double);
    TableField fmax("Maximum", Isis::TableField::Double);
    TableField favg("Average", Isis::TableField::Double);
    TableField fstd("StandardDeviation", Isis::TableField::Double);

    TableRecord record;
    record += fname;
    record += fmin;
    record += fmax;
    record += favg;
    record += fstd;

    Table table(cam_name, record);

    // Place all the gathered camera statistics in a table and attach it to the
    // cube. Skip "User Parameters" group.
    for (int i = 1; i < statsPvl.groups(); i++) {
      PvlGroup &group = statsPvl.group(i);

      int entry = 0;
      record[entry] = group.name();
      entry++;
      for (int j = 0; j < group.keywords(); j++) {
        record[entry] = toDouble(group[j][0]);
        entry++;
      }
      table += record;
    }

    icube->reopen("rw");
    icube->write(table);
    p.WriteHistory(*icube);
    icube->close();
  }
}
Exemple #21
0
//----------------------------------------------------------------------------
// Callback method called when window readraw is necessary or
// when glutPostRedisplay() was called.
void window::displayCallback(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // clear color and depth buffers

	//cout << *(world.getMatrix().getPointer() + 12) << " and " << *(world.getMatrix().getPointer() + 13) << " and " << *(world.getMatrix().getPointer() + 14) << endl;

	if (toggle_rage && !insideWorld(world.getMatrix()) && !jump)
	{
		world.getMatrix().identity();
	}
	else
	{
		processMovement();
	}

	camera.inverseCamera();
	glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
	glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
	glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse_character);

	// CHARACTER
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	cube.getMatrix().identity();
	all.getMatrix().setMatrix(cube.getMatrix().rotateY(PI/2));
	all.getMatrix().setMatrix(all.getMatrix().multiply(camera.getMatrix())); // YOU
	glLoadMatrixf(all.getMatrix().getPointer());
	if (toggle_rage)
		glColor3f(1.0,0.0,0.0);
	else
		glColor3f(0.0,0.0,1.0);
	glutSolidSphere(2,30,30);
	if (debug)
	{
		glColor3f(1.0,0.0,0.0);
		glutWireCube(3.6);
	}
	drawFPS();
	glDisable(GL_LIGHTING);
	glDisable(GL_LIGHT0);

	//glLoadIdentity();
	//updateParticles();
	//drawParticles();

	glLoadMatrixf(world.getMatrix().getPointer());
	Draw_Skybox(0,150,0,800,800,800);
	if (!toggle_rage) glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
	else glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse_rage);
	glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
	glPushMatrix();
	glTranslatef(0, -CURRENT_TERRAIN_HEIGHT, 0);
	glCallList(CURRENT_TERRAIN_ID);
	glPopMatrix();

	glDisable(GL_LIGHTING);
	light0.getMatrix().identity();
	light0.getMatrix().setMatrix(light0.getMatrix().translate(light0_position[0],light0_position[1],light0_position[2]));
	all.getMatrix().setMatrix(light0.getMatrix());
	all.getMatrix().setMatrix(all.getMatrix().multiply(world.getMatrix()));
	glLoadMatrixf(all.getMatrix().getPointer());
	glColor3f(1.0,1.0,1.0);
	glutSolidSphere(1.0,20,20);
	glEnable(GL_LIGHTING);

	// WORLD
	glEnable(GL_LIGHTING);
	if (toggle_shader) shader->bind();
	g_world->draw(world.getMatrix());
	if (toggle_shader) shader->unbind();
	glDisable(GL_LIGHTING);

	glutSwapBuffers();
}
Exemple #22
0
void View::calculateView(boost::shared_ptr<VIEW_AREA> view_area)
{
	stringstream subsets_str, axes_str, req_str;
	Database db = (*m_Server)[view_area->database];
	DIMENSION_LIST dims;
	UINT cubeId = (UINT)-1;
	if (!view_area->cube.empty()) {
		Cube cube = db.cube[view_area->cube];
		dims = cube.getCacheData().dimensions;
		cubeId = cube.getCacheData().cube;
	}
	view_area->calc.reset(new VIEW_CALC);
	view_area->calc->virt = false;
	view_area->calc->dimonaxis.resize(dims.size());
	view_area->calc->axes.resize(view_area->axes.size());
	{
		for (size_t axit = 0; axit < view_area->axes.size(); ++axit) {
			if (axit) {
				axes_str << "$";
			}
			if (!view_area->axes[axit].first.empty()) {
				boost::shared_ptr<VIEW_AXIS> axe = view_area->axes[axit].second;
				if (util::UTF8Comparer::compare(axe->database, view_area->database)) {
					string descr = "Databases differ.";
					LibPaloNGExceptionFactory::raise(LibPaloNGExceptionFactory::PALO_NG_ERROR_WRONG_PARAMETER, &descr);
				}
				axes_str << axe->ser_str;
				for (size_t subit = 0; subit < axe->as.size(); ++subit) {
					boost::shared_ptr<VIEW_SUBSET> sub = axe->as[subit].sub;
					if (util::UTF8Comparer::compare(sub->database, view_area->database)) {
						string descr = "Databases differ.";
						LibPaloNGExceptionFactory::raise(LibPaloNGExceptionFactory::PALO_NG_ERROR_WRONG_PARAMETER, &descr);
					}
					if (!subsets_str.str().empty()) {
						subsets_str << "$";
					}
					subsets_str << axe->as[subit].subsetHandle << ";" << sub->ser_str;
					Dimension d = (*m_Server)[axe->database].dimension[sub->dimension];
					size_t i;
					for (i = 0; i < dims.size(); ++i) {
						if (dims[i] == d.getCacheData().dimension) {
							view_area->calc->dimonaxis[i] = make_pair(axit, subit);
							view_area->calc->dim2axis[d.getCacheData().ndimension] = i;
							break;
						}
					}
					if (!dims.empty() && i == dims.size()) {
						stringstream str;
						str << "Dimension not in cube. Dimension: " << sub->dimension << " Cube: " << view_area->cube;
						string descr = str.str();
						LibPaloNGExceptionFactory::raise(LibPaloNGExceptionFactory::PALO_NG_ERROR_WRONG_PARAMETER, &descr);
					}
					if (d.getCacheData().type == DIMENSION_INFO::SYSTEM_ID) {
						view_area->calc->virt = true;
					}
				}
				boost::shared_ptr<VIEW_CALC_AXIS> cl(new VIEW_CALC_AXIS);
				view_area->calc->axes[axit] = cl;
				cl->nameIndex.resize(axe->as.size());
			}
		}
	}
	req_str << "database=" << db.getCacheData().database << "&view_subsets=" << subsets_str.str() << "&view_axes=" << axes_str.str() << "&view_area=" << view_area->ser_str;
	if (!view_area->cube.empty()) {
		req_str << "&cube=" << cubeId;
	}

	unsigned int dummy, sequencenumber = 0;
	SERVER_TOKEN token(sequencenumber);
	unique_ptr<istringstream> stream = m_Server->m_PaloClient->request("/view/calculate", req_str.str(), token, sequencenumber, dummy);
	view_area->calc->sequence = m_Server->getDataToken();
	boost::shared_ptr<VIEW_CALC_AXIS> curr;
	vector<size_t> startLine;
	vector<map<IdentifierType, size_t> > knownElems;
	bool area = false;
	while ((*stream).eof() == false) {
		if ((*stream).peek() == '[') {
			char line[1024];
			(*stream).getline(line, sizeof(line));
			string s(line);
			if (curr) {
				for (size_t i = 0; i < startLine.size(); ++i) {
					updateParentChild(curr, startLine[i], i, knownElems);
				}
				curr.reset();
			}
			if (s == "[Area]") {
				area = true;
			} else {
				s = s.substr(6, s.size() - 7);
				size_t pos = s.find_first_of(' ');
				if (pos != string::npos) {
					s = s.substr(0, pos);
				}
				curr = view_area->calc->axes[util::lexicalConversion(size_t, string, s)];
				startLine.clear();
				startLine.resize(curr->nameIndex.size(), 0);
				knownElems.clear();
				knownElems.resize(curr->nameIndex.size());
			}
		} else {
			if (area) {
				CELL_VALUE_PATH_PROPS val;
				CELL_VALUE_PROPS vp;
				(*stream) >> csv >> val;
				vp = val;
				view_area->calc->values[val.path] = vp;
			} else {
				vector<ELEMENT_INFO_EXT> v;
				size_t tuplen = curr->tuples.size();
				for (size_t i = 0; i < curr->nameIndex.size(); ++i) {
					ELEMENT_INFO_EXT element;
					(*stream) >> csv >> element.m_einf;

					jedox::util::CsvTokenFromStream tfs((*stream) >> csv);
					tfs.get(element.search_alias);
					tfs.get(element.path);

					if (tuplen) {
						if (!hasSameParentSubsets(v, curr->tuples[tuplen - 1], i)) {
							updateParentChild(curr, startLine[i], i, knownElems);
							knownElems[i].clear();
							startLine[i] = tuplen;
						}
					}

					knownElems[i].insert(make_pair(element.m_einf.element, curr->tuples.size()));
					v.push_back(element);
					curr->nameIndex[i][element.m_einf.nelement] = make_pair(element.m_einf.element, element.m_einf.type);
				}
				curr->tuples.push_back(v);
			}
		}
	}
/**
* Main program. 
* - Create an object "cube"
* - Specify mirrors for onilne help.
* - Specify information related to the file (optional)
* - Build metric tree 
* - Build call tree
* - Build location tree
* - Severity mapping
* - Building a topology
*    - create 1st cartesian.
*    - create 2nd cartesian
* - Output to a cube file
*
* - For a test read the cube again and save it in another file.
* - end.
*/
int main(int argc, char* argv[]) {
  Metric *met0, *met1, *met2;
  Region *regn0, *regn1, *regn2;
  Cnode  *cnode0, *cnode1, *cnode2;
  Machine* mach;
  Node* node;
  Process* proc0, *proc1;
  Thread *thrd0, *thrd1;

  Cube cube;

  // Specify mirrors (optional)
  cube.def_mirror("http://icl.cs.utk.edu/software/kojak/");

  // Specify information related to the file (optional)
  cube.def_attr("experiment time", "November 1st, 2004");
  cube.def_attr("description", "a simple example");

  // Build metric tree 
  met0 = cube.def_met("Time", "Uniq_name1", "", "sec", "", 
		      "@[email protected]#execution", 
		      "root node", NULL); // using mirror
  met1 = cube.def_met("User time", "Uniq_name2", "", "sec", "",  
                      "http://www.cs.utk.edu/usr.html", 
                      "2nd level", met0); // without using mirror
  met2 = cube.def_met("System time", "Uniq_name3", "", "sec", "", 
                       "http://www.cs.utk.edu/sys.html", 
                      "2nd level", met0); // without using mirror
 
  // Build call tree
  string mod    = "/ICL/CUBE/example.c";
  regn0  = cube.def_region("main", 21, 100, "", "1st level", mod);
  regn1  = cube.def_region("foo", 1, 10, "", "2nd level", mod);
  regn2  = cube.def_region("bar", 11, 20, "", "2nd level", mod);

  cnode0 = cube.def_cnode(regn0, mod, 21, NULL);
  cnode1 = cube.def_cnode(regn1, mod, 60, cnode0);
  cnode2 = cube.def_cnode(regn2, mod, 80, cnode0);

  // Build location tree
  mach  = cube.def_mach("MSC", "");
  node  = cube.def_node("Athena", mach);
  proc0 = cube.def_proc("Process 0", 0, node);
  proc1 = cube.def_proc("Process 1", 1, node);
  thrd0 = cube.def_thrd("Thread 0", 0, proc0);
  thrd1 = cube.def_thrd("Thread 1", 1, proc1);


  // Severity mapping

  cube.set_sev(met0, cnode0, thrd0, 4);
  cube.set_sev(met0, cnode0, thrd1, 0);
  cube.set_sev(met0, cnode1, thrd0, 5);
  cube.set_sev(met0, cnode1, thrd1, 9);
  cube.set_sev(met1, cnode0, thrd0, 2);
  cube.set_sev(met1, cnode0, thrd1, 1);
  // unset severities default to zero
  cube.set_sev(met1, cnode1, thrd1, 3);

  // building a topology
  // create 1st cartesian.
  int ndims = 2;
  vector<long> dimv;
  vector<bool> periodv;
  for (int i = 0; i < ndims; i++) {
    dimv.push_back(5);
    if (i % 2 == 0)
      periodv.push_back(true);
    else 
      periodv.push_back(false);
  }
  std::vector<std::string> namedims;
  namedims.push_back("first");
  namedims.push_back("second");     // comment this and no names will be recorded. The vector must have the
                                    // exact number of dimensions present in the current topology.
  //  namedims.push_back("third");  // uncomment this and no names at all will be recorded
  
  
  Cartesian* cart = cube.def_cart(ndims, dimv, periodv);
  cart->set_namedims(namedims);
  vector<long> p[2];
  p[0].push_back(0);
  p[0].push_back(0);
  p[1].push_back(2);
  p[1].push_back(2);
  cube.def_coords(cart, thrd1, p[0]);
  // create 2nd cartesian
  ndims = 2;
  vector<long> dimv2;
  vector<bool> periodv2;
  for (int i = 0; i < ndims; i++) {
    dimv2.push_back(3);
    if (i % 2 == 0)
      periodv2.push_back(true);
    else 
      periodv2.push_back(false);
  }

  cart->set_name("test1");
  Cartesian* cart2 = cube.def_cart(ndims, dimv2, periodv2);
  vector<long> p2[2];
  p2[0].push_back(0);
  p2[0].push_back(1);
  p2[1].push_back(1);
  p2[1].push_back(0);
  cube.def_coords(cart2, thrd0, p2[0]);
  cube.def_coords(cart2, thrd1, p2[1]);
  cart2->set_name("Test2");
  // Output to a cube file
  ofstream out;
  out.open("example.cube");
  out << cube;

  // Read it (example.cube) in and write it to another file (example2.cube)
  ifstream in("example.cube");
  Cube cube2;
  in >> cube2;

  ofstream out2;
  out2.open("example2.cube");
  out2 << cube2;

  Cube cube3(cube2); // Tests the cube's copy constructor.
  ofstream out3;
  out3.open("example3.cube");
  out3 << cube3;


}
int main(int argc, char *argv[]){
	int rank, size, len, result, random;

	int * atom_layer_count;
	char hostname[MPI_MAX_PROCESSOR_NAME];
	Cube cube;
	MPI_Status status;
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Get_processor_name(hostname, &len);
	if(rank==0){
		srand(time(NULL));
		for(int c=1;c<size;c++){
			random=rand();
			MPI_Send(&random, 1, MPI_INT, c, 98, MPI_COMM_WORLD);
		}
	}
	else{
		MPI_Recv(&random, 1, MPI_INT, 0, 98, MPI_COMM_WORLD, &status);
		srand(random);
	}
	cube.seed_random(rand());
	Infile_reader infile_reader((string)argv[1]/*"infile"*/);
	infile_reader.setData();
	cube.set_nparticle_move_count(infile_reader.get_nparticle_move_count());
	int counts_for_rank[infile_reader.gettimesteps()/infile_reader.get_graph_interval()][cube.get_domain_z()][infile_reader.get_num_sims()/size];
	double z_cent_mass[infile_reader.gettimesteps()][infile_reader.get_num_sims()/size];
	double flux_in[infile_reader.gettimesteps()][infile_reader.get_num_sims()/size];
	double flux_out[infile_reader.gettimesteps()][infile_reader.get_num_sims()/size];
	double int_factor[infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types()][infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types()];
	cube.set_domain(infile_reader.getunitcellsize()[0], infile_reader.getunitcellsize()[1], infile_reader.getunitcellsize()[2]);
	dat_file_writer dat_writer(infile_reader.getoutfilename());
	cube.set_temp(infile_reader.get_temp());
	Atom atom;
	Nanoparticle nanoparticle;
	if(rank==0){
		double ** temp_int_factor=cube.set_interaction_factor(infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types());
		for(int c=0;c<infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types();c++){
			for(int d=0;d<infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types();d++)
				int_factor[c][d]=temp_int_factor[c][d];
		}
		for(int c=1;c<size;c++)
			MPI_Send(&int_factor, (infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types())*(infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types()), MPI_DOUBLE, c, 97, MPI_COMM_WORLD);
	}
	else{
		double ** temp_int_factor = new double*[infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types()];
		for(int c=0;c<infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types();c++)
			temp_int_factor[c] = new double[infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types()];
		MPI_Recv(&int_factor, (infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types())*(infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types()), MPI_DOUBLE, 0, 97, MPI_COMM_WORLD, &status);
		for(int c=0;c<infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types();c++){
			for(int d=0;d<infile_reader.get_particle_types()-infile_reader.get_nanoparticle_types();d++)
				temp_int_factor[c][d] = int_factor[c][d];
		}
		cube.set_interaction_factor(temp_int_factor);
	}
	for(int n=0;n<infile_reader.get_num_sims()/size;n++){
		for(int c=0;c<infile_reader.get_particle_types();c++){
			if(!infile_reader.is_nanoparticle()[c]){
				atom.set_name(infile_reader.get_particle_name()[c]);
				atom.set_type_num(c);
				atom.set_strength(infile_reader.get_strength()[c]);
				atom.set_mass(infile_reader.get_mass()[c]);
				atom.set_fixed(infile_reader.is_fixed()[c]);
				for(float d=0;d<((float)cube.get_domain_x()*(float)cube.get_domain_y()*infile_reader.getpercentdomainfill()[c])/100;d++){
					atom.set_replaceable(true);
					while(!cube.insert_atom(atom, rand()%cube.get_domain_x(), rand()%cube.get_domain_y(), 0));
				}		
			}
			else{
				nanoparticle.set_T(infile_reader.get_nanoparticle_temp()[c]);
				for(double d=0;d<((double)cube.get_domain_x()*(double)cube.get_domain_y()*(double)cube.get_domain_z()*infile_reader.getpercentdomainfill()[c])/100;d++)
				cube.insert_nanoparticle(nanoparticle);
			}
		}
		for(int c=0;c<infile_reader.gettimesteps();c++){
			z_cent_mass[c][n]=0;
			cout << rank << ":" << c << endl;
			cube.advance_timestep_opentop();
			flux_in[c][n]=(double)cube.get_flux_in();
			flux_out[c][n]=(double)cube.get_flux_out();
			atom_layer_count=dat_writer.get_timestep_array_z(cube);
			for(int d=0;d<cube.get_domain_z();d++)
				z_cent_mass[c][n]+=d*atom_layer_count[d];
			z_cent_mass[c][n]/=(double)cube.get_population();
			if((c+1)%infile_reader.get_graph_interval()==0){
				for(int d=0;d<cube.get_domain_z();d++)
					counts_for_rank[(c+1)/infile_reader.get_graph_interval()-1][d][n]=atom_layer_count[d];
			}	
		}
		
		cube.clear();
	}
	for(int c=0;c<infile_reader.get_num_sims()/size;c++){
		for(int d=0;d<cube.get_domain_z();d++){
			if(rank==1)
				cout << rank << ": " << counts_for_rank[d][c] << endl;
			}
	}	
	if(rank!=0){
		for(int c=0;c<infile_reader.get_num_sims()/size;c++){
			for(int d=0;d<cube.get_domain_z();d++){
				for(int e=0;e<infile_reader.gettimesteps()/infile_reader.get_graph_interval();e++)
					MPI_Send(&counts_for_rank[e][d][c],1, MPI_INT, 0, 99, MPI_COMM_WORLD);
			}
			for(int d=0;d<infile_reader.gettimesteps();d++){
				MPI_Send(&z_cent_mass[d][c], 1, MPI_DOUBLE, 0, 90, MPI_COMM_WORLD);
				MPI_Send(&flux_in[d][c], 1, MPI_DOUBLE, 0, 89, MPI_COMM_WORLD);
				MPI_Send(&flux_out[d][c], 1, MPI_DOUBLE, 0, 88, MPI_COMM_WORLD);
			}
		}
	}
	else{
		int all_counts[infile_reader.gettimesteps()/infile_reader.get_graph_interval()][cube.get_domain_z()][infile_reader.get_num_sims()];
		double all_z_cent_mass[infile_reader.gettimesteps()][infile_reader.get_num_sims()];
		double all_flux_in[infile_reader.gettimesteps()][infile_reader.get_num_sims()];
		double all_flux_out[infile_reader.gettimesteps()][infile_reader.get_num_sims()];
		double avg_z_cent_mass[infile_reader.gettimesteps()];
		double avg_flux_in[infile_reader.gettimesteps()];
		double avg_flux_out[infile_reader.gettimesteps()];
		double z_cent_mass_dev[infile_reader.gettimesteps()][infile_reader.get_num_sims()];
		double z_cent_mass_std_dev[infile_reader.gettimesteps()];
		double deviations[infile_reader.gettimesteps()/infile_reader.get_graph_interval()][cube.get_domain_z()][infile_reader.get_num_sims()];
		double standard_dev[infile_reader.gettimesteps()/infile_reader.get_graph_interval()][cube.get_domain_z()];
		double average[infile_reader.gettimesteps()/infile_reader.get_graph_interval()][cube.get_domain_z()];
		stringstream convert;
		string timestep_number_string;
		for(int c=0;c<infile_reader.get_num_sims()/size;c++){
			for(int d=0;d<infile_reader.gettimesteps();d++){
				all_z_cent_mass[d][c]=z_cent_mass[d][c];
				all_flux_in[d][c]=flux_in[d][c];
				all_flux_out[d][c]=flux_out[d][c];
			}
			for(int d=0;d<cube.get_domain_z();d++){
				for(int e=0;e<infile_reader.gettimesteps()/infile_reader.get_graph_interval();e++)
					all_counts[e][d][c]=counts_for_rank[e][d][c];
			}
		}
		for(int c=1;c<size;c++){
			for(int d=0;d<infile_reader.get_num_sims()/size;d++){
				for(int e=0;e<cube.get_domain_z();e++){
					for(int b=0;b<infile_reader.gettimesteps()/infile_reader.get_graph_interval();b++)
						MPI_Recv(&counts_for_rank[b][e][d], 1, MPI_INT, c, 99, MPI_COMM_WORLD, &status);
				}
				for(int e=0;e<infile_reader.gettimesteps();e++){
					MPI_Recv(&z_cent_mass[e][d], 1, MPI_DOUBLE, c, 90, MPI_COMM_WORLD, &status);
					MPI_Recv(&flux_in[e][d], 1, MPI_DOUBLE, c, 89, MPI_COMM_WORLD, &status);
					MPI_Recv(&flux_out[e][d], 1, MPI_DOUBLE, c, 88, MPI_COMM_WORLD, &status);
				}
			}
			int r=0;
			for(int e=infile_reader.get_num_sims()/size*c;e<(infile_reader.get_num_sims()/size)*(c+1);e++){
				for(int d=0;d<infile_reader.gettimesteps();d++){
					all_z_cent_mass[d][e]=z_cent_mass[d][r];
					all_flux_in[d][e]=flux_in[d][r];
					all_flux_out[d][e]=flux_out[d][r];
				}
				for(int d=0;d<cube.get_domain_z();d++){
					for(int b=0;b<infile_reader.gettimesteps()/infile_reader.get_graph_interval();b++)
						all_counts[b][d][e]=counts_for_rank[b][d][r];
				}
				r++;
			}
		}
/*
		for(int c=0;c<infile_reader.get_num_sims();c++){
			for(int d=0;d<cube.get_domain_z();d++)
				cout << all_counts[d][c] << " ";
			cout << endl;
		}
*/
		for(int e=0;e<infile_reader.gettimesteps()/infile_reader.get_graph_interval();e++){
			for(int c=0;c<cube.get_domain_z();c++){
				average[e][c]=0;
				standard_dev[e][c]=0;
				for(int d=0;d<infile_reader.get_num_sims();d++){
					average[e][c]+=(double)all_counts[e][c][d];
					deviations[e][c][d]=all_counts[e][c][d];
				}
				average[e][c]/=(double)infile_reader.get_num_sims();
			}
		}

		for(int e=0;e<infile_reader.gettimesteps()/infile_reader.get_graph_interval();e++){
			for(int c=0;c<cube.get_domain_z();c++){
				for(int d=0;d<infile_reader.get_num_sims();d++){
					deviations[e][c][d]-=average[e][c];
					deviations[e][c][d]=pow(deviations[e][c][d],2);
					standard_dev[e][c]+=deviations[e][c][d];
				}
				standard_dev[e][c]/=infile_reader.get_num_sims()-1;
				standard_dev[e][c]=sqrt(standard_dev[e][c]);
			}
		}

		for(int c=0;c<infile_reader.gettimesteps();c++){
			avg_z_cent_mass[c]=0;
			avg_flux_in[c]=0;
			avg_flux_out[c]=0;
			z_cent_mass_std_dev[c]=0;
			for(int d=0;d<infile_reader.get_num_sims();d++){
				avg_z_cent_mass[c]+=all_z_cent_mass[c][d];
				avg_flux_in[c]+=all_flux_in[c][d];
				avg_flux_out[c]+=all_flux_out[c][d];
				z_cent_mass_dev[c][d]=all_z_cent_mass[c][d];
			}	
			avg_z_cent_mass[c]/=(double)infile_reader.get_num_sims();
			avg_flux_in[c]/=(double)infile_reader.get_num_sims();
			avg_flux_out[c]/=(double)infile_reader.get_num_sims();
		}

		for(int c=0;c<infile_reader.gettimesteps();c++){
			for(int d=0;d<infile_reader.get_num_sims();d++){
				z_cent_mass_dev[c][d]-=avg_z_cent_mass[c];
				z_cent_mass_dev[c][d]=pow(z_cent_mass_dev[c][d],2);
				z_cent_mass_std_dev[c]+=z_cent_mass_dev[c][d];
			}
			z_cent_mass_std_dev[c]/=infile_reader.get_num_sims()-1;
			z_cent_mass_std_dev[c]=sqrt(z_cent_mass_std_dev[c]);
		}
/*
		for(int c=0;c<cube.get_domain_z();c++)
			cout << average[c] << " ";
		cout << endl;
		for(int c=0;c<cube.get_domain_z();c++)
			cout << standard_dev[c]/average[c]*100 << " ";
		cout << endl;
*/
		ofstream aver;
		ofstream dev;
		ofstream z_cent_mass_file;
		ofstream z_cent_mass_dev_file;
		ofstream flux_in_file;
		ofstream flux_out_file;
		z_cent_mass_file.open((infile_reader.getoutfilename() + "_z_cent_mass.dat").c_str(), ios::out);
		z_cent_mass_dev_file.open((infile_reader.getoutfilename() + "_z_cent_mass_dev.dat").c_str(), ios::out);
		flux_in_file.open((infile_reader.getoutfilename() + "_flux_in.dat").c_str(),ios::out);
		flux_out_file.open((infile_reader.getoutfilename() + "_flux_out.dat").c_str(),ios::out);
		for(int d=0;d<infile_reader.gettimesteps()/infile_reader.get_graph_interval();d++){
			convert << (d+1)*infile_reader.get_graph_interval();
			timestep_number_string=convert.str();
			aver.open((infile_reader.getoutfilename() + "_" + timestep_number_string + ".dat").c_str(), ios::out);
			dev.open((infile_reader.getoutfilename() + "_" + timestep_number_string + "_deviations.dat").c_str(), ios::out);
			for(int c=0;c<cube.get_domain_z();c++){
				aver << c << " " << average[d][c] << endl;
				dev << c << " " << standard_dev[d][c]/average[d][c]*100 << endl;
			}
			aver.close();
			dev.close();
			convert.str("");
		}
		for(int c=0;c<infile_reader.gettimesteps();c++){
			z_cent_mass_file << c+1 << " " << avg_z_cent_mass[c] << endl;
			z_cent_mass_dev_file << c+1 << " " << z_cent_mass_std_dev[c]/avg_z_cent_mass[c]*100 << endl;
			flux_in_file << c+1 << " " << avg_flux_in[c] << endl;
			flux_out_file << c+1 << " " << avg_flux_out[c] << endl;
		}
		aver.close();
		dev.close();
		z_cent_mass_file.close();
		z_cent_mass_dev_file.close();
		flux_in_file.close();
		flux_out_file.close();

	}
	MPI_Finalize();
	return 0;
}
Cube get_inner_box(const Cube& outer_box, Coord edge_offset) {
	return Cube(outer_box.get_bound(0) + edge_offset, outer_box.get_bound(1) - edge_offset,
				outer_box.get_bound(2) + edge_offset, outer_box.get_bound(3) - edge_offset);
}
Exemple #26
0
int
ConvertMultiple(list<string> &filelist,int nanflag,int floatflag,Tes &newtes)
{
  // printf("[I] vbconv: converting %d files\n",(int)filelist.size());
  // pre-scan for dimensions
  int dimx=0,dimy=0,dimz=0,dimt=0;
  VB_datatype dtype=vb_short;
  for (list<string>::iterator ff=filelist.begin(); ff!=filelist.end(); ff++) {
    Cube cb;
    Tes ts;
    VBImage *im;
    if (cb.ReadHeader(*ff)==0) {
      im=&cb;
      dimt++;
    }
    else if (ts.ReadHeader(*ff)==0) {
      im=&ts;
      dimt+=ts.dimt;
    }
    else {
      printf("[E] vbconv: couldn't read %s\n",ff->c_str());
      exit(51);
    }
    if (ff==filelist.begin()) {
      dimx=im->dimx;
      dimy=im->dimy;
      dimz=im->dimz;
      dimt=1;
      dtype=im->datatype;
    }
    else if (im->dimx!=dimx||im->dimy!=dimy||im->dimz!=dimz) {
      printf("[E] vbconv: incompatible dimensions in file %s\n",ff->c_str());
      exit(51);
    }
  }
  int index=0;
  if (floatflag)
    dtype=vb_float;
  
  // now grab all the images
  newtes.SetVolume(dimx,dimy,dimz,dimt,dtype);
  int findex=1;
  for (list<string>::iterator ff=filelist.begin(); ff!=filelist.end(); ff++) {
    printf("[I] vbconv: converting file %d of %d\n",findex++,(int)filelist.size());
    newtes.AddHeader("vbconv: included file "+*ff);
    Cube cb;
    Tes ts;
    if (cb.ReadFile(*ff)==0) {
      newtes.SetCube(index++,cb);
    }
    else if (ts.ReadFile(*ff)==0) {
      for (int i=0; i<ts.dimt; i++) {
        ts.getCube(i,cb);
        newtes.SetCube(index++,cb);
      }
    }
    else {
      printf("[E] vbconv: couldn't read data from %s\n",ff->c_str());
      exit(5);
    }
  }
  if (nanflag)
    newtes.removenans();
  return 0;
}
Exemple #27
0
  /**
   * Constructor for the LRO NAC Camera Model
   *
   * @param lab Pvl Label to create the camera model from
   *
   * @internal 
   *   @history 2011-05-03 Jeannie Walldren - Added NAIF error check.
   */
  LroNarrowAngleCamera::LroNarrowAngleCamera(Cube &cube) : LineScanCamera(cube) {
    NaifStatus::CheckErrors();
    // Set up the camera info from ik/iak kernels
    SetFocalLength();
    SetPixelPitch();

    double constantTimeOffset = 0.0,
           additionalPreroll = 0.0,
           additiveLineTimeError = 0.0,
           multiplicativeLineTimeError = 0.0;

    QString ikernKey = "INS" + toString(naifIkCode()) + "_CONSTANT_TIME_OFFSET";
    constantTimeOffset = getDouble(ikernKey);

    ikernKey = "INS" + toString(naifIkCode()) + "_ADDITIONAL_PREROLL";
    additionalPreroll = getDouble(ikernKey);

    ikernKey = "INS" + toString(naifIkCode()) + "_ADDITIVE_LINE_ERROR";
    additiveLineTimeError = getDouble(ikernKey);

    ikernKey = "INS" + toString(naifIkCode()) + "_MULTIPLI_LINE_ERROR";
    multiplicativeLineTimeError = getDouble(ikernKey);

    // Get the start time from labels
    Pvl &lab = *cube.label();
    PvlGroup &inst = lab.findGroup("Instrument", Pvl::Traverse);
    QString stime = inst["SpacecraftClockPrerollCount"];
    SpiceDouble etStart;

    if(stime != "NULL") {
      etStart = getClockTime(stime).Et();
    }
    else {
      etStart = iTime((QString)inst["PrerollTime"]).Et();
    }

    // Get other info from labels
    double csum = inst["SpatialSumming"];
    double lineRate = (double) inst["LineExposureDuration"] / 1000.0;
    double ss = inst["SampleFirstPixel"];
    ss += 1.0;

    lineRate *= 1.0 + multiplicativeLineTimeError;
    lineRate += additiveLineTimeError;
    etStart += additionalPreroll * lineRate;
    etStart += constantTimeOffset;

    setTime(etStart);

    // Setup detector map
    LineScanCameraDetectorMap *detectorMap = new LineScanCameraDetectorMap(this, etStart, lineRate);
    detectorMap->SetDetectorSampleSumming(csum);
    detectorMap->SetStartingDetectorSample(ss);

    // Setup focal plane map
    CameraFocalPlaneMap *focalMap = new CameraFocalPlaneMap(this, naifIkCode());

    //  Retrieve boresight location from instrument kernel (IK) (addendum?)
    ikernKey = "INS" + toString(naifIkCode()) + "_BORESIGHT_SAMPLE";
    double sampleBoreSight = getDouble(ikernKey);

    ikernKey = "INS" + toString(naifIkCode()) + "_BORESIGHT_LINE";
    double lineBoreSight = getDouble(ikernKey);

    focalMap->SetDetectorOrigin(sampleBoreSight, lineBoreSight);
    focalMap->SetDetectorOffset(0.0, 0.0);

    // Setup distortion map
    LroNarrowAngleDistortionMap *distMap = new LroNarrowAngleDistortionMap(this);
    distMap->SetDistortion(naifIkCode());

    // Setup the ground and sky map
    new LineScanCameraGroundMap(this);
    new LineScanCameraSkyMap(this);

    LoadCache();
    NaifStatus::CheckErrors();
  }
Exemple #28
0
int
main(int argc,char *argv[])
{
  if (argc==1) {
    vbconv_help();
    exit(0);
  }
  tokenlist args;
  string outfile;
  int floatflag=0,nanflag=0,extractflag=0;
  set<int> includeset,excludeset;
  list<string> filelist;
  VBFF nullff;

  args.Transfer(argc-1,argv+1);
  for (size_t i=0; i<args.size(); i++) {
    if (args[i]=="-f")
      floatflag=1;
    else if (args[i]=="-n")
      nanflag=1;
    else if (args[i]=="-i" && i<args.size()-1) {
      includeset=numberset(args[++i]);
      if (includeset.empty()) {
        cout << "[E] vbconv: invalid inclusion range specified with -i\n";
        exit(111);
      }
    }
    else if (args[i]=="-e" && i<args.size()-1) {
      excludeset=numberset(args[++i]);
      if (excludeset.empty()) {
        cout << "[E] vbconv: invalid exclusion range specified with -e\n";
        exit(111);
      }
    }
    else if (args[i]=="-x" && i<args.size()-1)
      extractflag=1;
    else if (args[i]=="-v") {
      vbconv_version();
      exit(0);
    }
    else if (args[i]=="-h") {
      vbconv_help();
      exit(0);
    }
    else if (args[i]=="-o" && i<args.size()-1)
      outfile=args[++i];
    else {
      filelist.push_back(args[i]);
    }
  }

  if (filelist.size()<1) {
    printf("[E] vbconv: requires at least one input file\n");
    exit(10);
  }
  // if there's no -o flag and exactly two files specified, convert
  // the first to the second
  if (filelist.size()==2 && outfile.size()==0) {
    outfile=filelist.back();
    filelist.pop_back();
  }
  if (outfile.size()==0) {
    printf("[E] vbconv: requires an output filename be provided\n");
    exit(11);
  }

  // multiple files, must be 3D/4D combination
  if (filelist.size()>1) {
    Tes newtes;
    ConvertMultiple(filelist,nanflag,floatflag,newtes);
    if (WriteTes(newtes,outfile,extractflag,floatflag,nanflag,includeset,excludeset))
      exit(223);
    exit(0);  // just in case
  }
  int err;
  // just one file, see what kind
  Cube cb;
  if (cb.ReadFile(filelist.front())==0) {
    cb.fileformat=nullff;
    if (floatflag && cb.datatype!=vb_float)
      cb.convert_type(vb_float);
    if (nanflag)
      cb.removenans();
    if ((err=cb.WriteFile(outfile))) {
      printf("[E] vbconv: error %d writing %s\n",err,outfile.c_str());
      exit(4);
    }
    else {
      printf("[I] vbconv: wrote cube %s\n",outfile.c_str());
      exit(0);
    }
  }
  Tes ts;
  if (ts.ReadFile(filelist.front())==0) {
    ts.fileformat=nullff;
    if ((err=WriteTes(ts,outfile,extractflag,floatflag,nanflag,includeset,excludeset))) {
      printf("[E] vbconv: error %d writing %s\n",err,outfile.c_str());
      exit(4);
    }
    else {
      printf("[I] vbconv: wrote 4D volume %s\n",outfile.c_str());
      exit(0);
    }
  }
  VB_Vector vv;
  if (vv.ReadFile(*filelist.begin())==0) {
    // vv.fileformat=nullff; // FIXME -- can we set 1d fileformat?
    if (vv.WriteFile(outfile)) {
      printf("[E] vbconv: error writing %s\n",outfile.c_str());
      exit(4);
    }
    else {
      printf("[I] vbconv: wrote vector %s\n",outfile.c_str());
      exit(0);
    }
  }
  printf("[E] vbconv: couldn't make sense of file %s\n",filelist.front().c_str());
  exit(100);
}
Exemple #29
0
void IsisMain() {
  Process p;

  // Get the list of names of input CCD cubes to stitch together
  FileList flist;
  UserInterface &ui = Application::GetUserInterface();
  flist.Read(ui.GetFilename("FROMLIST"));
  if (flist.size() < 1) {
    string msg = "The list file[" + ui.GetFilename("FROMLIST") +
    " does not contain any filenames";
    throw iException::Message(iException::User,msg,_FILEINFO_);
  }

  string projection("Equirectangular");
  if(ui.WasEntered("MAP")) {
      Pvl mapfile(ui.GetFilename("MAP"));
      projection = (string) mapfile.FindGroup("Mapping")["ProjectionName"];
  }

  if(ui.WasEntered("PROJECTION")) {
      projection = ui.GetString("PROJECTION");
  }

  // Gather other user inputs to projection
  string lattype = ui.GetString("LATTYPE");
  string londir  = ui.GetString("LONDIR");
  string londom  = ui.GetString("LONDOM");
  int digits = ui.GetInteger("PRECISION");

  // Fix them for mapping group
  lattype = (lattype == "PLANETOCENTRIC") ? "Planetocentric" : "Planetographic";
  londir = (londir == "POSITIVEEAST") ? "PositiveEast" : "PositiveWest";

  Progress prog;
  prog.SetMaximumSteps(flist.size());
  prog.CheckStatus();

  Statistics scaleStat;
  Statistics longitudeStat;
  Statistics latitudeStat;
  Statistics equiRadStat;
  Statistics poleRadStat;
  PvlObject fileset("FileSet");

  // Save major equitorial and polar radii for last occuring
  double eqRad; 
  double eq2Rad; 
  double poleRad;

  string target("Unknown");
  for (unsigned int i = 0 ; i < flist.size() ; i++) {
    // Set the input image, get the camera model, and a basic mapping
    // group
    Cube cube;
    cube.Open(flist[i]);

    int lines = cube.Lines();
    int samples = cube.Samples();


    PvlObject fmap("File");
    fmap += PvlKeyword("Name",flist[i]);
    fmap += PvlKeyword("Lines", lines);
    fmap += PvlKeyword("Samples", samples);

    Camera *cam = cube.Camera();
    Pvl mapping;
    cam->BasicMapping(mapping);
    PvlGroup &mapgrp = mapping.FindGroup("Mapping");
    mapgrp.AddKeyword(PvlKeyword("ProjectionName",projection),Pvl::Replace);    
    mapgrp.AddKeyword(PvlKeyword("LatitudeType",lattype),Pvl::Replace);    
    mapgrp.AddKeyword(PvlKeyword("LongitudeDirection",londir),Pvl::Replace);    
    mapgrp.AddKeyword(PvlKeyword("LongitudeDomain",londom),Pvl::Replace);    

    // Get the radii
    double radii[3];
    cam->Radii(radii);

    eqRad   = radii[0] * 1000.0;
    eq2Rad  = radii[1] * 1000.0;
    poleRad = radii[2] * 1000.0;

    target = cam->Target();
    equiRadStat.AddData(&eqRad, 1);
    poleRadStat.AddData(&poleRad, 1);

    // Get resolution
    double lowres = cam->LowestImageResolution();
    double hires = cam->HighestImageResolution();
    scaleStat.AddData(&lowres, 1);
    scaleStat.AddData(&hires, 1);

    double pixres = (lowres+hires)/2.0;
    double scale = Scale(pixres, poleRad, eqRad);
    mapgrp.AddKeyword(PvlKeyword("PixelResolution",pixres),Pvl::Replace);
    mapgrp.AddKeyword(PvlKeyword("Scale",scale,"pixels/degree"),Pvl::Replace);
    mapgrp += PvlKeyword("MinPixelResolution",lowres,"meters");
    mapgrp += PvlKeyword("MaxPixelResolution",hires,"meters");

    // Get the universal ground range
    double minlat,maxlat,minlon,maxlon;
    cam->GroundRange(minlat,maxlat,minlon,maxlon,mapping);
    mapgrp.AddKeyword(PvlKeyword("MinimumLatitude",minlat),Pvl::Replace);
    mapgrp.AddKeyword(PvlKeyword("MaximumLatitude",maxlat),Pvl::Replace);
    mapgrp.AddKeyword(PvlKeyword("MinimumLongitude",minlon),Pvl::Replace);
    mapgrp.AddKeyword(PvlKeyword("MaximumLongitude",maxlon),Pvl::Replace);

    fmap.AddGroup(mapgrp);
    fileset.AddObject(fmap);

    longitudeStat.AddData(&minlon, 1);
    longitudeStat.AddData(&maxlon, 1);
    latitudeStat.AddData(&minlat, 1);
    latitudeStat.AddData(&maxlat, 1);

    p.ClearInputCubes();
    prog.CheckStatus();
  }

//  Construct the output mapping group with statistics
  PvlGroup mapping("Mapping");
  double avgPixRes((scaleStat.Minimum()+scaleStat.Maximum())/2.0);
  double avgLat((latitudeStat.Minimum()+latitudeStat.Maximum())/2.0);
  double avgLon((longitudeStat.Minimum()+longitudeStat.Maximum())/2.0);
  double avgEqRad((equiRadStat.Minimum()+equiRadStat.Maximum())/2.0);
  double avgPoleRad((poleRadStat.Minimum()+poleRadStat.Maximum())/2.0);
  double scale  = Scale(avgPixRes, avgPoleRad, avgEqRad);

  mapping += PvlKeyword("ProjectionName",projection);
  mapping += PvlKeyword("TargetName", target);
  mapping += PvlKeyword("EquatorialRadius",eqRad,"meters");
  mapping += PvlKeyword("PolarRadius",poleRad,"meters");
  mapping += PvlKeyword("LatitudeType",lattype);
  mapping += PvlKeyword("LongitudeDirection",londir);
  mapping += PvlKeyword("LongitudeDomain",londom);
  mapping += PvlKeyword("PixelResolution", SetRound(avgPixRes, digits), "meters/pixel");
  mapping += PvlKeyword("Scale", SetRound(scale, digits), "pixels/degree");
  mapping += PvlKeyword("MinPixelResolution",scaleStat.Minimum(),"meters");
  mapping += PvlKeyword("MaxPixelResolution",scaleStat.Maximum(),"meters");
  mapping += PvlKeyword("CenterLongitude", SetRound(avgLon,digits));
  mapping += PvlKeyword("CenterLatitude",  SetRound(avgLat,digits));
  mapping += PvlKeyword("MinimumLatitude", MAX(SetFloor(latitudeStat.Minimum(),digits), -90.0));
  mapping += PvlKeyword("MaximumLatitude", MIN(SetCeil(latitudeStat.Maximum(),digits), 90.0));
  mapping += PvlKeyword("MinimumLongitude",MAX(SetFloor(longitudeStat.Minimum(),digits), -180.0));
  mapping += PvlKeyword("MaximumLongitude",MIN(SetCeil(longitudeStat.Maximum(),digits), 360.0));

  PvlKeyword clat("PreciseCenterLongitude", avgLon);
  clat.AddComment("Actual Parameters without precision applied");
  mapping += clat;
  mapping += PvlKeyword("PreciseCenterLatitude",  avgLat);
  mapping += PvlKeyword("PreciseMinimumLatitude", latitudeStat.Minimum());
  mapping += PvlKeyword("PreciseMaximumLatitude", latitudeStat.Maximum());
  mapping += PvlKeyword("PreciseMinimumLongitude",longitudeStat.Minimum());
  mapping += PvlKeyword("PreciseMaximumLongitude",longitudeStat.Maximum());

  
  Application::GuiLog(mapping);

  // Write the output file if requested
  if (ui.WasEntered("TO")) {
    Pvl temp;
    temp.AddGroup(mapping);
    temp.Write(ui.GetFilename("TO","map"));
  }

  if (ui.WasEntered("LOG")) {
    Pvl temp;
    temp.AddObject(fileset);
    temp.Write(ui.GetFilename("LOG","log"));
  }

  p.EndProcess();
}
inline
void
op_reshape_ext::apply(Cube<typename T1::elem_type>& out, const OpCube<T1,op_reshape_ext>& in)
  {
  arma_extra_debug_sigprint();
  
  typedef typename T1::elem_type eT;
  
  const unwrap_cube<T1> A_tmp(in.m);
  const Cube<eT>& A   = A_tmp.M;
  
  const uword in_n_rows   = in.aux_uword_a;
  const uword in_n_cols   = in.aux_uword_b;
  const uword in_n_slices = in.aux_uword_c;
  const uword in_dim      = in.aux_uword_d;
  
  const uword in_n_elem = in_n_rows * in_n_cols * in_n_slices;
  
  if(A.n_elem == in_n_elem)
    {
    if(in_dim == 0)
      {
      if(&out != &A)
        {
        out.set_size(in_n_rows, in_n_cols, in_n_slices);
        arrayops::copy( out.memptr(), A.memptr(), out.n_elem );
        }
      else  // &out == &A, i.e. inplace resize
        {
        out.set_size(in_n_rows, in_n_cols, in_n_slices);
        // set_size() doesn't destroy data as long as the number of elements in the cube remains the same
        }
      }
    else
      {
      unwrap_cube_check< Cube<eT> > B_tmp(A, out);
      const Cube<eT>& B           = B_tmp.M;
      
      out.set_size(in_n_rows, in_n_cols, in_n_slices);
      
      eT* out_mem = out.memptr();
      
      const uword B_n_rows   = B.n_rows;
      const uword B_n_cols   = B.n_cols;
      const uword B_n_slices = B.n_slices;
      
      for(uword slice = 0; slice < B_n_slices; ++slice)
      for(uword row   = 0; row   < B_n_rows;   ++row  )
      for(uword col   = 0; col   < B_n_cols;   ++col  )
        {
        *out_mem = B.at(row,col,slice);
        out_mem++;
        }
      }
    }
  else
    {
    const unwrap_cube_check< Cube<eT> > B_tmp(A, out);
    const Cube<eT>& B                 = B_tmp.M;
    
    const uword n_elem_to_copy = (std::min)(B.n_elem, in_n_elem);
    
    out.set_size(in_n_rows, in_n_cols, in_n_slices);
    
    eT* out_mem = out.memptr();
    
    if(in_dim == 0)
      {
      arrayops::copy( out_mem, B.memptr(), n_elem_to_copy );
      }
    else
      {
      uword row   = 0;
      uword col   = 0;
      uword slice = 0;
      
      const uword B_n_rows = B.n_rows;
      const uword B_n_cols = B.n_cols;
      
      for(uword i=0; i<n_elem_to_copy; ++i)
        {
        out_mem[i] = B.at(row,col,slice);
        
        ++col;
        
        if(col >= B_n_cols)
          {
          col = 0;
          ++row;
          
          if(row >= B_n_rows)
            {
            row = 0;
            ++slice;
            }
          }
        }
      }
    
    for(uword i=n_elem_to_copy; i<in_n_elem; ++i)
      {
      out_mem[i] = eT(0);
      }
    
    }
  }