コード例 #1
0
ファイル: sun.cpp プロジェクト: JesperMikkelsen/Big-Numbers
double daylength(const Date &d, double latitude, double longitude, double timezone) {
  int J = d - Date(_T("1.1.2000"));
  int sommertid = 0;

  double K = delta(J);
  double L = timeq(J);
  double B = d.getDayOfYear();
  double C = f0(K,latitude);
  double D = RiseSet(-C,timezone,longitude,sommertid,L);
  double F = RiseSet( C,timezone,longitude,sommertid,L);
  double LEN = F - D;

  int hr_op,mn_op,hr_ned,mn_ned,hr_len,mn_len;
  dms(D,hr_op,mn_op);
  dms(F,hr_ned,mn_ned);
  dms(LEN,hr_len,mn_len);

//  printf("Solopgang:%lf Solnedgang:%lf\n",D,F);
  _tprintf(_T("%s %2d:%02d %2d:%02d %2d:%02d %lf\n")
          ,d.toString().cstr(),hr_op,mn_op,hr_ned,mn_ned,hr_len,mn_len,LEN);

  return LEN;
}
コード例 #2
0
ファイル: kspluto.cpp プロジェクト: Bugsbane/kstars
KSPluto::KSPluto(const QString &fn, double pSize )
    : KSAsteroid( 0, xi18n("Pluto"), fn, J2000,
                  39.48168677, 0.24880766, dms(17.14175), dms(113.76329),
                  dms(110.30347), dms(14.86205), 1.0, 0.0 )
{
    //Initialize the base orbital element values for J2000:
    a0 = 39.48168677; //semi-major axis (AU)
    e0 = 0.24880766;  //eccentricity
    i0.setD( 17.14175 );    //inclination (degrees)
    w0.setD( 113.76329 );   //argument of perihelion (degrees)
    N0.setD( 110.30347 );   //long. of ascending node (degrees)
    M0.setD(  14.86205 );   //mean anomaly (degrees)

    //rate-of-change values for the orbital elements
    a1 = -0.00076912;     // da/dt (AU/cnetury)
    e1 = 0.00006465;      // de/dt (1/century)
    i1 = 11.07/3600.;     // di/dt (degrees/century)
    w1 = -94.92/3600.;   // dw/dt (degrees/century)
    N1 = -37.33/3600.;    // dN/dt (degrees/century)
    M1 = 522880.15/3600.; // dM/dt (degrees/century)

    setPhysicalSize( pSize );
}
コード例 #3
0
ファイル: zfile.c プロジェクト: HoraceAndTheSpider/PSPUAE
static struct zfile *zuncompress (struct zfile *z)
{
    char *name = z->name;
    char *ext = strrchr (name, '.');
    uae_u8 header[4];

    if (ext != NULL) {
	ext++;
	if (strcasecmp (ext, "zip") == 0 && zlib_test ())
	     return unzip (z);
	if (strcasecmp (ext, "gz") == 0)
	     return gunzip (z);
	if (strcasecmp (ext, "adz") == 0)
// thinkp	adz-file support
	     return unzip (z);
// thinkp	adz-file support
	if (strcasecmp (ext, "roz") == 0)
	     return gunzip (z);
	if (strcasecmp (ext, "dms") == 0)
	     return dms (z);
	if (strcasecmp (ext, "lha") == 0
	    || strcasecmp (ext, "lzh") == 0)
	    return lha (z);
	memset (header, 0, sizeof (header));
	zfile_fseek (z, 0, SEEK_SET);
	zfile_fread (header, sizeof (header), 1, z);
	zfile_fseek (z, 0, SEEK_SET);
	if (header[0] == 0x1f && header[1] == 0x8b)
	    return gunzip (z);
	if (header[0] == 'P' && header[1] == 'K')
	    return unzip (z);
	if (header[0] == 'D' && header[1] == 'M' && header[2] == 'S' && header[3] == '!')
	    return dms (z);
    }
    return z;
}
コード例 #4
0
ファイル: SL_controller.c プロジェクト: akshararai/HERMES_qp
/*!*****************************************************************************
 *******************************************************************************
\note  stop
\date  August 7, 1992 
   
\remarks 

       send pump into low pressure and terminate loops

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

    none

 ******************************************************************************/
