You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2548 lines
81 KiB

13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
13 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  5. * Copyright (C) 2012-2020 KiCad Developers, see AUTHORS.txt for contributors.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License
  9. * as published by the Free Software Foundation; either version 2
  10. * of the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, you may find one here:
  19. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  20. * or you may search the http://www.gnu.org website for the version 2 license,
  21. * or you may write to the Free Software Foundation, Inc.,
  22. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  23. */
  24. /*
  25. Pcbnew PLUGIN for Eagle 6.x XML *.brd and footprint format.
  26. XML parsing and converting:
  27. Getting line numbers and byte offsets from the source XML file is not
  28. possible using currently available XML libraries within KiCad project:
  29. wxXmlDocument and boost::property_tree.
  30. property_tree will give line numbers but no byte offsets, and only during
  31. document loading. This means that if we have a problem after the document is
  32. successfully loaded, there is no way to correlate back to line number and byte
  33. offset of the problem. So a different approach is taken, one which relies on the
  34. XML elements themselves using an XPATH type of reporting mechanism. The path to
  35. the problem is reported in the error messages. This means keeping track of that
  36. path as we traverse the XML document for the sole purpose of accurate error
  37. reporting.
  38. User can load the source XML file into firefox or other xml browser and follow
  39. our error message.
  40. Load() TODO's
  41. *) verify zone fill clearances are correct
  42. */
  43. #include <cerrno>
  44. #include <wx/string.h>
  45. #include <wx/xml/xml.h>
  46. #include <common.h>
  47. #include <convert_basic_shapes_to_polygon.h>
  48. #include <fctsys.h>
  49. #include <geometry/geometry_utils.h>
  50. #include <kicad_string.h>
  51. #include <macros.h>
  52. #include <properties.h>
  53. #include <trigo.h>
  54. #include <wx/filename.h>
  55. #include <math/util.h> // for KiROUND
  56. #include <class_board.h>
  57. #include <class_module.h>
  58. #include <class_track.h>
  59. #include <class_edge_mod.h>
  60. #include <class_zone.h>
  61. #include <class_pcb_text.h>
  62. #include <class_dimension.h>
  63. #include <eagle_plugin.h>
  64. using namespace std;
  65. typedef MODULE_MAP::iterator MODULE_ITER;
  66. typedef MODULE_MAP::const_iterator MODULE_CITER;
  67. /// Parse an eagle distance which is either mm, or mils if there is "mil" suffix.
  68. /// Return is in BIU.
  69. static int parseEagle( const wxString& aDistance )
  70. {
  71. ECOORD::EAGLE_UNIT unit = ( aDistance.npos != aDistance.find( "mil" ) )
  72. ? ECOORD::EAGLE_UNIT::EU_MIL : ECOORD::EAGLE_UNIT::EU_MM;
  73. ECOORD coord( aDistance, unit );
  74. return coord.ToPcbUnits();
  75. }
  76. // In Eagle one can specify DRC rules where min value > max value,
  77. // in such case the max value has the priority
  78. template<typename T>
  79. static T eagleClamp( T aMin, T aValue, T aMax )
  80. {
  81. T ret = std::max( aMin, aValue );
  82. return std::min( aMax, ret );
  83. }
  84. /// Assemble a two part key as a simple concatenation of aFirst and aSecond parts,
  85. /// using a separator.
  86. static wxString makeKey( const wxString& aFirst, const wxString& aSecond )
  87. {
  88. wxString key = aFirst + '\x02' + aSecond;
  89. return key;
  90. }
  91. void ERULES::parse( wxXmlNode* aRules )
  92. {
  93. wxXmlNode* child = aRules->GetChildren();
  94. while( child )
  95. {
  96. if( child->GetName() == "param" )
  97. {
  98. const wxString& name = child->GetAttribute( "name" );
  99. const wxString& value = child->GetAttribute( "value" );
  100. if( name == "psElongationLong" )
  101. psElongationLong = wxAtoi( value );
  102. else if( name == "psElongationOffset" )
  103. psElongationOffset = wxAtoi( value );
  104. else if( name == "mvStopFrame" )
  105. value.ToDouble( &mvStopFrame );
  106. else if( name == "mvCreamFrame" )
  107. value.ToDouble( &mvCreamFrame );
  108. else if( name == "mlMinStopFrame" )
  109. mlMinStopFrame = parseEagle( value );
  110. else if( name == "mlMaxStopFrame" )
  111. mlMaxStopFrame = parseEagle( value );
  112. else if( name == "mlMinCreamFrame" )
  113. mlMinCreamFrame = parseEagle( value );
  114. else if( name == "mlMaxCreamFrame" )
  115. mlMaxCreamFrame = parseEagle( value );
  116. else if( name == "srRoundness" )
  117. value.ToDouble( &srRoundness );
  118. else if( name == "srMinRoundness" )
  119. srMinRoundness = parseEagle( value );
  120. else if( name == "srMaxRoundness" )
  121. srMaxRoundness = parseEagle( value );
  122. else if( name == "psTop" )
  123. psTop = wxAtoi( value );
  124. else if( name == "psBottom" )
  125. psBottom = wxAtoi( value );
  126. else if( name == "psFirst" )
  127. psFirst = wxAtoi( value );
  128. else if( name == "rvPadTop" )
  129. value.ToDouble( &rvPadTop );
  130. else if( name == "rlMinPadTop" )
  131. rlMinPadTop = parseEagle( value );
  132. else if( name == "rlMaxPadTop" )
  133. rlMaxPadTop = parseEagle( value );
  134. else if( name == "rvViaOuter" )
  135. value.ToDouble( &rvViaOuter );
  136. else if( name == "rlMinViaOuter" )
  137. rlMinViaOuter = parseEagle( value );
  138. else if( name == "rlMaxViaOuter" )
  139. rlMaxViaOuter = parseEagle( value );
  140. else if( name == "mdWireWire" )
  141. mdWireWire = parseEagle( value );
  142. }
  143. child = child->GetNext();
  144. }
  145. }
  146. EAGLE_PLUGIN::EAGLE_PLUGIN() :
  147. m_rules( new ERULES() ),
  148. m_xpath( new XPATH() ),
  149. m_mod_time( wxDateTime::Now() )
  150. {
  151. init( NULL );
  152. clear_cu_map();
  153. }
  154. EAGLE_PLUGIN::~EAGLE_PLUGIN()
  155. {
  156. deleteTemplates();
  157. delete m_rules;
  158. delete m_xpath;
  159. }
  160. const wxString EAGLE_PLUGIN::PluginName() const
  161. {
  162. return wxT( "Eagle" );
  163. }
  164. const wxString EAGLE_PLUGIN::GetFileExtension() const
  165. {
  166. return wxT( "brd" );
  167. }
  168. wxSize inline EAGLE_PLUGIN::kicad_fontz( const ECOORD& d ) const
  169. {
  170. // texts seem to better match eagle when scaled down by 0.95
  171. int kz = d.ToPcbUnits() * 95 / 100;
  172. return wxSize( kz, kz );
  173. }
  174. BOARD* EAGLE_PLUGIN::Load( const wxString& aFileName, BOARD* aAppendToMe, const PROPERTIES* aProperties )
  175. {
  176. LOCALE_IO toggle; // toggles on, then off, the C locale.
  177. wxXmlNode* doc;
  178. init( aProperties );
  179. m_board = aAppendToMe ? aAppendToMe : new BOARD();
  180. // Give the filename to the board if it's new
  181. if( !aAppendToMe )
  182. m_board->SetFileName( aFileName );
  183. // delete on exception, if I own m_board, according to aAppendToMe
  184. unique_ptr<BOARD> deleter( aAppendToMe ? NULL : m_board );
  185. try
  186. {
  187. // Load the document
  188. wxXmlDocument xmlDocument;
  189. wxFileName fn = aFileName;
  190. if( !xmlDocument.Load( fn.GetFullPath() ) )
  191. THROW_IO_ERROR( wxString::Format( _( "Unable to read file \"%s\"" ),
  192. fn.GetFullPath() ) );
  193. doc = xmlDocument.GetRoot();
  194. m_min_trace = INT_MAX;
  195. m_min_hole = INT_MAX;
  196. m_min_via = INT_MAX;
  197. loadAllSections( doc );
  198. BOARD_DESIGN_SETTINGS& designSettings = m_board->GetDesignSettings();
  199. if( m_min_trace < designSettings.m_TrackMinWidth )
  200. designSettings.m_TrackMinWidth = m_min_trace;
  201. if( m_min_via < designSettings.m_ViasMinSize )
  202. designSettings.m_ViasMinSize = m_min_via;
  203. if( m_min_hole < designSettings.m_MinThroughDrill )
  204. designSettings.m_MinThroughDrill = m_min_hole;
  205. if( m_rules->mdWireWire )
  206. {
  207. NETCLASSPTR defaultNetclass = designSettings.GetDefault();
  208. int clearance = KiROUND( m_rules->mdWireWire );
  209. if( clearance < defaultNetclass->GetClearance() )
  210. defaultNetclass->SetClearance( clearance );
  211. }
  212. // should be empty, else missing m_xpath->pop()
  213. wxASSERT( m_xpath->Contents().size() == 0 );
  214. }
  215. // Catch all exceptions thrown from the parser.
  216. catch( const XML_PARSER_ERROR &exc )
  217. {
  218. wxString errmsg = exc.what();
  219. errmsg += "\n@ ";
  220. errmsg += m_xpath->Contents();
  221. THROW_IO_ERROR( errmsg );
  222. }
  223. // IO_ERROR exceptions are left uncaught, they pass upwards from here.
  224. // Ensure the copper layers count is a multiple of 2
  225. // Pcbnew does not like boards with odd layers count
  226. // (these boards cannot exist. they actually have a even layers count)
  227. int lyrcnt = m_board->GetCopperLayerCount();
  228. if( (lyrcnt % 2) != 0 )
  229. {
  230. lyrcnt++;
  231. m_board->SetCopperLayerCount( lyrcnt );
  232. }
  233. centerBoard();
  234. deleter.release();
  235. return m_board;
  236. }
  237. void EAGLE_PLUGIN::init( const PROPERTIES* aProperties )
  238. {
  239. m_hole_count = 0;
  240. m_min_trace = 0;
  241. m_min_hole = 0;
  242. m_min_via = 0;
  243. m_xpath->clear();
  244. m_pads_to_nets.clear();
  245. m_board = NULL;
  246. m_props = aProperties;
  247. delete m_rules;
  248. m_rules = new ERULES();
  249. }
  250. void EAGLE_PLUGIN::clear_cu_map()
  251. {
  252. // All cu layers are invalid until we see them in the <layers> section while
  253. // loading either a board or library. See loadLayerDefs().
  254. for( unsigned i = 0; i < arrayDim(m_cu_map); ++i )
  255. m_cu_map[i] = -1;
  256. }
  257. void EAGLE_PLUGIN::loadAllSections( wxXmlNode* aDoc )
  258. {
  259. wxXmlNode* drawing = MapChildren( aDoc )["drawing"];
  260. NODE_MAP drawingChildren = MapChildren( drawing );
  261. wxXmlNode* board = drawingChildren["board"];
  262. NODE_MAP boardChildren = MapChildren( board );
  263. m_xpath->push( "eagle.drawing" );
  264. {
  265. m_xpath->push( "board" );
  266. wxXmlNode* designrules = boardChildren["designrules"];
  267. loadDesignRules( designrules );
  268. m_xpath->pop();
  269. }
  270. {
  271. m_xpath->push( "layers" );
  272. wxXmlNode* layers = drawingChildren["layers"];
  273. loadLayerDefs( layers );
  274. m_xpath->pop();
  275. }
  276. {
  277. m_xpath->push( "board" );
  278. wxXmlNode* plain = boardChildren["plain"];
  279. loadPlain( plain );
  280. wxXmlNode* signals = boardChildren["signals"];
  281. loadSignals( signals );
  282. wxXmlNode* libs = boardChildren["libraries"];
  283. loadLibraries( libs );
  284. wxXmlNode* elems = boardChildren["elements"];
  285. loadElements( elems );
  286. m_xpath->pop(); // "board"
  287. }
  288. m_xpath->pop(); // "eagle.drawing"
  289. }
  290. void EAGLE_PLUGIN::loadDesignRules( wxXmlNode* aDesignRules )
  291. {
  292. if( aDesignRules )
  293. {
  294. m_xpath->push( "designrules" );
  295. m_rules->parse( aDesignRules );
  296. m_xpath->pop(); // "designrules"
  297. }
  298. }
  299. void EAGLE_PLUGIN::loadLayerDefs( wxXmlNode* aLayers )
  300. {
  301. if( !aLayers )
  302. return;
  303. ELAYERS cu; // copper layers
  304. // Get the first layer and iterate
  305. wxXmlNode* layerNode = aLayers->GetChildren();
  306. m_eagleLayers.clear();
  307. while( layerNode )
  308. {
  309. ELAYER elayer( layerNode );
  310. m_eagleLayers.insert( std::make_pair( elayer.number, elayer ) );
  311. // find the subset of layers that are copper and active
  312. if( elayer.number >= 1 && elayer.number <= 16 && ( !elayer.active || *elayer.active ) )
  313. {
  314. cu.push_back( elayer );
  315. }
  316. layerNode = layerNode->GetNext();
  317. }
  318. // establish cu layer map:
  319. int ki_layer_count = 0;
  320. for( EITER it = cu.begin(); it != cu.end(); ++it, ++ki_layer_count )
  321. {
  322. if( ki_layer_count == 0 )
  323. m_cu_map[it->number] = F_Cu;
  324. else if( ki_layer_count == int( cu.size()-1 ) )
  325. m_cu_map[it->number] = B_Cu;
  326. else
  327. {
  328. // some eagle boards do not have contiguous layer number sequences.
  329. #if 0 // pre PCB_LAYER_ID & LSET:
  330. m_cu_map[it->number] = cu.size() - 1 - ki_layer_count;
  331. #else
  332. m_cu_map[it->number] = ki_layer_count;
  333. #endif
  334. }
  335. }
  336. #if 0 && defined(DEBUG)
  337. printf( "m_cu_map:\n" );
  338. for( unsigned i=0; i<arrayDim(m_cu_map); ++i )
  339. {
  340. printf( "\t[%d]:%d\n", i, m_cu_map[i] );
  341. }
  342. #endif
  343. // Set the layer names and cu count if we're loading a board.
  344. if( m_board )
  345. {
  346. m_board->SetCopperLayerCount( cu.size() );
  347. for( EITER it = cu.begin(); it != cu.end(); ++it )
  348. {
  349. PCB_LAYER_ID layer = kicad_layer( it->number );
  350. // these function provide their own protection against UNDEFINED_LAYER:
  351. m_board->SetLayerName( layer, FROM_UTF8( it->name.c_str() ) );
  352. m_board->SetLayerType( layer, LT_SIGNAL );
  353. // could map the colors here
  354. }
  355. }
  356. }
  357. #define DIMENSION_PRECISION 1 // 0.001 mm
  358. void EAGLE_PLUGIN::loadPlain( wxXmlNode* aGraphics )
  359. {
  360. if( !aGraphics )
  361. return;
  362. m_xpath->push( "plain" );
  363. // Get the first graphic and iterate
  364. wxXmlNode* gr = aGraphics->GetChildren();
  365. // (polygon | wire | text | circle | rectangle | frame | hole)*
  366. while( gr )
  367. {
  368. wxString grName = gr->GetName();
  369. if( grName == "wire" )
  370. {
  371. m_xpath->push( "wire" );
  372. EWIRE w( gr );
  373. PCB_LAYER_ID layer = kicad_layer( w.layer );
  374. wxPoint start( kicad_x( w.x1 ), kicad_y( w.y1 ) );
  375. wxPoint end( kicad_x( w.x2 ), kicad_y( w.y2 ) );
  376. if( layer != UNDEFINED_LAYER )
  377. {
  378. DRAWSEGMENT* dseg = new DRAWSEGMENT( m_board );
  379. int width = w.width.ToPcbUnits();
  380. // KiCad cannot handle zero or negative line widths
  381. if( width <= 0 )
  382. width = m_board->GetDesignSettings().GetLineThickness( layer );
  383. m_board->Add( dseg, ADD_MODE::APPEND );
  384. if( !w.curve )
  385. {
  386. dseg->SetStart( start );
  387. dseg->SetEnd( end );
  388. }
  389. else
  390. {
  391. wxPoint center = ConvertArcCenter( start, end, *w.curve );
  392. dseg->SetShape( S_ARC );
  393. dseg->SetStart( center );
  394. dseg->SetEnd( start );
  395. dseg->SetAngle( *w.curve * -10.0 ); // KiCad rotates the other way
  396. }
  397. dseg->SetLayer( layer );
  398. dseg->SetWidth( width );
  399. }
  400. m_xpath->pop();
  401. }
  402. else if( grName == "text" )
  403. {
  404. m_xpath->push( "text" );
  405. ETEXT t( gr );
  406. PCB_LAYER_ID layer = kicad_layer( t.layer );
  407. if( layer != UNDEFINED_LAYER )
  408. {
  409. TEXTE_PCB* pcbtxt = new TEXTE_PCB( m_board );
  410. m_board->Add( pcbtxt, ADD_MODE::APPEND );
  411. pcbtxt->SetLayer( layer );
  412. pcbtxt->SetText( FROM_UTF8( t.text.c_str() ) );
  413. pcbtxt->SetTextPos( wxPoint( kicad_x( t.x ), kicad_y( t.y ) ) );
  414. pcbtxt->SetTextSize( kicad_fontz( t.size ) );
  415. double ratio = t.ratio ? *t.ratio : 8; // DTD says 8 is default
  416. pcbtxt->SetTextThickness( KiROUND( t.size.ToPcbUnits() * ratio / 100 ));
  417. int align = t.align ? *t.align : ETEXT::BOTTOM_LEFT;
  418. if( t.rot )
  419. {
  420. int sign = t.rot->mirror ? -1 : 1;
  421. pcbtxt->SetMirrored( t.rot->mirror );
  422. double degrees = t.rot->degrees;
  423. if( degrees == 90 || t.rot->spin )
  424. pcbtxt->SetTextAngle( sign * t.rot->degrees * 10 );
  425. else if( degrees == 180 )
  426. align = ETEXT::TOP_RIGHT;
  427. else if( degrees == 270 )
  428. {
  429. pcbtxt->SetTextAngle( sign * 90 * 10 );
  430. align = ETEXT::TOP_RIGHT;
  431. }
  432. else // Ok so text is not at 90,180 or 270 so do some funny stuff to get placement right
  433. {
  434. if( ( degrees > 0 ) && ( degrees < 90 ) )
  435. pcbtxt->SetTextAngle( sign * t.rot->degrees * 10 );
  436. else if( ( degrees > 90 ) && ( degrees < 180 ) )
  437. {
  438. pcbtxt->SetTextAngle( sign * ( t.rot->degrees + 180 ) * 10 );
  439. align = ETEXT::TOP_RIGHT;
  440. }
  441. else if( ( degrees > 180 ) && ( degrees < 270 ) )
  442. {
  443. pcbtxt->SetTextAngle( sign * ( t.rot->degrees - 180 ) * 10 );
  444. align = ETEXT::TOP_RIGHT;
  445. }
  446. else if( ( degrees > 270 ) && ( degrees < 360 ) )
  447. {
  448. pcbtxt->SetTextAngle( sign * t.rot->degrees * 10 );
  449. align = ETEXT::BOTTOM_LEFT;
  450. }
  451. }
  452. }
  453. switch( align )
  454. {
  455. case ETEXT::CENTER:
  456. // this was the default in pcbtxt's constructor
  457. break;
  458. case ETEXT::CENTER_LEFT:
  459. pcbtxt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  460. break;
  461. case ETEXT::CENTER_RIGHT:
  462. pcbtxt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  463. break;
  464. case ETEXT::TOP_CENTER:
  465. pcbtxt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  466. break;
  467. case ETEXT::TOP_LEFT:
  468. pcbtxt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  469. pcbtxt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  470. break;
  471. case ETEXT::TOP_RIGHT:
  472. pcbtxt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  473. pcbtxt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  474. break;
  475. case ETEXT::BOTTOM_CENTER:
  476. pcbtxt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  477. break;
  478. case ETEXT::BOTTOM_LEFT:
  479. pcbtxt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  480. pcbtxt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  481. break;
  482. case ETEXT::BOTTOM_RIGHT:
  483. pcbtxt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  484. pcbtxt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  485. break;
  486. }
  487. }
  488. m_xpath->pop();
  489. }
  490. else if( grName == "circle" )
  491. {
  492. m_xpath->push( "circle" );
  493. ECIRCLE c( gr );
  494. PCB_LAYER_ID layer = kicad_layer( c.layer );
  495. if( layer != UNDEFINED_LAYER ) // unsupported layer
  496. {
  497. DRAWSEGMENT* dseg = new DRAWSEGMENT( m_board );
  498. m_board->Add( dseg, ADD_MODE::APPEND );
  499. int width = c.width.ToPcbUnits();
  500. int radius = c.radius.ToPcbUnits();
  501. // with == 0 means filled circle
  502. if( width <= 0 )
  503. {
  504. width = radius;
  505. radius = radius / 2;
  506. }
  507. dseg->SetShape( S_CIRCLE );
  508. dseg->SetLayer( layer );
  509. dseg->SetStart( wxPoint( kicad_x( c.x ), kicad_y( c.y ) ) );
  510. dseg->SetEnd( wxPoint( kicad_x( c.x ) + radius, kicad_y( c.y ) ) );
  511. dseg->SetWidth( width );
  512. }
  513. m_xpath->pop();
  514. }
  515. else if( grName == "rectangle" )
  516. {
  517. // This seems to be a simplified rectangular [copper] zone, cannot find any
  518. // net related info on it from the DTD.
  519. m_xpath->push( "rectangle" );
  520. ERECT r( gr );
  521. PCB_LAYER_ID layer = kicad_layer( r.layer );
  522. if( IsCopperLayer( layer ) )
  523. {
  524. // use a "netcode = 0" type ZONE:
  525. ZONE_CONTAINER* zone = new ZONE_CONTAINER( m_board );
  526. m_board->Add( zone, ADD_MODE::APPEND );
  527. zone->SetLayer( layer );
  528. zone->SetNetCode( NETINFO_LIST::UNCONNECTED );
  529. ZONE_HATCH_STYLE outline_hatch = ZONE_HATCH_STYLE::DIAGONAL_EDGE;
  530. const int outlineIdx = -1; // this is the id of the copper zone main outline
  531. zone->AppendCorner( wxPoint( kicad_x( r.x1 ), kicad_y( r.y1 ) ), outlineIdx );
  532. zone->AppendCorner( wxPoint( kicad_x( r.x2 ), kicad_y( r.y1 ) ), outlineIdx );
  533. zone->AppendCorner( wxPoint( kicad_x( r.x2 ), kicad_y( r.y2 ) ), outlineIdx );
  534. zone->AppendCorner( wxPoint( kicad_x( r.x1 ), kicad_y( r.y2 ) ), outlineIdx );
  535. if( r.rot )
  536. {
  537. zone->Rotate( zone->GetPosition(), r.rot->degrees * 10 );
  538. }
  539. // this is not my fault:
  540. zone->SetHatch( outline_hatch, ZONE_CONTAINER::GetDefaultHatchPitch(), true );
  541. }
  542. m_xpath->pop();
  543. }
  544. else if( grName == "hole" )
  545. {
  546. m_xpath->push( "hole" );
  547. // Fabricate a MODULE with a single PAD_ATTRIB_HOLE_NOT_PLATED pad.
  548. // Use m_hole_count to gen up a unique name.
  549. MODULE* module = new MODULE( m_board );
  550. m_board->Add( module, ADD_MODE::APPEND );
  551. module->SetReference( wxString::Format( "@HOLE%d", m_hole_count++ ) );
  552. module->Reference().SetVisible( false );
  553. packageHole( module, gr, true );
  554. m_xpath->pop();
  555. }
  556. else if( grName == "frame" )
  557. {
  558. // picture this
  559. }
  560. else if( grName == "polygon" )
  561. {
  562. m_xpath->push( "polygon" );
  563. loadPolygon( gr );
  564. m_xpath->pop(); // "polygon"
  565. }
  566. else if( grName == "dimension" )
  567. {
  568. EDIMENSION d( gr );
  569. PCB_LAYER_ID layer = kicad_layer( d.layer );
  570. if( layer != UNDEFINED_LAYER )
  571. {
  572. const BOARD_DESIGN_SETTINGS& designSettings = m_board->GetDesignSettings();
  573. DIMENSION* dimension = new DIMENSION( m_board );
  574. m_board->Add( dimension, ADD_MODE::APPEND );
  575. if( d.dimensionType )
  576. {
  577. // Eagle dimension graphic arms may have different lengths, but they look
  578. // incorrect in KiCad (the graphic is tilted). Make them even length in such case.
  579. if( *d.dimensionType == "horizontal" )
  580. {
  581. int newY = ( d.y1.ToPcbUnits() + d.y2.ToPcbUnits() ) / 2;
  582. d.y1 = ECOORD( newY, ECOORD::EAGLE_UNIT::EU_NM );
  583. d.y2 = ECOORD( newY, ECOORD::EAGLE_UNIT::EU_NM );
  584. }
  585. else if( *d.dimensionType == "vertical" )
  586. {
  587. int newX = ( d.x1.ToPcbUnits() + d.x2.ToPcbUnits() ) / 2;
  588. d.x1 = ECOORD( newX, ECOORD::EAGLE_UNIT::EU_NM );
  589. d.x2 = ECOORD( newX, ECOORD::EAGLE_UNIT::EU_NM );
  590. }
  591. }
  592. dimension->SetLayer( layer );
  593. // The origin and end are assumed to always be in this order from eagle
  594. dimension->SetOrigin( wxPoint( kicad_x( d.x1 ), kicad_y( d.y1 ) ),
  595. DIMENSION_PRECISION );
  596. dimension->SetEnd( wxPoint( kicad_x( d.x2 ), kicad_y( d.y2 ) ),
  597. DIMENSION_PRECISION );
  598. dimension->Text().SetTextSize( designSettings.GetTextSize( layer ) );
  599. dimension->Text().SetTextThickness( designSettings.GetTextThickness( layer ));
  600. dimension->SetWidth( designSettings.GetLineThickness( layer ) );
  601. dimension->SetUnits( EDA_UNITS::MILLIMETRES, false );
  602. // check which axis the dimension runs in
  603. // because the "height" of the dimension is perpendicular to that axis
  604. // Note the check is just if two axes are close enough to each other
  605. // Eagle appears to have some rounding errors
  606. if( abs( ( d.x1 - d.x2 ).ToPcbUnits() ) < 50000 ) // 50000 nm = 0.05 mm
  607. dimension->SetHeight( kicad_x( d.x3 - d.x1 ), DIMENSION_PRECISION );
  608. else
  609. dimension->SetHeight( kicad_y( d.y3 - d.y1 ), DIMENSION_PRECISION );
  610. dimension->AdjustDimensionDetails( DIMENSION_PRECISION );
  611. }
  612. }
  613. // Get next graphic
  614. gr = gr->GetNext();
  615. }
  616. m_xpath->pop();
  617. }
  618. void EAGLE_PLUGIN::loadLibrary( wxXmlNode* aLib, const wxString* aLibName )
  619. {
  620. if( !aLib )
  621. return;
  622. // library will have <xmlattr> node, skip that and get the single packages node
  623. wxXmlNode* packages = MapChildren( aLib )["packages"];
  624. if( !packages )
  625. return;
  626. m_xpath->push( "packages" );
  627. // Create a MODULE for all the eagle packages, for use later via a copy constructor
  628. // to instantiate needed MODULES in our BOARD. Save the MODULE templates in
  629. // a MODULE_MAP using a single lookup key consisting of libname+pkgname.
  630. // Get the first package and iterate
  631. wxXmlNode* package = packages->GetChildren();
  632. while( package )
  633. {
  634. m_xpath->push( "package", "name" );
  635. wxString pack_ref = package->GetAttribute( "name" );
  636. ReplaceIllegalFileNameChars( pack_ref, '_' );
  637. m_xpath->Value( pack_ref.ToUTF8() );
  638. wxString key = aLibName ? makeKey( *aLibName, pack_ref ) : pack_ref;
  639. MODULE* m = makeModule( package, pack_ref );
  640. // add the templating MODULE to the MODULE template factory "m_templates"
  641. std::pair<MODULE_ITER, bool> r = m_templates.insert( {key, m} );
  642. if( !r.second
  643. // && !( m_props && m_props->Value( "ignore_duplicates" ) )
  644. )
  645. {
  646. wxString lib = aLibName ? *aLibName : m_lib_path;
  647. const wxString& pkg = pack_ref;
  648. wxString emsg = wxString::Format(
  649. _( "<package> name: \"%s\" duplicated in eagle <library>: \"%s\"" ),
  650. GetChars( pkg ),
  651. GetChars( lib )
  652. );
  653. THROW_IO_ERROR( emsg );
  654. }
  655. m_xpath->pop();
  656. package = package->GetNext();
  657. }
  658. m_xpath->pop(); // "packages"
  659. }
  660. void EAGLE_PLUGIN::loadLibraries( wxXmlNode* aLibs )
  661. {
  662. if( !aLibs )
  663. return;
  664. m_xpath->push( "libraries.library", "name" );
  665. // Get the first library and iterate
  666. wxXmlNode* library = aLibs->GetChildren();
  667. while( library )
  668. {
  669. const wxString& lib_name = library->GetAttribute( "name" );
  670. m_xpath->Value( lib_name.c_str() );
  671. loadLibrary( library, &lib_name );
  672. library = library->GetNext();
  673. }
  674. m_xpath->pop();
  675. }
  676. void EAGLE_PLUGIN::loadElements( wxXmlNode* aElements )
  677. {
  678. if( !aElements )
  679. return;
  680. m_xpath->push( "elements.element", "name" );
  681. EATTR name;
  682. EATTR value;
  683. bool refanceNamePresetInPackageLayout;
  684. bool valueNamePresetInPackageLayout;
  685. // Get the first element and iterate
  686. wxXmlNode* element = aElements->GetChildren();
  687. while( element )
  688. {
  689. if( element->GetName() != "element" )
  690. {
  691. wxLogDebug( "expected: <element> read <%s>. Skip it", element->GetName() );
  692. // Get next item
  693. element = element->GetNext();
  694. continue;
  695. }
  696. EELEMENT e( element );
  697. // use "NULL-ness" as an indication of presence of the attribute:
  698. EATTR* nameAttr = nullptr;
  699. EATTR* valueAttr = nullptr;
  700. m_xpath->Value( e.name.c_str() );
  701. wxString pkg_key = makeKey( e.library, e.package );
  702. MODULE_CITER mi = m_templates.find( pkg_key );
  703. if( mi == m_templates.end() )
  704. {
  705. wxString emsg = wxString::Format( _( "No \"%s\" package in library \"%s\"" ),
  706. GetChars( FROM_UTF8( e.package.c_str() ) ),
  707. GetChars( FROM_UTF8( e.library.c_str() ) ) );
  708. THROW_IO_ERROR( emsg );
  709. }
  710. // copy constructor to clone the template
  711. MODULE* m = new MODULE( *mi->second );
  712. m_board->Add( m, ADD_MODE::APPEND );
  713. // update the nets within the pads of the clone
  714. for( auto pad : m->Pads() )
  715. {
  716. wxString pn_key = makeKey( e.name, pad->GetName() );
  717. NET_MAP_CITER ni = m_pads_to_nets.find( pn_key );
  718. if( ni != m_pads_to_nets.end() )
  719. {
  720. const ENET* enet = &ni->second;
  721. pad->SetNetCode( enet->netcode );
  722. }
  723. }
  724. refanceNamePresetInPackageLayout = true;
  725. valueNamePresetInPackageLayout = true;
  726. m->SetPosition( wxPoint( kicad_x( e.x ), kicad_y( e.y ) ) );
  727. // Is >NAME field set in package layout ?
  728. if( m->GetReference().size() == 0 )
  729. {
  730. m->Reference().SetVisible( false ); // No so no show
  731. refanceNamePresetInPackageLayout = false;
  732. }
  733. // Is >VALUE field set in package layout
  734. if( m->GetValue().size() == 0 )
  735. {
  736. m->Value().SetVisible( false ); // No so no show
  737. valueNamePresetInPackageLayout = false;
  738. }
  739. m->SetReference( FROM_UTF8( e.name.c_str() ) );
  740. m->SetValue( FROM_UTF8( e.value.c_str() ) );
  741. if( !e.smashed )
  742. { // Not smashed so show NAME & VALUE
  743. if( valueNamePresetInPackageLayout )
  744. m->Value().SetVisible( true ); // Only if place holder in package layout
  745. if( refanceNamePresetInPackageLayout )
  746. m->Reference().SetVisible( true ); // Only if place holder in package layout
  747. }
  748. else if( *e.smashed == true )
  749. { // Smashed so set default to no show for NAME and VALUE
  750. m->Value().SetVisible( false );
  751. m->Reference().SetVisible( false );
  752. // initialize these to default values in case the <attribute> elements are not present.
  753. m_xpath->push( "attribute", "name" );
  754. // VALUE and NAME can have something like our text "effects" overrides
  755. // in SWEET and new schematic. Eagle calls these XML elements "attribute".
  756. // There can be one for NAME and/or VALUE both. Features present in the
  757. // EATTR override the ones established in the package only if they are
  758. // present here (except for rot, which if not present means angle zero).
  759. // So the logic is a bit different than in packageText() and in plain text.
  760. // Get the first attribute and iterate
  761. wxXmlNode* attribute = element->GetChildren();
  762. while( attribute )
  763. {
  764. if( attribute->GetName() != "attribute" )
  765. {
  766. wxLogDebug( "expected: <attribute> read <%s>. Skip it", attribute->GetName() );
  767. attribute = attribute->GetNext();
  768. continue;
  769. }
  770. EATTR a( attribute );
  771. if( a.name == "NAME" )
  772. {
  773. name = a;
  774. nameAttr = &name;
  775. // do we have a display attribute ?
  776. if( a.display )
  777. {
  778. // Yes!
  779. switch( *a.display )
  780. {
  781. case EATTR::VALUE :
  782. {
  783. wxString reference = e.name;
  784. // EAGLE allows references to be single digits. This breaks KiCad netlisting, which requires
  785. // parts to have non-digit + digit annotation. If the reference begins with a number,
  786. // we prepend 'UNK' (unknown) for the symbol designator
  787. if( reference.find_first_not_of( "0123456789" ) == wxString::npos )
  788. reference.Prepend( "UNK" );
  789. nameAttr->name = reference;
  790. m->SetReference( reference );
  791. if( refanceNamePresetInPackageLayout )
  792. m->Reference().SetVisible( true );
  793. break;
  794. }
  795. case EATTR::NAME :
  796. if( refanceNamePresetInPackageLayout )
  797. {
  798. m->SetReference( "NAME" );
  799. m->Reference().SetVisible( true );
  800. }
  801. break;
  802. case EATTR::BOTH :
  803. if( refanceNamePresetInPackageLayout )
  804. m->Reference().SetVisible( true );
  805. nameAttr->name = nameAttr->name + " = " + e.name;
  806. m->SetReference( "NAME = " + e.name );
  807. break;
  808. case EATTR::Off :
  809. m->Reference().SetVisible( false );
  810. break;
  811. default:
  812. nameAttr->name = e.name;
  813. if( refanceNamePresetInPackageLayout )
  814. m->Reference().SetVisible( true );
  815. }
  816. }
  817. else
  818. // No display, so default is visible, and show value of NAME
  819. m->Reference().SetVisible( true );
  820. }
  821. else if( a.name == "VALUE" )
  822. {
  823. value = a;
  824. valueAttr = &value;
  825. if( a.display )
  826. {
  827. // Yes!
  828. switch( *a.display )
  829. {
  830. case EATTR::VALUE :
  831. valueAttr->value = opt_wxString( e.value );
  832. m->SetValue( e.value );
  833. if( valueNamePresetInPackageLayout )
  834. m->Value().SetVisible( true );
  835. break;
  836. case EATTR::NAME :
  837. if( valueNamePresetInPackageLayout )
  838. m->Value().SetVisible( true );
  839. m->SetValue( "VALUE" );
  840. break;
  841. case EATTR::BOTH :
  842. if( valueNamePresetInPackageLayout )
  843. m->Value().SetVisible( true );
  844. valueAttr->value = opt_wxString( "VALUE = " + e.value );
  845. m->SetValue( "VALUE = " + e.value );
  846. break;
  847. case EATTR::Off :
  848. m->Value().SetVisible( false );
  849. break;
  850. default:
  851. valueAttr->value = opt_wxString( e.value );
  852. if( valueNamePresetInPackageLayout )
  853. m->Value().SetVisible( true );
  854. }
  855. }
  856. else
  857. // No display, so default is visible, and show value of NAME
  858. m->Value().SetVisible( true );
  859. }
  860. attribute = attribute->GetNext();
  861. }
  862. m_xpath->pop(); // "attribute"
  863. }
  864. orientModuleAndText( m, e, nameAttr, valueAttr );
  865. // Set the local coordinates for the footprint text items
  866. m->Reference().SetLocalCoord();
  867. m->Value().SetLocalCoord();
  868. // Get next element
  869. element = element->GetNext();
  870. }
  871. m_xpath->pop(); // "elements.element"
  872. }
  873. ZONE_CONTAINER* EAGLE_PLUGIN::loadPolygon( wxXmlNode* aPolyNode )
  874. {
  875. EPOLYGON p( aPolyNode );
  876. PCB_LAYER_ID layer = kicad_layer( p.layer );
  877. ZONE_CONTAINER* zone = nullptr;
  878. bool keepout = ( p.layer == EAGLE_LAYER::TRESTRICT || p.layer == EAGLE_LAYER::BRESTRICT );
  879. if( !IsCopperLayer( layer ) && !keepout )
  880. return nullptr;
  881. // use a "netcode = 0" type ZONE:
  882. zone = new ZONE_CONTAINER( m_board );
  883. m_board->Add( zone, ADD_MODE::APPEND );
  884. if( p.layer == EAGLE_LAYER::TRESTRICT ) // front layer keepout
  885. zone->SetLayer( F_Cu );
  886. else if( p.layer == EAGLE_LAYER::BRESTRICT ) // bottom layer keepout
  887. zone->SetLayer( B_Cu );
  888. else
  889. zone->SetLayer( layer );
  890. if( keepout )
  891. {
  892. zone->SetIsKeepout( true );
  893. zone->SetDoNotAllowVias( true );
  894. zone->SetDoNotAllowTracks( true );
  895. zone->SetDoNotAllowCopperPour( true );
  896. zone->SetDoNotAllowPads( true );
  897. zone->SetDoNotAllowFootprints( false );
  898. }
  899. // Get the first vertex and iterate
  900. wxXmlNode* vertex = aPolyNode->GetChildren();
  901. std::vector<EVERTEX> vertices;
  902. // Create a circular vector of vertices
  903. // The "curve" parameter indicates a curve from the current
  904. // to the next vertex, so we keep the first at the end as well
  905. // to allow the curve to link back
  906. while( vertex )
  907. {
  908. if( vertex->GetName() == "vertex" )
  909. vertices.emplace_back( vertex );
  910. vertex = vertex->GetNext();
  911. }
  912. vertices.push_back( vertices[0] );
  913. SHAPE_POLY_SET polygon;
  914. polygon.NewOutline();
  915. for( size_t i = 0; i < vertices.size() - 1; i++ )
  916. {
  917. EVERTEX v1 = vertices[i];
  918. // Append the corner
  919. polygon.Append( kicad_x( v1.x ), kicad_y( v1.y ) );
  920. if( v1.curve )
  921. {
  922. EVERTEX v2 = vertices[i + 1];
  923. wxPoint center = ConvertArcCenter(
  924. wxPoint( kicad_x( v1.x ), kicad_y( v1.y ) ),
  925. wxPoint( kicad_x( v2.x ), kicad_y( v2.y ) ), *v1.curve );
  926. double angle = DEG2RAD( *v1.curve );
  927. double end_angle = atan2( kicad_y( v2.y ) - center.y,
  928. kicad_x( v2.x ) - center.x );
  929. double radius = sqrt( pow( center.x - kicad_x( v1.x ), 2 )
  930. + pow( center.y - kicad_y( v1.y ), 2 ) );
  931. // If we are curving, we need at least 2 segments otherwise
  932. // delta_angle == angle
  933. double delta_angle = angle / std::max(
  934. 2, GetArcToSegmentCount( KiROUND( radius ),
  935. ARC_HIGH_DEF, *v1.curve ) - 1 );
  936. for( double a = end_angle + angle;
  937. fabs( a - end_angle ) > fabs( delta_angle );
  938. a -= delta_angle )
  939. {
  940. polygon.Append( KiROUND( radius * cos( a ) ) + center.x,
  941. KiROUND( radius * sin( a ) ) + center.y );
  942. }
  943. }
  944. }
  945. // Eagle traces the zone such that half of the pen width is outside the polygon.
  946. // We trace the zone such that the copper is completely inside.
  947. if( p.width.ToPcbUnits() > 0 )
  948. {
  949. polygon.Inflate( p.width.ToPcbUnits() / 2, 32, SHAPE_POLY_SET::ALLOW_ACUTE_CORNERS );
  950. polygon.Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
  951. }
  952. zone->AddPolygon( polygon.COutline( 0 ) );
  953. // If the pour is a cutout it needs to be set to a keepout
  954. if( p.pour == EPOLYGON::CUTOUT )
  955. {
  956. zone->SetIsKeepout( true );
  957. zone->SetDoNotAllowCopperPour( true );
  958. zone->SetHatchStyle( ZONE_HATCH_STYLE::NO_HATCH );
  959. }
  960. else if( p.pour == EPOLYGON::HATCH )
  961. {
  962. int spacing = p.spacing ? p.spacing->ToPcbUnits() : 50 * IU_PER_MILS;
  963. zone->SetFillMode( ZONE_FILL_MODE::HATCH_PATTERN );
  964. zone->SetHatchFillTypeThickness( p.width.ToPcbUnits() );
  965. zone->SetHatchFillTypeGap( spacing - p.width.ToPcbUnits() );
  966. zone->SetHatchFillTypeOrientation( 0 );
  967. }
  968. // We divide the thickness by half because we are tracing _inside_ the zone outline
  969. // This means the radius of curvature will be twice the size for an equivalent EAGLE zone
  970. zone->SetMinThickness(
  971. std::max<int>( ZONE_THICKNESS_MIN_VALUE_MIL * IU_PER_MILS, p.width.ToPcbUnits() / 2 ) );
  972. if( p.isolate )
  973. zone->SetZoneClearance( p.isolate->ToPcbUnits() );
  974. else
  975. zone->SetZoneClearance( 1 ); // @todo: set minimum clearance value based on board settings
  976. // missing == yes per DTD.
  977. bool thermals = !p.thermals || *p.thermals;
  978. zone->SetPadConnection( thermals ? ZONE_CONNECTION::THERMAL : ZONE_CONNECTION::FULL );
  979. if( thermals )
  980. {
  981. // FIXME: eagle calculates dimensions for thermal spokes
  982. // based on what the zone is connecting to.
  983. // (i.e. width of spoke is half of the smaller side of an smd pad)
  984. // This is a basic workaround
  985. zone->SetThermalReliefGap( p.width.ToPcbUnits() + 50000 ); // 50000nm == 0.05mm
  986. zone->SetThermalReliefCopperBridge( p.width.ToPcbUnits() + 50000 );
  987. }
  988. int rank = p.rank ? (p.max_priority - *p.rank) : p.max_priority;
  989. zone->SetPriority( rank );
  990. return zone;
  991. }
  992. void EAGLE_PLUGIN::orientModuleAndText( MODULE* m, const EELEMENT& e, const EATTR* nameAttr,
  993. const EATTR* valueAttr )
  994. {
  995. if( e.rot )
  996. {
  997. if( e.rot->mirror )
  998. {
  999. double orientation = e.rot->degrees + 180.0;
  1000. m->SetOrientation( orientation * 10 );
  1001. m->Flip( m->GetPosition(), false );
  1002. }
  1003. else
  1004. m->SetOrientation( e.rot->degrees * 10 );
  1005. }
  1006. orientModuleText( m, e, &m->Reference(), nameAttr );
  1007. orientModuleText( m, e, &m->Value(), valueAttr );
  1008. }
  1009. void EAGLE_PLUGIN::orientModuleText( MODULE* m, const EELEMENT& e,
  1010. TEXTE_MODULE* txt, const EATTR* aAttr )
  1011. {
  1012. // Smashed part ?
  1013. if( aAttr )
  1014. { // Yes
  1015. const EATTR& a = *aAttr;
  1016. if( a.value )
  1017. {
  1018. txt->SetText( FROM_UTF8( a.value->c_str() ) );
  1019. }
  1020. if( a.x && a.y ) // OPT
  1021. {
  1022. wxPoint pos( kicad_x( *a.x ), kicad_y( *a.y ) );
  1023. txt->SetTextPos( pos );
  1024. }
  1025. // Even though size and ratio are both optional, I am not seeing
  1026. // a case where ratio is present but size is not.
  1027. double ratio = 8;
  1028. wxSize fontz = txt->GetTextSize();
  1029. if( a.size )
  1030. {
  1031. fontz = kicad_fontz( *a.size );
  1032. txt->SetTextSize( fontz );
  1033. if( a.ratio )
  1034. ratio = *a.ratio;
  1035. }
  1036. txt->SetTextThickness( KiROUND( fontz.y * ratio / 100 ));
  1037. int align = ETEXT::BOTTOM_LEFT; // bottom-left is eagle default
  1038. if( a.align )
  1039. align = a.align;
  1040. // The "rot" in a EATTR seems to be assumed to be zero if it is not
  1041. // present, and this zero rotation becomes an override to the
  1042. // package's text field. If they did not want zero, they specify
  1043. // what they want explicitly.
  1044. double degrees = a.rot ? a.rot->degrees : 0;
  1045. double orient; // relative to parent
  1046. int sign = 1;
  1047. bool spin = false;
  1048. if( a.rot )
  1049. {
  1050. spin = a.rot->spin;
  1051. sign = a.rot->mirror ? -1 : 1;
  1052. txt->SetMirrored( a.rot->mirror );
  1053. }
  1054. if( degrees == 90 || degrees == 0 || spin )
  1055. {
  1056. orient = degrees - m->GetOrientation() / 10;
  1057. txt->SetTextAngle( sign * orient * 10 );
  1058. }
  1059. else if( degrees == 180 )
  1060. {
  1061. orient = 0 - m->GetOrientation() / 10;
  1062. txt->SetTextAngle( sign * orient * 10 );
  1063. align = -align;
  1064. }
  1065. else if( degrees == 270 )
  1066. {
  1067. orient = 90 - m->GetOrientation() / 10;
  1068. align = -align;
  1069. txt->SetTextAngle( sign * orient * 10 );
  1070. }
  1071. else
  1072. {
  1073. orient = 90 - degrees - m->GetOrientation() / 10;
  1074. txt->SetTextAngle( sign * orient * 10 );
  1075. }
  1076. switch( align )
  1077. {
  1078. case ETEXT::TOP_RIGHT:
  1079. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  1080. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1081. break;
  1082. case ETEXT::BOTTOM_LEFT:
  1083. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  1084. txt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  1085. break;
  1086. case ETEXT::TOP_LEFT:
  1087. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  1088. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1089. break;
  1090. case ETEXT::BOTTOM_RIGHT:
  1091. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  1092. txt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  1093. break;
  1094. case ETEXT::TOP_CENTER:
  1095. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_CENTER );
  1096. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1097. break;
  1098. case ETEXT::BOTTOM_CENTER:
  1099. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_CENTER );
  1100. txt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  1101. break;
  1102. default:
  1103. ;
  1104. }
  1105. }
  1106. else // Part is not smash so use Lib default for NAME/VALUE // the text is per the original package, sans <attribute>
  1107. {
  1108. double degrees = ( txt->GetTextAngle() + m->GetOrientation() ) / 10;
  1109. // @todo there are a few more cases than these to contend with:
  1110. if( (!txt->IsMirrored() && ( abs( degrees ) == 180 || abs( degrees ) == 270 ))
  1111. || ( txt->IsMirrored() && ( degrees == 360 ) ) )
  1112. {
  1113. // ETEXT::TOP_RIGHT:
  1114. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  1115. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1116. }
  1117. }
  1118. }
  1119. MODULE* EAGLE_PLUGIN::makeModule( wxXmlNode* aPackage, const wxString& aPkgName )
  1120. {
  1121. std::unique_ptr<MODULE> m( new MODULE( m_board ) );
  1122. LIB_ID fpID;
  1123. fpID.Parse( aPkgName, LIB_ID::ID_PCB, true );
  1124. m->SetFPID( fpID );
  1125. // Get the first package item and iterate
  1126. wxXmlNode* packageItem = aPackage->GetChildren();
  1127. while( packageItem )
  1128. {
  1129. const wxString& itemName = packageItem->GetName();
  1130. if( itemName == "description" )
  1131. m->SetDescription( FROM_UTF8( packageItem->GetNodeContent().c_str() ) );
  1132. else if( itemName == "wire" )
  1133. packageWire( m.get(), packageItem );
  1134. else if( itemName == "pad" )
  1135. packagePad( m.get(), packageItem );
  1136. else if( itemName == "text" )
  1137. packageText( m.get(), packageItem );
  1138. else if( itemName == "rectangle" )
  1139. packageRectangle( m.get(), packageItem );
  1140. else if( itemName == "polygon" )
  1141. packagePolygon( m.get(), packageItem );
  1142. else if( itemName == "circle" )
  1143. packageCircle( m.get(), packageItem );
  1144. else if( itemName == "hole" )
  1145. packageHole( m.get(), packageItem, false );
  1146. else if( itemName == "smd" )
  1147. packageSMD( m.get(), packageItem );
  1148. packageItem = packageItem->GetNext();
  1149. }
  1150. return m.release();
  1151. }
  1152. void EAGLE_PLUGIN::packageWire( MODULE* aModule, wxXmlNode* aTree ) const
  1153. {
  1154. EWIRE w( aTree );
  1155. PCB_LAYER_ID layer = kicad_layer( w.layer );
  1156. wxPoint start( kicad_x( w.x1 ), kicad_y( w.y1 ) );
  1157. wxPoint end( kicad_x( w.x2 ), kicad_y( w.y2 ) );
  1158. int width = w.width.ToPcbUnits();
  1159. // KiCad cannot handle zero or negative line widths which apparently have meaning in Eagle.
  1160. if( width <= 0 )
  1161. {
  1162. BOARD* board = aModule->GetBoard();
  1163. if( board )
  1164. {
  1165. width = board->GetDesignSettings().GetLineThickness( layer );
  1166. }
  1167. else
  1168. {
  1169. // When loading footprint libraries, there is no board so use the default KiCad
  1170. // line widths.
  1171. switch( layer )
  1172. {
  1173. case Edge_Cuts:
  1174. width = Millimeter2iu( DEFAULT_EDGE_WIDTH );
  1175. break;
  1176. case F_SilkS:
  1177. case B_SilkS:
  1178. width = Millimeter2iu( DEFAULT_SILK_LINE_WIDTH );
  1179. break;
  1180. case F_CrtYd:
  1181. case B_CrtYd:
  1182. width = Millimeter2iu( DEFAULT_COURTYARD_WIDTH );
  1183. break;
  1184. default:
  1185. width = Millimeter2iu( DEFAULT_LINE_WIDTH );
  1186. }
  1187. }
  1188. }
  1189. // FIXME: the cap attribute is ignored because KiCad can't create lines
  1190. // with flat ends.
  1191. EDGE_MODULE* dwg;
  1192. if( !w.curve )
  1193. {
  1194. dwg = new EDGE_MODULE( aModule, S_SEGMENT );
  1195. dwg->SetStart0( start );
  1196. dwg->SetEnd0( end );
  1197. }
  1198. else
  1199. {
  1200. dwg = new EDGE_MODULE( aModule, S_ARC );
  1201. wxPoint center = ConvertArcCenter( start, end, *w.curve );
  1202. dwg->SetStart0( center );
  1203. dwg->SetEnd0( start );
  1204. dwg->SetAngle( *w.curve * -10.0 ); // KiCad rotates the other way
  1205. }
  1206. dwg->SetLayer( layer );
  1207. dwg->SetWidth( width );
  1208. dwg->SetDrawCoord();
  1209. aModule->Add( dwg );
  1210. }
  1211. void EAGLE_PLUGIN::packagePad( MODULE* aModule, wxXmlNode* aTree )
  1212. {
  1213. // this is thru hole technology here, no SMDs
  1214. EPAD e( aTree );
  1215. int shape = EPAD::UNDEF;
  1216. int eagleDrillz = e.drill.ToPcbUnits();
  1217. D_PAD* pad = new D_PAD( aModule );
  1218. aModule->Add( pad );
  1219. transferPad( e, pad );
  1220. if( e.first && *e.first && m_rules->psFirst != EPAD::UNDEF )
  1221. shape = m_rules->psFirst;
  1222. else if( aModule->GetLayer() == F_Cu && m_rules->psTop != EPAD::UNDEF )
  1223. shape = m_rules->psTop;
  1224. else if( aModule->GetLayer() == B_Cu && m_rules->psBottom != EPAD::UNDEF )
  1225. shape = m_rules->psBottom;
  1226. pad->SetDrillSize( wxSize( eagleDrillz, eagleDrillz ) );
  1227. pad->SetLayerSet( LSET::AllCuMask() );
  1228. if( eagleDrillz < m_min_hole )
  1229. m_min_hole = eagleDrillz;
  1230. // Solder mask
  1231. if( !e.stop || *e.stop == true ) // enabled by default
  1232. pad->SetLayerSet( pad->GetLayerSet().set( B_Mask ).set( F_Mask ) );
  1233. if( shape == EPAD::ROUND || shape == EPAD::SQUARE || shape == EPAD::OCTAGON )
  1234. e.shape = shape;
  1235. if( e.shape )
  1236. {
  1237. switch( *e.shape )
  1238. {
  1239. case EPAD::ROUND:
  1240. pad->SetShape( PAD_SHAPE_CIRCLE );
  1241. break;
  1242. case EPAD::OCTAGON:
  1243. // no KiCad octagonal pad shape, use PAD_CIRCLE for now.
  1244. // pad->SetShape( PAD_OCTAGON );
  1245. wxASSERT( pad->GetShape() == PAD_SHAPE_CIRCLE ); // verify set in D_PAD constructor
  1246. pad->SetShape( PAD_SHAPE_CHAMFERED_RECT );
  1247. pad->SetChamferPositions( RECT_CHAMFER_ALL );
  1248. pad->SetChamferRectRatio( 0.25 );
  1249. break;
  1250. case EPAD::LONG:
  1251. pad->SetShape( PAD_SHAPE_OVAL );
  1252. break;
  1253. case EPAD::SQUARE:
  1254. pad->SetShape( PAD_SHAPE_RECT );
  1255. break;
  1256. case EPAD::OFFSET:
  1257. pad->SetShape( PAD_SHAPE_OVAL );
  1258. break;
  1259. }
  1260. }
  1261. else
  1262. {
  1263. // if shape is not present, our default is circle and that matches their default "round"
  1264. }
  1265. if( e.diameter )
  1266. {
  1267. int diameter = e.diameter->ToPcbUnits();
  1268. pad->SetSize( wxSize( diameter, diameter ) );
  1269. }
  1270. else
  1271. {
  1272. double drillz = pad->GetDrillSize().x;
  1273. double annulus = drillz * m_rules->rvPadTop; // copper annulus, eagle "restring"
  1274. annulus = eagleClamp( m_rules->rlMinPadTop, annulus, m_rules->rlMaxPadTop );
  1275. int diameter = KiROUND( drillz + 2 * annulus );
  1276. pad->SetSize( wxSize( KiROUND( diameter ), KiROUND( diameter ) ) );
  1277. }
  1278. if( pad->GetShape() == PAD_SHAPE_OVAL )
  1279. {
  1280. // The Eagle "long" pad is wider than it is tall,
  1281. // m_elongation is percent elongation
  1282. wxSize sz = pad->GetSize();
  1283. sz.x = ( sz.x * ( 100 + m_rules->psElongationLong ) ) / 100;
  1284. pad->SetSize( sz );
  1285. if( e.shape && *e.shape == EPAD::OFFSET )
  1286. {
  1287. int offset = KiROUND( ( sz.x - sz.y ) / 2.0 );
  1288. pad->SetOffset( wxPoint( offset, 0 ) );
  1289. }
  1290. }
  1291. if( e.rot )
  1292. {
  1293. pad->SetOrientation( e.rot->degrees * 10 );
  1294. }
  1295. }
  1296. void EAGLE_PLUGIN::packageText( MODULE* aModule, wxXmlNode* aTree ) const
  1297. {
  1298. ETEXT t( aTree );
  1299. PCB_LAYER_ID layer = kicad_layer( t.layer );
  1300. if( layer == UNDEFINED_LAYER )
  1301. layer = Cmts_User;
  1302. TEXTE_MODULE* txt;
  1303. if( t.text == ">NAME" || t.text == ">name" )
  1304. txt = &aModule->Reference();
  1305. else if( t.text == ">VALUE" || t.text == ">value" )
  1306. txt = &aModule->Value();
  1307. else
  1308. {
  1309. // FIXME: graphical text items are rotated for some reason.
  1310. txt = new TEXTE_MODULE( aModule );
  1311. aModule->Add( txt );
  1312. }
  1313. txt->SetText( FROM_UTF8( t.text.c_str() ) );
  1314. wxPoint pos( kicad_x( t.x ), kicad_y( t.y ) );
  1315. txt->SetTextPos( pos );
  1316. txt->SetPos0( pos - aModule->GetPosition() );
  1317. txt->SetLayer( layer );
  1318. txt->SetTextSize( kicad_fontz( t.size ) );
  1319. double ratio = t.ratio ? *t.ratio : 8; // DTD says 8 is default
  1320. txt->SetTextThickness( KiROUND( t.size.ToPcbUnits() * ratio / 100 ));
  1321. int align = t.align ? *t.align : ETEXT::BOTTOM_LEFT; // bottom-left is eagle default
  1322. // An eagle package is never rotated, the DTD does not allow it.
  1323. // angle -= aModule->GetOrienation();
  1324. if( t.rot )
  1325. {
  1326. int sign = t.rot->mirror ? -1 : 1;
  1327. txt->SetMirrored( t.rot->mirror );
  1328. double degrees = t.rot->degrees;
  1329. if( degrees == 90 || t.rot->spin )
  1330. txt->SetTextAngle( sign * degrees * 10 );
  1331. else if( degrees == 180 )
  1332. align = ETEXT::TOP_RIGHT;
  1333. else if( degrees == 270 )
  1334. {
  1335. align = ETEXT::TOP_RIGHT;
  1336. txt->SetTextAngle( sign * 90 * 10 );
  1337. }
  1338. }
  1339. switch( align )
  1340. {
  1341. case ETEXT::CENTER:
  1342. // this was the default in pcbtxt's constructor
  1343. break;
  1344. case ETEXT::CENTER_LEFT:
  1345. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  1346. break;
  1347. case ETEXT::CENTER_RIGHT:
  1348. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  1349. break;
  1350. case ETEXT::TOP_CENTER:
  1351. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1352. break;
  1353. case ETEXT::TOP_LEFT:
  1354. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  1355. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1356. break;
  1357. case ETEXT::TOP_RIGHT:
  1358. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  1359. txt->SetVertJustify( GR_TEXT_VJUSTIFY_TOP );
  1360. break;
  1361. case ETEXT::BOTTOM_CENTER:
  1362. txt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  1363. break;
  1364. case ETEXT::BOTTOM_LEFT:
  1365. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_LEFT );
  1366. txt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  1367. break;
  1368. case ETEXT::BOTTOM_RIGHT:
  1369. txt->SetHorizJustify( GR_TEXT_HJUSTIFY_RIGHT );
  1370. txt->SetVertJustify( GR_TEXT_VJUSTIFY_BOTTOM );
  1371. break;
  1372. }
  1373. }
  1374. void EAGLE_PLUGIN::packageRectangle( MODULE* aModule, wxXmlNode* aTree ) const
  1375. {
  1376. ERECT r( aTree );
  1377. PCB_LAYER_ID layer = kicad_layer( r.layer );
  1378. EDGE_MODULE* dwg = new EDGE_MODULE( aModule, S_POLYGON );
  1379. aModule->Add( dwg );
  1380. dwg->SetLayer( layer );
  1381. dwg->SetWidth( 0 );
  1382. std::vector<wxPoint> pts;
  1383. wxPoint start( wxPoint( kicad_x( r.x1 ), kicad_y( r.y1 ) ) );
  1384. wxPoint end( wxPoint( kicad_x( r.x1 ), kicad_y( r.y2 ) ) );
  1385. pts.push_back( start );
  1386. pts.emplace_back( kicad_x( r.x2 ), kicad_y( r.y1 ) );
  1387. pts.emplace_back( kicad_x( r.x2 ), kicad_y( r.y2 ) );
  1388. pts.push_back( end );
  1389. dwg->SetPolyPoints( pts );
  1390. dwg->SetStart0( start );
  1391. dwg->SetEnd0( end );
  1392. if( r.rot )
  1393. dwg->Rotate( dwg->GetCenter(), r.rot->degrees * 10 );
  1394. }
  1395. void EAGLE_PLUGIN::packagePolygon( MODULE* aModule, wxXmlNode* aTree ) const
  1396. {
  1397. EPOLYGON p( aTree );
  1398. PCB_LAYER_ID layer = kicad_layer( p.layer );
  1399. EDGE_MODULE* dwg = new EDGE_MODULE( aModule, S_POLYGON );
  1400. aModule->Add( dwg );
  1401. dwg->SetWidth( 0 ); // it's filled, no need for boundary width
  1402. dwg->SetLayer( layer );
  1403. std::vector<wxPoint> pts;
  1404. // Get the first vertex and iterate
  1405. wxXmlNode* vertex = aTree->GetChildren();
  1406. std::vector<EVERTEX> vertices;
  1407. // Create a circular vector of vertices
  1408. // The "curve" parameter indicates a curve from the current
  1409. // to the next vertex, so we keep the first at the end as well
  1410. // to allow the curve to link back
  1411. while( vertex )
  1412. {
  1413. if( vertex->GetName() == "vertex" )
  1414. vertices.emplace_back( vertex );
  1415. vertex = vertex->GetNext();
  1416. }
  1417. vertices.push_back( vertices[0] );
  1418. for( size_t i = 0; i < vertices.size() - 1; i++ )
  1419. {
  1420. EVERTEX v1 = vertices[i];
  1421. // Append the corner
  1422. pts.emplace_back( kicad_x( v1.x ), kicad_y( v1.y ) );
  1423. if( v1.curve )
  1424. {
  1425. EVERTEX v2 = vertices[i + 1];
  1426. wxPoint center = ConvertArcCenter(
  1427. wxPoint( kicad_x( v1.x ), kicad_y( v1.y ) ),
  1428. wxPoint( kicad_x( v2.x ), kicad_y( v2.y ) ), *v1.curve );
  1429. double angle = DEG2RAD( *v1.curve );
  1430. double end_angle = atan2( kicad_y( v2.y ) - center.y,
  1431. kicad_x( v2.x ) - center.x );
  1432. double radius = sqrt( pow( center.x - kicad_x( v1.x ), 2 )
  1433. + pow( center.y - kicad_y( v1.y ), 2 ) );
  1434. // Don't allow a zero-radius curve
  1435. if( KiROUND( radius ) == 0 )
  1436. radius = 1.0;
  1437. int segCount = GetArcToSegmentCount( KiROUND( radius ), ARC_HIGH_DEF, *v1.curve ) - 1;
  1438. // If we are curving, we need at least 2 segments otherwise delta == angle
  1439. if( segCount < 2 )
  1440. segCount = 2;
  1441. double delta = angle / segCount;
  1442. for( double a = end_angle + angle; fabs( a - end_angle ) > fabs( delta ); a -= delta )
  1443. {
  1444. pts.push_back(
  1445. wxPoint( KiROUND( radius * cos( a ) ),
  1446. KiROUND( radius * sin( a ) ) ) + center );
  1447. }
  1448. }
  1449. }
  1450. dwg->SetPolyPoints( pts );
  1451. dwg->SetStart0( *pts.begin() );
  1452. dwg->SetEnd0( pts.back() );
  1453. dwg->SetDrawCoord();
  1454. dwg->GetPolyShape().Inflate( p.width.ToPcbUnits() / 2, 32,
  1455. SHAPE_POLY_SET::ALLOW_ACUTE_CORNERS );
  1456. }
  1457. void EAGLE_PLUGIN::packageCircle( MODULE* aModule, wxXmlNode* aTree ) const
  1458. {
  1459. ECIRCLE e( aTree );
  1460. PCB_LAYER_ID layer = kicad_layer( e.layer );
  1461. EDGE_MODULE* gr = new EDGE_MODULE( aModule, S_CIRCLE );
  1462. int width = e.width.ToPcbUnits();
  1463. int radius = e.radius.ToPcbUnits();
  1464. // with == 0 means filled circle
  1465. if( width <= 0 )
  1466. {
  1467. width = radius;
  1468. radius = radius / 2;
  1469. }
  1470. aModule->Add( gr );
  1471. gr->SetWidth( width );
  1472. switch ( (int) layer )
  1473. {
  1474. case UNDEFINED_LAYER:
  1475. layer = Cmts_User;
  1476. break;
  1477. default:
  1478. break;
  1479. }
  1480. gr->SetLayer( layer );
  1481. gr->SetStart0( wxPoint( kicad_x( e.x ), kicad_y( e.y ) ) );
  1482. gr->SetEnd0( wxPoint( kicad_x( e.x ) + radius, kicad_y( e.y ) ) );
  1483. gr->SetDrawCoord();
  1484. }
  1485. void EAGLE_PLUGIN::packageHole( MODULE* aModule, wxXmlNode* aTree, bool aCenter ) const
  1486. {
  1487. EHOLE e( aTree );
  1488. // we add a PAD_ATTRIB_HOLE_NOT_PLATED pad to this module.
  1489. D_PAD* pad = new D_PAD( aModule );
  1490. aModule->Add( pad );
  1491. pad->SetShape( PAD_SHAPE_CIRCLE );
  1492. pad->SetAttribute( PAD_ATTRIB_HOLE_NOT_PLATED );
  1493. // Mechanical purpose only:
  1494. // no offset, no net name, no pad name allowed
  1495. // pad->SetOffset( wxPoint( 0, 0 ) );
  1496. // pad->SetName( wxEmptyString );
  1497. wxPoint padpos( kicad_x( e.x ), kicad_y( e.y ) );
  1498. if( aCenter )
  1499. {
  1500. pad->SetPos0( wxPoint( 0, 0 ) );
  1501. aModule->SetPosition( padpos );
  1502. pad->SetPosition( padpos );
  1503. }
  1504. else
  1505. {
  1506. pad->SetPos0( padpos );
  1507. pad->SetPosition( padpos + aModule->GetPosition() );
  1508. }
  1509. wxSize sz( e.drill.ToPcbUnits(), e.drill.ToPcbUnits() );
  1510. pad->SetDrillSize( sz );
  1511. pad->SetSize( sz );
  1512. pad->SetLayerSet( LSET::AllCuMask().set( B_Mask ).set( F_Mask ) );
  1513. }
  1514. void EAGLE_PLUGIN::packageSMD( MODULE* aModule, wxXmlNode* aTree ) const
  1515. {
  1516. ESMD e( aTree );
  1517. PCB_LAYER_ID layer = kicad_layer( e.layer );
  1518. if( !IsCopperLayer( layer ) )
  1519. return;
  1520. D_PAD* pad = new D_PAD( aModule );
  1521. aModule->Add( pad );
  1522. transferPad( e, pad );
  1523. pad->SetShape( PAD_SHAPE_RECT );
  1524. pad->SetAttribute( PAD_ATTRIB_SMD );
  1525. wxSize padSize( e.dx.ToPcbUnits(), e.dy.ToPcbUnits() );
  1526. pad->SetSize( padSize );
  1527. pad->SetLayer( layer );
  1528. const LSET front( 3, F_Cu, F_Paste, F_Mask );
  1529. const LSET back( 3, B_Cu, B_Paste, B_Mask );
  1530. if( layer == F_Cu )
  1531. pad->SetLayerSet( front );
  1532. else if( layer == B_Cu )
  1533. pad->SetLayerSet( back );
  1534. int minPadSize = std::min( padSize.x, padSize.y );
  1535. // Rounded rectangle pads
  1536. int roundRadius = eagleClamp( m_rules->srMinRoundness * 2,
  1537. (int)( minPadSize * m_rules->srRoundness ), m_rules->srMaxRoundness * 2 );
  1538. if( e.roundness || roundRadius > 0 )
  1539. {
  1540. double roundRatio = (double) roundRadius / minPadSize / 2.0;
  1541. // Eagle uses a different definition of roundness, hence division by 200
  1542. if( e.roundness )
  1543. roundRatio = std::fmax( *e.roundness / 200.0, roundRatio );
  1544. pad->SetShape( PAD_SHAPE_ROUNDRECT );
  1545. pad->SetRoundRectRadiusRatio( roundRatio );
  1546. }
  1547. if( e.rot )
  1548. pad->SetOrientation( e.rot->degrees * 10 );
  1549. pad->SetLocalSolderPasteMargin( -eagleClamp( m_rules->mlMinCreamFrame,
  1550. (int) ( m_rules->mvCreamFrame * minPadSize ),
  1551. m_rules->mlMaxCreamFrame ) );
  1552. // Solder mask
  1553. if( e.stop && *e.stop == false ) // enabled by default
  1554. {
  1555. if( layer == F_Cu )
  1556. pad->SetLayerSet( pad->GetLayerSet().set( F_Mask, false ) );
  1557. else if( layer == B_Cu )
  1558. pad->SetLayerSet( pad->GetLayerSet().set( B_Mask, false ) );
  1559. }
  1560. // Solder paste (only for SMD pads)
  1561. if( e.cream && *e.cream == false ) // enabled by default
  1562. {
  1563. if( layer == F_Cu )
  1564. pad->SetLayerSet( pad->GetLayerSet().set( F_Paste, false ) );
  1565. else if( layer == B_Cu )
  1566. pad->SetLayerSet( pad->GetLayerSet().set( B_Paste, false ) );
  1567. }
  1568. }
  1569. void EAGLE_PLUGIN::transferPad( const EPAD_COMMON& aEaglePad, D_PAD* aPad ) const
  1570. {
  1571. aPad->SetName( FROM_UTF8( aEaglePad.name.c_str() ) );
  1572. // pad's "Position" is not relative to the module's,
  1573. // whereas Pos0 is relative to the module's but is the unrotated coordinate.
  1574. wxPoint padPos( kicad_x( aEaglePad.x ), kicad_y( aEaglePad.y ) );
  1575. aPad->SetPos0( padPos );
  1576. // Solder mask
  1577. const wxSize& padSize( aPad->GetSize() );
  1578. aPad->SetLocalSolderMaskMargin( eagleClamp( m_rules->mlMinStopFrame,
  1579. (int)( m_rules->mvStopFrame * std::min( padSize.x, padSize.y ) ),
  1580. m_rules->mlMaxStopFrame ) );
  1581. // Solid connection to copper zones
  1582. if( aEaglePad.thermals && !*aEaglePad.thermals )
  1583. aPad->SetZoneConnection( ZONE_CONNECTION::FULL );
  1584. MODULE* module = aPad->GetParent();
  1585. wxCHECK( module, /* void */ );
  1586. RotatePoint( &padPos, module->GetOrientation() );
  1587. aPad->SetPosition( padPos + module->GetPosition() );
  1588. }
  1589. void EAGLE_PLUGIN::deleteTemplates()
  1590. {
  1591. for( auto& t : m_templates )
  1592. delete t.second;
  1593. m_templates.clear();
  1594. }
  1595. void EAGLE_PLUGIN::loadSignals( wxXmlNode* aSignals )
  1596. {
  1597. ZONES zones; // per net
  1598. m_xpath->push( "signals.signal", "name" );
  1599. int netCode = 1;
  1600. // Get the first signal and iterate
  1601. wxXmlNode* net = aSignals->GetChildren();
  1602. while( net )
  1603. {
  1604. bool sawPad = false;
  1605. zones.clear();
  1606. const wxString& netName = escapeName( net->GetAttribute( "name" ) );
  1607. m_board->Add( new NETINFO_ITEM( m_board, netName, netCode ) );
  1608. m_xpath->Value( netName.c_str() );
  1609. // Get the first net item and iterate
  1610. wxXmlNode* netItem = net->GetChildren();
  1611. // (contactref | polygon | wire | via)*
  1612. while( netItem )
  1613. {
  1614. const wxString& itemName = netItem->GetName();
  1615. if( itemName == "wire" )
  1616. {
  1617. m_xpath->push( "wire" );
  1618. EWIRE w( netItem );
  1619. PCB_LAYER_ID layer = kicad_layer( w.layer );
  1620. if( IsCopperLayer( layer ) )
  1621. {
  1622. wxPoint start( kicad_x( w.x1 ), kicad_y( w.y1 ) );
  1623. double angle = 0.0;
  1624. double end_angle = 0.0;
  1625. double radius = 0.0;
  1626. double delta_angle = 0.0;
  1627. wxPoint center;
  1628. int width = w.width.ToPcbUnits();
  1629. if( width < m_min_trace )
  1630. m_min_trace = width;
  1631. if( w.curve )
  1632. {
  1633. center = ConvertArcCenter(
  1634. wxPoint( kicad_x( w.x1 ), kicad_y( w.y1 ) ),
  1635. wxPoint( kicad_x( w.x2 ), kicad_y( w.y2 ) ),
  1636. *w.curve );
  1637. angle = DEG2RAD( *w.curve );
  1638. end_angle = atan2( kicad_y( w.y2 ) - center.y,
  1639. kicad_x( w.x2 ) - center.x );
  1640. radius = sqrt( pow( center.x - kicad_x( w.x1 ), 2 ) +
  1641. pow( center.y - kicad_y( w.y1 ), 2 ) );
  1642. // If we are curving, we need at least 2 segments otherwise
  1643. // delta_angle == angle
  1644. int segments = std::max( 2, GetArcToSegmentCount( KiROUND( radius ),
  1645. ARC_HIGH_DEF, *w.curve ) - 1 );
  1646. delta_angle = angle / segments;
  1647. }
  1648. while( fabs( angle ) > fabs( delta_angle ) )
  1649. {
  1650. wxASSERT( radius > 0.0 );
  1651. wxPoint end( KiROUND( radius * cos( end_angle + angle ) + center.x ),
  1652. KiROUND( radius * sin( end_angle + angle ) + center.y ) );
  1653. TRACK* t = new TRACK( m_board );
  1654. t->SetPosition( start );
  1655. t->SetEnd( end );
  1656. t->SetWidth( width );
  1657. t->SetLayer( layer );
  1658. t->SetNetCode( netCode );
  1659. m_board->Add( t );
  1660. start = end;
  1661. angle -= delta_angle;
  1662. }
  1663. TRACK* t = new TRACK( m_board );
  1664. t->SetPosition( start );
  1665. t->SetEnd( wxPoint( kicad_x( w.x2 ), kicad_y( w.y2 ) ) );
  1666. t->SetWidth( width );
  1667. t->SetLayer( layer );
  1668. t->SetNetCode( netCode );
  1669. m_board->Add( t );
  1670. }
  1671. else
  1672. {
  1673. // put non copper wires where the sun don't shine.
  1674. }
  1675. m_xpath->pop();
  1676. }
  1677. else if( itemName == "via" )
  1678. {
  1679. m_xpath->push( "via" );
  1680. EVIA v( netItem );
  1681. PCB_LAYER_ID layer_front_most = kicad_layer( v.layer_front_most );
  1682. PCB_LAYER_ID layer_back_most = kicad_layer( v.layer_back_most );
  1683. if( IsCopperLayer( layer_front_most ) &&
  1684. IsCopperLayer( layer_back_most ) )
  1685. {
  1686. int kidiam;
  1687. int drillz = v.drill.ToPcbUnits();
  1688. VIA* via = new VIA( m_board );
  1689. m_board->Add( via );
  1690. via->SetLayerPair( layer_front_most, layer_back_most );
  1691. if( v.diam )
  1692. {
  1693. kidiam = v.diam->ToPcbUnits();
  1694. via->SetWidth( kidiam );
  1695. }
  1696. else
  1697. {
  1698. double annulus = drillz * m_rules->rvViaOuter; // eagle "restring"
  1699. annulus = eagleClamp( m_rules->rlMinViaOuter, annulus,
  1700. m_rules->rlMaxViaOuter );
  1701. kidiam = KiROUND( drillz + 2 * annulus );
  1702. via->SetWidth( kidiam );
  1703. }
  1704. via->SetDrill( drillz );
  1705. // make sure the via diameter respects the restring rules
  1706. if( !v.diam || via->GetWidth() <= via->GetDrill() )
  1707. {
  1708. double annulus = eagleClamp( m_rules->rlMinViaOuter,
  1709. (double)( via->GetWidth() / 2 - via->GetDrill() ),
  1710. m_rules->rlMaxViaOuter );
  1711. via->SetWidth( drillz + 2 * annulus );
  1712. }
  1713. if( kidiam < m_min_via )
  1714. m_min_via = kidiam;
  1715. if( drillz < m_min_hole )
  1716. m_min_hole = drillz;
  1717. if( layer_front_most == F_Cu && layer_back_most == B_Cu )
  1718. via->SetViaType( VIATYPE::THROUGH );
  1719. else if( layer_front_most == F_Cu || layer_back_most == B_Cu )
  1720. via->SetViaType( VIATYPE::MICROVIA );
  1721. else
  1722. via->SetViaType( VIATYPE::BLIND_BURIED );
  1723. wxPoint pos( kicad_x( v.x ), kicad_y( v.y ) );
  1724. via->SetPosition( pos );
  1725. via->SetEnd( pos );
  1726. via->SetNetCode( netCode );
  1727. }
  1728. m_xpath->pop();
  1729. }
  1730. else if( itemName == "contactref" )
  1731. {
  1732. m_xpath->push( "contactref" );
  1733. // <contactref element="RN1" pad="7"/>
  1734. const wxString& reference = netItem->GetAttribute( "element" );
  1735. const wxString& pad = netItem->GetAttribute( "pad" );
  1736. wxString key = makeKey( reference, pad ) ;
  1737. // D(printf( "adding refname:'%s' pad:'%s' netcode:%d netname:'%s'\n", reference.c_str(), pad.c_str(), netCode, netName.c_str() );)
  1738. m_pads_to_nets[ key ] = ENET( netCode, netName );
  1739. m_xpath->pop();
  1740. sawPad = true;
  1741. }
  1742. else if( itemName == "polygon" )
  1743. {
  1744. m_xpath->push( "polygon" );
  1745. auto* zone = loadPolygon( netItem );
  1746. if( zone )
  1747. {
  1748. zones.push_back( zone );
  1749. if( !zone->GetIsKeepout() )
  1750. zone->SetNetCode( netCode );
  1751. }
  1752. m_xpath->pop(); // "polygon"
  1753. }
  1754. netItem = netItem->GetNext();
  1755. }
  1756. if( zones.size() && !sawPad )
  1757. {
  1758. // KiCad does not support an unconnected zone with its own non-zero netcode,
  1759. // but only when assigned netcode = 0 w/o a name...
  1760. for( ZONE_CONTAINER* zone : zones )
  1761. zone->SetNetCode( NETINFO_LIST::UNCONNECTED );
  1762. // therefore omit this signal/net.
  1763. }
  1764. else
  1765. netCode++;
  1766. // Get next signal
  1767. net = net->GetNext();
  1768. }
  1769. m_xpath->pop(); // "signals.signal"
  1770. }
  1771. PCB_LAYER_ID EAGLE_PLUGIN::kicad_layer( int aEagleLayer ) const
  1772. {
  1773. int kiLayer;
  1774. // eagle copper layer:
  1775. if( aEagleLayer >= 1 && aEagleLayer < int( arrayDim( m_cu_map ) ) )
  1776. {
  1777. kiLayer = m_cu_map[aEagleLayer];
  1778. }
  1779. else
  1780. {
  1781. // translate non-copper eagle layer to pcbnew layer
  1782. switch( aEagleLayer )
  1783. {
  1784. // Eagle says "Dimension" layer, but it's for board perimeter
  1785. case EAGLE_LAYER::MILLING: kiLayer = Edge_Cuts; break;
  1786. case EAGLE_LAYER::DIMENSION: kiLayer = Edge_Cuts; break;
  1787. case EAGLE_LAYER::TPLACE: kiLayer = F_SilkS; break;
  1788. case EAGLE_LAYER::BPLACE: kiLayer = B_SilkS; break;
  1789. case EAGLE_LAYER::TNAMES: kiLayer = F_SilkS; break;
  1790. case EAGLE_LAYER::BNAMES: kiLayer = B_SilkS; break;
  1791. case EAGLE_LAYER::TVALUES: kiLayer = F_Fab; break;
  1792. case EAGLE_LAYER::BVALUES: kiLayer = B_Fab; break;
  1793. case EAGLE_LAYER::TSTOP: kiLayer = F_Mask; break;
  1794. case EAGLE_LAYER::BSTOP: kiLayer = B_Mask; break;
  1795. case EAGLE_LAYER::TCREAM: kiLayer = F_Paste; break;
  1796. case EAGLE_LAYER::BCREAM: kiLayer = B_Paste; break;
  1797. case EAGLE_LAYER::TFINISH: kiLayer = F_Mask; break;
  1798. case EAGLE_LAYER::BFINISH: kiLayer = B_Mask; break;
  1799. case EAGLE_LAYER::TGLUE: kiLayer = F_Adhes; break;
  1800. case EAGLE_LAYER::BGLUE: kiLayer = B_Adhes; break;
  1801. case EAGLE_LAYER::DOCUMENT: kiLayer = Cmts_User; break;
  1802. case EAGLE_LAYER::REFERENCELC: kiLayer = Cmts_User; break;
  1803. case EAGLE_LAYER::REFERENCELS: kiLayer = Cmts_User; break;
  1804. // Packages show the future chip pins on SMD parts using layer 51.
  1805. // This is an area slightly smaller than the PAD/SMD copper area.
  1806. // Carry those visual aids into the MODULE on the fabrication layer,
  1807. // not silkscreen. This is perhaps not perfect, but there is not a lot
  1808. // of other suitable paired layers
  1809. case EAGLE_LAYER::TDOCU: kiLayer = F_Fab; break;
  1810. case EAGLE_LAYER::BDOCU: kiLayer = B_Fab; break;
  1811. // these layers are defined as user layers. put them on ECO layers
  1812. case EAGLE_LAYER::USERLAYER1: kiLayer = Eco1_User; break;
  1813. case EAGLE_LAYER::USERLAYER2: kiLayer = Eco2_User; break;
  1814. // these will also appear in the ratsnest, so there's no need for a warning
  1815. case EAGLE_LAYER::UNROUTED: kiLayer = Dwgs_User; break;
  1816. case EAGLE_LAYER::TKEEPOUT: kiLayer = F_CrtYd; break;
  1817. case EAGLE_LAYER::BKEEPOUT: kiLayer = B_CrtYd; break;
  1818. case EAGLE_LAYER::TTEST:
  1819. case EAGLE_LAYER::BTEST:
  1820. case EAGLE_LAYER::HOLES:
  1821. default:
  1822. // some layers do not map to KiCad
  1823. wxLogMessage( wxString::Format( _( "Unsupported Eagle layer '%s' (%d), converted to Dwgs.User layer" ),
  1824. eagle_layer_name( aEagleLayer ), aEagleLayer ) );
  1825. kiLayer = Dwgs_User;
  1826. break;
  1827. }
  1828. }
  1829. return PCB_LAYER_ID( kiLayer );
  1830. }
  1831. const wxString& EAGLE_PLUGIN::eagle_layer_name( int aLayer ) const
  1832. {
  1833. static const wxString unknown( "unknown" );
  1834. auto it = m_eagleLayers.find( aLayer );
  1835. return it == m_eagleLayers.end() ? unknown : it->second.name;
  1836. }
  1837. void EAGLE_PLUGIN::centerBoard()
  1838. {
  1839. if( m_props )
  1840. {
  1841. UTF8 page_width;
  1842. UTF8 page_height;
  1843. if( m_props->Value( "page_width", &page_width ) &&
  1844. m_props->Value( "page_height", &page_height ) )
  1845. {
  1846. EDA_RECT bbbox = m_board->GetBoardEdgesBoundingBox();
  1847. int w = atoi( page_width.c_str() );
  1848. int h = atoi( page_height.c_str() );
  1849. int desired_x = ( w - bbbox.GetWidth() ) / 2;
  1850. int desired_y = ( h - bbbox.GetHeight() ) / 2;
  1851. DBG(printf( "bbox.width:%d bbox.height:%d w:%d h:%d desired_x:%d desired_y:%d\n",
  1852. bbbox.GetWidth(), bbbox.GetHeight(), w, h, desired_x, desired_y );)
  1853. m_board->Move( wxPoint( desired_x - bbbox.GetX(), desired_y - bbbox.GetY() ) );
  1854. }
  1855. }
  1856. }
  1857. wxDateTime EAGLE_PLUGIN::getModificationTime( const wxString& aPath )
  1858. {
  1859. // File hasn't been loaded yet.
  1860. if( aPath.IsEmpty() )
  1861. return wxDateTime::Now();
  1862. wxFileName fn( aPath );
  1863. if( fn.IsFileReadable() )
  1864. return fn.GetModificationTime();
  1865. else
  1866. return wxDateTime( 0.0 );
  1867. }
  1868. void EAGLE_PLUGIN::cacheLib( const wxString& aLibPath )
  1869. {
  1870. try
  1871. {
  1872. wxDateTime modtime = getModificationTime( aLibPath );
  1873. // Fixes assertions in wxWidgets debug builds for the wxDateTime object. Refresh the
  1874. // cache if either of the wxDateTime objects are invalid or the last file modification
  1875. // time differs from the current file modification time.
  1876. bool load = !m_mod_time.IsValid() || !modtime.IsValid() || m_mod_time != modtime;
  1877. if( aLibPath != m_lib_path || load )
  1878. {
  1879. wxXmlNode* doc;
  1880. LOCALE_IO toggle; // toggles on, then off, the C locale.
  1881. deleteTemplates();
  1882. // Set this before completion of loading, since we rely on it for
  1883. // text of an exception. Delay setting m_mod_time until after successful load
  1884. // however.
  1885. m_lib_path = aLibPath;
  1886. // 8 bit "filename" should be encoded according to disk filename encoding,
  1887. // (maybe this is current locale, maybe not, its a filesystem issue),
  1888. // and is not necessarily utf8.
  1889. string filename = (const char*) aLibPath.char_str( wxConvFile );
  1890. // Load the document
  1891. wxXmlDocument xmlDocument;
  1892. wxFileName fn( filename );
  1893. if( !xmlDocument.Load( fn.GetFullPath() ) )
  1894. THROW_IO_ERROR( wxString::Format( _( "Unable to read file \"%s\"" ),
  1895. fn.GetFullPath() ) );
  1896. doc = xmlDocument.GetRoot();
  1897. wxXmlNode* drawing = MapChildren( doc )["drawing"];
  1898. NODE_MAP drawingChildren = MapChildren( drawing );
  1899. // clear the cu map and then rebuild it.
  1900. clear_cu_map();
  1901. m_xpath->push( "eagle.drawing.layers" );
  1902. wxXmlNode* layers = drawingChildren["layers"];
  1903. loadLayerDefs( layers );
  1904. m_xpath->pop();
  1905. m_xpath->push( "eagle.drawing.library" );
  1906. wxXmlNode* library = drawingChildren["library"];
  1907. loadLibrary( library, NULL );
  1908. m_xpath->pop();
  1909. m_mod_time = modtime;
  1910. }
  1911. }
  1912. catch(...){}
  1913. // TODO: Handle exceptions
  1914. // catch( file_parser_error fpe )
  1915. // {
  1916. // // for xml_parser_error, what() has the line number in it,
  1917. // // but no byte offset. That should be an adequate error message.
  1918. // THROW_IO_ERROR( fpe.what() );
  1919. // }
  1920. //
  1921. // // Class ptree_error is a base class for xml_parser_error & file_parser_error,
  1922. // // so one catch should be OK for all errors.
  1923. // catch( ptree_error pte )
  1924. // {
  1925. // string errmsg = pte.what();
  1926. //
  1927. // errmsg += " @\n";
  1928. // errmsg += m_xpath->Contents();
  1929. //
  1930. // THROW_IO_ERROR( errmsg );
  1931. // }
  1932. }
  1933. void EAGLE_PLUGIN::FootprintEnumerate( wxArrayString& aFootprintNames, const wxString& aLibraryPath,
  1934. bool aBestEfforts, const PROPERTIES* aProperties )
  1935. {
  1936. wxString errorMsg;
  1937. init( aProperties );
  1938. try
  1939. {
  1940. cacheLib( aLibraryPath );
  1941. }
  1942. catch( const IO_ERROR& ioe )
  1943. {
  1944. errorMsg = ioe.What();
  1945. }
  1946. // Some of the files may have been parsed correctly so we want to add the valid files to
  1947. // the library.
  1948. for( MODULE_CITER it = m_templates.begin(); it != m_templates.end(); ++it )
  1949. aFootprintNames.Add( FROM_UTF8( it->first.c_str() ) );
  1950. if( !errorMsg.IsEmpty() && !aBestEfforts )
  1951. THROW_IO_ERROR( errorMsg );
  1952. }
  1953. MODULE* EAGLE_PLUGIN::FootprintLoad( const wxString& aLibraryPath, const wxString& aFootprintName,
  1954. const PROPERTIES* aProperties )
  1955. {
  1956. init( aProperties );
  1957. cacheLib( aLibraryPath );
  1958. MODULE_CITER mi = m_templates.find( aFootprintName );
  1959. if( mi == m_templates.end() )
  1960. return NULL;
  1961. // Return a copy of the template
  1962. return (MODULE*) mi->second->Duplicate();
  1963. }
  1964. void EAGLE_PLUGIN::FootprintLibOptions( PROPERTIES* aListToAppendTo ) const
  1965. {
  1966. PLUGIN::FootprintLibOptions( aListToAppendTo );
  1967. /*
  1968. (*aListToAppendTo)["ignore_duplicates"] = UTF8( _(
  1969. "Ignore duplicately named footprints within the same Eagle library. "
  1970. "Only the first similarly named footprint will be loaded."
  1971. ));
  1972. */
  1973. }
  1974. /*
  1975. void EAGLE_PLUGIN::Save( const wxString& aFileName, BOARD* aBoard, const PROPERTIES* aProperties )
  1976. {
  1977. // Eagle lovers apply here.
  1978. }
  1979. void EAGLE_PLUGIN::FootprintSave( const wxString& aLibraryPath, const MODULE* aFootprint, const PROPERTIES* aProperties )
  1980. {
  1981. }
  1982. void EAGLE_PLUGIN::FootprintDelete( const wxString& aLibraryPath, const wxString& aFootprintName )
  1983. {
  1984. }
  1985. void EAGLE_PLUGIN::FootprintLibCreate( const wxString& aLibraryPath, const PROPERTIES* aProperties )
  1986. {
  1987. }
  1988. bool EAGLE_PLUGIN::FootprintLibDelete( const wxString& aLibraryPath, const PROPERTIES* aProperties )
  1989. {
  1990. }
  1991. bool EAGLE_PLUGIN::IsFootprintLibWritable( const wxString& aLibraryPath )
  1992. {
  1993. return true;
  1994. }
  1995. */