Example #1
0
void
MapWindow::DrawOffTrackIndicator(Canvas &canvas)
{
  if (task == NULL || !task->Valid() || task->getActiveIndex() <= 0)
    return;

  if (fabs(Basic().TrackBearing-Calculated().WaypointBearing)<10) {
    // insignificant error
    return;
  }
  if (Calculated().Circling || task->TaskIsTemporary() ||
      SettingsMap().TargetPan) {
    // don't display in various modes
    return;
  }

  double distance_max = min(Calculated().WaypointDistance,
			    GetScreenDistanceMeters()*0.7);
  if (distance_max < 5000.0) {
    // too short to bother
    return;
  }

  GEOPOINT start = Basic().Location;
  GEOPOINT target = task->getTargetLocation();

  canvas.select(TitleWindowFont);
  canvas.set_text_color(Color(0x0, 0x0, 0x0));

  GEOPOINT dloc;
  int ilast = 0;
  for (double d=0.25; d<=1.0; d+= 0.25) {
    FindLatitudeLongitude(start,
			  Basic().TrackBearing,
			  distance_max*d,
			  &dloc);

    double distance0 = Distance(start, dloc);
    double distance1 = Distance(dloc, target);
    double distance = (distance0+distance1)/Calculated().WaypointDistance;
    int idist = iround((distance-1.0)*100);

    if ((idist != ilast) && (idist>0) && (idist<1000)) {

      TCHAR Buffer[5];
      _stprintf(Buffer, TEXT("%d"), idist);
      POINT sc;
      RECT brect;
      LonLat2Screen(dloc, sc);
      SIZE tsize = canvas.text_size(Buffer);

      brect.left = sc.x-4;
      brect.right = brect.left+tsize.cx+4;
      brect.top = sc.y-4;
      brect.bottom = brect.top+tsize.cy+4;

      if (label_block.check(brect)) {
        canvas.text(sc.x - tsize.cx / 2, sc.y - tsize.cy / 2, Buffer);
	ilast = idist;
      }
    }
  }
}
static void SetValues(void) {
  int atype = 0;
  AIRSPACE_ALT* top = NULL;
  AIRSPACE_ALT* base = NULL;
  TCHAR *name = 0;
  WndProperty* wp;
  TCHAR buffer[80];
  TCHAR buffer2[80];
  bool inside = false;
  double range = 0.0;
  double bearing;

  if (index_area >=0) {
    atype = AirspaceArea[index_area].Type;
    top = &AirspaceArea[index_area].Top;
    base = &AirspaceArea[index_area].Base;
    name = AirspaceArea[index_area].Name;
    inside = InsideAirspaceArea(GPS_INFO.Longitude, GPS_INFO.Latitude, 
				index_area);
    range = 
      RangeAirspaceArea(GPS_INFO.Longitude, GPS_INFO.Latitude, 
			index_area, &bearing);
  }
  if (index_circle >=0) {
    atype = AirspaceCircle[index_circle].Type;
    top = &AirspaceCircle[index_circle].Top;
    base = &AirspaceCircle[index_circle].Base;
    name = AirspaceCircle[index_circle].Name;
    inside = InsideAirspaceCircle(GPS_INFO.Longitude, GPS_INFO.Latitude, 
				  index_circle);
    range = 
      RangeAirspaceCircle(GPS_INFO.Longitude, GPS_INFO.Latitude, 
			  index_circle);

    DistanceBearing(GPS_INFO.Latitude,
		    GPS_INFO.Longitude,
		    AirspaceCircle[index_circle].Latitude, 
		    AirspaceCircle[index_circle].Longitude,
		    NULL, &bearing);
    if (inside) {
      bearing = AngleLimit360(bearing+180);
    }
  }

  if (range<0) {
    range = -range;
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpName"));
  if (wp) {
    wp->SetText(name);
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpType"));
  if (wp) {
    switch (atype) {
    case RESTRICT:
	// LKTOKEN  _@M565_ = "Restricted" 
      wp->SetText(gettext(TEXT("_@M565_"))); break;
    case PROHIBITED:
	// LKTOKEN  _@M537_ = "Prohibited" 
      wp->SetText(gettext(TEXT("_@M537_"))); break;
    case DANGER:
	// LKTOKEN  _@M213_ = "Danger Area" 
      wp->SetText(gettext(TEXT("_@M213_"))); break;
    case CLASSA:
      wp->SetText(TEXT("Class A")); break;
    case CLASSB:
      wp->SetText(TEXT("Class B")); break;
    case CLASSC:
      wp->SetText(TEXT("Class C")); break;
    case CLASSD:
      wp->SetText(TEXT("Class D")); break;
    case CLASSE:
      wp->SetText(TEXT("Class E")); break;
    case CLASSF:
      wp->SetText(TEXT("Class F")); break;
    case CLASSG:
      wp->SetText(TEXT("Class G")); break;
    case NOGLIDER:
	// LKTOKEN  _@M464_ = "No Glider" 
      wp->SetText(gettext(TEXT("_@M464_"))); break;
    case CTR:
      wp->SetText(TEXT("CTR")); break;
    case WAVE:
	// LKTOKEN  _@M794_ = "Wave" 
      wp->SetText(gettext(TEXT("_@M794_"))); break;
    default:
	// LKTOKEN  _@M765_ = "Unknown" 
      wp->SetText(gettext(TEXT("_@M765_")));
    }
    wp->RefreshDisplay();
  }
  
  wp = (WndProperty*)wf->FindByName(TEXT("prpTop"));
  if (wp) {
    switch (top->Base){
    case abUndef:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("%.0f[m] %.0f[ft] [?]"), 
		  (top->Altitude), 
		  (top->Altitude*TOFEET));
      } else {
	_stprintf(buffer, TEXT("%.0f ft [?]"), 
		  (top->Altitude*TOFEET));
      }
      break;
    case abMSL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("%.0f[m] %.0f[ft] MSL"), 
		  top->Altitude, top->Altitude*TOFEET);
      } else {
	_stprintf(buffer, TEXT("%.0f ft MSL"), 
		  top->Altitude*TOFEET);
      }
      break;
    case abAGL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("%.0f[m] %.0f[ft] AGL"), 
		  top->AGL, top->AGL*TOFEET);
      } else {
	_stprintf(buffer, TEXT("%.0f ft AGL"), 
		  top->AGL*TOFEET);
      }
      break;
    case abFL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("FL%.0f (%.0f[m] %.0f[ft])"), 
		  top->FL, FLAltRounded(top->Altitude), 
		  FLAltRounded(top->Altitude*TOFEET));
      } else {
	_stprintf(buffer, TEXT("FL%.0f (%.0f ft)"), 
		  top->FL, FLAltRounded(top->Altitude*TOFEET));
      }
      break;
    }
    wp->SetText(buffer);
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpBase"));
  if (wp) {
    switch (base->Base){
    case abUndef:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("%.0f[m] %.0f[ft] [?]"), 
		  base->Altitude, base->Altitude*TOFEET);
      } else {
	_stprintf(buffer, TEXT("%.0f ft [?]"), 
		  base->Altitude*TOFEET);
      }
      break;
    case abMSL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("%.0f[m] %.0f[ft] MSL"), 
		  base->Altitude, base->Altitude*TOFEET);
      } else {
	_stprintf(buffer, TEXT("%.0f ft MSL"), 
		  base->Altitude*TOFEET);
      }
      break;
    case abAGL:
      if (base->Altitude == 0) {
        _stprintf(buffer, TEXT("SFC"));
      } else {
	if (Units::GetUserAltitudeUnit() == unMeter) {
	  _stprintf(buffer, TEXT("%.0f[m] %.0f[ft] AGL"), 
		    base->AGL, base->AGL*TOFEET);
	} else {
	  _stprintf(buffer, TEXT("%.0f ft AGL"), 
		    base->AGL*TOFEET);
	}
      }
      break;
    case abFL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, TEXT("FL %.0f (%.0f[m] %.0f[ft])"), 
		  base->FL, FLAltRounded(base->Altitude), 
		  FLAltRounded(base->Altitude*TOFEET));
      } else {
	_stprintf(buffer, TEXT("FL%.0f (%.0f ft)"), 
		  base->FL, FLAltRounded(base->Altitude*TOFEET));
      }
      break;
    }
    wp->SetText(buffer);
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpRange"));
  if (wp) {
    if (inside) {
	// LKTOKEN  _@M359_ = "Inside" 
      wp->SetCaption(gettext(TEXT("_@M359_")));
    }
    Units::FormatUserDistance(range, buffer, 20);
    _stprintf(buffer2, TEXT(" %d")TEXT(DEG), iround(bearing));
    _tcscat(buffer, buffer2);
    wp->SetText(buffer);
    wp->RefreshDisplay();
  }
}
Example #3
0
/**
 * Feet to Pixel converters: convert y coordinate to pixels
 */
