KiCad PCB EDA Suite
util.h File Reference
#include <config.h>
#include <cstdint>
#include <limits>
#include <typeinfo>
#include <wx/debug.h>
#include <wx/log.h>

Go to the source code of this file.

Functions

template<typename T >
const T & Clamp (const T &lower, const T &value, const T &upper)
 Function Clamp limits value within the range lower <= value <= upper. More...
 
template<typename fp_type , typename ret_type = int>
constexpr ret_type KiROUND (fp_type v)
 Round a floating point number to an integer using "round halfway cases away from zero". More...
 
template<typename T >
rescale (T aNumerator, T aValue, T aDenominator)
 Function rescale() More...
 
template<typename T >
int sign (T val)
 
template<>
int rescale (int aNumerator, int aValue, int aDenominator)
 
template<>
int64_t rescale (int64_t aNumerator, int64_t aValue, int64_t aDenominator)
 

Function Documentation

◆ Clamp()

template<typename T >
const T& Clamp ( const T &  lower,
const T &  value,
const T &  upper 
)
inline

Function Clamp limits value within the range lower <= value <= upper.

It will work on temporary expressions, since they are evaluated only once, and it should work on most if not all numeric types, string types, or any type for which "operator < ()" is present. The arguments are accepted in this order so you can remember the expression as a memory aid:

result is: lower <= value <= upper

Definition at line 46 of file util.h.

47 {
48  wxASSERT( lower <= upper );
49  if( value < lower )
50  return lower;
51  else if( upper < value )
52  return upper;
53  return value;
54 }

Referenced by LSET::AllCuMask(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), SCH_SEXPR_PARSER::parseFill(), SCH_SEXPR_PARSER::parseJunction(), SCH_SEXPR_PARSER::parseStroke(), BRDITEMS_PLOTTER::plotOneDrillMark(), PCB_PLOT_PARAMS::SetSvgPrecision(), and DIALOG_PAGES_SETTINGS::UpdatePageLayoutExample().

◆ KiROUND()

template<typename fp_type , typename ret_type = int>
constexpr ret_type KiROUND ( fp_type  v)

Round a floating point number to an integer using "round halfway cases away from zero".

In Debug build an assert fires if will not fit into the return type.

Definition at line 68 of file util.h.

69 {
70  using max_ret = long long int;
71  fp_type ret = v < 0 ? v - 0.5 : v + 0.5;
72 
73  if( std::numeric_limits<ret_type>::max() < ret ||
74  std::numeric_limits<ret_type>::lowest() > ret )
75  {
76  wxLogDebug
77  ( "Overflow KiROUND converting value %f to %s", double( v ), typeid(ret_type).name() );
78  return 0;
79  }
80 
81  return ret_type( max_ret( ret ) );
82 }
const char * name
Definition: DXF_plotter.cpp:59

References name.