int
stop(char *msg)
{

  int i;

  user_kill();
  zero_integrator();
  dms();
  beep(1);
  printf("%s\n",msg);
  
  return TRUE;

}
コード例 #5
0
ファイル: skypoint.cpp プロジェクト: Bugsbane/kstars
void SkyPoint::GalacticToEquatorial1950(const dms* galLong, const dms* galLat) {

    double a = 123.0;
    double sinb, cosb, singLat, cosgLat, tangLat, singLong_a, cosgLong_a;

    dms c(12.25);
    dms b(27.4);
    tangLat = tan( galLat->radians() );
    galLat->SinCos(singLat,cosgLat);

    dms( galLong->Degrees() - a ).SinCos(singLong_a,cosgLong_a);
    b.SinCos(sinb,cosb);

    RA.setRadians(c.radians() + atan2(singLong_a,cosgLong_a*sinb-tangLat*cosb) );
    RA = RA.reduce();

    Dec.setRadians( asin(singLat*sinb+cosgLat*cosb*cosgLong_a) );
}
コード例 #6
0
ファイル: skypoint.cpp プロジェクト: Bugsbane/kstars
void SkyPoint::Equatorial1950ToGalactic(dms &galLong, dms &galLat) {

    double a = 192.25;
    double sinb, cosb, sina_RA, cosa_RA, sinDEC, cosDEC, tanDEC;

    dms c(303.0);
    dms b(27.4);
    tanDEC = tan( Dec.radians() );

    b.SinCos(sinb,cosb);
    dms( a - RA.Degrees() ).SinCos(sina_RA,cosa_RA);
    Dec.SinCos(sinDEC,cosDEC);

    galLong.setRadians( c.radians() - atan2( sina_RA, cosa_RA*sinb-tanDEC*cosb) );
    galLong = galLong.reduce();

    galLat.setRadians( asin(sinDEC*sinb+cosDEC*cosb*cosa_RA) );
}
コード例 #7
0
ファイル: skyline.cpp プロジェクト: birefringence/kstars
dms SkyLine::angularSize( int i ) const{
    if ( i < 0 || i+1 >= m_pList.size() ) {
        kDebug() << i18n("SkyLine index error: no such segment: %1", i );
        return dms();
    }

    SkyPoint *p1 = m_pList[i];
    SkyPoint *p2 = m_pList[i+1];
    double dalpha = p1->ra().radians() - p2->ra().radians();
    double ddelta = p1->dec().radians() - p2->dec().radians() ;

    double sa = sin(dalpha/2.);
    double sd = sin(ddelta/2.);

    double hava = sa*sa;
    double havd = sd*sd;

    double aux = havd + cos (p1->dec().radians()) * cos(p2->dec().radians()) * hava;

    dms angDist;
    angDist.setRadians( 2 * fabs(asin( sqrt(aux) )) );

    return angDist;
}
コード例 #8
0
void dmsBox::show(const dms *d, bool deg) { show( dms( *d ),deg ); }
コード例 #9
0
void dmsBox::showInHours (const dms *d) { showInHours( dms( *d ) ); }
コード例 #10
0
void dmsBox::showInDegrees (const dms *d) { showInDegrees( dms( *d ) ); }
コード例 #11
0
void SupernovaeComponent::loadData()
{
    QString serialNo, hostGalaxy, date, type, offset, SNPosition, discoverers ;
    dms ra, dec;
    float magnitude;
    qDebug()<<"Loading Supernovae data";
    //m_ObjectList.clear();
    latest.clear();
    objectNames(SkyObject::SUPERNOVA).clear();
    
    KStarsData *m_data = KStarsData::Instance(); // to convert equatorial coordinate to horizontal

    //SN     ,Host Galaxy     ,Date       , R.A.  , Decl.,   Offset  ,Mag.,  Disc. Ref.     ,      SN Position      ,  Posn. Ref.      ,Typ,  SN     ,Discoverer(s)
    QList< QPair<QString,KSParser::DataTypes> > sequence;
    sequence.append(qMakePair(QString("serialNo"),      KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("hostGalaxy"),    KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("date"),          KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("ra"),            KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("dec"),           KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("offset"),        KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("magnitude"),     KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("ignore1"),       KSParser::D_SKIP));
    sequence.append(qMakePair(QString("SNPosition"),    KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("ignore2"),       KSParser::D_SKIP));
    sequence.append(qMakePair(QString("type"),          KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("ignore3"),       KSParser::D_SKIP));
    sequence.append(qMakePair(QString("discoverers"),   KSParser::D_QSTRING));

    QString file_name = QStandardPaths::locate(QStandardPaths::DataLocation,
                                               QString("supernovae.dat"));
    KSParser snParser(file_name, '#', sequence);

    QHash<QString, QVariant> row_content;
    while (snParser.HasNextRow()){
        Supernova *sup=0;
        row_content = snParser.ReadNextRow();

        if(row_content["serialNo"].toString() == "Null")
            continue;

        serialNo    = row_content["serialNo"].toString().trimmed();
        hostGalaxy  = row_content["hostGalaxy"].toString();
        date        = row_content["date"].toString();
        ra          = dms(row_content["ra"].toString(), false);
        dec         = dms(row_content["dec"].toString());
        offset      = row_content["offset"].toString();
        magnitude   = row_content["magnitude"].toFloat();
        SNPosition  = row_content["SNPosition"].toString();
        type        = row_content["type"].toString();
        discoverers = row_content["discoverers"].toString();

        if (magnitude == KSParser::EBROKEN_FLOAT)
            magnitude = 99.9;

        sup=new Supernova(ra, dec, date, magnitude, serialNo, type, hostGalaxy, offset, discoverers);
        sup->EquatorialToHorizontal(m_data->lst(),m_data->geo()->lat());
        if (!m_ObjectList.empty())
        {
            if ( findByName(sup->name() ) == 0 )
            {
                //qDebug()<<"List of supernovae not empty. Found new supernova";
                m_ObjectList.append(sup);
                latest.append(sup);
            }/*
            else
                m_ObjectList.append(sup);*/
        }
        else             //if the list is empty
        {
            m_ObjectList.append(sup);
            latest.append(sup);
            //notifyNewSupernovae();
        }

        objectNames(SkyObject::SUPERNOVA).append(sup->name());
    }
    //notifyNewSupernovae();
}
コード例 #12
0
ファイル: dngwriter.cpp プロジェクト: ruphy/kipi-plugins
int DNGWriter::convert()
{
    d->cancel = false;

    try
    {
        if (inputFile().isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: No input file to convert. Aborted..." << endl;
            return -1;
        }

        QFileInfo inputInfo(inputFile());
        QString   dngFilePath = outputFile();

        if (dngFilePath.isEmpty())
        {
            dngFilePath = QString(inputInfo.baseName() + QString(".dng"));
        }

        QFileInfo          outputInfo(dngFilePath);
        QByteArray         rawData;
        DcrawInfoContainer identify;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Loading RAW data from " << inputInfo.fileName() << endl;

        KDcraw rawProcessor;
        if (!rawProcessor.extractRAWData(inputFile(), rawData, identify))
        {
            kDebug( 51000 ) << "DNGWriter: Loading RAW data failed. Aborted..." << endl;
            return -1;
        }

        if (d->cancel) return -2;

        int width      = identify.imageSize.width();
        int height     = identify.imageSize.height();
        int pixelRange = 16;

        kDebug( 51000 ) << "DNGWriter: Raw data loaded:" << endl;
        kDebug( 51000 ) << "--- Data Size:     " << rawData.size() << " bytes" << endl;
        kDebug( 51000 ) << "--- Date:          " << identify.dateTime.toString(Qt::ISODate) << endl;
        kDebug( 51000 ) << "--- Make:          " << identify.make << endl;
        kDebug( 51000 ) << "--- Model:         " << identify.model << endl;
        kDebug( 51000 ) << "--- Size:          " << width << "x" << height << endl;
        kDebug( 51000 ) << "--- Orientation:   " << identify.orientation << endl;
        kDebug( 51000 ) << "--- Top margin:    " << identify.topMargin << endl;
        kDebug( 51000 ) << "--- Left margin:   " << identify.leftMargin << endl;
        kDebug( 51000 ) << "--- Filter:        " << identify.filterPattern << endl;
        kDebug( 51000 ) << "--- Colors:        " << identify.rawColors << endl;
        kDebug( 51000 ) << "--- Black:         " << identify.blackPoint << endl;
        kDebug( 51000 ) << "--- White:         " << identify.whitePoint << endl;
        kDebug( 51000 ) << "--- CAM->XYZ:" << endl;

        QString matrixVal;
        for(int i=0; i<12; i+=3)
        {
            kDebug( 51000 ) << "                   "
                     << QString().sprintf("%03.4f  %03.4f  %03.4f", identify.cameraXYZMatrix[0][ i ],
                                                                    identify.cameraXYZMatrix[0][i+1],
                                                                    identify.cameraXYZMatrix[0][i+2])
                     << endl;
        }

        // Check if CFA layout is supported by DNG SDK.
        int bayerMosaic;

        if (identify.filterPattern == QString("GRBGGRBGGRBGGRBG"))
        {
            bayerMosaic = 0;
        }
        else if (identify.filterPattern == QString("RGGBRGGBRGGBRGGB"))
        {
            bayerMosaic = 1;
        }
        else if (identify.filterPattern == QString("BGGRBGGRBGGRBGGR"))
        {
            bayerMosaic = 2;
        }
        else if (identify.filterPattern == QString("GBRGGBRGGBRGGBRG"))
        {
            bayerMosaic = 3;
        }
        else
        {
            kDebug( 51000 ) << "DNGWriter: Bayer mosaic not supported. Aborted..." << endl;
            return -1;
        }

        // Check if number of Raw Color components is supported.
        if (identify.rawColors != 3)
        {
            kDebug( 51000 ) << "DNGWriter: Number of Raw color components not supported. Aborted..." << endl;
            return -1;
        }

/*      // NOTE: code to hack RAW data extraction

        QString   rawdataFilePath(inputInfo.baseName() + QString(".dat"));
        QFileInfo rawdataInfo(rawdataFilePath);

        QFile rawdataFile(rawdataFilePath);
        if (!rawdataFile.open(QIODevice::WriteOnly))
        {
            kDebug( 51000 ) << "DNGWriter: Cannot open file to write RAW data. Aborted..." << endl;
            return -1;
        }
        QDataStream rawdataStream(&rawdataFile);
        rawdataStream.writeRawData(rawData.data(), rawData.size());
        rawdataFile.close();
*/
        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Formating RAW data to memory" << endl;

        std::vector<unsigned short> raw_data;
        raw_data.resize(rawData.size());
        const unsigned short* dp = (const unsigned short*)rawData.data();
        for (uint i = 0; i < raw_data.size()/2; i++)
        {
            raw_data[i] = *dp;
            *dp++;
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG memory allocation and initialization" << endl;

        dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
        dng_memory_stream stream(memalloc);
        stream.Put(&raw_data.front(), raw_data.size()*sizeof(unsigned short));

        dng_rect rect(height, width);
        DNGWriterHost host(d, &memalloc);

        // Unprocessed raw data.
        host.SetKeepStage1(true);

        // Linearized, tone curve processed data.
        host.SetKeepStage2(true);

        AutoPtr<dng_image> image(new dng_simple_image(rect, 1, ttShort, 1<<pixelRange, memalloc));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG IFD structure creation" << endl;

        dng_ifd ifd;

        ifd.fUsesNewSubFileType        = true;
        ifd.fNewSubFileType            = 0;
        ifd.fImageWidth                = width;
        ifd.fImageLength               = height;
        ifd.fBitsPerSample[0]          = pixelRange;
        ifd.fBitsPerSample[1]          = 0;
        ifd.fBitsPerSample[2]          = 0;
        ifd.fBitsPerSample[3]          = 0;
        ifd.fCompression               = ccUncompressed;
        ifd.fPredictor                 = 1;
        ifd.fCFALayout                 = 1;                 // Rectangular (or square) layout.
        ifd.fPhotometricInterpretation = piCFA;
        ifd.fFillOrder                 = 1;
        ifd.fOrientation               = identify.orientation;
        ifd.fSamplesPerPixel           = 1;
        ifd.fPlanarConfiguration       = 1;
        ifd.fXResolution               = 0.0;
        ifd.fYResolution               = 0.0;
        ifd.fResolutionUnit            = 0;

        ifd.fUsesStrips                = true;
        ifd.fUsesTiles                 = false;

        ifd.fTileWidth                 = width;
        ifd.fTileLength                = height;
        ifd.fTileOffsetsType           = 4;
        ifd.fTileOffsetsCount          = 0;

        ifd.fSubIFDsCount              = 0;
        ifd.fSubIFDsOffset             = 0;
        ifd.fExtraSamplesCount         = 0;
        ifd.fSampleFormat[0]           = 1;
        ifd.fSampleFormat[1]           = 1;
        ifd.fSampleFormat[2]           = 1;
        ifd.fSampleFormat[3]           = 1;

        ifd.fLinearizationTableType    = 0;
        ifd.fLinearizationTableCount   = 0;
        ifd.fLinearizationTableOffset  = 0;

        ifd.fBlackLevelRepeatRows      = 1;
        ifd.fBlackLevelRepeatCols      = 1;
        ifd.fBlackLevel[0][0][0]       = identify.blackPoint;
        ifd.fBlackLevelDeltaHType      = 0;
        ifd.fBlackLevelDeltaHCount     = 0;
        ifd.fBlackLevelDeltaHOffset    = 0;
        ifd.fBlackLevelDeltaVType      = 0;
        ifd.fBlackLevelDeltaVCount     = 0;
        ifd.fBlackLevelDeltaVOffset    = 0;
        ifd.fWhiteLevel[0]             = identify.whitePoint;
        ifd.fWhiteLevel[1]             = identify.whitePoint;
        ifd.fWhiteLevel[2]             = identify.whitePoint;
        ifd.fWhiteLevel[3]             = identify.whitePoint;

        ifd.fDefaultScaleH             = dng_urational(1, 1);
        ifd.fDefaultScaleV             = dng_urational(1, 1);
        ifd.fBestQualityScale          = dng_urational(1, 1);

        ifd.fCFARepeatPatternRows      = 0;
        ifd.fCFARepeatPatternCols      = 0;

        ifd.fBayerGreenSplit           = 0;
        ifd.fChromaBlurRadius          = dng_urational(0, 0);
        ifd.fAntiAliasStrength         = dng_urational(100, 100);

        ifd.fActiveArea                = rect;
        ifd.fDefaultCropOriginH        = dng_urational(0, 1);
        ifd.fDefaultCropOriginV        = dng_urational(0, 1);
        ifd.fDefaultCropSizeH          = dng_urational(width, 1);
        ifd.fDefaultCropSizeV          = dng_urational(height, 1);

        ifd.fMaskedAreaCount           = 0;
        ifd.fLosslessJPEGBug16         = false;
        ifd.fSampleBitShift            = 0;

        ifd.ReadImage(host, stream, *image.Get());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG Negative structure creation" << endl;

        AutoPtr<dng_negative> negative(host.Make_dng_negative());

        negative->SetDefaultScale(ifd.fDefaultScaleH, ifd.fDefaultScaleV);
        negative->SetDefaultCropOrigin(ifd.fDefaultCropOriginH, ifd.fDefaultCropOriginV);
        negative->SetDefaultCropSize(ifd.fDefaultCropSizeH, ifd.fDefaultCropSizeV);
        negative->SetActiveArea(ifd.fActiveArea);

        negative->SetModelName(identify.model.toAscii());
        negative->SetLocalName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());
        negative->SetOriginalRawFileName(inputInfo.fileName().toAscii());

        negative->SetColorChannels(3);
        negative->SetColorKeys(colorKeyRed, colorKeyGreen, colorKeyBlue);
        negative->SetBayerMosaic(bayerMosaic);

        negative->SetWhiteLevel(identify.whitePoint, 0);
        negative->SetWhiteLevel(identify.whitePoint, 1);
        negative->SetWhiteLevel(identify.whitePoint, 2);
        negative->SetBlackLevel(identify.blackPoint, 0);
        negative->SetBlackLevel(identify.blackPoint, 1);
        negative->SetBlackLevel(identify.blackPoint, 2);

        negative->SetBaselineExposure(0.0);
        negative->SetBaselineNoise(1.0);
        negative->SetBaselineSharpness(1.0);

        dng_orientation orientation;
        switch (identify.orientation)
        {
            case DcrawInfoContainer::ORIENTATION_180:
                orientation = dng_orientation::Rotate180();
                break;

            case DcrawInfoContainer::ORIENTATION_90CCW:
                orientation = dng_orientation::Rotate90CCW();
                break;

            case DcrawInfoContainer::ORIENTATION_90CW:
                orientation = dng_orientation::Rotate90CW();
                break;

            default:   // ORIENTATION_NONE
                orientation = dng_orientation::Normal();
                break;
        }
        negative->SetBaseOrientation(orientation);

        negative->SetAntiAliasStrength(dng_urational(100, 100));
        negative->SetLinearResponseLimit(1.0);
        negative->SetShadowScale( dng_urational(1, 1) );

        negative->SetAnalogBalance(dng_vector_3(1.0, 1.0, 1.0));

        // -------------------------------------------------------------------------------

        // Set Camera->XYZ Color matrix as profile.
        dng_matrix_3by3 matrix(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
        dng_matrix_3by3 camXYZ;

        AutoPtr<dng_camera_profile> prof(new dng_camera_profile);
        prof->SetName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());

        camXYZ[0][0] = identify.cameraXYZMatrix[0][0];
        camXYZ[0][1] = identify.cameraXYZMatrix[0][1];
        camXYZ[0][2] = identify.cameraXYZMatrix[0][2];
        camXYZ[1][0] = identify.cameraXYZMatrix[0][3];
        camXYZ[1][1] = identify.cameraXYZMatrix[1][0];
        camXYZ[1][2] = identify.cameraXYZMatrix[1][1];
        camXYZ[2][0] = identify.cameraXYZMatrix[1][2];
        camXYZ[2][1] = identify.cameraXYZMatrix[1][3];
        camXYZ[2][2] = identify.cameraXYZMatrix[2][0];

        if (camXYZ.MaxEntry() == 0.0)
            kDebug( 51000 ) << "DNGWriter: Warning, camera XYZ Matrix is null" << endl;
        else 
            matrix = camXYZ;

        prof->SetColorMatrix1((dng_matrix) matrix);
        prof->SetCalibrationIlluminant1(lsD65);
        negative->AddProfile(prof);

        // -------------------------------------------------------------------------------

        // Clear "Camera WhiteXY"
        negative->SetCameraWhiteXY(dng_xy_coord());

        // This settings break color on preview and thumbnail
        //negative->SetCameraNeutral(dng_vector_3(1.0, 1.0, 1.0));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Updating metadata to DNG Negative" << endl;

        dng_exif *exif = negative->GetExif();
        exif->fModel.Set_ASCII(identify.model.toAscii());
        exif->fMake.Set_ASCII(identify.make.toAscii());

        // Time from original shot
        dng_date_time dt;
        dt.fYear   = identify.dateTime.date().year();
        dt.fMonth  = identify.dateTime.date().month();
        dt.fDay    = identify.dateTime.date().day();
        dt.fHour   = identify.dateTime.time().hour();
        dt.fMinute = identify.dateTime.time().minute();
        dt.fSecond = identify.dateTime.time().second();

        dng_date_time_info dti;
        dti.SetDateTime(dt);
        exif->fDateTimeOriginal  = dti;
        exif->fDateTimeDigitized = dti;
        negative->UpdateDateTime(dti);

        long int num, den;
        long     val;
        QString  str;
        KExiv2   meta;
        if (meta.load(inputFile()))
        {
            // String Tags

            str = meta.getExifTagString("Exif.Image.Software");
            if (!str.isEmpty()) exif->fSoftware.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.ImageDescription");
            if (!str.isEmpty()) exif->fImageDescription.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Artist");
            if (!str.isEmpty()) exif->fArtist.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Copyright");
            if (!str.isEmpty()) exif->fCopyright.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Photo.UserComment");
            if (!str.isEmpty()) exif->fUserComment.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.CameraSerialNumber");
            if (!str.isEmpty()) exif->fCameraSerialNumber.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLatitudeRef");
            if (!str.isEmpty()) exif->fGPSLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLongitudeRef");
            if (!str.isEmpty()) exif->fGPSLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSatellites");
            if (!str.isEmpty()) exif->fGPSSatellites.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSStatus");
            if (!str.isEmpty()) exif->fGPSStatus.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMeasureMode");
            if (!str.isEmpty()) exif->fGPSMeasureMode.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSTrackRef");
            if (!str.isEmpty()) exif->fGPSTrackRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSImgDirectionRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMapDatum");
            if (!str.isEmpty()) exif->fGPSMapDatum.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLatitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLongitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestBearingRef");
            if (!str.isEmpty()) exif->fGPSDestBearingRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestDistanceRef");
            if (!str.isEmpty()) exif->fGPSDestDistanceRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSProcessingMethod");
            if (!str.isEmpty()) exif->fGPSProcessingMethod.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSAreaInformation");
            if (!str.isEmpty()) exif->fGPSAreaInformation.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDateStamp");
            if (!str.isEmpty()) exif->fGPSDateStamp.Set_ASCII(str.toAscii());

            // Rational Tags

            if (meta.getExifTagRational("Exif.Photo.ExposureTime", num, den))          exif->fExposureTime          = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FNumber", num, den))               exif->fFNumber               = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ShutterSpeedValue", num, den))     exif->fShutterSpeedValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ApertureValue", num, den))         exif->fApertureValue         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.BrightnessValue", num, den))       exif->fBrightnessValue       = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ExposureBiasValue", num, den))     exif->fExposureBiasValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.MaxApertureValue", num, den))      exif->fMaxApertureValue      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalLength", num, den))           exif->fFocalLength           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.DigitalZoomRatio", num, den))      exif->fDigitalZoomRatio      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.SubjectDistance", num, den))       exif->fSubjectDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Image.BatteryLevel", num, den))          exif->fBatteryLevelR         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneXResolution", num, den)) exif->fFocalPlaneXResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneYResolution", num, den)) exif->fFocalPlaneYResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSAltitude", num, den))         exif->fGPSAltitude           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDOP", num, den))              exif->fGPSDOP                = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSSpeed", num, den))            exif->fGPSSpeed              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTrack", num, den))            exif->fGPSTrack              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSImgDirection", num, den))     exif->fGPSImgDirection       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestBearing", num, den))      exif->fGPSDestBearing        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestDistance", num, den))     exif->fGPSDestDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLatitude", num, den))         exif->fGPSLatitude[0]        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLongitude", num, den))        exif->fGPSLongitude[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTimeStamp", num, den))        exif->fGPSTimeStamp[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLatitude", num, den))     exif->fGPSDestLatitude[0]    = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLongitude", num, den))    exif->fGPSDestLongitude[0]   = dng_urational(num, den);

            // Integer Tags

            if (meta.getExifTagLong("Exif.Photo.ExposureProgram", val))          exif->fExposureProgram          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.MeteringMode", val))             exif->fMeteringMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.LightSource", val))              exif->fLightSource              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Flash", val))                    exif->fFlash                    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SensingMethod", val))            exif->fSensingMethod            = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FileSource", val))               exif->fFileSource               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneType", val))                exif->fSceneType                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.CustomRendered", val))           exif->fCustomRendered           = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ExposureMode", val))             exif->fExposureMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.WhiteBalance", val))             exif->fWhiteBalance             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneCaptureType", val))         exif->fSceneCaptureType         = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.GainControl", val))              exif->fGainControl              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Contrast", val))                 exif->fContrast                 = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Saturation", val))               exif->fSaturation               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Sharpness", val))                exif->fSharpness                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SubjectDistanceRange", val))     exif->fSubjectDistanceRange     = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalLengthIn35mmFilm", val))    exif->fFocalLengthIn35mmFilm    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ComponentsConfiguration", val))  exif->fComponentsConfiguration  = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelXDimension", val))          exif->fPixelXDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelYDimension", val))          exif->fPixelYDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalPlaneResolutionUnit", val)) exif->fFocalPlaneResolutionUnit = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSVersionID", val))           exif->fGPSVersionID             = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSAltitudeRef", val))         exif->fGPSAltitudeRef           = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSDifferential", val))        exif->fGPSDifferential          = (uint32)val;
        }

        // Markernote backup.

        QByteArray mkrnts = meta.getExifTagData("Exif.Photo.MakerNote");
        if (!mkrnts.isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: Backup Makernote (" << mkrnts.size() << " bytes)" << endl;

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(mkrnts.data(), mkrnts.size());
            AutoPtr<dng_memory_block> block(host.Allocate(mkrnts.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), mkrnts.size());
            negative->SetMakerNote(block);
            negative->SetMakerNoteSafety(true);
        }

        if (d->backupOriginalRawFile)
        {
            kDebug( 51000 ) << "DNGWriter: Backup Original RAW file (" << inputInfo.size() << " bytes)" << endl;

            // Compress Raw file data to Zip archive.

            QTemporaryFile zipFile;
            if (!zipFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write Zip Raw file. Aborted..." << endl;
                return -1;
            }
            KZip zipArchive(zipFile.fileName());
            zipArchive.open(QIODevice::WriteOnly);
            zipArchive.setCompression(KZip::DeflateCompression);
            zipArchive.addLocalFile(inputFile(), inputFile());
            zipArchive.close();

            // Load Zip Archive in a byte array

            QFileInfo zipFileInfo(zipFile.fileName());
            QByteArray zipRawFileData;
            zipRawFileData.resize(zipFileInfo.size());
            QDataStream dataStream(&zipFile);
            dataStream.readRawData(zipRawFileData.data(), zipRawFileData.size());
            kDebug( 51000 ) << "DNGWriter: Zipped RAW file size " << zipRawFileData.size() << " bytes" << endl;

            // Pass byte array to DNG sdk and compute MD5 fingerprint.

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(zipRawFileData.data(), zipRawFileData.size());
            AutoPtr<dng_memory_block> block(host.Allocate(zipRawFileData.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), zipRawFileData.size());

            dng_md5_printer md5;
            md5.Process(block->Buffer(), block->LogicalSize());
            negative->SetOriginalRawFileData(block);
            negative->SetOriginalRawFileDigest(md5.Result());
            negative->ValidateOriginalRawFileDigest();

            zipFile.remove();
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Build DNG Negative" << endl;

        // Assign Raw image data.
        negative->SetStage1Image(image);

        // Compute linearized and range mapped image
        negative->BuildStage2Image(host);

        // Compute demosaiced image (used by preview and thumbnail)
        negative->BuildStage3Image(host);

        negative->SynchronizeMetadata();
        negative->RebuildIPTC();

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        dng_preview_list previewList;

// NOTE: something is wrong with Qt < 4.4.0 to import TIFF data as stream in QImage.
#if QT_VERSION >= 0x40400

        if (d->previewMode != DNGWriter::NONE)
        {
            kDebug( 51000 ) << "DNGWriter: DNG preview image creation" << endl;

            // Construct a preview image as TIFF format.
            AutoPtr<dng_image> tiffImage;
            dng_render tiff_render(host, *negative);
            tiff_render.SetFinalSpace(dng_space_sRGB::Get());
            tiff_render.SetFinalPixelType(ttByte);
            tiff_render.SetMaximumSize(d->previewMode == MEDIUM ? 1280 : width);
            tiffImage.Reset(tiff_render.Render());

            dng_image_writer tiff_writer;
            AutoPtr<dng_memory_stream> dms(new dng_memory_stream(gDefaultDNGMemoryAllocator));

            tiff_writer.WriteTIFF(host, *dms, *tiffImage.Get(), piRGB,
                                  ccUncompressed, negative.Get(), &tiff_render.FinalSpace());

            // Write TIFF preview image data to a temp JPEG file
            std::vector<char> tiff_mem_buffer(dms->Length());
            dms->SetReadPosition(0);
            dms->Get(&tiff_mem_buffer.front(), tiff_mem_buffer.size());
            dms.Reset();

            QImage pre_image;
            if (!pre_image.loadFromData((uchar*)&tiff_mem_buffer.front(), tiff_mem_buffer.size(), "TIFF"))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot load TIFF preview data in memory. Aborted..." << endl;
                return -1;
            }

            QTemporaryFile previewFile;
            if (!previewFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            if (!pre_image.save(previewFile.fileName(), "JPEG", 90))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot save file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            // Load JPEG preview file data in DNG preview container.
            AutoPtr<dng_jpeg_preview> jpeg_preview;
            jpeg_preview.Reset(new dng_jpeg_preview);
            jpeg_preview->fPhotometricInterpretation = piYCbCr;
            jpeg_preview->fPreviewSize.v             = pre_image.height();
            jpeg_preview->fPreviewSize.h             = pre_image.width();
            jpeg_preview->fCompressedData.Reset(host.Allocate(previewFile.size()));

            QDataStream previewStream( &previewFile );
            previewStream.readRawData(jpeg_preview->fCompressedData->Buffer_char(), previewFile.size());

            AutoPtr<dng_preview> pp( dynamic_cast<dng_preview*>(jpeg_preview.Release()) );
            previewList.Append(pp);

            previewFile.remove();
        }

#endif /* QT_VERSION >= 0x40400 */

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG thumbnail creation" << endl;

        dng_image_preview thumbnail;
        dng_render thumbnail_render(host, *negative);
        thumbnail_render.SetFinalSpace(dng_space_sRGB::Get());
        thumbnail_render.SetFinalPixelType(ttByte);
        thumbnail_render.SetMaximumSize(256);
        thumbnail.fImage.Reset(thumbnail_render.Render());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Creating DNG file " << outputInfo.fileName() << endl;

        dng_image_writer writer;
        dng_file_stream filestream(QFile::encodeName(dngFilePath), true);

        writer.WriteDNG(host, filestream, *negative.Get(), thumbnail, 
                        d->jpegLossLessCompression ? ccJPEG : ccUncompressed,
                        &previewList);
    }

    catch (const dng_exception &exception)
    {
        int ret = exception.ErrorCode();
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code (" << ret << ")" << endl;
        return ret;
    }

    catch (...)
    {
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code unknow" << endl;
        return dng_error_unknown;
    }

    kDebug( 51000 ) << "DNGWriter: DNG conversion complete..." << endl;

    return dng_error_none;
}
コード例 #13
0
ファイル: ksplanet.cpp プロジェクト: Bugsbane/kstars
void KSPlanet::calcEcliptic(double Tau, EclipticPosition &epret) const {
    double sum[6];
    OrbitDataColl odc;
    double Tpow[6];

    Tpow[0] = 1.0;
    for (int i=1; i<6; ++i) {
        Tpow[i] = Tpow[i-1] * Tau;
    }

    if ( ! odm.loadData( odc, untranslatedName() ) ) {
        epret.longitude = dms(0.0);
        epret.latitude  = dms(0.0);
        epret.radius    = 0.0;
        qWarning() << "Could not get data for '" << name() << "'" << endl;
        return;
    }

    //Ecliptic Longitude
    for (int i=0; i<6; ++i) {
        sum[i] = 0.0;
        for (int j = 0; j < odc.Lon[i].size(); ++j) {
            sum[i] += odc.Lon[i][j].A * cos( odc.Lon[i][j].B + odc.Lon[i][j].C*Tau );
            /*
            qDebug() << "sum[" << i <<"] =" << sum[i] <<
            	" A = " << odc.Lon[i][j].A << " B = " << odc.Lon[i][j].B <<
            	" C = " << odc.Lon[i][j].C << endl;
            	*/
        }
        sum[i] *= Tpow[i];
        //qDebug() << name() << " : sum[" << i << "] = " << sum[i];
    }

    epret.longitude.setRadians( sum[0] + sum[1] + sum[2] + sum[3] + sum[4] + sum[5] );
    epret.longitude.setD( epret.longitude.reduce().Degrees() );

    //Compute Ecliptic Latitude
    for (uint i=0; i<6; ++i) {
        sum[i] = 0.0;
        for (int j = 0; j < odc.Lat[i].size(); ++j) {
            sum[i] += odc.Lat[i][j].A * cos( odc.Lat[i][j].B + odc.Lat[i][j].C*Tau );
        }
        sum[i] *= Tpow[i];
    }


    epret.latitude.setRadians( sum[0] + sum[1] + sum[2] + sum[3] + sum[4] + sum[5] );

    //Compute Heliocentric Distance
    for (uint i=0; i<6; ++i) {
        sum[i] = 0.0;
        for (int j = 0; j < odc.Dst[i].size(); ++j) {
            sum[i] += odc.Dst[i][j].A * cos( odc.Dst[i][j].B + odc.Dst[i][j].C*Tau );
        }
        sum[i] *= Tpow[i];
    }

    epret.radius = sum[0] + sum[1] + sum[2] + sum[3] + sum[4] + sum[5];

    /*
    qDebug() << name() << " pre: Lat = " << epret.latitude.toDMSString() << " Long = " <<
    	epret.longitude.toDMSString() << " Dist = " << epret.radius << endl;
    */

}
コード例 #14
0
void SupernovaeComponent::loadData()
{
    QString line;
    QString serialNo, hostGalaxy, date, type, offset, SNPosition, discoverers ;
    QStringList fields;
    dms ra, dec;
    float magnitude;
    KSFileReader fileReader;
    bool ok;
    kDebug()<<"Loading Supernovae data"<<endl;
    if( !fileReader.open("supernovae.dat")) return;
    //m_ObjectList.clear();
    latest.clear();
    objectNames(SkyObject::SUPERNOVA).clear();

    while (fileReader.hasMoreLines())
    {
        line=fileReader.readLine();
        Supernova *sup=0;
        //kDebug()<<line[0]<<" "<<line.size()<<endl;
        if(line[0]=='#' || line.size()<10) continue;
        fields=line.split(",");
        serialNo=fields.at(0);
        hostGalaxy=fields.at(1);
        date=fields.at(2);

        ra=dms(fields.at(3),false);
        dec=dms(fields.at(4));

        offset=fields.at(5);

        if(fields.at(6).isEmpty())
            magnitude=99;
        else
            magnitude=fields.at(6).toFloat(&ok);

        SNPosition=fields.at(8);
        type=fields.at(10);
        discoverers=fields.at(12);

        sup=new Supernova(ra, dec, date, magnitude, serialNo, type, hostGalaxy, offset, discoverers);

        if (!m_ObjectList.empty())
        {
            if ( findByName(sup->name() ) == 0 )
            {
                //kDebug()<<"List of supernovae not empty. Found new supernova";
                m_ObjectList.append(sup);
                latest.append(sup);
            }/*
            else
                m_ObjectList.append(sup);*/
        }
        else             //if the list is empty
        {
            m_ObjectList.append(sup);
            latest.append(sup);
            //notifyNewSupernovae();
        }

        objectNames(SkyObject::SUPERNOVA).append(sup->name());
    }
    //notifyNewSupernovae();
}
コード例 #15
0
ファイル: exporteyepieceview.cpp プロジェクト: KDE/kstars
void ExportEyepieceView::render() {
    float baseWidth = m_renderChart->width();
    float baseHeight = m_renderChart->height();

    if( m_renderImage )
        m_output = QImage( int(baseWidth * 2.25), int(baseHeight), QImage::Format_ARGB32 ); // 0.25 * baseWidth gap between the images
    else
        m_output = QImage( int(baseWidth), int(baseHeight), QImage::Format_ARGB32 );

    m_output.fill( Qt::white );
    QPainter op( &m_output );
    op.drawPixmap( QPointF(0,0), *m_renderChart );
    if( m_renderImage )
        op.drawPixmap( QPointF(baseWidth * 1.25,0), *m_renderImage );

    if( m_tickConfig != 0 && Options::useAltAz() ) { // FIXME: this is very skymap-state-heavy for my happiness --asimha
        // we must draw ticks
        QImage tickOverlay( baseWidth, baseHeight, QImage::Format_ARGB32 );
        tickOverlay.fill( Qt::transparent );

        QPainter p( &tickOverlay );
        p.setPen( Qt::red ); // FIXME: Determine color depending on situation, or make it configurable
        double rEnd = 0.85 * ( baseWidth / 2.);
        double rStart = 0.8 * ( baseWidth / 2.);
        QFont font;
        font.setPixelSize( ( rEnd - rStart ) );
        p.setFont( font );

        GeoLocation *geo = KStarsData::Instance()->geo();
        double alt0 = m_sp->alt().Degrees(); // altitude when hour = 0, i.e. at m_dt (see below).
        dms northAngle0 = EyepieceField::findNorthAngle( m_sp, geo->lat() );

        for( float hour = -3.5; hour <= 3.5; hour += 0.5 ) {
            dms rotation; // rotation

            // FIXME: Code duplication : code duplicated from EyepieceField. This should really be a member of SkyPoint or something.
            SkyPoint sp = SkyPoint::timeTransformed( m_sp, m_dt, geo, hour );
            double alt = sp.alt().Degrees();
            dms northAngle = EyepieceField::findNorthAngle( &sp, geo->lat() );

            rotation = ( northAngle - northAngle0 );
            if( m_tickConfig == 2 ) {
                // Dobsonian: add additional CW rotation by altitude, but compensate for the fact that we've already rotated by alt0
                rotation = rotation - dms( ( alt - alt0 ) );
            }
            rotation = rotation.reduce();
            p.save();
            p.translate( baseWidth/2.0, baseHeight/2.0 );
            p.rotate( -( rotation.Degrees() + 90.0 ) );
            p.drawLine( QPointF( rStart, 0 ), QPointF( rEnd, 0 ) );
            QTime ct = geo->UTtoLT( m_dt.addSecs( 3600.0 * hour ) ).time();
            p.drawText( QPointF( rEnd + 0.01 * baseWidth, 0 ), QString().sprintf( "%02d:%02d", ct.hour(), ct.minute() ) );
            p.restore();
        }
        p.end();
        op.drawImage( QPointF(0,0), tickOverlay );
        if( m_renderImage ) {
            op.drawImage( QPointF(baseWidth * 1.25, 0), tickOverlay );
        }
    }
    op.end();

    m_outputDisplay->setPixmap( (QPixmap::fromImage( m_output )).scaled( m_outputDisplay->width(), m_outputDisplay->height(), Qt::KeepAspectRatio, Qt::SmoothTransformation ) );
}
コード例 #16
0
ファイル: image.c プロジェクト: 00001/plan9port
Picture*
image(Angle ra, Angle dec, Angle wid, Angle hig)
{
	Pix *p;
	uchar *b, *up;
	int i, j, sx, sy, x, y;
	char file[50];
	Picture *pic;
	Img* ip;
	int lowx, lowy, higx, higy;
	int slowx, slowy, shigx, shigy;
	Header *h;
	Angle d, bd;
	Plate *pp, *bp;

	if(gam.gamma == 0)
		gam.gamma = -1;
	if(gam.max == gam.min) {
		gam.max = 17600;
		gam.min = 2500;
	}
	gam.absgamma = gam.gamma;
	gam.neg = 0;
	if(gam.absgamma < 0) {
		gam.absgamma = -gam.absgamma;
		gam.neg = 1;
	}
	gam.mult1 = 1. / (gam.max - gam.min);
	gam.mult2 = 255. * gam.mult1;

	if(nplate == 0)
		getplates();

	bp = 0;
	bd = 0;
	for(i=0; i<nplate; i++) {
		pp = &plate[i];
		d = dist(ra, dec, pp->ra, pp->dec);
		if(bp == 0 || d < bd) {
			bp = pp;
			bd = d;
		}
	}

	if(debug)
		Bprint(&bout, "best plate: %s %s disk %d %s\n",
			hms(bp->ra), dms(bp->dec),
			bp->disk, bp->rgn);

	h = getheader(bp->rgn);
	xypos(h, ra, dec, 0, 0);
	if(wid <= 0 || hig <= 0) {
		lowx = h->x;
		lowy = h->y;
		lowx = (lowx/500) * 500;
		lowy = (lowy/500) * 500;
		higx = lowx + 500;
		higy = lowy + 500;
	} else {
		lowx = h->x - wid*ARCSECONDS_PER_RADIAN*1000 /
			(h->param[Pxpixelsz]*h->param[Ppltscale]*2);
		lowy = h->y - hig*ARCSECONDS_PER_RADIAN*1000 /
			(h->param[Pypixelsz]*h->param[Ppltscale]*2);
		higx = h->x + wid*ARCSECONDS_PER_RADIAN*1000 /
			(h->param[Pxpixelsz]*h->param[Ppltscale]*2);
		higy = h->y + hig*ARCSECONDS_PER_RADIAN*1000 /
			(h->param[Pypixelsz]*h->param[Ppltscale]*2);
	}
	free(h);

	if(lowx < 0) lowx = 0;
	if(higx < 0) higx = 0;
	if(lowy < 0) lowy = 0;
	if(higy < 0) higy = 0;
	if(lowx > 14000) lowx = 14000;
	if(higx > 14000) higx = 14000;
	if(lowy > 14000) lowy = 14000;
	if(higy > 14000) higy = 14000;

	if(debug)
		Bprint(&bout, "xy on plate: %d,%d %d,%d\n",
			lowx,lowy, higx, higy);

	if(lowx >= higx || lowy >=higy) {
		Bprint(&bout, "no image found\n");
		return 0;
	}

	b = malloc((higx-lowx)*(higy-lowy)*sizeof(*b));
	if(b == 0) {
 emalloc:
		fprint(2, "malloc error\n");
		return 0;
	}
	memset(b, 0, (higx-lowx)*(higy-lowy)*sizeof(*b));

	slowx = lowx/500;
	shigx = (higx-1)/500;
	slowy = lowy/500;
	shigy = (higy-1)/500;

	for(sx=slowx; sx<=shigx; sx++)
	for(sy=slowy; sy<=shigy; sy++) {
		if(sx < 0 || sx >= nelem(rad28) || sy < 0 || sy >= nelem(rad28)) {
			fprint(2, "bad subplate %d %d\n", sy, sx);
			free(b);
			return 0;
		}
		sprint(file, "%s/%s/%s.%c%c",
			dssmount(bp->disk),
			bp->rgn, bp->rgn,
			rad28[sy],
			rad28[sx]);

		ip = dssread(file);
		if(ip == 0) {
			fprint(2, "can't read %s: %r\n", file);
			free(b);
			return 0;
		}

		x = sx*500;
		y = sy*500;
		for(j=0; j<ip->ny; j++) {
			if(y+j < lowy || y+j >= higy)
				continue;
			p = &ip->a[j*ip->ny];
			up = b + (higy - (y+j+1))*(higx-lowx) + (x - lowx);
			for(i=0; i<ip->nx; i++) {
				if(x+i >= lowx && x+i < higx)
					*up = dogamma(*p);
				up++;
				p += 1;
			}
		}
		free(ip);
	}

	pic = malloc(sizeof(Picture));
	if(pic == 0){
		free(b);
		goto emalloc;
	}
	pic->minx = lowx;
	pic->miny = lowy;
	pic->maxx = higx;
	pic->maxy = higy;
	pic->data = b;
	strcpy(pic->name, bp->rgn);
	return pic;
}
コード例 #17
0
ファイル: ksasteroid.cpp プロジェクト: Bugsbane/kstars
bool KSAsteroid::findGeocentricPosition( const KSNumbers *num, const KSPlanetBase *Earth ) {
    //determine the mean anomaly for the desired date.  This is the mean anomaly for the
    //ephemeis epoch, plus the number of days between the desired date and ephemeris epoch,
    //times the asteroid's mean daily motion (360/P):
    dms m = dms( double( M.Degrees() + ( num->julianDay() - JD ) * 360.0/P ) ).reduce();
    double sinm, cosm;
    m.SinCos( sinm, cosm );

    //compute eccentric anomaly:
    double E = m.Degrees() + e*180.0/dms::PI * sinm * ( 1.0 + e*cosm );

    if ( e > 0.05 ) { //need more accurate approximation, iterate...
        double E0;
        int iter(0);
        do {
            E0 = E;
            iter++;
            E = E0 - ( E0 - e*180.0/dms::PI *sin( E0*dms::DegToRad ) - m.Degrees() )/(1 - e*cos( E0*dms::DegToRad ) );
        } while ( fabs( E - E0 ) > 0.001 && iter < 1000 );
    }

    double sinE, cosE;
    dms E1( E );
    E1.SinCos( sinE, cosE );

    double xv = a * ( cosE - e );
    double yv = a * sqrt( 1.0 - e*e ) * sinE;

    //v is the true anomaly; r is the distance from the Sun
    double v = atan2( yv, xv ) / dms::DegToRad;
    double r = sqrt( xv*xv + yv*yv );

    //vw is the sum of the true anomaly and the argument of perihelion
    dms vw( v + w.Degrees() );
    double sinN, cosN, sinvw, cosvw, sini, cosi;

    N.SinCos( sinN, cosN );
    vw.SinCos( sinvw, cosvw );
    i.SinCos( sini, cosi );

    //xh, yh, zh are the heliocentric cartesian coords with the ecliptic plane congruent with zh=0.
    double xh = r * ( cosN * cosvw - sinN * sinvw * cosi );
    double yh = r * ( sinN * cosvw + cosN * sinvw * cosi );
    double zh = r * ( sinvw * sini );

    //the spherical ecliptic coordinates:
    double ELongRad = atan2( yh, xh );
    double ELatRad = atan2( zh, r );

    helEcPos.longitude.setRadians( ELongRad );
    helEcPos.latitude.setRadians( ELatRad );
    setRsun( r );

    if ( Earth ) {
        //xe, ye, ze are the Earth's heliocentric cartesian coords
        double cosBe, sinBe, cosLe, sinLe;
        Earth->ecLong().SinCos( sinLe, cosLe );
        Earth->ecLat().SinCos( sinBe, cosBe );

        double xe = Earth->rsun() * cosBe * cosLe;
        double ye = Earth->rsun() * cosBe * sinLe;
        double ze = Earth->rsun() * sinBe;

        //convert to geocentric ecliptic coordinates by subtracting Earth's coords:
        xh -= xe;
        yh -= ye;
        zh -= ze;
    }

    //the spherical geocentricecliptic coordinates:
    ELongRad = atan2( yh, xh );
    double rr = sqrt( xh*xh + yh*yh + zh*zh );
    ELatRad = atan2( zh, rr );

    ep.longitude.setRadians( ELongRad );
    ep.latitude.setRadians( ELatRad );
    if ( Earth ) setRearth( Earth );

    EclipticToEquatorial( num->obliquity() );
    nutate( num );
    aberrate( num );

    return true;
}
コード例 #18
0
ファイル: arrows.cpp プロジェクト: ushakov/mapsoft
int arr3[] =
{1,0,1, 1,0,0, 1,0,1, 1,1,1, 1,1,1, 1,1,1, 1,0,1, 0,0,1,
 0,1,0, 1,1,0, 1,1,0, 1,1,0, 0,1,0, 0,1,1, 0,1,1, 0,1,1,
 1,1,1, 1,1,1, 1,0,1, 1,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1};