inline int ycon(double y)
{
  return maxy - iround(y / SCALE);
}
Example #4
0
static void OnTaskPaintListItem(WindowControl * Sender, LKSurface& Surface){

  int n = UpLimit - LowLimit;
  TCHAR sTmp[120];
  TCHAR wpName[120];
  TCHAR landableStr[5] = TEXT(" [X]");
  // LKTOKEN _@M1238_ "L"
  landableStr[2] = MsgToken(1238)[0];
  LockTaskData();

  const PixelRect rcClient(Sender->GetClientRect());
  
  const int w0 = rcClient.GetSize().cx - DLGSCALE(1);
  const int w1 = Surface.GetTextWidth(TEXT(" 000km"));
  _stprintf(sTmp, _T("  000%s"), MsgToken(2179));
  const int w2 = Surface.GetTextWidth(sTmp);

  const int TextMargin = (rcClient.GetSize().cy - Surface.GetTextHeight(TEXT("A"))) / 2;

  const int p1 = w0-w1-w2- rcClient.GetSize().cy - DLGSCALE(2);
  const int p2 = w0-w2- rcClient.GetSize().cy - DLGSCALE(2);
  
  const PixelRect rc = {
      0, 
      0,
      rcClient.GetSize().cy, 
      rcClient.GetSize().cy
  };
  
  if (DrawListIndex < n){
    int i = LowLimit + DrawListIndex;
//    if ((WayPointList[Task[i].Index].Flags & LANDPOINT) >0)
//      MapWindow::DrawRunway(hDC,  &WayPointList[Task[i].Index],  rc, 3000,true);
    MapWindow::DrawTaskPicto(Surface, DrawListIndex,  rc, 2500);
    if (Task[i].Index>=0) {
      _stprintf(wpName, TEXT("%s%s"),
                WayPointList[Task[i].Index].Name,
                (WayPointList[Task[i].Index].Flags & LANDPOINT) ? landableStr : TEXT(""));

      if (AATEnabled && ValidTaskPoint(i+1) && (i>0)) {
        if (Task[i].AATType==0 || Task[i].AATType==3) {
          _stprintf(sTmp, TEXT("%s %.1f"),
                    wpName, Task[i].AATCircleRadius*DISTANCEMODIFY);
        } else {
          if(Task[i].AATType==2 && DoOptimizeRoute()) {
             _stprintf(sTmp, TEXT("%s %.1f/1"),
                    wpName, Task[i].PGConeSlope);
          } else {
             _stprintf(sTmp, TEXT("%s %.1f"),
                    wpName, Task[i].AATSectorRadius*DISTANCEMODIFY);
          }
        }
      } else {
        _stprintf(sTmp, TEXT("%s"), wpName);
      }

      Surface.SetBackgroundTransparent();
      Surface.SetTextColor(RGB_BLACK);
      Surface.DrawTextClip(rc.right + DLGSCALE(2), TextMargin, sTmp, p1-DLGSCALE(4));

      _stprintf(sTmp, TEXT("%.0f %s"),Task[i].Leg*DISTANCEMODIFY,Units::GetDistanceName());
      Surface.DrawText(rc.right+p1+w1-Surface.GetTextWidth(sTmp), TextMargin, sTmp);

      _stprintf(sTmp, TEXT("%d%s"),  iround(Task[i].InBound),MsgToken(2179));
      Surface.DrawText(rc.right +p2+w2-Surface.GetTextWidth(sTmp), TextMargin, sTmp);

    }

  } else {

    Surface.SetTextColor(RGB_BLACK);

     // if (DrawListIndex==n) { // patchout 091126
     if (DrawListIndex==n && UpLimit < MAXTASKPOINTS) { // patch 091126

	// LKTOKEN  _@M832_ = "add waypoint"
      _stprintf(sTmp, TEXT("  (%s)"), MsgToken(832));
      Surface.DrawText(rc.right +DLGSCALE(2), TextMargin, sTmp);
    } else if ((DrawListIndex==n+1) && ValidTaskPoint(0)) {

      if (!AATEnabled || ISPARAGLIDER) {
        // LKTOKEN  _@M735_ = "Total:"
        Surface.DrawText(rc.right +DLGSCALE(2), TextMargin, MsgToken(735));
	   _stprintf(sTmp, TEXT("%.0f %s%s"), lengthtotal*DISTANCEMODIFY, Units::GetDistanceName(), fai_ok?_T(" FAI"):_T(""));
	
       Surface.DrawText(rc.right +p1+w1-Surface.GetTextWidth(sTmp), TextMargin, sTmp);

      } else {

      double d1 = CALCULATED_INFO.TaskDistanceToGo;
      if ((CALCULATED_INFO.TaskStartTime>0.0) && (CALCULATED_INFO.Flying) && (ActiveTaskPoint>0)) {
                   d1 += CALCULATED_INFO.TaskDistanceCovered;
      }

	if (d1==0.0) {
	  d1 = CALCULATED_INFO.AATTargetDistance;
	}

	_stprintf(sTmp, TEXT("%s %.0f min %.0f (%.0f) %s"),
	// LKTOKEN  _@M735_ = "Total:"
                  MsgToken(735),
                  AATTaskLength*1.0,
		  DISTANCEMODIFY*lengthtotal,
		  DISTANCEMODIFY*d1,
		  Units::GetDistanceName());
	Surface.DrawText(rc.right +DLGSCALE(2), TextMargin, sTmp);
      }
    }
  }
  UnlockTaskData();

}
Example #5
0
static void ReadValues(void) {
  WndProperty* wp;
  bool changed = false;

  LockTaskData();
  wp = (WndProperty*)wf->FindByName(TEXT("prpEnableMultipleStartPoints"));
  if (wp) {
    CHECK_CHANGED(EnableMultipleStartPoints,
                  wp->GetDataField()->GetAsBoolean());
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpAATEnabled"));
  if (wp) {
    CHECK_CHANGED(AATEnabled,
                  wp->GetDataField()->GetAsInteger());
	if (DoOptimizeRoute()) AATEnabled=true; // force it on
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpTaskFinishLine"));
  if (wp) {
    CHECK_CHANGED(FinishLine,
                  wp->GetDataField()->GetAsInteger());
  }
  
  wp = (WndProperty*)wf->FindByName(TEXT("prpTaskFinishRadius"));
  if (wp) {
    CHECK_CHANGED(FinishRadius,
                  (DWORD)iround(wp->GetDataField()->GetAsFloat()
				/DISTANCEMODIFY));
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpTaskStartLine"));
  if (wp) {
    CHECK_CHANGED(StartLine, 
                  wp->GetDataField()->GetAsInteger());
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpTaskStartRadius"));
  if (wp) {
    CHECK_CHANGED(StartRadius,
                  (DWORD)iround(wp->GetDataField()->GetAsFloat()
				/DISTANCEMODIFY));
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpTaskFAISector"));
  if (wp) {
    CHECK_CHANGED(SectorType,
                  wp->GetDataField()->GetAsInteger());
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpTaskSectorRadius"));
  if (wp) {
    CHECK_CHANGED(SectorRadius,
                  (DWORD)iround(wp->GetDataField()->GetAsFloat()
				/DISTANCEMODIFY));
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpAutoAdvance"));
  if (wp) {
    CHECK_CHANGED(AutoAdvance, 
                  wp->GetDataField()->GetAsInteger());
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpMinTime"));
  if (wp) {
    CHECK_CHANGED(AATTaskLength, 
                  wp->GetDataField()->GetAsInteger());
	if (changed) CALCULATED_INFO.AATTimeToGo=AATTaskLength*60; 
  }
  if (changed) {
    TaskModified = true;
  }

  UnlockTaskData();

}
Example #6
0
void
GaugeVario::RenderBallast(Canvas &canvas)
{
  static int last_ballast = -1;
  static PixelRect label_rect = {-1,-1,-1,-1};
  static PixelRect value_rect = {-1,-1,-1,-1};
  static RasterPoint label_pos = {-1,-1};
  static RasterPoint value_pos = {-1,-1};

  if (!ballast_initialised) { // ontime init, origin and background rect
    const PixelRect rc = GetClientRect();

    PixelSize tSize;

    // position of ballast label
    label_pos.x = 1;
    label_pos.y = rc.top + 2
      + look.text_font->GetCapitalHeight() * 2
      - look.text_font->GetAscentHeight();

    // position of ballast value
    value_pos.x = 1;
    value_pos.y = rc.top + 1
      + look.text_font->GetCapitalHeight()
      - look.text_font->GetAscentHeight();

    // set upper left corner
    label_rect.left = label_pos.x;
    label_rect.top = label_pos.y
      + look.text_font->GetAscentHeight()
      - look.text_font->GetCapitalHeight();

    // set upper left corner
    value_rect.left = value_pos.x;
    value_rect.top = value_pos.y
      + look.text_font->GetAscentHeight()
      - look.text_font->GetCapitalHeight();

    // get max label size
    canvas.Select(*look.text_font);
    tSize = canvas.CalcTextSize(TEXT_BALLAST);

    // update back rect with max label size
    label_rect.right = label_rect.left + tSize.cx;
    label_rect.bottom = label_rect.top +
      look.text_font->GetCapitalHeight();

    // get max value size
    tSize = canvas.CalcTextSize(_T("100%"));

    value_rect.right = value_rect.left + tSize.cx;
    // update back rect with max label size
    value_rect.bottom = value_rect.top +
      look.text_font->GetCapitalHeight();

    ballast_initialised = true;
  }

  int ballast = iround(GetGlidePolar().GetBallast() * 100);

  if (!IsPersistent() || ballast != last_ballast) {
    // ballast hase been changed

    canvas.Select(*look.text_font);

    if (IsPersistent())
      canvas.SetBackgroundColor(look.background_color);
    else
      canvas.SetBackgroundTransparent();

    if (IsPersistent() || last_ballast < 1 || ballast < 1) {
      // new ballast is 0, hide label
      if (ballast > 0) {
        canvas.SetTextColor(look.dimmed_text_color);
        // ols ballast was 0, show label
        if (IsPersistent())
          canvas.DrawOpaqueText(label_pos.x, label_pos.y, label_rect, TEXT_BALLAST);
        else
          canvas.DrawText(label_pos.x, label_pos.y, TEXT_BALLAST);
      } else if (IsPersistent())
        canvas.DrawFilledRectangle(label_rect, look.background_color);
    }

    // new ballast 0, hide value
    if (ballast > 0) {
      TCHAR buffer[18];
      _stprintf(buffer, _T("%u%%"), ballast);
      canvas.SetTextColor(look.text_color);

      if (IsPersistent())
        canvas.DrawOpaqueText(value_pos.x, value_pos.y, value_rect, buffer);
      else
        canvas.DrawText(value_pos.x, value_pos.y, buffer);
    } else if (IsPersistent())
      canvas.DrawFilledRectangle(value_rect, look.background_color);

    if (IsPersistent())
      last_ballast = ballast;
  }
}
void TwoFrameModel::Read(FILE *f)
{
    fscanf(f, "%d\n", &m_num_points);

    fscanf(f, "%lf\n", &m_angle);
    fscanf(f, "%lf\n", &m_error);

    v3_t *points_tmp = new v3_t[m_num_points];
    double *tracks_tmp = new double[m_num_points];
    int *k1_tmp = new int[m_num_points];
    int *k2_tmp = new int[m_num_points];

    m_points = new v3_t[m_num_points];
    m_tracks = new int[m_num_points];

    for (int i = 0; i < m_num_points; i++) {
        int tr, k1, k2;
        fscanf(f, "%d %d %d %lf %lf %lf\n", &tr, &k1, &k2,
               &(Vx(points_tmp[i])), 
               &(Vy(points_tmp[i])), 
               &(Vz(points_tmp[i])));

        tracks_tmp[i] = (double) tr;
        k1_tmp[i] = k1;
        k2_tmp[i] = k2;
    }

    bool use_tracks = true;
    if (tracks_tmp[0] < 0)
        use_tracks = false;

    if (use_tracks) {
        int *perm = new int[m_num_points];
    
        qsort_ascending();
        qsort_perm(m_num_points, tracks_tmp, perm);

        for (int i = 0; i < m_num_points; i++) {
            m_tracks[i] = iround(tracks_tmp[i]);
            m_points[i] = points_tmp[perm[i]];
        }

        m_keys1 = m_keys2 = NULL;

        delete [] perm;
    } else {
        m_keys1 = new int[m_num_points];
        m_keys2 = new int[m_num_points];

        for (int i = 0; i < m_num_points; i++) {
            m_keys1[i] = k1_tmp[i];
            m_keys2[i] = k2_tmp[i];
            m_points[i] = points_tmp[i];
        }
     
        m_tracks = NULL;
    }

    delete [] points_tmp;
    delete [] tracks_tmp;
    delete [] k1_tmp;
    delete [] k2_tmp;

    ReadCamera(f, m_camera0);
    ReadCamera(f, m_camera1);
    
    ReadVector(f, 9, m_C0);
    ReadVector(f, 9, m_C1);
}
Example #8
0
void CanberraCnfDataSet::load_data(std::istream &f)
{
    string file_string;
    file_string.reserve(128*1024);
    file_string.assign((istreambuf_iterator<char>(f)),
                       istreambuf_iterator<char>());
    const char* beg = file_string.c_str();
    const char* end = beg + file_string.size();

    int acq_offset = 0, sam_offset = 0, eff_offset = 0, enc_offset = 0,
        chan_offset = 0;

    // we have here 48-byte blocks with meta data
    for (const char* ptr = beg+112; ptr+48 < end; ptr += 48) {
        // MW - should records 0 in ptr[1] or ptr[2] be really accepted?
        if ((ptr[1] != 0x20 || ptr[2] != 0x01) && ptr[1] != 0 && ptr[2] != 0)
            break;
        uint32_t offset = from_le<uint32_t>(ptr+10);
#if 0
        printf("%6ld: hex %02x %02x %02x %02x  -> %6u",
               ptr-beg, ptr[0], ptr[1], ptr[2], ptr[3], offset);
        if (offset > 0 && beg+offset+1 < end)
            printf(" -> hex %02x %02x", beg[offset], beg[offset+1]);
        printf("\n");
#endif
        switch (ptr[0]) {
            case 0:
                if (acq_offset == 0)
                    acq_offset = offset;
                else
                    enc_offset = offset;
                break;
            case 1:
                if (sam_offset == 0)
                    sam_offset = offset;
                break;
            case 2:
                if (eff_offset == 0)
                    eff_offset = offset;
                break;
            case 5:
                // We don't have specs, so it's all based on guessing.
                // At least for me. Checking a few CNF files I've got,
                // normally we are here when the record starts with 0x052001,
                // but the condition above (which I copied like everything
                // else from JF) is also passing when it starts with, say,
                // 0x054000 (Miha Cernetic sent us such a file).
                // No idea if the condition above can be safely changed.
                // Here is a workaround from JF - checking the value at the
                // offset.
                if (chan_offset == 0 &&
                           offset+1 < file_string.size() &&
                           file_string[offset] == '\x05' &&
                           file_string[offset+1] == '\x20')
                       chan_offset = offset;
                break;
            default:
                break;
        }
        if (acq_offset != 0 && sam_offset != 0 &&
                    eff_offset != 0 && chan_offset != 0)
            break;
    }
    if (enc_offset == 0)
        enc_offset = acq_offset;

    auto_ptr<Block> blk(new Block);

    // sample data - split name into name and description
    // (this was not in code from JF, it's my guess - MW)
    const char* sam_ptr = beg + sam_offset;
    if (sam_ptr+0x30+80 >= end || sam_ptr[0] != 1 || sam_ptr[1] != 0x20)
        fprintf(stderr, "Warning. Sample data not found.\n");
    else {
        string name = str_trim(string(sam_ptr+0x30, 32));
        if (!name.empty() && is_printable(name))
            blk->set_name(name);
        string desc = str_trim(string(sam_ptr+0x30+32, 48));
        if (!desc.empty() && is_printable(desc))
            blk->meta["description"] = desc;
    }

    // go to acquisition data
    const char* acq_ptr = beg + acq_offset;
    if (acq_ptr+48+128+10+4 >= end || acq_ptr[0] != 0 || acq_ptr[1] != 0x20)
        throw FormatError("Acquisition data not found.");
    uint16_t offset1 = from_le<uint16_t>(acq_ptr+34);
    uint16_t offset2 = from_le<uint16_t>(acq_ptr+36);

    const char* pha_ptr = acq_ptr + 48 + 128;
    if (pha_ptr[0] != 'P' || pha_ptr[1] != 'H' || pha_ptr[2] != 'A')
        fprintf(stderr, "Warning. PHA keyword not found.\n");

    int n_channels = from_le<uint16_t>(pha_ptr+10) * 256;
    if (n_channels < 256 || n_channels > 16384)
        throw FormatError("Unexpected number of channels" + S(n_channels));

    // dates and times
    const char* date_ptr = acq_ptr+48+offset2+1;
    format_assert(this, date_ptr + 3*8 < end);
    blk->meta["date and time"] = convert_date(date_ptr); // when taken
    float real_time = convert_time(date_ptr + 8);
    blk->meta["real time (s)"] = format1<float, 16>("%.2f", real_time);
    float live_time = convert_time(date_ptr + 16);
    blk->meta["live time (s)"] = format1<float, 16>("%.2f", live_time);

    format_assert(this, beg + enc_offset+48+32 + offset1 < end);
    Column *xcol = read_energy_callibration(beg + enc_offset+48+32 + offset1,
                                            blk.get(), n_channels);
    if (xcol == NULL)
        xcol = read_energy_callibration(beg + enc_offset+48+32,
                                        blk.get(), n_channels);
    if (xcol == NULL) {
        fprintf(stderr, "Warning. Energy Calibration not found.\n");
        xcol = new StepColumn(1, 1);
    }

    // code from JF is also reading detector name, but it's not needed here
    // detector name was 232 bytes after energy calibration

    // channel data
    const char* chan_ptr = beg + chan_offset;
    if (chan_ptr+512+4*n_channels > end || chan_ptr[0] != 5 ||
                                           chan_ptr[1] != 0x20) {
        delete xcol;
        throw FormatError("Channel data not found.");
    }
    VecColumn *ycol = new VecColumn;
    // the two first channels sometimes contain live and real time
    for (int i = 0; i < 2; ++i) {
        uint32_t y = from_le<uint32_t>(chan_ptr+512+4*i);
        if ((int) y == iround(real_time) || (int) y == iround(live_time))
            y = 0;
        ycol->add_val(y);
    }
    for (int i = 2; i < n_channels; ++i) {
        uint32_t y = from_le<uint32_t>(chan_ptr+512+4*i);
        ycol->add_val(y);
    }

    blk->add_column(xcol);
    blk->add_column(ycol);
    add_block(blk.release());
}
void WriteBundleFile(const char *bundle_file, 
                     const std::vector<camera_params_t> &cameras,
                     const std::vector<point_t> &points)
{
    FILE *f = fopen(bundle_file, "w");
    if (f == NULL) {
	printf("Error opening file %s for reading\n", bundle_file);
	return;
    }

    int num_images = cameras.size();
    int num_points = points.size();

    /* Count the number of good images */
    int num_good_images = 0;
    int *map = new int[num_images];
    for (int i = 0; i < num_images; i++) {
        if (cameras[i].f == 0) {
            map[i] = -1;                
            continue;
        }

        map[i] = num_good_images;
        num_good_images++;
    }

    printf("[WriteBundleFile] Writing %d images and %d points...\n",
	   num_good_images, num_points);

    fprintf(f, "# Bundle file v0.3\n");
    fprintf(f, "%d %d\n", num_good_images, num_points);    

    /* Write cameras */
    for (int i = 0; i < num_images; i++) {
        if (cameras[i].f == 0)
            continue;

        /* Focal length */
        fprintf(f, "%lf 0.0 0.0\n", cameras[i].f);

	/* Rotation */
        const double *R = cameras[i].R;
	fprintf(f, "%lf %lf %lf\n%lf %lf %lf\n%lf %lf %lf\n", 
                R[0], R[1], R[2], R[3], R[4], R[5], R[6], R[7], R[8]);

	/* Translation */
        const double *t = cameras[i].t;
	fprintf(f, "%lf %lf %lf\n", t[0], t[1], t[2]);
    }
    
    /* Write points */
    for (int i = 0; i < num_points; i++) {
	/* Position */
        const double *pos = points[i].pos;
	fprintf(f, "%lf %lf %lf\n", pos[0], pos[1], pos[2]);

	/* Color */
        const double *color = points[i].color;
	fprintf(f, "%d %d %d\n", 
                iround(color[0]), iround(color[1]), iround(color[2]));

	int num_visible;
        num_visible = points[i].views.size();
	fprintf(f, "%d", num_visible);

	for (int j = 0; j < num_visible; j++) {
	    int view = map[points[i].views[j].image];
            assert(view >= 0 && view < num_good_images);
            int key = points[i].views[j].key;
            double x = points[i].views[j].x;
            double y = points[i].views[j].y;

	    fprintf(f, " %d %d %0.2f %0.2f", view, key, x, y);
	}

        fprintf(f, "\n");
    }

    fclose(f);
}
            //
            // Initialize the variables we'll be using:
            //
            T lambda = theta / 2;
            T del = f / 2;
            T y = x / 2;
            boost::uintmax_t max_iter = policies::get_max_series_iterations<Policy>();
            T errtol = boost::math::policies::get_epsilon<T, Policy>();
            T sum = init_sum;
            //
            // k is the starting location for iteration, we'll
            // move both forwards and backwards from this point.
            // k is chosen as the peek of the Poisson weights, which
            // will occur *before* the largest term.
            //
            int k = iround(lambda, pol);
            // Forwards and backwards Poisson weights:
            T poisf = boost::math::gamma_p_derivative(1 + k, lambda, pol);
            T poisb = poisf * k / lambda;
            // Initial forwards central chi squared term:
            T gamf = boost::math::gamma_q(del + k, y, pol);
            // Forwards and backwards recursion terms on the central chi squared:
            T xtermf = boost::math::gamma_p_derivative(del + 1 + k, y, pol);
            T xtermb = xtermf * (del + k) / y;
            // Initial backwards central chi squared term:
            T gamb = gamf - xtermb;

            //
            // Forwards iteration first, this is the
            // stable direction for the gamma function
            // recurrences:
Example #11
0
int
DataFieldFloat::GetAsInteger() const
{
  return iround(mValue);
}
Example #12
0
static void SetValues(void) {
  int atype = 0;
  AIRSPACE_ALT* top = NULL;
  AIRSPACE_ALT* base = NULL;
  TCHAR *name = 0;
  WndProperty* wp;
  TCHAR buffer[80];
  TCHAR buffer2[80];
  bool inside = false;
  double range = 0.0;
  double bearing;

  if (index_area >=0) {
    AIRSPACE_AREA &area = airspace_database.AirspaceArea[index_area];
    MapWindow &map_window = XCSoarInterface::main_window.map;

    atype = area.Type;
    top = &area.Top;
    base = &area.Base;
    name = area.Name;
    inside = airspace_database.InsideArea(XCSoarInterface::Basic().Location,
                                          index_area);
    range = airspace_database.RangeArea(XCSoarInterface::Basic().Location,
                                        index_area, &bearing,
                                        map_window);
  }

  if (index_circle >=0) {
    AIRSPACE_CIRCLE &circle = airspace_database.AirspaceCircle[index_circle];

    atype = circle.Type;
    top = &circle.Top;
    base = &circle.Base;
    name = circle.Name;
    inside = airspace_database.InsideCircle(XCSoarInterface::Basic().Location,
                                            index_circle);
    range = airspace_database.CircleDistance(XCSoarInterface::Basic().Location,
                                             index_circle);

    DistanceBearing(XCSoarInterface::Basic().Location, circle.Location,
		    NULL, &bearing);
    if (inside) {
      bearing = AngleLimit360(bearing+180);
    }
  }

  if (range<0) {
    range = -range;
  }

  wp = (WndProperty*)wf->FindByName(_T("prpName"));
  if (wp) {
    wp->SetText(name);
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(_T("prpType"));
  if (wp) {
    switch (atype) {
    case RESTRICT:
      wp->SetText(gettext(_T("Restricted"))); break;
    case PROHIBITED:
      wp->SetText(gettext(_T("Prohibited"))); break;
    case DANGER:
      wp->SetText(gettext(_T("Danger Area"))); break;
    case CLASSA:
      wp->SetText(gettext(_T("Class A"))); break;
    case CLASSB:
      wp->SetText(gettext(_T("Class B"))); break;
    case CLASSC:
      wp->SetText(gettext(_T("Class C"))); break;
    case CLASSD:
      wp->SetText(gettext(_T("Class D"))); break;
    case CLASSE:
      wp->SetText(gettext(_T("Class E"))); break;
    case CLASSF:
      wp->SetText(gettext(_T("Class F"))); break;
    case NOGLIDER:
      wp->SetText(gettext(_T("No Glider"))); break;
    case CTR:
      wp->SetText(gettext(_T("CTR"))); break;
    case WAVE:
      wp->SetText(gettext(_T("Wave"))); break;
    default:
      wp->SetText(gettext(_T("Unknown")));
    }
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(_T("prpTop"));
  if (wp) {
    switch (top->Base){
    case abUndef:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("%.0f[m] %.0f[ft] [?]"),
		  (top->Altitude),
		  (top->Altitude*TOFEET));
      } else {
	_stprintf(buffer, _T("%.0f ft [?]"),
		  (top->Altitude*TOFEET));
      }
      break;
    case abMSL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("%.0f[m] %.0f[ft] MSL"),
		  top->Altitude, top->Altitude*TOFEET);
      } else {
	_stprintf(buffer, _T("%.0f ft MSL"),
		  top->Altitude*TOFEET);
      }
      break;
    case abAGL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("%.0f[m] %.0f[ft] AGL"),
		  top->AGL, top->AGL*TOFEET);
      } else {
	_stprintf(buffer, _T("%.0f ft AGL"),
		  top->AGL*TOFEET);
      }
      break;
    case abFL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("FL%.0f (%.0f[m] %.0f[ft])"),
		  top->FL, FLAltRounded(top->Altitude),
		  FLAltRounded(top->Altitude*TOFEET));
      } else {
	_stprintf(buffer, _T("FL%.0f (%.0f ft)"),
		  top->FL, FLAltRounded(top->Altitude*TOFEET));
      }
      break;
    }
    wp->SetText(buffer);
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(_T("prpBase"));
  if (wp) {
    switch (base->Base){
    case abUndef:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("%.0f[m] %.0f[ft] [?]"),
		  base->Altitude, base->Altitude*TOFEET);
      } else {
	_stprintf(buffer, _T("%.0f ft [?]"),
		  base->Altitude*TOFEET);
      }
      break;
    case abMSL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("%.0f[m] %.0f[ft] MSL"),
		  base->Altitude, base->Altitude*TOFEET);
      } else {
	_stprintf(buffer, _T("%.0f ft MSL"),
		  base->Altitude*TOFEET);
      }
      break;
    case abAGL:
      if (base->Altitude == 0) {
        _stprintf(buffer, _T("SFC"));
      } else {
	if (Units::GetUserAltitudeUnit() == unMeter) {
	  _stprintf(buffer, _T("%.0f[m] %.0f[ft] AGL"),
		    base->AGL, base->AGL*TOFEET);
	} else {
	  _stprintf(buffer, _T("%.0f ft AGL"),
		    base->AGL*TOFEET);
	}
      }
      break;
    case abFL:
      if (Units::GetUserAltitudeUnit() == unMeter) {
	_stprintf(buffer, _T("FL %.0f (%.0f[m] %.0f[ft])"),
		  base->FL, FLAltRounded(base->Altitude),
		  FLAltRounded(base->Altitude*TOFEET));
      } else {
	_stprintf(buffer, _T("FL%.0f (%.0f ft)"),
		  base->FL, FLAltRounded(base->Altitude*TOFEET));
      }
      break;
    }
    wp->SetText(buffer);
    wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(_T("prpRange"));
  if (wp) {
    if (inside) {
      wp->SetCaption(gettext(_T("Inside")));
    }
    Units::FormatUserDistance(range, buffer, 20);
    _stprintf(buffer2, _T(" %d")_T(DEG), iround(bearing));
    _tcscat(buffer, buffer2);
    wp->SetText(buffer);
    wp->RefreshDisplay();
  }
}
// interp4_table0_complex_per_adj()
void interp4_table0_complex_per_adj(
double *r_ck,		/* [K1,K2,K3,K4] out */
double *i_ck,
const int K1,
const int K2,
const int K3,
const int K4,
const double *r_h1,	/* [J1*L1+1,1] in */
const double *i_h1,
const double *r_h2,	/* [J2*L2+1,1] in */
const double *i_h2,
const double *r_h3,	/* [J3*L3+1,1] in */
const double *i_h3,
const double *r_h4,	/* [J4*L4+1,1] in */
const double *i_h4,
const int J1,
const int J2,
const int J3,
const int J4,
const int L1,
const int L2,
const int L3,
const int L4,
const double *p_tm,	/* [M,4] in */
const int M,
const double *r_fm,	/* [M,1] in */
const double *i_fm)
{
	int mm;

	/* trick: shift table pointer to center */
	{
	const int ncenter1 = floor(J1 * L1/2.);
	r_h1 += ncenter1;
	i_h1 += ncenter1;
	}
	{
	const int ncenter2 = floor(J2 * L2/2.);
	r_h2 += ncenter2;
	i_h2 += ncenter2;
	}
	{
	const int ncenter3 = floor(J3 * L3/2.);
	r_h3 += ncenter3;
	i_h3 += ncenter3;
	}
	{
	const int ncenter4 = floor(J4 * L4/2.);
	r_h4 += ncenter4;
	i_h4 += ncenter4;
	}

	/* initialize output to zero */
	(void) memset((void *) r_ck, 0, K1*K2*K3*K4*sizeof(*r_ck));
	(void) memset((void *) i_ck, 0, K1*K2*K3*K4*sizeof(*i_ck));

	/* interp */
    for (mm=0; mm < M; mm++) {
	int jj1, jj2, jj3, jj4;
	const double t4 = p_tm[3*M];
	const double t3 = p_tm[2*M];
	const double t2 = p_tm[M];
	const double t1 = *p_tm++;
	const double fmr = *r_fm++;
	const double fmi = *i_fm++;
	const int koff1 = 1 + floor(t1 - J1 / 2.);
	const int koff2 = 1 + floor(t2 - J2 / 2.);
	const int koff3 = 1 + floor(t3 - J3 / 2.);
	int k4 = 1 + floor(t4 - J4 / 2.);

	for (jj4=0; jj4 < J4; jj4++, k4++) {
		const double p4 = (t4 - k4) * L4;
		const int n4 = /* ncenter4 + */ iround(p4);
		const double coef4r = r_h4[n4];
		const double coef4i = i_h4[n4];
		const int k4mod = mymod(k4, K4);
		const mwIndex k4Idx = k4mod*K3*K2*K1;

		const double v4r = coef4r * fmr + coef4i * fmi;
		const double v4i = coef4r * fmi - coef4i * fmr;
		int k3 = koff3;

	for (jj3=0; jj3 < J3; jj3++, k3++) {
		const double p3 = (t3 - k3) * L3;
		const int n3 = /* ncenter3 + */ iround(p3);
		const double coef3r = r_h3[n3];
		const double coef3i = i_h3[n3];
		const int k3mod = mymod(k3, K3);
		const mwIndex k3Idx = k3mod*K2*K1;

		const double v3r = coef3r * v4r + coef3i * v4i;
		const double v3i = coef3r * v4i - coef3i * v4r;
		int k2 = koff2;

	for (jj2=0; jj2 < J2; jj2++, k2++) {
		const double p2 = (t2 - k2) * L2;
		const int n2 = /* ncenter2 + */ iround(p2);
		const double coef2r = r_h2[n2];
		const double coef2i = i_h2[n2];
		const int k2mod = mymod(k2, K2);
		const mwIndex k2Idx = k2mod*K1;

		const double v2r = coef2r * v3r + coef2i * v3i;
		const double v2i = coef2r * v3i - coef2i * v3r;
		int k1 = koff1;

	for (jj1=0; jj1 < J1; jj1++, k1++) {
		const double p1 = (t1 - k1) * L1;
		const int n1 = /* ncenter1 + */ iround(p1);
		register const double coef1r = r_h1[n1];
		register const double coef1i = i_h1[n1];
		const int k1mod = mymod(k1, K1);
		const mwIndex kk = k4Idx + k3Idx + k2Idx + k1mod; /* 4D array index */

		r_ck[kk] += coef1r * v2r + coef1i * v2i;
		i_ck[kk] += coef1r * v2i - coef1i * v2r;

	} /* j1 */
	} /* j2 */
	} /* j3 */
	} /* j4 */
    }
}
/*
* interp4_table0_real_per_adj()
* 4D, 0th-order, real, periodic
*/
void interp4_table0_real_per_adj(
double *r_ck,		/* [K1,K2,K3,K4] out */
double *i_ck,
const int K1,
const int K2,
const int K3,
const int K4,
const double *r_h1,	/* [J1*L1+1,1] in */
const double *r_h2,	/* [J2*L2+1,1] in */
const double *r_h3,	/* [J3*L3+1,1] in */
const double *r_h4,	/* [J4*L4+1,1] in */
#ifdef Provide_flip
const int flip1,	/* sign flips every K? */
const int flip2,
const int flip3,
const int flip4,
#endif
const int J1,
const int J2,
const int J3,
const int J4,
const int L1,
const int L2,
const int L3,
const int L4,
const double *p_tm,	/* [M,4] in */
const int M,
const double *r_fm,	/* [M,1] in */
const double *i_fm)
{
	int mm;

	/* trick: shift table pointer to center */
	{
	const int ncenter1 = floor(J1 * L1/2.);
	r_h1 += ncenter1;
	}
	{
	const int ncenter2 = floor(J2 * L2/2.);
	r_h2 += ncenter2;
	}
	{
	const int ncenter3 = floor(J3 * L3/2.);
	r_h3 += ncenter3;
	}
	{
	const int ncenter4 = floor(J4 * L4/2.);
	r_h4 += ncenter4;
	}

	/* initialize output to zero */
	(void) memset((void *) r_ck, 0, K1*K2*K3*K4*sizeof(*r_ck));
	(void) memset((void *) i_ck, 0, K1*K2*K3*K4*sizeof(*i_ck));

	/* interp */
    for (mm=0; mm < M; mm++) {
	int jj1, jj2, jj3, jj4;
	const double t4 = p_tm[3*M];
	const double t3 = p_tm[2*M];
	const double t2 = p_tm[M];
	const double t1 = *p_tm++;
	const double fmr = *r_fm++;
	const double fmi = *i_fm++;
	const int koff1 = 1 + floor(t1 - J1 / 2.);
	const int koff2 = 1 + floor(t2 - J2 / 2.);
	const int koff3 = 1 + floor(t3 - J3 / 2.);
	int k4 = 1 + floor(t4 - J4 / 2.);

	for (jj4=0; jj4 < J4; jj4++, k4++) {
		const double p4 = (t4 - k4) * L4;
		const int n4 = /* ncenter4 + */ iround(p4);
		double coef4r = r_h4[n4];
		const int wrap4 = floor(k4 / (double) K4);
		const int k4mod = k4 - K4 * wrap4;
		const mwIndex k4Idx = k4mod*K3*K2*K1;

#ifdef Provide_flip
		if (flip4 && (wrap4 % 2))
			coef4r = -coef4r; /* trick: sign flip */
#endif

		const double v4r = coef4r * fmr;
		const double v4i = coef4r * fmi;
		int k3 = koff3;

	for (jj3=0; jj3 < J3; jj3++, k3++) {
		const double p3 = (t3 - k3) * L3;
		const int n3 = /* ncenter3 + */ iround(p3);
		double coef3r = r_h3[n3];
		const int wrap3 = floor(k3 / (double) K3);
		const int k3mod = k3 - K3 * wrap3;
		const mwIndex k3Idx = k3mod*K2*K1;

#ifdef Provide_flip
		if (flip3 && (wrap3 % 2))
			coef3r = -coef3r; /* trick: sign flip */
#endif

		const double v3r = coef3r * v4r;
		const double v3i = coef3r * v4i;
		int k2 = koff2;

	for (jj2=0; jj2 < J2; jj2++, k2++) {
		const double p2 = (t2 - k2) * L2;
		const int n2 = /* ncenter2 + */ iround(p2);
		double coef2r = r_h2[n2];
		const int wrap2 = floor(k2 / (double) K2);
		const int k2mod = k2 - K2 * wrap2;
		const mwIndex k2Idx = k2mod*K1;

#ifdef Provide_flip
		if (flip2 && (wrap2 % 2))
			coef2r = -coef2r; /* trick: sign flip */
#endif

		const double v2r = coef2r * v3r;
		const double v2i = coef2r * v3i;
		int k1 = koff1;

	for (jj1=0; jj1 < J1; jj1++, k1++) {
		const double p1 = (t1 - k1) * L1;
		const int n1 = /* ncenter1 + */ iround(p1);
		register double coef1r = r_h1[n1];
		const int wrap1 = floor(k1 / (double) K1);
		const int k1mod = k1 - K1 * wrap1;
		const mwIndex kk = k4Idx + k3Idx + k2Idx + k1mod; /* 4D array index */

#ifdef Provide_flip
		if (flip1 && (wrap1 % 2))
			coef1r = -coef1r; /* trick: sign flip */
#endif

		r_ck[kk] += coef1r * v2r;
		i_ck[kk] += coef1r * v2i;
	} /* j1 */
	} /* j2 */
	} /* j3 */
	} /* j4 */
    }
}
Example #15
0
// TODO code: Optimise vario rendering, this is slow
void
GaugeVario::RenderValue(Canvas &canvas, int x, int y,
                        DrawInfo *value_info, DrawInfo *label_info,
                        fixed value, const TCHAR *label)
{
  PixelSize tsize;

#ifndef FIXED_MATH
  value = (double)iround(value * 10) / 10; // prevent the -0.0 case
#endif

  if (!value_info->initialised) {

    value_info->rc.right = x - Layout::Scale(5);
    value_info->rc.top = y + Layout::Scale(3)
      + look.text_font->GetCapitalHeight();

    value_info->rc.left = value_info->rc.right;
    // update back rect with max label size
    value_info->rc.bottom = value_info->rc.top + look.value_font->GetCapitalHeight();

    value_info->text_position.x = value_info->rc.left;
    value_info->text_position.y = value_info->rc.top
                         + look.value_font->GetCapitalHeight()
                         - look.value_font->GetAscentHeight();

    value_info->last_value = fixed(-9999);
    value_info->last_text[0] = '\0';
    value_info->last_unit = Unit::UNDEFINED;
    value_info->initialised = true;
  }

  if (!label_info->initialised) {

    label_info->rc.right = x;
    label_info->rc.top = y + Layout::Scale(1);

    label_info->rc.left = label_info->rc.right;
    // update back rect with max label size
    label_info->rc.bottom = label_info->rc.top
      + look.text_font->GetCapitalHeight();

    label_info->text_position.x = label_info->rc.left;
    label_info->text_position.y = label_info->rc.top
      + look.text_font->GetCapitalHeight()
      - look.text_font->GetAscentHeight();

    label_info->last_value = fixed(-9999);
    label_info->last_text[0] = '\0';
    label_info->initialised = true;
  }

  canvas.SetBackgroundTransparent();

  if (!IsPersistent() || (dirty && !StringIsEqual(label_info->last_text, label))) {
    canvas.SetTextColor(look.dimmed_text_color);
    canvas.Select(*look.text_font);
    tsize = canvas.CalcTextSize(label);
    label_info->text_position.x = label_info->rc.right - tsize.cx;

    if (IsPersistent()) {
      canvas.SetBackgroundColor(look.background_color);
      canvas.DrawOpaqueText(label_info->text_position.x, label_info->text_position.y,
                            label_info->rc, label);
      label_info->rc.left = label_info->text_position.x;
      _tcscpy(label_info->last_text, label);
    } else {
      canvas.DrawText(label_info->text_position.x, label_info->text_position.y,
                      label);
    }
  }

  if (!IsPersistent() || (dirty && value_info->last_value != value)) {
    TCHAR buffer[18];
    canvas.SetBackgroundColor(look.background_color);
    canvas.SetTextColor(look.text_color);
    _stprintf(buffer, _T("%.1f"), (double)value);
    canvas.Select(*look.value_font);
    tsize = canvas.CalcTextSize(buffer);
    value_info->text_position.x = value_info->rc.right - tsize.cx;

    if (IsPersistent()) {
      canvas.DrawOpaqueText(value_info->text_position.x,
                            value_info->text_position.y,
                            value_info->rc, buffer);

      value_info->rc.left = value_info->text_position.x;
      value_info->last_value = value;
    } else {
      canvas.DrawText(value_info->text_position.x, value_info->text_position.y,
                      buffer);
    }
  }

  if (!IsPersistent() ||
      value_info->last_unit != Units::current.vertical_speed_unit) {
    value_info->last_unit = Units::current.vertical_speed_unit;
    const UnitSymbol *unit_symbol = units_look.GetSymbol(value_info->last_unit);
    unit_symbol->Draw(canvas, x - Layout::Scale(5), value_info->rc.top,
                      look.background_color, COLOR_GRAY);
  }
}
Example #16
0
Stack* Stack_Blend_Label_Field(const Stack *stack, const Stack *label, 
    double alpha, const uint8_t *color_map, int color_number, Stack *out)
{
  TZ_ASSERT(stack->kind == GREY, "Unsupported kind");
  TZ_ASSERT(label->kind == GREY || label->kind == GREY16, "Unsupported kind");
  TZ_ASSERT(Stack_Same_Size(stack, label), "Unmatched size");

  if (alpha < 0.0) {
    TZ_WARN(ERROR_DATA_VALUE);
    alpha = 0.0;
  }
  if (alpha > 1.0) {
    TZ_WARN(ERROR_DATA_VALUE);
    alpha = 1.0;
  }

  if (out == NULL) {
    out = Make_Stack(COLOR, stack->width, stack->height, stack->depth);
  }

  TZ_ASSERT(out->kind == COLOR, "Unsupported kind");

  color_t *out_array = (color_t*) out->array;

  if (color_map == NULL) {
    color_map = Jet_Colormap;
    color_number = Jet_Color_Number;
  }

  size_t voxel_number = Stack_Voxel_Number(stack);
  size_t offset;
  Image_Array ima;
  ima.array = label->array;
  for (offset = 0; offset < voxel_number; ++offset) {
    int label_value;
    if (label->kind == GREY) {
      label_value = ima.array8[offset];
    } else {
      label_value = ima.array16[offset];
    }
    
    int gray_value = stack->array[offset];
    if (label_value > 0) {
      label_value = (label_value - 1) % color_number;
      int k;
      for (k = 0; k < 3; ++k) {
        int value = iround((1.0 - alpha) * gray_value +
            alpha * color_map[label_value * 3 + k]);
        if (value < 0) {
          value = 0;
        } else if (value > 255) {
          value = 255;
        }
        out_array[offset][k] = value;
      }
    } else {
      int k;
      for (k = 0; k < 3; ++k) {
        out_array[offset][k] = gray_value;
      }
    }
#ifdef _DEBUG_2
      if (out_array[offset][0] == 0 && out_array[offset][1] == 0 &&
          out_array[offset][2] == 0) {
        printf("debug here\n");
      }
#endif
  }

  return out;
}
Example #17
0
void
GaugeVario::RenderSpeedToFly(Canvas &canvas, int x, int y)
{
  if (!Basic().airspeed_available ||
      !Basic().total_energy_vario_available)
    return;

  static fixed last_v_diff;
  fixed v_diff;

  const unsigned arrow_y_size = Layout::Scale(3);
  const unsigned arrow_x_size = Layout::Scale(7);

  const PixelRect rc = GetClientRect();

  int nary = NARROWS * arrow_y_size;
  int ytop = rc.top + YOFFSET + nary; // JMW
  int ybottom = rc.bottom - YOFFSET - nary - Layout::FastScale(1);

  ytop += Layout::Scale(14);
  ybottom -= Layout::Scale(14);

  x = rc.right - 2 * arrow_x_size;

  // only draw speed command if flying and vario is not circling
  if ((Calculated().flight.flying)
      && (!Basic().gps.simulator || !Calculated().circling)) {
    v_diff = Calculated().V_stf - Basic().indicated_airspeed;
    v_diff = Clamp(v_diff, -DELTA_V_LIMIT, DELTA_V_LIMIT); // limit it
    v_diff = iround(v_diff/DELTA_V_STEP) * DELTA_V_STEP;
  } else
    v_diff = fixed(0);

  if (!IsPersistent() || last_v_diff != v_diff || dirty) {
    last_v_diff = v_diff;

    if (IsPersistent()) {
      // bottom (too slow)
      canvas.DrawFilledRectangle(x, ybottom + YOFFSET,
                                 x + arrow_x_size * 2 + 1,
                                 ybottom + YOFFSET + nary + arrow_y_size +
                                 Layout::FastScale(2),
                                 look.background_color);

      // top (too fast)
      canvas.DrawFilledRectangle(x, ytop - YOFFSET + 1,
                                 x + arrow_x_size * 2  +1,
                                 ytop - YOFFSET - nary + 1 - arrow_y_size -
                                 Layout::FastScale(2),
                                 look.background_color);
    }

    RenderClimb(canvas);

    canvas.SelectNullPen();

    if (look.colors) {
      if (positive(v_diff)) {
        // too slow
        canvas.Select(look.sink_brush);
      } else {
        canvas.Select(look.lift_brush);
      }
    } else {
      if (look.inverse)
        canvas.SelectWhiteBrush();
      else
        canvas.SelectBlackBrush();
    }

    if (positive(v_diff)) {
      // too slow
      y = ybottom;
      y += YOFFSET;

      while (positive(v_diff)) {
        if (v_diff > DELTA_V_STEP) {
          canvas.Rectangle(x, y,
                           x + arrow_x_size * 2 + 1, y + arrow_y_size - 1);
        } else {
          RasterPoint arrow[3];
          arrow[0].x = x;
          arrow[0].y = y;
          arrow[1].x = x + arrow_x_size;
          arrow[1].y = y + arrow_y_size - 1;
          arrow[2].x = x + 2 * arrow_x_size;
          arrow[2].y = y;
          canvas.DrawTriangleFan(arrow, 3);
        }
        v_diff -= DELTA_V_STEP;
        y += arrow_y_size;
      }
    } else if (negative(v_diff)) {
      // too fast
      y = ytop;
      y -= YOFFSET;

      while (negative(v_diff)) {
        if (v_diff < -DELTA_V_STEP) {
          canvas.Rectangle(x, y + 1,
                           x + arrow_x_size * 2 + 1, y - arrow_y_size + 2);
        } else {
          RasterPoint arrow[3];
          arrow[0].x = x;
          arrow[0].y = y;
          arrow[1].x = x + arrow_x_size;
          arrow[1].y = y - arrow_y_size + 1;
          arrow[2].x = x + 2 * arrow_x_size;
          arrow[2].y = y;
          canvas.DrawTriangleFan(arrow, 3);
        }
        v_diff += DELTA_V_STEP;
        y -= arrow_y_size;
      }
    }
  }
}
Example #18
0
void MapWindow::DrawWindAtAircraft2(Canvas &canvas, const POINT Orig, const RECT rc) {
  int i;
  POINT Start;
  TCHAR sTmp[12];
  static SIZE tsize = {0,0};

  if (Calculated().WindSpeed<1) {
    return; // JMW don't bother drawing it if not significant
  }

  if (tsize.cx == 0){
    canvas.select(MapWindowBoldFont);
    tsize = canvas.text_size(TEXT("99"));
    tsize.cx = tsize.cx/2;
  }

  canvas.select(MapGfx.hpWind);
  canvas.select(MapGfx.hbWind);

  int wmag = iround(4.0*Calculated().WindSpeed);

  Start.y = Orig.y;
  Start.x = Orig.x;

  int kx = tsize.cx/InfoBoxLayout::scale/2;

  POINT Arrow[7] = { {0,-20}, {-6,-26}, {0,-20},
                     {6,-26}, {0,-20},
                     {8+kx, -24},
                     {-8-kx, -24}};

  for (i=1;i<4;i++)
    Arrow[i].y -= wmag;

  PolygonRotateShift(Arrow, 7, Start.x, Start.y,
		     Calculated().WindBearing-DisplayAngle);
  canvas.polygon(Arrow, 5);

  if (SettingsMap().WindArrowStyle==1) {
    POINT Tail[2] = {{0,-20}, {0,-26-min(20,wmag)*3}};
    double angle = AngleLimit360(Calculated().WindBearing-DisplayAngle);
    for(i=0; i<2; i++) {
      if (InfoBoxLayout::scale>1) {
        Tail[i].x *= InfoBoxLayout::scale;
        Tail[i].y *= InfoBoxLayout::scale;
      }
      protateshift(Tail[i], angle, Start.x, Start.y);
    }

    // optionally draw dashed line
    Pen dash_pen(Pen::DASH, 1, Color(0, 0, 0));
    canvas.select(dash_pen);
    canvas.line(Tail[0], Tail[1]);
  }


  _stprintf(sTmp, TEXT("%i"), iround(Calculated().WindSpeed * SPEEDMODIFY));

  TextInBoxMode_t TextInBoxMode = { 16 | 32 }; // JMW test {2 | 16};
  if (Arrow[5].y>=Arrow[6].y) {
    TextInBox(canvas, sTmp, Arrow[5].x-kx, Arrow[5].y, TextInBoxMode, rc);
  } else {
    TextInBox(canvas, sTmp, Arrow[6].x-kx, Arrow[6].y, TextInBoxMode, rc);
  }
}
Example #19
0
void
GaugeVario::RenderBugs(Canvas &canvas)
{
  static int last_bugs = -1;
  static PixelRect label_rect = {-1,-1,-1,-1};
  static PixelRect value_rect = {-1,-1,-1,-1};
  static RasterPoint label_pos = {-1,-1};
  static RasterPoint value_pos = {-1,-1};

  if (!bugs_initialised) {
    const PixelRect rc = GetClientRect();
    PixelSize tSize;

    label_pos.x = 1;
    label_pos.y = rc.bottom - 2
      - look.text_font->GetCapitalHeight()
      - look.text_font->GetAscentHeight();

    value_pos.x = 1;
    value_pos.y = rc.bottom - 1
      - look.text_font->GetAscentHeight();

    label_rect.left = label_pos.x;
    label_rect.top = label_pos.y
      + look.text_font->GetAscentHeight()
      - look.text_font->GetCapitalHeight();
    value_rect.left = value_pos.x;
    value_rect.top = value_pos.y
      + look.text_font->GetAscentHeight()
      - look.text_font->GetCapitalHeight();

    canvas.Select(*look.text_font);
    tSize = canvas.CalcTextSize(TEXT_BUG);

    label_rect.right = label_rect.left + tSize.cx;
    label_rect.bottom = label_rect.top
      + look.text_font->GetCapitalHeight()
      + look.text_font->GetHeight()
      - look.text_font->GetAscentHeight();

    tSize = canvas.CalcTextSize(_T("100%"));

    value_rect.right = value_rect.left + tSize.cx;
    value_rect.bottom = value_rect.top +
      look.text_font->GetCapitalHeight();

    bugs_initialised = true;
  }

  int bugs = iround((fixed(1) - GetComputerSettings().polar.bugs) * 100);
  if (!IsPersistent() || bugs != last_bugs) {

    canvas.Select(*look.text_font);

    if (IsPersistent())
      canvas.SetBackgroundColor(look.background_color);
    else
      canvas.SetBackgroundTransparent();

    if (IsPersistent() || last_bugs < 1 || bugs < 1) {
      if (bugs > 0) {
        canvas.SetTextColor(look.dimmed_text_color);
        if (IsPersistent())
          canvas.DrawOpaqueText(label_pos.x, label_pos.y, label_rect, TEXT_BUG);
        else
          canvas.DrawText(label_pos.x, label_pos.y, TEXT_BUG);
      } else if (IsPersistent())
        canvas.DrawFilledRectangle(label_rect, look.background_color);
    }

    if (bugs > 0) {
      TCHAR buffer[18];
      _stprintf(buffer, _T("%d%%"), bugs);
      canvas.SetTextColor(look.text_color);
      if (IsPersistent())
        canvas.DrawOpaqueText(value_pos.x, value_pos.y, value_rect, buffer);
      else 
        canvas.DrawText(value_pos.x, value_pos.y, buffer);
    } else if (IsPersistent())
      canvas.DrawFilledRectangle(value_rect, look.background_color);

    if (IsPersistent())
      last_bugs = bugs;
  }
}
Example #20
0
 /**
  * Converts a geographical distance (m) to a screen distance (px)
  * @param x A geographical distance (m)
  * @return The converted distance in px
  */
 unsigned GeoToScreenDistance(const fixed x) const {
   return iround(scale * x);
 }