Referenced by CADSTAR_PCB_ARCHIVE_LOADER::addAttribute(), ZONE_FILLER::addHatchFillTypeOnZone(), PCAD2KICAD::PCB_POLYGON::AddToBoard(), GRID_HELPER::AlignGrid(), PCB_GRID_HELPER::AlignToArc(), PCB_GRID_HELPER::AlignToSegment(), EC_45DEGREE::Apply(), CADSTAR_PCB_ARCHIVE_LOADER::applyDimensionSettings(), CADSTAR_SCH_ARCHIVE_LOADER::applyTextSettings(), CADSTAR_SCH_ARCHIVE_LOADER::applyTransform(), HPGL_PLOTTER::Arc(), PLOTTER::Arc(), PDF_PLOTTER::Arc(), SCH_SHEET::AutoplaceFields(), PCB_GRID_HELPER::BestSnapAnchor(), LEGACY_PLUGIN::biuParse(), build_pad_testpoints(), BuildCornersList_S_Shape(), PAD::BuildEffectivePolygon(), DIRECTION_45::BuildInitialTrace(), ZONE_FILLER::buildThermalSpokes(), LIB_ARC::CalcEdit(), LIB_ARC::CalcMidPoint(), LIB_ARC::CalcRadiusAngles(), PCAD2KICAD::CalculateTextLengthSize(), KIGFX::WX_VIEW_CONTROLS::CenterOnCursor(), SHAPE_POLY_SET::chamferFilletPolygon(), EE_INSPECTION_TOOL::CheckSymbol(), Clamp_Text_PenSize(), ClipAndDrawPoly(), EE_SELECTION_TOOL::CollectHits(), SCH_LINE_WIRE_BUS_TOOL::computeBreakPoint(), computeCenter(), ConfigureHPGLPenSizes(), AM_PRIMITIVE::ConvertShapeToPolygon(), ALTIUM_PARSER::ConvertToKicadUnit(), SHAPE_ARC::ConvertToPolyline(), PCAD2KICAD::CorrectTextPosition(), FOOTPRINT::CoverageRatio(), MICROWAVE_TOOL::createFootprint(), MICROWAVE_TOOL::createMicrowaveInductor(), MICROWAVE_TOOL::createPolygonShape(), PL_EDIT_TOOL::DeleteItemCursor(), SCH_EDIT_TOOL::DeleteItemCursor(), PCB_CONTROL::DeleteItemCursor(), KIGFX::STROKE_FONT::Draw(), KIGFX::SCH_PAINTER::draw(), KIGFX::PCB_PAINTER::draw(), KIGFX::OPENGL_GAL::DrawArcSegment(), AM_PRIMITIVE::DrawBasicShape(), BITMAP_BASE::DrawBitmap(), CADSTAR_PCB_ARCHIVE_LOADER::drawCadstarText(), KIGFX::OPENGL_GAL::DrawGrid(), KIGFX::CAIRO_GAL_BASE::DrawGrid(), DRAWING_TOOL::DrawVia(), GERBER_PLOTTER::emitDcode(), PCB_EXPR_EVALUATOR::Evaluate(), GERBER_FILE_IMAGE::ExecuteRS274XCommand(), EDIT_POINTS::FindPoint(), HPGL_PLOTTER::FlashPadCircle(), HPGL_PLOTTER::FlashPadOval(), HPGL_PLOTTER::FlashPadRect(), HPGL_PLOTTER::FlashPadRoundRect(), PCB_TEXT::Flip(), WX_HTML_REPORT_BOX::Flush(), FootprintWriteShape(), BM2CMP_FRAME::FormatOutputSize(), formatStroke(), DSN::SPECCTRA_DB::FromSESSION(), gen_arc(), GENDRILL_WRITER_BASE::genDrillMapFile(), RENDER_3D_LEGACY::generate3dGrid(), geom_transf(), GERBER_DRAW_ITEM::GetABPosition(), GetArcCenter(), GetArcToSegmentCount(), LIB_PIN::GetBoundingBox(), FOOTPRINT::GetCoverageArea(), DIALOG_PAGES_SETTINGS::GetCustomSizeMilsFromDialog(), SCH_JUNCTION::getEffectiveShape(), WS_DATA_ITEM::GetEndPosUi(), GRID_HELPER::GetGrid(), KIGFX::GAL::GetGridPoint(), EDA_TEXT::GetInterline(), EDA_DRAW_FRAME::GetNearestGridPosition(), EE_SELECTION_TOOL::GetNode(), IMAGE_SIZE::GetOutputDPI(), GetPenSizeForBold(), GetPenSizeForNormal(), WS_DATA_ITEM::GetPenSizeUi(), WS_DATA_ITEM_POLYGONS::GetPenSizeUi(), WS_DATA_ITEM_TEXT::GetPenSizeUi(), LIB_CIRCLE::GetRadius(), PCB_SHAPE::GetRadius(), PCB_SHAPE::GetRectCorners(), PAD::GetRoundRectCornerRadius(), BITMAP_BASE::GetSize(), PAD::GetSolderPasteMargin(), WS_DATA_ITEM::GetStartPosUi(), EDA_TEXT::GetTextBox(), SCH_TEXT::GetTextOffset(), GERBER_DRAW_ITEM::GetXYPosition(), GraphicTextWidth(), GRArc1(), ZONE::HatchBorder(), ALTIUM_PCB::HelperCreateBoardOutline(), ALTIUM_PCB::HelperParseDimensions6Leader(), HelperShapeLineChainFromAltiumVertices(), LIB_CIRCLE::HitTest(), LIB_ARC::HitTest(), PCB_SHAPE::HitTest(), DIALOG_PLOT::init_Dialog(), initializePlotter(), GENERAL_COLLECTOR::Inspect(), TRACK::IsPointOnEnds(), iu_to_d356(), EDA_TEXT::LenSize(), EAGLE_PLUGIN::Load(), CADSTAR_SCH_ARCHIVE_LOADER::loadDocumentationSymbols(), CADSTAR_SCH_ARCHIVE_LOADER::loadGraphicStaightSegment(), SCH_EAGLE_PLUGIN::loadLabel(), EAGLE_PLUGIN::loadPlain(), EAGLE_PLUGIN::loadPolygon(), EAGLE_PLUGIN::loadSignals(), PCB_SELECTION_TOOL::Main(), DSN::SPECCTRA_DB::makeIMAGE(), DSN::SPECCTRA_DB::makePADSTACK(), TRANSFORM::MapAngles(), PLOTTER::markerSquare(), Mils2mm(), GERBVIEW_PRINTOUT::milsToIU(), PCBNEW_PRINTOUT::milsToIU(), Mm2mils(), ACTION_TOOLBAR::OnCustomRender(), DIALOG_POSITION_RELATIVE::OnOkClick(), BM2CMP_FRAME::OpenProjectFiles(), VECTOR2< unsigned int >::operator/(), EAGLE_PLUGIN::orientFPText(), EAGLE_PLUGIN::packagePad(), EAGLE_PLUGIN::packagePolygon(), EAGLE_PLUGIN::packageText(), DIALOG_PAD_PROPERTIES::padValuesOK(), PCAD2KICAD::PCB_ARC::Parse(), SCH_SEXPR_PARSER::parseArc(), ALTIUM_PCB::ParseArcs6Data(), PCB_PARSER::parseBoardUnits(), GPCB_FPL_CACHE::parseFOOTPRINT(), parseInt(), SCH_SEXPR_PARSER::parseInternalUnits(), GERBER_PLOTTER::plotArc(), BRDITEMS_PLOTTER::PlotFootprintGraphicItem(), PS_PLOTTER::PlotImage(), PDF_PLOTTER::PlotImage(), BRDITEMS_PLOTTER::PlotPcbShape(), GERBER_PLOTTER::plotRoundRectAsRegion(), PSLIKE_PLOTTER::postscriptOverlinePositions(), GERBER_DRAW_ITEM::Print(), FABMASTER::processArc(), FABMASTER::processFootprints(), FABMASTER::processLine(), FABMASTER::processPadStacks(), FABMASTER::processPins(), FABMASTER::processRectangle(), FABMASTER::processText(), FABMASTER::processVias(), GERBER_FILE_IMAGE::ReadIJCoord(), PARAM_CFG_INT_WITH_SCALE::ReadParam(), EXCELLON_IMAGE::readToolInformation(), GERBER_FILE_IMAGE::ReadXYCoord(), PANEL_SETUP_PINMAP::reBuildMatrixPanel(), VECTOR2< unsigned int >::Resize(), PSLIKE_PLOTTER::returnPostscriptTextWidth(), VECTOR2< unsigned int >::Rotate(), PCB_SHAPE::Rotate(), RotatePoint(), rotationFromString(), SCH_SEXPR_PLUGIN::saveJunction(), SCH_SEXPR_PLUGIN::saveSheet(), DSN::scale(), PCB_SHAPE::Scale(), scaletoIU(), PLOTTER::segmentAsOval(), SegmentIntersectsSegment(), PL_SELECTION_TOOL::SelectPoint(), WS_DATA_ITEM_TEXT::SetConstrainedTextSize(), PCAD2KICAD::SetTextSizeFromStrokeFontHeight(), PCAD2KICAD::SetTextSizeFromTrueTypeFontHeight(), SHAPE_ARC::SHAPE_ARC(), snapAngle(), PS_PLOTTER::StartPlot(), PCAD2KICAD::StrToInt1Units(), PCAD2KICAD::StrToIntUnits(), WS_DATA_ITEM_TEXT::SyncDrawItems(), AR_MATRIX::traceArc(), AR_MATRIX::traceCircle(), AR_MATRIX::TraceFilledRectangle(), PANEL_SETUP_BOARD_STACKUP::transferDataFromUIToStackup(), PANEL_EESCHEMA_DISPLAY_OPTIONS::TransferDataFromWindow(), DIALOG_LIB_SYMBOL_PROPERTIES::TransferDataFromWindow(), DIALOG_MOVE_EXACT::TransferDataFromWindow(), DIALOG_PAD_PRIMITIVES_TRANSFORM::Transform(), TransformOvalToPolygon(), SHAPE_ARC::update_bbox(), DIALOG_DIMENSION_PROPERTIES::updateDimensionFromDialog(), ALIGNED_DIMENSION::updateGeometry(), ORTHOGONAL_DIMENSION::updateGeometry(), DIALOG_PAGES_SETTINGS::UpdatePageLayoutExample(), DIALOG_DRC::updateUI(), KIGFX::ORIGIN_VIEWITEM::ViewDraw(), and EXCELLON_WRITER::writeCoordinates().