int arr4[] =
{1,1,0,1, 1,0,1,0, 1,1,0,1, 1,0,0,1, 1,1,0,0, 1,1,0,1, 1,0,0,1, 1,1,0,0,
 1,0,1,0, 1,0,1,0, 1,0,1,0, 1,1,1,0, 1,0,1,0, 1,0,1,0, 1,0,1,0, 1,0,1,1,
 1,0,0,1, 1,1,0,1, 1,1,0,0, 1,0,0,1, 1,1,0,1, 1,0,1,0, 1,1,0,1, 1,1,0,0,
 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1};

inline int dms(int d, int m, int s) {return d*3600+m*60+s;}

                                    // координаты углов
const int lat1 = dms(55,00,00)/3; // данные задаем в секундах, деленных на три
const int lat2 = dms(55,10,00)/3;
const int lon1 = dms(111,00,00)/3;
const int lon2 = dms(111,10,00)/3;

main(){

  map_tracer m(lat1, lon1, lat2, lon2);
  m.set_dirs(100,100);

  const int arr_size=4;
  print_pnm_head(m.w*arr_size, m.h*arr_size);
  simple_rainbow R(500,3000);

  for (int lat=m.lat2-1; lat>=m.lat1; lat--){
    for (int row=0; row<arr_size; row++){
コード例 #19
0
/*
 * @short Initialize the comets list.
 * Reads in the comets data from the comets.dat file.
 *
 * Populate the list of Comets from the data file.
 * The data file is a CSV file with the following columns :
 * @li 1 full name [string]
 * @li 2 modified julian day of orbital elements [int]
 * @li 3 perihelion distance in AU [double]
 * @li 4 eccentricity of orbit [double]
 * @li 5 inclination angle of orbit in degrees [double]
 * @li 6 argument of perihelion in degrees [double]
 * @li 7 longitude of the ascending node in degrees [double]
 * @li 8 time of perihelion passage (YYYYMMDD.DDD) [double]
 * @li 9 orbit solution ID [string]
 * @li 10 Near-Earth Object (NEO) flag [bool]
 * @li 11 comet total magnitude parameter [float]
 * @li 12 comet nuclear magnitude parameter [float]
 * @li 13 object diameter (from equivalent sphere) [float]
 * @li 14 object bi/tri-axial ellipsoid dimensions [string]
 * @li 15 geometric albedo [float]
 * @li 16 rotation period [float]
 * @li 17 orbital period [float]
 * @li 18 earth minimum orbit intersection distance [double]
 * @li 19 orbit classification [string]
 * @li 20 comet total magnitude slope parameter
 * @li 21 comet nuclear magnitude slope parameter
 * @note See KSComet constructor for more details.
 */
void CometsComponent::loadData() {
    QString name, orbit_id, orbit_class, dimensions;
    bool neo;
    int mJD;
    double q, e, dble_i, dble_w, dble_N, Tp, earth_moid;
    long double JD;
    float M1, M2, K1, K2, diameter, albedo, rot_period, period;

    emitProgressText(i18n("Loading comets"));
    objectNames(SkyObject::COMET).clear();

    QList< QPair<QString, KSParser::DataTypes> > sequence;
    sequence.append(qMakePair(QString("full name"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("epoch_mjd"), KSParser::D_INT));
    sequence.append(qMakePair(QString("q"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("e"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("i"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("w"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("om"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("tp_calc"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("orbit_id"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("neo"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("M1"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("M2"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("diameter"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("extent"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("albedo"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("rot_period"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("per_y"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("moid"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("class"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("H"), KSParser::D_SKIP));
    sequence.append(qMakePair(QString("G"), KSParser::D_SKIP));

    QString file_name = QStandardPaths::locate(QStandardPaths::DataLocation, QString("comets.dat") );
    KSParser cometParser(file_name, '#', sequence);

    QHash<QString, QVariant> row_content;
    while (cometParser.HasNextRow()){
        KSComet *com = 0;
        row_content = cometParser.ReadNextRow();
        name   = row_content["full name"].toString();
        name   = name.trimmed();
        mJD    = row_content["epoch_mjd"].toInt();
        q    = row_content["q"].toDouble();
        e    = row_content["e"].toDouble();
        dble_i = row_content["i"].toDouble();
        dble_w = row_content["w"].toDouble();
        dble_N = row_content["om"].toDouble();
        Tp     = row_content["tp_calc"].toDouble();
        orbit_id = row_content["orbit_id"].toString();
        neo = row_content["neo"] == "Y";

        if(row_content["M1"].toFloat()==0.0)
            M1 = 101.0;
        else
            M1 = row_content["M1"].toFloat();

        if(row_content["M2"].toFloat()==0.0)
            M2 = 101.0;
        else
            M2 = row_content["M2"].toFloat();

        diameter = row_content["diameter"].toFloat();
        dimensions = row_content["extent"].toString();
        albedo  = row_content["albedo"].toFloat();
        rot_period = row_content["rot_period"].toFloat();
        period  = row_content["per_y"].toFloat();
        earth_moid  = row_content["moid"].toDouble();
        orbit_class = row_content["class"].toString();
        K1 = row_content["H"].toFloat();
        K2 = row_content["G"].toFloat();

        JD = static_cast<double>( mJD ) + 2400000.5;

        com = new KSComet( name, QString(), JD, q, e,
                           dms( dble_i ), dms( dble_w ),
                           dms( dble_N ), Tp, M1, M2,
                           K1, K2 );
        com->setOrbitID( orbit_id );
        com->setNEO( neo );
        com->setDiameter( diameter );
        com->setDimensions( dimensions );
        com->setAlbedo( albedo );
        com->setRotationPeriod( rot_period );
        com->setPeriod( period );
        com->setEarthMOID( earth_moid );
        com->setOrbitClass( orbit_class );
        com->setAngularSize( 0.005 );
        m_ObjectList.append( com );

        // Add *short* name to the list of object names
        objectNames( SkyObject::COMET ).append( com->name() );
    }
}
コード例 #20
0
ファイル: cmoon.c プロジェクト: koniti/astronomical-almanac
/* Calculate geometric position of the Moon and apply
 * approximate corrections to find apparent position,
 * phase of the Moon, etc. for AA.ARC.
 */
int domoon()
{
int i, prtsav;
double ra0, dec0, r;
double x, y, z, lon0;
double c, s, temp;
double pp[3], qq[3];
double acos();

/* Compute obliquity of the ecliptic, coseps, and sineps
 */
epsiln(TDT);

/* Run the orbit calculation twice, at two different times,
 * in order to find the rate of change of R.A. and Dec.
 */

/* Calculate for 0.001 day ago
 */
prtsav = prtflg;
prtflg = 0; /* disable display */
moonll(TDT-0.001, moonpp, moonpol);
/*
lonlat( rearth, TDT, eapolar ); // precess earth to date
// lonlat( rearth, TDT, eapolar, 1 );
*/
ra0 = ra;
dec0 = dec;
lon0 = l;
prtflg = prtsav;

/* Calculate for present instant.
 */
moonll(TDT, moonpp, moonpol);

/* The rates of change.  These are used by altaz() to
 * correct the time of rising, transit, and setting.
 */
 dradt = ra - ra0;
 if (dradt >= PI)
   dradt = dradt - 2.0 * PI;
 if (dradt <= -PI)
   dradt = dradt + 2.0 * PI;
 dradt = 1000.0 * dradt;
 ddecdt = 1000.0*(dec-dec0);


/* Post the ecliptic longitude and latitude, in radians,
 * and the radius in au.
 */
obpolar[0] = l;
obpolar[1] = B;
r = 1.0/sin(p); /* distance in earth-radii */
ra0 = Rearth*r; /* factor is radius of earth in au */
obpolar[2] = ra0;

/* Rate of change in longitude, degrees per day
 * used for phase of the moon
 */
lon0 = 1000.0*RTD*(l - lon0);

/* convert to ecliptic rectangular coordinates */

z = ra0 * cos(B);
x = z * cos(l);
y = z * sin(l);
z = ra0 * sin(B);
/* convert to equatorial coordinates */
pp[0] = x;
pp[1] = y * coseps - z * sineps;
pp[2] = y * sineps + z * coseps;

/* Find sun-moon-earth angles */
precess( rearth, TDT, -1 );
for( i=0; i<3; i++ )
	qq[i] = rearth[i] + pp[i];
angles( pp, qq, rearth );

/* Display answers
 */
if( prtflg )
	{
	  /* Apparent ecliptic coordinates.
	     The nutation in longitude is added to the ecliptic longitude.
	     See AA page C2.  First rotate the coordinate system about the
	     x axis from mean equator to ecliptic.
	     Then rotate about the z axis by the nutation in longitude.  */
	  x = Mapp[0];
	  y = Mapp[1];
	  z = Mapp[2];
	  temp  =  coseps * y  +  sineps * z;
	  z     = -sineps * y  +  coseps * z;
	  y = temp;

	  c = cos(nutl);
	  s = sin(nutl);
	  temp = c * x - s * y;
	  y    = s * x + c * y;
	  x = temp;

	  Mapp[0] = zatan2( x, y );
	  Mapp[1] = asin( z );
	  Mapp[2] = Rem;
	printf( "Apparent geocentric longitude %.3f deg", RTD*Mapp[0] );
	printf( "   latitude %.3f deg\n", RTD*Mapp[1] );
	printf( "Distance %.3f Earth-radii\n", r );
	printf( "Horizontal parallax" );
	dms( p );
	printf( "Semidiameter" );
	x = 0.272453 * p  +  0.0799/RTS; /* AA page L6 */
	dms( x );

	x = RTD * acos(-ep);
	printf( "\nElongation from sun %.2f deg,", x );
	x = 0.5 * (1.0 + pq);
	printf( "  Illuminated fraction %.2f\n", x );

/* Find phase of the Moon by comparing Moon's longitude
 * with Earth's longitude.
 *
 * The number of days before or past indicated phase is
 * estimated by assuming the true longitudes change linearly
 * with time.  These rates are estimated for the date, but
 * do not stay constant.  The error can exceed 0.15 day in 4 days.
 */
/* Apparent longitude of sun.
 * Moon's longitude was already corrected for light time.
 */
	y = eapolar[0] - 20.496/(RTS*eapolar[2]);
	x = obpolar[0] - y;
	x = modtp( x ) * RTD;	/* difference in longitude */
	i = x/90;		/* number of quarters */
	x = (x - i*90.0);	/* phase angle mod 90 degrees */

/* days per degree of phase angle */
	z = 1.0/(lon0 - (0.9856/eapolar[2]));

	if( x > 45.0 )
		{
		y = -(x - 90.0)*z;
		if( y > 1.0 )
			printf( "Phase %.1f days before ", y );
		else
			printf( "Phase %.2f days before ", y );
		i = (i+1) & 3;
		}
	else
		{
		y = x*z;
		if( y > 1.0 )
			printf( "Phase %.1f days past ", y );
		else
			printf( "Phase %.2f days past ", y );
		}


	switch(i)
		{
		case 0: printf( "Full Moon\n" ); break;
		case 1: printf( "Third Quarter\n" ); break;
		case 2: printf( "New Moon\n" ); break;
		case 3: printf( "First Quarter\n" ); break;
		}
	} /* if prtflg */

printf( "    Apparent:  R.A." );
hms(ra);
printf( "Declination" );
dms(dec);
printf( "\n" );

/* Compute and display topocentric position (altaz.c)
 */
pp[0] = ra;
pp[1] = dec;
pp[2] = r * Rearth;
altaz( pp, UT );
return(0);
}
コード例 #21
0
void ossimNitfProjectionFactory::parseGeographicString(
   const ossimString& geographicLocation, std::vector<ossimGpt>& gpts) const
{
   gpts.clear();
   
   if (geographicLocation.size() != 60)
   {
      return;
   }

   std::string::size_type geo_index = 0;
   for (int i=0; i<4; ++i)
   {
      //---
      // We have to split up the geographicLocation string for the dms class.
      // 
      // geographicLocation = ddmmssXdddmmssX (four times).
      // "dd mm ss X" has a string length of 10
      // "ddd mm ss X" has a string length of 11
      //---
      std::string::size_type lat_index = 0;
      std::string::size_type lon_index = 0;
      const char SPACE = ' ';
      ossimString latString(10, SPACE);
      ossimString lonString(11, SPACE);

      // degrees latitude
      latString[lat_index++] = geographicLocation[geo_index++];
      latString[lat_index++] = geographicLocation[geo_index++];
      ++lat_index;

      // minutes latitude
      latString[lat_index++] = geographicLocation[geo_index++];
      latString[lat_index++] = geographicLocation[geo_index++];
      ++lat_index;
      
      // seconds latitude
      latString[lat_index++] = geographicLocation[geo_index++];
      latString[lat_index++] = geographicLocation[geo_index++];
      ++lat_index;

      // hemisphere
      latString[lat_index++] = geographicLocation[geo_index++];
 
      // degrees longitude
      lonString[lon_index++] = geographicLocation[geo_index++];
      lonString[lon_index++] = geographicLocation[geo_index++];
      lonString[lon_index++] = geographicLocation[geo_index++];
      ++lon_index;

      // minutes longitude
      lonString[lon_index++] = geographicLocation[geo_index++];
      lonString[lon_index++] = geographicLocation[geo_index++];
      ++lon_index;

      // seconds longitude
      lonString[lon_index++] = geographicLocation[geo_index++];
      lonString[lon_index++] = geographicLocation[geo_index++];
      ++lon_index;

      // hemisphere
      lonString[lon_index++] = geographicLocation[geo_index++];

      // Convert to decimal degrees using the dms class.
      ossimGpt gpt;
      ossimDms dms(0.0);
      dms.setLatFlag(true);
      if ( ! dms.setDegrees(latString.c_str()) )
      {
         gpts.clear();
         return;
      }
      gpt.latd(dms.getDegrees());

      dms.setLatFlag(false);
      if ( ! dms.setDegrees(lonString.c_str()) )
      {
         gpts.clear();
         return;
      }
      gpt.lond(dms.getDegrees());

      gpts.push_back(gpt);

      if (traceDebug())
      {
         ossimNotify(ossimNotifyLevel_DEBUG)
            << "ossimNitfProjectionFactory::parseGeographicString DEBUG:"
            << "\nground point[" << i << "]:  " << gpt
            << std::endl;
      }
   }
}
コード例 #22
0
ファイル: kstarsdcop.cpp プロジェクト: felipebetancur/kstars
void KStars::setAltAz( double alt, double az ) {
    map()->setDestinationAltAz( dms(alt), dms(az) );
}
コード例 #23
0
ファイル: swewin.c プロジェクト: jacapoduri/MeteoAstrologia
static int swisseph(char *buf)
{
  char serr[AS_MAXCH*2], serr_save[AS_MAXCH], serr_warn[AS_MAXCH];
  char s[AS_MAXCH]; 
  char s1[AS_MAXCH], s2[AS_MAXCH];
  char star[AS_MAXCH];
  char *sp, *sp2;
  char se_pname[AS_MAXCH];
  char *spnam, *spnam2 = "";
  char *fmt = "PZBRS";
  char *plsel, *psp;
  char *gap = " ";
  double jut = 0.0, y_frac;
  int i, j;
  double hpos;
  int jday, jmon, jyear, jhour, jmin, jsec;
  int ipl, ipldiff = SE_SUN;
  double x[6], xequ[6], xcart[6], xcartq[6];
  double cusp[12+1];    /* cusp[0] + 12 houses */
  double ascmc[10];		/* asc, mc, vertex ...*/
  double ar, sinp;
  double a, sidt, armc, lon, lat;
  double eps_true, eps_mean, nutl, nuto;
  char ephepath[AS_MAXCH];
  char fname[AS_MAXCH];
  char splan[100], sast[AS_MAXCH];
  int nast, iast;
  long astno[100];
  long iflag = 0, iflag2;              /* external flag: helio, geo... */
  long iflgret;
  long whicheph = SEFLG_SWIEPH;
  AS_BOOL universal_time = FALSE;
  AS_BOOL calc_house_pos = FALSE;
  short gregflag;
  AS_BOOL diff_mode = FALSE;
  int round_flag = 0;
  double tjd_ut = 2415020.5;
  double tjd_et, t2;
  double delt;
  char bc[20];
  char *jul;
  int hsys = (int) *pd.hsysname;
  *serr = *serr_save = *serr_warn = '\0';
  strcpy(ephepath, SE_EPHE_PATH);
  if (strcmp(pd.ephe, ephe[1]) == 0) {
    whicheph = SEFLG_JPLEPH;
    strcpy(fname, SE_FNAME_DE406);
  } else if (strcmp(pd.ephe, ephe[0]) == 0) 
    whicheph = SEFLG_SWIEPH;
  else
    whicheph = SEFLG_MOSEPH;
  if (strcmp(pd.etut, "UT") == 0)
    universal_time = TRUE;
  if (strcmp(pd.plansel, plansel[0]) == 0) {
    plsel = PLSEL_D;
  } else if (strcmp(pd.plansel, plansel[1]) == 0) {
    plsel = PLSEL_P;
  } else if (strcmp(pd.plansel, plansel[2]) == 0) {
    plsel = PLSEL_A;
  }
  if (strcmp(pd.ctr, ctr[0]) == 0)
    calc_house_pos = TRUE;
  else if (strcmp(pd.ctr, ctr[1]) == 0) {
    iflag |= SEFLG_TOPOCTR;
    calc_house_pos = TRUE;
  } else if (strcmp(pd.ctr, ctr[2]) == 0) {
    iflag |= SEFLG_HELCTR;
  } else if (strcmp(pd.ctr, ctr[3]) == 0) {
    iflag |= SEFLG_BARYCTR;
  } else if (strcmp(pd.ctr, ctr[4]) == 0) {
    iflag |= SEFLG_SIDEREAL;
	swe_set_sid_mode(SE_SIDM_FAGAN_BRADLEY, 0, 0);
  } else if (strcmp(pd.ctr, ctr[5]) == 0) {
    iflag |= SEFLG_SIDEREAL;
	swe_set_sid_mode(SE_SIDM_LAHIRI, 0, 0);
#if 0
  } else {
    iflag &= ~(SEFLG_HELCTR | SEFLG_BARYCTR | SEFLG_TOPOCTR);
#endif
  }
  lon = pd.lon_deg + pd.lon_min / 60.0 + pd.lon_sec / 3600.0;
  if (*pd.lon_e_w == 'W')
    lon = -lon;
  lat = pd.lat_deg + pd.lat_min / 60.0 + pd.lat_sec / 3600.0;
  if (*pd.lat_n_s == 'S')
    lat = -lat;
  sprintf(s, "Planet Positions from %s \n\n", pd.ephe);
  do_print(buf, s);                               
  if (whicheph & SEFLG_JPLEPH)
    swe_set_jpl_file(fname);
  iflag = (iflag & ~SEFLG_EPHMASK) | whicheph;
  iflag |= SEFLG_SPEED;
#if 0
  if (pd.helio) iflag |= SEFLG_HELCTR;
#endif
  if ((long) pd.year * 10000L + (long) pd.mon * 100L + (long) pd.mday < 15821015L) 
    gregflag = FALSE;
  else
    gregflag = TRUE;
  jday = pd.mday;
  jmon = pd.mon;
  jyear = pd.year;
  jhour = pd.hour;
  jmin = pd.min;
  jsec = pd.sec;
  jut = jhour + jmin / 60.0 + jsec / 3600.0;
  tjd_ut = swe_julday(jyear,jmon,jday,jut,gregflag);
  swe_revjul(tjd_ut, gregflag, &jyear, &jmon, &jday, &jut);
  jut += 0.5 / 3600;
  jhour = (int) jut;
  jmin = (int) fmod(jut * 60, 60);
  jsec = (int) fmod(jut * 3600, 60);
  *bc = '\0';
  if (pd.year <= 0)
    sprintf(bc, "(%d B.C.)", 1 - jyear);
  if (jyear * 10000L + jmon * 100L + jday <= 15821004)
    jul = "jul.";
  else
    jul = "";
  sprintf(s, "%d.%d.%d %s %s    %#02d:%#02d:%#02d %s\n",
    jday, jmon, jyear, bc, jul,
    jhour, jmin, jsec, pd.etut);
  do_print(buf, s);
  jut = jhour + jmin / 60.0 + jsec / 3600.0;
  if (universal_time) {
    delt = swe_deltat(tjd_ut);
    sprintf(s, " delta t: %f sec", delt * 86400.0);
    do_print(buf, s);
    tjd_et = tjd_ut + delt;
  } else
    tjd_et = tjd_ut;
  sprintf(s, " jd (ET) = %f\n", tjd_et);
  do_print(buf, s);
  iflgret = swe_calc(tjd_et, SE_ECL_NUT, iflag, x, serr);
  eps_true = x[0];
  eps_mean = x[1];
  strcpy(s1, dms(eps_true, round_flag));
  strcpy(s2, dms(eps_mean, round_flag));
  sprintf(s, "\n%-15s %s%s%s    (true, mean)", "Ecl. obl.", s1, gap, s2);
  do_print(buf, s);
  nutl = x[2];
  nuto = x[3];
  strcpy(s1, dms(nutl, round_flag));
  strcpy(s2, dms(nuto, round_flag));
  sprintf(s, "\n%-15s %s%s%s    (dpsi, deps)", "Nutation", s1, gap, s2);
  do_print(buf, s);
  do_print(buf, "\n\n");
  do_print(buf, "               ecl. long.       ecl. lat.   ");
  do_print(buf, "    dist.          speed");
  if (calc_house_pos)
    do_print(buf, "          house");
  do_print(buf, "\n");
  if (iflag & SEFLG_TOPOCTR)
    swe_set_topo(lon, lat, pd.alt);
  sidt = swe_sidtime(tjd_ut) + lon / 15;
  if (sidt >= 24)
    sidt -= 24;
  if (sidt < 0)
    sidt += 24;
  armc = sidt * 15;
  /* additional asteroids */
  strcpy(splan, plsel);
  if (strcmp(plsel,PLSEL_P) == 0) {
    char *cpos[40];
    strcpy(sast, pd.sast);
    j = cut_str_any(sast, ",;. \t", cpos, 40);
    for (i = 0, nast = 0; i < j; i++) {
      if ((astno[nast] = atol(cpos[i])) > 0) {
	nast++;
	strcat(splan, "+");
      }
    }
  }
  for (psp = splan, iast = 0; *psp != '\0'; psp++) {
    if (*psp == '+') {
      ipl = SE_AST_OFFSET + (int) astno[iast];
	  iast++;
    } else
      ipl = letter_to_ipl(*psp);
    if (iflag & SEFLG_HELCTR) {
      if (ipl == SE_SUN
        || ipl == SE_MEAN_NODE || ipl == SE_TRUE_NODE
        || ipl == SE_MEAN_APOG || ipl == SE_OSCU_APOG)
      continue;
    } else if (iflag & SEFLG_BARYCTR) {
      if (ipl == SE_MEAN_NODE || ipl == SE_TRUE_NODE
        || ipl == SE_MEAN_APOG || ipl == SE_OSCU_APOG)
      continue;
    } else          /* geocentric */
      if (ipl == SE_EARTH)
        continue;
    /* ecliptic position */
    if (ipl == SE_FIXSTAR) {
      iflgret = swe_fixstar(star, tjd_et, iflag, x, serr);
      strcpy(se_pname, star);
    } else {
      iflgret = swe_calc(tjd_et, ipl, iflag, x, serr);
      swe_get_planet_name(ipl, se_pname);
	  if (ipl > SE_AST_OFFSET) {
   	    sprintf(s, "#%d", (int) astno[iast-1]);
		strcat(se_pname, "            ");
		strcpy(se_pname + 11 - strlen(s), s);
	  }
    }
    if (iflgret >= 0) {
      if (calc_house_pos) {
        hpos = swe_house_pos(armc, lat, eps_true, hsys, x, serr);
        if (hpos == 0)
          iflgret = ERR;
      }
    }
    if (iflgret < 0) {
      if (*serr != '\0' && strcmp(serr, serr_save) != 0) {
        strcpy (serr_save, serr);
        do_print(buf, "error: ");
        do_print(buf, serr);
        do_print(buf, "\n");
      }
    } else if (*serr != '\0' && *serr_warn == '\0')
      strcpy(serr_warn, serr);
    /* equator position */
    if (strpbrk(fmt, "aADdQ") != NULL) {
      iflag2 = iflag | SEFLG_EQUATORIAL;
      if (ipl == SE_FIXSTAR)
        iflgret = swe_fixstar(star, tjd_et, iflag2, xequ, serr);
      else
        iflgret = swe_calc(tjd_et, ipl, iflag2, xequ, serr);
    }
    /* ecliptic cartesian position */
    if (strpbrk(fmt, "XU") != NULL) {
      iflag2 = iflag | SEFLG_XYZ;
      if (ipl == SE_FIXSTAR)
        iflgret = swe_fixstar(star, tjd_et, iflag2, xcart, serr);
      else
        iflgret = swe_calc(tjd_et, ipl, iflag2, xcart, serr);
    }
    /* equator cartesian position */
    if (strpbrk(fmt, "xu") != NULL) {
      iflag2 = iflag | SEFLG_XYZ | SEFLG_EQUATORIAL;
      if (ipl == SE_FIXSTAR)
        iflgret = swe_fixstar(star, tjd_et, iflag2, xcartq, serr);
      else
        iflgret = swe_calc(tjd_et, ipl, iflag2, xcartq, serr);
    }
    spnam = se_pname;
    /*
     * The string fmt contains a sequence of format specifiers;
     * each character in fmt creates a column, the columns are
     * sparated by the gap string.
     */
    for (sp = fmt; *sp != '\0'; sp++) {
      if (sp != fmt) 
        do_print(buf, gap);
      switch(*sp) {
      case 'y':
          sprintf(s, "%d", jyear);
          do_print(buf, s);
          break;
      case 'Y':
          jut = 0;
          t2 = swe_julday(jyear,1,1,jut,gregflag);
          y_frac = (tjd_ut - t2) / 365.0;
          sprintf(s, "%.2lf", jyear + y_frac);
          do_print(buf, s);
          break;
      case 'p':
          if (diff_mode)
            sprintf(s, "%d-%d", ipl, ipldiff);
          else
            sprintf(s, "%d", ipl);
          do_print(buf, s);
          break;
      case 'P':
          if (diff_mode)
            sprintf(s, "%.3s-%.3s", spnam, spnam2);
          else
            sprintf(s, "%-11s", spnam);
          do_print(buf, s);
          break;
      case 'J':
      case 'j':
          sprintf(s, "%.2f", tjd_ut);
          do_print(buf, s);
          break;
      case 'T':
          sprintf(s, "%02d.%02d.%d", jday, jmon, jyear);
          do_print(buf, s);
          break;
      case 't':
          sprintf(s, "%02d%02d%02d", jyear % 100, jmon, jday);
          do_print(buf, s);
          break;
      case 'L':
          do_print(buf, dms(x[0], round_flag));
          break;
      case 'l':
          sprintf(s, "%# 11.7f", x[0]);
          do_print(buf, s);
          break;
      case 'Z':
          do_print(buf, dms(x[0], round_flag|BIT_ZODIAC));
          break;
      case 'S':
      case 's':
          if (*(sp+1) == 'S' || *(sp+1) == 's' || strpbrk(fmt, "XUxu") != NULL) {
            for (sp2 = fmt; *sp2 != '\0'; sp2++) {
              if (sp2 != fmt) 
                do_print(buf, gap);
              switch(*sp2) {
                case 'L':       /* speed! */
                case 'Z':       /* speed! */
                  do_print(buf, dms(x[3], round_flag));
                  break;
                case 'l':       /* speed! */
                  sprintf(s, "%11.7f", x[3]);
                  do_print(buf, s);
                  break;
                case 'B':       /* speed! */
                  do_print(buf, dms(x[4], round_flag));
                  break;
                case 'b':       /* speed! */
                  sprintf(s, "%11.7f", x[4]);
                  do_print(buf, s);
                  break;
                case 'A':       /* speed! */
                  do_print(buf, dms(xequ[3]/15, round_flag|SEFLG_EQUATORIAL));
                  break;
                case 'a':       /* speed! */
                  sprintf(s, "%11.7f", xequ[3]);
                  do_print(buf, s);
                  break;
                case 'D':       /* speed! */
                  do_print(buf, dms(xequ[4], round_flag));
                  break;
                case 'd':       /* speed! */
                  sprintf(s, "%11.7f", xequ[4]);
                  do_print(buf, s);
                  break;
                case 'R':       /* speed! */
                case 'r':       /* speed! */
                  sprintf(s, "%# 14.9f", x[5]);
                  do_print(buf, s);
                  break;
                case 'U':       /* speed! */
                case 'X':       /* speed! */
                  if (*sp =='U') 
                    ar = sqrt(square_sum(xcart));
                  else 
                    ar = 1;
                  sprintf(s, "%# 14.9f%s", xcart[3]/ar, gap);
                  do_print(buf, s);
                  sprintf(s, "%# 14.9f%s", xcart[4]/ar, gap);
                  do_print(buf, s);
                  sprintf(s, "%# 14.9f", xcart[5]/ar);
                  do_print(buf, s);
                  break;
                case 'u':       /* speed! */
                case 'x':       /* speed! */
                  if (*sp =='u') 
                    ar = sqrt(square_sum(xcartq));
                  else 
                    ar = 1;
                  sprintf(s, "%# 14.9f%s", xcartq[3]/ar, gap);
                  do_print(buf, s);
                  sprintf(s, "%# 14.9f%s", xcartq[4]/ar, gap);
                  do_print(buf, s);
                  sprintf(s, "%# 14.9f", xcartq[5]/ar);
                  do_print(buf, s);
                  break;
                default:
                  break;
              }
            }
            if (*(sp+1) == 'S' || *(sp+1) == 's')
              sp++;
          } else {
            do_print(buf, dms(x[3], round_flag));
          }
          break;
      case 'B':
          do_print(buf, dms(x[1], round_flag));
          break;
      case 'b':
          sprintf(s, "%# 11.7f", x[1]);
          do_print(buf, s);
          break;
      case 'A': /* rectascensio */
          do_print(buf, dms(xequ[0]/15, round_flag|SEFLG_EQUATORIAL));
          break;
      case 'a': /* rectascensio */
          sprintf(s, "%# 11.7f", xequ[0]);
          do_print(buf, s);
          break;
      case 'D': /* declination */
          do_print(buf, dms(xequ[1], round_flag));
          break;
      case 'd': /* declination */
          sprintf(s, "%# 11.7f", xequ[1]);
          do_print(buf, s);
          break;
      case 'R':
          sprintf(s, "%# 14.9f", x[2]);
          do_print(buf, s);
          break;
      case 'r':
          if ( ipl == SE_MOON ) { /* for moon print parallax */
            sinp = 8.794 / x[2];        /* in seconds of arc */
            ar = sinp * (1 + sinp * sinp * 3.917402e-12);
            /* the factor is 1 / (3600^2 * (180/pi)^2 * 6) */
            sprintf(s, "%# 13.5f\"", ar);       
          } else {
            sprintf(s, "%# 14.9f", x[2]);
          }
          do_print(buf, s);
          break;
      case 'U':
      case 'X':
          if (*sp =='U') 
            ar = sqrt(square_sum(xcart));
          else 
            ar = 1;
          sprintf(s, "%# 14.9f%s", xcart[0]/ar, gap);
          do_print(buf, s);
          sprintf(s, "%# 14.9f%s", xcart[1]/ar, gap);
          do_print(buf, s);
          sprintf(s, "%# 14.9f", xcart[2]/ar);
          do_print(buf, s);
          break;
      case 'u':
      case 'x':
          if (*sp =='u') 
            ar = sqrt(square_sum(xcartq));
          else 
            ar = 1;
          sprintf(s, "%# 14.9f%s", xcartq[0]/ar, gap);
          do_print(buf, s);
          sprintf(s, "%# 14.9f%s", xcartq[1]/ar, gap);
          do_print(buf, s);
          sprintf(s, "%# 14.9f", xcartq[2]/ar);
          do_print(buf, s);
          break;
      case 'Q':
          sprintf(s, "%-15s", spnam);
          do_print(buf, s);
          do_print(buf, dms(x[0], round_flag));
          do_print(buf, dms(x[1], round_flag));
          sprintf(s, "  %# 14.9f", x[2]);
          do_print(buf, s);
          do_print(buf, dms(x[3], round_flag));
          do_print(buf, dms(x[4], round_flag));
          sprintf(s, "  %# 14.9f\n", x[5]);
          do_print(buf, s);
          sprintf(s, "               %s", dms(xequ[0], round_flag));
          do_print(buf, s);
          do_print(buf, dms(xequ[1], round_flag));
          sprintf(s, "                %s", dms(xequ[3], round_flag));
          do_print(buf, s);
          do_print(buf, dms(xequ[4], round_flag));
          break;
      } /* switch */
    }   /* for sp */
    if (calc_house_pos) {
      sprintf(s, "  %# 6.4f", hpos);
          sprintf(s, "%# 9.4f", hpos);
      do_print(buf, s);
    }
    do_print(buf, "\n");
  }     /* for psp */
  if (*serr_warn != '\0') {
    do_print(buf, "\nwarning: ");
    do_print(buf, serr_warn);
    do_print(buf, "\n");
  }
  /* houses */
  sprintf(s, "\nHouse Cusps (%s)\n\n", pd.hsysname);
  do_print(buf, s);
  a = sidt + 0.5 / 3600;
  sprintf(s, "sid. time : %4d:%#02d:%#02d  ",
        (int) a, (int) fmod(a * 60, 60), (int) fmod(a * 3600, 60));
  do_print(buf, s);
  a = armc + 0.5 / 3600;
  sprintf(s, "armc      : %4d%c%#02d'%#02d\"\n",
        (int) armc, ODEGREE_CHAR, (int) fmod(armc * 60, 60),
        (int) fmod(a * 3600, 60));
  do_print(buf, s);
  sprintf(s, "geo. lat. : %4d%c%#02d'%#02d\" ",
        pd.lat_deg, *pd.lat_n_s, pd.lat_min, pd.lat_sec);
  do_print(buf, s);
  sprintf(s, "geo. long.: %4d%c%#02d'%#02d\"\n\n",
        pd.lon_deg, *pd.lon_e_w, pd.lon_min, pd.lon_sec);
  do_print(buf, s);
  swe_houses_ex(tjd_ut, iflag, lat, lon, hsys, cusp, ascmc);
  round_flag |= BIT_ROUND_SEC;
#if FALSE
  sprintf(s, "AC        : %s\n", dms(ascmc[0], round_flag));
  do_print(buf, s);
  sprintf(s, "MC        : %s\n", dms(ascmc[1], round_flag));
  do_print(buf, s);
  for (i = 1; i <= 12; i++) {
	sprintf(s, "house   %2d: %s\n", i, dms(cusp[i], round_flag));
    do_print(buf, s);
  }
  sprintf(s, "Vertex    : %s\n", dms(ascmc[3], round_flag));
  do_print(buf, s);
#else
  sprintf(s, "AC        : %s\n", dms(ascmc[0], round_flag|BIT_ZODIAC));
  do_print(buf, s);
  sprintf(s, "MC        : %s\n", dms(ascmc[1], round_flag|BIT_ZODIAC));
  do_print(buf, s);
  for (i = 1; i <= 12; i++) {
	sprintf(s, "house   %2d: %s\n", i, dms(cusp[i], round_flag|BIT_ZODIAC));
    do_print(buf, s);
  }
  sprintf(s, "Vertex    : %s\n", dms(ascmc[3], round_flag|BIT_ZODIAC));
  do_print(buf, s);
#endif  
  return 0;
}
コード例 #24
0
void SkyMap::keyPressEvent( QKeyEvent *e ) {
    KStars* kstars = KStars::Instance();
    QString s;
    bool arrowKeyPressed( false );
    bool shiftPressed( false );
    float step = 1.0;
    if ( e->modifiers() & Qt::ShiftModifier ) { step = 10.0; shiftPressed = true; }

    //If the DBus resume key is not empty, then DBus processing is
    //paused while we wait for a keypress
    if ( ! data->resumeKey.isEmpty() && QKeySequence(e->key()) == data->resumeKey ) {
        //The resumeKey was pressed.  Signal that it was pressed by
        //resetting it to empty; this will break the loop in
        //KStars::waitForKey()
        data->resumeKey = QKeySequence();
        return;
    }

    if(m_previewLegend) {
        slotCancelLegendPreviewMode();
    }

    switch ( e->key() ) {
    case Qt::Key_Left :
        if ( Options::useAltAz() ) {
            focus()->setAz( dms( focus()->az().Degrees() - step * MINZOOM/Options::zoomFactor() ).reduce() );
            focus()->HorizontalToEquatorial( data->lst(), data->geo()->lat() );
        } else {
            focus()->setRA( focus()->ra().Hours() + 0.05*step * MINZOOM/Options::zoomFactor() );
            focus()->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
        }

        arrowKeyPressed = true;
        slewing = true;
        break;

    case Qt::Key_Right :
        if ( Options::useAltAz() ) {
            focus()->setAz( dms( focus()->az().Degrees() + step * MINZOOM/Options::zoomFactor() ).reduce() );
            focus()->HorizontalToEquatorial( data->lst(), data->geo()->lat() );
        } else {
            focus()->setRA( focus()->ra().Hours() - 0.05*step * MINZOOM/Options::zoomFactor() );
            focus()->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
        }

        arrowKeyPressed = true;
        slewing = true;
        break;

    case Qt::Key_Up :
        if ( Options::useAltAz() ) {
            focus()->setAlt( focus()->alt().Degrees() + step * MINZOOM/Options::zoomFactor() );
            if ( focus()->alt().Degrees() > 90.0 ) focus()->setAlt( 90.0 );
            focus()->HorizontalToEquatorial( data->lst(), data->geo()->lat() );
        } else {
            focus()->setDec( focus()->dec().Degrees() + step * MINZOOM/Options::zoomFactor() );
            if (focus()->dec().Degrees() > 90.0) focus()->setDec( 90.0 );
            focus()->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
        }

        arrowKeyPressed = true;
        slewing = true;
        break;

    case Qt::Key_Down:
        if ( Options::useAltAz() ) {
            focus()->setAlt( focus()->alt().Degrees() - step * MINZOOM/Options::zoomFactor() );
            if ( focus()->alt().Degrees() < -90.0 ) focus()->setAlt( -90.0 );
            focus()->HorizontalToEquatorial(data->lst(), data->geo()->lat() );
        } else {
            focus()->setDec( focus()->dec().Degrees() - step * MINZOOM/Options::zoomFactor() );
            if (focus()->dec().Degrees() < -90.0) focus()->setDec( -90.0 );
            focus()->EquatorialToHorizontal( data->lst(), data->geo()->lat() );
        }

        arrowKeyPressed = true;
        slewing = true;
        break;

    case Qt::Key_Plus:   //Zoom in
    case Qt::Key_Equal:
        zoomInOrMagStep( e->modifiers() );
        break;

    case Qt::Key_Minus:  //Zoom out
    case Qt::Key_Underscore:
        zoomOutOrMagStep( e->modifiers() );
        break;

    case Qt::Key_0: //center on Sun
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::SUN ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_1: //center on Mercury
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::MERCURY ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_2: //center on Venus
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::VENUS ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_3: //center on Moon
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::MOON ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_4: //center on Mars
        setClickedObject( data->skyComposite()->planet( KSPlanetBase:: MARS) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_5: //center on Jupiter
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::JUPITER ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_6: //center on Saturn
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::SATURN ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_7: //center on Uranus
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::URANUS ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_8: //center on Neptune
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::NEPTUNE ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_9: //center on Pluto
        setClickedObject( data->skyComposite()->planet( KSPlanetBase::PLUTO ) );
        setClickedPoint( clickedObject() );
        slotCenter();
        break;

    case Qt::Key_BracketLeft:   // Begin measuring angular distance
        if( !rulerMode )
            slotBeginAngularDistance();
        break;
    case Qt::Key_Escape:        // Cancel angular distance measurement
        {
            if( rulerMode )
                slotCancelRulerMode();

            if( m_fovCaptureMode )
                slotFinishFovCaptureMode();
            break;
        }
 
    case Qt::Key_C: //Center clicked object
        if ( clickedObject() ) slotCenter();
        break;

    case Qt::Key_D: //Details window for Clicked/Centered object
    {
        SkyObject *orig = 0;
        if ( shiftPressed ) { 
            orig = clickedObject();
            setClickedObject( focusObject() );
        }

        if ( clickedObject() ) {
            slotDetail();
        }

        if ( orig ) {
            setClickedObject( orig );
        }
        break;
    }

    case Qt::Key_P: //Show Popup menu for Clicked/Centered object
        if ( shiftPressed ) {
            if ( focusObject() ) 
                focusObject()->showPopupMenu( pmenu, QCursor::pos() );
        } else {
            if ( clickedObject() )
                clickedObject()->showPopupMenu( pmenu, QCursor::pos() );
        }
        break;

    case Qt::Key_O: //Add object to Observing List
    {
        SkyObject *orig = 0;
        if ( shiftPressed ) {
            orig = clickedObject();
            setClickedObject( focusObject() );
        }

        if ( clickedObject() ) {
            kstars->observingList()->slotAddObject();
        }

        if ( orig ) {
            setClickedObject( orig );
        }
        break;
    }

    case Qt::Key_L: //Toggle User label on Clicked/Centered object
    {
        SkyObject *orig = 0;
        if ( shiftPressed ) {
            orig = clickedObject();
            setClickedObject( focusObject() );
        }

        if ( clickedObject() ) {
            if ( isObjectLabeled( clickedObject() ) )
                slotRemoveObjectLabel();
            else
                slotAddObjectLabel();
        }

        if ( orig ) {
            setClickedObject( orig );
        }
        break;
    }

    case Qt::Key_T: //Toggle planet trail on Clicked/Centered object (if solsys)
    {
        SkyObject *orig = 0;
        if ( shiftPressed ) {
            orig = clickedObject();
            setClickedObject( focusObject() );
        }

        KSPlanetBase* planet = dynamic_cast<KSPlanetBase*>( clickedObject() );
        if( planet ) {
            if( planet->hasTrail() )
                slotRemovePlanetTrail();
            else
                slotAddPlanetTrail();
        }

        if ( orig ) {
            setClickedObject( orig );
        }
        break;
    }

    case Qt::Key_R:
        {
            // Toggle relativistic corrections
            Options::setUseRelativistic( ! Options::useRelativistic() );
            kDebug() << "Relativistc corrections: " << Options::useRelativistic();
            forceUpdate();
            break;
        }

    case Qt::Key_A:
        Options::setUseAntialias( ! Options::useAntialias() );
        kDebug() << "Use Antialiasing: " << Options::useAntialias();
        forceUpdate();
        break;     

    case Qt::Key_K:
        {
            if(m_fovCaptureMode)
                slotCaptureFov();
            break;
        }

    case Qt::Key_PageUp:
        {
            KStars::Instance()->selectPreviousFov();
            break;
        }    

    case Qt::Key_PageDown:
        {
            KStars::Instance()->selectNextFov();
            break;
        }

    default:
        // We don't want to do anything in this case. Key is unknown
        return;
    }

    if ( arrowKeyPressed ) {
        stopTracking();
        setDestination( *focus() );
    }

    forceUpdate(); //need a total update, or slewing with the arrow keys doesn't work.
}
コード例 #25
0
bool KSComet::findGeocentricPosition( const KSNumbers *num, const KSPlanetBase *Earth ) {
	double v(0.0), r(0.0);

	//Precess the longitude of the Ascending Node to the desired epoch:
	dms n = dms( double(N.Degrees() - 3.82394E-5 * ( num->julianDay() - J2000 )) ).reduce();

	if ( e > 0.98 ) {
		//Use near-parabolic approximation
		double k = 0.01720209895; //Gauss gravitational constant
		double a = 0.75 * ( num->julianDay() - JDp ) * k * sqrt( (1+e)/(q*q*q) );
		double b = sqrt( 1.0 + a*a );
		double W = pow((b+a),1.0/3.0) - pow((b-a),1.0/3.0);
		double c = 1.0 + 1.0/(W*W);
		double f = (1.0-e)/(1.0+e);
		double g = f/(c*c);

		double a1 = (2.0/3.0) + (2.0*W*W/5.0);
		double a2 = (7.0/5.0) + (33.0*W*W/35.0) + (37.0*W*W*W*W/175.0);
		double a3 = W*W*( (432.0/175.0) + (956.0*W*W/1125.0) + (84.0*W*W*W*W/1575.0) );
		double w = W*(1.0 + g*c*( a1 + a2*g + a3*g*g ));

		v = 2.0*atan(w) / dms::DegToRad;
		r = q*( 1.0 + w*w )/( 1.0 + w*w*f );
	} else {
		//Use normal ellipse method
		//Determine Mean anomaly for desired date:
		dms m = dms( double(360.0*( num->julianDay() - JDp )/P) ).reduce();
		double sinm, cosm;
		m.SinCos( sinm, cosm );

		//compute eccentric anomaly:
		double E = m.Degrees() + e*180.0/dms::PI * sinm * ( 1.0 + e*cosm );

		if ( e > 0.05 ) { //need more accurate approximation, iterate...
			double E0;
			int iter(0);
			do {
				E0 = E;
				iter++;
				E = E0 - ( E0 - e*180.0/dms::PI *sin( E0*dms::DegToRad ) - m.Degrees() )/(1 - e*cos( E0*dms::DegToRad ) );
			} while ( fabs( E - E0 ) > 0.001 && iter < 1000 );
		}

		double sinE, cosE;
		dms E1( E );
		E1.SinCos( sinE, cosE );

		double xv = a * ( cosE - e );
		double yv = a * sqrt( 1.0 - e*e ) * sinE;

		//v is the true anomaly; r is the distance from the Sun

		v = atan( yv/xv ) / dms::DegToRad;
		//resolve atan ambiguity
		if ( xv < 0.0 ) v += 180.0;

		r = sqrt( xv*xv + yv*yv );
	}

	//vw is the sum of the true anomaly and the argument of perihelion
	dms vw( v + w.Degrees() );
	double sinN, cosN, sinvw, cosvw, sini, cosi;

	n.SinCos( sinN, cosN );
	vw.SinCos( sinvw, cosvw );
	i.SinCos( sini, cosi );

	//xh, yh, zh are the heliocentric cartesian coords with the ecliptic plane congruent with zh=0.
	double xh = r * ( cosN * cosvw - sinN * sinvw * cosi );
	double yh = r * ( sinN * cosvw + cosN * sinvw * cosi );
	double zh = r * ( sinvw * sini );

	//xe, ye, ze are the Earth's heliocentric cartesian coords
	double cosBe, sinBe, cosLe, sinLe;
	Earth->ecLong()->SinCos( sinLe, cosLe );
	Earth->ecLat()->SinCos( sinBe, cosBe );

	double xe = Earth->rsun() * cosBe * cosLe;
	double ye = Earth->rsun() * cosBe * sinLe;
	double ze = Earth->rsun() * sinBe;

	//convert to geocentric ecliptic coordinates by subtracting Earth's coords:
	xh -= xe;
	yh -= ye;
	zh -= ze;

	//Finally, the spherical ecliptic coordinates:
	double ELongRad = atan( yh/xh );
	//resolve atan ambiguity
	if ( xh < 0.0 ) ELongRad += dms::PI;

	double rr = sqrt( xh*xh + yh*yh );
	double ELatRad = atan( zh/rr );  //(rr can't possibly be negative, so no atan ambiguity)

	ep.longitude.setRadians( ELongRad );
	ep.latitude.setRadians( ELatRad );
	setRsun( r );
	setRearth( Earth );
	
	EclipticToEquatorial( num->obliquity() );
	nutate( num );
	aberrate( num );

	return true;
}
コード例 #26
0
/*
 *@short Initialize the asteroids list.
 *Reads in the asteroids data from the asteroids.dat file.
 *
 * The data file is a CSV file with the following columns :
 * @li 1 full name [string]
 * @li 2 Modified Julian Day of orbital elements [int]
 * @li 3 perihelion distance in AU [double]
 * @li 4 semi-major axis
 * @li 5 eccentricity of orbit [double]
 * @li 6 inclination angle of orbit in degrees [double]
 * @li 7 argument of perihelion in degrees [double]
 * @li 8 longitude of the ascending node in degrees [double]
 * @li 9 mean anomaly
 * @li 10 time of perihelion passage (YYYYMMDD.DDD) [double]
 * @li 11 orbit solution ID [string]
 * @li 12 absolute magnitude [float]
 * @li 13 slope parameter [float]
 * @li 14 Near-Earth Object (NEO) flag [bool]
 * @li 15 comet total magnitude parameter [float] (we should remove this column)
 * @li 16 comet nuclear magnitude parameter [float] (we should remove this column)
 * @li 17 object diameter (from equivalent sphere) [float]
 * @li 18 object bi/tri-axial ellipsoid dimensions [string]
 * @li 19 geometric albedo [float]
 * @li 20 rotation period [float]
 * @li 21 orbital period [float]
 * @li 22 earth minimum orbit intersection distance [double]
 * @li 23 orbit classification [string]
 */
void AsteroidsComponent::loadData() {
    QString line, name, full_name, orbit_id, orbit_class, dimensions;
    QStringList fields;
    int mJD;
    double q, a, e, dble_i, dble_w, dble_N, dble_M, H, G, earth_moid;
    long double JD;
    float diameter, albedo, rot_period, period;
    bool ok, neo;

    emitProgressText( i18n("Loading asteroids") );

    // Clear lists
    m_ObjectList.clear();
    objectNames( SkyObject::ASTEROID ).clear();

    QList< QPair<QString, KSParser::DataTypes> > sequence;
    sequence.append(qMakePair(QString("full name"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("epoch_mjd"), KSParser::D_INT));
    sequence.append(qMakePair(QString("q"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("a"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("e"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("i"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("w"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("om"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("ma"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("tp_calc"), KSParser::D_SKIP));
    sequence.append(qMakePair(QString("orbit_id"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("H"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("G"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("neo"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("tp_calc"), KSParser::D_SKIP));
    sequence.append(qMakePair(QString("M2"), KSParser::D_SKIP));
    sequence.append(qMakePair(QString("diameter"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("extent"), KSParser::D_QSTRING));
    sequence.append(qMakePair(QString("albedo"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("rot_period"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("per_y"), KSParser::D_FLOAT));
    sequence.append(qMakePair(QString("moid"), KSParser::D_DOUBLE));
    sequence.append(qMakePair(QString("class"), KSParser::D_QSTRING));

    QString file_name = KStandardDirs::locate( "appdata",
                                               QString("asteroids.dat") );
    KSParser asteroid_parser(file_name, '#', sequence);

    QHash<QString, QVariant> row_content;
    while (asteroid_parser.HasNextRow()){
        row_content = asteroid_parser.ReadNextRow();
        full_name = row_content["full name"].toString();
        full_name = full_name.trimmed();
        int catN  = full_name.section(" ", 0, 0).toInt();
        name = full_name.section(" ", 1, -1);
        mJD  = row_content["epoch_mjd"].toInt();
        q    = row_content["q"].toDouble();
        a    = row_content["a"].toDouble();
        e    = row_content["e"].toDouble();
        dble_i = row_content["i"].toDouble();
        dble_w = row_content["w"].toDouble();
        dble_N = row_content["om"].toDouble();
        dble_M = row_content["ma"].toDouble();
        orbit_id = row_content["orbit_id"].toString();
        H   = row_content["H"].toDouble();
        G   = row_content["G"].toDouble();
        neo = row_content["neo"].toString() == "Y";
        diameter = row_content["diameter"].toFloat();
        dimensions = row_content["extent"].toString();
        albedo  = row_content["albedo"].toFloat();
        rot_period = row_content["rot_period"].toFloat();
        period  = row_content["per_y"].toFloat();
        earth_moid  = row_content["moid"].toDouble();
        orbit_class = row_content["class"].toString();

        JD = static_cast<double>(mJD) + 2400000.5;

        KSAsteroid *new_asteroid = new KSAsteroid( catN, name, QString(), JD,
                                          a, e,
                                          dms(dble_i), dms(dble_w),
                                          dms(dble_N), dms(dble_M),
                                          H, G );
        new_asteroid->setPerihelion(q);
        new_asteroid->setOrbitID(orbit_id);
        new_asteroid->setNEO(neo);
        new_asteroid->setDiameter(diameter);
        new_asteroid->setDimensions(dimensions);
        new_asteroid->setAlbedo(albedo);
        new_asteroid->setRotationPeriod(rot_period);
        new_asteroid->setPeriod(period);
        new_asteroid->setEarthMOID(earth_moid);
        new_asteroid->setOrbitClass(orbit_class);
        new_asteroid->setAngularSize(0.005);
        m_ObjectList.append(new_asteroid);

        // Add name to the list of object names
        objectNames(SkyObject::ASTEROID).append(name);
    }
}