Example #21
0
void BC_Resources::init_font_defs(double scale)
{
	char string[BCTEXTLEN];
	def_font(small_font,       iround(scale*11));
	def_font(small_font2,      iround(scale*11));
	def_font(medium_font,      iround(scale*14));
	def_font(medium_font2,     iround(scale*14));
	def_font(large_font,       iround(scale*18));
	def_font(large_font2,      iround(scale*20));
	def_font(big_font,         iround(scale*160), iround(scale*160));
	def_font(big_font2,        iround(scale*160), iround(scale*160));
	def_font(small_fontset,    iround(scale*10));
	def_font(medium_fontset,   iround(scale*14));
	def_font(large_fontset,    iround(scale*18));
	def_font(big_fontset,      iround(scale*24));
	def_font(small_font_xft,   (scale*10.6667));
	def_font(small_b_font_xft, (scale*10.6667));
	def_font(medium_font_xft,  (scale*13.3333));
	def_font(medium_b_font_xft,(scale*13.3333));
	def_font(large_font_xft,   (scale*21.3333));
	def_font(large_b_font_xft, (scale*21.3333));
	def_font(big_font_xft,     (scale*37.3333));
	def_font(big_b_font_xft,   (scale*37.3333));

	set_font(small_font_xft2,  default_font_xft2);
	set_font(medium_font_xft2, default_font_xft2);
	set_font(large_font_xft2,  default_font_xft2);
	set_font(big_font_xft2,    default_font_xft2);
}
Example #22
0
void taper_grad(float ** waveconv,float ** taper_coeff, float **srcpos, int nshots, int **recpos, int ntr, int sws)
{

	/* extern variables */

        extern float DH;
	extern int FREE_SURF, NX, NY, NXG, NYG;
	extern int NPROCX, NPROCY, MYID, POS[3];
	extern FILE *FP;
	
	/* local variables */
	int i, j, h, ifw, ii, jj, n, xb, yb, xe, ye, taperlength,taperlength2, VTON, SRTON;
	int ijc, iy, ix, iii, jjj, xx, yy, srctaper_gridpt, i1, j1;

	extern int GRADT1, GRADT2, GRADT3, GRADT4;
	float amp, a, *window, grad_tap, **waveconvtmp;
	char modfile[STRING_SIZE];
	
	extern float SRTRADIUS;
	extern int SRTSHAPE, FILTSIZE;
        float **m, **edgemat, **mm, **msum, minm, maxm, x, y, rad, **taper_coeff_glob;
        float maxrad;
        float EXP_TAPER_GRAD_HOR;

	FILE *fp_taper;

	/*SRTSHAPE=2;
	SRTRADIUS=25.0;
	filtsize=2;*/
        
        EXP_TAPER_GRAD_HOR = 2.0; /* TAPER TEST  */

    /* =============== */
    /* Vertical taper  */
    /* =============== */
	
	if(sws==1){
	
	/* define taper geometry */
	taperlength=GRADT2-GRADT1;
	taperlength2=GRADT4-GRADT3;
	ifw = GRADT4-GRADT1;
	
	/*printf("%d \t %d \t %d \t %d \n",GRADT1, GRADT2, GRADT3, GRADT4);
	printf("%d \t %d \t %d \n",taperlength, taperlength2,ifw);*/
	
	if (MYID==0)
	{
		fprintf(FP,"\n **Message from taper_grad (printed by PE %d):\n",MYID);
		fprintf(FP," Coefficients for gradient taper are now calculated.\n");
	}
	
	waveconvtmp = matrix(0,NY+1,0,NX+1);
	window=vector(1,ifw);
	 
	 /* Gaussian window */  
        a=3;    /* damping coefficient */
        for (i=1;i<=ifw;i++){
	window[i] = 1.0;
	
	    if(i<=taperlength){
	       window[i] = exp(-(1.0/2.0)*(a*(i-taperlength)/(taperlength/2.0))*(a*(i-taperlength)/(taperlength/2.0)));
	    }
	    
	    if(i>=(ifw-taperlength2)){
	       window[i] = exp(-(1.0/2.0)*(a*(i-(ifw-taperlength2))/(taperlength2/2.0))*(a*(i-(ifw-taperlength2))/(taperlength2/2.0)));
	    }
	    
	}
	
	/* loop over global grid */
	for (j=1;j<=NYG;j++){
	
	   h=1;
	   for (i=1;i<=NXG;i++){

                        grad_tap=0.0;
			
			if((i>GRADT1)&&(i<GRADT4)){
			   grad_tap=window[h];
			   h++;
			}
			   			
			if ((POS[1]==((i-1)/NX)) && 
		   	 (POS[2]==((j-1)/NY))){
				ii=i-POS[1]*NX;
				jj=j-POS[2]*NY;

				taper_coeff[jj][ii]=grad_tap;

			}
		}
	}	
	
	/* apply taper on local gradient */
	for (j=1;j<=NY;j++){
	   for (i=1;i<=NX;i++){
           waveconv[j][i]*=taper_coeff[j][i];
	   waveconvtmp[j][i] = waveconv[j][i];
           }
	}
	
		
        /* apply filter at shot and receiver points */
	for (n=1;n<=nshots;n++)
	{
		i = iround(srcpos[1][n]/DH);
		j = iround(srcpos[2][n]/DH);
		if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
			ii = i-POS[1]*NX;
			jj = j-POS[2]*NY;
			/*waveconvtmp[jj][ii] = 1*waveconv[jj][ii]
						+ 8*(waveconv[jj-1][ii] + waveconv[jj+1][ii] + waveconv[jj][ii-1] + waveconv[jj][ii+1])
						+ 4*(waveconv[jj-1][ii-1] + waveconv[jj-1][ii+1] + waveconv[jj+1][ii+1] + waveconv[jj+1][ii-1]);
			waveconvtmp[jj][ii] = waveconvtmp[jj][ii]/49;*/
			
			waveconvtmp[jj][ii] = 0.0;
		}
	}

	for (j=1;j<=NY;j++){
		for (i=1;i<=NX;i++){
        		waveconv[j][i] = waveconvtmp[j][i];
		}
	}	
	
	for (n=1;n<=ntr;n++)
	{
		i = recpos[1][n];
		j = recpos[2][n];
		if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
			ii = i-POS[1]*NX;
			jj = j-POS[2]*NY;
			/*waveconvtmp[jj][ii] = 1*waveconv[jj][ii]
						+ 8*(waveconv[jj-1][ii] + waveconv[jj+1][ii] + waveconv[jj][ii-1] + waveconv[jj][ii+1])
						+ 4*(waveconv[jj-1][ii-1] + waveconv[jj-1][ii+1] + waveconv[jj+1][ii+1] + waveconv[jj+1][ii-1]);
			waveconvtmp[jj][ii] = waveconvtmp[jj][ii]/49;*/
			
			waveconvtmp[jj][ii] = 0.0;
			
		}
	}

	for (j=1;j<=NY;j++){
		for (i=1;i<=NX;i++){
        		waveconv[j][i] = waveconvtmp[j][i];
		}
	}	

	sprintf(modfile,"taper_coeff_vert.bin");

	writemod(modfile,taper_coeff,3); 

	MPI_Barrier(MPI_COMM_WORLD);

	if (MYID==0) mergemod(modfile,3); 


	free_vector(window,1,ifw);
	free_matrix(waveconvtmp,0,NX+1,0,NY+1);
	}

        
	/* ======================== */
	/* Horizontal Taper         */
	/* ======================== */
	
	if(sws==2){
        /* define taper geometry */
        taperlength=GRADT2-GRADT1;
        taperlength2=GRADT4-GRADT3;
        ifw = GRADT2-GRADT1+1;

        printf("%d \t %d \t %d \t %d \n",GRADT1, GRADT2, GRADT3, GRADT4);
        printf("%d \t %d \t %d \n",taperlength, taperlength2,ifw);

        if (MYID==0)
        {
                fprintf(FP,"\n **Message from taper_grid (printed by PE %d):\n",MYID);
                fprintf(FP," Coefficients for gradient taper are now calculated.\n");
        }

        waveconvtmp = matrix(0,NY+1,0,NX+1);
        window=vector(1,ifw);
         
        /* Gaussian window */  
        a=3;    /* damping coefficient */
        for (i=1;i<=ifw;i++){
        window[i] = 1.0;

            if(i<=taperlength){
               window[i] = exp(-(1.0/2.0)*(a*(i-taperlength)/(taperlength/2.0))*(a*(i-taperlength)/(taperlength/2.0)));
            }
          
        }

        /* loop over global grid */
	h=1;
        for (j=1;j<=NYG;j++){
           for (i=1;i<=NXG;i++){

                        grad_tap=0.0;

                        if((j>=GRADT1)&&(j<=GRADT2)){
                           grad_tap=window[h];
                        }

                        if(j>GRADT2){
                          
                          /*grad_tap=((float)(j*DH))*((float)(j*DH))*((float)(j*DH));*/
			  /*grad_tap=((float)(j*DH))*((float)(j*DH));*/
			  /*grad_tap=(float)(j*DH);*/ 
			  
			  /*grad_tap=((float)((j*DH)/(GRADT2*DH)));*/ 
			  /*grad_tap=1.0;*/

			  grad_tap=pow((float)(j*DH),EXP_TAPER_GRAD_HOR);

                        }
                        
                        /*grad_tap=((float)(j*DH));*/
			
			  
                        if ((POS[1]==((i-1)/NX)) && 
                         (POS[2]==((j-1)/NY))){
                                ii=i-POS[1]*NX;
                                jj=j-POS[2]*NY;

                                taper_coeff[jj][ii]=grad_tap;

                        }

                }
		
	   if(j>=GRADT1){h++;}
        }

        /* apply taper on local gradient */
        for (j=1;j<=NY;j++){
           for (i=1;i<=NX;i++){
           waveconv[j][i]*=taper_coeff[j][i];
           waveconvtmp[j][i] = waveconv[j][i];
           }
        }



        /* apply filter at shot and receiver points */
        /*for (n=1;n<=nshots;n++)
        {
                i = iround(srcpos[1][n]/DH);
                j = iround(srcpos[2][n]/DH);
                if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
                        ii = i-POS[1]*NX;
                        jj = j-POS[2]*NY;
                        waveconvtmp[jj][ii] = 1*waveconv[jj][ii]
                                                + 8*(waveconv[jj-1][ii] + waveconv[jj+1][ii] + waveconv[jj][ii-1] + waveconv[jj][ii+1])
                                                + 4*(waveconv[jj-1][ii-1] + waveconv[jj-1][ii+1] + waveconv[jj+1][ii+1] + waveconv[jj+1][ii-1]);
                        waveconvtmp[jj][ii] = waveconvtmp[jj][ii]/49;
                }
        }

        for (j=1;j<=NY;j++){
                for (i=1;i<=NX;i++){
                        waveconv[j][i] = waveconvtmp[j][i];
                }
        }

        for (n=1;n<=ntr;n++)
        {
                i = recpos[1][n];
                j = recpos[2][n];
                if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
                        ii = i-POS[1]*NX;
                        jj = j-POS[2]*NY;
                        waveconvtmp[jj][ii] = 1*waveconv[jj][ii]
                                                + 8*(waveconv[jj-1][ii] + waveconv[jj+1][ii] + waveconv[jj][ii-1] + waveconv[jj][ii+1])
                                                + 4*(waveconv[jj-1][ii-1] + waveconv[jj-1][ii+1] + waveconv[jj+1][ii+1] + waveconv[jj+1][ii-1]);
                        waveconvtmp[jj][ii] = waveconvtmp[jj][ii]/49;
                }
        }

        for (j=1;j<=NY;j++){
                for (i=1;i<=NX;i++){
                        waveconv[j][i] = waveconvtmp[j][i];
                }
        }*/

        sprintf(modfile,"taper_coeff_hor.bin");
        writemod(modfile,taper_coeff,3); 
        MPI_Barrier(MPI_COMM_WORLD);
        if (MYID==0) mergemod(modfile,3); 


        free_vector(window,1,ifw);
        free_matrix(waveconvtmp,0,NX+1,0,NY+1);
        } /* end of sws==2 */

        /* =================================== */
        /* taper source and receiver positions */
	/* =================================== */
	
	if(sws==3) {
                /* Convert from meters to gridpoints -> minimum 5x5 gridpoints */
                srctaper_gridpt = (int)(ceil(2.0*SRTRADIUS/DH));
                if (srctaper_gridpt<5)  srctaper_gridpt = 5;

                m               = matrix(1,srctaper_gridpt,1,srctaper_gridpt);
                edgemat         = matrix(1,4,1,1);
                mm              = matrix(1,NYG,1,NXG);
                msum            = matrix(1,NYG,1,NXG);
                taper_coeff_glob= matrix(1,NYG,1,NXG);
		waveconvtmp     = matrix(0,NY+1,0,NX+1);

                for (iy=1;iy<=NYG;iy++)
                        for (ix=1;ix<=NXG;ix++)  msum[iy][ix] = 1.0;

                MPI_Barrier(MPI_COMM_WORLD);

                /*****************************/
                /* Taper at source positions */
                /*****************************/

                a = 1.0;
                maxrad = sqrt(2.0*SRTRADIUS*SRTRADIUS);
                for (j=1;j<=srctaper_gridpt;j++) {
                        for (i=1;i<=srctaper_gridpt;i++) {
                                x = ((float)i-((float)srctaper_gridpt)/2.0-0.5)*DH;
                                y = ((float)j-((float)srctaper_gridpt)/2.0-0.5)*DH;
                                rad = sqrt(x*x+y*y);

                                switch (SRTSHAPE) {
                                case 1:
                                        m[j][i] = erf(a*rad/maxrad);
                                        break;
                                case 2:
                                        if (rad>0)      m[j][i] = log(rad);
                                        else            m[j][i] = 0.0;
                                        break;
                                }
                        }
                }

                /* generate local taper matrix */
                minm = minimum_m(m,srctaper_gridpt,srctaper_gridpt);
                for (j=1;j<=srctaper_gridpt;j++)
                        for (i=1;i<=srctaper_gridpt;i++)  m[j][i] -= minm;

                /* normalize taper matrix to max of values at the centre of all 4 taper area edges,     */
                /* not the global maximum, which is located at the corners                              */
                edgemat[1][1] = m[1][srctaper_gridpt/2];
                edgemat[2][1] = m[srctaper_gridpt/2][1];
                edgemat[3][1] = m[srctaper_gridpt/2][srctaper_gridpt];
                edgemat[4][1] = m[srctaper_gridpt][srctaper_gridpt/2];
                maxm = maximum_m(edgemat,1,4);
                for (j=1;j<=srctaper_gridpt;j++)
                        for (i=1;i<=srctaper_gridpt;i++) {
                                m[j][i] /= maxm;
                                if (m[j][i]>1.0)  m[j][i] = 1.0;
                        }

                /* get central position within the taper */
                ijc = (int)(ceil((float)srctaper_gridpt/2));

                /*********************/
                /* loop over sources */
                for (n=1;n<=nshots;n++) {
                        for (iy=1;iy<=NYG;iy++)
                                for (ix=1;ix<=NXG;ix++)  mm[iy][ix] = 1.0;

                        i = iround(srcpos[1][n]/DH);
                        j = iround(srcpos[2][n]/DH);
                        for (iy=1;iy<=srctaper_gridpt;iy++) {
                                for (ix=1;ix<=srctaper_gridpt;ix++) {
                                        xx = i + ix - ijc;
                                        yy = j + iy - ijc;
                                        if ((xx<1) || (xx>NXG) || (yy<1) || (yy>NYG))  continue;
                                        mm[yy][xx] = m[iy][ix];
                                }
                        }

/*                      for (iy=1;iy<=NYG;iy++)
                                for (ix=1;ix<=NXG;ix++)  msum[iy][ix] += mm[iy][ix];
*/
                        for (iy=1;iy<=NYG;iy++)
                                for (ix=1;ix<=NXG;ix++)
                                        if (msum[iy][ix] > mm[iy][ix])
                                                msum[iy][ix] = mm[iy][ix];

                }

                /***********************/
                /* loop over receivers */
                /*for (n=1;n<=ntr;n++) {
                        for (iy=1;iy<=NYG;iy++)
                                for (ix=1;ix<=NXG;ix++)  mm[iy][ix] = 1.0;

                        i = recpos[1][n];
                        j = recpos[2][n];
                        for (iy=1;iy<=srctaper_gridpt;iy++) {
                                for (ix=1;ix<=srctaper_gridpt;ix++) {
                                        xx = i + ix - ijc;
                                        yy = j + iy - ijc;
                                        if ((xx<1) || (xx>NXG) || (yy<1) || (yy>NYG))  continue;
                                        mm[yy][xx] = m[iy][ix];
                                }
                        }*/

/*                      for (iy=1;iy<=NYG;iy++)    Die kommenden zwei Zeilen wurden von Daniel auskommentiert.
                                for (ix=1;ix<=NXG;ix++)  msum[iy][ix] += mm[iy][ix];
*/
                       /* for (iy=1;iy<=NYG;iy++)
                                for (ix=1;ix<=NXG;ix++)
                                        if (msum[iy][ix] > mm[iy][ix])
                                                msum[iy][ix] = mm[iy][ix];

                }*/

                minm = minimum_m(msum,NXG,NYG);
                for (iy=1;iy<=NYG;iy++)
                        for (ix=1;ix<=NXG;ix++)  msum[iy][ix] -= minm;

                maxm = maximum_m(msum,NXG,NYG);
                for (iy=1;iy<=NYG;iy++)
                        for (ix=1;ix<=NXG;ix++) {
                                taper_coeff_glob[iy][ix] = msum[iy][ix]/maxm;

                                if ((POS[1]==((ix-1)/NX)) && (POS[2]==((iy-1)/NY))){
                                        ii = ix-POS[1]*NX;
                                        jj = iy-POS[2]*NY;
                                        /*Diese Zeile wurde von Daniel auskommentiert: taper_coeff[jj][ii] = taper_coeff_glob[iy][ix] * ((float)(iy*DH));*/
					/*taper_coeff[jj][ii] = ((float)(iy*DH)) * ((float)(iy*DH)) * ((float)(iy*DH));*/
					taper_coeff[jj][ii]=msum[iy][ix]/maxm;
                                }
                        }
			
	/* apply taper on local gradient */
        for (j=1;j<=NY;j++){
           for (i=1;i<=NX;i++){
           waveconv[j][i]*=taper_coeff[j][i];
           waveconvtmp[j][i] = waveconv[j][i];
           }
        }	
		
	 /* apply filter at shot and receiver points */
	for (n=1;n<=nshots;n++)
	{
		i1 = iround(srcpos[1][n]/DH);
		j1 = iround(srcpos[2][n]/DH);
		
		for (i=i1-FILTSIZE;i<=i1+FILTSIZE;i++){
		   for (j=j1-FILTSIZE;j<=j1+FILTSIZE;j++){
		       if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
			     ii = i-POS[1]*NX;
			     jj = j-POS[2]*NY;
			     /*waveconvtmp[jj][ii] = 1*waveconv[jj][ii]
				       		+ 8*(waveconv[jj-1][ii] + waveconv[jj+1][ii] + waveconv[jj][ii-1] + waveconv[jj][ii+1])
						+ 4*(waveconv[jj-1][ii-1] + waveconv[jj-1][ii+1] + waveconv[jj+1][ii+1] + waveconv[jj+1][ii-1]);
			      waveconvtmp[jj][ii] = waveconvtmp[jj][ii]/49;*/
			      if (jj>0){
			         waveconvtmp[jj][ii] = 0.0;
			         taper_coeff[jj][ii] = 0.0;
			      }
		        }
		    }
		}
		
		
	}

	
	/*for (n=1;n<=ntr;n++)
	{
		i1 = recpos[1][n];
		j1 = recpos[2][n];
		
            for (i=i1-FILTSIZE;i<=i1+FILTSIZE;i++){
		   for (j=j1-FILTSIZE;j<=j1+FILTSIZE;j++){
		
		       if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
			    ii = i-POS[1]*NX;
			    jj = j-POS[2]*NY;   */
			    /* Die kommenden 4 Zeilen wurden von Daniel auskommentiert. waveconvtmp[jj][ii] = 1*waveconv[jj][ii]
						+ 8*(waveconv[jj-1][ii] + waveconv[jj+1][ii] + waveconv[jj][ii-1] + waveconv[jj][ii+1])
						+ 4*(waveconv[jj-1][ii-1] + waveconv[jj-1][ii+1] + waveconv[jj+1][ii+1] + waveconv[jj+1][ii-1]);
			      waveconvtmp[jj][ii] = waveconvtmp[jj][ii]/49;*/
			
		/*	waveconvtmp[jj][ii] = 0.0;
			
		       }
		   }
	     }	       
	}*/		
		
        /* apply taper on local gradient */
        for (j=1;j<=NY;j++){
           for (i=1;i<=NX;i++){
           waveconv[j][i] = waveconvtmp[j][i];
           }
        }
	
	
                free_matrix(m,1,srctaper_gridpt,1,srctaper_gridpt);
                free_matrix(edgemat,1,4,1,1);
                free_matrix(mm,1,NYG,1,NXG);
                free_matrix(msum,1,NYG,1,NXG);
                free_matrix(taper_coeff_glob,1,NYG,1,NXG);
		free_matrix(waveconvtmp,0,NX+1,0,NY+1);
        
	
	

 
		
	MPI_Barrier(MPI_COMM_WORLD);
        sprintf(modfile,"taper_coeff_sources.bin");
        writemod(modfile,taper_coeff,3); 
        MPI_Barrier(MPI_COMM_WORLD);
        if (MYID==0) mergemod(modfile,3); 
	
	}

    /* ======================== */
    /* Read Taper from file     */  
    /* ======================== */
        
    if((sws>=4)&&(sws<=6)){
        
          if (MYID==0)
          {
                  fprintf(FP,"\n **Message from taper_grid (printed by PE %d):\n",MYID);
                  fprintf(FP," Coefficients for gradient taper are now calculated.\n");
          }
        
        if(sws==4){fp_taper=fopen("taper.bin","r");}
        if(sws==5){fp_taper=fopen("taper_u.bin","r");}
        if(sws==6){fp_taper=fopen("taper_rho.bin","r");}

        /* loop over global grid */
        for (i=1;i<=NXG;i++){
            for (j=1;j<=NYG;j++){
           
                fread(&grad_tap, sizeof(float), 1, fp_taper);
                                                                                       
                if ((POS[1]==((i-1)/NX)) && (POS[2]==((j-1)/NY))){
                   ii=i-POS[1]*NX;
                   jj=j-POS[2]*NY;
        
                   taper_coeff[jj][ii]=grad_tap;
                             
                }
            }
        }
 
        for (j=1;j<=NY;j++){   
           for (i=1;i<=NX;i++){     
              waveconv[j][i]*=taper_coeff[j][i];
           }                            
        }   
                                         
        fclose(fp_taper);
        
        sprintf(modfile,"taper_coeff_file.bin");
        writemod(modfile,taper_coeff,3);
                        
        MPI_Barrier(MPI_COMM_WORLD);
        if (MYID==0) mergemod(modfile,3);       
        } 
}
Example #23
0
void WindAnalyser::_calcWind(NMEA_INFO *nmeaInfo,
                             DERIVED_INFO *derivedInfo) {
  int i;
  double av=0;
  if (!numwindsamples) return;

  // reject if average time step greater than 2.0 seconds
  if ((windsamples[numwindsamples-1].t - windsamples[0].t)/
      (numwindsamples-1)>2.0) {
    return;
  }

  // find average
  for (i=0; i<numwindsamples; i++) {
    av += windsamples[i].mag;
  }
  av/= numwindsamples;

  // find zero time for times above average
  double rthisp;
  int j;
  int ithis = 0;
  double rthismax = 0;
  double rthismin = 0;
  int jmax= -1;
  int jmin= -1;
  int idiff;

  for (j=0; j<numwindsamples; j++) {

    rthisp= 0;

    for (i=0; i<numwindsamples; i++) {
      if (i== j) continue;
      ithis = (i+j)%numwindsamples;
      idiff = i;
      if (idiff>numwindsamples/2) {
        idiff = numwindsamples-idiff;
      }
      rthisp += (windsamples[ithis].mag)*idiff;
    }
    if ((rthisp<rthismax)||(jmax==-1)) {
      rthismax = rthisp;
      jmax = j;
    }
    if ((rthisp>rthismin)||(jmin==-1)) {
      rthismin = rthisp;
      jmin = j;
    }
  }

  if(jmin<0 || jmax<0) {
      return;
  }
  // jmax is the point where most wind samples are below
  // jmin is the point where most wind samples are above

  maxVector = windsamples[jmax].v;
  minVector = windsamples[jmin].v;

  // attempt to fit cycloid

  double phase;
  double mag = 0.5*(windsamples[jmax].mag - windsamples[jmin].mag);
  double wx, wy;
  double cmag;
  double rthis=0;
  for (i=0; i<numwindsamples; i++) {
    phase = ((i+jmax)%numwindsamples)*3.141592*2.0/numwindsamples;
    wx = cos(phase)*av+mag;
    wy = sin(phase)*av;
    cmag = sqrt(wx*wx+wy*wy)-windsamples[i].mag;
    rthis += cmag*cmag;
  }
  rthis/= numwindsamples;
  LKASSERT(rthis>=0);
  if (rthis<0) return; // UNMANAGED
  rthis = sqrt(rthis);

  int quality;

  if (mag>1) {
    quality = 5- iround(rthis/mag*3);
  } else {
    quality = 5- iround(rthis);
  }

  if (circleCount<3) quality--;
  if (circleCount<2) quality--;
  if (circleCount<1) return;

  quality= min(quality,5);  //5 is maximum quality, make sure we honour that.

  Vector a;

  #if BUGSTOP
  LKASSERT(windsamples[jmax].mag!=0);
  #endif
  if (windsamples[jmax].mag==0) return;

  a.x = -mag*maxVector.x/windsamples[jmax].mag;
  a.y = -mag*maxVector.y/windsamples[jmax].mag;

  if (quality<1) {
    return;   //measurment quality too low
  }

  if (a.x*a.x+a.y*a.y<30*30) {
    // limit to reasonable values (60 knots), reject otherwise
    slot_newEstimate(nmeaInfo, derivedInfo, a, quality);
  }

}
Example #24
0
void ZLocsegChainConn::display(QPainter &painter, int z, Display_Style option) const
{
  UNUSED_PARAMETER(option);

  if ((m_hookChain != NULL) && (m_loopChain != NULL)) {
    Local_Neuroseg *locseg1;
    Local_Neuroseg *locseg2;
    if (m_hookSpot == 0) {
      locseg1 = m_hookChain->headNeuroseg();
    } else {
      locseg1 = m_hookChain->tailNeuroseg();
    }

    if (m_mode == NEUROCOMP_CONN_LINK) {
      if (m_loopSpot == 0) {
        locseg2 = m_loopChain->headNeuroseg();
      } else {
        locseg2 = m_loopChain->tailNeuroseg();
      }
    } else {
#ifdef _DEBUG_2
      print();
#endif
      locseg2 = m_loopChain->neurosegAt(m_loopSpot);
    }

    double center1[3], center2[3];
    Local_Neuroseg_Center(locseg1, center1);
    Local_Neuroseg_Center(locseg2, center2);

    for (int i = 0; i < 3; i++) {
      center1[i] = round(center1[i]);
      center2[i] = round(center2[i]);
    }

    QPointF center;

    painter.setPen(QPen(QColor(255, 255, 255, 255), .7));

    if ((center1[2] == z) || (z < 0)) {
      center.setX(center1[0]);
      center.setY(center1[1]);
      painter.drawEllipse(center, 3, 3);
    }

    if ((center2[2] == z) || (z < 0)){
      center.setX(center2[0]);
      center.setY(center2[1]);
      painter.drawEllipse(center, 3, 3);
    }

    voxel_t start, end;
    for (int i = 0; i < 3; i++) {
      start[i] = iround(center1[i]);
      end[i] = iround(center2[i]);
    }

    if (start[2] == z || z < 0 || end[2] == z || z < 0 ||
        (start[2] < z && end[2] > z) ||
        (start[2] > z && end[2] < z)) {
      QColor lineColor(255, 255, 255);
      painter.setPen(QPen(lineColor, .7));


      painter.drawLine(QPointF(center1[0], center1[1]),
          QPointF(center2[0], center2[1]));
    }

    /*
    Object_3d *obj = Line_To_Object_3d(start, end);

    for (size_t i = 0; i < obj->size; i++) {
      if (((obj->voxels[i][2] == z) || (z < 0))&&
          IS_IN_CLOSE_RANGE(obj->voxels[i][0], 0, widget->width() - 1) &&
          IS_IN_CLOSE_RANGE(obj->voxels[i][1], 0, widget->height() - 1)){
        uchar *pixel = widget->scanLine(obj->voxels[i][1])
                       + 4 * obj->voxels[i][0];
        if (i % 2 == 0) {
          pixel[0] = 255;
          pixel[1] = 255;
          pixel[2] = 255;
          pixel[3] = 255;
        } else {
          pixel[0] = 0;
          pixel[1] = 0;
          pixel[2] = 0;
          pixel[3] = 255;
        }
      }
    }

    Kill_Object_3d(obj);
    */
  }
}
static double FLAltRounded(double alt) {
  int f = iround(alt/10)*10;
  return (double)f;
}
Example #26
0
KaboHaze::KaboHaze(SpaceLocation *creator, Ship *ohost, double obasepower)
:
SpaceLocation(creator, Vector2(0.0, 0.0), 0.0)
{
	STACKTRACE;
	prev = 0;
	next = 0;

	// update the list (insert at the start)
	if (KaboHazeFirst)
		KaboHazeFirst->prev = this;
	next = KaboHazeFirst;
	prev = 0;
	KaboHazeFirst = this;

	//mother = omother;
	host = ohost;
	basepower = obasepower;

	power = basepower;

	//	decay_time = odecaytime;	// in milliseconds

	newcrew = iround(host->getCrew());
	oldcrew = newcrew;

	// this "haze" is passive, of course:
	collide_flag_anyone = 0;
	collide_flag_sameteam = 0;
	collide_flag_sameship = 0;

	// I'll make 64 rotated versions in total, if needed, which I'll store
	// in memory:

	for ( int i = 0; i < 64; ++i ) {
		shield_bmp[i] = 0;
	}
	sprite_index = 0;			 // no rotation.
	shield_sprite_index = 0;

	// this item cannot collide

	collide_flag_anyone = 0;

	// this is probably important ... otherwise a thing like a flipping wedge indicator
	// can avoid a shield from being drawn ?!?!

	layer = LAYER_SHIPS;
	set_depth(DEPTH_SHIPS + 0.1);
	// The +0.1 places this presence at a higher level, so that this routine is
	// always done after the ship was drawn! Thnx Orz, for telling.

	// Graphics init stuff for the shield !

	// copy the ship sprite (yes, a COPY because we need to do some operations on it !)

	SpaceSprite *ship_spr;
	ship_spr = host->get_sprite();
	if (!ship_spr) {
		state = 0;
		return;
	}

	//BITMAP *ship_bmp;
	int wship = ship_spr->width();
	int hship = ship_spr->height();

	BITMAP *ship_bmp = create_bitmap(wship, hship);
	clear_to_color(ship_bmp, 0); // important otherwise it contains artefacts

	int index = 0;
	ship_spr->draw(Vector2(0, 0), Vector2(wship, hship), index, ship_bmp);
	// this does a (masked?) blit

	// create a blurred image from this:
	int R = 3;
	blit_blur(ship_bmp, R);		 // a complex and costly funtion ! Inefficiently programmed as well of course (by me).

	// now, create a masked shield - only the area that covers the
	// blurred image of the ship:

	shield_bmp[sprite_index] = create_bitmap(wship, hship);
								 // important otherwise it contains artefacts
	clear_to_color(shield_bmp[sprite_index], 0);

	// scale/draw a shield:

	/*
	// the raw shield image
	BITMAP *raw_bmp = this->sprite->get_bitmap_readonly(0);

	int wraw = raw_bmp->w;
	int hraw = raw_bmp->h;

	stretch_blit(raw_bmp, shield_bmp[sprite_index], 0, 0, wraw, hraw, 0, 0, wship, hship );
	*/
								 // a uniform green glow
	clear_to_color(shield_bmp[sprite_index], tw_makecol(0,255,0));

	// mask out the areas outside the ship, so that the shield only covers
	// the ship.
	blit_singlecolor(ship_bmp, shield_bmp[sprite_index], tw_makecol(0,0,0));

	destroy_bitmap(ship_bmp);

	// ok ! this is what we need - only things left are
	// resize
	// rotate
	// trans-draw.
	// which we've to do repeatedly.

	// we may also cache the rotated images !

	// flashes can occur within the edges of the shield ... check where the
	// edges are !! (assuming here, it's a closed shape).

	edge_left = new int [hship];
	edge_right = new int [hship];

	for ( int j = 0; j < hship; ++j ) {
		edge_left[j] = -1;
		edge_right[j] = -1;
		for ( int i = 0; i < wship; ++i ) {
			int color = getpixel(shield_bmp[0], i, j);

			if ( color != 0 ) {
				if ( edge_left[j] == -1 )
					edge_left[j] = i;

				edge_right[j] = i;
			}

		}
	}

	attributes &= ~ATTRIB_STANDARD_INDEX;
}
Example #27
0
/**
 * Feet to Pixel converters: convert x coordinate to pixels
 */