◆ rescale() [1/3]

template<typename T >
T rescale ( aNumerator,
aValue,
aDenominator 
)

Function rescale()

Scales a number (value) by rational (numerator/denominator). Numerator must be <= denominator.

Definition at line 95 of file util.h.

96 {
97  return aNumerator * aValue / aDenominator;
98 }

Referenced by commonParallelProjection(), PNS::commonParallelProjection(), PAD::GetBestAnchorPosition(), SEG::Intersect(), SEG::LineProject(), SEG::NearestPoint(), SHAPE_LINE_CHAIN_BASE::PointInside(), processEdge(), PNS::MEANDER_SHAPE::reflect(), VECTOR2< unsigned int >::Resize(), and POLY_GRID_PARTITION::scanCell().

◆ rescale() [2/3]

template<>
int rescale ( int  aNumerator,
int  aValue,
int  aDenominator 
)

Definition at line 32 of file util.cpp.

33 {
34  int64_t numerator = (int64_t) aNumerator * (int64_t) aValue;
35 
36  // round to nearest
37  if( ( numerator < 0 ) ^ ( aDenominator < 0 ) )
38  return ( numerator - aDenominator / 2 ) / aDenominator;
39  else
40  return ( numerator + aDenominator / 2 ) / aDenominator;
41 
42 }

