File: plugins.adoc

package info (click to toggle)
kicad 5.0.2+dfsg1-1~bpo9+1
  • links: PTS, VCS
  • area: main
  • in suites: stretch-backports
  • size: 234,600 kB
  • sloc: cpp: 505,330; ansic: 57,038; python: 4,886; sh: 879; awk: 294; makefile: 253; xml: 103; perl: 5
file content (1725 lines) | stat: -rw-r--r-- 53,460 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
:author: The KiCad Team
:doctype: article
:revdate: @REVDATE@
:toc:
:ascii-ids:

= Kicad Plugins

_KiCad Plugin System_

[[copyright]]
*Copyright*

This document is Copyright (C) 2016 by it's contributors as listed below.
You may distribute it and/or modify it under the terms of either the GNU
General Public License (http://www.gnu.org/licenses/gpl.html), version 3
or later, or the Creative Commons Attribution License
(http://creativecommons.org/licenses/by/3.0/), version 3.0 or later.

All trademarks within this guide belong to their legitimate owners.

[[contributors]]
*Contributors*

Cirilo Bernardo

[[feedback]]
*Feedback*

Please direct any bug reports, suggestions or new versions to here:

- About KiCad document: https://github.com/KiCad/kicad-doc/issues

- About KiCad software: https://bugs.launchpad.net/kicad

- About KiCad software i18n: https://github.com/KiCad/kicad-i18n/issues


[[publication_date_and_software_version]]
*Publication date and software version*

Published on January 29, 2016.

<<<<

== Introduction to the KiCad plugin system

The KiCad plugin system is a framework for extending the capabilities
of KiCad using shared libraries. One of the main advantages of using
a plugin is that it is not necessary to rebuild the KiCad suite while
developing a plugin; in fact, plugins can be built with the aid of a
very small set of headers from the KiCad source tree. Removing the
requirement to build KiCad during plugin development greatly increases
productivity by ensuring that the developer only compiles code directly
related to the plugin which is being developed and thus reducing the
time required for each build and test cycle.

Plugins were initially developed for the 3D model viewer to make it
possible to support more types of 3D models without requiring major
changes to the KiCad source for each new model type supported. The
plugin framework was later generalized so that in the future developers
can create different classes of plugins.  Currently only 3D plugins are
implemented within KiCad but it is envisioned that a PCB plugin will
eventually be developed to make it possible for users to implement
data Importers and Exporters.


[[plugin-classes]]
=== Plugin Classes

Plugins are divided into Plugin Classes since each plugin addresses
problems in a specific domain and therefore requires an interface
unique to that domain. For example, the 3D model plugins load 3D
model data from files and translate that data into a format which
can be displayed by the 3D viewer. A PCB Import/Export plugin
would take PCB data and export to other electrical or mechanical
data formats, or translate a foreign format into a KiCad PCB. At
the moment only the 3D Plugin Class has been developed and it
will be the focus of this document.

Implementing a Plugin Class requires creating code within the KiCad
source tree which manages the loading of plugin code. Within the
KiCad source tree, the file `plugins/ldr/pluginldr.h` declares the
base class for all plugin loaders.  This class declares the most
basic functions which we would expect to find in any KiCad plugin
(boilerplate code) and its implementation provides basic checks
on version compatibility between the plugin loader and the
available plugins. The header `plugins/ldr/3d/pluginldr3D.h` declares
a loader for the 3D Plugin Class. The loader is responsible for
loading a given plugin and making its functions available to KiCad.
Each instance of a plugin loader represents an actual plugin
implementation and acts as a transparent bridge between KiCad and
the plugin's features. The loader is not the only code required within
KiCad to support plugins: we also need code to discover the plugins
and code to invoke the functions of the plugins via the plugin loader.
In the case of the 3D plugins the discovery and invocation functions
are all contained within the S3D_CACHE class.

Plugin developers do not need to be concerned with the details of
KiCad's internal code for managing plugins unless a new Plugin
Class is being developed; a plugin only needs to define the functions
declared by their specific plugin class.

The header `include/plugins/kicad_plugin.h` declares the generic
functions required of all KiCad plugins; these functions identify
the Plugin Class, provide the name of the specific plugin, provide
version information for the Plugin Class API, provide version
information for the specific plugin, and provide a basic version
compatibility check on the Plugin Class API. In brief, these
functions are:

[source,c]
-----
/* Return a UTF-8 string naming the Plugin Class */
char const* GetKicadPluginClass( void );

/* Return version information for the Plugin Class API */
void GetClassVersion( unsigned char* Major, unsigned char* Minor,
     unsigned char* Patch, unsigned char* Revision );

/*
   Return true if the version check implemented in the plugin
   determines that the given Plugin Class API is compatible.
 */
bool CheckClassVersion( unsigned char Major,
    unsigned char Minor, unsigned char Patch, unsigned char Revision );

/* Return the name of the specific plugin, for example "PLUGIN_3D_VRML" */
const char* GetKicadPluginName( void );

/* Return version information for the specific plugin */
void GetPluginVersion( unsigned char* Major, unsigned char* Minor,
     unsigned char* Patch, unsigned char* Revision );
-----


[[class-plugin-3d]]
==== Plugin Class: PLUGIN_3D

The header `include/plugins/3d/3d_plugin.h` declares the functions
which must be implemented by all 3D plugins and defines a number of
functions which are required by the plugin and which the user must
not reimplement. The defined functions which the user must not
reimplement are:

[source,c]
-----
/* Returns the Plugin Class name "PLUGIN_3D" */
char const* GetKicadPluginClass( void );

/* Return version information for the PLUGIN_3D API */
void GetClassVersion( unsigned char* Major, unsigned char* Minor,
     unsigned char* Patch, unsigned char* Revision );

/*
   Performs basic version checks enforced by the developers of
   the loader for the PLUGIN_3D class and returns true if the
   checks pass
 */
bool CheckClassVersion( unsigned char Major, unsigned char Minor,
     unsigned char Patch, unsigned char Revision );
-----

The functions which the user must implement are as follows:
[source,c]
-----
/* Return the number of extension strings supported by the plugin */
int GetNExtensions( void );

/*
   Return the requested extension string; valid values are 0 to
   GetNExtensions() - 1
 */
char const* GetModelExtension( int aIndex );

/* Return the total number of file filters supported by the plugin */
int GetNFilters( void );

/*
   Return the file filter requested; valid values are 0 to
   GetNFilters() - 1
 */
char const* GetFileFilter( int aIndex );

/*
    Return true if the plugin can render this type of 3D model.
    In some cases a plugin may not yet provide a visual model
    and must return false.
 */
bool CanRender( void );

/* Load the specified model and return a pointer to its visual model data */
SCENEGRAPH* Load( char const* aFileName );
-----



== Tutorials: 3D Plugin Class

This section contains a description of two very simple plugins of the
PLUGIN_3D class and walks the user through the setup and building of
the code.


[[basic-3d-plugin]]
=== Basic 3D Plugin

This tutorial walks the user through the development of a very basic
3D plugin named "PLUGIN_3D_DEMO1". The purpose of this tutorial is only
to demonstrate the construction of a very basic 3D plugin which does
nothing other than provide a few filter strings which permit the KiCad
user to filter file names while browsing for 3D models. The code
demonstrated here is the absolute minimum requirement for any 3D plugin
and can be used as a template for creating more advanced plugins.

In order to build the demo project we require the following:

* https://cmake.org/[CMake]
* KiCad plugin headers
* KiCad Scene Graph library `kicad_3dsg`

To automatically detect the KiCad headers and library we shall use a
CMake FindPackage script; the script supplied in this tutorial should
work on Linux and Windows if the relevant header files are installed
to `${KICAD_ROOT_DIR}/kicad` and the KiCad Scene Graph library is
installed in `${KICAD_ROOT_DIR}/lib`.

To start let's create a project directory and the FindPackage script:

[source,bash]
-----
mkdir demo && cd demo
export DEMO_ROOT=${PWD}
mkdir CMakeModules && cd CMakeModules
cat > FindKICAD.cmake << _EOF
find_path( KICAD_INCLUDE_DIR kicad/plugins/kicad_plugin.h
    PATHS ${KICAD_ROOT_DIR}/include $ENV{KICAD_ROOT_DIR}/include
    DOC "Kicad plugins header path."
    )

if( NOT ${KICAD_INCLUDE_DIR} STREQUAL "KICAD_INCLUDE_DIR-NOTFOUND" )

    # attempt to extract the version information from sg_version.h
    find_file( KICAD_SGVERSION sg_version.h
        PATHS ${KICAD_INCLUDE_DIR}
        PATH_SUFFIXES kicad/plugins/3dapi
        NO_DEFAULT_PATH )

    if( NOT ${KICAD_SGVERSION} STREQUAL "KICAD_SGVERSION-NOTFOUND" )

        # extract the "#define KICADSG_VERSION*" lines
        file( STRINGS ${KICAD_SGVERSION} _version REGEX "^#define.*KICADSG_VERSION.*" )

        foreach( SVAR ${_version} )
            string( REGEX MATCH KICADSG_VERSION_[M,A,J,O,R,I,N,P,T,C,H,E,V,I,S]* _VARNAME ${SVAR} )
            string( REGEX MATCH [0-9]+ _VALUE ${SVAR} )

            if( NOT ${_VARNAME} STREQUAL "" AND NOT ${_VALUE} STREQUAL "" )
                set( _${_VARNAME} ${_VALUE} )
            endif()

        endforeach()

        #ensure that NOT SG3D_VERSION* will evaluate to '0'
        if( NOT _KICADSG_VERSION_MAJOR )
            set( _KICADSG_VERSION_MAJOR 0 )
        endif()

        if( NOT _KICADSG_VERSION_MINOR )
            set( _KICADSG_VERSION_MINOR 0 )
        endif()

        if( NOT _KICADSG_VERSION_PATCH )
            set( _KICADSG_VERSION_PATCH 0 )
        endif()

        if( NOT _KICADSG_VERSION_REVISION )
            set( _KICADSG_VERSION_REVISION 0 )
        endif()

        set( KICAD_VERSION ${_KICADSG_VERSION_MAJOR}.${_KICADSG_VERSION_MINOR}.${_KICADSG_VERSION_PATCH}.${_KICADSG_VERSION_REVISION} )
        unset( KICAD_SGVERSION CACHE )

    endif()
endif()


find_library( KICAD_LIBRARY
    NAMES kicad_3dsg
    PATHS
        ${KICAD_ROOT_DIR}/lib $ENV{KICAD_ROOT_DIR}/lib
        ${KICAD_ROOT_DIR}/bin $ENV{KICAD_ROOT_DIR}/bin
    DOC "Kicad scenegraph library path."
    )

include( FindPackageHandleStandardArgs )
FIND_PACKAGE_HANDLE_STANDARD_ARGS( KICAD
    REQUIRED_VARS
        KICAD_INCLUDE_DIR
        KICAD_LIBRARY
        KICAD_VERSION
    VERSION_VAR KICAD_VERSION )


mark_as_advanced( KICAD_INCLUDE_DIR )
set( KICAD_VERSION_MAJOR ${_KICADSG_VERSION_MAJOR} CACHE INTERNAL "" )
set( KICAD_VERSION_MINOR ${_KICADSG_VERSION_MINOR} CACHE INTERNAL "" )
set( KICAD_VERSION_PATCH ${_KICADSG_VERSION_PATCH} CACHE INTERNAL "" )
set( KICAD_VERSION_TWEAK ${_KICADSG_VERSION_REVISION} CACHE INTERNAL "" )
_EOF
-----


Kicad and its plugin headers must be installed; if they are installed
to a user directory or under `/opt` on Linux, or you are using Windows,
you will need to set the `KICAD_ROOT_DIR` environment variable to
point to the directory containing the KiCad `include` and `lib`
directories. For OS X the FindPackage script presented here may require
some adjustments.

To configure and build the tutorial code we will use CMake and
create a `CMakeLists.txt` script file:

[source,bash]
-----
cd ${DEMO_ROOT}
cat > CMakeLists.txt << _EOF
# declare the name of the project
project( PLUGIN_DEMO )

# check that we have a version of CMake with all required features
cmake_minimum_required( VERSION 2.8.12 FATAL_ERROR )

# inform CMake of where to find the FindKICAD script
set( CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/CMakeModules )

# attempt to discover the installed kicad headers and library
# and set the variables:
#     KICAD_INCLUDE_DIR
#     KICAD_LIBRARY
find_package( KICAD 1.0 REQUIRED )

# add the kicad include directory to the compiler's search path
include_directories( ${KICAD_INCLUDE_DIR}/kicad )

# create a plugin named s3d_plugin_demo1
add_library( s3d_plugin_demo1 MODULE
    src/s3d_plugin_demo1.cpp
    )
    
_EOF
-----

The first demo project is very basic; it consists of a single file
with no external link dependencies other than the compiler defaults.
We start by creating a source directory:

[source,bash]
-----
cd ${DEMO_ROOT}
mkdir src && cd src
export DEMO_SRC=${PWD}
-----

Now we create the plugin source itself:

.s3d_plugin_demo1.cpp
[source,c]
-----
#include <iostream>

// the 3d_plugin.h header defines the functions required of 3D plugins
#include "plugins/3d/3d_plugin.h"

// define the version information of this plugin; do not confuse this
// with the Plugin Class version which is defined in 3d_plugin.h
#define PLUGIN_3D_DEMO1_MAJOR 1
#define PLUGIN_3D_DEMO1_MINOR 0
#define PLUGIN_3D_DEMO1_PATCH 0
#define PLUGIN_3D_DEMO1_REVNO 0

// implement the function which provides users with this plugin's name
const char* GetKicadPluginName( void )
{
    return "PLUGIN_3D_DEMO1";
}

// implement the function which provides users with this plugin's version
void GetPluginVersion( unsigned char* Major, unsigned char* Minor,
    unsigned char* Patch, unsigned char* Revision )
{
    if( Major )
        *Major = PLUGIN_3D_DEMO1_MAJOR;

    if( Minor )
        *Minor = PLUGIN_3D_DEMO1_MINOR;

    if( Patch )
        *Patch = PLUGIN_3D_DEMO1_PATCH;

    if( Revision )
        *Revision = PLUGIN_3D_DEMO1_REVNO;

    return;
}

// number of extensions supported; on *NIX systems the extensions are
// provided twice - once in lower case and once in upper case letters
#ifdef _WIN32
    #define NEXTS 7
#else
    #define NEXTS 14
#endif

// number of filter sets supported
#define NFILS 5

// define the extension strings and filter strings which this
// plugin will supply to the user
static char ext0[] = "wrl";
static char ext1[] = "x3d";
static char ext2[] = "emn";
static char ext3[] = "iges";
static char ext4[] = "igs";
static char ext5[] = "stp";
static char ext6[] = "step";

#ifdef _WIN32
static char fil0[] = "VRML 1.0/2.0 (*.wrl)|*.wrl";
static char fil1[] = "X3D (*.x3d)|*.x3d";
static char fil2[] = "IDF 2.0/3.0 (*.emn)|*.emn";
static char fil3[] = "IGESv5.3 (*.igs;*.iges)|*.igs;*.iges";
static char fil4[] = "STEP (*.stp;*.step)|*.stp;*.step";
#else
static char ext7[] = "WRL";
static char ext8[] = "X3D";
static char ext9[] = "EMN";
static char ext10[] = "IGES";
static char ext11[] = "IGS";
static char ext12[] = "STP";
static char ext13[] = "STEP";

static char fil0[] = "VRML 1.0/2.0 (*.wrl;*.WRL)|*.wrl;*.WRL";
static char fil1[] = "X3D (*.x3d;*.X3D)|*.x3d;*.X3D";
static char fil2[] = "IDF 2.0/3.0 (*.emn;*.EMN)|*.emn;*.EMN";
static char fil3[] = "IGESv5.3 (*.igs;*.iges;*.IGS;*.IGES)|*.igs;*.iges;*.IGS;*.IGES";
static char fil4[] = "STEP (*.stp;*.step;*.STP;*.STEP)|*.stp;*.step;*.STP;*.STEP";
#endif

// instantiate a convenient data structure for accessing the
// lists of extension and filter strings
static struct FILE_DATA
{
    char const* extensions[NEXTS];
    char const* filters[NFILS];

    FILE_DATA()
    {
        extensions[0] = ext0;
        extensions[1] = ext1;
        extensions[2] = ext2;
        extensions[3] = ext3;
        extensions[4] = ext4;
        extensions[5] = ext5;
        extensions[6] = ext6;
        filters[0] = fil0;
        filters[1] = fil1;
        filters[2] = fil2;
        filters[3] = fil3;
        filters[4] = fil4;

#ifndef _WIN32
        extensions[7] = ext7;
        extensions[8] = ext8;
        extensions[9] = ext9;
        extensions[10] = ext10;
        extensions[11] = ext11;
        extensions[12] = ext12;
        extensions[13] = ext13;
#endif
        return;
    }

} file_data;


// return the number of extensions supported by this plugin
int GetNExtensions( void )
{
    return NEXTS;
}

// return the indexed extension string
char const* GetModelExtension( int aIndex )
{
    if( aIndex < 0 || aIndex >= NEXTS )
        return NULL;

    return file_data.extensions[aIndex];
}

// return the number of filter strings provided by this plugin
int GetNFilters( void )
{
    return NFILS;
}

// return the indexed filter string
char const* GetFileFilter( int aIndex )
{
    if( aIndex < 0 || aIndex >= NFILS )
        return NULL;

    return file_data.filters[aIndex];
}

// return false since this plugin does not provide visualization data
bool CanRender( void )
{
    return false;
}

// return NULL since this plugin does not provide visualization data
SCENEGRAPH* Load( char const* aFileName )
{
    // this dummy plugin does not support rendering of any models
    return NULL;
}
-----

This source file meets all the minimum requirements to implement
a 3D plugin. The plugin does not produce any data for rendering
models but it can provide KiCad with a list of supported model
file extensions and file extension filters to enhance the 3D
model file selection dialog. Within KiCad the extension strings
are used to select the plugins which may be used to load a
specified model; for example, if the plugin is `wrl` then KiCad
will invoke each plugin which claims to support the extension
`wrl` until a plugin returns visualization data. The file
filters provided by each plugin are passed to the 3D file
selector dialog to improve the browsing UI.

To build the plugin:

[source,bash]
-----
cd ${DEMO_ROOT}
# export KICAD_ROOT_DIR if necessary
mkdir build && cd build
cmake .. && make
-----

The plugin will be built but not installed; you must copy the
plugin file to KiCad's plugin directory if you wish to load the plugin.


[[advanced-3d-plugin]]
=== Advanced 3D Plugin

This tutorial walks the user through the development of a 3D plugin
named "PLUGIN_3D_DEMO2". The purpose of this tutorial is to demonstrate
the construction of a very basic scene graph which the KiCad previewer
can render. The plugin claims to handle files of type `txt`. Although
the file must exist in order for the cache manager to invoke the
plugin, the file contents are not processed by this plugin; instead,
the plugin simply creates a scene graph containing a pair of tetrahedra.
This tutorial assumes that the first tutorial had been completed and
that the CMakeLists.txt and FindKICAD.cmake script files have been
created.

Place the new source file in the same directory as the previous
tutorial's source file and we will extend the previous tutorial's
CMakeLists.txt file to build this tutorial. Since this plugin will
create a scene graph for KiCad we need to link to KiCad's scene
graph library `kicad_3dsg`. KiCad's Scene Graph Library provides
a set of classes which can be used to build the Scene Graph Object;
the Scene Graph Object is an intermediate data visualization format
used by the 3D Cache Manager. All plugins which support model
visualization must translate the model data into a scene graph via
this library.

The first step is to extend `CMakeLists.txt` to build this tutorial project:

[source,bash]
-----
cd ${DEMO_ROOT}
cat >> CMakeLists.txt << _EOF
add_library( s3d_plugin_demo2 MODULE
    src/s3d_plugin_demo2.cpp
    )

target_link_libraries( s3d_plugin_demo2 ${KICAD_LIBRARY} )
_EOF
-----

Now we change to the source directory and create the source file:

[source,bash]
-----
cd ${DEMO_SRC}
-----

.s3d_plugin_demo2.cpp
[source,c]
-----
#include <cmath>
// 3D Plugin Class declarations
#include "plugins/3d/3d_plugin.h"
// interface to KiCad Scene Graph Library
#include "plugins/3dapi/ifsg_all.h"

// version information for this plugin
#define PLUGIN_3D_DEMO2_MAJOR 1
#define PLUGIN_3D_DEMO2_MINOR 0
#define PLUGIN_3D_DEMO2_PATCH 0
#define PLUGIN_3D_DEMO2_REVNO 0

// provide the name of this plugin
const char* GetKicadPluginName( void )
{
    return "PLUGIN_3D_DEMO2";
}

// provide the version of this plugin
void GetPluginVersion( unsigned char* Major, unsigned char* Minor,
    unsigned char* Patch, unsigned char* Revision )
{
    if( Major )
        *Major = PLUGIN_3D_DEMO2_MAJOR;

    if( Minor )
        *Minor = PLUGIN_3D_DEMO2_MINOR;

    if( Patch )
        *Patch = PLUGIN_3D_DEMO2_PATCH;

    if( Revision )
        *Revision = PLUGIN_3D_DEMO2_REVNO;

    return;
}


// number of extensions supported
#ifdef _WIN32
#define NEXTS 1
#else
#define NEXTS 2
#endif

// number of filter sets supported
#define NFILS 1

static char ext0[] = "txt";

#ifdef _WIN32
static char fil0[] = "demo (*.txt)|*.txt";
#else
static char ext1[] = "TXT";

static char fil0[] = "demo (*.txt;*.TXT)|*.txt;*.TXT";
#endif


static struct FILE_DATA
{
    char const* extensions[NEXTS];
    char const* filters[NFILS];

    FILE_DATA()
    {
        extensions[0] = ext0;
        filters[0] = fil0;

#ifndef _WIN32
        extensions[1] = ext1;
#endif
        return;
    }

} file_data;


int GetNExtensions( void )
{
    return NEXTS;
}


char const* GetModelExtension( int aIndex )
{
    if( aIndex < 0 || aIndex >= NEXTS )
        return NULL;

    return file_data.extensions[aIndex];
}


int GetNFilters( void )
{
    return NFILS;
}


char const* GetFileFilter( int aIndex )
{
    if( aIndex < 0 || aIndex >= NFILS )
        return NULL;

    return file_data.filters[aIndex];
}


// return true since this plugin can provide visualization data
bool CanRender( void )
{
    return true;
}


// create the visualization data
SCENEGRAPH* Load( char const* aFileName )
{
    // For this demonstration we create a tetrahedron (tx1) consisting
    // of a SCENEGRAPH (VRML Transform) which in turn contains 4
    // SGSHAPE (VRML Shape) objects representing each of the sides of
    // the tetrahedron. Each Shape is associated with a color (SGAPPEARANCE)
    // and a SGFACESET (VRML Geometry->indexedFaceSet). Each SGFACESET is
    // associated with a vertex list (SGCOORDS), a per-vertex normals
    // list (SGNORMALS), and a coordinate index (SGCOORDINDEX). One shape
    // is used to represent each face so that we may use per-vertex-per-face
    // normals.
    //
    // The tetrahedron in turn is a child of a top level SCENEGRAPH (tx0)
    // which has a second SCENEGRAPH child (tx2) which is a transformation
    // of the tetrahedron tx1 (rotation + translation). This demonstrates
    // the reuse of components within the scene graph hierarchy.

    // define the vertices of the tetrahedron
    // face 1: 0, 3, 1
    // face 2: 0, 2, 3
    // face 3: 1, 3, 2
    // face 4: 0, 1, 2
    double SQ2 = sqrt( 0.5 );
    SGPOINT vert[4];
    vert[0] = SGPOINT( 1.0, 0.0, -SQ2 );
    vert[1] = SGPOINT( -1.0, 0.0, -SQ2 );
    vert[2] = SGPOINT( 0.0, 1.0, SQ2 );
    vert[3] = SGPOINT( 0.0, -1.0, SQ2 );


    // create the top level transform; this will hold all other
    // scenegraph objects; a transform may hold other transforms and
    // shapes
    IFSG_TRANSFORM* tx0 = new IFSG_TRANSFORM( true );

    // create the transform which will house the shapes
    IFSG_TRANSFORM* tx1 = new IFSG_TRANSFORM( tx0->GetRawPtr() );

    // add a shape which we will use to define one face of the tetrahedron;
    // shapes hold facesets and appearances
    IFSG_SHAPE* shape = new IFSG_SHAPE( *tx1 );

    // add a faceset; these contain coordinate lists, coordinate indices,
    // vertex lists, vertex indices, and may also contain color lists and
    // their indices.

    IFSG_FACESET* face = new IFSG_FACESET( *shape );

    IFSG_COORDS* cp = new IFSG_COORDS( *face );
    cp->AddCoord( vert[0] );
    cp->AddCoord( vert[3] );
    cp->AddCoord( vert[1] );

    // coordinate indices - note: enforce triangles;
    // in real plugins where it is not necessarily possible
    // to determine which side a triangle is visible from,
    // 2 point orders must be specified for each triangle
    IFSG_COORDINDEX* coordIdx = new IFSG_COORDINDEX( *face );
    coordIdx->AddIndex( 0 );
    coordIdx->AddIndex( 1 );
    coordIdx->AddIndex( 2 );

    // create an appearance; appearances are owned by shapes
    
    // magenta
    IFSG_APPEARANCE* material = new IFSG_APPEARANCE( *shape);
    material->SetSpecular( 0.1, 0.0, 0.1 );
    material->SetDiffuse( 0.8, 0.0, 0.8 );
    material->SetAmbient( 0.2, 0.2, 0.2 );
    material->SetShininess( 0.2 );

    // normals
    IFSG_NORMALS* np = new IFSG_NORMALS( *face );
    SGVECTOR nval = S3D::CalcTriNorm( vert[0], vert[3], vert[1] );
    np->AddNormal( nval );
    np->AddNormal( nval );
    np->AddNormal( nval );

    //
    // Shape2
    // Note: we reuse the IFSG* wrappers to create and manipulate new
    // data structures.
    //
    shape->NewNode( *tx1 );
    face->NewNode( *shape );
    coordIdx->NewNode( *face );
    cp->NewNode( *face );
    np->NewNode( *face );
    
    // vertices
    cp->AddCoord( vert[0] );
    cp->AddCoord( vert[2] );
    cp->AddCoord( vert[3] );
    
    // indices
    coordIdx->AddIndex( 0 );
    coordIdx->AddIndex( 1 );
    coordIdx->AddIndex( 2 );
    
    // normals
    nval = S3D::CalcTriNorm( vert[0], vert[2], vert[3] );
    np->AddNormal( nval );
    np->AddNormal( nval );
    np->AddNormal( nval );
    // color (red)
    material->NewNode( *shape );
    material->SetSpecular( 0.2, 0.0, 0.0 );
    material->SetDiffuse( 0.9, 0.0, 0.0 );
    material->SetAmbient( 0.2, 0.2, 0.2 );
    material->SetShininess( 0.1 );

    //
    // Shape3
    //
    shape->NewNode( *tx1 );
    face->NewNode( *shape );
    coordIdx->NewNode( *face );
    cp->NewNode( *face );
    np->NewNode( *face );
    
    // vertices
    cp->AddCoord( vert[1] );
    cp->AddCoord( vert[3] );
    cp->AddCoord( vert[2] );
    
    // indices
    coordIdx->AddIndex( 0 );
    coordIdx->AddIndex( 1 );
    coordIdx->AddIndex( 2 );
    
    // normals
    nval = S3D::CalcTriNorm( vert[1], vert[3], vert[2] );
    np->AddNormal( nval );
    np->AddNormal( nval );
    np->AddNormal( nval );
    
    // color (green)
    material->NewNode( *shape );
    material->SetSpecular( 0.0, 0.1, 0.0 );
    material->SetDiffuse( 0.0, 0.9, 0.0 );
    material->SetAmbient( 0.2, 0.2, 0.2 );
    material->SetShininess( 0.1 );

    //
    // Shape4
    //
    shape->NewNode( *tx1 );
    face->NewNode( *shape );
    coordIdx->NewNode( *face );
    cp->NewNode( *face );
    np->NewNode( *face );
    
    // vertices
    cp->AddCoord( vert[0] );
    cp->AddCoord( vert[1] );
    cp->AddCoord( vert[2] );
    
    // indices
    coordIdx->AddIndex( 0 );
    coordIdx->AddIndex( 1 );
    coordIdx->AddIndex( 2 );
    
    // normals
    nval = S3D::CalcTriNorm( vert[0], vert[1], vert[2] );
    np->AddNormal( nval );
    np->AddNormal( nval );
    np->AddNormal( nval );
    
    // color (blue)
    material->NewNode( *shape );
    material->SetSpecular( 0.0, 0.0, 0.1 );
    material->SetDiffuse( 0.0, 0.0, 0.9 );
    material->SetAmbient( 0.2, 0.2, 0.2 );
    material->SetShininess( 0.1 );

    // create a copy of the entire tetrahedron shifted Z+2 and rotated 2/3PI
    IFSG_TRANSFORM* tx2 = new IFSG_TRANSFORM( tx0->GetRawPtr() );
    tx2->AddRefNode( *tx1 );
    tx2->SetTranslation( SGPOINT( 0, 0, 2 ) );
    tx2->SetRotation( SGVECTOR( 0, 0, 1 ), M_PI*2.0/3.0 );

    SGNODE* data = tx0->GetRawPtr();

    // delete the wrappers
    delete shape;
    delete face;
    delete coordIdx;
    delete material;
    delete cp;
    delete np;
    delete tx0;
    delete tx1;
    delete tx2;

    return (SCENEGRAPH*)data;
}
-----

== Application Programming Interface (API)

Plugins are implemented via Application Programming Interface (API)
implementations. Each Plugin Class has its specific API and in the
3D Plugin tutorials we have seen examples of the implementation of
the 3D Plugin API as declared by the header `3d_plugin.h`. Plugins
may also rely on other APIs defined within the KiCad source tree;
in the case of 3D plugins, all plugins which support visualization
of models must interact with the Scene Graph API as declared in
the header `ifsg_all.h` and its included headers.

This section describes the details of available Plugin Class APIs
and other KiCad APIs which may be required for implementations of
plugin classes.

=== Plugin Class APIs

There is currently only one plugin class declared for KiCad: the 3D
Plugin Class. All KiCad plugin classes must implement
a basic set of functions declared in the header file `kicad_plugin.h`;
these declarations are referred to as the Base Kicad Plugin Class.
No implementation of the Base Kicad Plugin Class exists; the header file
exists purely to ensure that plugin developers implement these
defined functions in each plugin implementation.

Within KiCad, each instance of a Plugin Loader implements the API
presented by a plugin as though the Plugin Loader is a class providing
the plugin's services. This is achieved by the Plugin Loader class
providing a public interface containing function names which are
similar to those implemented by the plugin; the argument lists may
vary to accommodate the need to inform the user of any problems which
may be encountered if, for example, no plugin is loaded. Internally 
the Plugin Loader uses a stored pointer to each API function to
invoke each function on behalf of the user.


==== API: Base Kicad Plugin Class

The Base Kicad Plugin Class is defined by the header file `kicad_plugin.h`.
This header must be included in the declaration of all other plugin
classes; for an example see the 3D Plugin Class declaration in the
header file `3d_plugin.h`. The prototypes for these functions were briefly
described in <<plugin-classes,Plugin Classes>>. The API is implemented
by the base plugin loader as defined in `pluginldr.cpp`.

To help make sense of the functions required by the base KiCad plugin header
we must look at what happens in the base Plugin Loader class. The Plugin
Loader class declares a virtual function `Open()` which takes the full
path to the plugin to be loaded. The implementation of the `Open()` function
within a specific plugin class loader will initially invoke the protected
`open()` function of the base plugin loader; this base `open()` function
attempts to find the address of each of the required basic plugin functions;
once the addresses of each function have been retrieved, a number of checks
are enforced:

. Plugin `GetKicadPluginClass()` is invoked and the result is compared to
  the Plugin Class string provided by the Plugin Loader implementation; if
  these strings do not match then the opened plugin is not intended for the
  Plugin Loader instance.
. Plugin `GetClassVersion()` is invoked to retrieve the Plugin Class API Version
  implemented by the plugin.
. Plugin Loader virtual `GetLoaderVersion()` function is invoked to retrieve the
  Plugin Class API Version implemented by the loader.
. The Plugin Class API Version reported by the plugin and the loader are
  required to have the same Major Version number, otherwise they are
  considered incompatible. This is the most basic version test and it is
  enforced by the base plugin loader.
. Plugin `CheckClassVersion()` is invoked with the Plugin Class API Version
  information of the Plugin Loader; if the Plugin supports the given version
  then it returns `true` to indicate success. If successful the loader creates
  a PluginInfo string based on the results of `GetKicadPluginName()` and
  `GetPluginVersion()`, and the plugin loading procedure
  continues within the Plugin Loader's `Open()` implementation.


==== API: 3D Plugin Class

The 3D Plugin Class is declared by the header file `3d_plugin.h` and it
extends the required plugin functions as described in
<<class-plugin-3d,Plugin Class: PLUGIN_3D>>. The corresponding
Plugin Loader is defined in `pluginldr3D.cpp` and the loader implements
the following public functions in addition to the required API functions:

[source,c]
-----
/* Open the plugin specified by the full path "aFullFileName" */
bool Open( const wxString& aFullFileName );

/* Close the currently opened plugin */
void Close( void );

/* Retrieve the Plugin Class API Version implemented by this Plugin Loader */
void GetLoaderVersion( unsigned char* Major, unsigned char* Minor,
    unsigned char* Revision, unsigned char* Patch ) const;
-----

The required 3D Plugin Class functions are exposed via the
following functions:

[source,c]
-----
/* returns the Plugin Class or NULL if no plugin loaded */
char const* GetKicadPluginClass( void );

/* returns false if no plugin loaded */
bool GetClassVersion( unsigned char* Major, unsigned char* Minor,
    unsigned char* Patch, unsigned char* Revision );

/* returns false if the class version check fails or no plugin is loaded */
bool CheckClassVersion( unsigned char Major, unsigned char Minor,
    unsigned char Patch, unsigned char Revision );

/* returns the Plugin Name or NULL if no plugin loaded */
const char* GetKicadPluginName( void );

/*
   returns false if no plugin is loaded, otherwise the arguments
   contain the result of GetPluginVersion()
 */
bool GetVersion( unsigned char* Major, unsigned char* Minor,
    unsigned char* Patch, unsigned char* Revision );

/*
   sets aPluginInfo to an empty string if no plugin is loaded,
   otherwise aPluginInfo is set to a string of the form:
   [NAME]:[MAJOR].[MINOR].[PATCH].[REVISION] where
   NAME = name provided by GetKicadPluginClass()
   MAJOR, MINOR, PATCH, REVISION = version information from 
   GetPluginVersion()
 */
void GetPluginInfo( std::string& aPluginInfo );
-----

In typical situations, the user would do the following:

. Create an instance of `KICAD_PLUGIN_LDR_3D`.
. Invoke `Open( "/path/to/myplugin.so" )` to open a specific plugin.
  The return value must be checked to ensure that the plugin loaded
  as desired.
. Invoke any of the 3D Plugin Class calls as exposed by `KICAD_PLUGIN_LDR_3D`.
. Invoke `Close()` to close (unlink) the plugin.
. Destroy the `KICAD_PLUGIN_LDR_3D` instance.

=== Scenegraph Class APIs

The Scenegraph Class API is defined by the header `ifsg_all.h` and its
included headers. The API consists of a number of helper routines with
the namespace `S3D` as defined in `ifsg_api.h` and wrapper classes defined
by the various `ifsg_*.h` headers; the wrappers support the underlying
scene graph classes which, taken together, form a scene graph structure
which is compatible with VRML2.0 static scene graphs. The headers,
structures, classes and their public functions are as follows:

.sg_version.h
[source,c]
-----
/*
   Defines version information of the SceneGraph Classes.
   All plugins which use the scenegraph class should include this header
   and check the version information against the version reported by
   S3D::GetLibVersion() to ensure compatibility
 */

#define KICADSG_VERSION_MAJOR         2
#define KICADSG_VERSION_MINOR         0
#define KICADSG_VERSION_PATCH         0
#define KICADSG_VERSION_REVISION      0
-----


.sg_types.h
[source,c]
-----
/*
   Defines the SceneGraph Class Types; these types
   are closely related to VRML2.0 node types.
 */
 
namespace S3D
{
    enum SGTYPES
    {
        SGTYPE_TRANSFORM = 0,
        SGTYPE_APPEARANCE,
        SGTYPE_COLORS,
        SGTYPE_COLORINDEX,
        SGTYPE_FACESET,
        SGTYPE_COORDS,
        SGTYPE_COORDINDEX,
        SGTYPE_NORMALS,
        SGTYPE_SHAPE,
        SGTYPE_END
    };
};
-----

The `sg_base.h` header contains declarations of basic data types used
by the scenegraph classes.

.sg_base.h
[source,c]
-----
/*
    This is an RGB color model equivalent to the VRML2.0
    RGB model where each color may have a value within the
    range [0..1].
 */
 
class SGCOLOR
{
public:
    SGCOLOR();
    SGCOLOR( float aRVal, float aGVal, float aBVal );

    void GetColor( float& aRedVal, float& aGreenVal, float& aBlueVal ) const;
    void GetColor( SGCOLOR& aColor ) const;
    void GetColor( SGCOLOR* aColor ) const;

    bool SetColor( float aRedVal, float aGreenVal, float aBlueVal );
    bool SetColor( const SGCOLOR& aColor );
    bool SetColor( const SGCOLOR* aColor );
};


class SGPOINT
{
public:
    double x;
    double y;
    double z;

public:
    SGPOINT();
    SGPOINT( double aXVal, double aYVal, double aZVal );

    void GetPoint( double& aXVal, double& aYVal, double& aZVal );
    void GetPoint( SGPOINT& aPoint );
    void GetPoint( SGPOINT* aPoint );

    void SetPoint( double aXVal, double aYVal, double aZVal );
    void SetPoint( const SGPOINT& aPoint );
};


/*
    A SGVECTOR has 3 components (x,y,z) similar to a point; however
    a vector ensures that the stored values are normalized and
    prevents direct manipulation of the component variables.
 */
class SGVECTOR
{
public:
    SGVECTOR();
    SGVECTOR( double aXVal, double aYVal, double aZVal );

    void GetVector( double& aXVal, double& aYVal, double& aZVal ) const;

    void SetVector( double aXVal, double aYVal, double aZVal );
    void SetVector( const SGVECTOR& aVector );

    SGVECTOR& operator=( const SGVECTOR& source );
};
-----


The `IFSG_NODE` class is the base class for all scenegraph nodes. All
scenegraph objects implement the public functions of this class but in
some cases a particular function may have no meaning for a specific
class.

.ifsg_node.h
[source,c]
-----
class IFSG_NODE
{
public:
    IFSG_NODE();
    virtual ~IFSG_NODE();

    /**
     * Function Destroy
     * deletes the scenegraph object held by this wrapper
     */
    void Destroy( void );

    /**
     * Function Attach
     * associates a given SGNODE* with this wrapper
     */
    virtual bool Attach( SGNODE* aNode ) = 0;

    /**
     * Function NewNode
     * creates a new node to associate with this wrapper
     */
    virtual bool NewNode( SGNODE* aParent ) = 0;
    virtual bool NewNode( IFSG_NODE& aParent ) = 0;

    /**
     * Function GetRawPtr()
     * returns the raw internal SGNODE pointer
     */
    SGNODE* GetRawPtr( void );

    /**
     * Function GetNodeType
     * returns the type of this node instance
     */
    S3D::SGTYPES GetNodeType( void ) const;

    /**
     * Function GetParent
     * returns a pointer to the parent SGNODE of this object
     * or NULL if the object has no parent (ie. top level transform)
     * or if the wrapper is not currently associated with an SGNODE.
     */
    SGNODE* GetParent( void ) const;

    /**
     * Function SetParent
     * sets the parent SGNODE of this object.
     *
     * @param aParent [in] is the desired parent node
     * @return true if the operation succeeds; false if
     * the given node is not allowed to be a parent to
     * the derived object.
     */
    bool SetParent( SGNODE* aParent );

    /**
     * Function GetNodeTypeName
     * returns the text representation of the node type
     * or NULL if the node somehow has an invalid type
     */
    const char * GetNodeTypeName( S3D::SGTYPES aNodeType ) const;

    /**
     * Function AddRefNode
     * adds a reference to an existing node which is not owned by
     * (not a child of) this node.
     *
     * @return true on success
     */
    bool AddRefNode( SGNODE* aNode );
    bool AddRefNode( IFSG_NODE& aNode );

    /**
     * Function AddChildNode
     * adds a node as a child owned by this node.
     *
     * @return true on success
     */
    bool AddChildNode( SGNODE* aNode );
    bool AddChildNode( IFSG_NODE& aNode );
};
-----


`IFSG_TRANSFORM` is similar to a VRML2.0 Transform node; it may
contain any number of child IFSG_SHAPE and IFSG_TRANSFORM nodes
and any number of referenced IFSG_SHAPE and IFSG_TRANSFORM nodes.
A valid scenegraph must have a single `IFSG_TRANSFORM` object
as a root.

.ifsg_transform.h
[source,c]
-----
/**
 * Class IFSG_TRANSFORM
 * is the wrapper for the VRML compatible TRANSFORM block class SCENEGRAPH
 */

class IFSG_TRANSFORM : public IFSG_NODE
{
public:
    IFSG_TRANSFORM( bool create );
    IFSG_TRANSFORM( SGNODE* aParent );
    
    bool SetScaleOrientation( const SGVECTOR& aScaleAxis, double aAngle );
    bool SetRotation( const SGVECTOR& aRotationAxis, double aAngle );
    bool SetScale( const SGPOINT& aScale );
    bool SetScale( double aScale );
    bool SetCenter( const SGPOINT& aCenter );
    bool SetTranslation( const SGPOINT& aTranslation );

    /* various base class functions not shown here */
};
-----


`IFSG_SHAPE` is similar to a VRML2.0 Shape node; it must contain
a single child or reference FACESET node and may contain a
single child or reference APPEARANCE node.

.ifsg_shape.h
[source,c]
-----
/**
 * Class IFSG_SHAPE
 * is the wrapper for the SGSHAPE class
 */

class IFSG_SHAPE : public IFSG_NODE
{
public:
    IFSG_SHAPE( bool create );
    IFSG_SHAPE( SGNODE* aParent );
    IFSG_SHAPE( IFSG_NODE& aParent );

    /* various base class functions not shown here */
};
-----


`IFSG_APPEARANCE` is similar to a VRML2.0 Appearance node, however,
at the moment it only represents the equivalent of an Appearance
node containing a Material node.

.ifsg_appearance.h
[source,c]
-----
class IFSG_APPEARANCE : public IFSG_NODE
{
public:
    IFSG_APPEARANCE( bool create );
    IFSG_APPEARANCE( SGNODE* aParent );
    IFSG_APPEARANCE( IFSG_NODE& aParent );

    bool SetEmissive( float aRVal, float aGVal, float aBVal );
    bool SetEmissive( const SGCOLOR* aRGBColor );
    bool SetEmissive( const SGCOLOR& aRGBColor );

    bool SetDiffuse( float aRVal, float aGVal, float aBVal );
    bool SetDiffuse( const SGCOLOR* aRGBColor );
    bool SetDiffuse( const SGCOLOR& aRGBColor );

    bool SetSpecular( float aRVal, float aGVal, float aBVal );
    bool SetSpecular( const SGCOLOR* aRGBColor );
    bool SetSpecular( const SGCOLOR& aRGBColor );

    bool SetAmbient( float aRVal, float aGVal, float aBVal );
    bool SetAmbient( const SGCOLOR* aRGBColor );
    bool SetAmbient( const SGCOLOR& aRGBColor );

    bool SetShininess( float aShininess );
    bool SetTransparency( float aTransparency );

    /* various base class functions not shown here */
    
    /* the following functions make no sense within an
       appearance node and always return a failure code
       
        bool AddRefNode( SGNODE* aNode );
        bool AddRefNode( IFSG_NODE& aNode );
        bool AddChildNode( SGNODE* aNode );
        bool AddChildNode( IFSG_NODE& aNode );
     */
};
-----


`IFSG_FACESET` is similar to a VRML2.0 Geometry node which
contains an IndexedFaceSet node.  It must contain a single
child or reference COORDS node, a single child COORDINDEX
node, and a single child or reference NORMALS node; in
addition there may be a single child or reference COLORS node.
A simplistic normals calculation function is provided to aid
the user in assigning normal values to surfaces. The deviations
from the VRML2.0 analogue are as follows:

. Normals are always per-vertex.
. Colors are always per vertex.
. The coordinate index set must describe triangular faces only.

.ifsg_faceset.h
[source,c]
-----
/**
 * Class IFSG_FACESET
 * is the wrapper for the SGFACESET class
 */

class IFSG_FACESET : public IFSG_NODE
{
public:
    IFSG_FACESET( bool create );
    IFSG_FACESET( SGNODE* aParent );
    IFSG_FACESET( IFSG_NODE& aParent );

    bool CalcNormals( SGNODE** aPtr );

    /* various base class functions not shown here */
};
-----


.ifsg_coords.h
[source,c]
-----
/**
 * Class IFSG_COORDS
 * is the wrapper for SGCOORDS
 */

class IFSG_COORDS : public IFSG_NODE
{
public:
    IFSG_COORDS( bool create );
    IFSG_COORDS( SGNODE* aParent );
    IFSG_COORDS( IFSG_NODE& aParent );

    bool GetCoordsList( size_t& aListSize, SGPOINT*& aCoordsList );
    bool SetCoordsList( size_t aListSize, const SGPOINT* aCoordsList );
    bool AddCoord( double aXValue, double aYValue, double aZValue );
    bool AddCoord( const SGPOINT& aPoint );

    /* various base class functions not shown here */

    /* the following functions make no sense within a
       coords node and always return a failure code
       
        bool AddRefNode( SGNODE* aNode );
        bool AddRefNode( IFSG_NODE& aNode );
        bool AddChildNode( SGNODE* aNode );
        bool AddChildNode( IFSG_NODE& aNode );
     */
};
-----


`IFSG_COORDINDEX` is similar to a VRML2.0 coordIdx[]
set except it must exclusively describe triangular
faces, which implies that the total number of indices
is divisible by 3.

.ifsg_coordindex.h
[source,c]
-----
/**
 * Class IFSG_COORDINDEX
 * is the wrapper for SGCOORDINDEX
 */
 
class IFSG_COORDINDEX : public IFSG_INDEX
{
public:
    IFSG_COORDINDEX( bool create );
    IFSG_COORDINDEX( SGNODE* aParent );
    IFSG_COORDINDEX( IFSG_NODE& aParent );

    bool GetIndices( size_t& nIndices, int*& aIndexList );
    bool SetIndices( size_t nIndices, int* aIndexList );
    bool AddIndex( int aIndex );

    /* various base class functions not shown here */

    /* the following functions make no sense within a
       coordindex node and always return a failure code
       
        bool AddRefNode( SGNODE* aNode );
        bool AddRefNode( IFSG_NODE& aNode );
        bool AddChildNode( SGNODE* aNode );
        bool AddChildNode( IFSG_NODE& aNode );
     */
};
-----


`IFSG_NORMALS` is equivalent to a VRML2.0 Normals node.

.ifsg_normals.h
[source,c]
-----
/**
 * Class IFSG_NORMALS
 * is the wrapper for the SGNORMALS class
 */

class IFSG_NORMALS : public IFSG_NODE
{
public:
    IFSG_NORMALS( bool create );
    IFSG_NORMALS( SGNODE* aParent );
    IFSG_NORMALS( IFSG_NODE& aParent );

    bool GetNormalList( size_t& aListSize, SGVECTOR*& aNormalList );
    bool SetNormalList( size_t aListSize, const SGVECTOR* aNormalList );
    bool AddNormal( double aXValue, double aYValue, double aZValue );
    bool AddNormal( const SGVECTOR& aNormal );

    /* various base class functions not shown here */

    /* the following functions make no sense within a
       normals node and always return a failure code
       
        bool AddRefNode( SGNODE* aNode );
        bool AddRefNode( IFSG_NODE& aNode );
        bool AddChildNode( SGNODE* aNode );
        bool AddChildNode( IFSG_NODE& aNode );
     */
};
-----

`IFSG_COLORS` is similar to a VRML2.0 colors[] set.

.ifsg_colors.h
[source,c]
-----
/**
 * Class IFSG_COLORS
 * is the wrapper for SGCOLORS
 */

class IFSG_COLORS : public IFSG_NODE
{
public:
    IFSG_COLORS( bool create );
    IFSG_COLORS( SGNODE* aParent );
    IFSG_COLORS( IFSG_NODE& aParent );

    bool GetColorList( size_t& aListSize, SGCOLOR*& aColorList );
    bool SetColorList( size_t aListSize, const SGCOLOR* aColorList );
    bool AddColor( double aRedValue, double aGreenValue, double aBlueValue );
    bool AddColor( const SGCOLOR& aColor );

    /* various base class functions not shown here */

    /* the following functions make no sense within a
       normals node and always return a failure code
       
        bool AddRefNode( SGNODE* aNode );
        bool AddRefNode( IFSG_NODE& aNode );
        bool AddChildNode( SGNODE* aNode );
        bool AddChildNode( IFSG_NODE& aNode );
     */
};
-----


The remaining API functions are defined in `ifsg_api.h` as follows:

.ifsg_api.h
[source,c]
-----
namespace S3D
{
    /**
     * Function GetLibVersion retrieves version information of the
     * kicad_3dsg library
     */
    SGLIB_API void GetLibVersion( unsigned char* Major, unsigned char* Minor,
                                  unsigned char* Patch, unsigned char* Revision );

    // functions to extract information from SGNODE pointers
    SGLIB_API S3D::SGTYPES GetSGNodeType( SGNODE* aNode );
    SGLIB_API SGNODE* GetSGNodeParent( SGNODE* aNode );
    SGLIB_API bool AddSGNodeRef( SGNODE* aParent, SGNODE* aChild );
    SGLIB_API bool AddSGNodeChild( SGNODE* aParent, SGNODE* aChild );
    SGLIB_API void AssociateSGNodeWrapper( SGNODE* aObject, SGNODE** aRefPtr );

    /**
     * Function CalcTriNorm
     * returns the normal vector of a triangle described by vertices p1, p2, p3
     */
    SGLIB_API SGVECTOR CalcTriNorm( const SGPOINT& p1, const SGPOINT& p2, const SGPOINT& p3 );

    /**
     * Function WriteCache
     * writes the SGNODE tree to a binary cache file
     *
     * @param aFileName is the name of the file to write
     * @param overwrite must be set to true to overwrite an existing file
     * @param aNode is any node within the node tree which is to be written
     * @return true on success
     */
    SGLIB_API bool WriteCache( const char* aFileName, bool overwrite, SGNODE* aNode,
        const char* aPluginInfo );

    /**
     * Function ReadCache
     * reads a binary cache file and creates an SGNODE tree
     *
     * @param aFileName is the name of the binary cache file to be read
     * @return NULL on failure, on success a pointer to the top level SCENEGRAPH node;
     * if desired this node can be associated with an IFSG_TRANSFORM wrapper via
     * the IFSG_TRANSFORM::Attach() function.
     */
    SGLIB_API SGNODE* ReadCache( const char* aFileName, void* aPluginMgr,
        bool (*aTagCheck)( const char*, void* ) );

    /**
     * Function WriteVRML
     * writes out the given node and its subnodes to a VRML2 file
     *
     * @param filename is the name of the output file
     * @param overwrite should be set to true to overwrite an existing VRML file
     * @param aTopNode is a pointer to a SCENEGRAPH object representing the VRML scene
     * @param reuse should be set to true to make use of VRML DEF/USE features
     * @return true on success
     */
    SGLIB_API bool WriteVRML( const char* filename, bool overwrite, SGNODE* aTopNode,
                    bool reuse, bool renameNodes );

    // NOTE: The following functions are used in combination to create a VRML
    // assembly which may use various instances of each SG* representation of a module.
    // A typical use case would be:
    // 1. invoke 'ResetNodeIndex()' to reset the global node name indices
    // 2. for each model pointer provided by 'S3DCACHE->Load()', invoke 'RenameNodes()' once;
    //    this ensures that all nodes have a unique name to present to the final output file.
    //    Internally, RenameNodes() will only rename the given node and all Child subnodes;
    //    nodes which are only referenced will not be renamed. Using the pointer supplied
    //    by 'S3DCACHE->Load()' ensures that all nodes but the returned node (top node) are
    //    children of at least one node, so all nodes are given unique names.
    // 3. if SG* trees are created independently of S3DCACHE->Load() the user must invoke
    //    RenameNodes() as appropriate to ensure that all nodes have a unique name
    // 4. create an assembly structure by creating new IFSG_TRANSFORM nodes as appropriate
    //    for each instance of a component; the component base model as returned by
    //    S3DCACHE->Load() may be added to these IFSG_TRANSFORM nodes via 'AddRefNode()';
    //    set the offset, rotation, etc of the IFSG_TRANSFORM node to ensure correct
    // 5. Ensure that all new IFSG_TRANSFORM nodes are placed as child nodes within a
    //    top level IFSG_TRANSFORM node in preparation for final node naming and output
    // 6. Invoke RenameNodes() on the top level assembly node
    // 7. Invoke WriteVRML() as normal, with renameNodes = false, to write the entire assembly
    //    structure to a single VRML file
    // 8. Clean up by deleting any extra IFSG_TRANSFORM wrappers and their underlying SG*
    //    classes which have been created solely for the assembly output

    /**
     * Function ResetNodeIndex
     * resets the global SG* class indices
     *
     * @param aNode may be any valid SGNODE
     */
    SGLIB_API void ResetNodeIndex( SGNODE* aNode );

    /**
     * Function RenameNodes
     * renames a node and all children nodes based on the current
     * values of the global SG* class indices
     *
     * @param aNode is a top level node
     */
    SGLIB_API void RenameNodes( SGNODE* aNode );

    /**
     * Function DestroyNode
     * deletes the given SG* class node. This function makes it possible
     * to safely delete an SG* node without associating the node with
     * its corresponding IFSG* wrapper.
     */
    SGLIB_API void DestroyNode( SGNODE* aNode );

    // NOTE: The following functions facilitate the creation and destruction
    // of data structures for rendering

    /**
     * Function GetModel
     * creates an S3DMODEL representation of aNode (raw data, no transforms)
     *
     * @param aNode is the node to be transcribed into an S3DMODEL representation
     * @return an S3DMODEL representation of aNode on success, otherwise NULL
     */
    SGLIB_API S3DMODEL* GetModel( SCENEGRAPH* aNode );

    /**
     * Function Destroy3DModel
     * frees memory used by an S3DMODEL structure and sets the pointer to
     * the structure to NULL
     */
    SGLIB_API void Destroy3DModel( S3DMODEL** aModel );

    /**
     * Function Free3DModel
     * frees memory used internally by an S3DMODEL structure
     */
    SGLIB_API void Free3DModel( S3DMODEL& aModel );

    /**
     * Function Free3DMesh
     * frees memory used internally by an SMESH structure
     */
    SGLIB_API void Free3DMesh( SMESH& aMesh );

    /**
     * Function New3DModel
     * creates and initializes an S3DMODEL struct
     */
    SGLIB_API S3DMODEL* New3DModel( void );

    /**
     * Function Init3DMaterial
     * initializes an SMATERIAL struct
     */
    SGLIB_API void Init3DMaterial( SMATERIAL& aMat );

    /**
     * Function Init3DMesh
     * creates and initializes an SMESH struct
     */
    SGLIB_API void Init3DMesh( SMESH& aMesh );
};
-----

For actual usage examples of the Scenegraph API see the
<<advanced-3d-plugin,Advanced 3D Plugin tutorial>> above and the KiCad VRML1, VRML2,
and X3D parsers.