inline int xcon(double x)
{
  return iround(x / SCALE);
}
Example #28
0
void KaboHaze::animate(Frame *space)
{
	STACKTRACE;
	// IMPORTANT: physics must not be changed, that is, NON-LOCAL variable must not
	// be changed in this subroutine !
	// Reason: the TimeWarp engine can decide to skip animations in case of low
	// frame-rate, thus, leading to a desynch between computers!

	/*

	  Aaaaah, lots of work to do for a simple job, namely, create a transparent overlay
	  of the shield onto the host:

	  - Init (see constructor):
	  Take the host-ship picture.
	  Create a (blurred) mask image of it.
	  Draw the shield and
	  Overlay the mask.

	  - Animate:
	  Scale and draw the masked shield,
	  Rotate and
	  Draw transparent onto the screen.

	*/

	if (!host)
		return;

	//if ( state == 0 )
	//	return;

	// the host can die in-between calculate and animate, therefore I use this; it's
	// not allowed to change state of this presence though; that's done only in
	// calculate().

	// Create a rotated copy of the shield sprite ... but only, if such a thing
	// does not exist, yet ! The purpose of this is, to spread the amount of
	// calculations over different frames, and to limit them to when they're
	// needed.

	int wshield = shield_bmp[0]->w;
	int hshield = shield_bmp[0]->h;

	if ( !shield_bmp[shield_sprite_index] ) {
		shield_bmp[shield_sprite_index] = create_bitmap(wshield, hshield);
								 // important otherwise it contains artefacts
		clear_to_color(shield_bmp[shield_sprite_index], 0);
		rotate_sprite(shield_bmp[shield_sprite_index], shield_bmp[0], 0, 0, iround((1<<24)*(host->angle + 0.5*PI)/PI2) );
		// result is in sprite_bmp[sprite_index]   ( nice conventions, huh !)
	}

	//sprite_index = 0;	// also needed - for collision detection??
	// note, I've turned the collision of, since collide_flag_anyone = 0, but
	// otherwise, the collision detector would use this sprite_index to access
	// a ship sprite that doesnt exist !!

	// next, animate ...

	// first, reserve space for the target image, but ... how big should it be?
	// well, as big as the ship_bmp, but then, zoomed in space:

	int wfinal = int(wshield * space_zoom);
	int hfinal = int(hshield * space_zoom);

	BITMAP *final_bmp;
	final_bmp = create_bitmap(wfinal, hfinal);

	// scale/draw a shield:

	stretch_blit(shield_bmp[shield_sprite_index], final_bmp, 0, 0, wshield, hshield, 0, 0, wfinal, hfinal );
	// result is in final_bmp

	// I need to calculate screen coordinates (using the original bmp size).
	//	double xhost = host->normal_pos().x;
	//	double yhost = host->normal_pos().y;
	Vector2 Vcorner;
	Vcorner = corner(host->normal_pos(), Vector2(wshield, hshield) );

								 //wcorner(xhost, wshield);
	int xplot = iround(Vcorner.x);
								 //hcorner(yhost, hshield);
	int yplot = iround(Vcorner.y);
	// these routines are the standard way to calculate screen coordinates !

								 // local
	double power_scaled = power / 10.0;
	if ( power_scaled > 1.0 )
		power_scaled = 1.0;		 // max brightness.

	// change the brightness of the shield:
	int brightness = int(255 * power_scaled);

	set_add_blender(0, 0, 0, brightness);

	draw_trans_sprite(space->surface, final_bmp, xplot, yplot);
	space->add_box(xplot, yplot, wshield, hshield);

	// also, draw a (few) flashes, at twice the brightness:

	brightness = 255;

	for ( int i = 0; i < int(power); ++i ) {
		int dx, dy;

		dx = wshield;
		dy = hshield;

		int icheck = 0;
		for (;;) {
			++icheck;
			if (icheck > 100)
				break;			 // too bad !!

								 //graphics
			dy = rand() % hshield;
			if (edge_left[dy] == -1)
				continue;

			if ( !(rand() % 2) ) //graphics
				dx = edge_left[dy];
			else
				dx = edge_right[dy];
		}

		dx -= wshield / 2;
		dy -= hshield / 2;

		double a = host->angle + 0.5*PI;
								 // rotated around the center
		int dx2 = iround(wshield/2 + dx * cos(a) - dy * sin(a));
		int dy2 = iround(hshield/2 + dy * cos(a) + dx * sin(a));

		dx = iround( dx2 * space_zoom);
		dy = iround( dy2 * space_zoom);

		int x = xplot + dx;
		int y = yplot + dy;

		tw_putpixel(space->surface, x, y, tw_makecol(brightness,brightness,0) );

		space->add_pixel(x, y);

	}

	// release the temporary bitmap:
	destroy_bitmap(final_bmp);
}
Example #29
0
void MarkLocation(const double lon, const double lat, const double altitude)
#endif
{
  #if USETOPOMARKS
  LockTerrainDataGraphics();
  if (topo_marks) {
    topo_marks->addPoint(lon, lat);
    topo_marks->triggerUpdateCache = true;
  }
  UnlockTerrainDataGraphics();
  #endif

  char message[160];

  FILE *stream;
  TCHAR tstring[50];
  bool dopreambol=false;
  TCHAR fname[MAX_PATH];
  LocalPath(fname,TEXT(LKD_WAYPOINTS));
  _tcscat(fname,_T(DIRSEP)); 
  _stprintf(tstring,_T("LK%04d%02d%02d.cup"), GPS_INFO.Year,GPS_INFO.Month,GPS_INFO.Day);
  _tcscat(fname,tstring);

  stream = _tfopen(fname,TEXT("r"));
  if (stream == NULL)
	dopreambol=true;
  else
	fclose(stream);

  stream = _tfopen(fname,TEXT("a+"));
  if (stream != NULL){
	if (dopreambol) {
		// file was created empty, we need to add preambol header for CUP
		strcpy(message,"name,code,country,lat,lon,elev,style,rwdir,rwlen,freq,desc\r\n");
		fwrite(message,strlen(message),1,stream);
	}

	char marktime[10], slat[20], slon[20], snear[50];
	Units::TimeToTextSimple(tstring,TimeLocal((int)GPS_INFO.Time));
	TCHAR2ascii(tstring,marktime,10);

	LatitudeToCUPString(lat,tstring);
	TCHAR2ascii(tstring,slat,20);
	LongitudeToCUPString(lon,tstring);
	TCHAR2ascii(tstring,slon,20);

	int j=FindNearestFarVisibleWayPoint(lon,lat,15000,WPT_UNKNOWN);
	if (j>0) {
        _tcscpy(tstring,WayPointList[j].Name); // Name is sized NAME_SIZE, 30, so ok with tstring[50]
        tstring[19]='\0'; // sized 20 chars
		TCHAR2ascii(tstring,snear,50);
	} else {
		strcpy(snear,"unknown");
	}

	sprintf(message,"MK%s%02d,LK8000,,%s,%s,%d.0m,1,,,,Created on %02d-%02d-%04d at h%s near: %s\r\n",
		marktime,GPS_INFO.Second,slat,slon, iround((int)altitude),
		GPS_INFO.Day,GPS_INFO.Month,GPS_INFO.Year, marktime, snear );

	fwrite(message,strlen(message),1,stream);
	fclose(stream);



	j=GetVirtualWaypointMarkerSlot();

	WayPointList[j].Latitude=lat;
	WayPointList[j].Longitude=lon;
	WayPointList[j].Altitude=altitude;
	WayPointList[j].Visible=TRUE;
	WayPointList[j].FarVisible=TRUE;

    ascii2TCHAR(marktime, tstring,50);
	_stprintf(WayPointList[j].Name,_T("MK%s%02d"),tstring,GPS_INFO.Second);
    #if BUGSTOP
    LKASSERT(WayPointList[j].Comment!=NULL);
    #endif
    if (WayPointList[j].Comment!=NULL) {
        ascii2TCHAR(snear, tstring, 50);
	    _stprintf(WayPointList[j].Comment,_T("Near: %s"),tstring);
    }

	WayPointCalc[j].WpType=WPT_TURNPOINT;

	// Force updating DoRange otherwise it will pass up to 3 minutes
	// before this marker appears in the 2.3 tps page
	LastDoRangeWaypointListTime=0; 
  }

}
Example #30
0
static void SetValues(int indexid) {
  //TCHAR *name = 0;
  //TCHAR *cn = 0;
  WndProperty* wp;
  TCHAR buffer[80];
  //TCHAR status[10];
  //static TCHAR Name[MAXFLARMNAME+1];
  //static TCHAR Cn[MAXFLARMCN+1];
  int wlen;

  if (indexid<0 || indexid>MAXTRAFFIC) {
	StartupStore(_T("--- LK setvalues invalid indexid=%d%s"),indexid,NEWLINE);
	// DoStatusMessage(_T("ERR-216 INVALID INDEXID"));
	return;
  }
  if ( LKTraffic[indexid].ID <=0 || LKTraffic[indexid].Status <LKT_REAL) {
	StartupStore(_T("--- LK setvalues invalid indexid=%d%s"),indexid,NEWLINE);
	// DoStatusMessage(_T("ERR-217 INVALID INDEXID"));
	return;
  }
  wp = (WndProperty*)wf->FindByName(TEXT("prpRegName"));
  if (wp) {

	wlen=wcslen(LKTraffic[indexid].Name);
	// a ? probably
	if (wlen==1) {
		_stprintf(buffer,_T("%06x"),LKTraffic[indexid].ID);
		buffer[MAXFLARMNAME]='\0';
	} else {
		_tcsncpy(buffer,LKTraffic[indexid].Name,MAXFLARMNAME);
		buffer[MAXFLARMNAME]='\0';
		ConvToUpper(buffer);
	}
	//name=Name;
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }


#if 0
  wp = (WndProperty*)wf->FindByName(TEXT("prpStatus"));
  if (wp) {
	switch(LKTraffic[indexid].Status) {
		case LKT_REAL:
			_tcscpy(status,_T("LIVE"));
			break;
		case LKT_GHOST:
			_tcscpy(status,_T("GHOST"));
			break;
		case LKT_ZOMBIE:
			_tcscpy(status,_T("ZOMBIE"));
			break;
		default:
			_tcscpy(status,_T("UNKNOWN"));
			break;
	}
	wp->SetText(status);
	wp->RefreshDisplay();
  }
#endif
  
  wp = (WndProperty*)wf->FindByName(TEXT("prpCn"));
  if (wp) {
	if ( _tcslen(LKTraffic[indexid].Cn) == 1 ) {
		if (LKTraffic[indexid].Cn[0] == _T('?')) {
			_tcscpy(buffer,_T(""));
		} else {
			_tcsncpy(buffer,LKTraffic[indexid].Cn,MAXFLARMCN);
			buffer[MAXFLARMCN]='\0';
		}
	} else {
		_tcsncpy(buffer,LKTraffic[indexid].Cn,MAXFLARMCN);
		buffer[MAXFLARMCN]='\0';
	}
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpDistance"));
  if (wp) {
	_stprintf(buffer,_T("%.1f %s"),LKTraffic[indexid].Distance*DISTANCEMODIFY, Units::GetDistanceName());
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpAltitude"));
  if (wp) {
	_stprintf(buffer,_T("%.0f %s"),LKTraffic[indexid].Altitude*ALTITUDEMODIFY, Units::GetAltitudeName());
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }
  wp = (WndProperty*)wf->FindByName(TEXT("prpAltDiff"));
  if (wp) {
	// this has to be reverted, because it is a relative altitude to us
	_stprintf(buffer,_T("%+.0f %s"),(CALCULATED_INFO.NavAltitude - LKTraffic[indexid].Altitude)*ALTITUDEMODIFY*-1, Units::GetAltitudeName());
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }
  wp = (WndProperty*)wf->FindByName(TEXT("prpSpeed"));
  if (wp) {
	_stprintf(buffer,_T("%.0f %s"),LKTraffic[indexid].Speed*SPEEDMODIFY, Units::GetHorizontalSpeedName());
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }
  wp = (WndProperty*)wf->FindByName(TEXT("prpVario"));
  if (wp) {
	_stprintf(buffer,_T("%+.1f %s"),LKTraffic[indexid].Average30s*LIFTMODIFY, Units::GetVerticalSpeedName());
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }

  wp = (WndProperty*)wf->FindByName(TEXT("prpBearing"));
  if (wp) {
	_stprintf(buffer, TEXT(" %d")TEXT(DEG), iround(LKTraffic[indexid].Bearing));
	wp->SetText(buffer);
	wp->RefreshDisplay();
  }

  FlarmId* flarmId = file.GetFlarmIdItem(LKTraffic[indexid].ID);
  if (flarmId != NULL) {
	wp = (WndProperty*)wf->FindByName(TEXT("prpName"));
	if (wp) {
		_stprintf(buffer,_T("%s"),flarmId->name);
		wp->SetText(buffer);
		wp->RefreshDisplay();
	}
	wp = (WndProperty*)wf->FindByName(TEXT("prpAirfield"));
	if (wp) {
		_stprintf(buffer,_T("%s"),flarmId->airfield);
		wp->SetText(buffer);
		wp->RefreshDisplay();
	}
	wp = (WndProperty*)wf->FindByName(TEXT("prpType"));
	if (wp) {
		_stprintf(buffer,_T("%s"),flarmId->type);
		wp->SetText(buffer);
		wp->RefreshDisplay();
	}
	wp = (WndProperty*)wf->FindByName(TEXT("prpFreq"));
	if (wp) {
		_stprintf(buffer,_T("%s"),flarmId->freq);
		wp->SetText(buffer);
		wp->RefreshDisplay();
	}


  }
		


}