◆ rescale() [3/3]

template<>
int64_t rescale ( int64_t  aNumerator,
int64_t  aValue,
int64_t  aDenominator 
)

Definition at line 46 of file util.cpp.

47 {
48 #ifdef __SIZEOF_INT128__
49  __int128_t numerator = (__int128_t) aNumerator * (__int128_t) aValue;
50 
51  if( ( numerator < 0 ) ^ ( aDenominator < 0 ) )
52  return ( numerator - aDenominator / 2 ) / aDenominator;
53  else
54  return ( numerator + aDenominator / 2 ) / aDenominator;
55 #else
56  int64_t r = 0;
57  int64_t sign = ( ( aNumerator < 0 ) ? -1 : 1 ) * ( aDenominator < 0 ? -1 : 1 ) *
58  ( aValue < 0 ? -1 : 1 );
59 
60  int64_t a = std::abs( aNumerator );
61  int64_t b = std::abs( aValue );
62  int64_t c = std::abs( aDenominator );
63 
64  r = c / 2;
65 
66  if( b <= INT_MAX && c <= INT_MAX )
67  {
68  if( a <= INT_MAX )
69  return sign * ( ( a * b + r ) / c );
70  else
71  return sign * ( a / c * b + ( a % c * b + r ) / c);
72  }
73  else
74  {
75  uint64_t a0 = a & 0xFFFFFFFF;
76  uint64_t a1 = a >> 32;
77  uint64_t b0 = b & 0xFFFFFFFF;
78  uint64_t b1 = b >> 32;
79  uint64_t t1 = a0 * b1 + a1 * b0;
80  uint64_t t1a = t1 << 32;
81  int i;
82 
83  a0 = a0 * b0 + t1a;
84  a1 = a1 * b1 + ( t1 >> 32 ) + ( a0 < t1a );
85  a0 += r;
86  a1 += a0 < (uint64_t)r;
87 
88  for( i = 63; i >= 0; i-- )
89  {
90  a1 += a1 + ( ( a0 >> i ) & 1 );
91  t1 += t1;
92 
93  if( (uint64_t) c <= a1 )
94  {
95  a1 -= c;
96  t1++;
97  }
98  }
99 
100  return t1 * sign;
101  }
102 #endif
103 }
int sign(T val)
Definition: util.h:101

References sign().

◆ sign()