[go: up one dir, main page]

0% found this document useful (0 votes)
222 views480 pages

Surfcam 2005 API

cam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
222 views480 pages

Surfcam 2005 API

cam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 480

Appl i cati on Pr ocedur al I nter face (API )

Dat ab ase F u n ct io n s
T o o l L ib rary F u n ct io n s
SURF CAM L ist b o x Dialo g F u n ct io n s
T o o lp at h F u n ct io n s

Date of last revision: 01/28/07 2:20 PM

 Copyright Surfware, Incorporated 2005. All Rights Reserved.


SURFCAM is a registered trademark and Surfware is a trademark of Surfware, Incorporated.

TSH/v 5-11
SURFCAM 2005 • API Documentation Table of Contents

iii
SURFCAM 2005 • API Documentation Table of Contents

Contents
Preface ......................................................................................................................................................... xi

Part I SURFCAM Database API

Chapter 1: Introduction .............................................................................................1


Introduction to the SURFCAM Database API.................................................................... 1
What is Required?............................................................................................................... 2
How the API Works............................................................................................................ 2
Accessing the SURFCAM Database of Elements .............................................................. 2
Interacting with SURFCAM ............................................................................................... 3
Miscellaneous Functions..................................................................................................... 3

Chapter 2: Step-By-Step Tutorial on Creating a Custom DLL ...............................4


Step 1: Preparing the SURFCAM.INI file .......................................................................... 4
Step 2: The DLL entry function must be defined in the program ....................................... 5
Step 3. Retrieving the SURFCAM database handle and window handle.......................... 7
Step 4: Reading from the database..................................................................................... 7
Step 5: Writing to the database .......................................................................................... 8
Step 6: Compiling considerations ...................................................................................... 8

Chapter 3: SURFCAM Symbols and Structures ......................................................9


Standared Symbols............................................................................................................. 9
Standard Strucutres .......................................................................................................... 11

Chapter 4: Function Summary Tables ..................................................................16


Memory Allocation Functions ........................................................................................... 17
List Functions .................................................................................................................... 18
Database Write and Retrieval Functions............................................................................ 19
Memory Stack Functions ................................................................................................... 20
Safe Functions.................................................................................................................... 20
SURFCAM Interface Functions ........................................................................................ 21
General Element Functions................................................................................................ 22
Element Evaluation Functions ........................................................................................... 23
Element Conversion Functions.......................................................................................... 26
Transformation Functions.................................................................................................. 27
Layer Functions.................................................................................................................. 28

i
Table of Contents SURFCAM 2005 • API Documentation

View Functions...................................................................................................................29
Vector Functions ................................................................................................................30
Point Functions...................................................................................................................32
Line Functions ....................................................................................................................33
Polyline Functions ..............................................................................................................33
Line Mesh Functions ..........................................................................................................34
Arc Functions .....................................................................................................................34
Conic Functions..................................................................................................................35
NURB Curve Functions .....................................................................................................35
NURB Surface Functions ...................................................................................................37

Chapter 5: SURFCAM API Function Descriptions ................................................ 39


scApp_GetCurrentColor...................................................................................................41
scApp_GetCurrentLayer...................................................................................................42
scApp_GetIniFileName .................................................................................................... ??
scApp_GetInstanceHandle ...............................................................................................43
scApp_GetNumOfLayers .................................................................................................44
scApp_GetTitle ................................................................................................................45
scApp_GetUnikKnots ......................................................................................................49
scApp_GetUnitType.........................................................................................................50
scApp_GetWindowHandle...............................................................................................46
scApp_LayerActive ..........................................................................................................47
scApp_LayerAlloc............................................................................................................48
scApp_LayerVisible .........................................................................................................49
scApp_ProcessDigtFile ....................................................................................................54
scApp_SelectionFinal.......................................................................................................50
scApp_SelectionInit .........................................................................................................51
scApp_ScanViewTable ....................................................................................................52
scApp_SetCurrentColor ...................................................................................................53
scApp_SetCurrentLayer ...................................................................................................54
scApp_SetModifiedFlag.......................................................................................................
scArc_3Points...................................................................................................................55
scArc_AllocMem .............................................................................................................56
scArc_WriteToDB............................................................................................................57
scConic_AllocMem..........................................................................................................58
scConic_TransformToStandard........................................................................................59
scCurve_Eval....................................................................................................................60
scCurve_EvalLengthFinal ................................................................................................61
scCurve_EvalLengthInit ...................................................................................................62
scCurve_GetRange ...........................................................................................................63
scDB_GetHandle..............................................................................................................64
scDB_GetHeader .............................................................................................................65
scDB_WriteHeader...........................................................................................................66

ii
SURFCAM 2005 • API Documentation Table of Contents

scDist_FpointFpoint......................................................................................................... 70
scDist_FpointFpoint2d..................................................................................................... 72

scDist_PointPoint ............................................................................................................ 67
scDist_PointPoint2dVec .................................................................................................. 68
scElement_DeleteElement ............................................................................................... 69
scElement_Final............................................................................................................... 70
scElement_GetArc ........................................................................................................... 71
scElement_GetColorAttrib .............................................................................................. 72
scElement_GetCount ....................................................................................................... 73
scElement_GetLayer........................................................................................................ 74
scElement_GetLayerAttrib ............................................................................................. 75
scElement_GetLine.......................................................................................................... 76
scElement_GetLmesh ...................................................................................................... 77
scElement_GetNurbCurve ............................................................................................... 78
scElement_GetNurbSurface............................................................................................. 79
scElement_GetPline......................................................................................................... 80
scElement_GetPoint......................................................................................................... 81
scElement_GetText...........................................................................................................??
scElement_GetType......................................................................................................... 82
scElement_GetTypeFromHandle..................................................................................... 83
scElement_GetVector ...................................................................................................... 84
scElement_GetView ........................................................................................................ 85
scElement_GetVisibleAttrib............................................................................................ 86
scElement_InitHandle...................................................................................................... 87
scElement_NextHandle ................................................................................................... 88
scElement_SetColorAttrib ............................................................................................... 89
scElement_SetColorAttribEx ........................................................................................ 102
scElement_SetLayerAttrib ............................................................................................... 91
scElement_SetLayerAttribEx........................................................................................... 92
scElement_ValidHandle .................................................................................................. 93
scElement_WriteToDB.................................................................................................... 94
scFVec_Add................................................................................................................... 229
scFVec_FPointFPoint .................................................................................................... 246
scFVec_Magnitude ........................................................................................................ 242
scFVec_Normalize......................................................................................................... 246
scFVec_Scale................................................................................................................. 252
scLayer_AllocMem.......................................................................................................... 95
scLayer_FindFreeLayer.................................................................................................... 96
scLayer_FindNextAllocLayer.......................................................................................... 97
scLayer_FindNextFreeLayer............................................................................................ 98
scLayer_GetAttrib............................................................................................................ 99
scLayer_GetFromHandle ............................................................................................... 106
scLayer_GetLayerFromHandle ...................................................................................... 100

iii
Table of Contents SURFCAM 2005 • API Documentation

scLayer_GetName ..........................................................................................................101
scLayer_SetLayerVisibility ..............................................................................................56
scLayer_WriteToDB.......................................................................................................102
scLine_AllocMem ..........................................................................................................103
scLine_WriteToDB ........................................................................................................104
scList_BackWalk............................................................................................................105
scList_Concat .................................................................................................................106
scList_Final ....................................................................................................................107
scList_GetHead ..............................................................................................................108
scList_GetNext ...............................................................................................................109
scList_GetPrev ...............................................................................................................110
scList_GetTail ................................................................................................................111
scList_Init .......................................................................................................................112
scList_InsertElement ......................................................................................................113
scList_InsertHead ...........................................................................................................114
scList_InsertTail .............................................................................................................115
scList_IsEmpty ...............................................................................................................116
scList_MoveElement......................................................................................................117
scList_MoveHead...........................................................................................................118
scList_MoveTail.............................................................................................................119
scList_NumElements......................................................................................................120
scList_Reinit...................................................................................................................142
scList_RemoveAll ..........................................................................................................121
scList_RemoveElement..................................................................................................122
scList_RemoveHead.......................................................................................................123
scList_RemoveTail.........................................................................................................124
scList_Sort......................................................................................................................125
scList_Walk....................................................................................................................126
scLmesh_AllocMem.......................................................................................................127
scLmesh_GetPoints ........................................................................................................128
scLmesh_WriteToDB.....................................................................................................129
scMat_GetRotation.........................................................................................................130
scMat_Identity................................................................................................................131
scMat_Inverse.................................................................................................................132
scMat_InverseTransform................................................................................................133
scMat_InverseTransform2d............................................................................................134
scMat_Multiply ..............................................................................................................135
scMat_OrthoInverse .......................................................................................................136
scMat_SetColumn ..........................................................................................................137
scMat_Transform ...........................................................................................................138
scMat_Transform2d .......................................................................................................139
scMat_Transpose............................................................................................................140
scMem_Alloc .................................................................................................................141
scMem_CheckAlloc .......................................................................................................142

iv
SURFCAM 2005 • API Documentation Table of Contents

scMem_CheckAllocList ................................................................................................ 143


scMem_CountAllocList................................................................................................. 144
scMem_Free................................................................................................................... 145
scMem_FreeAll ............................................................................................................. 146
scMem_Realloc ............................................................................................................. 147
scNcurve_AllocMem ..................................................................................................... 148
scNcurve_ArcToNurb.................................................................................................... 149
scNcurve_Break............................................................................................................. 150
scNcurve_ChainNurbs ................................................................................................... 151
scNcurve_Clamp............................................................................................................ 152
scNcurve_ConicToNurb ................................................................................................ 153
scNcurve_ConvertToArcLine........................................................................................ 168
scNcurve_ClipParam1 ................................................................................................... 154
scNcurve_ClipParam2 ................................................................................................... 155
scNcurve_ElementToNurb ............................................................................................ 156
scNcurve_EllipseToNurb............................................................................................... 155
scNcurve_EllipseXYToNurb......................................................................................... 156
scNcurve_FitNurb...........................................................................................................???
scNcurve_FromPointArray ............................................................................................ 157
scNcurve_FromPointList ............................................................................................... 158
scNcurve_GetPolyDisplayAttrib ................................................................................... 159
scNcurve_GetRationalAttrib ......................................................................................... 160
scNcurve_InterpPtsTans ................................................................................................ 161
scNcurve_JoinTwoNurbs............................................................................................... 162
scNcurve_ProjectLoop2Nsurf........................................................................................ 172
scNcurve_ProjectToNsurf.............................................................................................. 173
scNcurve_ProjectUVToNsurf........................................................................................ 178
scNcurve_RaiseOrder .................................................................................................... 180
scNcurve_RemoveKnots ............................................................................................... 163
scNcurve_Reverse.......................................................................................................... 164
scNcurve_SetPolyDisplayAttrib .................................................................................... 165
scNcurve_SetRationalAttrib .......................................................................................... 166
scNcurve_WriteToDB ................................................................................................... 167
scNsurf_AllocMem........................................................................................................ 168
scNsurf_Clamp .............................................................................................................. 207
scNsurf_ConvertToPolygon .......................................................................................... 169
scNsurf_Eval.................................................................................................................. 170
scNsurf_EvalCurvature.................................................................................................. 171
scNsurf_FitNurb ............................................................................................................ 188
scNsurf_FixDegeneration ....................................................................................................
scNsurf_GetArrowDisplayAttrib ................................................................................... 172
scNsurf_GetArrowPositionAttrib .................................................................................. 173
scNsurf_GetCutDirectionAttrib..................................................................................... 174
scNsurf_GetIsoNurb ...................................................................................................... 175

v
Table of Contents SURFCAM 2005 • API Documentation

scNsurf_GetNormalDirectionAttrib ...............................................................................176
scNsurf_GetNumberOfULinesAttrib .............................................................................177
scNsurf_GetNumberOfVLinesAttrib .............................................................................178
scNsurf_GetPolyDisplayAttrib.......................................................................................179
scNsurf_GetSpan............................................................................................................180
scNsurf_GetRange..........................................................................................................190
scNsurf_GetRationalAttrib.............................................................................................181
scNsurf_IsDegeneratedClosed........................................................................................195
scNsurf_NurbGrid ..........................................................................................................182
scNsurf_NurbListAutoSort.............................................................................................183
scNsurf_Offset................................................................................................................195
scNsurf_ProjectPoint………………………………………………………………….. 187
scNsurf_ProjectPointParam............................................................................................188
scNsurf_ProjectPointSide...............................................................................................215
scNsurf_RemoveKnots...................................................................................................184
scNsurf_Revolution........................................................................................................185
scNsurf_Ruled ................................................................................................................186
scNsurf_SetArrowDisplayAttrib ....................................................................................187
scNsurf_SetArrowPositionAttrib ...................................................................................188
scNsurf_SetCutDirectionAttrib ......................................................................................189
scNsurf_SetNormalDirectionAttrib................................................................................190
scNsurf_SetNumberOfULinesAttrib ..............................................................................191
scNsurf_SetNumberOfVLinesAttrib ..............................................................................192
scNsurf_SetPolyDisplayAttrib .......................................................................................193
scNsurf_SetRange ..........................................................................................................194
scNsurf_SetRationalAttrib .............................................................................................195
scNsurf_WriteToDB.......................................................................................................196
scPlane_VectorPoint ......................................................................................................197
scPline_AllocMem .........................................................................................................198
scPline_ElementToPline ................................................................................................199
scPline_WriteToDB .......................................................................................................200
scPoint_AllocMem.........................................................................................................201
scPoint_ArcEnd..............................................................................................................202
scPoint_GetMinMax ......................................................................................................227
scPoint_OppositeSideOfLine .........................................................................................203
scPoint_OppositeSideOfVector......................................................................................204
scPoint_PointVecParam .................................................................................................211
scPoint_ProjectToLine ...................................................................................................205
scPoint_ProjectToPlane..................................................................................................206
scPoint_WriteToDB .......................................................................................................207
scSafe_acos.....................................................................................................................208
scSafe_atof .....................................................................................................................209
scSafe_atoi......................................................................................................................210
scSafe_sprintf .................................................................................................................211

vi
SURFCAM 2005 • API Documentation Table of Contents

scSafe_sqrt ..................................................................................................................... 212


scSafe_strcat .................................................................................................................. 213
scSafe_strcpy ................................................................................................................. 214
scStack_Final ................................................................................................................. 215
scStack_Init.................................................................................................................... 216
scStack_Peek ................................................................................................................. 217
scStack_Pop ................................................................................................................... 218
scStack_Push ................................................................................................................. 219
scVec_Add..................................................................................................................... 220
scVec_Add2d................................................................................................................. 221
scVec_AddScaledVecs .................................................................................................. 222
scVec_AngleMinusPiPi ................................................................................................. 223
scVec_AngleZero2Pi ..................................................................................................... 224
scVec_AngleZeroPi ....................................................................................................... 225
scVec_AngleZeroPi2 ..................................................................................................... 226
scVec_BetweenVecVec ................................................................................................. 227
scVec_BetweenVecVec2d ............................................................................................. 228
scVec_Collinear............................................................................................................. 229
scVec_CrossProduct ...................................................................................................... 230
scVec_DotProduct ......................................................................................................... 231
scVec_Magnitude .......................................................................................................... 232
scVec_Magnitude2d ...................................................................................................... 239
scVec_MagnitudeCrossProduct..................................................................................... 233
scVec_Normalize........................................................................................................... 234
scVec_Normalize2d....................................................................................................... 235
scVec_PointPoint........................................................................................................... 236
scVec_PointPoint2d....................................................................................................... 237
scVec_ProjectToPlaneN ................................................................................................ 238
scVec_ProjectToPlaneNThroughVec ............................................................................ 239
scVec_Scale ................................................................................................................... 240
scVec_Scale2d ............................................................................................................... 241
scVec_Set_axis_vec....................................................................................................... 250
scVec_SinAngle............................................................................................................. 242
scView_AllocMem ........................................................................................................ 243
scView_ArbitraryAxis ................................................................................................... 244
scView_Arc ................................................................................................................... 245
scView_Compare........................................................................................................... 246
scView_GetCview ......................................................................................................... 247
scView_GetView ........................................................................................................... 248
scView_InitStandardView ............................................................................................. 249
scView_WorldToView… .............................................................................................. 250
scView_WriteToDB ...................................................................................................... 251
scXForm_Element ......................................................................................................... 295
scXForm_TranslateRel… .............................................................................................. 296

vii
Table of Contents SURFCAM 2005 • API Documentation

scXForm_TranslateAbs..................................................................................................297
scXForm_Rotate….........................................................................................................298
scXForm_Scale...............................................................................................................299
scXForm_ScaleXYZ ......................................................................................................300
scXForm_Mirror.............................................................................................................301
scXForm_TranslateRelUI...............................................................................................302
scXForm_TranslateAbsUI..............................................................................................303
scXForm_RotateUI.........................................................................................................304
scXForm_ScaleUI ..........................................................................................................305
scXForm_ScaleXYZUI ..................................................................................................306
scXForm_MirrorUI ........................................................................................................307
scXForm_TranslateRelUISel..........................................................................................308
scXForm_TranslateAbsUISel.........................................................................................309
scXForm_RotateUISel ...................................................................................................310
scXForm_ScaleUISel .....................................................................................................311
scXForm_ScaleXYZUISel .............................................................................................312
scXForm_MirrorUISel ...................................................................................................313
scXForm_ToViewUISel.................................................................................................314

Chapter 6: Sample Code...................................................................................... 253


Sample input translator code ..........................................................................................255
Sample output translator code ........................................................................................256
Sample code: Channel.cpp .............................................................................................257
Sample code: CADL to DSN translator .........................................................................265
Mainwin.cpp......................................................................................................................... 265
Mainwin.h ............................................................................................................................ 270
ReadElements.cpp................................................................................................................ 271
ReadElements.h.................................................................................................................... 284
CadlFunctions.cpp................................................................................................................ 286
CadlFunctions.h ................................................................................................................... 292

Part III SURFCAM Listbox API

Chapter 7: Introduction to the SURFCAM Listbox API...................................... 295


SURFCAM Listbox Dialog Layout................................................................................295
Creating the Listbox Dialog ...........................................................................................296
Writing Text to the Dialog .............................................................................................297
Completing the Dialog ...................................................................................................297
Compiling and Linking Considerations..........................................................................297

viii
SURFCAM 2005 • API Documentation Table of Contents

Chapter 8: Listbox API Function Descriptions ..................................................298


FinalListBox .................................................................................................................. 299
GetAbortStatus............................................................................................................... 300
InitListBox ..................................................................................................................... 301
lb_printf ......................................................................................................................... 302
put_end_message ........................................................................................................... 303
SetListBoxButtons ......................................................................................................... 304
WaitForEnd.................................................................................................................... 305

Part III SURFCAM Tool Library API

Introduction to the SURFCAM Tool Library API......................................................... 313


Tool Library Structures.................................................................................................. 314
TOOLLIBS.H Symbolic Constants ............................................................................... 314
TOOLLIBS.H Structures ............................................................................................... 316
Tool Design File Data Structure .................................................................................... 316
Mill Tool Data Structure................................................................................................ 316
Lathe Tool Data Structure.............................................................................................. 318
Cutter Data Structure ..................................................................................................... 319
Material Data Structure.................................................................................................. 320
Mill Tool API................................................................................................................. 321
Choosing A Mill Tool: ToolLib_nGetMillTool function .............................................. 321
Loading a Mill Tool: ToolLib_nLoadMill function ...................................................... 321
Drill Tool API................................................................................................................ 322
Choosing a Drill Tool: ToolLib_nGetDrillTool function.............................................. 322
Loading a Drill Tool: ToolLib_nLoadDrillTool function.............................................. 322
Lathe Tool API .............................................................................................................. 323
Choosing a Lathe Tool: ToolLib_nGetLatheTool function ........................................... 323
Loading a Lathe Tool: ToolLib_nLoadLatheTool function........................................... 323
Lathe Drill Tool API...................................................................................................... 324
Choosing a Lathe Drill Tool: ToolLib_nGetLDrillTool function ................................. 324
Loading a Lathe Drill Tool: ToolLib_nLoadLDrillTool function ................................. 324
Digitizer Tool API ......................................................................................................... 325
Choosing a Digitizer Tool: ToolLib_nGetDgtzTool function ....................................... 325
Loading a Digitizer Tool: ToolLib_nLoadDgtzTool function....................................... 325
EDM Tool API............................................................................................................... 326
Choosing a EDM Tool: ToolLib_nGetEdmTool function............................................. 326
Loading a EDM Tool: ToolLib_nLoadEdmTool function ............................................ 326
Tool API Additional Functions...................................................................................... 327
Choosing a Tool By Type: ToolLib_nGetTool function ............................................... 327
Loading a Tool By Type: ToolLib_nLoadTool function ............................................... 327
Choosing a Material: ToolLib_nGetMaterial function .................................................. 328

ix
Table of Contents SURFCAM 2005 • API Documentation

Loading a Material: ToolLib_nLoadMaterial function ..................................................328


Getting Current Tool Units Type: ToolLib_nGetToolUnits function ............................329
Setting New Tool Units Type: ToolLib_nSetToolUnits function ..................................329

Sample Tool Library Code .............................................................................................329

x
SURFCAM 2005 • API Documentation Table of Contents

Part IV SURFCAM Tool Library API

Chapter 9: Introduction to the SURFCAM Toolpath API....................................337


Toolpaths in SURFCAM ............................................................................................... 337
INC File Naming Convention........................................................................................ 338
Anatomy of an INC file ................................................................................................. 339
INC Records................................................................................................................... 339
Tables of SURFCAM INC Records .............................................................................. 341
Writing a SURFCAM Toolpath API DLL..................................................................... 347

Chapter 10: SURFCAM Toolpath API Function Descriptions ...........................351


scNCOp_CreateOperation ............................................................................................. 353
scNCOp_CreateOperationToo....................................................................................... 354
scNCOp_SetCurrentDesc .............................................................................................. 355
scNCOp_CommitOperation........................................................................................... 356
scNCOp_CommitBeforeLastOperation ...............................................................................
scNCOp_ReleaseOperation ........................................................................................... 357
scNCOp_GetItemPacketHandle ..........................................................................................
scNCOp_OpenNCProjectItem.............................................................................................
scNCOp_SelectNCProjectItem............................................................................................
scNCOp_GetOpSectionName ....................................................................................... 377
scNCOp_AddSetupSection..................................................................................................
scICDAPI_Query ........................................................................................................... 378
scICDAPI_Open ............................................................................................................ 358
scICDAPI_Eof ............................................................................................................... 359
scICDAPI_Getc ............................................................................................................. 360
scICDAPI_Putc.............................................................................................................. 361
scICDAPI_Read............................................................................................................. 362
scICDAPI_Write............................................................................................................ 363
scICDAPI_Seek ............................................................................................................. 364
scICDAPI_Tell .............................................................................................................. 365
scICDAPI_Close............................................................................................................ 366
scICDAPI_Erase ..................................................................................................................
scICDAPI_SetSize...............................................................................................................
scICDAPI_Clone .................................................................................................................

Chapter 11: SURFCAM Toolpath API Sample Code ..........................................369


Sample code: Writing to an INC file ............................................................................. 371
Sample code: Reading from an INC file........................................................................ 279

xi
Table of Contents SURFCAM 2005 • API Documentation

xii
SURFCAM 2005 • API Documentation Table of Contents

Preface

This volume contains the full documentation for three separate SURFCAM
application programming interfaces (APIs) in three parts. Part I documents the
SURFCAM Database API, which allows access to SURFCAM’s geometry
functions and element database. Part II documents the SURFCAM Listbox dialog
API. Part III contains information on the SURFCAM Tool and Materials Library
API.

SURFCAM also provides access to the tool and materials library through the API.
The tools and materials in the tool and materials library can be retrieved as data
structures, or retrieved through the graphical user interface provided in the tool
library Dynamic Link Library (DLL). More complete management of the tool and
materials databases can be provided by standard ODBC software tools.

xiii
Table of Contents SURFCAM 2005 • API Documentation

xiv
SURFCAM 2005 • API Documentation Table of Contents

Part I

xv
Table of Contents SURFCAM 2005 • API Documentation

xvi
SURFCAM 2005 • API Documentation Chapter 9 Toolpath API

Chapter 1
Introduction

INTRODUCTION TO THE SURFCAM DATABASE API


SURFCAM’s Application Programming Interface (API) allows
third-party applications access to selected SURFCAM functions. API
The ability to utilize SURFCAM’s powerful geometric construction Application
and manipulation functions directly permits advanced SURFCAM Programming
users and programmers to create flexible custom applications suited Interface
best to their specialized needs. Some examples of possible applications include
file translators (both to and from SURFCAM design file format), “family of parts”
applications, applications that filter out selected geometries, colors, or layers from
existing design files, etc. The fact that the SURFCAM file translators that ship
with SURFCAM 2005 were written using solely the API functions demonstrates
the practical usability of SURFCAM’s API.

The scope of the database API functions focuses on creating, retrieving, and
manipulating elements in the database of SURFCAM geometric entities. After
first constructing or retrieving a database of SURFCAM elements, the elements
(such as points, lines, splines, and NURB surfaces) can be scaled, mirrored, and
transformed in various ways. There are functions that retrieve and modify the
layer and color properties of elements, that measure the distances between points
in space and control points of a NURB surface, that determine the slope of a
NURB surface at a particular location. SURFCAM’s API provides functions to
easily manage the list of elements in the database, allowing functions to be
applied to specified elements in the list.

Utilizing SURFCAM’s API requires knowledge of software programming.


Because the functions in the API are accessed using C language header files the C
and C++ programming environments are recommended. Other languages which
can access C language functions are also acceptable.

1
Chapter 1 Introduction SURFCAM 2005 • API Documentation

WHAT IS REQUIRED?
In order to take advantage of SURFCAM’s API, the programmer will require a
licensed copy of SURFCAM V7.0A Build 106 or higher. The programmer will
also require four header files: expfunc.h, dllstrct.h, dllelems.h, and stackdll.h.

HOW THE API WORKS


The database API is exclusively accessed through the FileOpen and FileSaveAs
dialogs in SURFCAM. After accepting the parameters of the FileOpen or
FileSaveAs dialogs, SURFCAM loads the correct DLL associated with each file
type (specified in the SURFCAM.INI file) and executes the entry function within
the specified DLL. The arguments of the function include the filename, the path
to the SURFCAM.INI file, and the INI file key.

ACCESSING THE SURFCAM DATABASE


SURFCAM stores all of its geometry information in memory as a database of
elements. The API provides read and write access to this database (note that the
API cannot delete elements from the database). After using the API call
scDB_GetHandle to retrieve the handle to the database, the API function
scDB_NextHandle may be called to retrieve successive element handles from the
database. These element handles can be queried for the type of element they
represent using the function scElement_GetTypeFromHandle, and subsequently
the element information can be extracted into data structures using the appropriate
element function (scElement_GetArc, scElement_GetNurbCurve, etc.)

Writing to the SURFCAM database requires special consideration of element


memory allocation. SURFCAM elements are defined as data structures, with each
element type having a corresponding data structure. The API functions that
manipulate elements use pointers to these structures, and require only the data
members specific to that structure, such as the x, y, and z coordinates of an
SC_Point structure. However, the database also requires color and layer
information which is not contained in the standard data structures. Thus, when an
element is created that is intended to be written to the SURFCAM database, it
must be created using an AllocMem function. Each element has an AllocMem
function (scPoint_AllocMem, scLine_AllocMem, scNcurve_AllocMem, etc.)
which allocates not only the data members of the structure, but also the layer and
color information for that structure. An element created in this manner can later
be stored using the appropriate WriteToDB function, again specific to each

2
SURFCAM 2005 • API Documentation Chapter 1 Introduction

element (scPoint_WriteToDB, scNsurf_WriteToDB, etc.). Elements created


using AllocMem functions must also be destroyed using the scElement_Final
function after being written to the database in order to free the allocated memory.

INTERACTING WITH SURFCAM


The API allows direct manipulation of SURFCAM for certain operations. Vital
information such as handles to the SURFCAM window and SURFCAM database
are accessible, as well as current color and layer information. In addition,
additional layers may be added and the current color and layer may be changed.

MISCELLANEOUS FUNCTIONS
The API also has a group of functions to create and manipulate general lists and
general stacks. After initializing a list, the list as accessed through its handle.
Functions to add and remove list elements manipulate the list contents, and
operations such as sort and reverse can be performed on the list. Stacks are
simpler forms of lists, with only push, pop, and peek operations.

Because matrix operations are so critical in manipulating geometry, the API


includes standard functions to process matrices. These matrix functions use
standard four-by-four location and transformation matrices.

There are also “safe” functions in the API. These functions are versions of their
standard counterparts with extended error checking, preventing runtime errors and
allowing wider ranges of input values.

3
Chapter 2 Step-By-Step Tutorial SURFCAM 2005 • API Documentation

Chapter 2
Step-By-Step
Tutorial on Creating
a Custom DLL

A Dynamic Link Library (DLL) must satisfy several conditions in order to take
advantage of the SURFCAM API. The SURFCAM API functions are based on
the C computer language, therefore a C or C++ development environment is
recommended. DLLs created using the API functions are accessible only through
SURFCAM’s FileOpen and FileSaveAs dialogs. The required steps necessary to
create a DLL using the SURFCAM API are as follows:

STEP 1. PREPARE THE SURFCAM.INI FILE

SURFCAM will not recognize nor call any custom DLL without an entry in the
SURFCAM.INI file. Open this file and examine the last section, headed by the
string “[FileOpenSave]”.
[FileOpenSave]
DSN=DSN Files(*.DSN), "*.dsn;*.tle;*.tlm;*.tmp",,,dsnread,dsnwrite,C:\surfcam\dsn,APPEND_FALSE
...
IGS=IGS Files(*.IGS),
"*.igs",igs2dsn.dll,dsn2igs.dll,SurfcamDllEntryPoint,SurfcamDllEntryPoint,C:\surfcam\igs,APPEND_FALSE
...

4
SURFCAM 2005 • API Documentation Chapter 2 Step-By-Step Tutorial

Each file type is associated with a “key”, which identifies each entry to
SURFCAM. Each key holds eight different entries.
1. The file type entry as it will appear in the FileOpen or FileSaveAs dialog.
2. The extension of the file type, which filters the files shown in the FileOpen or FileSaveAs
dialog.
3. The DLL called by SURFCAM after selecting a file in FileOpen.
4. The DLL called by SURFCAM after selecting a file in FileSaveAs.
5. The name of the entry function called first by SURFCAM (see Step 2 below) in the DLL
called after FileOpen.
6. The name of the entry function called first by SURFCAM (see Step 2 below) in the DLL
called after FileSaveAs.
7. The default directory for the FileOpen or FileSaveAs dialog.
8. The default value for the Append flag in the FileOpen dialog. Append preserves the existing
database of elements.

The IGES file type, for example, has the key “IGS”. SURFCAM is instructed to
call the DLL igs2dsn.dll after the FileOpen dialog, and the DLL dsn2igs.dll after
the FileSaveAs dialog. The name of the entry function in igs2dsn.dll is
SurfcamDllEntryPoint. The name of the entry function in dsn2igs.dll is also
SurfcamDllEntryPoint. IGES files are normally stored in the C:\surfcam\igs
directory.

The form for any custom DLL must be similar. For example, a DLL to take
existing geometry and create a family of parts using settings stored in files of type
“.fam” or “.txt” would only be used after a FileOpen. A valid addition to the INI
file would be similar to the following:
FAM=FAM Files(*.fam), “*.fam;*.txt”,family.dll,,MyDllEntryFunction,,C:\MyDirectory,APPEND_TRUE

STEP 2. THE DLL ENTRY FUNCTION MUST BE DEFINED IN THE PROGRAM

SURFCAM calls the entry function within the custom DLL from the FileOpen or
FileSaveAs dialogs. SURFCAM knows the name of the entry function from the
SURFCAM.INI file, so the name of the entry function will correspond to that
character string. SURFCAM passes three arguments to this function; the
arguments for this function MUST be the following (in this order):

1. char * (the name of the SURFCAM.INI file including full path)


2. char * (the coded section name and key within the INI file)
3. char * (the filename – including full path – from the FileOpen or FileSaveAs dialog)

5
Chapter 2 Step-By-Step Tutorial SURFCAM 2005 • API Documentation

The coded section name consists of the section in the INI file and the file type key
associated with the DLL call – this key is appended after the section name. In the
IGES translator, for example, the passed section name string would be
“FileOpenSave_IGS”.

The function must also return an integer, so an example of a valid function


prototype is the following:

int MyDllEntryFunction(char *, char *, char *);

A final consideration is function decoration, or function mangling. If the program


is being developed in a C++ environment, be sure to enclose the entry function
with an extern “C”.

The following is an example of the most basic entry function. Note that the
character strings were not used in this particular example.

#if defined(__cplusplus)
extern "C"
{
#endif

__declspec(dllexport) int
MyDllEntryFunction(char *ini_file_name,
char *section_name,
char *file_name)
{
MyMainFunction(); // Main function

return(TRUE);
}

#if defined(__cplusplus)
}
#endif

STEP 3. RETRIEVING THE SURFCAM DATABASE HANDLE AND WINDOW HANDLE

Although Steps 1 and 2 provide all the steps necessary to access the API
functions, the functions will have minimal utility without access to the
SURFCAM database of elements. The API provides both the function and the
handle variable to permit the DLL to both read from and write to the database.
The handle type is HSC_DB. Use the function scDB_GetHandle( ) to retrieve
the SURFCAM database handle. The database handle is used for all functions
involving reading from and writing to the database.

6
SURFCAM 2005 • API Documentation Chapter 2 Step-By-Step Tutorial

HSC_DB hSurfcamDatabase;

hSurfcamDatabase = scDB_GetHandle();

Retrieving the handle to the SURFCAM window uses a similar process. The
window handle is used for Win32 API functions for Windows 95 and Windows
NT environments.

HWND hSurfcamWindow;

hSurfcamWindow = scApp_GetWindowHandle();

STEP 4. READING FROM THE DATABASE

The elements in the database can be accessed through their handles. At present,
the program must use two functions to retrieve element handles:
scElement_InitHandle and scElement_NextHandle. In order to walk through
the entire database of elements, a loop such as the following is recommended.

HSC_Element hSurfcamElement;

for (hSurfcamElement = scElement_InitHandle(hSurfcamDatabase);


scElement_ValidHandle(hSurfcamElement);
hSurfcamElement = scElement_NextHandle(hSurfcamElement))
{
...
}

This loop will iterate the element handle for every element in the database. The
element handle may either be stored in a list, or the element data may be read
from the handle within the loop.

Reading the element data from the element handle requires two steps: the type of
element must be determined, then the data must be read into the appropriate
element data structure.

if(scElement_GetTypeFromHandle(hSurfcamElement) == SC_Point) {
SC_Point *Point;
Point = scElement_GetPoint(hSurfcamElement);
...
}

7
Chapter 2 Step-By-Step Tutorial SURFCAM 2005 • API Documentation

STEP 5. WRITING TO THE DATABASE

Elements in the SURFCAM database possess information beyond that in the basic
data structures. Each element also has color and layer assignment data; therefore,
writing just the element data structure to the database is insufficient. In order to
create an element that contains this information, the AllocMem functions must be
used.

For each SURFCAM element, there is an AllocMem function. When creating


elements to write to the database, you MUST use the AllocMem functions, rather
than declaring the element as a type. For example, to create a point element, the
correct method would be the following:
SC_Point * pPoint;

pPoint = scPoint_AllocMem();

rather than:

SC_Point Point;

Elements created using AllocMem may be properly written to the database using
WriteToDB functions.

STEP 6. COMPILING AND LINKING CONSIDERATIONS

Each file that uses SURFCAM API functions must include the expfunc.h header
file. The files expfunc.h, stackdll.h, dllstrct.h and dllelems.h must reside in the
compiler include directory. The linker must link to the API library.

8
SURFCAM 2005 • API Documentation Chapter 3 SURFCAM Symbols and Structures

Chapter 3
SURFCAM Symbols
and Structures

SURFCAM STANDARD SYMBOLS


SURFCAM uses several standard symbols and structures in the source code. You
may recognize these as #define preprocessor statements. Standard symbols
promote clarity and simplify the programming and debugging process; using
standard symbols rather than their corresponding values is highly recommended.
As a reference, the standard symbols and their corresponding values are listed
below. See dllelems.h for source code.

Table 2.1: SURFCAM Element Types

Symbol Description Value


SC_POINT SURFCAM Point element 1
SC_LINE SURFCAM Line element 2
SC_PLINE SURFCAM Polyline element 3
SC_LMESH SURFCAM Line mesh element 4
SC_LAYER SURFCAM Layer 6
SC_ARC SURFCAM Arc element 7
SC_VIEW SURFCAM View 9
SC_TOOL SURFCAM Tool 10
SC_SUL SURFCAM Composite Surface element 11
SC_NCURVE SURFCAM NURB Curve element 12
SC_NSURF SURFCAM NURB Surface element 13
SC_TEXT SURFCAM Text 14
SC_VECTOR SURFCAM Vector element 15
SC_DIM_STYLE SURFCAM Dimension Style 16
SC_DIM_ENTITY SURFCAM Dimension Entity 17
SC_CONIC SURFCAM Conic element 18
SC_ELEMSIZE SURFCAM element size 19

9
Chapter 3 SURFCAM Symbols and Structures SURFCAM 2005 • API Documentation

Table 2.2: SURFCAM Colors

Symbol Description Value


BLACK Color black 0
DARKBLUE Color dark blue 1
DARKGREEN Color dark green 2
DARKCYAN Color dark cyan 3
DARKRED Color dark red 4
DARKMAGENTA Color dark magenta 5
DARKYELLOW Color dark yellow 6
LIGHTGRAY Color light gray 7
DARKGRAY Color dark gray 8
BRIGHTBLUE Color bright blue 9
BRIGHTGREEN Color bright green 10
BRIGHTCYAN Color bright cyan 11
BRIGHTRED Color bright red 12
BRIGHTMAGENTA Color bright magenta 13
BRIGHTYELLOW Color bright yellow 14
WHITE Color white 15
INVALID_COLOR Invalid color -1

Table 2.3: NURB Surface and NURB Curve Symbols

Symbol Description Value


NATURAL Natural curve direction 0
REVERSED Reversed curve direction 1
U_DIRECTION U parameter curve direction 0
V_DIRECTION V parameter curve direction 1
ULOW_VLOW Surface corner with low U, low V parameters 0
UHIGH_VLOW Surface corner with high U, low V parameters 1
ULOW_VHIGH Surface corner with low U, high V parameters 2
UHIGH_VHIGH Surface corner with high U, high V parameters 3
OFF Display off 0
ON Display on 1

10
SURFCAM 2005 • API Documentation Chapter 3 SURFCAM Symbols and Structures

SURFCAM STANDARD STRUCTURES


SURFCAM stores geometry information in structures. It is necessary to be
familiar with the following structures in order to utilize most of the SURFCAM
API functions. See the file dllstruct.h for the source code defining the structures.

Table 2.4 HSC_Element Structure Members

Type Member Description


1
HSC_DB hDB Handle to SURFCAM database
unsigned long hEl Handle to element in SURFCAM database

Table 2.5 SC_Header Structure Members

Type Member Description


unsigned short version SURFCAM database version number
char [2] reserved Reserved for SURFCAM use
char [32] author Name of the file’s author
char [8] sversion SURFCAM version number
char [40] title The title of the design

Table 2.6 SC_Point and SC_DirVector Structure Members

Type Member Description


double x X coordinate in space
double y Y coordinate in space
double z Z coordinate in space

Table 2.7 SC_Vector Structure Members

Type Member Description


SC_Point start Starting coordinates in space
SC_DirVector dir Direction vector w.r.t. starting coordinates

1
HSC_DB is an unsigned long

11
Chapter 3 SURFCAM Symbols and Structures SURFCAM 2005 • API Documentation

Table 2.8 SC_Line Structure Members

Type Member Description


SC_Point start Starting point of line in space
SC_Point end Ending point of line in space

Table 2.9 SC_Arc Structure Members

Type Member Description


SC_Point center Center point of arc in space
SC_DirVector normal Normal vector (plane of arc)
SC_DirVector begin Vector defining the beginning of the arc
double angle Angle of arc sweep
double radius Radius of the arc

Table 2.10 SC_PLine Structure Members

Type Member Description


unsigned int n Number of points in polyline
SC_Point * p_SC_Point Pointer to array of polyline points

Table 2.11 SC_LMesh Structure Members

Type Member Description


unsigned int n Number of rows of points in line mesh
unsigned int m Number of columns of points in line mesh
SC_Point * p_SC_Point Pointer to array of line mesh points

Table 2.12 SC_Layer Structure Members

Type Member Description


char [30] name Name and attributes of layer

Table 2.13 SC_NurbPoint Structure Members

Type Member Description


double w Weight of NURB control point
SC_Point point Coordinates of NURB control point

12
SURFCAM 2005 • API Documentation Chapter 3 SURFCAM Symbols and Structures

Table 2.14 SC_NurbCurve Structure Members

Type Member Description


unsigned int order Order of NURB curve
unsigned int npts Number of control points
double startu Starting parametric value U
double endu Ending parametric value U
SC_NurbPoint * p_SC_NPoint Pointer to array of NURB control points
double * p_knot Array of knot points on the NURB curve

Table 2.15 SC_View Structure Members

Type Member Description


char [30] name The name of the view
unsigned int view The reference number of the view
double [4][4] view_matrix Orthogonal view matrix associated with view
double depth Distance of plane from origin

Table 2.16 SC_NurbSurface Structure Members

Type Member Description


unsigned int orderu Order of U parameter NURB curves
unsigned int orderv Order of V parameter NURB curves
unsigned int nptsu Number of U curve control points
unsigned int nptsv Number of V curve control points
double startu Starting parametric value U
double endu Ending parametric value U
double startv Starting parametric value V
double endv Ending parametric value V
SC_NurbPoint * p_SC_NPoint Pointer to array of NURB control points
double * p_uknot Array of knot points on the U curve
double * p_vknot Array of knot points on the V curve
ll_handle * region_list List of regions independent of surface

Table 2.17 SC_Gpv_param_type Structure Members

Type Member Description


double u Parametric U value at a point on the surface
double v Parametric V value at a point on the surface

Table 2.18 SC_Gcrv_param_type Structure Members

Type Member Description

13
Chapter 3 SURFCAM Symbols and Structures SURFCAM 2005 • API Documentation

double u Parametric U value of a point on the curve

Table 2.19 SC_Gpv_param_type Structure Members

Type Member Description


SC_Gpv_param_type start Parametric values at the first location on the
surface
SC_Gpv_param_type end Parametric values at the second location on
the surface

2
Table 2.20 SC_Conic Structure Members

Type Member Description


double a, b, c, d, e, f Coefficients of conic equation:
2 2
ax + bxy + cy + dx + ey + f = 0
double zt Z coordinate of plane of conic element
double x1, y1 X and Y coordinates of starting point of conic
double x2, y2 X and Y coordinates of ending point of conic

Table 2.21 SC_Triangle Structure Members

Type Member Description


long [3] index Index to vertices points

Table 2.22 SC_Polygon Structure Members

Type Member Description


long vts_num Number of vertices
SC_Point * vts_array Array of vertices
long triangle_num Number of triangles in polygon
SC_Triangle * triangles Array of triangles in polygon

Table 2.23 SC_Plane Structure Members

Type Member Description


double a Normal vector component in “i” direction
double b Normal vector component in “j” direction
double c Normal vector component in “k” direction

2
Note that SC_Conic elements can only be defined in the X-Y plane. To define a conic element
outside of the X-Y plane, the conic element must first be defined in the X-Y plane, and then
transformed.

14
SURFCAM 2005 • API Documentation Chapter 3 SURFCAM Symbols and Structures

double d Distance from origin along normal vector

Table 2.23 ll_element Structure Members

Type Member Description


ll_element * next Pointer to next list element
ll_element * prev Pointer to previous list element
int datasize Size of list element
char [0] data List data

Table 2.23 ll_handle Structure Members

Type Member Description


ll_element * head Pointer to first (head) list element
ll_element * tail Pointer to last (tail) list element
ll_element * curr Pointer to current list element
int els Total number of elements in list

15
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

Chapter 4
Function Summary
Tables

The functions available through SURFCAM’s API are summarized in the


following tables. The tables are divided by functionality groups, and list the
names of the function, the descriptions of the actions of the functions, and the
page number where the complete description of the function may be found. See
the header file expfunc.h for the source code.

16
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Memory Allocation Functions


Memory allocation functions
scMem_Alloc General memory allocation function, creating a temporary memory 139
block.

Memory deallocation functions


scMem_Free Frees memory block at a specified address allocated by SURFCAM. 143
scMem_FreeAll Frees all memory allocated by the DLL. 144
scElement_Final Frees memory block for an element. Follows element allocation 70
functions such as scArc_AllocMem, scConic_AllocMem, etc…

Memory reallocation function


scMem_Realloc Reallocates memory by moving a specified memory block from one 145
address to another.

Memory evaluation functions


scMem_CheckAlloc Checks to see if memory was allocated by SURFCAM at a specified 140
address.
scMem_CheckAllocList Checks the validity of the “malloc” allocated list (i.e. checks all the 141
memory blocks allocated by SURFCAM).
scMem_CountAllocList Counts the number of memory allocations made by SURFCAM. 142

Element memory allocation functions


scArc_AllocMem Allocates memory for an arc. 56
scConic_AllocMem Allocates memory for a conic element. 58
scLayer_AllocMem Allocates memory for a layer. 95
scLmesh_AllocMem Allocates memory for a line mesh. 127
scNcurve_AllocMem Allocates memory for a NURB curve. 146
scNsurf_AllocMem Allocates memory for a NURB surface. 167
scPline_AllocMem Allocates memory for a polyline. 196
scPoint_AllocMem Allocates memory for a point. 199
scView_AllocMem Allocates memory for a view. 241

17
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

List Functions
List memory allocation functions
scList_Init Allocates memory and initializes the list. 112
scList_Final Deletes the list and free the memory used by the list. 107

List manipulation functions


scList_InsertHead Inserts an element at the head of the list. 114
scList_InsertTail Inserts an element at the tail of the list. 115
scList_InsertElement Inserts an element at a specified location within the list. 113
scList_Reinit Reinitialize the list 136
scList_RemoveAll Removes all current elements. 121
scList_RemoveHead Removes an element from the head of the list. 123
scList_RemoveTail Removes an element from the tail of the list. 124
scList_RemoveElement Removes an element from a specified location within the list. 122
scList_MoveHead Moves an element to the head of the list. 118
scList_MoveTail Moves an element to the tail of the list. 119
scList_MoveElement Moves an element from one list to another, or within the list. 117

List evaluation functions


scList_GetHead Retrieves the value of an element at the head of the list. 108
scList_GetTail Retrieves the value of an element at the tail of the list. 111
scList_GetNext Retrieves the value of the next element within the list. 109
scList_GetPrev Retrieves the value of the previous element within the list. 110
scList_NumElements Retrieves the number of elements within the list. 120
scList_IsEmpty Checks to see if the list is currently empty. 116

List operation functions


scList_Walk Walks forward through the list, using each value as the 126
argument for a specified function.
scList_BackWalk Walks backward through the list, using each value as the 105
argument for a specified function.
scList_Sort Sorts the list according to a specified function. 125
scList_Concat Concatenates two lists together, destroying the second list. 106

18
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Database Write and Retrieval Functions


Database handle functions
scDB_GetHandle Gets the database handle. 63
scDB_GetHeader Gets the database header. 64
scDB_WriteHeader Writes the database header. 65

Read into database function


scApp_GetTitle Reads in the title of the window. 45
scApp_ProcessDigtFile //To Do, By Anil 54
scApp_ScanViewTable Scans the view table from the database. 50

Element handle functions


scElement_InitHandle Initializes an element handle. 87
scElement_NextHandle Returns the next element handle from the database. 88
scElement_ValidHandle Determines whether an element handle is valid. 93
scElement_GetTypeFromHandle Determines the type of an element (arc, line, point, etc.) from 83
the element handle.

Database retrieval functions


scElement_GetArc Retrieves an arc from the database. 71
scElement_GetColorAttrib Retrieves the color of an element from the database. 72
scElement_GetColorAttribEx Retrieves the color of an element from the database. ??
scElement_GetCount Retrieves the total number of elements from the database. 73
scElement_GetLayer Retrieves a layer from the database. 74
scElement_GetLayerAttrib Retrieves the attributes of a layer from the database. 75
scElement_GetLine Retrieves a line from the database. 76
scElement_GetLmesh Retrieves a line mesh from the database. 77
scElement_GetNurbCurve Retrieves a NURB curve from the database. 78
scElement_GetNurbSurface Retrieves a NURB surface from the database. 79
scElement_GetPline Retrieves a polyline from the database. 80
scElement_GetPoint Retrieves a point from the database. 81
scElement_GetText Retrieves a text from the database. ??
scElement_GetVector Retrieves a vector from the database. 84
scElement_GetView Retrieves a view from the database. 85

Database deletion function


scElement_DeleteElement Retrieves a view from the database. 69

19
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

Database write functions


scArc_WriteToDB Writes an arc to the database. 57
scElement_WriteToDB Writes an element to the database. 94
scLayer_WriteToDB Writes a layer to the database. 102
scLine_WriteToDB Writes a line to the database. 104
scLmesh_WriteToDB Writes a line mesh to the database. 129
scNcurve_WriteToDB Writes a NURB curve to the database. 167
scNsurf_WriteToDB Writes a NURB surface to the database. 196
scPline_WriteToDB Writes a polyline to the database. 200
scPoint_WriteToDB Writes a point to the database. 207
scView_WriteToDB Writes a view to the database. 252

Memory Stack Functions


Memory stack functions
scStack_Init Initializes the memory stack. 217
scStack_Push Pushes an element onto the top of the memory stack. 220
scStack_Pop Pops an element from the top of the memory stack. 219
scStack_Peek Peeks at the element on top of the memory stack. 218
scStack_Final Deletes the memory stack, freeing up the memory. 216

Safe Functions
Safe functions
scSafe_acos Returns the arc-cosine of a number, returning acos(1) for 209
numbers greater than 1 and acos(-1) for numbers less than -1.
scSafe_atof Returns a floating point decimal, clipping excess characters. 210
scSafe_atoi Returns an integer, clipping excess characters. 211
scSafe_sprintf Prints a string to a buffer, clipping excess characters. 212
scSafe_sqrt Returns the square-root of a number or zero. 213
scSafe_strcat Concatenates two strings, clipping excess characters. 214
scSafe_strcpy Copies two strings, clipping excess characters. 215

20
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

SURFCAM Interface Functions


Retrieve information from SURFCAM application
scApp_GetCurrentColor Gets the current color from SURFCAM. 41
scApp_GetCurrentLayer Gets the current layer from SURFCAM. 42
scApp_GetIniFileName Get Surfcam ini file name ??
scApp_GetInstanceHandle Gets the DLL handle from SURFCAM. 43
scApp_GetNumLayers Gets the number of layers. 44
scApp_GetTitle Reads in the window title from SURFCAM. 45
scApp_GetWindowHandle Gets the window handle from SURFCAM. 46
scApp_LayerActive Checks to see whether a specified layer is active. 47
scApp_LayerAlloc Checks to see whether a specified layer is allocated memory. 48
scApp_LayerVisible Checks to see whether a specified layer is visible. 49

Sets SURFCAM attributes


scApp_SetCurrentColor Sets the current color for SURFCAM. 53
scApp_SetCurrentLayer Sets the current layer for SURFCAM. 54
scApp_SetModifiedFlag Set Surfcam database dirty (modified) ??
scLayer_SetLayerVisibility Sets the given layer Visible/Invisible 56

SURFCAM query functions


scLayer_FindFreeLayer Finds the first free (unallocated) layer. 93
scLayer_FindNextAllocLayer Finds the first allocated layer above a specified layer. 94
scLayer_FindNextFreeLayer Finds the first free (unallocated) layer above a specified layer. 95
scView_GetCview Finds the construction view and retrieves it. 242
scView_GetView Finds the current view and retrieves it. 243

Select functions
scApp_SelectionInit Provides SURFCAM selector options (masks, selections, etc.). 51
scApp_SelectionFinal Must follow scApp_SelectionInit. 50

21
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

General Element Functions


Element handle functions
scElement_InitHandle Initializes an element handle. 87
scElement_NextHandle Returns the next element handle from the database. 88
scElement_ValidHandle Determines whether an element handle is valid. 93

Element memory functions


scElement_Final Frees memory block for an element. Follows functions such 69
as scArc_AllocMem, scConic_AllocMem, etc…

Element database functions


scElement_GetArc Retrieves an arc from the database. 71
scElement_GetCount Retrieves the total number of elements from the database. 73
scElement_GetLayer Retrieves a layer from the database. 74
scElement_GetLine Retrieves a line from the database. 76
scElement_GetLmesh Retrieves a line mesh from the database. 77
scElement_GetNurbCurve Retrieves a NURB curve from the database. 78
scElement_GetNurbSurface Retrieves a NURB surface from the database. 79
scElement_GetPline Retrieves a polyline from the database. 80
scElement_GetPoint Retrieves a point from the database. 81
scElement_GetVector Retrieves a vector from the database. 84
scElement_GetView Retrieves a view from the database. 85
scElement_WriteToDB Writes an element to the database. 94

Get element attributes


scElement_GetColorAttrib Gets the color of an element from the database. 72
scElement_GetLayerAttrib Retrieves the attributes of a layer from the database. 75
scElement_GetType Determines the type of an element (arc, line, point, etc.) from 82
the element pointer.
scElement_GetTypeFromHandle Determines the type of an element (arc, line, point, etc.) from 83
the element handle.
scElement_GetVisibleAttrib Determines whether an element is set to be visible or not. 86

Set element attributes


scElement_SetColorAttribEx Sets the color of an element in the database. 89
scElement_SetLayerAttribEx Sets the layer of an element in the database. 91

Convert elements
scNcurve_ElementToNurb Converts an element to a NURB curve. 154
scPline_ElementToPline Converts an element to a polyline. 199

22
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Evaluation Functions
Memory-level Evaluation
scMem_CheckAlloc Checks to see if memory was allocated by SURFCAM at a 140
specified address.
scMem_CheckAllocList Checks the validity of the “malloc” allocated list (i.e. checks 141
all the memory blocks allocated by SURFCAM).
scMem_CountAllocList Counts the number of memory allocations made by 142
SURFCAM.
scStack_Peek Checks the value of the top of the stack. 218

Application-level Evaluation
scApp_GetCurrentColor Gets the current color from SURFCAM. 41
scApp_GetCurrentLayer Gets the current layer from SURFCAM. 42
scApp_GetIniFileName Get Surfcam ini file name ??
scApp_GetInstanceHandle Gets the DLL handle from SURFCAM. 43
scApp_GetNumLayers Gets the number of layers. 44
scApp_GetTitle Reads in the window title from SURFCAM. 45
scApp_GetUnikKnots Get the list of unique knot vector 49
scApp_GetUnitType Get Surfcam unit type 50
scApp_GetWindowHandle Gets the window handle from SURFCAM. 46
scApp_LayerActive Checks to see whether a specified layer is active. 47
scApp_LayerAlloc Checks to see whether a specified layer is allocated. 48
scApp_LayerVisible Checks to see whether a specified layer is visible. 49
scView_GetCview Retrieves the construction view. 248
scView_GetView Retrieves the current view. 249

Database Evaluation
scElement_GetCount Retrieves the total number of elements from the database. 73
scLayer_FindFreeLayer Finds the first free (unallocated) layer. 96
scLayer_FindNextAllocLayer Finds the first allocated layer above a specified layer. 97
scLayer_FindNextFreeLayer Finds the first free (unallocated) layer with a reference 98
number higher than that of a specified layer.

Element Evaluation
scElement_GetType Determines the type of an element (arc, line, point, etc.) from 82
the element pointer.
scElement_GetTypeFromHandle Determines the type of an element (arc, line, point, etc.) from 83
the element handle.
scElement_GetColorAttrib Retrieves the color of an element from the database. 72
scElement_GetLayerAttrib Retrieves the layer of an element from the database. 75

23
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

scElement_GetVisibleAttrib Determines whether an element is set to be visible or not. 76

Layer Evaluation
scLayer_GetAttrib Gets the attributes for a specified layer. 99
scLayer_GetFromHandle Gets the layer number from the current element handle. 106
scLayer_GetLayerFromHandle Gets the layer number from the current element handle. 100
scLayer_GetName Gets the name for a specified layer. 101

View Evaluation
scView_Compare Compares two specified views for homogeneity within a 247
specified tolerance (checks to see if the views are identical).

Point Evaluation
scDist_FpointFpoint Evaluates the linear distance between two points. 70
scDist_FpointFpoint2d Evaluates the 2-d distance between two points. 72
scDist_PointPoint Evaluates the linear distance between two points. 67
scDist_PointPoint2dVec Evaluates the 2-d distance between two points. 68
scPoint_OppositeSideOfVector Determines if two points lie on opposite sides of a given 204
vector.

Line mesh Evaluation


scLmesh_GetPoints Gets the mesh points for a specified line mesh. 128

Curve Evaluation
scCurve_EvalLengthInit Evaluates the length of an arc or curve. 62
scCurve_EvalLengthFinal Must follow scCurve_EvalLengthInit. 61
scCurve_Eval Evaluates a point on a curve at a specified curve parameter. 60
scCurve_GetRange Determines the span range given the curve parameters. 63
scNcurve_GetPolyDisplayAttrib Determines if the polygon is displayed for a NURB curve. 159
scNcurve_GetRationalAttrib Determines if the NURB curve is rational. 160

24
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

NURB surface Evaluation


scNsurf_Eval Evaluates the surface parameters of a given point on a 170
surface.
scNsurf_EvalCurvature Returns the curvature of a surface at a given point. 171
scNsurf_FitNurb Fit NURB surface with non-rational NURB surface 188
scNsurf_FixDegeneration Fix degenerate surface ???
scNsurf_GetArrowDisplayAttrib Determines if the surface arrow is displayed for a specified 172
NURB surface.
scNsurf_GetArrowPositionAttrib Determines the position of the displayed surface arrow for 173
a specified NURB surface.
scNsurf_GetCutDirectionAttrib Determines the cut direction (u axis or v axis) for a 174
specified NURB surface.
scNsurf_GetIsoNurb Gets the isometric curves from a NURB surface. 175
scNsurf_GetNormalDirectionAttrib Determines the normal direction of the NURB surface. 176
scNsurf_GetNumberOfULinesAttrib Determines the number of u-direction lines of a specified 177
NURB surface.
scNsurf_GetNumberOfVLinesAttrib Determines the number of v-direction lines of a specified 178
NURB surface.
scNsurf_GetPolyDisplayAttrib Determines if the polyline mesh is displayed for a specified 179
NURB surface.
scNsurf_GetSpan Returns the u-v range of a surface. 180
scNsurf_GetRange Determines the span range given the surface parameters. 190
scNsurf_GetRationalAttrib Determines if the specified NURB surface is rational. 181
scNsurf_IsDegeneratedClosed Check to see if the surface is degenerate or closed 195
scNsurf_Offset Offsets a Nurb Surface by a given offset distance 195
scNsurf_ProjectPoint Projects a point onto a surface using a specified view 187
scNsurf_ProjectPointParam Projects a point onto a surface using a specified view and 188
returning both point and parameter
scNsurf_ProjectPointSide Projects a point onto a surface using a specified view and 215
returning both point and side information of the projected
point

25
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

Element Conversion Functions


Element(s)-to-NURB curve
scNcurve_ArcToNurb Converts an arc to a NURB curve. 147
scNcurve_ConicToNurb Converts a conic element to a NURB curve. 151
scNcurve_ConvertToArcLine Converts a Spline to Arcs and Lines. 168
scNcurve_ElementToNurb Converts an element to a NURB curve. 154
scNcurve_EllipseToNurb Converts an ellipse to a NURB curve (parameter set 1). 155
scNcurve_EllipseXYToNurb Converts an ellipse to a NURB curve (parameter set 2). 156
scNcurve_FitNurb Fit NURB curve with non-rational NURB curve ???
scNcurve_FromPointArray Defines a NURB curve from an array of points. 157
scNcurve_FromPointList Defines a NURB curve from a list of points. 158
scNcurve_InterpPtsTans Converts a set of points and tangent vectors to a NURB curve. 161

Element-to-polyline
scPline_ElementToPline Converts an element to a polyline. 199

Curves-to-loop
scNcurve_ChainNurbs Converts a set of curves to a curve chain (a loop). 149

NURB curve(s)-to-NURB surface


scNsurf_NurbListAutoSort Defines a NURB surface from one set of NURB curves. 183
scNsurf_NurbGrid Defines a NURB surface from two sets of NURB curves. 182

NURB surface-to-polygon
scNsurf_ConvertToPolygon Converts a NURB surface to an approximated surface 169
composed of polygons (triangles).

26
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Transformation Functions
Matrix transformation functions
scMat_GetRotation Constructs a matrix given a specified vector. 130
scMat_Identity Converts a matrix into an identity matrix. 131
scMat_Inverse Calculates the inverse of a specified matrix. 132
scMat_InverseTransform Calculates the inverse transform of a specified transform 133
matrix.
scMat_InverseTransform2d Calculates the inverse transform (using x and y axes only) of a 134
specified transform matrix.
scMat_Multiply Calculates the product of two specified matrices. 135
scMat_OrthoInverse Calculates the orthogonal inverse of a specified matrix. 136
scMat_SetColumn Set column of the matrix 137
scMat_Transform Transforms a three dimensional point given a matrix. 138
scMat_Transform2d Transform a 2D point 139
scMat_Transpose Calculates the transpose of a specified matrix. 140

Element transformations
scConic_TransformToStandard Transforms the position and orientation of a conic in space to 59
standard position and orientation.
scNcurve_Reverse Reverses the direction of a NURB curve. 164
scXForm_Element Transform element 295
scXForm_TranslateRel Translate element by relative distance 296
scXForm_TranslateAbs Translate element to absolute location 297
scXForm_Rotate Rotate element around a point 298
scXForm_Scale Scale a vector 299
scXForm_ScaleXYZ Scale an element by two points 300
scXForm_Mirror Mirror transformation along the line defined by two points 301
scXForm_TranslateRelUI Translate element by relative distance with UI 302
scXForm_TranslateAbsUI Translate element to absolute location with UI 303
scXForm_RotateUI Rotate element with UI 304
scXForm_ScaleUI Scale a vector with UI 305
scXForm_ScaleXYZUI Scale an element with UI 306
scXForm_MirrorUI Mirror transformation with UI 307
scXForm_TranslateRelUISel Translate element by relative distance with UI and selection 308
scXForm_TranslateAbsUISel Translate element to absolute location with UI and selection 309
scXForm_RotateUISel Rotate element with UI and selection 310
scXForm_ScaleUISel Scale a vector with UI and selection 311
scXForm_ScaleXYZUISel Scale an element with UI and selection 312
scXForm_MirrorUISel Mirror transformation with UI and selection 313
scXForm_ToViewUISel Transform to view with UI and selection 314

27
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

World-to-view
scView_WorldToView Converts a point to view coordinates using a matrix. 251

28
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Layer Functions
Allocate Memory
scLayer_AllocMem Allocates memory for a layer. 95

Set Layer
scApp_SetCurrentLayer Sets the current layer for SURFCAM. 54
scLayer_SetLayerVisibility Sets the given layer Visible/Invisible 56

Layer database functions


scApp_GetNumOfLayers Gets the number of layers in a specified database. 44
scElement_GetLayer Retrieves a layer from the database. 74
scElement_GetLayerAttrib Retrieves the layer of an element from the database. 75
scElement_SetLayerAttrib Sets the layer of an element in the database. 92
scLayer_WriteToDB Writes a layer to the database. 102

Find layers
scLayer_FindFreeLayer Finds the first free (unallocated) layer. 96
scLayer_FindNextAllocLayer Finds the first allocated layer above a specified layer. 97
scLayer_FindNextFreeLayer Finds the first free (unallocated) layer above a specified layer. 98

Get layer information


scApp_LayerActive Checks to see whether a specified layer is active. 47
scApp_LayerAlloc Checks to see whether a specified layer is allocated. 48
scApp_LayerVisible Checks to see whether a specified layer is visible. 49
scLayer_GetAttrib Gets the attributes for a specified layer. 99
scLayer_GetFromHandle Gets the layer number from the current element handle. 106
scLayer_GetLayerFromHandle Gets the layer number from the current element handle. 100
scLayer_GetName Gets the name for a specified layer. 101

29
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

View Functions
Allocate memory
scView_AllocMem Allocates memory for a view. 244

View database functions


scElement_GetView Retrieves a view from the database. 85
scView_WriteToDB Writes a view to the database. 252

Initialize view
scView_InitStandardView Initializes the standard view. 250

Retrieve view
scView_GetCview Retrieves the construction view. 248
scView_GetView Retrieves the current view. 249

Compare views
scView_Compare Compares two views within a specified tolerance. 247

Set a view
scView_ArbitraryAxis Sets the view to an arbitrary axis using a single vector. 245
scView_Arc Returns the view parallel to the normal vector of an arc. 246
scView_WorldToView Converts a point or vector to view coordinates using a matrix. 251

30
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Vector Functions
Vector database functions
scElement_GetVector Retrieves a vector from the database. 84

Double-precision vector operations


scVec_Add Adds two vectors together (double). 221
scVec_AddScaledVecs The vector sum of two scaled vectors (double). 223
scVec_BetweenVecVec Returns the vector between two vectors. 228
scVec_Normalize Normalizes a vector (double). 235
scVec_PointPoint Defines a vector from two points (double). 237
scVec_ProjectToPlaneN Projects a vector onto a plane defined by the plane 239
normal.
scVec_ProjectToPlaneNThroughVec Projects a vector onto a plane defined by the plane 240
normal using a second vector as the reference view.
scVec_Scale Scales a vector (double). 241
scVec_Set_axis_vec Set axis vector 250
scVec_SinAngle Returns the sine angle of a vector. 243
scFVec_FpointFPoint Defines a vector from two points (float). 246
scFVec_Add Adds two vectors together (float). 229
scFVec_Scale Scales a vector (float). 252
scFVec_Magnitude Determines the magnitude of a vector (float). 242
scFVec_Normalize Normalizes a vector (float). 246

Double-precision vector operations (2-dimensional)


scVec_Add2d Adds two vectors together in x-y plane only (double). 222
scVec_BetweenVecVec2d Returns the vector between two vectors in two 229
dimensions.
scVec_Normalize2d Normalizes a vector (double) in x-y dimensions only. 236
scVec_PointPoint2d Defines a vector from two points (double) in x-y 238
dimensions.
scVec_Scale2d Scales a vector (double) in x-y dimensions only. 242

31
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

Double-precision vector analysis


scVec_AngleMinusPiPi Returns the angle between two vectors (from minus π 224
radians to π radians).
scVec_AngleZero2Pi Returns the angle between two vectors (from zero radians 225
to 2π radians).
scVec_AngleZeroPi Returns the angle between two vectors (from zero radians 226
to π radians).
scVec_AngleZeroPi2 Returns the angle between two vectors (from zero radians 227
to π/2 radians).
scVec_Collinear Checks to see if two vectors are collinear. 230
scVec_CrossProduct Returns the cross product vector of two vectors. 231
scVec_DotProduct Returns the dot product of two vectors. 232
scVec_Magnitude Determines the magnitude of a vector (double). 233
scVec_Magnitude2d Determines the magnitude of a vector (double). 239
scVec_MagnitudeCrossProduct Determines the magnitude of the cross product of two 234
vectors.

Functions using vectors


scNcurve_InterpPtsTans Converts a set of points and tangent vectors to a NURB 161
curve.
scPlane_VectorPoint Constructs a plane given a vector and a point. 197
scPoint_OppositeSideOfVector Determines if two points lie on opposite sides of a given 204
vector.
scView_WorldToView Converts a point or vector to view coordinates using a 251
matrix.

32
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Point Functions
Allocate memory
scPoint_AllocMem Allocates memory for a point. 201

Point database functions


scElement_GetPoint Retrieves a point from the database. 81
scPoint_WriteToDB Writes a point to the database. 207

Point evaluation functions


scDist_PointPoint Evaluates the linear distance between two points. 67
scDist_PointPoint2dVec Evaluates the 2-d distance between two points. 68
scDist_FpointFpoint Evaluates the linear distance between two points. 70
scDist_FpointFpoint2d Evaluates the 2-d distance between two points. 72
scPoint_OppositeSideOfVector Determines if two points lie on opposite sides of a given vector. 204

Point creation functions


scPoint_ArcEnd Creates an endpoint of an arc. 202
scPoint_GetMinMax Scan the display list and get the minmax 227
scPoint_PointVecParam Get point from point vector and param 211
scPoint_ProjectToLine Projects a point onto a specified line. 205
scPoint_ProjectToPlane Projects a point onto a specified plane. 206

Functions using points


scArc_3Points Defines an arc using three points. 55
scNcurve_FromPointArray Defines a NURB curve from a list of points. 157
scNcurve_FromPointList Defines a NURB curve from an array of points. 158
scNcurve_InterpPtsTans Converts a set of points and tangent vectors to a NURB curve. 161
scPlane_VectorPoint Constructs a plane given a vector and a point. 197
scVec_PointPoint Creates a direction vector between two points. 237
scVec_PointPoint2d Creates a direction vector (in x-y plane only) between two 238
points.

33
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

Line Functions
Allocate memory
scLine_AllocMem Allocates memory for a line. 103

Line database functions


scElement_GetLine Retrieves a line from the database. 76
scLine_WriteToDB Writes a line to the database. 104

Functions using lines


scPoint_OppositeSideOfLine Determines if two points lie on opposite sides of a given line. 203
scPoint_ProjectToLine Projects a point onto a specified line. 205

Polyline Functions
Allocate memory
scPline_AllocMem Allocates memory for a polyline. 198

Line database functions


scElement_GetPline Retrieves a polyline from the database. 80
scPline_WriteToDB Writes a polyline to the database. 200

Functions using polylines


scPline_ElementToPline Converts an element to a polyline. 199
scNcurve_GetPolyDisplayAttrib Checks whether the polygon for a NURB curve is set to be 159
displayed or hidden.
scNcurve_SetPolyDisplayAttrib Sets whether the polygon for a NURB curve is set to be 165
displayed or hidden.

34
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

Line mesh Functions


Allocate memory
scLmesh_AllocMem Allocates memory for a line mesh. 127

Line database functions


scElement_GetLmesh Retrieves a line mesh from the database. 77
scLmesh_WriteToDB Writes a line mesh to the database. 129

Functions using line meshes


scLmesh_GetPoints Gets the line mesh for a given surface element. 128
scNsurf_GetPolyDisplayAttrib Checks whether the line mesh for a NURB surface is set to be 179
displayed or hidden.
scNsurf_SetPolyDisplayAttrib Sets whether the line mesh for a NURB surface is set to be 193
displayed or hidden.

Arc Functions
Allocate memory
scArc_AllocMem Allocates memory for an arc. 56

Arc database functions


scElement_GetArc Retrieves an arc from the database. 71
scArc_WriteToDB Writes an arc to the database. 57

Arc creation function


scArc_3Points Defines an arc using three points. 55

Arc manipulation functions


scNcurve_ArcToNurb Converts an arc to a NURB curve. 147
scNcurve_EllipseToNurb Converts an ellipse to a NURB curve. 155
scNcurve_EllipseXYToNurb Converts an ellipse (XY plane only) to a NURB curve. 156

Functions that use arcs


scPoint_ArcEnd Creates an endpoint of an arc. 202
scView_Arc Returns the view parallel to the normal vector of an arc. 246

35
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

Conic Functions
Allocate memory
scConic_AllocMem Allocates memory for a conic. 58

Conic transformation functions


scConic_TransformToStandard Transforms a position and orientation of a conic in space to 59
standard position and orientation (at the origin along z axis).
scNcurve_ConicToNurb Converts a conic element to a NURB curve. 153

NURB Curve Functions


Allocate memory
scNcurve_AllocMem Allocates memory for a NURB curve. 146

NURB curve database functions


scElement_GetNurbCurve Retrieves an NURB curve from the database. 78
scNcurve_WriteToDB Writes an NURB curve to the database. 167

NURB curve creation functions


scNcurve_InterpPtsTans Defines a set of points and tangent vectors as a NURB 161
curve.
scNcurve_FromPointArray Defines a NURB curve from a list of points. 157
scNcurve_FromPointList Defines a NURB curve from an array of points. 158

NURB curve evaluation functions


scCurve_EvalLengthInit Evaluates the length of an arc or curve. 62
scCurve_EvalLengthFinal Must follow scCurve_EvalLengthInit. 61
scCurve_Eval Evaluates a point on an arc or curve where a value for a 60
specified parameter is met.
scCurve_GetRange Determines the span range given the curve parameters. 63
scNcurve_GetPolyDisplayAttrib Determines if the polygon is displayed for a NURB curve. 159
scNcurve_GetRationalAttrib Determines if the NURB curve is rational. 160

36
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

NURB conversion functions


scNcurve_ArcToNurb Converts an arc to a NURB curve. 147
scNcurve_ConicToNurb Converts a conic element to a NURB curve. 153
scNcurve_ElementToNurb Converts an element to a NURB curve. 154
scNcurve_EllipseToNurb Converts an ellipse to a NURB curve (parameter set 1). 155
scNcurve_EllipseXYToNurb Converts an ellipse to a NURB curve (parameter set 2). 156
scNcurve_InterpPtsTans Converts a set of points and tangent vectors to a NURB 161
curve.
scNcurve_FromPointArray Defines a NURB curve from a list of points. 157
scNcurve_FromPointList Defines a NURB curve from an array of points. 158

NURB curve operation functions


scNcurve_ChainNurbs Converts a set of (NURB) curves into a single chain (loop). 149
scNcurve_Break Breaks a NURB curve into two defined NURB curves. 148
scNcurve_Clamp Clamps a NURB curve, adding additional control points. 150
scNcurve_ClipParam1 Clips a NURB curve at a specified knot (parameter set 1). 152
scNcurve_ClipParam2 Clips a NURB curve at a specified knot (parameter set 2). 153
scNcurve_JoinTwoNurbs Joins two NURB curves into a single NURB curve. 162
scNcurve_ProjectLoop2Nsurf Project a loop of curves onto surface 172
scNcurve_ProjectToNsurf Project curve onto surface 173
scNcurve_ProjectUVToNsurf Project UV parametric curve onto surface 178
scNcurve_RaiseOrder Increase the curve order 180
scNcurve_Reverse Reverses the direction of the NURB curve. 164
scNcurve_SetPolyDisplayAttrib Sets whether the polygon is displayed for a NURB curve. 165
scNcurve_SetRationalAttrib Sets whether the NURB curve is rational. 166

Functions that use NURB curves


scNsurf_GetIsoNurb Gets the isometric display curves from a NURB surface. 175
scNsurf_NurbListAutoSort Defines a NURB surface from one sets of NURB curves. 173
scNsurf_Revolution Creates a NURB surface by revolving a NURB curve. 185
scNsurf_Ruled Creates a NURB surface by using two existing NURB 186
curves as surface edges (u-direction and v-direction).
scNsurf_NurbGrid Defines a NURB surface from two sets of NURB curves. 182

37
Chapter 4 Function Summary Tables SURFCAM 2005 • API Documentation

NURB Surface Functions


Allocate memory
scNsurf_AllocMem Allocates memory for a NURB surface. 168

NURB surface database functions


scElement_GetNurbSurface Retrieves an NURB surface from the database. 79
scNsurf_WriteToDB Writes an NURB surface to the database. 196

NURB surface creation functions


scNsurf_NurbGrid Creates a NURB surface from two sets of NURB curves. 182
scNsurf_NurbListAutoSort Creates a NURB surface from one set of NURB curves 183
using automatic sorting.
scNsurf_Revolution Creates a NURB surface by revolving a NURB curve. 185
scNsurf_Ruled Creates a NURB surface by using two existing NURB 186
curves as surface edges (u-direction and v-direction).

NURB surface evaluation functions


scNsurf_Eval Evaluates the surface parameters of a given point on a 170
surface.
scNsurf_EvalCurvature Returns the curvature of a surface at a given point. 171
scNsurf_GetArrowDisplayAttrib Determines if the surface arrow is displayed for a specified 172
NURB surface.
scNsurf_GetArrowPositionAttrib Determines the position of the displayed surface arrow for 173
a specified NURB surface.
scNsurf_GetCutDirectionAttrib Determines the cut direction (u axis or v axis) for a 174
specified NURB surface.
scNsurf_GetIsoNurb Gets the isometric display curves from a NURB surface. 175
scNsurf_GetNormalDirectionAttrib Determines the normal direction of the NURB surface. 176
scNsurf_GetNumberOfULinesAttrib Determines the number of u-direction lines of a specified 177
NURB surface.
scNsurf_GetNumberOfVLinesAttrib Determines the number of v-direction lines of a specified 178
NURB surface.
scNsurf_GetPolyDisplayAttrib Determines if the polyline mesh is displayed for a specified 179
NURB surface.
scNsurf_GetSpan Returns the u-v range of a surface. 180
scNsurf_GetRationalAttrib Determines if the specified NURB surface is rational. 181
scNsurf_IsDegeneratedClosed Check to see if the surface is degenerate or closed 195

38
SURFCAM 2005 • API Documentation Chapter 4 Function Summary Tables

NURB conversion functions


scNsurf_ConvertToPolygon Converts a NURB surface to an approximated surface 169
composed of polygons (triangles).

NURB surface operation functions


scNsurf_Clamp Clamps a NURB surface, adding additional control points. 207
scNsurf_SetArrowDisplayAttrib Sets whether the surface arrow is displayed for a specified 187
NURB surface.
scNsurf_SetArrowPositionAttrib Sets the position of the displayed surface arrow for a 188
specified NURB surface.
scNsurf_SetCutDirectionAttrib Sets the cut direction (u axis or v axis) for a specified 189
NURB surface.
scNsurf_SetNormalDirectionAttrib Sets the normal direction of the NURB surface. 190
scNsurf_SetNumberOfULinesAttrib Sets the number of u-direction lines of a specified NURB 191
surface.
scNsurf_SetNumberOfVLinesAttrib Sets the number of v-direction lines of a specified NURB 192
surface.
scNsurf_SetPolyDisplayAttrib Sets whether the polyline mesh is displayed for a specified 193
NURB surface.
scNsurf_SetRange Sets the range of a surface element. 194
scNsurf_SetRationalAttrib Sets whether the specified NURB surface is rational. 195

39
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

40
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Chapter 5
Function
Descriptions

41
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

42
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_GetCurrentColor

PROTOTYPE: UINT scApp_GetCurrentColor()

ACTION: Returns the value for the current SURFCAM color.

FUNCTION RETURN TYPE: unsigned int

RETURN: BLACK Black


DARKBLUE Dark Blue
DARKGREEN Dark Green
DARKCYAN Dark Cyan
DARKRED Dark Red
DARKMAGENTA Dark Magenta
DARKYELLOW Dark Yellow
LIGHTGRAY Light Gray
DARKGRAY Dark Gray
BRIGHTBLUE Bright Blue
BRIGHTGREEN Bright Green
BRIGHTCYAN Bright Cyan
BRIGHTRED Bright Red
BRIGHTMAGENTA Bright Magenta
BRIGHTYELLOW Bright Yellow
WHITE White

ARGUMENTS: <None>

43
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_GetCurrentLayer

PROTOTYPE: UINT scApp_GetCurrentLayer()

ACTION: Returns reference value for the current layer. SURFCAM


supports up to 256 layers, so valid return values fall between 0
and 255.

FUNCTION RETURN TYPE: unsigned int

RETURN: Reference value for the current layer (0 to 255).

ARGUMENTS: <None>

44
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_GetIniFileName

PROTOTYPE: char* scApp_GetIniFileName()

ACTION: Get Surfcam ini file name

FUNCTION RETURN TYPE: char *

RETURN: Surfcam ini file name

ARGUMENTS: <None>

45
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_GetInstanceHandle

PROTOTYPE: HANDLE scApp_GetInstanceHandle()

ACTION: Returns the handle for the Dynamic Link Library (DLL) associated
with the SURFCAM API.

FUNCTION RETURN TYPE: HANDLE

RETURN: Reference DLL handle value for dll_io.dll.

ARGUMENTS: <None>

46
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_SetElemHandle

PROTOTYPE: void scApp_SetElemHandle(HSC_Element hEl,


SC_NurbSurface *nsurf)

ACTION: //To Do By Anil

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: HSC_Element hEl Handle of element


SC_NurbSurface *nsurf NURB Surface

47
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_GetNumOfLayers

PROTOTYPE: int scApp_GetNumOfLayers(int * iFirstLayer)

ACTION: Counts the number of layers currently defined in SURFCAM and


returns the reference number of the first allocated layer.

FUNCTION RETURN TYPE: int

RETURN: The number of layers currently defined in SURFCAM.

OUTPUT ARGUMENTS: int * iFirstLayer Number of the first


allocated layer

48
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_GetTitle

PROTOTYPE: int scApp_GetTitle(char * szTitle, int iMaxlength)

ACTION: Reads in the text of the titlebar of the SURFCAM window and
copies it to caller supplied buffer. The text includes the currently
open file. If the length of the string exceeds maxlength, the string
is truncated.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: int iMaxlength Maximum length of title


character string

INPUT and
OUTPUT ARGUMENTS: char * szTitle Pointer to the character buffer
that receives the title string

49
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_GetUnikKnots

PROTOTYPE: int scApp_GetUnikKnots(double * knots,


int tot_num, double **unik_knots, int *unik_num)

ACTION: Get the list of unique knot vector

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: double* knots Knot vector to check


Int tot_num Input know vector size

INPUT and
OUTPUT ARGUMENTS: double ** unik_knots Returned unique knot vector
Int* unik_num Unique knot vector size

50
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_GetUnitType

PROTOTYPE: int scApp_GetUnitType(void)

ACTION: Get Surfcam unit type.

FUNCTION RETURN TYPE: int

RETURN: Surfcam unit type


0: Inch
1: Metric

INPUT and
OUTPUT ARGUMENTS: None

51
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_GetWindowHandle

PROTOTYPE: HWND scApp_GetWindowHandle()

ACTION: Retrieves the Windows handle for the SURFCAM application.

FUNCTION RETURN TYPE: HWND

RETURN: Windows handle reference

ARGUMENTS: <None>

52
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_LayerActive

PROTOTYPE: int scApp_LayerActive(int iLayer)

ACTION: Checks to see if a specified layer is active. If the return value is


false, the layer is inactive. If the return value is true, the layer is
active.

FUNCTION RETURN TYPE: int

RETURN: FALSE Layer is inactive


TRUE Layer is active

INPUT ARGUMENTS: int iLayer Layer number (0-255)

53
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_LayerAlloc

PROTOTYPE: int scApp_LayerAlloc(int iLayer)

ACTION: Checks to see if a specified layer has been allocated in


SURFCAM. If the return value is false, the layer has not been
allocated. If the return value is true, then the layer has been
allocated. Note that valid layer numbers are between 0 and 255.

FUNCTION RETURN TYPE: int

RETURN: FALSE The layer has not been allocated


TRUE The layer has been allocated

INPUT ARGUMENTS: int layer Layer number (0-255)

54
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_LayerVisible

PROTOTYPE: int scApp_LayerVisible(int iLayer)

ACTION: Checks to see if a specified layer is visible or hidden. If the return


value is false, the layer is hidden or invalid; if the return value is
true, the layer is visible.

FUNCTION RETURN TYPE: int

RETURN: FALSE Layer is hidden or invalid


TRUE Layer is visible

INPUT ARGUMENTS: int layer Layer number (0-255)

55
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_ProcessDigtFile

PROTOTYPE: int scApp_ProcessDigtFile(FILE *, int, int *)

ACTION: Create geometric entities by importing digitized file with defined


entity type and reading function.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: FILE* fp_d Digitized file name


int out_type Entity type to create
0,1,…,8 for type of point, line, pline, lmesh,
spline, ncurve, ncurve by control point, nsurf,
nsurf by control point
int* pfunc_get_pt
Function point to read in points from the
digitized file

56
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_ScanViewTable

PROTOTYPE: int scApp_ScanViewTable( unsigned short * nTable,


unsigned nNum)

ACTION: Retrieves the SURFCAM view table into a specified table of


nNum unsigned short integers. The view table is an array of
unsigned short integers holding valid (allocated) view references.
The view table is filled for up to nNum views, truncating the list of
views if insufficient memory is allocated.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: unsigned nNum Size of table (array of integers)

OUTPUT ARGUMENTS: unsigned short * nTable Table to be filled

57
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_SelectionFinal

PROTOTYPE: int scApp_SelectionFinal()

ACTION: Frees the memory reserved by scApp_SelectionInit. Note:


this function must follow instances of scApp_SelectionInit.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

ARGUMENTS: <None>

58
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_SelectionInit

PROTOTYPE: int scApp_SelectionInit ( int iSelType, unsigned nEleMask,


unsigned nColMask, int iTrimSurf )

ACTION: Provides SURFCAM selector options. The function sets the type
of selection and the selection masks. The element and color
masks are defined in a two-byte register by bit values, with each
bit representing a given color or element to be masked. A value
of TRUE for the iTrimSurf flag selects trimmed surfaces only.
This function must be followed by scApp_SelectionFinal.

FUNCTION RETURN TYPE: int

RETURN: 0 or higher Success


~0 Fail

INPUT ARGUMENTS: int iSelType Type of selection


MENU_SELECT Menu selection
SELECT_ALL Select all
SELECT_ACTIVE Select active
SELECT_ELEMENTS Select elements

unsigned nEleMask Mask for element(s)


unsigned nColMask Mask for color(s)
int iTrimSurf Flag for trimmed surfaces only

SAMPLE CODE:
unsigned nColorMask;
unsigned nElementMask;

nColorMask = dll_mask_bit(WHITE) | dll_mask_bit(DARKRED);


nElementMask = dll_mask_bit(SC_POINT) | dll_mask_bit(SC_LINE);

scApp_SelectionInit(MENU_SELECT, nElementMask, nColorMask, 0);

59
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_SetCurrentColor

PROTOTYPE: void scApp_SetCurrentColor(unsigned int nColor )

ACTION: Sets the current SURFCAM color.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: unsigned int nColor Color to be set as current


BLACK Black
DARKBLUE Dark Blue
DARKGREEN Dark Green
DARKCYAN Dark Cyan
DARKRED Dark Red
DARKMAGENTA Dark Magenta
DARKYELLOW Dark Yellow
LIGHTGRAY Light Gray
DARKGRAY Dark Gray
BRIGHTBLUE Bright Blue
BRIGHTGREEN Bright Green
BRIGHTCYAN Bright Cyan
BRIGHTRED Bright Red
BRIGHTMAGENTA Bright Magenta
BRIGHTYELLOW Bright Yellow
WHITE White

60
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scApp_SetCurrentLayer

PROTOTYPE: void scApp_SetCurrentLayer(unsigned int nLayer )

ACTION: Sets a specified layer to be the current layer. Note that the
referenced layer must be first allocated before it can be set as
the current layer.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: unsigned int nLayer Layer to be set as current

61
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scApp_SetModifiedFlag

PROTOTYPE: void scApp_SetModifiedFlag( void )

ACTION: Set Surfcam database dirty (modified)

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: void

62
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLayer_SetLayerVisibility

PROTOTYPE: int scLayer_SetLayerVisibility(unsigned int nLayer,


int nVisible )

ACTION: Sets a specified layer to be Visible/Invisible layer.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: unsigned int nLayer Layer to be set as


Visible/Invisible

Int nVisible Visibility attribute


0 Invisible Layer Attribute
1 Visible Layer Attribute

63
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scArc_AllocMem

PROTOTYPE: SC_Arc * scArc_AllocMem()

ACTION: Allocates memory for an arc.

FUNCTION RETURN TYPE: SC_Arc *

RETURN: Pointer to the arc or NULL if unsuccessful

ARGUMENTS: <None>

64
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scArc_WriteToDB

PROTOTYPE: HSC_Element scArc_WriteToDB(HSC_DB hDB,


SC_Arc * Arc)

ACTION: Writes an arc to the database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle

INPUT ARGUMENTS: HSC_DB hDB Database handle


SC_Arc * Arc The arc to be written

65
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scArc_3Points

PROTOTYPE: int scArc_3Points( SC_Arc * Arc,


SC_Point * Point1,
SC_Point * Point2,
SC_Point * Point3,
int iFullCircle)

ACTION: Defines an arc using three points. The iFullCircle flag controls
whether a full circle is to be defined or an arc with endpoints at
the proper points.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Point * Point1 Point 1


SC_Point * Point2 Point 2
SC_Point * Point3 Point 3
int iFullCircle Flag that controls whether an arc
is to be defined or a full circle
FALSE Arc
TRUE Circle

OUTPUT ARGUMENTS: SC_Arc * Arc Arc to be defined

66
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scConic_AllocMem

PROTOTYPE: SC_Conic * scConic_AllocMem()

ACTION: Allocates memory for a conic element.

FUNCTION RETURN TYPE: SC_Conic *

RETURN: Pointer to the conic element or NULL if unsuccessful

ARGUMENTS: <None>

67
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scConic_TransformToStandard

PROTOTYPE: int scConic_TransformToStandard(SC_Conic * Newconic,


double dblMatrix [4][4],
SC_Conic * Oldconic )

ACTION: Gives the transformation matrix for the transformation of a conic


in space to a standard conic. (A standard conic lies at the origin
in the x-y plane).

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Conic * Oldconic Original conic

OUTPUT ARGUMENTS: double dblMatrix [4][4] Transformation matrix


SC_Conic * Newconic New standard conic

68
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scCurve_Eval

PROTOTYPE: int scCurve_Eval( SC_Element Curve,


int iFlag,
SC_Gcrv_param_type * Parameter,
SC_Point * Point )

ACTION: Evaluates the point on a curve at a specified parameter.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Curve Curve element


int iFlag Evaluation flag for point or
derivative:
DLL_GCE_POINT Point evaluation
DLL_GCE_NORMAL Normal vector evaluation
DLL_GCE_PRIME First derivative with respect to u
DLL_GCE_DOUBLE_PRIME Second derivative with respect to u
DLL_GCE_TANGENT Tangent vector at the point
DLL_GCE_NUM_DERIVS Number of derivatives

SC_Gcrv_param_type *
Parameter Curve parameter (such as
distance along curve in curve
space)

OUTPUT ARGUMENTS: SC_Point * Point Point defined

69
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scCurve_EvalCurvature

PROTOTYPE: double
scCurve_EvalCurvature( SC_Element Curve,
UINT iDirection,
SC_Gcrv_param_type * Param )

ACTION: Returns the curvature (inverse of the radius) of a curve element in


a specified parametric direction.

FUNCTION RETURN TYPE: double

RETURN: Curvature of a curve at a point described by a set of curve


parameters

INPUT ARGUMENTS: SC_Element Curve Curve element


unsigned int iDirection Direction of curve
GSC_U_CURVE normal curvature in u direction
GSC_V_CURVE normal curvature in v direction
GSC_NUM_CURVES

SC_Gcrv_param_type *
Parameter Curve parameter (such as
distance along curve in curve
space)

70
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scCurve_EvalLengthFinal

PROTOTYPE: int scCurve_EvalLengthFinal(SC_Element Curve )

ACTION: Frees the memory allocated for the curve mapping in


scCurve_EvalLengthInit.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_Element Curve Curve element

71
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scCurve_EvalLengthInit

PROTOTYPE: int scCurve_EvalLengthInit( SC_Element Curve,


int iNumSpans,
double * dblLength)

ACTION: Evaluates the length of a curve. This function maps out the curve
along the u-dimension (in curve space) and returns the total
length of the curve. In addition, the spans between adjacent
knots of the original curve are divided into iNumSpans number of
spans. Note that this function must be followed by
scCurve_EvalLengthFinal in order to free the memory
used to map out the curve.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Curve Curve element


int iNumSpans Divides each original span
(between adjacent knots) into
iNumSpans number of spans.

OUTPUT ARGUMENTS: double * dblLength Total length of curve

72
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scCurve_GetSpan

PROTOTYPE: int scCurve_GetSpan( SC_Element Curve,


SC_Gcrv_param_type * Parameter,
int iFlag,
double * dblLower,
double * dblUpper )

ACTION: Determines the span range given a curve parameter.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Curve Curve element


SC_Gcrv_param_type *
Parameter Distance along curve in curve
space
int iFlag Flags
DLL_GCRV_FLAGS_NORMAL Normal curve
DLL_GCRV_FLAGS_NOTRIM Not a trimmed curve
DLL_GCRV_FLAGS_EXTENDED_SPAN Extended curve

OUTPUT ARGUMENTS: double * dblLower Lower bound


double * dblUpper Upper bound

73
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scDB_GetHandle

PROTOTYPE: HSC_DB scDB_GetHandle()

ACTION: Retrieves the current SURFCAM database handle. This handle


is used in all subsequent database operations.

FUNCTION RETURN TYPE: HSC_DB

RETURN: Database handle or NULL if unsuccessful

ARGUMENTS: <None>

SAMPLE CODE:
// This code demonstrates how to manipulate the SURFCAM database
// The following routine will read through the entire database
// and assign any points to layer 30 and any lines to layer 40

HSC_DB hDatabase;
HSC_Element hElementTemp;
SC_Element * pElement;
int iType, iReturn, iLayer;

hDatabase = scDB_GetHandle(); // Retrieve the handle to the database

for (hElementTemp = scElement_InitHandle(hDatabase); // Set up loop


hElementTemp.hEl != INVALID_HANDLE;
hElementTemp = scElement_GetNextHandle(hDatabase)) {

iType = scElement_GetTypeFromHandle(hElementTemp); // Retrieve element type

if (iType == SC_POINT) { // If it’s a point...


SC_Point * pPoint = scElement_GetPoint(hElementTemp); // Get the line
iReturn = scElement_SetLayerAttribute(pPoint, 30); // Assign it to layer 30
assert (iReturn == 0);
}

else if (iType == SC_LINE) { // If it’s a line...


SC_Line * pLine = scElement_GetLine(hElementTemp); // Get the line
iReturn = scElement_SetLayerAttribute(pLine, 40); // Assign it to layer 40
assert (iReturn == 0);
}
}

74
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scDB_GetHeader

PROTOTYPE: void scDB_GetHeader(HSC_DB hDB, SC_Header *Header )

ACTION: Gets the header from the current SURFCAM database. The
header information is written into a structure SC_Header. The
header contains information on the version of SURFCAM, the
author, and the title of the file.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: HSC_DB hDB Database header

OUTPUT ARGUMENTS: SC_Header * Header Pointer to header structure

75
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scDB_WriteHeader

PROTOTYPE: void scDB_WriteHeader( HSC_DB hDB, char * szTitle,


char * szAuthor )

ACTION: Writes the title and author information to the header to the
database.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: HSC_DB hDB Database header


char * szTitle Title of file
char * szAuthor Author of file

76
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scDist_PointPoint

PROTOTYPE: double scDist_PointPoint( SC_Point * Point1,


SC_Point * Point2 )

ACTION: Determines the distance between two points in three-dimensional


space.

FUNCTION RETURN TYPE: double

RETURN: Distance between two points

INPUT ARGUMENTS: SC_Point * Point1 Address of point 1


SC_Point * Point2 Address of point 2

77
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scDist_FpointFpoint

PROTOTYPE: float scDist_FpointFpoint( SC_FPoint * Point1,


SC_FPoint * Point2 )

ACTION: Determines the distance between two points in three-dimensional


space.

FUNCTION RETURN TYPE: float

RETURN: Distance between two points

INPUT ARGUMENTS: SC_FPoint * Point1 Address of point 1


SC_FPoint * Point2 Address of point 2

78
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scDist_PointPoint2dVec

PROTOTYPE: double scDist_PointPoint2dVec( SC_Point * Point1,


SC_Point * Point2,
SC_DirVector * Vector )

ACTION: Determines the distance between two points projected onto a


view plane. The plane of the view is defined by the normal vector
Vector.

FUNCTION RETURN TYPE: double

RETURN: Magnitude of the distance between the two projected points

INPUT ARGUMENTS: SC_Point * Point1 Point 1


SC_Point * Point2 Point 2
SC_DirVector * Vector Normal vector of view plane

79
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scDist_FpointFpoint2d

PROTOTYPE: float scDist_FpointFpoint2d( SC_FPoint * Point1,


SC_FPoint * Point2 )

ACTION: Determines the distance between two points projected onto a


view plane. The plane of the view is defined by the normal vector
Vector.

FUNCTION RETURN TYPE: float

RETURN: Magnitude of the distance between the two projected points

INPUT ARGUMENTS: SC_FPoint * Point1 Point 1


SC_FPoint * Point2 Point 2

80
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_DeleteElement

PROTOTYPE: void scElement_DeleteElement(HSC_Element hElem )

ACTION: Deletes a single element from the SURFCAM database.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: HSC_Element hElem Handle of element

81
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_Final

PROTOTYPE: void scElement_Final(SC_Element Element )

ACTION: Frees the memory reserved for any SURFCAM element.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Element Element Pointer to element address

82
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetArc

PROTOTYPE: SC_Arc * scElement_GetArc(HSC_Element hElement )

ACTION: Retrieves an arc from the element handle. If the element is an


arc, the function creates an arc (SC_Arc) using AllocMem and
returns the pointer to the created arc. If the element is not an arc,
the function returns a NULL and no arc is created.

FUNCTION RETURN TYPE: SC_Arc *

RETURN: Retrieves arc from element handle or NULL if unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

83
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetColorAttrib

PROTOTYPE: int scElement_GetColorAttrib(SC_Element hElement )

ACTION: Returns the color of an element from the element handle.

FUNCTION RETURN TYPE: int

RETURN: BLACK Black


DARKBLUE Dark Blue
DARKGREEN Dark Green
DARKCYAN Dark Cyan
DARKRED Dark Red
DARKMAGENTA Dark Magenta
DARKYELLOW Dark Yellow
LIGHTGRAY Light Gray
DARKGRAY Dark Gray
BRIGHTBLUE Bright Blue
BRIGHTGREEN Bright Green
BRIGHTCYAN Bright Cyan
BRIGHTRED Bright Red
BRIGHTMAGENTA Bright Magenta
BRIGHTYELLOW Bright Yellow
WHITE White

INPUT ARGUMENTS: SC_Element hElement Element that is being examined

84
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetColorAttribEx

PROTOTYPE: int scElement_GetColorAttribEx(SC_Element hElement )

ACTION: Returns the color of an element from the element handle.

FUNCTION RETURN TYPE: int

RETURN: BLACK Black


DARKBLUE Dark Blue
DARKGREEN Dark Green
DARKCYAN Dark Cyan
DARKRED Dark Red
DARKMAGENTA Dark Magenta
DARKYELLOW Dark Yellow
LIGHTGRAY Light Gray
DARKGRAY Dark Gray
BRIGHTBLUE Bright Blue
BRIGHTGREEN Bright Green
BRIGHTCYAN Bright Cyan
BRIGHTRED Bright Red
BRIGHTMAGENTA Bright Magenta
BRIGHTYELLOW Bright Yellow
WHITE White

INPUT ARGUMENTS: SC_Element hElement Element that is being examined

85
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetCount

PROTOTYPE: int scElement_GetCount(HSC_DB hDB )

ACTION: Returns the total number of elements in the database.

FUNCTION RETURN TYPE: int

RETURN: Total number of elements in the database

INPUT ARGUMENTS: HSC_DB hDB Database handle

SAMPLE CODE:
// This code demonstrates how to retrieve information from the SURFCAM database
// The following routine will read through the entire database to count the
// number of elements, comparing that result to the number returned by the
// function scElement_GetCount().

HSC_DB hDatabase;
HSC_Element hElementTemp;
int iCount1, iCount2;

iCount1 = 0;
iCount2 = 0;

hDatabase = scDB_GetHandle(); // Retrieve the handle to the database

iCount1 = scElement_GetCount(hDatabase);

for (hElementTemp = scElement_InitHandle(hDatabase); // Set up loop


hElementTemp.hEl != INVALID_HANDLE;
hElementTemp = scElement_GetNextHandle(hDatabase)) {

iCount2++;
}

assert (iCount1 == iCount2); // Compare the results

86
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetLayer

PROTOTYPE: SC_Layer * scElement_GetLayer(HSC_Element hElement)

ACTION: Retrieves a layer from the element handle and defines the layer
as an SC_Layer structure. If the element is a layer, the function
creates a layer (SC_Layer) and returns the pointer to the created
layer. If the element is not a layer, the function returns a NULL
and no layer is created.

FUNCTION RETURN TYPE: SC_Layer *

RETURN: Layer retrieved from the element handle or NULL if unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

87
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetLayerAttrib

PROTOTYPE: int scElement_GetLayerAttrib(SC_Element Element )

ACTION: Returns the layer number of a specified element.

FUNCTION RETURN TYPE: int

RETURN: Layer number

INPUT ARGUMENTS: SC_Element Element Element that is being examined

88
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetLine

PROTOTYPE: SC_Line * scElement_GetLine(HSC_Element hElement )

ACTION: Retrieves a line from the element handle and defines the line as a
SC_Line structure. If the element is a line, the function creates a
line (SC_Line) and returns the pointer to the created line. If the
element is not a line, the function returns a NULL and no line is
created.

FUNCTION RETURN TYPE: SC_Line *

RETURN: Retrieves a line from the element handle or NULL if unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

89
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetLmesh

PROTOTYPE: SC_Lmesh *
scElement_GetLmesh(HSC_Element hElement )

ACTION: Retrieves a line mesh from the element handle and defines the
line mesh as an SC_LMesh structure. If the element is a line
mesh, the function creates a line mesh (SC_LMesh) and returns
the pointer to the created line mesh. If the element is not a line
mesh, the function returns a NULL and no line mesh is created.

FUNCTION RETURN TYPE: SC_LMesh *

RETURN: Retrieves a line mesh from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

90
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetNurbCurve

PROTOTYPE: SC_NurbCurve *
scElement_GetNurbCurve(HSC_Element hElement )

ACTION: Retrieves a NURB curve from the element handle and defines it
as a SC_NurbCurve structure. If the element is a NURB curve,
the function creates a NURB curve (SC_NurbCurve) and returns
the pointer to the created NURB curve. If the element is not a
NURB curve, the function returns a NULL and no NURB curve is
created.

FUNCTION RETURN TYPE: SC_NurbCurve *

RETURN: Retrieves a NURB curve from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

91
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetNurbSurface

PROTOTYPE: SC_NurbSurface *
scElement_GetNurbSurface(HSC_Element hElement )

ACTION: Retrieves a NURB surface from the element handle and defines it
as a SC_NurbSurface structure. If the element is a NURB
surface, the function creates a NURB surface (SC_NurbSurface)
and returns the pointer to the created NURB surface. If the
element is not a NURB surface, the function returns a NULL and
no NURB surface is created.

FUNCTION RETURN TYPE: SC_NurbSurface *

RETURN: Retrieves a NURB surface from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

92
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetPline

PROTOTYPE: SC_PLine * scElement_GetPline(HSC_Element hElement )

ACTION: Retrieves a polyline from the element handle and defines it as a


SC_PLine structure. If the element is a polyline, the function
creates a polyline (SC_PLine) and returns the pointer to the
created polyline. If the element is not a polyline, the function
returns a NULL and no polyline is created.

FUNCTION RETURN TYPE: SC_PLine *

RETURN: Retrieves a polyline from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

93
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetPoint

PROTOTYPE: SC_Point * scElement_GetPoint(HSC_Element hElement )

ACTION: Retrieves a point from the element handle and defines it as a


SC_Point structure. If the element is a point, the function creates
a point (SC_Point) and returns the pointer to the created point. If
the element is not a point, the function returns a NULL and no
point is created.

FUNCTION RETURN TYPE: SC_Point *

RETURN: Retrieves a point from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

94
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetText

PROTOTYPE: int scElement_GetText(


struct SCElementHandle hElement,
SC_TextPtr **apScTextList )

ACTION: // To Do By Anil

FUNCTION RETURN TYPE: int

RETURN: // To Do By Anil

INPUT ARGUMENTS: // To Do By Anil

95
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetType

PROTOTYPE: int scElement_GetType(SC_Element hElement )

ACTION: Returns the type of a given element from the element pointer.

FUNCTION RETURN TYPE: int

RETURN: SC_POINT Point


SC_LINE Line
SC_PLINE Polyline
SC_LMESH Line mesh
SC_LAYER Layer
SC_ARC Arc
SC_VIEW View
SC_NCURVE NURB curve
SC_NSURF NURB surface
SC_VECTOR Vector
SC_CONIC Conic

INPUT ARGUMENTS: SC_Element * hElement Element

96
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetTypeFromHandle

PROTOTYPE: int
scElement_GetTypeFromHandle(HSC_Element handle)

ACTION: Determines type of element from element handle.

FUNCTION RETURN TYPE: int

RETURN: SC_POINT Point


SC_LINE Line
SC_PLINE Polyline
SC_LMESH Line mesh
SC_LAYER Layer
SC_ARC Arc
SC_VIEW View
SC_NCURVE NURB curve
SC_NSURF NURB surface
SC_VECTOR Vector
SC_CONIC Conic

INPUT ARGUMENTS: HSC_Element handle Element handle

97
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetVector

PROTOTYPE: SC_Vector *
scElement_GetVector(HSC_Element hElement )

ACTION: Retrieves a vector from the element handle and defines it as a


SC_Vector structure. If the element is a vector, the function
creates a vector (SC_Vector) and returns the pointer to the
created vector. If the element is not a vector, the function returns
a NULL and no vector is created.

FUNCTION RETURN TYPE: SC_Vector *

RETURN: Retrieves a vector from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

98
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_GetView

PROTOTYPE: SC_View * scElement_GetView(HSC_Element hElement )

ACTION: Retrieves a view from the element handle and defines it as a


SC_View structure. If the element is a view, the function creates
a view (SC_View) and returns the pointer to the created view. If
the element is not a view, the function returns a NULL and no
view is created.

FUNCTION RETURN TYPE: SC_View *

RETURN: Retrieves a view from the element handle or NULL if


unsuccessful

INPUT ARGUMENTS: HSC_Element hElement Element handle

99
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_GetVisibleAttrib

PROTOTYPE: int scElement_GetVisibleAttrib(SC_Element Element )

ACTION: Checks to see if an element is set to be visible or hidden. If the


return value is false, the element is hidden; if the return value is
true, the element is visible.

FUNCTION RETURN TYPE: int

RETURN: FALSE Hidden


TRUE Visible

INPUT ARGUMENTS: SC_Element Element Element that is being examined

100
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_InitHandle

PROTOTYPE: HSC_Element scElement_InitHandle(HSC_DB hDB)

ACTION: Returns the handle to the initial element in the SURFCAM


database. If there are no elements in the database, the function
returns INVALID_HANDLE in the member variable hEl of the
returned element handle.

FUNCTION RETURN TYPE: HSC_Element

RETURN: The handle of the initial element in the database

INPUT ARGUMENTS: HSC_DB hDB Database handle

SAMPLE CODE:
// This code demonstrates how to manipulate the SURFCAM database
// The following routine will read through the entire database
// and assign any points to layer 30 and any lines to layer 40
HSC_DB hDatabase;
HSC_Element hElementTemp;
SC_Element * pElement;
int iType, iReturn, iLayer;

hDatabase = scDB_GetHandle(); // Retrieve the handle to the database

for (hElementTemp = scElement_InitHandle(hDatabase); // Set up loop


hElementTemp.hEl != INVALID_HANDLE;
hElementTemp = scElement_GetNextHandle(hDatabase)) {

iType = scElement_GetTypeFromHandle(hElementTemp); // Retrieve element type

if (iType == SC_POINT) { // If it’s a point...


SC_Point * pPoint = scElement_GetPoint(hElementTemp); // Get the point
iReturn = scElement_SetLayerAttribute(pPoint, 30); // Assign it to layer 30
assert (iReturn == 0);
}
else if (iType == SC_LINE) { // If it’s a line...
SC_Line * pLine = scElement_GetLine(hElementTemp); // Get the line
iReturn = scElement_SetLayerAttribute(pLine, 40); // Assign it to layer 40
assert (iReturn == 0);
}
}

101
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_NextHandle

PROTOTYPE: HSC_Element
scElement_NextHandle(HSC_Element hElement )

ACTION: Returns the next element handle from the database. If the next
element is invalid or there is no next element, the hEl member of
the returned HSC_Element is set to INVALID_HANDLE.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Returns the next element handle from the database or an


HSC_Element with the hEl member set to INVALID_HANDLE if
the next element is invalid.

INPUT ARGUMENTS: HSC_Element hElement Element handle

SAMPLE CODE:
// This code demonstrates how to read through the SURFCAM database
HSC_DB hDatabase;
HSC_Element hElementTemp;
int iType;
SC_Point * pPoint;
SC_Lmesh * pLMesh;
SC_Arc * pArc;

hDatabase = scDB_GetHandle(); // Retrieve the handle to the database

for (hElementTemp = scElement_InitHandle(hDatabase); // Set up loop


hElementTemp.hEl != INVALID_HANDLE;
hElementTemp = scElement_GetNextHandle(hDatabase)) {

iType = scElement_GetTypeFromHandle(hElementTemp); // Retrieve element type

switch (iType) {
case SC_POINT:
pPoint = scElement_GetPoint(hElementTemp); // Get the point
break;
case SC_LMESH:
pLMesh = scElement_GetLmesh(hElementTemp); // Get the line mesh
break;
case SC_ARC:
pArc = scElement_GetArc(hElementTemp); // Get the arc
break;
}
}

102
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_SetColorAttribEx

PROTOTYPE: int scElement_SetColorAttribEx(HSC_Element hElem,


int iColor)

ACTION: Sets the color of an element on screen and in the SURFCAM


database.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: HSC_Element hElem Handle of element


int iColor Color desired
BLACK Black
DARKBLUE Dark Blue
DARKGREEN Dark Green
DARKCYAN Dark Cyan
DARKRED Dark Red
DARKMAGENTA Dark Magenta
DARKYELLOW Dark Yellow
LIGHTGRAY Light Gray
DARKGRAY Dark Gray
BRIGHTBLUE Bright Blue
BRIGHTGREEN Bright Green
BRIGHTCYAN Bright Cyan
BRIGHTRED Bright Red
BRIGHTMAGENTA Bright Magenta
BRIGHTYELLOW Bright Yellow
WHITE White

103
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_SetColorAttrib

PROTOTYPE: int scElement_SetColorAttrib( SC_Element Element,


int iColor)

ACTION: Sets the color of an element on the screen.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Element that is being colored


int iColor Color desired
BLACK Black
DARKBLUE Dark Blue
DARKGREEN Dark Green
DARKCYAN Dark Cyan
DARKRED Dark Red
DARKMAGENTA Dark Magenta
DARKYELLOW Dark Yellow
LIGHTGRAY Light Gray
DARKGRAY Dark Gray
BRIGHTBLUE Bright Blue
BRIGHTGREEN Bright Green
BRIGHTCYAN Bright Cyan
BRIGHTRED Bright Red
BRIGHTMAGENTA Bright Magenta
BRIGHTYELLOW Bright Yellow
WHITE White

104
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_SetLayerAttribEx

PROTOTYPE: int scElement_SetLayerAttribEx(HSC_Element hElem,


int iLayer )

ACTION: Assigns an element to a layer on screen and in the SURFCAM


database. Moving a visible element to an invisible layer results in
the removal of the element from the screen, and moving the
element from an invisible layer to a visible layer results in the
addition of the element to the screen.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: HSC_Element hElem Handle of the element


int iLayer Assigned layer for element

SAMPLE CODE:
// This code demonstrates how to manipulate the SURFCAM database
// The following routine will read through the entire database
// and assign any points to layer 30 and any lines to layer 40

HSC_DB hDatabase;
HSC_Element hElementTemp;
int iType, iReturn, iLayer;

hDatabase = scDB_GetHandle(); // Retrieve the handle to the database

for (hElementTemp = scElement_InitHandle(hDatabase); // Set up loop


hElementTemp.hEl != INVALID_HANDLE;
hElementTemp = scElement_GetNextHandle(hDatabase)) {

iType = scElement_GetTypeFromHandle(hElementTemp); // Retrieve element type

if (iType == SC_POINT) { // If it’s a point...


iReturn = scElement_SetLayerAttribute(hElementTemp, 30);// Assign it to layer 30
}
else if (iType == SC_LINE) { // If it’s a line...
iReturn = scElement_SetLayerAttribute(hElementTemp, 40);// Assign it to layer 40
}
}

105
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_SetLayerAttrib

PROTOTYPE: int scElement_SetLayerAttrib(SC_Element Element,


int iLayer )

ACTION: Assigns an element to a layer.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Element that is being assigned


int iLayer Assigned layer for element

SAMPLE CODE:
// This code demonstrates how to manipulate the SURFCAM database
// The following routine will read through the entire database
// and assign any points to layer 30 and any lines to layer 40

HSC_DB hDatabase;
HSC_Element hElementTemp;
SC_Element * pElement;
int iType, iReturn, iLayer;

hDatabase = scDB_GetHandle(); // Retrieve the handle to the database

for (hElementTemp = scElement_InitHandle(hDatabase); // Set up loop


hElementTemp.hEl != INVALID_HANDLE;
hElementTemp = scElement_GetNextHandle(hDatabase)) {

iType = scElement_GetTypeFromHandle(hElementTemp); // Retrieve element type

if (iType == SC_POINT) { // If it’s a point...


SC_Point * pPoint = scElement_GetPoint(hElementTemp); // Get the line
iReturn = scElement_SetLayerAttribute(pPoint, 30); // Assign it to layer 30
assert (iReturn == 0);
}
else if (iType == SC_LINE) { // If it’s a line...
SC_Line * pLine = scElement_GetLine(hElementTemp); // Get the line
iReturn = scElement_SetLayerAttribute(pLine, 40); // Assign it to layer 40
assert (iReturn == 0);
}
}

106
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scElement_ValidHandle

PROTOTYPE: int scElement_ValidHandle(HSC_Element hElement )

ACTION: Checks the validity of an element handle.

FUNCTION RETURN TYPE: int

RETURN: FALSE Invalid handle


TRUE Valid handle

INPUT ARGUMENTS: HSC_Element hElement Element handle

107
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scElement_WriteToDB

PROTOTYPE: HSC_Element scElement_WriteToDB( HSC_DB hDB,


SC_Element elem)

ACTION: Writes an element into the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle

INPUT ARGUMENTS: HSC_DB hDB Database handle


SC_Element elem Element

108
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLayer_AllocMem

PROTOTYPE: SC_Layer * scLayer_AllocMem();

ACTION: Allocates memory for a layer.

FUNCTION RETURN TYPE: SC_Layer *

RETURN: Pointer to address of layer in memory or NULL if unsuccessful

ARGUMENTS: <None>

109
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scLayer_FindFreeLayer

PROTOTYPE: int scLayer_FindFreeLayer()

ACTION: Checks to see if there is a free layer available. If one exists, the
function returns the lowest layer reference number.

FUNCTION RETURN TYPE: int

RETURN: 0-255 Lowest reference number of free layer


-1 No free layers exist

ARGUMENTS: <None>

110
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLayer_FindNextAllocLayer

PROTOTYPE: int scLayer_FindNextAllocLayer(int iMinimum)

ACTION: Checks to see if there is a layer that has been allocated memory
with a reference number higher than iMinimum. If one exists, the
function returns the lowest layer reference number.

FUNCTION RETURN TYPE: int

RETURN: 0 - 255 The reference number of the


next allocated layer
INVALID_LAYER No layers have been allocated
memory

INPUT ARGUMENTS: int iMinimum The specified lowest layer

111
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scLayer_FindNextFreeLayer

PROTOTYPE: int scLayer_FindNextFreeLayer(int iMinimum)

ACTION: Checks to see if there is a free layer available with a reference


number equal to or higher than iMinimum. If one exists, the
function returns the lowest layer reference number.

FUNCTION RETURN TYPE: int

RETURN: 0-255 The number of the next free


layer
INVALID_LAYER No free layers exist

INPUT ARGUMENTS: int iMinimum The specified lowest layer

112
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLayer_GetAttrib

PROTOTYPE: void scLayer_GetAttrib(int iLayer, int Attributes [3])

ACTION: Gets the attributes for a specified layer. The value filled for
Attributes [0] indicates whether the layer has been allocated in
SURFCAM. The value filled in Attributes [1] indicates whether
the layer is visible. The value filled in Attributes [2] indicates
whether the layer is active. The values can be TRUE or FALSE.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: int iLayer Layer reference number

OUTPUT ARGUMENTS: int Attributes [3] Array of layer attributes


Attributes [0] Allocated attribute
Attributes [1] Visible attribute
Attributes [2] Active attribute

113
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scLayer_GetFromHandle

PROTOTYPE: UINT scLayer_GetFromHandle(HSC_Element h)

ACTION: Returns the reference number of the layer according to the


element handle.

FUNCTION RETURN TYPE: unsigned int

RETURN: Reference number of a layer given the element handle

INPUT ARGUMENTS: HSC_Element h Element handle

114
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLayer_GetLayerFromHandle

PROTOTYPE: UINT scLayer_GetLayerFromHandle(HSC_Element h)

ACTION: Returns the reference number of the layer according to the


element handle.

FUNCTION RETURN TYPE: unsigned int

RETURN: Reference number of a layer given the element handle

INPUT ARGUMENTS: HSC_Element h Element handle

115
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scLayer_GetName

PROTOTYPE: int scLayer_GetName(int iLayer,


char * sBuffer,
int iBufferSize )

ACTION: Gets the name of a layer when given a layer reference number.
The name is written into a character buffer sBuffer with length
iBufferSize.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: int iLayer Layer reference number


int iBufferSize Size of buffer for layer name

OUTPUT ARGUMENTS: char * sBuffer Buffer that stores the layer name

116
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLayer_WriteToDB

PROTOTYPE: HSC_Element scLayer_WriteToDB( HSC_DB hDB,


SC_Layer * Layer)

ACTION: Write a layer to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle

INPUT ARGUMENTS: HSC_DB hDB Handle for database


SC_Layer * Layer Layer to be written

117
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scLine_AllocMem

PROTOTYPE: SC_Line * scLine_AllocMem()

ACTION: Allocates memory for a line.

FUNCTION RETURN TYPE: SC_Line *

ARGUMENTS: <None>

RETURN: Pointer to address of line created or NULL if unsuccessful

118
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLine_WriteToDB

PROTOTYPE: HSC_Element scLine_WriteToDB(HSC_DB hDB,


SC_Line * Line )

ACTION: Writes a line to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle

INPUT ARGUMENTS: HSC_DB hDB Database handle


SC_Line * line Line to be written

119
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_BackWalk

PROTOTYPE: int scList_BackWalk(ll_handle * list,


int (* pFunction)(void * Element, int iElementSize))

ACTION: Walks a list backward calling a specified function (pFunction) for


every element in the list (see scList_Walk). The function
must return an integer, and must have arguments for a pointer to
an element and the element size.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: ll_handle * list Specified list


int (* pFunction) (void * Element, int iElementSize)
Function to be called for every
element in the list (the function
gets passed a pointer to the list
elements and the size of the
corresponding element)

120
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_Concat

PROTOTYPE: ll_handle * scList_Concat(ll_handle * List1, ll_handle * List2 )

ACTION: Concatenates two lists into one. The second list is destroyed
after being concatenated with the first list.

FUNCTION RETURN TYPE: ll_handle *

RETURN: Pointer to the resulting list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List1 Primary list


ll_handle * List2 List to concatenate

121
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_Final

PROTOTYPE: void scList_Final(ll_handle * List )

ACTION: Frees up the memory allocated for the list, destroying the list.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: ll_handle * List Specified list

122
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_GetHead

PROTOTYPE: void * scList_GetHead(ll_handle * List, int * iSize)

ACTION: Retrieves the element at the head (top) of the list, also retrieving
the size of the element.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to top element in list or NULL if unsuccessful

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: ll_handle * List Specified list

123
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_GetNext

PROTOTYPE: void * scList_GetNext(void * Element, int * iSize)

ACTION: Retrieves the next element in the list, also getting the size of the
element.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to the next element in the list or NULL if unsuccessful

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: void * Element Current list element pointer

124
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_GetPrev

PROTOTYPE: void * scList_GetPrev(void * Element, int * iSize)

ACTION: Retrieves the previous element in the list, also retrieving the size
of the element.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to the previous element in the list or NULL if unsuccessful

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: void * Element Current list element pointer

125
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_GetTail

PROTOTYPE: void * scList_GetTail(ll_handle * List, int * iSize)

ACTION: Retrieves the element at the tail (bottom) of the list, also retrieving
the size of the element.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to bottom (tail) element in list or NULL if unsuccessful

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: ll_handle * List Specified list

126
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_Init

PROTOTYPE: ll_handle * scList_Init()

ACTION: Creates an empty list of elements, returning the pointer to the


allocated linked list.

FUNCTION RETURN TYPE: ll_handle *

RETURN: Pointer to created list or NULL if unsuccessful

ARGUMENTS: <None>

127
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_InsertElement

PROTOTYPE: void * scList_InsertElement( ll_handle * List,


void * Pos,
void * Element,
int iSize)

ACTION: Inserts an element into the list in front of the element Pos.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to element in list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List Specified list


void * Pos Position to insert element
void * Element Element to be inserted
int iSize Size of element to be inserted

128
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_InsertHead

PROTOTYPE: void * scList_InsertHead(ll_handle * List,


void * Element,
int iSize)

ACTION: Inserts an element at the head of the list.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to element in list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List Specified list


void * Element Element to be inserted
int iSize Size of element

129
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_InsertTail

PROTOTYPE: void * scList_InsertTail(ll_handle * List,


void * Element,
int iSize)

ACTION: Inserts an element at the tail of the list.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to element in list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List Specified list


void * Element Element to be inserted
int iSize Size of element

130
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_IsEmpty

PROTOTYPE: int scList_IsEmpty(ll_handle * List )

ACTION: Checks to seek if the list is empty.

FUNCTION RETURN TYPE: int

RETURN: FALSE List has elements


TRUE List is empty

INPUT ARGUMENTS: ll_handle * List Specified list

131
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_MoveElement

PROTOTYPE: void * scList_MoveElement( ll_handle * List1,


void * Element1,
ll_handle * List2,
void * Element2 )

ACTION: Moves element Element1 in List1 to List2 in a position after


Element2. Note that this function can also be used for a single
list by setting List1 and List2 to the address of the single list.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to element in list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List1 List 1


ll_handle * List2 List 2
void * Element1 Element to move in List1
void * Element2 Element in List2 to put after
Element1 in List 1

132
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_MoveHead

PROTOTYPE: void * scList_MoveHead( ll_handle * List1,


void * Element,
ll_handle * List2 )

ACTION: Moves a specified element to the head of list List2.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to element in list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List1 List 1


ll_handle * List2 List 2
void * Element Element in List1

133
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_MoveTail

PROTOTYPE: void * scList_MoveTail( ll_handle * List1,


void * Element,
ll_handle * List2 )

ACTION: Moves a specified element in list 1 to the end (tail) of list 2.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to element in list or NULL if unsuccessful

INPUT ARGUMENTS: ll_handle * List1 List 1


ll_handle * List2 List 2
void * Element Element in List1

134
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_NumElements

PROTOTYPE: int scList_NumElements(ll_handle * List )

ACTION: Returns the number of elements in the list.

FUNCTION RETURN TYPE: int

RETURN: Number of elements in the list

INPUT ARGUMENTS: ll_handle * List Specified list

135
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_Reinit

PROTOTYPE: void scList_Reinit( ll_handle * )

ACTION: Reinitialize the linked list of ll_handle with an empty list of


elements..

FUNCTION RETURN TYPE: void

RETURN: void

ARGUMENTS: ll_handle * List Specified list

136
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_RemoveAll

PROTOTYPE: void scList_RemoveAll(ll_handle * List )

ACTION: Reinitializes the list by removing all elements.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: ll_handle * List Specified list

137
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_RemoveElement

PROTOTYPE: int scList_RemoveElement(ll_handle * List,


void * Element )

ACTION: Removes a specified element from a list.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: ll_handle * List Specified list


void * Element Element to be removed

138
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_RemoveHead

PROTOTYPE: int scList_RemoveHead(ll_handle * List )

ACTION: Removes the element at the head of the list.

FUNCTION RETURN TYPE: int

INPUT ARGUMENTS: ll_handle * List Specified list

RETURN: 0 Success
~0 Fail

139
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_RemoveTail

PROTOTYPE: int scList_RemoveTail(ll_handle * List )

ACTION: Removes the element at the tail of the list

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: ll_handle * List Specified list

140
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scList_Sort

PROTOTYPE: int scList_Sort( ll_handle * List,


int (*)(void * Element1, void * Element2 ))

ACTION: Sorts the list according to the specified function. For example, a
pre-defined function HIGH (SC_Point *, SC_Point *) could be
used to sort a point list from highest point to lowest point. The
sorting function must return an integer.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: ll_handle * List Specified list


int (*)(void * Element1, void * Element2 )
Pointer to sorting function (the
sorting function takes pointers to
two elements in the list)

141
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scList_Walk

PROTOTYPE: int scList_Walk(ll_handle * List,


int (* pFunction)(void * Element, int iElementSize) )

ACTION: Walks forward through the specified list, passing each list
element to the function pFunction.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: ll_handle * List Specified list


int (* pFunction) (void * Wlement, int iElementSize )
Function to be called for every
element in the list (the function
is passed a pointer to the list
elements and the size of the
corresponding element)

142
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLmesh_AllocMem

PROTOTYPE: SC_Lmesh * scLmesh_AllocMem(int iRows, int iColumns )

ACTION: Allocate memory for a line mesh of iRows rows and iColumns
columns, defining the address in the computer’s memory. Use
scElement_Final to free the allocated memory, and
scMem_Free to free the array of points associated with the line
mesh.

FUNCTION RETURN TYPE: SC_LMesh *

RETURN: Pointer to address of line mesh or NULL if unsuccessful

INPUT ARGUMENTS: int iRows Number of rows in line mesh


int iColumns Number of columns in line mesh

143
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scLmesh_GetPoints

PROTOTYPE: int scLmesh_GetPoints( HSC_Element hElement,


int * iNumPtsU, int * iNumPtsV,
SC_Point ** Points)

ACTION: Returns the mesh points for a given surface element. Note that
this function allocates memory for the array of mesh points
created and returned during its operation. Use
scElement_Final to free the allocated memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: HSC_Element hElement Element handle

OUTPUT ARGUMENTS: int * iNumPtsU Number of points in u direction


int * iNumPtsV Number of points in v direction
SC_Point ** Points Array of points (in world
coordinates)

144
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scLmesh_WriteToDB

PROTOTYPE: HSC_Element scLmesh_WriteToDB ( HSC_DB hDB,


SC_Lmesh * Lmesh)

ACTION: Writes a line mesh to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle or NULL if unsuccessful

INPUT ARGUMENTS: HSC_DB hDB Database handle


SC_Lmesh * Lmesh Line mesh to be written

145
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMat_GetRotation

PROTOTYPE: int scMat_GetRotation(SC_DirVector * AxisVector,


SC_Point * AxisPoint,
double dblAngle,
double dblMatrix [4][4])

ACTION: Construct a rotation matrix given the angle from a specified vector
in world coordinates.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_DirVector * AxisVector Vector direction


SC_Point * AxisPoint Vector position
double dblAngle Angle of rotation

OUTPUT ARGUMENTS: double dblMatrix [4][4] Four-by-four rotation matrix

146
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMat_Identity

PROTOTYPE: void scMat_Identity(double dblMatrix [4][4])

ACTION: Constructs an identity matrix.

FUNCTION RETURN TYPE: void

RETURN: <None>

OUTPUT ARGUMENTS: double dblMatrix [4][4] Four-by-four identity matrix

147
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMat_Inverse

PROTOTYPE: void scMat_Inverse(double dblMatrix [4][4],


double dblInvMatrix [4][4])

ACTION: Calculates and returns inverse of a four-by-four matrix.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: double dblMatrix [4][4] Four-by-four original matrix

OUTPUT ARGUMENTS: double dblInvMatrix [4][4] Four-by-four inverse matrix

148
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMat_InverseTransform

PROTOTYPE: void scMat_InverseTransform(SC_Point * Original,


SC_Point * Result,
double dblMatrix [4][4],
int iFlags)

ACTION: Calculates and returns inverse transform of point original using


the orthogonal matrix matrix [4][4].

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point * Original Point to be transformed


double dblMatrix [4][4] Four-by-four inverse
transformation matrix
int iFlags Transformation flag (flags = 0
specifies a point to be
transformed, thus the point must
be both rotated and translated;
flags = 1 specifies that the input
element is a vector, and thus
requires only rotation.)

OUTPUT ARGUMENTS: SC_Point * Result Resulting point

149
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMat_InverseTranform2d

PROTOTYPE: void scMat_InverseTransform2d(double * Original2D,


double * Result2,
double dblMatrix [4][4],
int iVectorFlag)

ACTION: Calculates and returns inverse transform (2D) of the two


dimensional point Original2D using orthogonal matrix
dblMatrix [4][4]. This operation may be performed on either a
point or a vector; if the element is a point, the point is both rotated
and translated. If the element is a vector, the point is rotated.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: double * Original2D Original x-y coordinates


double dblMatrix [4][4] Four-by-four original matrix
int iVectorFlag Transformation flag
FALSE Original2D is a point
TRUE Original2D is a vector

OUTPUT ARGUMENTS: double * Result2D Transformed x-y coordinates

150
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMat_Multiply

PROTOTYPE: int scMat_Multiply( double dblMatrixA [4][4],


double dblMatrixB [4][4],
double dblMatrixC [4][4])

ACTION: Returns the product (dblMatrixC [4][4]) of two four-by-four


matrices (dblMatrixA [4][4] and dblMatrixB [4][4]).

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: double dblMatrixA [4][4] Four-by-four matrix A


double dblMatrixB [4][4] Four-by-four matrix B

OUTPUT ARGUMENTS: double dblMatrixC [4][4] Four-by-four product matrix C

151
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMat_OrthoInverse

PROTOTYPE: void scMat_OrthoInverse(double dblMatrix [4][4],


double dblInvMatrix [4][4])

ACTION: Returns the inverse of an orthogonal four-by-four matrix. This


function is both faster and more numerically stable than the
function scMat_Inverse. If the matrix is not orthogonal, the result
is undefined.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: double dblMatrix [4][4] Four-by-four original matrix

OUTPUT ARGUMENTS: double dblInvMatrix [4][4] Four-by-four inverted matrix or


undefined if unsuccessful

152
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMat_SetColumn

PROTOTYPE: void scMat_SetColumn(SC_Point *v ,


double mat [3][3],
int col)

ACTION: Set column of the matrix

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point* v value to set


double mat[3][3] matrix to set
Int col Column to set

OUTPUT ARGUMENTS: Double mat[3][3] matrix to set

153
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMat_Transform

PROTOTYPE: void scMat_Transform( SC_Point * Original,


SC_Point * Result,
double dblMatrix [4][4],
int iVectorFlag)

ACTION: Transforms point Original into Result using the transformation


matrix dblMatrix. This operation may be performed on either a
point or a vector; if the element is a point, the point is both rotated
and translated. If the element is a vector, the point is rotated.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point * Original Original point


double dblMatrix [4][4] Four-by-four transformation
matrix
int iVectorFlag Transformation flag
FALSE Original is a point
TRUE Original is a vector

OUTPUT ARGUMENTS: SC_Point * Result Transformed point

154
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMat_Transform2d

PROTOTYPE: void scMat_Transform2d( double *ps2 ,


double *pd2 ,
double mat [4][4],
int flags )

ACTION: Transform a 2D point

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: double* ps2 Starting point


double mat [4][4] Transform matrix
int flags 1 for vector and 0 for point

OUTPUT ARGUMENTS: double* pd2 Point from transformation

155
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMat_Transpose

PROTOTYPE: void scMat_Transpose(double dblMatrix [4][4],


double dblTMatrix [4][4])

ACTION: Transposes a four-by-four matrix.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: double dblMatrix [4][4] Original matrix

OUTPUT ARGUMENTS: double dblTMatrix [4][4] Transpose of matrix

156
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMem_Alloc

PROTOTYPE: void * scMem_Alloc(unsigned int iSize)

ACTION: Returns address of “malloc” allocated memory of size iSize.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to address of “malloc” allocated memory or NULL if


unsuccessful

INPUT ARGUMENTS: unsigned int iSize Size of memory block

157
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMem_CheckAlloc

PROTOTYPE: int scMem_CheckAlloc(void * pMemory)

ACTION: Check memory allocation allocated by SURFCAM given an


address.

FUNCTION RETURN TYPE: int

RETURN: FALSE Memory not allocated


TRUE Memory allocated

INPUT ARGUMENTS: void * pMemory Pointer to memory address

158
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMem_CheckAllocList

PROTOTYPE: int scMem_CheckAllocList()

ACTION: Checks validity of “malloc” allocated list.

FUNCTION RETURN TYPE: int

RETURN: 0 Memory is valid


~0 Memory is invalid

ARGUMENTS: <None>

159
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMem_CountAllocList

PROTOTYPE: int scMem_CountAllocList()

ACTION: Returns the current number of memory allocations.

FUNCTION RETURN TYPE: int

RETURN: Number of current memory allocations

ARGUMENTS: <None>

160
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMem_Free

PROTOTYPE: void scMem_Free(void * pMemory)

ACTION: Free memory block referenced by pMemory. This will deallocate


the memory and invalidate the pointer.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: void * pMemory Pointer to memory address

161
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scMem_FreeAll

PROTOTYPE: void scMem_FreeAll()

ACTION: Free all the memory allocated by the current DLL using
SURFCAM memory allocation functions (e.g.
scMem_AllocMem, scPoint_AllocMem,
scNcurve_AllocMem).

FUNCTION RETURN TYPE: void

RETURN: <None>

ARGUMENTS: <None>

162
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scMem_Realloc

PROTOTYPE: void * scMem_Realloc(void * pMemory, unsigned int iSize)

ACTION: Reallocates memory block size (the new memory block may be at
a different address from the original memory block).

FUNCTION RETURN TYPE: void *

RETURN: Address of resulting memory allocation

INPUT ARGUMENTS: unsigned int iSize Desired size of memory block


void * pMemory Pointer to original memory
address

163
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_AllocMem

PROTOTYPE: SC_NurbCurve * scNcurve_AllocMem( unsigned int iPoints,


unsigned int iOrder)

ACTION: Allocates memory for a NURB curve.

FUNCTION RETURN TYPE: SC_NurbCurve *

RETURN: Memory address of NURB curve or NULL if unsuccessful

INPUT ARGUMENTS: unsigned int iPoints Number of control points in


NURB curve
unsigned int iOrder Order of NURB curve (1-21)

164
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ArcToNurb

PROTOTYPE: int scNcurve_ArcToNurb(SC_Arc * Arc,


SC_NurbCurve ** NCurve,
int iFlag)

ACTION: Converts an arc to a NURB curve. The parameter flag


determines the parameterization of the resulting NURB curve.
Note that this function allocates memory for a NURB curve.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Arc * Arc Arc to be converted


int iFlag NURB curve parameter flags
PARAM_CHORD_LENGTH Defined by arc’s chord length
PARAM_NORMALIZED Normalized arc (0.0 to 1.0)
PARAM_DEFAULT Defined by angle

OUTPUT ARGUMENTS: SC_NurbCurve ** NCurve Pointer to resulting NURB curve

165
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_Break

PROTOTYPE: int scNcurve_Break( SC_NurbCurve ** NCurve,


double dblStart,
double dblEnd,
double dblTolerance )

ACTION: Retrieves a NURB curve from the original NURB curve given start
and end parameters and a specified tolerance. The NURB curve
is redefined by this function. Note: If the start or end parameter
falls within the tolerance distance of any of the original curve’s
knots, the resulting endpoint will be defined at that knot.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_NurbCurve ** NCurve NURB curve

INPUT ARGUMENTS: double dblStart Start curve parameter


double dblEnd End curve parameter
double dblTolerance Tolerance

166
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ChainNurbs

PROTOTYPE: int scNcurve_ChainNurbs( SC_NurbCurve * NurbList [ ],


int * iRevFlag,
int iNum,
SC_NurbCurve ** Result )

ACTION: Converts a list of NURB curves into one curve. The resulting
curve may be reversed from the direction of the original curve list.
Note that this function allocates memory for a NURB curve.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * NurbList [ ] List of original NURB curves


int * iRevFlag Reverse curve direction flag
NATURAL Maintains curve direction
REVERSED Reverses curve direction

int iNum Number of NURB curves in list

OUTPUT ARGUMENTS: SC_NurbCurve ** Result Resulting NURB curve

167
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_Clamp

PROTOTYPE: int scNcurve_Clamp(SC_NurbCurve ** NCurve)

ACTION: Clamps the NURB curve. The NURB curve is clamped at each
interior knot, resulting in an equivalent NURB curve that is a
series of Bezier spans.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_NurbCurve ** NCurve NURB curve

168
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ClipParam1

PROTOTYPE: int scNcurve_ClipParam1( SC_Element Curve,


SC_Gcrv_param_type * P1,
SC_Gcrv_param_type * P2)

ACTION: Clips parameter P2 to lie in the span where P1 lies. The


parameters P1 and P2 are given in terms of curve space and
correspond to parametric distances along the given curve.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_Gcrv_param_type * P2 Parameter to be clipped.

INPUT ARGUMENTS: SC_Element Curve Curve element


SC_Gcrv_param_type * P1 Parameter point determining
span to which P2 will be
clipped.

169
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_ClipParam2

PROTOTYPE: int scNcurve_ClipParam2(SC_Element Curve,


SC_Gcrv_param_type * P1,
SC_Gcrv_param_type * P2,
SC_Gcrv_param_type * RP1,
SC_Gcrv_param_type * RP2)

ACTION: Clips the specified parameter P2 to lie in the span where P1 lies.
The parameters P1 and P2 are given in terms of curve space
and correspond to distances along the given curve. In addition,
the function outputs two parameters RP1 and RP2 which are
clamped to either side of the nearest curve knot.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Curve Curve element


SC_Gcrv_param_type * P1 Parameter that determines the
span to which the output
parameter will be clipped
SC_Gcrv_param_type * P2 Parameter to be clipped

OUTPUT ARGUMENTS: SC_Gcrv_param_type * RP1 Clamped output parameter 1


SC_Gcrv_param_type * RP2 Clamped output parameter 2

170
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ConicToNurb

PROTOTYPE: int scNcurve_ConicToNurb( SC_Conic * ConicCurve,


int iStdConicFlag,
SC_NurbCurve ** NCurve)

ACTION: Converts a conic entity into a NURB curve. The conic can be a
standard conic or a non-standard conic. This function allocates
memory for the resulting NURB curve. Use scElement_Final
to free the allocated block of memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Conic * ConicCurve Conic curve to be converted


int iStdConicFlag Standard parameter flag
FALSE Non-standard conic
TRUE Standard conic

OUTPUT ARGUMENTS: SC_NurbCurve ** NCurve Pointer to resulting NURB curve

171
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_ConvertToArcLine

PROTOTYPE: int scNcurve_ConvertToArcLine(HSC_Element hElem,


double *dTol, double *dMinR, double
*dMaxR, int *nCheckPts, int *nFitArea,
ll_handle *list)

ACTION: Converts a curve element to Arcs and Lines,


Similar to Surfcam Spline to Arcs function.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: HSC_Element hElem Handle of element


double *dTol Tolerance
double *dMinR Minimum Radius
double *dMaxR Maximum Radius
int *nCheckPts Check points per
span
int *nFitArea Fit Area Least
Squares

OUTPUT ARGUMENTS: ll_handle * List Created elements list

172
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ElementToNurb

PROTOTYPE: int scNcurve_ElementToNurb(SC_Element * Element,


SC_NurbCurve ** NCurve,
int iParamFlag)

ACTION: Converts a curve element to a NURB curve. This function


allocates memory for the resulting NURB curve. Use
scElement_Final to free the allocated block of memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element * Element Element to be converted


int iParamFlag Option flag
1 Chord length
2 Normalized curve
3 Default curve

OUTPUT ARGUMENTS: SC_NurbCurve ** NCurve Pointer to resulting NURB curve

173
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_EllipseToNurb

PROTOTYPE: int scNcurve_EllipseToNurb( SC_Point Center,


SC_Point NormalVec,
SC_Point MajorVec,
double dblMajor,
double dblMinor,
double dblStartAngle,
double dblEndAngle,
SC_NurbCurve ** NCurve)

ACTION: Converts an ellipse to a NURB curve. The ellipse information is


given by the center point Center, the normal vector, the major-
direction vector, and the radii of the ellipse. The start and end
angles of the ellipse are also supplied. This function allocates
memory for the resulting NURB curve. Use scElement_Final
to free the allocated block of memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Point Center Center-point of ellipse (in world


coordinates)
SC_Point NormalVec Normal vector reference point
for ellipse surface (in world
coordinates)
SC_Point MajorVec Major vector reference point
double dblMajor Major radius of ellipse
double dblMinor Minor radius of ellipse
double dblStartAngle Starting angle
double dblEndAngle Ending angle

OUTPUT ARGUMENTS: SC_NurbCurve ** NCurve Resulting NURB curve

174
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_EllipseXYToNurb

PROTOTYPE: int scNcurve_EllipseXYToNurb( SC_Point * Center,


double dblMajor,
double dblMinor,
double dblStartAngle,
double dblEndAngle,
double dblEllipseAngle,
SC_NurbCurve ** Curve)

ACTION: Converts an ellipse to a NURB curve. The ellipse information is


given by the center point Center, the ellipse angle, and the radii
of the ellipse. The start and end angles of the ellipse are also
supplied. Note that the ellipse angle is the difference in
orientation between the ellipse and the standard x-y plane. This
function creates and allocates memory for the resulting NURB
curve. Use scElement_Final to free the allocated block of
memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Point Center Center-point of ellipse (in world


coordinates)
double dblMajor Major radius of ellipse
double dblMinor Minor radius of ellipse
double dblStartAngle Starting angle
double dblEndAngle Ending angle
double dblEllipseAngle Ellipse angle

OUTPUT ARGUMENTS: SC_NurbCurve ** Curve Resulting NURB curve

175
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_FitNurb

PROTOTYPE: int
scNcurve_FitNurb(SC_NurbCurve ** NCurve,
double dblTolerance )

ACTION: Fit NURB curve with non-rational NURB curve

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve** NCurve NURB curve to be fit


Double dblTolerance Fitting tolerance

OUTPUT ARGUMENTS: SC_NurbCurve ** NCurve Resulting NURB curve

176
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_FromPointArray

PROTOTYPE: SC_NurbCurve *
scNcurve_FromPointArray( SC_Point * PointArray,
int iPoints)

ACTION: Builds a cubic NURB curve that interpolates the given set of
points. This function allocates memory for the resulting NURB
curve. Use scElement_Final to free the allocated block of
memory.

FUNCTION RETURN TYPE: SC_NurbCurve *

RETURN: Memory address pointer to the resulting NURB curve

INPUT ARGUMENTS: SC_Point * PointArray Pointer to an array of SC_Points


int iPoints Number of points in point array

177
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_FromPointList

PROTOTYPE: SC_NurbCurve *
scNcurve_FromPointList(ll_handle * PointList )

ACTION: Convert a list of points (in world coordinates) to a single NURB


curve (cubic third degree curve) by interpolating the list of points.
This function allocates memory for the resulting NURB curve.
Use scElement_Final to free the allocated block of memory.

FUNCTION RETURN TYPE: SC_NurbCurve *

RETURN: Resulting NURB curve from point list

INPUT ARGUMENTS: ll_handle * PointList Pointer to a points list

178
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_GetPolyDisplayAttrib

PROTOTYPE: int
scNcurve_GetPolyDisplayAttrib(SC_NurbCurve * curve)

ACTION: Checks to see if the control polygon is displayed for a specified


NURB curve.

FUNCTION RETURN TYPE: int

RETURN: FALSE No polygon displayed


TRUE Polygon displayed

INPUT ARGUMENTS: SC_NurbCurve * curve NURB curve being analyzed

179
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_GetRationalAttrib

PROTOTYPE: int scNcurve_GetRationalAttrib(SC_NurbCurve * Curve)

ACTION: Checks to see if a specified NURB curve is rational. The curve is


rational if the returned value is true, and non-rational if the
returned value is false.

FUNCTION RETURN TYPE: int

RETURN: FALSE Non-rational


TRUE Rational

INPUT ARGUMENTS: SC_NurbCurve * Curve NURB curve being analyzed

180
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_InterpPtsTans

PROTOTYPE: int scNcurve_InterpPtsTans(SC_NurbCurve ** Result,


int iPoints,
SC_Point * PointList,
SC_Point * TanList )

ACTION: Creates a NURB curve from a list of points and the tangent
vectors of the curve along those points. This function allocates
memory for the resulting NURB curve. Use scElement_Final
to free the allocated block of memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: int iPoints Number of points


SC_Point * PointList List of points
SC_Point * TanList List of tangent vectors at points

OUTPUT ARGUMENTS: SC_NurbCurve ** Result NURB curve

181
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_JoinTwoNurbs

PROTOTYPE: int scNcurve_JoinTwoNurbs(SC_NurbCurve * First,


SC_NurbCurve * Second,
int iRevFlag,
SC_NurbCurve ** Result )

ACTION: Joins two NURB curves into a single NURB curve. The function
also is able to reverse the direction of the second NURB curve
when defining the point array of the joined NURB curve. This
function allocates memory for the resulting NURB curve. Use
scElement_Final to free the allocated block of memory.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * First First NURB curve


SC_NurbCurve * Second Second NURB curve
int iRevFlag Reverse second curve flag
FALSE No reversal
TRUE Reverse second NURB curve

OUTPUT ARGUMENTS: SC_NurbCurve ** Result Resulting joined NURB curve

182
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ProjectLoop2Nsurf

PROTOTYPE: int scNcurve_ProjectLoop2Nsurf(int curve_num,


SC_NurbCurve ** Curve,
SC_NurbSurface * Surface,
SC_TrimCurve **trim_curve,
double Proj_tol )

ACTION: Project a loop of curves onto surface

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: int curve_num Number of curves to project


SC_NurbCurve * Curve NURB curve list
SC_NurbSurface * Surface NURB surface
Double Proj_tol Project tolerance

OUTPUT ARGUMENTS: SC_NurbCurve ** trim_curve Resulting trimmed NURB curve

183
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_ProjectToNsurf

PROTOTYPE: int scNcurve_ProjectToNsurf(SC_NurbCurve * Curve,


SC_NurbSurface * Surface,
SC_TrimCurve **trim_curve,
double Proj_tol )

ACTION: Project curve onto surface

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * Curve NURB curve


SC_NurbSurface * Surface NURB surface
Double Proj_tol Project tolerance

OUTPUT ARGUMENTS: SC_NurbCurve ** trim_curve Resulting trimmed NURB curve

184
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_ProjectUVToNsurf

PROTOTYPE: int scNcurve_ProjectUVToNsurf(


SC_NurbCurve * curve_uv,
SC_NurbSurface * Surface,
SC_TrimCurve **trim_curve,
double Proj_tol )

ACTION: Project UV parametric curve onto surface

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * Curve_uv NURB curve


SC_NurbSurface * Surface NURB surface
Double Proj_tol Project tolerance

OUTPUT ARGUMENTS: SC_NurbCurve ** trim_curve Resulting trimmed NURB curve

185
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_RaiseOrder

PROTOTYPE: int scNcurve_RaiseOrder(


SC_NurbCurve ** nurb_curve,
int nTargetorder )

ACTION: Increase the curve order

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve ** nurb_curve NURB curve


int nTargetorder Order number requested

OUTPUT ARGUMENTS: SC_NurbCurve ** nurb_curve Resulting NURB curve

186
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_RemoveKnots

PROTOTYPE: int scNcurve_RemoveKnots(SC_NurbCurve** Ncurve,


int iNum )

ACTION: Removes unnecessary knots from a specified NURB curve. In


order to remove all the duplicate knots from a knot position, pass
a zero for iNum. In order to keep one duplicate knot at each knot
location, pass a one for iNum. This function will not change the
shape of the curve, but will change the data structure.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT
ARGUMENTS: SC_NurbCurve ** NCurve NURB curve
int iNum Number of duplicate knots to
retain

187
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_Reverse

PROTOTYPE: int scNcurve_Reverse(SC_NurbCurve** NCurve)

ACTION: Reverses the direction of a specified NURB curve. This function


reverses the list of control points and knot vectors in the specified
NURB curve’s structure.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_NurbCurve ** NCurve NURB curve

188
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_SetPolyDisplayAttrib

PROTOTYPE: void
scNcurve_SetPolyDisplayAttrib(SC_NurbCurve * curve,
int iDisplay )

ACTION: Sets control point mesh display attributes of a specified NURB


curve. Set iDisplay to false for no control point mesh, and true for
a visible control point mesh.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbCurve * curve NURB curve being analyzed


int iDisplay Display attribute
FALSE Hide control point mesh
TRUE Display control point mesh

189
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_SetRationalAttrib

PROTOTYPE: void
scNcurve_SetRationalAttrib(SC_NurbCurve * NCurve,
int iRational )

ACTION: Sets the rational attribute of a specified NURB curve. A non-


rational curve does not have weighted control points, while a
rational curve does have weighted control points. This function
defines the curve as a non-rational curve if iRational is set to
false, and rational if iRational is set to true.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbCurve * NCurve NURB curve being set


int iRational Rational display characteristic
FALSE Set NURB curve to rational
TRUE Set NURB curve to non-rational

190
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNcurve_WriteToDB

PROTOTYPE: HSC_Element
scNcurve_WriteToDB(HSC_DB hDB,
SC_NurbCurve * NCurve)

ACTION: Writes a NURB curve to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Handle to the NURB curve in the SURFCAM database

INPUT ARGUMENTS: HSC_DB hDB Handle for database


SC_NurbCurve * NCurve NURB curve to be written

191
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_AllocMem

PROTOTYPE: SC_NurbSurface * scNsurf_AllocMem( UINT iNumPointsU,


UINT iNumPointsV,
UINT iOrderU,
UINT iOrderV)

ACTION: Allocate memory for NURB surfaces.

FUNCTION RETURN TYPE: SC_NurbSurface *

RETURN: Memory address pointer to NURB surfaces

INPUT ARGUMENTS: unsigned int iNumPointsU Number of points in NURB curve


going in the u-direction
unsigned int iNumPointsV Number of points in NURB curve
going in the v-direction
unsigned int iOrderU Order of NURB curve going in
the u-direction (1-21)
unsigned int iOrderV Order of NURB curve going in
the v-direction (1-21)

192
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_ConvertToPolygon

PROTOTYPE: int scNsurf_ConvertToPolygon(SC_NurbSurface * NSurf,


SC_Polygon * Polygons,
int iNumSampleCurves,
double dblTolerance)

ACTION: Converts a NURB surface (NSurf ) to a set of polygons


(Polygons). The function samples the NURB surface at a
specified resolution (iNumSampleCurves) and defines the
resulting polygon. These polygons are used to display the
surface when using the quick shading option in SURFCAM.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface * NSurf NURB surface to be converted


int iNumSampleCurves Number of sampling curves
double dblTolerance Tolerance of conversion error

OUTPUT ARGUMENTS: SC_Polygon * Polygons Polygons to be defined

193
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_Eval

PROTOTYPE: int scNsurf_Eval( SC_Element Element,


int iEvalFlag,
SC_Gpv_param_type * Param,
SC_Point * Point )

ACTION: Returns the point or derivative vector on a surface in world


coordinates given a set of surface parameters describing a
location on the surface. The result depends upon the evaluation
flag passed to the function.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Surface element


int iEvalFlag Evaluation flag
DLL_GSE_POINT Point coordinates
DLL_GSE_NORMAL Normal vector
DLL_GSE_U_PRIME First derivative with respect to u
DLL_GSE_U_DOUBLE_PRIME Second derivative with respect to u
DLL_GSE_V_PRIME First derivative with respect to v
DLL_GSE_V_DOUBLE_PRIME Second derivative with respect to v
DLL_GSE_U_CROSS_V Cross product of u and v
DLL_GSE_TWIST_VECTOR Twist vector
DLL_GSE_NUM_DERIVS

SC_Gpv_param_type * Param Surface parameters describing a


location on the surface

OUTPUT ARGUMENTS: SC_Point * Point Point on surface or derivative


of surface at that point

194
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_EvalCurvature

PROTOTYPE: double
scNsurf_EvalCurvature( SC_Element Surface,
UINT iDirection,
SC_Gpv_param_type * Param )

ACTION: Returns the curvature (inverse of the radius) of a surface element


in a specified parametric direction.

FUNCTION RETURN TYPE: double

RETURN: Curvature of a surface at a point described by a set of surface


parameters

INPUT ARGUMENTS: SC_Element Surface Surface element


unsigned int iDirection Direction of curve
GSC_U_CURVE normal curvature in u direction
GSC_V_CURVE normal curvature in v direction
GSC_NUM_CURVES

SC_Gpv_param_type * Param Surface parameters describing a


location on the surface

195
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_FitNurb

PROTOTYPE: int
scNsurf_FitNurb(SC_NurbSurface ** NSurface,
double dblTolerance )

ACTION: Fit NURB surface with non-rational NURB surface

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface **NSurface Resulting NURB surface


double dblTolerance Tolerance in calculations

196
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_FixDegeneration

PROTOTYPE: int
scNsurf_FixDegeneration(SC_NurbSurface *apNsurf,
double adDegCheckTol,
double adTrimBackSize )

ACTION: Fix degenerate surface

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface * Nsurface Surface to be fixed


double adDegCheckTol Tolerance used to check
surface
double adTrimBackSize TrimBackSized used to
fix the degenerated
surface

197
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_GetArrowDisplayAttrib

PROTOTYPE: int
scNsurf_GetArrowDisplayAttrib(SC_NurbSurface *surf )

ACTION: Checks to see if the arrow for a selected NURB surface has been
set to display the associated surface arrow.

FUNCTION RETURN TYPE: int

RETURN: FALSE Arrow is hidden


TRUE Arrow is displayed

INPUT ARGUMENTS: SC_NurbSurface * surf The specified NURB surface

198
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_GetArrowPositionAttrib

PROTOTYPE: int
scNsurf_GetArrowPositionAttrib(SC_NurbSurface * Surf )

ACTION: Returns the corner at which the surface arrow for a selected
NURB surface has been set to display.

FUNCTION RETURN TYPE: int

RETURN: ULOW_VLOW Corner 1 (low u, low v )


UHIGH_VLOW Corner 2 (high u, low v )
ULOW_VHIGH Corner 3 (low u, high v )
UHIGH_VHIGH Corner 4 (high u, high v )

INPUT ARGUMENTS: SC_NurbSurface * Surf The specified NURB surface

199
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_GetCutDirectionAttrib

PROTOTYPE: int
scNsurf_GetCutDirectionAttrib(SC_NurbSurface * Surf )

ACTION: Returns the direction of a cut (the major direction) for a selected
NURB surface.

FUNCTION RETURN TYPE: int

RETURN: U_DIRECTION u direction


V_DIRECTION v direction

INPUT ARGUMENTS: SC_NurbSurface * Surf The specified NURB surface

200
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_GetIsoNurb

PROTOTYPE: unsigned long


scNsurf_GetIsoNurb( SC_NurbSurface * NSurface,
SC_NurbCurvePtr * NCurveList [ ] )

ACTION: Gets the current isoparametric display curves (u and v ) from a


specified NURB surface. The function also returns the number of
isoparametric curves that are currently being displayed. The
number of curves returned by this function are defined by the
functions scNsurf_SetNumberOfULinesAttrib and
scNsurf_SetNumberOfVLinesAttrib. This function
allocates memory for the NURB curves created. The use
scElement_Final to free the allocated memory.

FUNCTION RETURN TYPE: unsigned long

RETURN: The number of isometric display curves that define the NURB
surface

INPUT ARGUMENTS: SC_NurbSurface * NSurface The specified NURB


surface

OUTPUT ARGUMENTS: SC_NurbCurvePtr * NCurveList [ ] The list of isometric curves

201
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_GetNormalDirectionAttrib

PROTOTYPE: int
scNsurf_GetNormalDirectionAttrib(SC_NurbSurface * Surf )

ACTION: Gets the surface normal vector attribute from a NURB surface
structure. The returned value indicates whether the NURB
surface normal is natural (u x v ) or reversed (v x u ).

FUNCTION RETURN TYPE: int

RETURN: NATURAL Natural (u x v )


REVERSED Reversed (v x u )

INPUT ARGUMENTS: SC_NurbSurface * Surf NURB surface being analyzed

202
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_GetNumberOfULinesAttrib

PROTOTYPE: int
scNsurf_GetNumberOfULinesAttrib(SC_NurbSurface * Surf )

ACTION: Returns the number of defined u-direction display curves in a


specified NURB surface.

FUNCTION RETURN TYPE: int

RETURN: Number of defined u - direction display curves in a specified


NURB surface.

INPUT ARGUMENTS: SC_NurbSurface * Surf NURB surface being analyzed

203
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_GetNumberOfVLinesAttrib

PROTOTYPE: int
scNsurf_GetNumberOfVLinesAttrib(SC_NurbSurface * Surf )

ACTION: Returns the number of defined v -direction display curves in a


specified NURB surface.

FUNCTION RETURN TYPE: int

RETURN: Number of defined v -direction display curves in a specified


NURB surface.

INPUT ARGUMENTS: SC_NurbSurface * Surf NURB surface being analyzed

204
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_GetPolyDisplayAttrib

PROTOTYPE: int
scNsurf_GetPolyDisplayAttrib(SC_NurbSurface * Surf )

ACTION: Checks to see if the control point mesh is displayed for a


specified NURB surface.

FUNCTION RETURN TYPE: int

RETURN: FALSE No control point mesh displayed


TRUE Control point mesh displayed

INPUT ARGUMENTS: SC_NurbSurface * Surf NURB curve being analyzed

205
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_GetSpan

PROTOTYPE: int scNsurf_GetSpan(SC_Element Surface,


SC_Gpv_param_range_type * Range)

ACTION: Returns the u and v parameter ranges of a surface.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Surface Surface element

OUTPUT ARGUMENTS: SC_Gpv_param_range_type * Range Surface parameters

206
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_GetRange

PROTOTYPE: int scNsurf_GetRange(SC_Element Surface,


SC_Gpv_param_range_type * Range)

ACTION: Returns the u and v parameter ranges of a surface.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Surface Surface element

OUTPUT ARGUMENTS: SC_Gpv_param_range_type * Range Surface parameters

207
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

208
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_GetRationalAttrib

PROTOTYPE: int
scNsurf_GetRationalAttrib(SC_NurbSurface * NSurface)

ACTION: Returns the rational attribute of a specified NURB surface. The


surface is rational if the returned value is true, and non-rational if
the returned value is false.

FUNCTION RETURN TYPE: int

RETURN: FALSE Non-rational


TRUE Rational

INPUT ARGUMENTS: SC_NurbSurface * NSurface NURB surface being analyzed

209
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_IsDegeneratedClosed

PROTOTYPE: int
scNsurf_IsDegeneratedClosed(
SC_NurbSurface * Nsurface,
double *tolerance,
int *degenerated,
int *closed)

ACTION: Check to see if the surface is degenerate or closed

FUNCTION RETURN TYPE: int

RETURN: FALSE Non-degenerate or closed


TRUE degenerate or closed

INPUT ARGUMENTS: SC_NurbSurface * NSurface NURB surface to check


Double * tolerance Tolerance used to check surface
OUTPUT ARGUMENTS: int* degenerate Generate information
int* closed Closeness information

210
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_NurbGrid

PROTOTYPE: int scNsurf_NurbGrid(SC_NurbCurve * NCurveListU [ ],


int iNumCurvesU,
SC_NurbCurve * NCurveListV [ ],
int iNumCurvesV,
SC_NurbSurface ** NSurface,
double dblTolerance )

ACTION: Creates a NURB surface from two arrays (NCurveListU [ ] and


NCurveListV [ ] ) of NURB curves. These NURB curves run in the
u -direction and v -direction respectively, and the resulting surface
must fall within the specified tolerance (dblTolerance ) or the
function will fail. Note that this function allocates memory for the
NURB surface during its execution.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * NCurveListU [ ] Array of u-direction NURB


curves
int iNumCurvesU Number of NURB curves in
u-direction curve array
SC_NurbCurve * NCurveListV [ ] Array of v-direction NURB
curves
int iNumCurvesV Number of NURB curves in
v-direction curve array
SC_NurbSurface ** NSurface Resulting NURB surface
double dblTolerance Tolerance in calculations

211
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_NurbListAutoSort

PROTOTYPE: int scNsurf_NurbListAutoSort(SC_NurbCurve * CList [ ],


int iNumCurves,
SC_NurbSurface ** Surf,
double dblTolerance)

ACTION: Creates a NURB surface from an array (CList [ ] ) of NURB


curves. The resulting surface must fall within a specified
tolerance of the NURB curves. Note that this function allocates
memory for a NURB surface during its execution.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * CList [ ] Array of NURB curves


int iNumCurves Number of NURB curves
in the curve array
SC_NurbSurface ** Surf Resulting NURB surface
double dblTolerance Tolerance in calculations

212
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_Offset

PROTOTYPE: int scNsurf_Offset(SC_NurbSurface ** OrigNsurface,


double OffsetDist,
int OffsetSide, int OffsetFactor,
SC_ NurbSurface ** ResltNsurface)

ACTION: Offset a Nurb Surface by a given distance & side

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface ** NSurface Surface that needs offset


double OffsetDist Offset distance
int OffsetSide Offset side
int OffsetFactor Offset factor

OUTPUT ARGUMENTS: SC_ NurbSurface ** NSurface Resulting Surface

213
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_ProjectPoint

PROTOTYPE: int scNsurf_ProjectPoint(SC_NurbSurface ** Nsurface,


SC_Point* pOrigPt,
SC_View* pView, double dTol,
SC_Point* pProjPt )

ACTION: Projects a point onto a surface using a specified view and


calculation tolerance.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface ** NSurface Surface to project onto


SC_Point* pOrigPt Point to project
SC_View* pView View used for projection
double dTol Tolerance of projection

OUTPUT ARGUMENTS: SC_Point* pProjPt Projected point

214
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_ProjectPointParam

PROTOTYPE: int scNsurf_ProjectPointParam(


SC_NurbSurface* pSurf,
SC_Point* pOrigPoint,
SC_View* pView,
double dTol,
SC_Point* pOutPt,
SC_Gpv_param_type* pOutParam)

ACTION: Projects a point onto a surface using a specified view and


returning both point and parameter

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface ** NSurface Surface to project onto


SC_Point* pOrigPoint Point to project
SC_View* pView View used for projection
double dTol Tolerance of projection

OUTPUT ARGUMENTS: SC_Point* pOutPt Projected point


SC_Gpv_param_type* pOutParam parameter of the point

215
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_ProjectPointSide

PROTOTYPE: int scNsurf_ProjectPointSide(


SC_NurbSurface* pSurf,
SC_Point* pOrigPoint,
SC_View* pView,
double dTol,
SC_Point* pOutPt,
int* pSide)

ACTION: Projects a point onto a surface using a specified view and


returning both point and side information of the projected point.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface ** NSurface Surface to project onto


SC_Point* pOrigPoint Point to project
SC_View* pView View used for projection
double dTol Tolerance of projection

OUTPUT ARGUMENTS: SC_Point* pOutPt Projected point


int* pSide Side information of projected
point. 0:Inside;1:Outsie;2:On
boundary

216
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_RemoveKnots

PROTOTYPE: int scNsurf_RemoveKnots(SC_NurbSurface ** Nsurface,


int iDirection )

ACTION: Removes the unnecessary knots from a NURB surface. The


duplicate knots may be removed in the U direction, the V
direction, or both directions.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface ** NSurface Resulting NURB surface


int iDirection Direction of knot removal
U_DIRECTION U Direction
V_DIRECTION V Direction
UV_DIRECTION Both directions

217
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_Revolution

PROTOTYPE: int scNsurf_Revolution(SC_NurbCurve * NCurve,


SC_Point * AxisBase,
SC_Point * AxisHead,
double dblStartAngle,
double dblEndAngle,
SC_NurbSurface ** NSurface)

ACTION: This function creates a NURB surface by revolving a NURB curve


in space. This curve NCurve is rotated around an axis of rotation,
defined by the world coordinate points AxisBase and AxisHead.
The rotation angles are given by dblStartAngle and dblEndAngle,
defining the edges of the revolved surface (parallel to the original
curve). The resulting NURB surface is defined as NSurface.
Note that this function allocates memory for a NURB surface
during its execution.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * NCurve NURB curve to be revolved


SC_Point * AxisBase Reference point 1 for axis
SC_Point * AxisHead Reference point 2 for axis
double dblStartAngle Start angle for revolution
double dblEndAngle End angle for revolution

OUTPUT ARGUMENTS: SC_NurbSurface ** NSurface Resulting NURB surface

218
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_Ruled

PROTOTYPE: int scNsurf_Ruled( SC_NurbCurve * NCurve1,


SC_NurbCurve * NCurve2,
SC_NurbSurface ** NSurface)

ACTION: This function creates a NURB surface by defining a ruled surface


using two existing NURB curves. Note that this function allocates
memory for a NURB surface during its execution.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbCurve * NCurve1 NURB curve 1


SC_NurbCurve * NCurve2 NURB curve 2

OUTPUT ARGUMENTS: SC_NurbSurface ** NSurface Resulting NURB surface

219
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_Clamp

PROTOTYPE: int
scNsurf_Clamp(SC_NurbSurface ** NSurface, int dir)

ACTION: Clamps the NURB surface with U or V direction. The NURB


surface is clamped at each interior knot, resulting in an equivalent
NURB surface that is a series of Bezier spans.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface ** NSurface The specified NURB surface


int dir 0, 1, 2 are for U, V and both direction.

220
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_SetArrowDisplayAttrib

PROTOTYPE: void
scNsurf_SetArrowDisplayAttrib(SC_NurbSurface * NSurface,
int iDisplay)

ACTION: Sets the arrow display attribute for a specified NURB surface to
be visible or invisible. To set the arrow to be visible, set iDisplay
to true; to hide the surface arrow, set iDisplay to false.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * NSurface The specified NURB surface


int iDisplay The display control variable
FALSE Arrow is hidden
TRUE Arrow is displayed

221
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_SetArrowPositionAttrib

PROTOTYPE: void
scNsurf_SetArrowPositionAttrib(SC_NurbSurface * NSurf,
int iArrowPosition)

ACTION: Sets the corner at which the surface arrow for a selected NURB
surface will be set to display.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * NSurf The specified NURB surface


int iArrowPosition The control variable for the
corner display attribute
ULOW_VLOW Corner 1 (low u, low v )
UHIGH_VLOW Corner 2 (high u, low v )
ULOW_VHIGH Corner 3 (low u, high v )
UHIGH_VHIGH Corner 4 (high u, high v )

222
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_SetCutDirectionAttrib

PROTOTYPE: void
scNsurf_SetCutDirectionAttrib(SC_NurbSurface * NSurface,
int iCutDir )

ACTION: Sets the direction of a cut (the major direction) for a selected
NURB surface.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * NSurface The specified NURB surface


int iCutDir The control variable for the
desired cut direction
U_DIRECTION u direction
V_DIRECTION v direction

223
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_SetNormalDirectionAttrib

PROTOTYPE: int
scNsurf_SetNormalDirectionAttrib(SC_NurbSurface * NSurf,
int iDirection)

ACTION: Sets the surface normal vector attribute from a NURB surface
structure. The normal vector of the NURB surface normal can be
set to be natural (u x v ) or reversed (v x u ).

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_NurbSurface * NSurf NURB surface being analyzed


int iDirection Normal vector flag
NATURAL Natural
REVERSED Reversed

224
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_SetNumberOfULinesAttrib

PROTOTYPE: void
scNsurf_SetNumberOfULinesAttrib(SC_NurbSurface * Surf,
int iNumULines)

ACTION: Sets the number of displayed u -direction NURB curves in a


specified NURB surface.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * Surf NURB surface being defined


int iNumULines The number of u -direction lines
in a specified NURB surface.

225
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_SetNumberOfVLinesAttrib

PROTOTYPE: void
scNsurf_SetNumberOfVLinesAttrib(SC_NurbSurface * Surf,
int iNumVLines)

ACTION: Sets the number of displayed v -direction curves in a specified


NURB surface.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * Surf NURB surface being defined


int iNumVLines The number of v -direction lines
in a specified NURB surface.

226
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_SetPolyDisplayAttrib

PROTOTYPE: void
scNsurf_SetPolyDisplayAttrib(SC_NurbSurface * NSurf,
int iDisplay )

ACTION: Sets the control point mesh to be visible or hidden for a specified
NURB surface. By setting display to false, the mesh is hidden.
Setting display to true sets the mesh to be visible.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * NSurf NURB curve being defined


int iDisplay Control variable for displaying
control point mesh of a NURB
surface
OFF No control point mesh
ON Control point mesh

227
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_SetRange

PROTOTYPE: int scNsurf_SetRange(SC_Element Surface, int iWrite,


SC_Gs_param_range_type * Range)

ACTION: Sets the range of an element. The function also discriminates


between temporary and permanent ranges. Setting iWrite to true
writes the new range to the database.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Surface Surface element


int iWrite Write flag
FALSE Do not write modified surface to the
database
TRUE Write the modified surface to the
database

SC_Gs_param_range_type * range
Range of surface
element (u-v )

228
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scNsurf_SetRationalAttrib

PROTOTYPE: void
scNsurf_GetRationalAttrib(SC_NurbSurface * NSurface,
int iRational)

ACTION: Sets the rational attribute of a specified NURB surface to be


rational or irrational. A curve is non-rational if the control points
are not weighted, and rational if the control points are weighted.
The surface is set to be rational if iRational is set to 1, and non-
rational if iRational is set to 0.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_NurbSurface * NSurface NURB surface being defined


int iRational The control variable for the
rational attribute
FALSE Non-rational
TRUE Rational

229
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNsurf_WriteToDB

PROTOTYPE: HSC_Element scNsurf_WriteToDB(HSC_DB hDB,


SC_NurbSurface * NSurf )

ACTION: Writes a surface to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: The handle to the surface written to the database

INPUT ARGUMENTS: HSC_DB hDB Handle for database


SC_NurbSurface * NSurf NURB surface to be written

230
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPlane_VectorPoint

PROTOTYPE: void scPlane_VectorPoint(SC_Plane * Plane,


SC_Point * Point,
SC_DirVector * NormalVector )

ACTION: Constructs a plane from a vector and a point. Note that planes
cannot be written to the database.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point * Point Point


SC_DirVector * NormalVector Vector

OUTPUT ARGUMENTS: SC_Plane * Plane Plane

231
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scPline_AllocMem

PROTOTYPE: SC_Pline * scPline_AllocMem(int iPoints)

ACTION: Allocates memory for a polyline, defining the address in the


computer’s memory.

FUNCTION RETURN TYPE: SC_PLine *

INPUT ARGUMENTS: int iPoints Number of points in the polyline

RETURN: Pointer to address of polyline or NULL if unsuccessful

232
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPline_ElementToPline

PROTOTYPE: int scPline_ElementToPline( SC_Element Element,


SC_Pline ** PLine,
double dblTolerance)

ACTION: Converts a curve to a polyline within a specified tolerance. Note


that this function allocates memory for a polyline during its
execution.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Curve element


double dblTolerance Tolerance

OUTPUT ARGUMENTS: SC_Pline ** PLine Resulting polyline

233
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scPline_WriteToDB

PROTOTYPE: HSC_Element scPline_WriteToDB( HSC_DB hDB,


SC_PLine * PLine)

ACTION: Writes a polyline to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle to the polyline written to the database

INPUT ARGUMENTS: HSC_DB hDB Handle for database


SC_PLine * PLine Polyline to be written

234
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPoint_AllocMem

PROTOTYPE: SC_Point * scPoint_AllocMem()

ACTION: Allocate memory for a point, defining the address in the


computer’s memory.

FUNCTION RETURN TYPE: SC_Point *

RETURN: Pointer to SURFCAM point or NULL if unsuccessful

ARGUMENTS: <None>

235
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scPoint_ArcEnd

PROTOTYPE: void scPoint_ArcEnd(SC_Point * Point,


SC_Arc * Arc,
int iEnd)

ACTION: Evaluates an endpoint of a specified arc.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Arc * Arc Specified arc


int iEnd Arc end flag
0 Start of arc
1 End of arc

OUTPUT ARGUMENTS: SC_Point * Point Endpoint to be defined

236
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPoint_GetMinMax

PROTOTYPE: int scPoint_GetMinMax(SC_Point * Point)

ACTION: Scan the display list and get the minmax

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: none

OUTPUT ARGUMENTS: SC_Point * Point Return point with min/max

237
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scPoint_OppositeSideOfLine

PROTOTYPE: int scPoint_OppositeSideOfLine( SC_Point * Point1,


SC_Point * Point2,
SC_Line * Line)

ACTION: Checks to see if two points lie on opposite sides of a specified


line. This function operates in two dimensions only (the line and
points must be planar).

FUNCTION RETURN TYPE: int

RETURN: FALSE The two points do not lie on opposite sides of the
specified line.
TRUE The two points do lie on opposite sides of the
specified line.

INPUT ARGUMENTS: SC_Point * Point1 Point 1


SC_Point * Point2 Point 2
SC_Line * Line Line

238
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPoint_OppositeSideOfVector

PROTOTYPE: int scPoint_OppositeSideOfVector( SC_Point * Point1,


SC_Point * Point2,
SC_Vector * Vector)

ACTION: Checks to see if two points lie on opposite sides of a specified


vector.

FUNCTION RETURN TYPE: int

RETURN: FALSE The two points do not lie on opposite sides of the
specified vector.
TRUE The two points do lie on opposite sides of the
specified vector.

INPUT ARGUMENTS: SC_Point * Point1 Point 1


SC_Point * Point2 Point 2
SC_Vector * Vector Vector

239
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scPoint_PointVecParam

PROTOTYPE: void scPoint_PointVecParam(SC_Point *outputPoint,


SC_Point * inputPoint,
SC_DirVector * vDir,
double dDist)
ACTION: Get point from point vector and param

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point* inputPoint Start point


SC_DirVector* vDir Direction vector
Double dDist Distance

OUTPUT ARGUMENTS: SC_Point* outputPoint Output point

240
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPoint_ProjectToLine

PROTOTYPE: void scPoint_ProjectToLine( SC_Point * Result,


SC_Point * Original,
SC_Line * Line)

ACTION: Projects a point onto a line. The resulting point would be the
normal projection (with respect to the line) of the original point.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point * Original Original point


SC_Line * Line Line used for projection

OUTPUT ARGUMENTS: SC_Point * Result Resulting point on line

241
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scPoint_ProjectToPlane

PROTOTYPE: void scPoint_ProjectToPlane( SC_Point * Result,


SC_Plane * Plane,
SC_Point * Original)

ACTION: Projects a point onto a plane. The resulting point would be


projected onto the plane with respect to the plane normal.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Plane * Plane Plane used for projection


SC_Point * Original Original point

OUTPUT ARGUMENTS: SC_Point * Result Resulting point

242
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scPoint_WriteToDB

PROTOTYPE: HSC_Element scPoint_WriteToDB(HSC_DB hDB,


SC_Point * Point)

ACTION: Writes a point to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle associated with the point written to the database

INPUT ARGUMENTS: HSC_DB hDB Handle for database


SC_Point * Point Point to be written

243
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scSafe_acos

PROTOTYPE: double scSafe_acos (double dblNumber )

ACTION: “Safe” version of arccosine (acos) math function, preventing


errors from invalid input numbers. This “Safe” function extends
the range of valid values, returning cos(1) if a is greater than 1
and cos(-1) if a is less than -1.

FUNCTION RETURN TYPE: double

RETURN: Arccosine of the input number

INPUT ARGUMENTS: double dblNumber Double precision number for


arccos operation

244
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scSafe_atof

PROTOTYPE: double scSafe_atof(char * sBuffer )

ACTION: “Safe” version of “a-to-f” function. This “Safe” function returns a


zero value if a NULL is passed.

FUNCTION RETURN TYPE: double

RETURN: Converted double precision number from character string

INPUT ARGUMENTS: char * sBuffer Character buffer for string

245
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scSafe_atoi

PROTOTYPE: int scSafe_atoi(char * sBuffer )

ACTION: “Safe” version of “a-to-i” function. This “Safe” function returns a


zero value if a NULL is passed.

FUNCTION RETURN TYPE: int

RETURN: Converted integer from character string

INPUT ARGUMENTS: char * sBuffer Character buffer for string

246
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scSafe_sprintf

PROTOTYPE: int scSafe_sprintf(int iLength, char * sBuffer, char * fmt , ...)

ACTION: “Safe” version of “sprintf” function. This “Safe” function verifies


the string bounds (the buffer size) and clips the excess part of the
string before proceeding with the “sprintf” function.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: int iLength Maximum length of the string


char * fmt String format(s)

OUTPUT ARGUMENTS: char * sBuffer Character buffer for string

247
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scSafe_sqrt

PROTOTYPE: double scSafe_sqrt(double dblNumber )

ACTION: “Safe” version of the square-root function. This “Safe” function


prevents an invalid argument (i.e. error from negative variable).

FUNCTION RETURN TYPE: double

RETURN: Square root of input variable or 0.0 if invalid argument

INPUT ARGUMENTS: double dblNumber Input variable

248
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scSafe_strcat

PROTOTYPE: char * scSafe_strcat( int iLength,


char * sDestination,
char * sSource)

ACTION: “Safe” version of “strcat” function. This “Safe” function prevents


writing beyond the bounds of the strings, clipping the excess part
of the string.

FUNCTION RETURN TYPE: char *

RETURN: Resulting character string of two concatenated strings

INPUT ARGUMENTS: int iLength Maximum string length argument


char * sSource Source string

OUTPUT ARGUMENTS: char * sDestination Destination string

249
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scSafe_strcpy

PROTOTYPE: char * scSafe_strcpy(int iLength,


char * sDestination,
char * sSource)

ACTION: “Safe” version of “strcpy” function. This “Safe” function prevents


copying beyond the string limits, clipping the excess part of the
string.

FUNCTION RETURN TYPE: char *

RETURN: Character string of two copied strings

INPUT ARGUMENTS: int iLength Usable string length argument


char * sSource Source string

OUTPUT ARGUMENTS: char * sDestination Destination string

250
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scStack_Final

PROTOTYPE: void scStack_Final(ll_handle * Stack)

ACTION: Cleans up a memory stack, freeing the allocated memory.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: ll_handle * Stack Specified stack

251
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scStack_Init

PROTOTYPE: ll_handle * scStack_Init()

ACTION: Initializes a memory stack, allocating memory for the stack.

FUNCTION RETURN TYPE: ll_handle *

RETURN: Pointer to the initialized stack

ARGUMENTS: <None>

252
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scStack_Peek

PROTOTYPE: int scStack_Peek( ll_handle * Stack,


void * Pos,
int * iSize)

ACTION: Check the active element of the stack, also getting the size of the
element.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: ll_handle * Stack Specified stack

OUTPUT ARGUMENTS: void * Pos Active element of stack

253
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scStack_Pop

PROTOTYPE: int scStack_Pop( ll_handle * Stack,


void * Pos,
int * iSize)

ACTION: Pop out the element at the top of the stack, also getting the size
of the element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: ll_handle * Stack Specified stack

OUTPUT ARGUMENTS: void * Pos Pointer to top of stack

254
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scStack_Push

PROTOTYPE: void * scStack_Push(ll_handle * Stack,


void * Pos,
int * iSize)

ACTION: Push an element to the top of the stack, also getting the size of
the element.

FUNCTION RETURN TYPE: void *

RETURN: Pointer to top of the stack

INPUT and
OUTPUT ARGUMENTS: int * iSize Pointer to the integer that will
receive the size of the element,
or NULL if the caller does not
wish to receive the element size.

INPUT ARGUMENTS: ll_handle * Stack Specified stack


void * Pos Pointer to top of stack

255
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_Add

PROTOTYPE: int scVec_Add(SC_DirVector * Result,


SC_DirVector * Vector1,
SC_DirVector * Vector2)

ACTION: Adds two vectors.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_DirVector * Vector1 First vector to be added


SC_DirVector * Vector2 Second vector to be added

OUTPUT ARGUMENTS: SC_DirVector * Result Resulting sum of vectors

256
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scFvec_Add

PROTOTYPE: int scFvec_Add(SC_FDirVector * Result,


SC_FDirVector * Vector1,
SC_FDirVector * Vector2)

ACTION: Adds two vectors.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_FDirVector * Vector1 First vector to be added


SC_FDirVector * Vector2 Second vector to be added

OUTPUT ARGUMENTS: SC_FDirVector * Result Resulting sum of vectors

257
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_Add2d

PROTOTYPE: void scVec_Add2d( SC_DirVector * Result,


SC_DirVector * Vector1 ,
SC_DirVector * Vector2)

ACTION: Adds two vectors (with respect to the x and y axes only). The z
values are ignored.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_DirVector * Vector1 First vector to be added


SC_DirVector * Vector2 Second vector to be added

OUTPUT ARGUMENTS: SC_DirVector * Result Resulting sum of vectors

258
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_AddScaledVecs

PROTOTYPE: int scVec_AddScaledVecs(SC_DirVector * Sum,


SC_DirVector * Vector1,
double dblScale1,
SC_DirVector * Vector2,
double dblScale2)

ACTION: The vector sum of two scaled vectors. The vectors are scaled
before they are added together.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_DirVector * Vector1 Vector 1


double dblScale1 Scaling factor 1
SC_DirVector * Vector2 Vector 2
double dblScale2 Scaling factor 2

OUTPUT ARGUMENTS: SC_DirVector * Sum Resulting vector

259
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_AngleMinusPiPi

PROTOTYPE: double scVec_AngleMinusPiPi( SC_DirVector * Vector1 ,


SC_DirVector * Vector2,
SC_DirVector * Normal )

ACTION: Returns the angle between Vector1 and Vector2, specifying


Normal as the normal vector between the two other vectors. The
angle is constrained to fall between -π radians (-180 degrees)
and π radians (180 degrees).

FUNCTION RETURN TYPE: double

RETURN: Angle between Vector1 and Vector2 in radians

INPUT ARGUMENTS: SC_DirVector * Vector1 First vector


SC_DirVector * Vector2 Second vector
SC_DirVector * Normal Normal vector

260
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_AngleZero2Pi

PROTOTYPE: double scVec_AngleZero2Pi( SC_DirVector * Vector1 ,


SC_DirVector * Vector2,
SC_DirVector * Normal )

ACTION: Returns the angle between Vector1 and Vector2, specifying


Normal as the normal vector between the two other vectors. The
angle is constrained to fall between 0 and 2π radians (360
degrees).

FUNCTION RETURN TYPE: double

RETURN: Angle between Vector1 and Vector2 in radians

INPUT ARGUMENTS: SC_DirVector * Vector1 First vector


SC_DirVector * Vector2 Second vector
SC_DirVector * Normal Normal vector

261
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_AngleZeroPi

PROTOTYPE: double scVec_AngleZeroPi(SC_DirVector * Vector1 ,


SC_DirVector * Vector2 )

ACTION: Returns the angle between Vector1 and Vector2. The angle is
constrained to fall between 0 and π radians(180 degrees).

FUNCTION RETURN TYPE: double

INPUT ARGUMENTS: SC_DirVector * Vector1 First vector


SC_DirVector * Vector2 Second vector

RETURN: Angle between Vector1 and Vector2 in radians

262
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_AngleZeroPi2

PROTOTYPE: double scVec_AngleZeroPi2( SC_DirVector * Vector1 ,


SC_DirVector * Vector2 )

ACTION: Returns the angle between two specified vectors. The returned
angle is constrained to fall between 0 and π/2 radians (90
degrees).

FUNCTION RETURN TYPE: double

INPUT ARGUMENTS: SC_DirVector Vector1 First vector


SC_DirVector Vector2 Second vector

RETURN: Angle between Vector1 and Vector2 in radians

263
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_BetweenVecVec

PROTOTYPE: int scVec_BetweenVecVec( SC_DirVector * Vector,


SC_DirVector * Reference1,
SC_DirVector * Reference2,
SC_DirVector * Normal )

ACTION: Checks to see whether a vector (Vector ) lies between two


specified vectors (Reference1 and Reference2 ). The normal
vector defines the direction of the sweep between the reference
vectors by the right hand rule. The three vectors must lie on the
same plane.

FUNCTION RETURN TYPE: int

RETURN: FALSE Test vector does not lie between the two
specified vectors
TRUE Test vector does lie between the two specified
vectors

INPUT ARGUMENTS: SC_DirVector * Vector Vector to be tested


SC_DirVector * Reference1 Reference vector 1
SC_DirVector * Reference2 Reference vector 2
SC_DirVector * Normal Normal vector

264
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_BetweenVecVec2d

PROTOTYPE: int scVec_BetweenVecVec2d( SC_DirVector * TestVec,


SC_DirVector * Vector1,
SC_DirVector * Vector2,
double dblTolerance,
int iFullFlag )

ACTION: Checks to see if a specified vector’s x-y projection lies between


the x-y projections of two given vectors. If the two-dimensional
test vector TestVec lies in the region swept out from the two-
dimensional projections of Vector1 to Vector2, the function
returns a value of true; if not, the function returns a value of false.
If Vector1 and Vector2 are collinear, the full-circle flag indicates
whether the angle between the vectors is zero or 2π radians.

FUNCTION RETURN TYPE: int

RETURN: FALSE x-y components of TestVec lie between the x-y


components of Vector1 and Vector2
TRUE x-y components do not lie between the x-y
components of Vector1 and Vector2

INPUT ARGUMENTS: SC_DirVector * TestVec Test vector


SC_DirVector * Vector1 Vector 1
SC_DirVector * Vector2 Vector 2
double dblTolerance Tolerance
int iFullFlag Full circle flag
FALSE 0 radians
TRUE 2π radians

265
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_Collinear

PROTOTYPE: int scVec_Collinear( SC_DirVector * Vector1,


SC_DirVector * Vector2,
double dblTolerance)

ACTION: Checks the collinearity of two vectors within a specified tolerance.


The tolerance is compared to the dot product of the two vectors.

FUNCTION RETURN TYPE: int

RETURN: FALSE Not collinear


TRUE Collinear

INPUT ARGUMENTS: SC_DirVector * Vector1 Vector 1


SC_DirVector * Vector2 Vector 2
double dblTolerance Tolerance

266
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_CrossProduct

PROTOTYPE: int scVec_CrossProduct( SC_DirVector * Result,


SC_DirVector * Vector1,
SC_DirVector * Vector2 )

ACTION: Calculates the cross product vector of two specified vectors


(Vector1 and Vector2 ).

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_DirVector * Vector1 First vector


SC_DirVector * Vector2 Second vector

OUTPUT ARGUMENTS: SC_DirVector * Result Resulting vector

267
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_DotProduct

PROTOTYPE: double scVec_DotProduct( SC_DirVector * DirVector1,


SC_DirVector * DirVector2 )

ACTION: Calculates the dot product of two specified direction vectors.

FUNCTION RETURN TYPE: double

RETURN: Dot product of the two direction vectors

INPUT ARGUMENTS: SC_DirVector * DirVector1 First vector


SC_DirVector * DirVector2 Second vector

268
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_Magnitude

PROTOTYPE: double scVec_Magnitude(SC_DirVector * DirVector )

ACTION: Calculates the magnitude of a specified direction vector.

FUNCTION RETURN TYPE: double

RETURN: Magnitude of vector

INPUT ARGUMENTS: SC_DirVector * DirVector Specified direction vector

269
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scFvec_Magnitude

PROTOTYPE: float scFvec_Magnitude(SC_FDirVector * DirVector )

ACTION: Calculates the magnitude of a specified direction vector.

FUNCTION RETURN TYPE: float

RETURN: Magnitude of vector

INPUT ARGUMENTS: SC_FDirVector * DirVector Specified direction vector

270
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_Magnitude2d

PROTOTYPE: double scVec_Magnitude2d(SC_DirVector * DirVector )

ACTION: Calculates the magnitude of a specified direction vector.

FUNCTION RETURN TYPE: double

RETURN: Magnitude of vector

INPUT ARGUMENTS: SC_DirVector * DirVector Specified direction vector

271
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_MagnitudeCrossProduct

PROTOTYPE: double
scVec_MagnitudeCrossProduct(SC_DirVector * Vector1,
SC_DirVector * Vector2)

ACTION: Calculates the magnitude of the cross-product of two specified


vectors.

FUNCTION RETURN TYPE: double

RETURN: Magnitude of cross product of two vectors (double)

INPUT ARGUMENTS: SC_DirVector * Vector1 Specified direction vector 1


SC_DirVector * Vector2 Specified direction vector 2

272
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_Normalize

PROTOTYPE: int scVec_Normalize(SC_DirVector * DirVector )

ACTION: Converts a specified direction vector into a unit vector (magnitude


of 1 unit). The normalized vector replaces the original vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_DirVector * DirVector Specified direction vector

273
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scFvec_Normalize

PROTOTYPE: int scFvec_Normalize(SC_FDirVector * DirVector )

ACTION: Converts a specified direction vector into a unit vector (magnitude


of 1 unit). The normalized vector replaces the original vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_FDirVector * DirVector Specified direction vector

274
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_Normalize2d

PROTOTYPE: int scVec_Normalize2d(SC_DirVector * DirVector )

ACTION: Converts a specified vector into a two-dimensional (x-y) unit


vector (magnitude of 1 unit). The z-axis vector is also scaled in
order to preserve the direction of the vector. The normalized
vector replaces the original vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_DirVector * DirVector Specified direction vector

275
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_PointPoint

PROTOTYPE: int scVec_PointPoint( SC_DirVector * Result,


SC_Point * Point1,
SC_Point * Point2 )

ACTION: Defines a direction vector using two specified points in space.


The first point is assigned to be the origin of the vector, while the
second point is assigned to be the head of the vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Point * Point1 Point 1 (assigned to be the


vector origin)
SC_Point * Point2 Point 2 (assigned to be the
vector head)

OUTPUT ARGUMENTS: SC_DirVector * Result Resulting direction vector

276
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scFvec_FpointFpoint

PROTOTYPE: int scFvec_FpointFpoint( SC_FDirVector * Result,


SC_FPoint * Point1,
SC_FPoint * Point2 )

ACTION: Defines a direction vector using two specified points in space.


The first point is assigned to be the origin of the vector, while the
second point is assigned to be the head of the vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_FPoint * Point1 Point 1 (assigned to be the


vector origin)
SC_FPoint * Point2 Point 2 (assigned to be the
vector head)

OUTPUT ARGUMENTS: SC_FDirVector * Result Resulting direction vector

277
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_PointPoint2d

PROTOTYPE: void scVec_PointPoint2d( SC_DirVector * Result,


SC_DirVector * Vector1,
SC_DirVector * Vector2 )

ACTION: Creates a vector from two other vectors with respect to the x and
y axes only.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_DirVector * Vector1 Vector 1


SC_DirVector * Vector2 Vector 2

OUTPUT ARGUMENTS: SC_DirVector * Result Resulting vector

278
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_ProjectToPlaneN

PROTOTYPE: int scVec_ProjectToPlaneN( SC_DirVector * Vector,


SC_DirVector * Normal )

ACTION: Projects a direction vector onto a plane defined by a normal


vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_DirVector * Vector Projected vector

INPUT ARGUMENTS: SC_DirVector * Normal Vector normal to the defined


plane

279
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_ProjectToPlaneNThroughVec

PROTOTYPE: int
scVec_ProjectToPlaneNThroughVec(SC_DirVector * Vector,
SC_DirVector * Norm,
SC_DirVector * Proj )

ACTION: Projects a vector onto a plane (defined by a second vector) along


a view defined by a third vector. The projected vector replaces
the original vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_DirVector * Vector Vector to be manipulated

INPUT ARGUMENTS: SC_DirVector * Norm Normal vector


SC_DirVector * Proj Projection vector

280
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_Scale

PROTOTYPE: int scVec_Scale(SC_DirVector * DirVector,


double dblScale)

ACTION: Scales a direction vector according to a double-precision number.


The scaled vector replaces the original vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_DirVector * DirVector Scaled vector

INPUT ARGUMENTS: double dblScale Scaling factor

281
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scFvec_Scale

PROTOTYPE: int scFvec_Scale(SC_FDirVector * DirVector,


float flScale)

ACTION: Scales a direction vector according to a float-precision number.


The scaled vector replaces the original vector.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT and OUTPUT


ARGUMENTS: SC_FDirVector * DirVector Scaled vector

INPUT ARGUMENTS: float flScale Scaling factor

282
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_Scale2d

PROTOTYPE: void scVec_Scale2d( SC_DirVector *Vector,


double dblScale)

ACTION: Scales a vector with respect to the x and y axes only according to
a double-precision number. The returned vector parameters
replace the original vector parameters.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT and OUTPUT


ARGUMENTS: SC_DirVector * Vector Vector

INPUT ARGUMENTS: double dblScale Scaling factor

283
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scVec_Set_axis_vec

PROTOTYPE: void scVec_Set_axis_vec(SC_DirVector * DirVector, int )

ACTION: Set axis vector

FUNCTION RETURN TYPE: void

RETURN: none

INPUT ARGUMENTS: SC_DirVector * DirVector Specified direction vector


Int axis 0, 1, 2 are for X, Y and Z axis

284
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scVec_SinAngle

PROTOTYPE: double scVec_SinAngle( SC_DirVector * DirVector1,


SC_DirVector * DirVector2 )

ACTION: Returns the sine of the angle between two direction vectors.

FUNCTION RETURN TYPE: double

RETURN: Sine of the angle between two direction vectors

INPUT ARGUMENTS: SC_DirVector * DirVector1 Vector 1


SC_DirVector * DirVector2 Vector 2

285
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scView_AllocMem

PROTOTYPE: SC_View * scView_AllocMem();

ACTION: Allocate memory for a view, defining the pointer to the address in
the computer’s memory.

FUNCTION RETURN TYPE: SC_View *

RETURN: Pointer to view or NULL if unsuccessful

ARGUMENTS: <None>

286
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scView_ArbitraryAxis

PROTOTYPE: void scView_ArbitraryAxis( SC_View * View,


SC_DirVector * Normal )

ACTION: Sets an arbitrary view given a single vector. This view sets the
vector defined by Normal as the normal vector for the view.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_DirVector * Normal Reference vector for view

OUTPUT ARGUMENTS: SC_View * View Defined view

287
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scView_Arc

PROTOTYPE: int scView_Arc( SC_View * ViewFound,


SC_Arc * Arc )

ACTION: Returns the view with the same normal as that of a specified arc.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Arc * Arc Specified arc

OUTPUT ARGUMENTS: SC_View * ViewFound Returned view

288
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scView_Compare

PROTOTYPE: int scView_Compare( SC_View * View1,


SC_View * View2 )

ACTION: Compares two specified views to one another. If the return value
is false, the two views are the same. If the return value is true,
the two views are different.

FUNCTION RETURN TYPE: int

RETURN: FALSE Identical


TRUE Different

INPUT ARGUMENTS: SC_View * View1 First view


SC_View * View2 Second view

289
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scView_GetCview

PROTOTYPE: int scView_GetCview(SC_View * Cview )

ACTION: Get the current SURFCAM construction view (CView).

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

OUTPUT ARGUMENTS: SC_View * Cview Returned CView

290
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scView_GetView

PROTOTYPE: int scView_GetView(SC_View * View,


unsigned short iNum)

ACTION: Finds a view given a reference number and retrieves it intoView.


If the view does not exist, the function returns FAIL.

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: unsigned short iNum View number

OUTPUT ARGUMENTS: SC_View * View Returned view

291
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scView_InitStandardView

PROTOTYPE: int scView_InitStandardView(SC_View * View,


int iNum )

ACTION: Initializes a view to one of the standard SURFCAM views (1 to 8).

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: int iNum Reference number of standard


SURFCAM view (1 to 8).

OUTPUT ARGUMENTS: SC_View * View Resulting view

292
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scView_WorldToView

PROTOTYPE: void scView_WorldToView(SC_Point * Original,


SC_Point * Result,
double dblMatrix [4][4],
int iTransformFlag)

ACTION: Converts the point Original in world coordinates to Result in view


coordinates using the matrix dblMatrix. The function also
transforms the element if the element corresponds to a point,
rather than a vector.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: SC_Point * Original Original point


double dblMatrix [4][4] Transformation matrix
int iTransformFlag Transformation flag
FALSE Element is a vector
TRUE Element is a point

OUTPUT ARGUMENTS: SC_Point * Result Transformed point

293
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scView_WriteToDB

PROTOTYPE: HSC_Element scView_WriteToDB( HSC_DB hDB,


SC_View * View )

ACTION: Writes a view to the SURFCAM database.

FUNCTION RETURN TYPE: HSC_Element

RETURN: Element handle to the corresponding view written to the database

INPUT ARGUMENTS: HSC_DB hDB Handle for database


SC_View * View Layer to be written

294
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_Element

PROTOTYPE: int scXForm_Element( Unsigned short xmode,


Double mat[4][4], double scale, short flags, SC_Element Element
)

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

295
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_TranslateRel

PROTOTYPE: int scXForm_TranslateRel( Unsigned short xmode,


SC_Point *pscPnt, SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address


SC_Point * pscPnt Point defined

OUTPUT ARGUMENTS:

296
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_TranslateAbs

PROTOTYPE: int scXForm_TranslateAbs( Unsigned short xmode,


SC_Point *pscPntFrom, SC_Point *pscPntTo,
SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address


SC_Point * pscPntFrom From Point defined
SC_Point * pscPntTo To Point defined

OUTPUT ARGUMENTS:

297
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_Rotate

PROTOTYPE: int scXForm_Rotate( Unsigned short xmode,


Double lfAngle, SC_Point *pscPnt,
SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address


SC_Point * pscPnt Point defined

OUTPUT ARGUMENTS:

298
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_Scale

PROTOTYPE: int scXForm_Scale( Unsigned short xmode,


Double lfScale, SC_Point *pscPnt,
SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address


SC_Point * pscPnt Point defined

OUTPUT ARGUMENTS:

299
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_ScaleXYZ

PROTOTYPE: int scXForm_ScaleXYZ( Unsigned short xmode,


SC_Point *pscPntScale, SC_Point *pscPnt,
SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address


SC_Point * pscPnt Point defined

OUTPUT ARGUMENTS:

300
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_Mirror

PROTOTYPE: int scXForm_Mirror( Unsigned short xmode,


SC_Point *pscPnt, SC_Point *pscPnt2,
SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address


SC_Point * pscPnt Point defined
SC_Point * pscPnt2 Point2 defined

OUTPUT ARGUMENTS:

301
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_TranslateRelUI

PROTOTYPE: int scXForm_TranslateRelUI( Unsigned short xmode,


SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

302
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_TranslateAbsUI

PROTOTYPE: int scXForm_TranslateAbsUI( Unsigned short xmode,


SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

303
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_RotateUI

PROTOTYPE: int scXForm_RotateUI( Unsigned short xmode,


SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

304
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_ScaleUI

PROTOTYPE: int scXForm_ScaleUI( Unsigned short xmode,


SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

305
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_ScaleXYZUI

PROTOTYPE: int scXForm_ScaleXYZUI( Unsigned short xmode,


SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

306
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_MirrorUI

PROTOTYPE: int scXForm_MirrorUI( Unsigned short xmode,


SC_Element Element )

ACTION: Transform element

FUNCTION RETURN TYPE: int

RETURN: 0 Success
~0 Fail

INPUT ARGUMENTS: SC_Element Element Pointer to element address

OUTPUT ARGUMENTS:

307
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_TranslateRelUISel

PROTOTYPE: void scXForm_TranslateRelUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

308
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_TranslateAbsUISel

PROTOTYPE: void scXForm_TranslateAbsUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

309
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_RotateUISel

PROTOTYPE: void scXForm_RotateUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

310
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_ScaleUISel

PROTOTYPE: void scXForm_ScaleUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

311
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_ScaleXYZUISel

PROTOTYPE: void scXForm_ScaleXYZUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

312
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

scXForm_MirrorUISel

PROTOTYPE: void scXForm_MirrorUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

313
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scXForm_ToViewUISel

PROTOTYPE: void scXForm_ToViewUISel( )

ACTION: Transform element

FUNCTION RETURN TYPE: void

RETURN: void

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

314
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

315
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Chapter 6
Sample Code Using
the SURFCAM API

316
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

317
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Sample input translator code

unsigned nColor, nLayer;


HWND hWndParent;
char sBuffer[FILESIZE];
FILE * InputFile;

SC_Point scp;
SC_Point * pSCPoint;

...

hWndParent = scApp_GetWindowHandle();

InputFile = fopen(szFilename, "rt"); /* Open input text file */

HSC_DB hDB = scDB_GetHandle(); /* Get SURFCAM database handle */

/* Start loop reading element types from file here */


...

switch(nTypeRead)
{
case POINT: /* POINT is defined as the ElementMap index for a point element */
{
/* Read element data into SC_Point format here */
...

pSCPoint = scPoint_AllocMem(); /* Allocate memory for point */


*pSCPoint = scp; /* Assign point properties */

scElement_SetColorAttrib(pSCPoint, nColor); /* Set color attrib for point */


scElement_SetLayerAttrib(pSCPoint, nLayer); /* Set layer attrib for point */
scPoint_WriteToDB(hDB, pSCPoint); /* Write point to SC database */
scElement_Final(pSCPoint); /* Free memory for point element */

break;
}

case LINE:
{
/* Read element data into SC_Line format here */
...

break;
}

case CURVE:
{
/* Read element data into SC_Ncurve format here */
...

break;
}

...
}

...

318
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Sample output translator code

#include “expfunc.h”
#include “dllstruct.h”

int rc, nColorNumber, nLayerNumber;


unsigned nColor;
HWND hWndParent;
FILE * OutputFile;

...

hWndParent = scApp_GetWindowHandle();

/* Mask database for valid element types only */


rc = scApp_SelectionInit(0, dll_mask_bit(SC_POINT) | dll_mask_bit(SC_LINE) |
dll_mask_bit(SC_PLINE) | dll_mask_bit(SC_ARC) |
dll_mask_bit(SC_NCURVE) | dll_mask_bit(SC_NSURF), 0, 0);

if(rc != SUCCESS) { /* If unable to mask, return */


scApp_SelectionFinal();
return;
};

OutputFile = fopen(szFilename, "wt"); /* Opens file for writing */

HSC_DB hDB = scDB_GetHandle(); /* Gets SURFCAM database handle */

HSC_Element hEl; /* General element handle */

/* Loop through database until no more valid handles */


for(hEl = scElement_InitHandle(hDB); scElement_ValidHandle(hEl);
hEl = scElement_NextHandle(hEl))
{
switch(scElement_GetTypeFromHandle(hEl)) /* Return SURFCAM element type */
{
case SC_POINT: /* Process a SC_Point element */
{
SC_Point *scp = scElement_GetPoint(hEl); /* Retrieves and allocates point */

if (scp) { /* If valid SC_Point (not NULL) */


nColorNumber = scElement_GetColorAttrib(scp); /* Gets point color */
nLayerNumber = scElement_GetLayerAttrib(scp); /* Gets point layer */
nColor = ColorMap((unsigned int) nColorNumber); /* Converts color index */
fprintf(OutputFile, "POINT %.16G,%.16G,%.16G,%d,%d,0,0,0\n",
scp->x, scp->y, scp->z, color, layer_num);
scElement_Final(scp); /* Frees memory allocated */
}
}
break;
...

319
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Sample Code: Channel.cpp

The following sample code was written as part of a demonstration application showcasing the versatility of the
SURFCAM API. This program automatically creates extrusion mold surfaces given front, center, and rear profiles
of the extrusion surface. These profiles are selected by the user through a “Graphical User Interface” (GUI)
incorporating the Microsoft Foundation Classes (MFC) library of GUI objects. Note that the relevant information is
gathered in the GUI and processed by the SURFCAM API functions.
// Channel.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h" // MFC-specific header file


#include <expfunc.h> // SURFCAM API header file
#include <float.h> // MFC-specific header file
#include <math.h> // MFC-specific header file
#include "PointLists.h" // Header file for center section arrays
#include "DialogChannel.h" // Header file for first dialog box (MFC)
#include "DialogSurface.h" // Header file for second dialog box (MFC)
#include "Channel.h" // Header file for this application (MFC)

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Define data structures

typedef struct stProfileData {


ll_handle *m_hProfilePoints; // List of points (SURFCAM specific)
int m_iPoints; // Number of points
int m_iColor; // Color index of profile
double m_dblMaxY; // Maximum Y (used for alignment)
double m_dblMinY; // Minimum Y (used for alignment)
SC_Point m_Point[3][64]; // Point array for sub-profiles (SURFCAM specific)
SC_PLine *m_PLine[3]; // Polyline for sub-profiles (SURFCAM specific)
SC_NurbCurve *m_NCurve[3]; // Nurb curve for sub-profiles (SURFCAM specific)
} ProfileData;

typedef struct stBoundaryData {


SC_Point m_Points[3]; // Point array for boundary edge (SURFCAM specific)
SC_PLine *m_PLine; // Polyline for boundary edge (SURFCAM specific)
SC_NurbCurve *m_NCurve; // Nurb curve for boundary edge (SURFCAM specific)
} BoundaryData;

typedef struct stChannelData {


ProfileData m_Profile[3]; // Three profiles (2 ends, 1 center)
BoundaryData m_Boundary[3][2]; // Two boundary edges for each of three channels
int m_iCenter; // User selection for center profile
int m_iSurfaceColor; // Color of constructed surface
double m_dblDistance; // Spacing between the profiles
BOOL m_bAlign; // Flag whether to align the profiles
BOOL m_bAllocate; // Flag whether to allocate a new layer
CString m_szFilename[2]; // Filenames for data files (MFC specific)
HSC_DB m_hDatabase; // Handle for SURFCAM database (SURFCAM specific)
SC_NurbSurface*m_NSurf[3]; // Resulting Nurb surface (SURFCAM specific)
} ChannelData;

///////////////////////////////////////////////////////////////////////////////
// Local function declarations

static void DoChannel();


static void InitializeData(ChannelData &Data);
static int ReadData(ChannelData &Data);

320
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

static void GetCenterPoints(ChannelData &Data);


static void DefineProfiles(ChannelData &Data);
static void DefineBoundaries(ChannelData &Data);
static void CreateSurfaces(ChannelData &Data);
static void FindYMinMax(ChannelData &Data, double dblY, int i);

/////////////////////////////////////////////////////////////////////////////
// Begin MFC-specific code

/////////////////////////////////////////////////////////////////////////////
// CChannelApp

BEGIN_MESSAGE_MAP(CChannelApp, CWinApp)
//{{AFX_MSG_MAP(CChannelApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CChannelApp construction

CChannelApp::CChannelApp()
{
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CChannelApp object

CChannelApp theApp;

// End MFC-specific code


/////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
// SurfcamDllEntryPoint
// This is the standard function called by SURFCAM when using a dll. Note
// that the function must have this standard declaration, even if the character
// strings are not utilized by the dll. The minimum purpose of this function
// is to get the pointer to the SURFCAM functions and assign it to the global
// variable ut_p_pSCFuncs.
//

// Note that this extern "C" is necessary if using C++.


#if defined(__cplusplus)
extern "C"
{
#endif

__declspec(dllexport) int
SurfcamDllEntryPoint(
char *ini_file_name,
char *section_name,
char *file_name)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState()); // MFC-specifc

DoChannel(); // Main functions

return(TRUE);
}

#if defined(__cplusplus)
}
#endif

///////////////////////////////////////////////////////////////////////////////
// DoChannel
// This is the main function for this program, allocating the data structure
// and calling the functions to manipulate that data structure.

321
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

//

static void
DoChannel()
{
UINT wCurrentLayer;
SC_Layer * pLayer; // SURFCAM specific
HWND hWndParent;

// Use scApp_GetWindowHandle to get the Win32 handle for SURFCAM's window.


hWndParent = scApp_GetWindowHandle();

// This is the main data object, which is passed from function to function.
ChannelData m_Data;

// Initialize the main data object using a function setting all variables.
// Not only is this good programming practice, but this also prevents
// many errors during execution.
InitializeData(m_Data);

// Make SURFCAM the parent window when creating this dialog box
CDialogChannel Dlg(CWnd::FromHandle(hWndParent)); // MFC specific

if (Dlg.DoModal() == IDCANCEL) {
return;
}

// Assign information gathered from dialog box into data object.


m_Data.m_szFilename[0] = Dlg.m_szSectionFile1;
m_Data.m_szFilename[1] = Dlg.m_szSectionFile2;

m_Data.m_Profile[0].m_iColor = Dlg.m_iColor[0];
m_Data.m_Profile[1].m_iColor = Dlg.m_iColor[1];
m_Data.m_Profile[2].m_iColor = Dlg.m_iColor[2];

m_Data.m_iCenter = Dlg.m_iCenter;

// Make SURFCAM the parent window when creating this dialog box
CDialogSurface SurfaceDlg(CWnd::FromHandle(hWndParent));

if (SurfaceDlg.DoModal() == IDCANCEL) {
return;
}

// Assign information gathered from dialog box into data object.


m_Data.m_dblDistance = SurfaceDlg.m_dblDistance;
m_Data.m_bAlign = SurfaceDlg.m_bAlign;
m_Data.m_bAllocate = SurfaceDlg.m_bAllocate;
m_Data.m_iSurfaceColor = SurfaceDlg.m_iColor;

// Read the data files. If there's an error, abort the program by returning.
if (ReadData(m_Data) == FAIL) {
return;
}

// Save current (original) layer index


wCurrentLayer = scApp_GetCurrentLayer();

// If user desires to allocate a new layer...


if (m_Data.m_bAllocate) {
int iLayer;
HSC_Element hElement;

pLayer = scLayer_AllocMem();
iLayer = scLayer_FindFreeLayer();

scElement_SetLayerAttrib(pLayer, iLayer);

hElement = scLayer_WriteToDB(m_Data.m_hDatabase, pLayer);


scApp_SetCurrentLayer(iLayer);
}

GetCenterPoints(m_Data);

322
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

DefineProfiles(m_Data);
DefineBoundaries(m_Data);
CreateSurfaces(m_Data);

// Free up all the allocated memory reserved for the elements. (No longer needed).
scMem_FreeAll();

if (m_Data.m_bAllocate) {
// Go back to original layer
scApp_SetCurrentLayer(wCurrentLayer);
}
}

///////////////////////////////////////////////////////////////////////////////
// InitializeData
// This function initializes the main data structure to ensure valid values.
// This also allocates memory for each list and retrieves the database handle.
//

static void
InitializeData(ChannelData &Data)
{
int i,j;

for (i = 0; i < 3; i++) {

Data.m_Profile[i].m_hProfilePoints = scList_Init();
Data.m_Profile[i].m_iPoints = 0;
Data.m_Profile[i].m_iColor = 0;
Data.m_Profile[i].m_dblMaxY = -DBL_MAX;
Data.m_Profile[i].m_dblMinY = DBL_MAX;
Data.m_NSurf[i] = NULL;

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


Data.m_Profile[i].m_NCurve[j] = NULL;
Data.m_Profile[i].m_PLine[j] = NULL;
}

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


Data.m_Boundary[i][j].m_NCurve = NULL;
Data.m_Boundary[i][j].m_PLine = NULL;
}
}

Data.m_dblDistance = 0.0;
Data.m_iSurfaceColor = 0;
Data.m_bAlign = FALSE;
Data.m_bAllocate = FALSE;
Data.m_hDatabase = scDB_GetHandle();
}

///////////////////////////////////////////////////////////////////////////////
// ReadData
// This function reads in the points from the selected end profile files.
// The points are stored in the data structure as two lists of points.
//

static int
ReadData(ChannelData &Data)
{
int i;
CStdioFile Section[2]; // MFC specific
CString szBuffer; // MFC specific
CString szTemp; // MFC specific
SC_Point TempPoint = {0,0,0}; // SURFCAM specific

// Read and process both profile files


for (i = 0; i < 2; i++) {

// Open file
Section[i].Open(Data.m_szFilename[i], CFile::modeRead | CFile::shareDenyWrite);

323
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

// Insert dummy element at the head of appropriate list


scList_InsertHead(Data.m_Profile[i*2].m_hProfilePoints, &TempPoint, sizeof(SC_Point));

// Read from file until end of file (EOF) or empty line


while (Section[i].ReadString(szBuffer)) {
if (szBuffer.IsEmpty())
break;

// Define point using file data and spacing distance information


TempPoint.x = i * 2 * Data.m_dblDistance;
TempPoint.y = atof(szBuffer.Left(szBuffer.Find(',')));
TempPoint.z = atof(szBuffer.Right(szBuffer.GetLength() - szBuffer.Find(',') - 1));

// Find the minimum and maximum values of Y for profile alignment


FindYMinMax(Data, TempPoint.y, i * 2);

// Store point in list


scList_InsertHead(Data.m_Profile[i*2].m_hProfilePoints, &TempPoint, sizeof(SC_Point));

// Record number of points entered thus far


Data.m_Profile[i*2].m_iPoints++;
}
}
return SUCCESS;
}

///////////////////////////////////////////////////////////////////////////////
// GetCenterPoints
// This function defines the user-selected center section from pre-defined
// arrays.
//

static void
GetCenterPoints(ChannelData &Data)
{
int iArraySize = 0;
int i = 0;
SC_Point TempPoint = {0,0,0};

// Insert dummy element at head


scList_InsertHead(Data.m_Profile[1].m_hProfilePoints, &TempPoint, sizeof(SC_Point));

// Find length of point arrays (number of elements)


if (Data.m_iCenter == 1)
iArraySize = sizeof(PointList1)/sizeof(PointList1[0]);

else if (Data.m_iCenter == 2)
iArraySize = sizeof(PointList2)/sizeof(PointList2[0]);

else if (Data.m_iCenter == 3)
iArraySize = sizeof(PointList3)/sizeof(PointList3[0]);

// Since each point uses two elements, divide the total by two
for(i = 0; i < (iArraySize / 2); i++) {

TempPoint.x = Data.m_dblDistance;

if (Data.m_iCenter == 1) {
TempPoint.y = PointList1[i*2];
TempPoint.z = PointList1[i*2+1];
}
else if (Data.m_iCenter == 2) {
TempPoint.y = PointList2[i*2];
TempPoint.z = PointList2[i*2+1];
}

else if (Data.m_iCenter == 3) {
TempPoint.y = PointList3[i*2];
TempPoint.z = PointList3[i*2+1];
}

324
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

// Find the minimum and maximum values


FindYMinMax(Data, TempPoint.y, 1);

// Store point in list


scList_InsertHead(Data.m_Profile[1].m_hProfilePoints, &TempPoint, sizeof(SC_Point));
}

Data.m_Profile[1].m_iPoints = iArraySize / 2;

///////////////////////////////////////////////////////////////////////////////
// DefineProfiles
// This function converts the points in the point lists and creates the
// profiles. The profiles are converted to Nurb curves in order to create
// the Nurb surfaces later on.
//

static void
DefineProfiles(ChannelData &Data)
{
int i, j, k = 0;
double dblOffset = 0.0;
UINT wCurrentColor = 0;
SC_Point *pPoint = NULL; // SURFCAM specific

// Use scApp_GetCurrentColor to retrieve and save the index of the current color.
wCurrentColor = scApp_GetCurrentColor();

// Loop through each profile (there are two end profiles plus a center profile).
for (i = 0; i < 3; i++) {

// Assign the pPoint element pointer to the tail of the list, which happens
// to be the dummy variable which was the first to be entered into the list.
pPoint = (SC_Point *)(scList_GetTail(Data.m_Profile[i].m_hProfilePoints, NULL));

// Use scApp_SetCurrentColor to set the color for the profile to be drawn.


scApp_SetCurrentColor(Data.m_Profile[i].m_iColor);

// Each profile is made up of three sub-profiles.


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

// Allocate memory for elements. AllocMem functions MUST be used if


// the element is to be written to the SURFCAM database for storage.
Data.m_Profile[i].m_PLine[j] = scPline_AllocMem(Data.m_Profile[i].m_iPoints/3);
Data.m_Profile[i].m_NCurve[j] = scNcurve_AllocMem(Data.m_Profile[i].m_iPoints/3, 1);

// If aligning the profiles, assign a value to the offset to center


// the profiles. Otherwise, the offset remains zero.
if (Data.m_bAlign) {
dblOffset = Data.m_Profile[i].m_dblMaxY -
(fabs(Data.m_Profile[i].m_dblMaxY - Data.m_Profile[i].m_dblMinY) / 2);
}

// Add points to array from list to define boundary curve control points
Data.m_Boundary[j][0].m_Points[i] = *(SC_Point *)(scList_GetPrev(pPoint, NULL));
Data.m_Boundary[j][0].m_Points[i].y = Data.m_Boundary[j][0].m_Points[i].y - dblOffset;

// Retrieve polyline points from list


for (k=0; k < (Data.m_Profile[i].m_iPoints/3); k++) {
pPoint = (SC_Point *)(scList_GetPrev(pPoint, NULL));
pPoint->y = pPoint->y - dblOffset;
Data.m_Profile[i].m_Point[j][k] = *pPoint;
}

// Add points to list to define boundary curves


Data.m_Boundary[j][1].m_Points[i] = *pPoint;

// Define polyline using points from list


Data.m_Profile[i].m_PLine[j]->p_SC_Point = Data.m_Profile[i].m_Point[j];

// Convert polyline to Nurb curve

325
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

scNcurve_ElementToNurb(Data.m_Profile[i].m_PLine[j],
&Data.m_Profile[i].m_NCurve[j], 3);

// Free memory reserved for polyline (no longer needed)


scElement_Final(Data.m_Profile[i].m_PLine[j]);

// Write Nurb curve to the SURFCAM database for permanent storage


scNcurve_WriteToDB(Data.m_hDatabase, Data.m_Profile[i].m_NCurve[j]);
}
}
// Return SURFCAM's color to the original color before this function.
scApp_SetCurrentColor(wCurrentColor);
}

///////////////////////////////////////////////////////////////////////////////
// DefineBoundaries
// This function converts the points in the point lists and creates the
// boundaries. The boundaries are created directly from the point lists.
//

static void
DefineBoundaries(ChannelData &Data)
{
int i,j = 0;
UINT wCurrentColor = 0;

wCurrentColor = scApp_GetCurrentColor();

scApp_SetCurrentColor(Data.m_iSurfaceColor);

// There are three channels to be constructed.


for (i = 0; i < 3; i++) {

// Each channel has two edge boundaries.


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

// Allocate memory for elements


Data.m_Boundary[i][j].m_PLine = scPline_AllocMem(3);
Data.m_Boundary[i][j].m_NCurve = scNcurve_AllocMem(3, 1);

// Define polyline using points


Data.m_Boundary[i][j].m_PLine->p_SC_Point = Data.m_Boundary[i][j].m_Points;

// Convert polyline to Nurb curve


scNcurve_ElementToNurb(Data.m_Boundary[i][j].m_PLine,
&Data.m_Boundary[i][j].m_NCurve, 3);

// Free memory reserved for polyline (no longer needed)


scElement_Final(Data.m_Boundary[i][j].m_PLine);

// Write Nurb curve to the SURFCAM database for permanent storage


scNcurve_WriteToDB(Data.m_hDatabase, Data.m_Boundary[i][j].m_NCurve);
}
}
scApp_SetCurrentColor(wCurrentColor);
}

326
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

///////////////////////////////////////////////////////////////////////////////
// CreateSurfaces
// This function creates the surfaces from the profiles and boundaries.
//

static void
CreateSurfaces(ChannelData &Data)
{
int i, j = 0;
UINT wCurrentColor = 0;

SC_NurbCurve * NCurveListU[2];
SC_NurbCurve * NCurveListV[3];

wCurrentColor = scApp_GetCurrentColor();

scApp_SetCurrentColor(Data.m_iSurfaceColor);

// There are three channels to be constructed.


for(i = 0; i < 3; i++) {

// Each channel has three sub-profiles


for(j = 0; j < 3; j++) {
NCurveListV[j] = Data.m_Profile[j].m_NCurve[i];
}

// Each channel has two boundary edges


for(j = 0; j < 2; j++) {
NCurveListU[j] = Data.m_Boundary[i][j].m_NCurve;
}

// Use scNsurf_NurbGrid to create a Nurb surface from two sets of Nurb


// curves.
scNsurf_NurbGrid(NCurveListU, 2, NCurveListV, 3, &Data.m_NSurf[i], 0.01);

// Write the resulting surface to the database for storage and display.
scNsurf_WriteToDB(Data.m_hDatabase, Data.m_NSurf[i]);
}
scApp_SetCurrentColor(wCurrentColor);
}

///////////////////////////////////////////////////////////////////////////////
// FindYMinMax
// This function determines the maximum and minimum values of Y for each
// profile in order to align them correctly.
//

static void
FindYMinMax(ChannelData &Data, double dblY, int i)
{
Data.m_Profile[i].m_dblMaxY = max(Data.m_Profile[i].m_dblMaxY, dblY);
Data.m_Profile[i].m_dblMinY = min(Data.m_Profile[i].m_dblMinY, dblY);
}

327
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Sample Code: CADL to DSN Translator

/* ------------------------ MAINWIN.CPP ----------------------------------


* --------- Copyright (c) Surfware Inc. 1987 to 1997 --------------------
* --------------------- ALL RIGHTS RESERVED -----------------------------
* It is a violation of United States copyright laws to dl_remove or alter
* this copyright notice without express written consent of Surfware Inc.
* -----------------------------------------------------------------------
*/

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <os.h>
#include <types.h>
#include <const.h>
#include "mainwin.h"
#include <expfunc.h> /* SURFCAM header file */
#include "ReadElements.h"
#include "..\h\list_io.h"
#include "resource.h"
#include "version.h" /* SURFCAM header file */

extern "C" char title[] = TITLE;


extern "C" char version[] = VERSION;
extern "C" char copyright[] = COPYRIGHT;
extern "C" char copyright2[] = "";

/* --Begin local prototypes-- */


static int ReadCadl(char *FileName);
static unsigned short * InitViewTable(unsigned n);
/* --End local prototypes-- */

static listbox lb;

/*------------------------------------------------------------------------------
/* Function: Cadl2DsnMain
/*
/* Action: Main function for CADL to DSN translator
/*
/* Type: void
/*
/* Input: char *ini_file_name Init file name
/* char *section_name Name of the section
/* char *FileName Name of the CADL file
/*
/* Output: int rc Return code
/*
/* Returns: <None>
/*
/* Called by: SURFCAM main program
/*
/* Calls: AFX_MANAGE_STATE
/* scApp_GetWindowHandle
/* lb_printf
/* read_cadl
/* result.Loadstring
/* FinalListBox
/* put_end_message
/* WaitForEnd
/*
/*--------------------------------------------------------------------------*/
extern "C" void

328
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Cadl2DsnMain (char *ini_file_name, /* Retrieve info from SURFCAM */


char *section_name,
char *FileName)
{
int rc; /* Return code variable */

HWND hWndParent;

AFX_MANAGE_STATE(AfxGetStaticModuleState());

hWndParent = scApp_GetWindowHandle(); /* Get the window handle */

InitListBox(lb, CWnd::FromHandle(hWndParent));

lb_printf(lb, COPYRIGHT_LISTBOX, "%s %s\n%s \n",title,version,copyright);

rc = ReadCadl(FileName); /* FileName: CADL file name */

CString Result;

/* File read succesful? */


if(rc == FAIL) {
Result.LoadString(IDS_FAIL);
lb_printf(lb, NEWLINE_LISTBOX, (char*)LPCTSTR(Result));
FinalListBox(lb);
}
else {
Result.LoadString(IDS_SUCCESS);
put_end_message(lb, rc,(char*)LPCTSTR(Result), NULL);
WaitForEnd(lb);
}
}

/*------------------------------------------------------------------------------
/*
/* Function: ReadCadl
/*
/* Action: Reads in the elements from a CADL file and translates
/* the elements into SURFCAM elements
/*
/* Type: static int
/*
/* Input: char *FileName Name of CADL file
/*
/* Output: Database of SURFCAM elements in DSN format
/*
/* Return: 0 Success
/* ~0 Error
/*
/* Called by: Cadl2DsnMain
/*
/* Calls: InitViewTable
/* ReadArc
/* ReadLine
/* ReadPoint
/* ReadSpline
/* ReadView
/* ReadArray
/* ReadPolyline
/* ReadVLine
/* ReadVPoint
/* ReadPolygon
/* ReadVPolygon
/* ReadConic
/* scApp_GetCurrentLayer
/* scDB_GetHandle
/* scElement_Final
/*
/*
/*

329
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/* Arguments: char sBuffer[512] Character string buffer


/* char *pBuffer Character pointers
/* int i Index counter
/* int *bAdd Added element flag
/* int *ArrayDim1 Array dimension 1
/* int *ArrayDim2 Array dimension 2
/* long int *ArraySize Array size
/* uint *nSaveLayer Save layer reference
/* ushort *ViewTable View conversion table array
/* uint *nColor Color read from file
/* uint *nLayer Layer read from file
/* static uchar length[] Length index
/* static char * keys Element index
/* SC_View *LastView Last view used
/* SC_View *pCurrentView Pointer to current view
/* HSC_DB *hDB SURFCAM database handle
/* double *ViewMatrixArray View matrix array
/*
/*--------------------------------------------------------------------------*/
static int
ReadCadl(char *FileName)
{
char sBuffer[512]; /* Character string buffer */
char *pBuffer; /* Character pointer */
int i; /* Index counter */
int bAdd; /* Added element flag */
int ArrayDim1, ArrayDim2; /* Array dimensions */
long int ArraySize; /* View matrix array size */

unsigned int nSaveLayer; /* Save layer */


unsigned short *ViewTable; /* View conversion table */
double *ViewMatrixArray = NULL; /* View matrix array */

SC_View LastView; /* Last view used */


SC_View CurrentView; /* Current view */

static unsigned char length[] = {3,6,4,5,6,4,5,8,5,6,7,8,5,0};


static char * keys[] = {"ARC","CIRCLE","LINE","POINT","SPLINE",
"VIEW","ARRAY", "POLYLINE","VLINE","VPOINT",
"POLYGON","VPOLYGON","CONIC",""};

ArraySize = 0L; /* Initialize view matrix size to zero */

FILE *pFile = fopen(FileName, "r");

if (pFile == NULL)
return(FAIL);

const_init(); /* Set global constant */

HSC_DB hDB = scDB_GetHandle(); /* Get Database handle */

ViewTable = InitViewTable(MAX_VIEW_NUM);

nSaveLayer = scApp_GetCurrentLayer(); /* Get current layer of SURFCAM */

LastView.view = 0; /* Last view is not initialized */

while (fgets(sBuffer, 511, pFile))


{
for (i = 0; length[i]; i++)
if (!strncmp(keys[i], sBuffer, length[i]))
break;

if (!length[i])
continue;

pBuffer = sBuffer + length[i];

bAdd = 0;

330
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

switch(i)
{
case ARC:
ReadArc(pBuffer, &hDB, &nSaveLayer, &CurrentView, &LastView, ViewTable,
&bAdd, ARCFLAG);
break;

case CIRCLE:
ReadArc(pBuffer, &hDB, &nSaveLayer, &CurrentView, &LastView, ViewTable,
&bAdd, CIRCLEFLAG);
break;

case LINE:
ReadLine(pBuffer, &hDB, &bAdd, &nSaveLayer);
break;

case POINT:
ReadPoint(pBuffer, &hDB, &bAdd, &nSaveLayer);
break;

case SPLINE:
ReadSpline(pBuffer, &hDB, &bAdd, &nSaveLayer, &ArrayDim1, &ArrayDim2,
&LastView, &CurrentView, ViewTable, &ViewMatrixArray);
break;

case VIEW:
ReadView(pBuffer, &hDB, ViewTable, &LastView);
break;

case ARRAY:
ReadArray(pBuffer, pFile, &ViewMatrixArray, &ArraySize, &ArrayDim1,
&ArrayDim2);
break;

case POLYLINE:
ReadPolyline(pBuffer, &hDB, &bAdd, &nSaveLayer, &ArrayDim1,
&ViewMatrixArray);
break;

case VLINE:
ReadVLine(pBuffer, &hDB, &bAdd, &nSaveLayer, &CurrentView, &LastView,
ViewTable);
break;

case VPOINT:
ReadVPoint(pBuffer, &hDB, &bAdd, &nSaveLayer, &CurrentView, &LastView,
ViewTable);
break;

case POLYGON:
ReadPolygon(pBuffer, &hDB, &bAdd, &nSaveLayer, &ArrayDim1, &CurrentView,
&LastView, ViewTable, &ArraySize, &ViewMatrixArray);
break;

case VPOLYGON:
ReadVPolygon(pBuffer, &hDB, &bAdd, &nSaveLayer, &ArrayDim1, &CurrentView,
&LastView, ViewTable, &ArraySize, &ViewMatrixArray);
break;

case CONIC:

331
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

ReadConic(pBuffer, &hDB, &bAdd, &nSaveLayer, &LastView, &CurrentView,


ViewTable);
break;

default:
break;
} /* End switch */
} /* End while */

/* Free up the allocated memory */


ArraySize = 0L;
scMem_Free(ViewTable);

fclose(pFile);
return SUCCESS;
}

/*------------------------------------------------------------------------------
/* Function: InitViewTable
/*
/* Action: Initializes view table
/*
/* Type: unsigned short *
/*
/* Input: unsigned n Number of views
/*
/* Returns: Pointer to initizlized view table
/*
/* Called by: ReadCadl
/*
/*----------------------------------------------------------------------------*/
static unsigned short *
InitViewTable(unsigned n)
{
int i;
unsigned short *tab;

/* Allocate one extra so view number & array index match */


tab = (unsigned short *)scMem_Alloc((n+1) * sizeof(*tab));
memset(tab, 0, (n+1) * sizeof(*tab));

/* Scan the view list to set up the view table */


/* Put views allocated in SURFCAM into table */
scApp_ScanViewTable(tab, n+1);

for(i = 1; i < 9 ; i++)


tab[i] = (unsigned short)i;

return(tab);
}

332
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/* ------------------------- MAINWIN.H -----------------------------------


* --------- Copyright (c) Surfware Inc. 1987 to 1997 --------------------
* --------------------- ALL RIGHTS RESERVED -----------------------------
* It is a violation of United States copyright laws to dl_remove or alter
* this copyright notice without express written consent of Surfware Inc.
* -----------------------------------------------------------------------
*/

#ifndef __MAINWIN_H__
#define __MAINWIN_H__

#ifdef __cplusplus
extern "C" {
#endif

void Cadl2DsnMain(char *ini_file_name,


char *section_name,
char *file_name);

#ifdef __cplusplus
}
#endif

/* For switch loop: case definitions */


#define ARC 0
#define CIRCLE 1
#define LINE 2
#define POINT 3
#define SPLINE 4
#define VIEW 5
#define ARRAY 6
#define POLYLINE 7
#define VLINE 8
#define VPOINT 9
#define POLYGON 10
#define VPOLYGON 11
#define CONIC 12

#endif

333
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/* ---------------------- ReadElements.cpp -------------------------------


* --------- Copyright (c) Surfware Inc. 1987 to 1997 --------------------
* --------------------- ALL RIGHTS RESERVED -----------------------------
* It is a violation of United States copyright laws to remove or alter
* this copyright notice without express written consent of Surfware Inc.
* -----------------------------------------------------------------------
*/

#include "stdafx.h"
#include <types.h>
#include <const.h>
#include <math.h>
#include <expfunc.h> /* SURFCAM header file */
#include "CadlFunctions.h"
#include "ReadElements.h"

static unsigned short FindFreeView(unsigned short min,


unsigned short *tab);

static int ReadCadlSpline(HSC_DB *hDB,


int n,
int ndim,
double *depth,
double*& ViewMatrixArray,
SC_View *pCurrentView,
unsigned int *nColor,
unsigned int *nLayer);

static void GetCdlVmCoeffs(double*& ViewMatrixArray,


unsigned int i,
int ndim,
double *depth,
struct coeffs *pBuffer);

static void TranslateArc(double *p_dblAngle1,


double *p_dblAngle2,
double *p_dblRadius,
SC_Point *p_Origin,
unsigned int *p_nColor,
unsigned int *p_nLayer,
SC_View *p_View,
SC_View *p_LastView,
unsigned short *p_nView,
unsigned short *p_nViewTable,
int *p_iAdd,
HSC_DB *p_hDB);

int
ReadArc(char *pBuffer, /* Character pointers */
HSC_DB *hDB, /* SURFCAM database handle */
unsigned int *nSaveLayer, /* Save layer */
SC_View *CurrentView, /* View being used currently */
SC_View *LastView, /* Last view used */
unsigned short *ViewTable, /* View conversion table */
int *bAdd, /* Added element flag */
int bCircle) /* Circle/Arc flag */
{
SC_Point Point; /* Points read in from CADL */
double dblAngle1; /* Arc start angle */
double dblAngle2; /* Arc end angle */
double dblRadius; /* Arc radius */
unsigned short nViewNum; /* View number */
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */

334
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

switch(bCircle)
{
case ARCFLAG:
if (sscanf(pBuffer,"%lf,%lf,%lf,%lf,%lf,%lf,%hu,%u,%u",
&Point.x, &Point.y, &Point.z, &dblRadius, &dblAngle1, &dblAngle2,
&nViewNum, &nColor, &nLayer) < 7)
break;

if (!CheckCadl(hDB, &nColor, &nLayer, &nViewNum, nSaveLayer))


break;

/* Ensure that the start angle is less than the end angle */
if(dblAngle1 > dblAngle2)
dblAngle1 -= 360.0;

dblAngle1 *= _dtr; /* _dtr is the degrees to radians constant */


dblAngle2 *= _dtr; /* _dtr is the degrees to radians constant */

TranslateArc(&dblAngle1, &dblAngle2, &dblRadius, &Point, &nColor,


&nLayer, CurrentView, LastView, &nViewNum, ViewTable, bAdd, hDB);

break;

case CIRCLEFLAG:
if(sscanf(pBuffer,"%lf,%lf,%lf,%lf,%hu,%u,%u",
&Point.x, &Point.y, &Point.z, &dblRadius, &nViewNum, &nColor,
&nLayer) < 5)
break;

if(!CheckCadl(hDB, &nColor, &nLayer, &nViewNum, nSaveLayer))


break;

dblAngle1 = 0.0;
dblAngle2 = _2pi;

TranslateArc(&dblAngle1, &dblAngle2, &dblRadius, &Point, &nColor,


&nLayer, CurrentView, LastView, &nViewNum, ViewTable, bAdd, hDB);

break;
}
return SUCCESS;
}

/*------------------------------------------------------------------------------
/* Function: TranslateArc
/*
/* Action: Translates an arc or circle into an SC_Arc
/*
/* Type: void
/*
/* Input and
/* Output: HSC_DB *p_hDB SURFCAM database
/* SC_Arc *p_Arc Arc written to database
/*
/* Input: double *p_dblAngle1 Start angle (0 for circle)
/* double *p_dblAngle2 End angle (2 PI for circle)
/* double *p_dblRadius Radius of arc
/* SC_Point *p_Origin Origin coordinates
/* unsigned int *p_nColor CADL color for arc
/* unsigned int *p_nLayer CADL layer for arc
/* SC_View *p_View Current SURFCAM view
/* SC_View *p_LastView Last SURFCAM view
/* unsigned short *p_nView View number
/* unsigned short *p_nViewTable View table
/* int *p_iAdd Add flag (entity added)
/*
/* Returns: <None>
/*
/* Called by: ReadArc
/*
/*----------------------------------------------------------------------------*/

335
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

static void
TranslateArc(double *p_dblAngle1, double *p_dblAngle2, double *p_dblRadius,
SC_Point *p_Origin, unsigned int *p_nColor, unsigned int *p_nLayer,
SC_View *p_View, SC_View *p_LastView, unsigned short *p_nView,
unsigned short *p_nViewTable, int *p_iAdd, HSC_DB *p_hDB)
{
double x1, y1; /* Arc center position */
SC_Arc *p_Arc;

if (!GetCadlView(p_View, p_nView, p_LastView, p_nViewTable))


return;

p_Arc = scArc_AllocMem(); /* Allocate memory for SC_Arc element */

p_Arc->angle = *p_dblAngle2 - *p_dblAngle1; /* Total angle is angle difference */

if (p_Arc->angle < 1e-5) { /* Tolerance (lower bound) */


*p_dblAngle1 = 0.0; /* Converts to full circle */
p_Arc->angle = _2pi; /* if angle too low. */
}
p_Arc->radius = *p_dblRadius;

/* Find center in world coodinates */


CdlTransformViewWorld(&p_Arc->center, p_Origin, p_View);

x1 = cos(*p_dblAngle1);
y1 = sin(*p_dblAngle1);

p_Arc->begin.x = x1*p_View->view_mat[0][0] + y1*p_View->view_mat[0][1];


p_Arc->begin.y = x1*p_View->view_mat[1][0] + y1*p_View->view_mat[1][1];
p_Arc->begin.z = x1*p_View->view_mat[2][0] + y1*p_View->view_mat[2][1];

p_Arc->normal.x = p_View->view_mat[0][2];
p_Arc->normal.y = p_View->view_mat[1][2];
p_Arc->normal.z = p_View->view_mat[2][2];

/* Set in_color and in_layer to arc pointer */


SetLayerColor(p_Arc, p_nColor, p_nLayer);

scArc_WriteToDB(*p_hDB, p_Arc); /* Write arc to data base */

/* Free the arc memory allocated by scArc_AllocMem */


scElement_Final(p_Arc);

*p_iAdd = 1;
}

int
ReadArray(char *pBuffer,
FILE *pFile,
double **ViewMatrixArray, /* Pointer to view matrix array */
long int *ArraySize, /* View matrix array size */
int *ArrayDim1,
int *ArrayDim2)
{
int TotalDim; /* Total dimensions */
int i;
double *dblValue;
char *pChar;
char *sBuffer;

*ArrayDim2 = 1;
sscanf(pBuffer, " %*[^[] [ %d ] [ %d", ArrayDim1, ArrayDim2);
TotalDim = (*ArrayDim1) * (*ArrayDim2);

/* Now read in the array itself */


*pBuffer = '\0';

if (*ViewMatrixArray == NULL)
(*ViewMatrixArray) = (double*)scMem_Alloc(sizeof(double)*TotalDim);

336
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

else if(TotalDim > *ArraySize)


(*ViewMatrixArray) = (double*)scMem_Realloc((*ViewMatrixArray),
sizeof(double)*TotalDim);

*ArraySize = TotalDim;

for (i = 0; i < TotalDim; )


{
while (isspace(*pBuffer) || *pBuffer == ',')
pBuffer++;

if (!*pBuffer)
{
if (!fgets(sBuffer, 139, pFile))
break;
pBuffer = sBuffer;
continue;
};

dblValue = (*ViewMatrixArray)+i;
*dblValue = strtod(pBuffer, &pChar);
pBuffer = pChar;
i++;
};

/* Eat the last closing brace */


for (;;) {
if (!*pBuffer) {
if (!fgets(sBuffer, 139, pFile))
break;
pBuffer = sBuffer;
}
if (*pBuffer == '}')
break;
pBuffer++;
}

return SUCCESS;
}

int
ReadConic(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
SC_View *LastView, SC_View *pCurrentView, unsigned short *ViewTable)
{
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
unsigned short nViewNum; /* View number */

int i, rc;
int nFlags = STD_CONIC;
double Matrix[4][4];
SC_Conic Conic;
SC_Conic NewConic;
SC_Point *Point;
SC_NurbCurve *Ncurve;

sscanf(pBuffer, "%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%d,%d,%d",
&Conic.a, &Conic.b, &Conic.c, &Conic.d, &Conic.e,
&Conic.f, &Conic.x1, &Conic.y1, &Conic.x2, &Conic.y2,
&Conic.zt, &nViewNum, &nColor, nLayer);

if (!CheckCadl(hDB, &nColor, &nLayer, &nViewNum, nSaveLayer))


return FAIL;

if (!GetCadlView(pCurrentView, &nViewNum, LastView, ViewTable))


return FAIL;

/* Transform conic into standard position and get the transformation matrix */
rc = scConic_TransformToStandard(&NewConic, Matrix, &Conic);

337
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

if (rc == SUCCESS)
{
/* Convert standard conic into nurb curve */
rc = scNcurve_ConicToNurb(&NewConic, nFlags, &Ncurve);
};

/* Transform nurb control points to world coords */


if (rc == SUCCESS) {
for (i = 0; i < (int)Ncurve->npts; i++) {
Point = &(Ncurve->p_SC_NPoint[i].point);

/* Transform point back to local coord */


scMat_Transform(Point, Point, Matrix, 0);

/* Transform point from local to global */


CdlTransformViewWorld(Point, Point, pCurrentView);
}
}

/* Set in_color and in_layer to NURB pointer */


SetLayerColor(Ncurve, &nColor, &nLayer);

scNcurve_WriteToDB(*hDB, Ncurve); /* Write NURB curve to database */


scElement_Final(Ncurve); /* Free sc_Ncurve allocated memory */

if (rc == SUCCESS)
*bAdd = 1;

return SUCCESS;
}

int
ReadLine(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer)
{
SC_Point Endpoint1, Endpoint2;
SC_Line *pLine;
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
unsigned short nDummyView = 1; /* Dummy view */

if (sscanf(pBuffer,"%lf,%lf,%lf,%lf,%lf,%lf,%u,%u",
&Endpoint1.x, &Endpoint1.y, &Endpoint1.z,
&Endpoint2.x, &Endpoint2.y, &Endpoint2.z,
&nColor, &nLayer) < 6)
return FAIL;

if (!CheckCadl(hDB, &nColor, &nLayer, &nDummyView, nSaveLayer))


return FAIL;

pLine = scLine_AllocMem(); /* Allocate memory for a line */

pLine->start = Endpoint1; /* Define start point */


pLine->end = Endpoint2; /* Define end point */

/* Set in_color and in_layer to line pointer */


SetLayerColor(pLine, &nColor, &nLayer);
scLine_WriteToDB(*hDB, pLine); /* Write line to database */
scElement_Final(pLine); /* Free scLine allocated memory */
*bAdd = 1;

return SUCCESS;
}

int
ReadPoint(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer)
{
SC_Point Point;
SC_Point *PointPtr; /* Point pointer */
unsigned int nColor; /* Input color from CADL */

338
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

unsigned int nLayer; /* Input layer from CADL */


unsigned short nDummyView = 1; /* Dummy view from CADL */

if (sscanf(pBuffer,"%lf,%lf,%lf,%u,%u",
&Point.x, &Point.y, &Point.z, &nColor, &nLayer) < 3)
return FAIL;

if (!CheckCadl(hDB, &nColor, &nLayer, &nDummyView, nSaveLayer))


return FAIL;

PointPtr = scPoint_AllocMem(); /* Allocate memory for point */

*PointPtr = Point;

/* Set in_color and in_layer to point pointer */


SetLayerColor(PointPtr, &nColor, &nLayer);

scPoint_WriteToDB(*hDB, PointPtr); /* Write point to database */


scElement_Final(PointPtr); /* Free scPoint allocated memory */
*bAdd = 1;

return SUCCESS;
}

int
ReadPolygon(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, SC_View *pCurrentView, SC_View * LastView,
unsigned short *ViewTable, long int *ArraySize,
double **ViewMatrixArray)
{
SC_Point Endpoint1, Endpoint2;
SC_Point Point; /* Input point pointer */
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
int nIndex; /* Index variable */
unsigned short nDummyView = 1; /* Dummy view */

sscanf(pBuffer, "%*d,%*d,%d, %*[^,],%u,%u",


&nIndex, &nColor, &nLayer);
if (nIndex*3 != (*ArrayDim1))
return FAIL; /* Something has gone wrong */

if (!CheckCadl(hDB, &nColor, &nLayer, &nDummyView, nSaveLayer))


return FAIL; /* Something has gone wrong */

GetCdlVm3dPoint(*ViewMatrixArray, 0, &Endpoint1);
GetCdlVm3dPoint(*ViewMatrixArray, nIndex-1, &Endpoint2);

if (scDist_PointPoint(&Endpoint1, &Endpoint2) > _fchain_tol)


{
GetCdlVm3dPoint(*ViewMatrixArray, 0, &Point);
SetCdlVm3dPoint(*ViewMatrixArray, nIndex, &Point, ArraySize);
nIndex++;
};

ReadCadlPolyline(hDB, nIndex, *ViewMatrixArray, &nColor, &nLayer);

*bAdd = 1;

scMem_Free(*ViewMatrixArray);

*ViewMatrixArray = NULL;

return SUCCESS;
}

int
ReadPolyline(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, double **ViewMatrixArray)
{

339
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

unsigned int nColor; /* Input color from CADL */


unsigned int nLayer; /* Input layer from CADL */
unsigned short nDummyView = 1; /* Dummy view */
int nIndex;

sscanf(pBuffer, "%d, %*[^,],%*lf,%*d,%*d,%*d,%u,%u",


&nIndex, &nColor, &nLayer);

if (nIndex*3 != *ArrayDim1)
return FAIL; /* Somthing has gone wrong */

if (!CheckCadl(hDB, &nColor, &nLayer, &nDummyView, nSaveLayer))


return FAIL; /* Somthing has gone wrong */

/* Calls read polyline function */


ReadCadlPolyline(hDB, nIndex, *ViewMatrixArray, &nColor, &nLayer);

*bAdd = 1;

scMem_Free(*ViewMatrixArray);

*ViewMatrixArray = NULL;

return SUCCESS;
}

int
ReadSpline(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, int *ArrayDim2, SC_View *LastView,
SC_View *pCurrentView, unsigned short *ViewTable,
double **ViewMatrixArray)
{
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
unsigned short nViewNum = 1; /* View number */
char SplineType[6]; /* Spline type buffer */
int nIndex;
int nDim; /* Number of dimensions */
double dblDepth;

sscanf(pBuffer, " %[^,], %*[^,],%d,%u,%u", SplineType, &nIndex,


&nColor, &nLayer);

if (!strncmp(SplineType, "C3", 2))


{
if ((nIndex != (*ArrayDim1)) || ((*ArrayDim2) != 12))
return FAIL; /* Somthing has gone wrong */

pCurrentView = (SC_View *)NULL;


nDim = 3;
dblDepth = 0.0;
}

else if (!strncmp(SplineType, "C2", 2))


{

/* Rescan the line to get the depth and view */


sscanf(pBuffer, " %[^,], %*[^,],%d,%lf,%u,%u,%u",
SplineType, &nIndex, &dblDepth, &nViewNum, &nColor, &nLayer);

if (nIndex != (*ArrayDim1) || (*ArrayDim2) != 8)


return FAIL; /* Somthing has gone wrong */

if (!GetCadlView(pCurrentView, &nViewNum, LastView, ViewTable))


return FAIL; /* Somthing has gone wrong */

nDim = 2;

else

340
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

return FAIL; /* Only 3d or 2d spline in coef format */

if (!CheckCadl(hDB, &nColor, &nLayer, &nViewNum, nSaveLayer))


return FAIL;

*bAdd = ReadCadlSpline(hDB, *ArrayDim1, nDim, &dblDepth, *ViewMatrixArray,


pCurrentView, &nColor, &nLayer);

scMem_Free(*ViewMatrixArray);

*ViewMatrixArray = NULL;

return SUCCESS;
}

/*------------------------------------------------------------------------------
/* Function: ReadCadlSpline
/*
/* Action: Reads in a CADL spline and tranforms it into a NURB curve. This
/* is accomplished by converting each parametric cubic span of the
/* CADL spline into a Bezier curve. These Bezier curves are
/* appended together and the extraneous control points and knots
/* are removed. This algorithm allows the converted curves to
/* accurately represent curves with sharp corners (i.e. C1 discon-
/* tinuity).
/*
/* Type: static int
/*
/* Input and
/* Output: HSC_DB *p_hDB SURFCAM database
/*
/* Input: int nNumOfSpans Number of CADL pc spans
/* int nDimensions Dimensions (2D or 3D)
/* double nDepth Depth of spline
/* double *&PointArray Array of control points
/* SC_View *p_View Current SURFCAM view
/*
/* Returns: 0 Success
/* ~0 Fail
/*
/* Called by: ReadSpline
/*
/* Calls: GetCdlVmCoeffs
/* SetLayerColor
/* scElement_Final
/* scNcurve_AllocMem
/* scNcurve_RemoveKnots
/* scNcurve_WriteToDB
/*
/*----------------------------------------------------------------------------*/
static int
ReadCadlSpline(HSC_DB *hDB, int nNumOfSpans, int nDimensions,
double *dblDepth, double *& PointArray, SC_View * p_View,
unsigned int * nColor, unsigned int * nLayer)

{
int i, nIndex, nReps;
int idx = 0;
int idx_knots = 0;
double dblDistance = 0.0;
coeffs TempCoeff;
SC_Point Origin;
SC_NurbCurve *NurbCurve = NULL;
UINT nOrder;
UINT nNumOfPoints;

nOrder = 4;
nNumOfPoints = 3 * nNumOfSpans + 1;

NurbCurve = scNcurve_AllocMem(nNumOfPoints, nOrder);

341
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/* Fill first four knots with zeroes (fourth order equation) */


for(i=0;i<4;i++) {
NurbCurve->p_knot[idx_knots++] = 0.0;
}

for(nIndex = 0; nIndex < nNumOfSpans; nIndex++)


{
/* Read in coefficients for each pc CADL span */
GetCdlVmCoeffs(PointArray, nIndex, nDimensions, dblDepth, &TempCoeff);

/* Bezier control point 1 (origin of span)*/


NurbCurve->p_SC_NPoint[idx].w = 1.0;
NurbCurve->p_SC_NPoint[idx].point.x = TempCoeff.c[0][3];
NurbCurve->p_SC_NPoint[idx].point.y = TempCoeff.c[1][3];
NurbCurve->p_SC_NPoint[idx].point.z = TempCoeff.c[2][3];
Origin = NurbCurve->p_SC_NPoint[idx].point;
idx ++;

/* Bezier control point 2 */


NurbCurve->p_SC_NPoint[idx].w = 1.0;
NurbCurve->p_SC_NPoint[idx].point.x = (TempCoeff.c[0][2] / 3.0) + TempCoeff.c[0][3];
NurbCurve->p_SC_NPoint[idx].point.y = (TempCoeff.c[1][2] / 3.0) + TempCoeff.c[1][3];
NurbCurve->p_SC_NPoint[idx].point.z = (TempCoeff.c[2][2] / 3.0) + TempCoeff.c[2][3];
idx ++;

/* Bezier control point 3 */


NurbCurve->p_SC_NPoint[idx].w = 1.0;
NurbCurve->p_SC_NPoint[idx].point.x = TempCoeff.c[0][0] + TempCoeff.c[0][1]
+ TempCoeff.c[0][2] + TempCoeff.c[0][3] - (3.0 * TempCoeff.c[0][0]
+ 2 * TempCoeff.c[0][1] + TempCoeff.c[0][2]) / 3.0;
NurbCurve->p_SC_NPoint[idx].point.y = TempCoeff.c[1][0] + TempCoeff.c[1][1]
+ TempCoeff.c[1][2] + TempCoeff.c[1][3] - (3.0 * TempCoeff.c[1][0]
+ 2 * TempCoeff.c[1][1] + TempCoeff.c[1][2]) / 3.0;
NurbCurve->p_SC_NPoint[idx].point.z = TempCoeff.c[2][0] + TempCoeff.c[2][1]
+ TempCoeff.c[2][2] + TempCoeff.c[2][3] - (3.0 * TempCoeff.c[2][0]
+ 2 * TempCoeff.c[2][1] + TempCoeff.c[2][2]) / 3.0;
idx ++;

/* Bezier control point 4 */


/*(C0 continuity assumed: point 4 discarded for all spans except for the last span)*/
NurbCurve->p_SC_NPoint[idx].w = 1.0;
NurbCurve->p_SC_NPoint[idx].point.x = TempCoeff.c[0][0] + TempCoeff.c[0][1]
+ TempCoeff.c[0][2] + TempCoeff.c[0][3];
NurbCurve->p_SC_NPoint[idx].point.y = TempCoeff.c[1][0] + TempCoeff.c[1][1]
+ TempCoeff.c[1][2] + TempCoeff.c[1][3];
NurbCurve->p_SC_NPoint[idx].point.z = TempCoeff.c[2][0] + TempCoeff.c[2][1]
+ TempCoeff.c[2][2] + TempCoeff.c[2][3];

/* Knots are NOT normalized. Knots are defined at the distances along the curve */
dblDistance += scDist_PointPoint(&Origin, &NurbCurve->p_SC_NPoint[idx].point);

if(nIndex == (nNumOfSpans - 1)) /* Last span requires four knots */


nReps = 4;
else /* Intermediate spans require three */
nReps = 3;

for(i=0;i<nReps;i++) {
NurbCurve->p_knot[idx_knots++] = dblDistance;
}
}

NurbCurve->startu = 0.0; /* Fill in NURB curve */


NurbCurve->endu = dblDistance;
SetLayerColor(NurbCurve, nColor, nLayer);

scNcurve_RemoveKnots(&NurbCurve, 0); /* Remove extra knots */


scNcurve_WriteToDB(*hDB, NurbCurve); /* Write to database */

scElement_Final(NurbCurve); /* Free up memory */

return (1);
}

342
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/*------------------------------------------------------------------------------
/* Function: GetCadlVmCoeffs
/*
/* Action: Retrieve the matrix coefficients (2D and 3D)
/*
/* Type: void
/*
/* Input: double*& ViewMatrixArray Array of coordinates
/* unsigned int i Number of elements in array
/* int ndim Number of coordinate sets
/* double depth Z coordinate values
/*
/* Output: struct coeffs *pBuffer
/*
/* Returns: <None>
/*
/* Called by: ReadCadlSpline
/*
/*----------------------------------------------------------------------------*/
static void
GetCdlVmCoeffs(double*& ViewMatrixArray,
unsigned int i,
int ndim,
double *depth,
struct coeffs *pBuffer)
{
int j, k;

i *= ndim * 4;
for (j = 0; j < ndim; j++) {
for (k = 0; k < 4; k++) {
pBuffer->c[j][k] = ViewMatrixArray[i];
i++;
}
}

if (ndim == 2) {
pBuffer->c[2][0] = pBuffer->c[2][1] = pBuffer->c[2][2] = 0.0;
pBuffer->c[2][3] = *depth;
}

return;
}

int
ReadView(char *pBuffer, HSC_DB *hDB, unsigned short *ViewTable, SC_View *LastView)
{
SC_View View;
SC_View ViewFound;
unsigned short nFreeView;

if(sscanf(pBuffer,"%u,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",&View.view,
&View.view_mat[0][0], &View.view_mat[0][1], &View.view_mat[0][2],
&View.view_mat[1][0], &View.view_mat[1][1], &View.view_mat[1][2],
&View.view_mat[2][0], &View.view_mat[2][1], &View.view_mat[2][2]) != 10)
return FAIL;

if(View.view > MAX_VIEW_NUM || View.view == 0)


return FAIL;

if(fabs(View.view_mat[0][0]) < _accy &&


fabs(View.view_mat[0][1]) < _accy &&
fabs(View.view_mat[0][2]) < _accy)
return FAIL; /* Illegal matrix */

sprintf(View.name, "CADL View %d.", View.view);

if (ViewTable[View.view])
{ /* This View is already used */

343
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/* Get the information and put into ViewFound */


int rc = scView_GetView(&ViewFound, View.view);

if (rc == SUCCESS) /* The same View */


if (scView_Compare(&View, &ViewFound) == 0)
return FAIL;

nFreeView = FindFreeView(50, ViewTable);


if (nFreeView == 0)
return FAIL; /* No free View found */
ViewTable[View.view] = nFreeView;
View.view = nFreeView;
ViewTable[nFreeView] = nFreeView;
}
else
ViewTable[View.view] = View.view;

scView_WriteToDB(*hDB, &View); /* Write View to database */

/* Save View just read to last_view */


*LastView = View;

return SUCCESS;
}

/*------------------------------------------------------------------------------
/* Function: FindFreeView
/*
/* Action: Finds first free view reference number
/*
/* Type: unsigned short
/*
/* Input: SC_Point *pin Input point
/* SC_View *v View
/*
/* Output: SC_Point *pout Output point
/*
/* Returns: 1 to MAX_VIEW_NUM Free view number
/* 0 Error code
/*
/* Called by: ReadView
/*
/*----------------------------------------------------------------------------*/
static unsigned short
FindFreeView(unsigned short min, unsigned short *tab)

{
unsigned short i;

for (i = min; i <= MAX_VIEW_NUM; i++) {


if (tab[i] == 0)
return(i);
}
return(0);
}

int
ReadVLine(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
SC_View *pCurrentView, SC_View * LastView, unsigned short *ViewTable)
{
SC_Point Endpoint1, Endpoint2;
SC_Line * pLine;
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
unsigned short nView; /* Dummy view from CADL */

344
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

if (sscanf(pBuffer,"%lf,%lf,%lf,%lf,%lf,%lf,%hu,%u,%u",
&Endpoint1.x, &Endpoint1.y, &Endpoint1.z,
&Endpoint2.x, &Endpoint2.y, &Endpoint2.z,
&nView, &nColor, &nLayer) < 7)
return FAIL;

if (!CheckCadl(hDB, &nColor, &nLayer, &nView, nSaveLayer))


return FAIL;

if (!GetCadlView(pCurrentView, &nView, LastView, ViewTable))


return FAIL;

pLine = scLine_AllocMem(); /* Allocate memory for a line */

/* Find start point in world coodinates */


CdlTransformViewWorld(&pLine->start, &Endpoint1, pCurrentView);

/* Find end point in world coodinates */


CdlTransformViewWorld(&pLine->end, &Endpoint2, pCurrentView);

/* Set in_color and in_layer to line pointer */


SetLayerColor(pLine, &nColor, &nLayer);
scLine_WriteToDB(*hDB, pLine); /* Write line to database */
scElement_Final(pLine); /* Free scLine allocated memory */

*bAdd = 1;

return SUCCESS;
}

int
ReadVPoint(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer,
SC_View *pCurrentView, SC_View * LastView, unsigned short *ViewTable)
{
SC_Point Point;
SC_Point * PointPtr; /* Input point pointer */
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
unsigned short nViewNum; /* View from CADL */

if (sscanf(pBuffer,"%lf,%lf,%lf,%hu,%u,%u",
&Point.x, &Point.y, &Point.z, &nViewNum, &nColor, &nLayer) < 4)
return FAIL;

if (!CheckCadl(hDB, &nColor, &nLayer, &nViewNum, nSaveLayer))


return FAIL;

if (!GetCadlView(pCurrentView, &nViewNum, LastView, ViewTable))


return FAIL;

PointPtr = scPoint_AllocMem(); /* Allocate memory for point */

/* Find point in world coodinates */


CdlTransformViewWorld(PointPtr, &Point, pCurrentView);

/* Set in_color and in_layer to point pointer */


SetLayerColor(PointPtr, &nColor, &nLayer);
scPoint_WriteToDB(*hDB, PointPtr); /* Write point to database */
scElement_Final(PointPtr); /* Free scPoint allocated memory */

*bAdd = 1;

return SUCCESS;
}

345
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

int
ReadVPolygon(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, SC_View *pCurrentView, SC_View * LastView,
unsigned short *ViewTable, long int *ArraySize,
double **ViewMatrixArray)
{
SC_Point Point;
SC_Point Endpoint1, Endpoint2;
unsigned int nColor; /* Input color from CADL */
unsigned int nLayer; /* Input layer from CADL */
unsigned short nView; /* Dummy view from CADL */
int nIndex;
int nPoints;
int i;
double dblDepth;

sscanf(pBuffer, "%*d,%*d,%d, %*[^,],%lf,%hu,%u,%u",


&nIndex, &dblDepth, &nView, &nColor, &nLayer);
if (nIndex*2 != *ArrayDim1)
return FAIL; /* Something has gone wrong */

if (!CheckCadl(hDB, &nColor, &nLayer, &nView, nSaveLayer))


return FAIL; /* Something has gone wrong */

if (!GetCadlView(pCurrentView, &nView, LastView, ViewTable))


return FAIL; /* Something has gone wrong */

/* Check if it is closed */
GetCdlVm2dPoint(*ViewMatrixArray, 0, &Endpoint1);
GetCdlVm2dPoint(*ViewMatrixArray, nIndex-1, &Endpoint2);
if (scDist_PointPoint(&Endpoint1, &Endpoint2) < _fchain_tol)
nPoints = nIndex;
else
nPoints = nIndex + 1;

/* Convert to 3-d & transform to view coords */


for (i = nPoints - 1; i >= 0; i--) {
GetCdlVm2dPoint(*ViewMatrixArray, i, &Point);
Point.z = dblDepth;
CdlTransformViewWorld(&Point, &Point, pCurrentView);
SetCdlVm3dPoint(*ViewMatrixArray, i, &Point, ArraySize);
}

if (nPoints != nIndex) {
GetCdlVm3dPoint(*ViewMatrixArray, 0, &Point);
SetCdlVm3dPoint(*ViewMatrixArray, nPoints - 1, &Point, ArraySize);
}

ReadCadlPolyline(hDB, nIndex, *ViewMatrixArray, &nColor, &nLayer);

*bAdd = 1;

scMem_Free(*ViewMatrixArray);

ViewMatrixArray = NULL;

return SUCCESS;
}

346
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/* ----------------------- ReadElements.h --------------------------------


* --------- Copyright (c) Surfware Inc. 1987 to 1997 --------------------
* --------------------- ALL RIGHTS RESERVED -----------------------------
* It is a violation of United States copyright laws to remove or alter
* this copyright notice without express written consent of Surfware Inc.
* -----------------------------------------------------------------------
*/

#ifndef __READELEMENTS_H__
#define __READELEMENTS_H__

int ReadArc(char *sBuffer, /* Character pointers */


HSC_DB *hDB, /* SURFCAM database handle */
unsigned int *nSaveLayer, /* Save layer */
SC_View *CurrentView, /* View being used currently */
SC_View *LastView, /* Last view used */
unsigned short *ViewTable, /* View conversion table */
int *bAdd, /* Added element flag */
int bCircle); /* Circle/Arc flag */

int ReadArray(char *pBuffer,


FILE *pFile,
double **ViewMatrixArray, /* View matrix array */
long int *ArraySize, /* View matrix array size */
int *ArrayDim1,
int *ArrayDim2);

int ReadConic(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
SC_View *LastView, SC_View *pCurrentView, unsigned short *ViewTable);

int ReadLine(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer);

int ReadPoint(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer);

int ReadPolygon(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, SC_View *pCurrentView, SC_View * LastView,
unsigned short *ViewTable, long int *ArraySize,
double **ViewMatrixArray);

int ReadPolyline(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, double **ViewMatrixArray);

int ReadSpline(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, int *ArrayDim2, SC_View *LastView,
SC_View *pCurrentView, unsigned short *ViewTable,
double **ViewMatrixArray);

int ReadView(char *pBuffer, HSC_DB *hDB, unsigned short *ViewTable, SC_View *LastView);

int ReadVLine(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
SC_View *pCurrentView, SC_View * LastView, unsigned short *ViewTable);

int ReadVPoint(char *pBuffer, HSC_DB *hDB, int * bAdd, unsigned int *nSaveLayer,
SC_View *pCurrentView, SC_View * LastView, unsigned short *ViewTable);

int ReadVPolygon(char *pBuffer, HSC_DB *hDB, int *bAdd, unsigned int *nSaveLayer,
int *ArrayDim1, SC_View *pCurrentView, SC_View * LastView,
unsigned short *ViewTable, long int*ArraySize,
double **ViewMatrixArray);

347
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

struct coeffs { /* Temporary spline coefficients */


double c[3][4];
};

#define STD_CONIC 1
#define ARCFLAG 0
#define CIRCLEFLAG 1
#define _fchain_tol 2e-4 /* Chaining operation tolerance */

#endif

348
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/* ---------------------- CadlFunctions.cpp ------------------------------


* --------- Copyright (c) Surfware Inc. 1987 to 1997 --------------------
* --------------------- ALL RIGHTS RESERVED -----------------------------
* It is a violation of United States copyright laws to remove or alter
* this copyright notice without express written consent of Surfware Inc.
* -----------------------------------------------------------------------
*/

#include "stdafx.h"
#include "expfunc.h"
#include <types.h>
#include "CadlFunctions.h"

static void CdlLayer(HSC_DB *hDB,


unsigned int *nLayer);

static void AddLayer(HSC_DB *hDB,


unsigned int LayerNum,
char *LayerName);

/*------------------------------------------------------------------------------
/* Function: CheckCadl
/*
/* Action: Checks the validity of the CADL file and sets the layer
/*
/* Type: int
/*
/* Input: HSC_DB *hDb Database handle
/* unsigned int *color Input color from CADL
/* unsigned int *nLayer Input layer from CADL
/* unsigned short *nViewNum View number from CADL
/* unsigned int *CurrentLayer Current layer of SURFCAM
/*
/* Returns: 1 Success
/* 0 Too many views
/*
/*
/* Calls: CdlLayer
/*
/*----------------------------------------------------------------------------*/

int
CheckCadl(
HSC_DB *hDB,
unsigned int *nColor, /* Input color from CADL */
unsigned int *nLayer, /* Input layer from CADL */
unsigned short *nViewNum, /* View number from CADL */
unsigned int *CurrentLayer) /* Current layer of SURFCAM */
{
int Colormap[] = {0, 10, 12, 6, 14, 11, 13, 8, 9, 1, 2, 3, 4, 5, 7, 15};
/* Black, Green, Red, Brown, Yellow, Cyan, Magenta,
Dark Gray, Blue, Light Blue, Light Green,
Light Cyan, Light Red, Light Magenta, Light Gray, White */

if (*nLayer == 0)
*nLayer = *CurrentLayer;

CdlLayer(hDB, nLayer);

*nColor = Colormap[*nColor & 15];

if (*nViewNum > MAX_VIEW_NUM)


return(0);
else
return(1);
}

349
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/*------------------------------------------------------------------------------
/* Function: CdlLayer
/*
/* Action: Transforms coordinates using transformation matrix
/*
/* Type: void
/*
/* Input: HSC_DB *hDB Database handle
/* unsigned int *nLayer Input layer from CADL
/*
/* Returns: <None>
/*
/* Called by: CheckCadl
/*
/* Calls: scApp_LayerAlloc
/* AddLayer
/*
/*----------------------------------------------------------------------------*/
static void
CdlLayer(HSC_DB *hDB, unsigned int *nLayer)
{
char sBuffer[30];

int nLayerNum = *nLayer;

nLayerNum &= 255; /* Keep the layer within range */

if (! scApp_LayerAlloc(nLayerNum) ) /* If the layer is not allocated... */


{
sprintf(sBuffer,"CDL layer %d", *nLayer);
AddLayer(hDB, nLayerNum, sBuffer); /* ...call AddLayer function */
}

*nLayer = nLayerNum;

return;
}

/*------------------------------------------------------------------------------
/* Function: AddLayer
/*
/* Action: Adds a layer to the SURFCAM database
/*
/* Type: void
/*
/* Input: unsigned int nLayer Specified layer
/* char *layer_name Layer name
/*
/* Output: HSC_DB hDB Database handle
/*
/* Returns: <None>
/*
/* Called by: CdlLayer
/*
/* Calls: scLayer_AllocMem
/* scElement_SetLayerAttrib
/* scLayer_WriteToDB
/* scElement_Final
/*
/*----------------------------------------------------------------------------*/
static void
AddLayer(HSC_DB *hDB,
unsigned int nLayer,
char *sLayerName)
{
/* Allocate memory for layer */
SC_Layer * CurrentLayer = scLayer_AllocMem();

350
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/* Set layer number to the layer */


scElement_SetLayerAttrib(CurrentLayer, nLayer);

/* Set layer name to the layer struct */


strncpy(CurrentLayer->name, sLayerName, 30);
CurrentLayer->name[29] = '\0';

/* Write the layer into SURFCAM database */


scLayer_WriteToDB(*hDB, CurrentLayer);

/* Free the layer allocated in scLayer_AllocMem */


scElement_Final(CurrentLayer);

return;
}

/*------------------------------------------------------------------------------
/* Function: GetCadlView
/*
/* Action: Transforms coordinates using transformation matrix
/*
/* Type: int
/*
/* Input: unsigned short *nViewNum View number
/* SC_View *LastView Last view
/* unsigned short *ViewTable Pointer to view table
/*
/* Output: SC_View *pView Pointer to view
/*
/* Returns: 0 Success
/* ~0 Error code
/*
/*----------------------------------------------------------------------------*/
int
GetCadlView(SC_View *pView,
unsigned short *nViewNum,
SC_View *LastView,
unsigned short *ViewTable)
{
int rc = SUCCESS;
SC_View CurrentView;

*nViewNum = ViewTable[*nViewNum]; /* Input view translation */

if (LastView->view == 0 || *nViewNum != LastView->view)


{
if (*nViewNum == 0) /* Use cview */
/* Assign cview of SURFCAM to pCurrentView */
rc = scView_GetCview(&CurrentView);
else
/* Assign view with nViewNum to pCurrentView */
rc = scView_GetView(&CurrentView, *nViewNum);
if (rc == FAIL)
return(0);

/* Save last view for speed */


*LastView = CurrentView;
}

*pView = *LastView;

return(1);
}

351
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/*------------------------------------------------------------------------------
/* Function: CdlTransformViewWorld
/*
/* Action: Transforms coordinates using transformation matrix
/*
/* Type: int
/*
/* Input: SC_Point *Input Input point
/* SC_View *View View
/*
/* Output: SC_Point *Output Output point
/*
/* Returns: 0 Success
/* ~0 Error code
/*
/*----------------------------------------------------------------------------*/
int
CdlTransformViewWorld(SC_Point *Output,
SC_Point *Input,
SC_View *View)
{
SC_Point Temp = *Input; /* copy the point */

/* find pt. in world coodinates */


Output->x = Temp.x*View->view_mat[0][0] + Temp.y*View->view_mat[0][1] +
Temp.z*View->view_mat[0][2];
Output->y = Temp.x*View->view_mat[1][0] + Temp.y*View->view_mat[1][1] +
Temp.z*View->view_mat[1][2];
Output->z = Temp.x*View->view_mat[2][0] + Temp.y*View->view_mat[2][1] +
Temp.z*View->view_mat[2][2];

return SUCCESS;
}

/*------------------------------------------------------------------------------
/* Function: SetLayerColor
/*
/* Action: Sets the SURFCAM layer and the SURFCAM color of an element
/*
/* Type: void
/*
/* Input and
/* Output: SC_Element Element SURFCAM element
/*
/* Input: uint nColor SURFCAM color
/* uint nLayer SURFCAM layer
/*
/* Returns: <None>
/*
/*----------------------------------------------------------------------------*/
void
SetLayerColor(SC_Element Element, unsigned int * nColor, unsigned int * nLayer)
{
/* Sets the SURFCAM color for an element */
scElement_SetColorAttrib(Element, *nColor);

/* Sets the SURFCAM layer for an element */


scElement_SetLayerAttrib(Element, *nLayer);
}

352
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/*------------------------------------------------------------------------------
/* Function: GetCadlVm3dPoint
/*
/* Action: Retrieves a three-dimensional point from the coordinate array
/*
/* Type: void
/*
/* Input: double *ViewMatrixArray Array of coordinates
/* unsigned int i Number of points
/*
/* Output: SC_Point *Point Output point
/*
/* Returns: <None>
/*
/* Called by: read_cadl
/*
/*----------------------------------------------------------------------------*/
void
GetCdlVm3dPoint(double *ViewMatrixArray,
unsigned int i,
SC_Point *Point)
{
Point->x = ViewMatrixArray[i*3];
Point->y = ViewMatrixArray[i*3+1];
Point->z = ViewMatrixArray[i*3+2];
}

/*------------------------------------------------------------------------------
/* Function: GetCdlVm2dPoint
/*
/* Action: Retrieves a two-dimensional point from the coordinate array
/*
/* Type: void
/*
/* Input: double *ViewMatrixArray Array of coordinates
/* unsigned int i Number of points
/*
/* Output: SC_Point *Point Output point
/*
/* Returns: <None>
/*
/*----------------------------------------------------------------------------*/
void
GetCdlVm2dPoint(double *ViewMatrixArray,
unsigned int i,
SC_Point *Point)
{
Point->x = ViewMatrixArray[i*2];
Point->y = ViewMatrixArray[i*2+1];
Point->z = 0.0;

return;
}

/*------------------------------------------------------------------------------
/* Function: SetCdlVm3dPoint
/*
/* Action: Sets a three-dimensional point in the coordinate array
/*
/* Type: void
/*
/* Input: SC_Point *p Output point
/* unsigned int i Number of points
/*
/* Output: double *ViewMatrixArray Array of coordinates
/*
/* Returns: <None>
/*
/*----------------------------------------------------------------------------*/

353
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

void
SetCdlVm3dPoint(double *ViewMatrixArray,
unsigned int i,
SC_Point *Point,
long int *ArraySize)
{
if (*ArraySize < (int)(3*i+3))
{
*ArraySize = 3*i+3;
ViewMatrixArray = (double*)scMem_Realloc(ViewMatrixArray,
sizeof(double)*(*ArraySize));
};

ViewMatrixArray[i*3] = Point->x;
ViewMatrixArray[i*3+1] = Point->y;
ViewMatrixArray[i*3+2] = Point->z;

return;
}

/*------------------------------------------------------------------------------
/* Function: ReadCadlPolyline
/*
/* Action: Reads in a polyline from the CADL file
/*
/* Type: int
/*
/* Input: unsigned n Number of points
/* double*& ViewMatrixArray Array of coordinates
/* unsigned int * nColor Input color
/* unsigned int * nLayer Input layer
/* HSC_DB hDB Database handle
/*
/* Returns: 0 Success
/* ~0 Error code
/*
/* Calls: scPLine_AllocMem
/* scPLine_WriteToDB
/* scElement_Final
/* scMem_Free
/*
/*----------------------------------------------------------------------------*/
int
ReadCadlPolyline(HSC_DB * hDB,
unsigned n,
double * ViewMatrixArray,
unsigned int * nColor,
unsigned int * nLayer)
{
SC_Point Point;
unsigned i;

SC_PLine *PLine = scPline_AllocMem((unsigned short) n);

PLine->n = (unsigned short)n;

for (i = 0; i < n; i++)


{
GetCdlVm3dPoint(ViewMatrixArray, i, &Point);

(PLine->p_SC_Point)[i] = Point;
};

/* Set nColor and nLayer to polyline pointer */


SetLayerColor(PLine, nColor, nLayer);
scPline_WriteToDB(*hDB, PLine); /* Write polyline to database */
scElement_Final(PLine); /* Free scPLine allocated memory */

return SUCCESS;
}

354
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/* ----------------------- CadlFunctions.h -------------------------------


* --------- Copyright (c) Surfware Inc. 1987 to 1997 --------------------
* --------------------- ALL RIGHTS RESERVED -----------------------------
* It is a violation of United States copyright laws to remove or alter
* this copyright notice without express written consent of Surfware Inc.
* -----------------------------------------------------------------------
*/

#ifndef __CADLFUNCTIONS_H__
#define __CADLFUNCTIONS_H__

int CheckCadl(HSC_DB *hDB,


unsigned int *nColor,
unsigned int *nLayer,
unsigned short *nViewNum,
unsigned int *CurrentLayer);

int GetCadlView(SC_View *pView,


unsigned short *nViewNum,
SC_View *LastView,
unsigned short *ViewTable);

int CdlTransformViewWorld(SC_Point *Output,


SC_Point *Input,
SC_View *View);

void SetLayerColor(SC_Element Element,


unsigned int *nColor,
unsigned int *nLayer);

void SetCdlVm3dPoint(double *ViewMatrixArray,


unsigned int i,
SC_Point *Point,
long int *ArraySize);

void GetCdlVm3dPoint(double *ViewMatrixArray,


unsigned int i,
SC_Point *Point);

void GetCdlVm2dPoint(double *ViewMatrixArray,


unsigned int i,
SC_Point *Point);

int ReadCadlPolyline(HSC_DB * hDB,


unsigned n,
double * ViewMatrixArray,
unsigned int * nColor,
unsigned int * nLayer);

#endif

355
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Part II

356
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

357
Chapter 7 Introduction to the Listbox Dialog SURFCAM 2005 • API Documentation

Chapter 7
Introduction to the
SURFCAM Listbox
dialog API
The translators that ship with SURFCAM 2005 use a common listbox dialog to
communicate with the user during the translation process. The ability to utilize
this listbox dialog in custom applications is available through the SURFCAM
listbox dialog API, described in this documentation. Note that this listbox dialog
is derived from Microsoft’s Foundation Class library (MFC) Version 4.2, so any
development environment using the SURFCAM listbox dialog must support this
library.

SURFCAM LISTBOX LAYOUT


The SURFCAM listbox dialog has three main components. The top windows are
for text output, and the buttons at the bottom are for user input. The top window
is the copyright listbox; this listbox is used to display the name of the DLL that is
being run and the associated copyright information.

The second component is the middle listbox, which comprises the primary output
area of the dialog. The contents of the listbox may be continually updated during
the translation process.

The third component of the dialog is the row of buttons at the bottom of the
dialog. These buttons allow the user to save the contents of the listboxes to a file,
print them, or close the window. During the translation process, the translation
may be canceled as well.

358
SURFCAM 2005 • API Documentation Chapter 7 Introduction to the Listbox Dialog

FIGURE 7.1 LAYOUT OF THE SURFCAM LISTBOX DIALOG

CREATING THE LISTBOX DIALOG


The listbox dialog is created in two steps: first the dialog variable is declared, then
the listbox is initialized. The variable is declared as a type “listbox”. A sample
declaration would be:

static listbox MyListbox;

The dialog is a child window, and must therefore have a parent window. The
listbox dialog is associated with a parent window in the initialization process.
The InitListBox function initializes and displays the dialog to the screen.

InitListBox(MyListbox, (CWnd *) ParentWindow));

359
Chapter 7 Introduction to the Listbox Dialog SURFCAM 2005 • API Documentation

WRITING TEXT TO THE DIALOG


Once the dialog is initialized, text may be written to the listboxes. Text may be
written to either the upper (“copyright”) listbox or the lower primary listbox. The
function that performs the text output is lb_printf. The arguments are parallel to
the C function printf.

There is a second, more specialized function that writes text to the primary output
listbox. The put_end_message function takes a beginning string, an end string,
and a “success” flag. If the “success” flag is true, then put_end_message writes
the beginning string, the string “Successful”, and then the end string to the main
output listbox. If the “success” flag indicates failure, then put_end_message
writes the beginning string, the string “Unsuccessful”, and then the end string to
the main output listbox.

COMPLETING THE DIALOG


Once all the text has been written to the dialog, use the WaitForEnd function to
put the dialog into a modal loop. The program will not proceed until the Close
button is selected.

COMPILING AND LINKING CONSIDERATIONS


The header file “list_io.h” must be included in every file that uses the Listbox
Dialog API functions, and the file must be in the include path for the compiler.
The linker must also link to the dll_io.lib export library.

360
SURFCAM 2005 • API Documentation Chapter 8 Listbox Dialog Function Descriptions

Chapter 8
Listbox Dialog API
Function Descriptions

361
Chapter 8 Listbox Dialog Function Descriptions SURFCAM 2005 • API Documentation

FinalListBox

PROTOTYPE: void FinalListBox(listbox &Listbox)

ACTION: Destroys the listbox and frees the memory associated with the
listbox.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENT: listbox &Listbox Reference to the listbox dialog

362
SURFCAM 2005 • API Documentation Chapter 8 Listbox Dialog Function Descriptions

GetAbortStatus

PROTOTYPE: int GetAbortStatus(listbox &Listbox)

ACTION: Returns the abort status of the listbox dialog, checking to see if
the user has pressed the Cancel button.

FUNCTION RETURN TYPE: int

RETURNS: FALSE Cancel has not been pressed


TRUE Cancel has been pressed

INPUT ARGUMENT: listbox &Listbox Reference to the listbox dialog

363
Chapter 8 Listbox Dialog Function Descriptions SURFCAM 2005 • API Documentation

InitListBox

PROTOTYPE: void InitListBox(listbox &Listbox, CWnd *Parent )

ACTION: Initializes the listbox dialog, associating the dialog with an existing
parent window. The listbox is initialized with only the Cancel
button enabled.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: listbox &Listbox Reference to an existing


listbox dialog to be initialized.

CWnd *Parent Pointer to the parent window to


which the dialog will be
associated.

364
SURFCAM 2005 • API Documentation Chapter 8 Listbox Dialog Function Descriptions

lb_printf

PROTOTYPE: void lb_printf(listbox &Listbox, int iType, char *format, ...)

ACTION: Prints a string to the dialog listboxes. This function is similar to


the printf statement in the C runtime library. By specifying the
intended output listbox (the copyright listbox or the main listbox),
the function will print the string appropriately. The string may
either be appended to the contents of the main listbox or may
replace the contents entirely.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: listbox &Listbox Reference to the listbox dialog


int iType Reference of output listbox
COPYRIGHT_LISTBOX String written to copyright listbox
NEWLINE_LISTBOX String appended in output listbox
FEEDBACK_LISTBOX String replaces output listbox contents

char * format, ... printf character string

365
Chapter 8 Listbox Dialog Function Descriptions SURFCAM 2005 • API Documentation

put_end_message

PROTOTYPE: void put_end_message(listbox &Listbox, int rc, char *Start,char


*End )

ACTION: Prints a message to the main output listbox indicating success or


failure. This message consists of a “Successful” or
“Unsuccessful” character string appended to the Start character
string passed to the function. The appended string is dependent
upon the value of rc passed to the function; a value of SUCCESS
results in the “Successful” string being appended. The End
character string is typically the name of the file being processed,
and is appended at the end of the final string. Note that either
Start or End may be NULL.

FUNCTION RETURN TYPE: void

RETURNS: <None>

INPUT ARGUMENTS: listbox &Listbox Reference to the listbox dialog

int rc Success/Fail flag


SUCCESS Appends “Succesful” to printed string
FAIL Appends “Unsuccesful” to printed string

char * Start Beginning of string to be printed

char * End End of string to be printed

366
SURFCAM 2005 • API Documentation Chapter 8 Listbox Dialog Function Descriptions

SetListBoxButtons

PROTOTYPE: void SetListBoxButtons(listbox &Listbox, BOOL bState)

ACTION: Toggles the state of the listbox buttons. The three buttons Save,
Print, and Close are enabled and the Cancel button is disabled
when bState is TRUE. The three buttons Save, Print, and Close
are disabled and the Cancel button is enabled when bState is
FALSE.

FUNCTION RETURN TYPE: void

RETURN: <None>

INPUT ARGUMENTS: listbox &Listbox Refence to the listbox dialog


BOOL bState Activation state

367
Chapter 8 Listbox Dialog Function Descriptions SURFCAM 2005 • API Documentation

WaitForEnd

PROTOTYPE: void WaitForEnd(listbox &Listbox)

ACTION: Displays dialog modally until the user selects the Close button.
The Cancel button is the only button disabled.

FUNCTION RETURN TYPE: void

RETURNS: <None>

INPUT ARGUMENTS: listbox &Listbox Reference to the listbox dialog

368
SURFCAM 2005 • API Documentation Chapter 8 Listbox Dialog Function Descriptions

Part III

369
Chapter 8 Listbox Dialog Function Descriptions SURFCAM 2005 • API Documentation

370
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

SURFCAM Tool Library


Technical Documentation

Copyright 2005 SURFWARE INC.


All Rights Reserved

371
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

372
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

SURFCAM Tool Library -Introduction .....................................................................................................................313


Tool Library Structures..............................................................................................................................................314
TOOLLIBS.H SYMBOLIC CONSTANTS ........................................................................................................ 314
TOOLLIBS.H STRUCTURES ........................................................................................................................ 316
Tool Design File Data Structure............................................................................................................. 316
Mill Tool Data Structure......................................................................................................................... 316
Lathe Tool Data Structure ...................................................................................................................... 318
Cutter Data Structure ............................................................................................................................. 319
Material Data Structure.......................................................................................................................... 320
Mill Tool API ............................................................................................................................................................321
CHOOSING A MILL TOOL: TOOLLIB_NGETMILLTOOL FUNCTION ................................................................ 321
LOADING A MILL TOOL: TOOLLIB_NLOADMILL FUNCTION ......................................................................... 321
Drill Tool API............................................................................................................................................................322
CHOOSING A DRILL TOOL: TOOLLIB_NGETDRILLTOOL FUNCTION .............................................................. 322
LOADING A DRILL TOOL: TOOLLIB_NLOADDRILLTOOL FUNCTION ............................................................. 322
Lathe Tool API ..........................................................................................................................................................323
CHOOSING A LATHE TOOL: TOOLLIB_NGETLATHETOOL FUNCTION............................................................ 323
LOADING A LATHE TOOL: TOOLLIB_NLOADLATHETOOL FUNCTION ........................................................... 323
Lathe Drill Tool API..................................................................................................................................................324
CHOOSING A LATHE DRILL TOOL: TOOLLIB_NGETLDRILLTOOL FUNCTION ................................................ 324
LOADING A LATHE DRILL TOOL: TOOLLIB_NLOADLDRILLTOOL FUNCTION ............................................... 324
Digitizer Tool API .....................................................................................................................................................325
CHOOSING A DIGITIZER TOOL: TOOLLIB_NGETDGTZTOOL FUNCTION ........................................................ 325
LOADING A DIGITIZER TOOL: TOOLLIB_NLOADDGTZTOOL FUNCTION ........................................................ 325
EDM Tool API ..........................................................................................................................................................326
CHOOSING A EDM TOOL: TOOLLIB_NGETEDMTOOL FUNCTION ................................................................. 326
LOADING A EDM TOOL: TOOLLIB_NLOADEDMTOOL FUNCTION ................................................................ 326
Tool API Additional Functions..................................................................................................................................327
CHOOSING A TOOL BY TYPE: TOOLLIB_NGETTOOL FUNCTION ................................................................... 327
LOADING A TOOL BY TYPE: TOOLLIB_NLOADTOOL FUNCTION .................................................................. 327
CHOOSING A MATERIAL: TOOLLIB_NGETMATERIAL FUNCTION .................................................................. 328
LOADING A MATERIAL: TOOLLIB_NLOADMATERIAL FUNCTION .................................................................. 328
GETTING CURRENT TOOL UNITS TYPE: TOOLLIB_NGETTOOLUNITS FUNCTION .......................................... 329
Setting New Tool Units Type: ToolLib_nSetToolUnits function ..............................................................................329

Sample Code ..............................................................................................................................................................329

373
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

374
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

SURFCAM Tool Library -Introduction

The purpose of the SURFCAM Tool Library DLL (TOOLLIB.DLL) is to provide a user replaceable module and
application programmable interface (API) to choose, load and optionally manage the SURFCAM tool and material
database. This document is intended as a reference for programmers who would be responsible for writing a
replacement for the tool library DLL. It also is intended as a reference for 3rd party applications that may need to
interface with the tool and material library and use the DLL.

The initial implementation of the SURFCAM Tool Library is written in C++ using the Microsoft Foundation
Class Library using ODBC classes to connect to the tool and material databases. The API consists of a C typed
structure that contains tool information which is able to be used by SURFCAM, and C functions which allow the
operator to select from a list of tools or load a specified tool from the library. Since these functions use a C calling
convention, and structure definitions are provided in C style header files, this module is most easily replaced with or
used by another written in C/C++. You are free to choose any other language or development tool to replace the tool
library DLL, but then interfacing correctly with SURFCAM may be more difficult, and support for any problems you
encounter may not be able to be provided.

The layout of this document is first to describe the tool data structures. Then the API functions for each type of
tool is presented. Finally, a few additional functions to complete the API are presented.

375
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Tool Library Structures


The definitions of tool library structures are provided in the file TOOLLIBS.H. This file also defines symbolic
constants that represent parameters and values for the tool information, and is included by TOOLAPI.H.
TOOLAPI.H provides the function prototypes for the tool library API. These two header files describe the tool
library interface and in most cases should not be changed. This information is intended to supplement source code
comments, which in most cases should be sufficient to understand the usage of structures’ member variables, so you
may wish to skip this section and refer to the header files instead.

TOOLLIBS.H Symbolic Constants

The following symbols appear in TOOLLIBS.H, each is followed by a description of its purpose.

#define MAX_NAME_SIZE 260 // Maximum Tool Drawing File Name


This is the maximum length of a string used to contain a tool drawing file name. Generally, this is large enough to
hold the longest allowed file name, which is specific to the operating system.

#define MAX_NUMBER_DRAWINGS 5 // Maximum Tool Drawings


This is the maximum allowed number of tool drawing files. Most tools in the default tool database are represented
with two files -the first for the tool and the other for the holder. You may use up to 3 additional drawings to represent
the tool.

#define MAX_TOOL_DESC 40 // Maximum Tool Description Info


This is the maximum length of a string used to describe a tool.

// Tool Types
#define TL_TYPE_MILL 0 // Mill Tools
#define TL_TYPE_DRILL 1 // Drill Tools
#define TL_TYPE_LATHE 2 // Lathe Tools
#define TL_TYPE_LDRILL 3 // Lathe Drill Tools
#define TL_TYPE_DIGITIZE 4 // Digitizer Tools
#define TL_TYPE_EDM 5 // EDM Tools
#define TL_NUM_TYPES 6 // number of tool types
These symbols are for the various Tool Types supported in SURFCAM. The tool data structure tl_cutter_struct
member “type” should contain one of these values, depending upon the type of tool choosed or loaded from the
database. This is usually determined from which API function is called.

// Mill Tool Classes


#define TL_MILL_CLASS_BALLNOSE 0 // Mill Ballnose
#define TL_MILL_CLASS_ENDMILL 1 // Mill End Mill
#define TL_MILL_CLASS_BULLNOSE 2 // Mill Bullnose
#define TL_MILL_CLASS_TEARDROP 3 // Mill Teardrop
#define TL_MILL_CLASS_KEY 4 // Mill Key
#define TL_MILL_CLASS_FACE 5 // Mill Carbide Face
#define TL_MILL_CLASS_TAPER 6 // Mill Tapered
These symbols are for the various classes of mill tools supported in SURFCAM. The tool class is not currently
stored in the cutter structure.

376
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

// Drill Tool Classes


#define TL_DRILL_CLASS_CENTER 0 // Drill Center
#define TL_DRILL_CLASS_DRILL 1 // Drill Drill
#define TL_DRILL_CLASS_TAP 2 // Drill Tap
#define TL_DRILL_CLASS_REAMER 3 // Drill Reamer
#define TL_DRILL_CLASS_BORE 4 // Drill Boring Head
These symbols are for the various classes of drill tools supported in SURFCAM. The tool class is not currently
stored in the cutter structure.

// Lathe Tool Classes


#define TL_LATHE_CLASS_TURN 0 // Lathe Face/Turn
#define TL_LATHE_CLASS_ROUND 1 // Lathe Face/Turn Round
#define TL_LATHE_CLASS_TRIANGLE 2 // Lathe Face/Turn Triangle
#define TL_LATHE_CLASS_THREAD 3 // Lathe Thread
#define TL_LATHE_CLASS_GROOVE 4 // Lathe Groove
These symbols are for the various classes of lathe tools supported in SURFCAM. The tool class is not currently
stored in the cutter structure.

// Tool Coolant Flags


#define TL_COOLANT_OFF 0 // Coolant Off
#define TL_COOLANT_FLOOD 1 // Coolant Flood
#define TL_COOLANT_MIST 2 // Coolant Mist
These symbols are for the various coolant types supported in SURFCAM. The tool data structure tl_cutter_struct
member “coolant” should contain one of these values

// Tool Program Flags -Tip or Center


#define TL_PROGRAM_TO_TIP 0 // Tool Tip
#define TL_PROGRAM_TO_CENTER 1 // Tool Center
These symbols are for the tool data structure tl_cutter_struct member “tip”. This indicates whether the tool is
programmed from the tool tip, or the tool center.

// tl_cutter_struct.cutter_flags
#define TL_FLAGS_GROOVE 1 // Groove
These symbols are for the tool data structure tl_cutter_struct member cutter_flags.

// Tool Tip Orientation -Tip Offset Direction


#define TL_LATHE_FACE 0
#define TL_LATHE_OD_TURN 1
#define TL_LATHE_OD_GROOVE 2
#define TL_LATHE_OD_BACK_TURN 3
#define TL_LATHE_BACK_FACE 4
#define TL_LATHE_ID_BACK_TURN 5
#define TL_LATHE_ID_GROOVE 6
#define TL_LATHE_ID_TURN 7
These symbols are for the lathe tool data structure tl_lathe_struct “orient” and “operation” members -orient for the
tool orientation and operation is for the tool default lathe operation type.

377
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

TOOLLIBS.H Structures

Tool Design File Data Structure


This structure type holds data for a tool drawing file:

typedef struct tl_tool_dsn_struct


{
char filename[MAX_NAME_SIZE+1];
int spin;
} tl_tool_dsn_type;

char filename The name of the file which contains the tool drawing.

int spin TRUE if the tool is to spin while displayed. FALSE if the tool is not to spin.

Mill Tool Data Structure


This structure contains data for most types of tools — mill, drill, digitizer, and edm tools share this same structure.

typedef struct tl_mill_struct


{
double ctipr; // tip radius
double ctotr; // total radius
double cdifr; // difference radius
double ctipoff; // ctipr + distance away from surface
double shank_radius; // shank radius (initial power for edm)
double flute_height; // flute height (power setting for edm)
double total_height; // total height (spark gap for edm)
double taper_angle; // taper angle
double tip_angle; // tip angle
int flutes; // number flutes (Wire feed for EDM)
int scallop; // scallop or increment
double scallop_height; // scallop height/increment value
} tl_mill_type;

double ctipr The tool Tip Radius. Also, this may be called the tool Corner Radius.

double ctotr The tool Total Radius. This should be larger than the tip radius. For edm tools, this is the radius of
the wire.

double cdifr The calculated difference between the total radius and the tip radius.

double ctipoff The calculated tip offset, which is equal to the sum of the tip radius and the amount of material
to leave (distance from the surface).

double shank_radius The radius of the shank of the tool for mill, drill, or digitizer tools. For edm tools this
member holds the initial power setting.

double flute_height The height of the tool flutes. For edm tools this member holds the power setting.

double taper_angle The angle between the edge of the tool and the axis of rotation.

378
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

double tip_angle The tip or included angle for a drill tool.

int flutes The number of flutes on the tool.

int scallop TRUE/FALSE indicates scallop or increment.

double scallop_height The scallop height or increment value. Interpretation depends upon the value of the member
scallop above.

In general, data which may not be used for a specific tool type can be safely initialized to zero.

379
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Lathe Tool Data Structure


This structure contains data for lathe tools.

typedef struct tl_lathe_struct


{
double ctipr; // tip radius
double width; // width, interior circle
double angle1; // back angle of tip
double angle2; // front angle of tip
double cangle; // clearance angle from cutting edge
int orient; // tool tip orientation number
int operation; // default operation: od,od back,id back,id
int nsides; // number of sides on insert
int upr; // units per revolution vs. u per min
int dummy; // used to be turret
double rough_cut; // default rough depth of cut
double finish_cut; // default finish depth of cut
double clearance_y; // default clearance in y
} tl_lathe_type;

double ctipr The tip or nose radius of the lathe tool.

double width The width or interior circle of the lathe tool.

double angle1 The front angle.

double angle2 The back angle.

double cangle The clearance angle.

int orient The tool orientation.

int operation The default operation type for the tool.

int nsides The number of sides on insert.

int upr The units per revolution.

int dummy Kept to maintain compatibility with old data structure, this used to be the turret number.

double rough_cut The depth for rough cut.

double finish_cut The depth for finish cut.

double clearance_y The clearance_y.

380
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Cutter Data Structure


This structure contains data for the tool. It contains the information common to all tool types and the information
specific to mill or lathe tools. The cutter data structure is filled in by the tool library API functions and then used by
SURFCAM.

typedef struct tl_cutter_struct


{
int type; // tool type
int ref_number; // tool reference number
char tool_desc[MAX_TOOL_DESC +1]; // tool description
int tool_number; // program tool number
int height_offset; // program height offset number
int dia_offset; // program diameter offset number
int coolant; // default coolant type
int tip; // tip or center programming
int material; // tool material
double tolerance; // default cutting tolerance
double clearance; // default clearance
double chip_load; // default chip load

int cutter_flags; // cutter flags


union // cutter information
{
tl_mill_type mill;
tl_mill_type drill;
tl_mill_type edm;
tl_lathe_type lathe;
} cutter;

int num_drawings; // tool drawings


tl_tool_dsn_type drawings[MAX_NUMBER_DRAWINGS];
} tl_cutter_type;

int type The tool type. This is to be filled in with one of the predefined tool type symbol/values provided
above. It should match the type requested by the API function called.

int ref_number The tool reference number. This is used to lookup the tool by number in the load functions.

char tool_desc The textual description of the tool. This is used currently in the tool list box for the user to select
from the list of available tools.

int tool_number The program tool number.

int height_offset The program height offset number.

int dia_offset The program diameter offset number.

int coolant The default coolant for the tool.

int tip TRUE/FALSE tool is programmed to the tip or center.

int material The tool material library reference number.

double tolerance The default cutting tolerance.

381
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

double clearance The default surface clearance.

double chip_load The default chip load.

int cutter_flags One of above cutter flag symbol/values.

union cutter Tool specific information.

int num_drawings Number of tool drawing files. Usually two -one for the tool, one for the holder.

tl_tool_dsn_type drawings Name and spin for the tool drawing file. At most 5 of these.

Material Data Structure


This structure contains data relating the tool cutting speed and chip load factor to the material being machined. This
structure is filled in by the material library functions and then used by SURFCAM.

typedef struct tl_material_struct


{
int refnum; // material reference number
char desc[40]; // material description
double sfm; // surface cutting speed (SFM)
double chplfactor; // tool chip load multiplier
} tl_material_type;

int ref_num The material reference number. This is used to lookup the tool by number in the load functions.

char desc The material description. This is used in the Get material dialog box.

double sfm The material surface speed. This is selected from the material table depending upon the currently
selected tool material.

double chplfactor The material chip load factor. This is also selected from the material table depending upon the
currently selected tool material.

382
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Mill Tool API

Choosing A Mill Tool: ToolLib_nGetMillTool function


Displays a modal dialog box with a list of available mill tools. This function is to provide a user interface to choose
the mill tool and should not return until one is selected, or the dialog box is canceled.

Declaration:
extern “C” long ToolLib_nGetMillTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE mill tool is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_MILL and fill in the general tool information and the cutter mill union.

Loading a Mill Tool: ToolLib_nLoadMill function


Loads the mill tool specified by reference number from the tool library. This does not provide any user interface,
except perhaps to report an error condition.

Declaration:
extern “C” long ToolLib_nLoadMillTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The tool reference number of the requested mill tool.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE mill tool cutter information is provided.
FALSE no cutter information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_MILL and fill in the general tool information and the cutter mill union.

383
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Drill Tool API

Choosing a Drill Tool: ToolLib_nGetDrillTool function


Displays a modal dialog box with a list of available drill tools. This function is to provide a user interface to choose
the drill tool and should not return until one is selected, or the dialog box is canceled.

Declaration:
extern “C” long ToolLib_nGetDrillTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE drill tool is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_DRILL and fill in the general tool information and the cutter drill union.

Loading a Drill Tool: ToolLib_nLoadDrillTool function


Loads the drill tool specified by reference number from the tool library. This does not provide any user interface,
except perhaps to report an error condition.

Declaration:
extern “C” long ToolLib_nLoadDrillTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The tool reference number of the requested drill tool.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE drill tool cutter information is provided.
FALSE no cutter information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_DRILL and fill in the general tool information and the cutter drill union.

384
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Lathe Tool API

Choosing a Lathe Tool: ToolLib_nGetLatheTool function


Displays a modal dialog box with a list of available lathe tools. This function is to provide a user interface to choose
the lathe tool and should not return until one is selected, or the dialog box is canceled.

Declaration:
extern “C” long ToolLib_nGetLatheTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE lathe tool is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_LATHE and fill in the general tool information and the cutter lathe union.

Loading a Lathe Tool: ToolLib_nLoadLatheTool function


Loads the lathe tool specified by reference number from the tool library. This does not provide any user interface,
except perhaps to report an error condition.

Declaration:
extern “C” long ToolLib_nLoadLatheTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The tool reference number of the requested lathe tool.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE lathe tool cutter information is provided.
FALSE no cutter information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_LATHE and fill in the general tool information and the cutter lathe union.

385
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Lathe Drill Tool API

Choosing a Lathe Drill Tool: ToolLib_nGetLDrillTool function


Displays a modal dialog box with a list of available lathe drill tools. This function is to provide a user interface to
choose the lathe drill tool and should not return until one is selected, or the dialog box is canceled.

Declaration:
extern “C” long ToolLib_nGetLDrillTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE lathe drill tool is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_LDRILL and fill in the general tool information and the cutter drill union.

Loading a Lathe Drill Tool: ToolLib_nLoadLDrillTool function


Loads the lathe drill tool specified by reference number from the tool library. This does not provide any user
interface, except perhaps to report an error condition.

Declaration:
extern “C” long ToolLib_nLoadLDrillTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The tool reference number of the requested lathe drill tool.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE lathe drill tool cutter information is provided.
FALSE no cutter information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_LDRILL and fill in the general tool information and the cutter drill union.

386
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Digitizer Tool API

Choosing a Digitizer Tool: ToolLib_nGetDgtzTool function


Displays a modal dialog box with a list of available digitizers. This function is to provide a user interface to choose
the digitizer and should not return until one is selected, or the dialog box is canceled. A digitizer is treated as a mill
tool and this function fills the mill cutter union.

Declaration:
extern “C” long ToolLib_nGetDgtzTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM. INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE digitizer is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_DIGITIZE and fill in the general tool information and the cutter mill union.

Loading a Digitizer Tool: ToolLib_nLoadDgtzTool function


Loads the digitizer specified by reference number from the tool library. This does not provide any user interface,
except perhaps to report an error condition. A digitizer is treated as a mill tool and this function fills the mill cutter
union.

Declaration:
extern “C” long ToolLib_nLoadDgtzTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
long nToolRef The tool reference number of the requested digitizer.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE digitizer information is provided.
FALSE no information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_DIGITIZE and fill in the general tool information and the cutter mill union.

387
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

EDM Tool API

Choosing a EDM Tool: ToolLib_nGetEdmTool function


Displays a modal dialog box with a list of available Edm tools. This function is to provide a user interface to choose
the Edm tool and should not return until one is selected, or the dialog box is canceled.

Declaration:
extern “C” long ToolLib_nGetEdmTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE edm tool is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_EDM and fill in the general tool information and the cutter edm union.

Loading a EDM Tool: ToolLib_nLoadEdmTool function


Loads the edm tool specified by reference number from the tool library. This does not provide any user interface,
except perhaps to report an error condition.

Declaration:
extern “C” long ToolLib_nLoadEdmTool(long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolRef The tool reference number of the requested edm tool.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE edm tool cutter information is provided.
FALSE no cutter information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
TL_TYPE_EDM and fill in the general tool information and the cutter edm union.

388
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Tool API Additional Functions

Choosing a Tool By Type: ToolLib_nGetTool function


This function is called as a utility function to choose a tool of the specified type. The default implementation is to
call one of the above get tool API functions depending upon the tool type. This function is to provide a user interface
to choose the mill tool and should not return until one is selected, or the dialog box is canceled.

Declaration:
extern “C” long ToolLib_nGetTool(long nToolType, long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolType The type of tool to be selected.
long nToolRef The reference number of the tool to display as the current selection. This is usually the last
tool selected, or at start is configured from SURFCAM.INI.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE tool is chosen and cutter information is provided.
FALSE no tool selected, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
nToolType and fill in the general tool information and the appropriate cutter union data.

Loading a Tool By Type: ToolLib_nLoadTool function


This function is called as a utility function to load a tool of the specified type. The default implementation is to call
one of the above load tool API functions depending upon the tool type. This does not provide any user interface,
except perhaps to report an error condition.

Declaration:
extern “C” long ToolLib_nLoadTool(long nToolType, long nToolRef, tl_cutter_type *tl_cutter);

Parameters:
long nToolType The type of tool to be selected.
long nToolRef The tool reference number of the requested tool.
tl_cutter_type *tl_cutter A pointer to the cutter data structure which is to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE tool cutter information is provided.
FALSE no cutter information found for the requested tool, or error occured.

Comments:
SURFCAM provides the address of an existing cutter structure to be filled in when calling this function. It
does not need to allocate the structure or free it if an error occurs. This should set the tool type to
nToolType and fill in the general tool information and the appropriate cutter union data.

389
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Choosing a Material: ToolLib_nGetMaterial function


This function is called to allow the user to select the material being machined. It is to display a dialog box with a list
of materials for the user to make the selection. Upon selection the material structure is filled with the selected
material reference number, description, SFM, and CLF for the tool material type.

Declaration:
extern long ToolLib_nGetMaterial(long nType, long nMaterialRef, tl_material_type *tl_material);

Parameters:
long nType This is the tool material type for the currently selected tool. This is used to select the
appropriate SFM and CLF from the selected material.
long nMaterialRefThe reference number of the material to display as the current selection. This is usually
the last material selected, or at start is configured from SURFCAM.INI.
tl_material_type *tl_material A Pointer to the material data structure to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE material information is provided.
FALSE no material selected, user canceled, or error occured.

Comments:
SURFCAM provides the address of an existing material structure to be filled in when calling this function.
It does not need to allocate the structure or free it if an error occurs. This should fill in the material
information for the specified tool material type.

Loading a Material: ToolLib_nLoadMaterial function


This function is to load the specified material by reference number into the material data structure. This function
does not display any user interface, except perhaps to indicate an error condition.

Declaration:
extern long ToolLib_nLoadMaterial(long nType, long nMaterialRef, tl_material_type *tl_material);

Parameters:
long nType This is the tool material type for the currently selected tool. This is used to selecte the
appropriate SFM and CLF from the requested material.
long nMaterialRefThis is the reference number for the material requested.
tl_material_type *tl_material A Pointer to the material data structure to be filled in upon returning the
value of TRUE from this function.

Return Values:
TRUE material information is provided.
FALSE no material information found for the requested material, or error occured.

Comments:
SURFCAM provides the address of an existing material structure to be filled in when calling this function.
It does not need to allocate the structure or free it if an error occurs. This should fill in the material
information for the specified tool material type.

390
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

Getting Current Tool Units Type: ToolLib_nGetToolUnits function


This function is called to retrieve the current tool units type.

Declaration:
extern “C” long ToolLib_nGetToolUnits(void);

Return Values:
The function returns one of the following values of the symbols declared in ToolAPI.h:
TOOLLIB_UNITS_US
TOOLLIB_UNITS_METRIC

Setting New Tool Units Type: ToolLib_nSetToolUnits function


This function is called to select a new tool units type.

Declaration:
extern “C” long ToolLib_nSetToolUnits(long nUnits);

Parameters:
long nUnits The new unit type requested. This should be one of the values for the unit symbols defined in
ToolAPI.h.

Return Values:
TRUE if units type changed successfully.
FALSE units not changed (invalid unit type specified).

Comments:
SURFCAM calls ToolLib_nSetToolUnits() when the user changes units in the options menu. In the current
implementation, the database contains US and Metric tools, and only tools of the requested unit type are
displayed for selection by the user. An alternative method might be converting the parameters to the current
units for the selected tool when the cutter structure is filled in and returned from the Get or Load functions.

391
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

Sample Code
// ToolLib.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include "ToolLib.h"
#include "ToolAPI.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// CToolLibApp
BEGIN_MESSAGE_MAP(CToolLibApp, CWinApp)
//{{AFX_MSG_MAP(CToolLibApp)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CToolLibApp construction
CToolLibApp::CToolLibApp()
{
m_nToolUnits =TOOLLIB_UNITS_US;
} // CToolLibApp

/////////////////////////////////////////////////////////////////////////////
// The one and only CToolLibApp object
CToolLibApp theApp;

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetMillTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: User Selects Tool

return(FALSE); // Failure
} // ToolLib_nGetMillTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadMillTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Load Referenced Tool -No User Interaction.

return(FALSE); // Failure
} // ToolLib_nLoadMillTool

392
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetDrillTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: User Selects Tool

return(FALSE); // Failure
} // ToolLib_nGetDrillTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadDrillTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Load Referenced Tool -No User Interaction.

return(FALSE); // Failure
} // ToolLib_nLoadDrillTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetLatheTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: User Selects Tool

return(FALSE); // Failure
} // ToolLib_nGetLatheTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadLatheTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Load Referenced Tool -No User Interaction.
return(FALSE); // Failure
} // ToolLib_nLoadLatheTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetLDrillTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: User Selects Tool
return(FALSE); // Failure
} // ToolLib_nGetLDrillTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadLDrillTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Load Referenced Tool -No User Interaction.

return(FALSE); // Failure
} // ToolLib_nLoadLDrillTool

393
Chapter 6 Sample Code SURFCAM 2005 • API Documentation

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetDgtzTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: User Selects Tool

return(FALSE); // Failure
} // ToolLib_nGetDgtzTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadDgtzTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Load Referenced Tool -No User Interaction.

return(FALSE); // Failure
} // ToolLib_nLoadDgtzTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetEdmTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: User Selects Tool

return(FALSE); // Failure
} // ToolLib_nGetEdmTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadEdmTool(long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Load Referenced Tool -No User Interaction.

return(FALSE); // Failure
} // ToolLib_nLoadEdmTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetTool(long nToolType, long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Use or replace this -Its used as helper to call one of the above.
long nRes =FALSE; // Nothing Gotten

switch (nToolType)
{
case TL_TYPE_MILL:
nRes =ToolLib_nGetMillTool(nToolRef, tl_cutter); break;
case TL_TYPE_DRILL:
nRes =ToolLib_nGetDrillTool(nToolRef, tl_cutter); break;
case TL_TYPE_LATHE:
nRes =ToolLib_nGetLatheTool(nToolRef, tl_cutter); break;
case TL_TYPE_LDRILL:
nRes =ToolLib_nGetLDrillTool(nToolRef, tl_cutter); break;
case TL_TYPE_DIGITIZE:
nRes =ToolLib_nGetDgtzTool(nToolRef, tl_cutter); break;
case TL_TYPE_EDM:
nRes =ToolLib_nGetEdmTool(nToolRef, tl_cutter); break;
default: // Something Errory
TRACE0("ToolLib Error: Bad Tool Type Requested!\n");
break;
} // switch on nToolType

return(nRes);
} // ToolLib_nGetTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadTool(long nToolType, long nToolRef, tl_cutter_type *tl_cutter)
{
// TODO: Use or replace this -Its used as helper to call one of the above.
long nRes =FALSE; // Nothing Loaded

switch (nToolType)
{
case TL_TYPE_MILL:
nRes =ToolLib_nLoadMillTool(nToolRef, tl_cutter); break;
case TL_TYPE_DRILL:
nRes =ToolLib_nLoadDrillTool(nToolRef, tl_cutter); break;

394
SURFCAM 2005 • API Documentation Chapter 6 Sample Code

case TL_TYPE_LATHE:
nRes =ToolLib_nLoadLatheTool(nToolRef, tl_cutter); break;
case TL_TYPE_LDRILL:
nRes =ToolLib_nLoadLDrillTool(nToolRef, tl_cutter); break;
case TL_TYPE_DIGITIZE:
nRes =ToolLib_nLoadDgtzTool(nToolRef, tl_cutter); break;
case TL_TYPE_EDM:
nRes =ToolLib_nLoadEdmTool(nToolRef, tl_cutter); break;
default: // Something Errory
TRACE0("ToolLib Error: Bad Tool Type Requested!\n");
break;
} // switch on nToolType

return(nRes);
} // ToolLib_nLoadTool

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetMaterial(long nType, long nMaterialRef, tl_material_type
*tl_material)
{

return(FALSE); // Failure
} // ToolLib_nGetMaterial

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nLoadMaterial(long nType, long nMaterialRef, tl_material_type
*tl_material)
{

return(FALSE); // Failure
} // ToolLib_nLoadMaterial

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nGetToolUnits(void)
{
// Simple Access to current units type
return(theApp.m_nToolUnits);
} // ToolLib_nGetToolUnits

/////////////////////////////////////////////////////////////////////////////
extern "C" long ToolLib_nSetToolUnits(long nUnits)
{
// Check for valid Units....
switch(nUnits)
{
case TOOLLIB_UNITS_US: // US Tool -Units Inches
theApp.m_nToolUnits =TOOLLIB_UNITS_US;
break;
case TOOLLIB_UNITS_METRIC: // Metric Tool -Units MiliMeters
theApp.m_nToolUnits =TOOLLIB_UNITS_METRIC;
break;
default: // Something Errory...
TRACE0("Unknown Units Type In ToolLib_nSetToolUnits.\n");
return(FALSE); // Failure
} // switch on nUnits

// TODO: Add Your Own Units Change Code.

return(TRUE); // Succeeded -Units Set


} // ToolLib_nSetToolUnits

/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////

395
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

Part IV

3
9
6
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

397
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

Chapter 9
The SURFCAM
Toolpath API

INTRODUCTION TO THE SURFCAM TOOLPATH API


New to SURFCAM 2005 is access to the SURFCAM Toolpath API.
SURFCAM’s Toolpath Application Programming Interface (API) allows any user
to write Windows-based applications that can access SURFCAM’s toolpath
operations database. Using the API, users can write programs to generate, read,
and modify toolpath operations directly. The user may then send the operation to
the post-processor or SURFCAM Verify from the SURFCAM Operations
Manager.

Utilizing SURFCAM’s NCPost Interface requires a licensed copy of SURFCAM


2005 and intermediate knowledge of software programming. Because the
functions described below are accessed using C language header files, the C and
C++ programming environments are recommended. Other languages that can
access C language functions are also acceptable.

TOOLPATHS IN SURFCAM

SURFCAM is a powerful CAD/CAM package allowing users to create and


manipulate geometry, and then cut the actual geometry using a Computer
Numerical Control (CNC) machine. Users utilize SURFCAM’s ability to cut the
geometry by creating an “operation”, a program of toolpath commands. A user
creates an operation by selecting a cutting tool, the desired geometry, and toolpath
parameters. From this information, SURFCAM generates the program of toolpath
commands.

398
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

SURFCAM cuts parts by generating programs understood by a wide range of


CNC machines. Because the languages of the CNC machines varies so much
between different manufacturers, SURFCAM creates a generalized program that
is “post-processed” (after the generalized program is generated) to create the final
program that will be sent to a specific machine. This generalized program is
called an Intermediate Numerical Control (INC) file. The main SURFCAM
program can only create, store, manipulate, and understand INC files; the finalized
programs sent to the machining centers are created by a separate post-processor
which use INC files as their input.

INC FILE NAMING CONVENTION

SURFCAM names INC files according to the order in which they are created.
The conventional INC file is named “INC***.inc”, where the *** is a three letter
suffix. The first INC file created would be called “INCAAA.inc”, the second
would be called “INCAAB.inc”, and so on.

399
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

ANATOMY OF AN INC FILE


An INC file is no longer a physically distinct file, as it was in SURFCAM 6.1 and
earlier. Instead, multiple INC files are stored within a single file with the
extension ICD, or Intermediate Compound Document. Using Microsoft’s
Object Linking and Embedding technology (OLE for short), all the many
toolpaths associated with a design file are conveniently stored within the single
compound document file. However, for simplicity’s sake we will consider INC
documents as separate files.

NOTE FOR ADVANCED USERS

The ICD file uses a standard Microsoft COM (Component Object Model) storage
interface known as IStorage. Within the IStorage interface are IStream objects.
These IStream objects are the INC files, and the NCPost API functions to create,
read, and write the INC files are actually wrappers for standard IStream member
functions.

INC RECORDS

IINC files are composed of a series of INC records. Each INC record corresponds
to either toolpath parameter information or a command, and is composed of three
parts. The first part of the INC record gives the type, the second part of the record
states the size of the record data, and the third part of the INC record gives the
actual data (if any). The only exception to this is the INC header, which must be
the first record in the INC file. The INC header has no record size or data type.

Record Type Record Size Record Data

Figure 1 Structure of a typical INC record

Each INC file contains the information for a single toolpath, using the same tool
throughout the toolpath. Operations requiring multiple tools will require separate
INC files. Every INC file has a specific structure described on the next page.

400
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

INC Header

Record type: No type


Data type: inct_header

Address Information

Record type: INC_ADDRESS


Data type: inct_address

World Coordinate System

Record type: INC_WORLD_COORDS


Data type: inct_world_coords

Operation

Record type: INC_OPERATION


Data type: inct_operation

Flag for multi-axis

Record type: INC_MULTI_OFF or INC_MULTI_ON


Data type: No data

Cutter Information

Record type: INC_CUTTER_INFO_EX


Data type: inct_cutterx

Tool Change Information

Record type: INC_TOOL_CHANGE_EX


Data type: inct_tcx

Feed Rate Information

Record type: INC_FEED_RATE


Data type: inct_feed_rate

Plunge Rate Information

Record type: INC_PLUNGE_RATE


Data type: inct_plunge_rate

401
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

There are 63 different INC records used in SURFCAM toolpaths. The code that
defines them is found in incstrct.h, and these records are summarized in the table
below.

Table 9-1 SURFCAM INC records


Inc Record Description Data Type
INC_RAPID Linear rapid move to position inct_line
INC_LINE Linear feed move to position inct_line
INC_ARC_CW Clockwise arc move to inct_arc
position
INC_ARC_CCW Counter-clockwise arc move inct_arc
to position
INC_DWELL Dwell command inct_dwell
INC_COMP_CANCEL Cancel cutter compensation inct_line
INC_COMP_LEFT Apply left cutter compensation inct_line
INC_COMP_CANCEL Apply right cutter inct_line
compensation
INC_CANCEL End of canned sequence None
INC_CANCEL_DRILL End of canned drill sequence None
INC_CANCEL_THREAD End of canned threading None
sequence
INC_START_DRILL Start of canned drill sequence inct_start_drill
INC_TOOL_CHANGE Tool change data (obsolete) inct_tc
INC_TOOL_CHANGE_EX Tool change data (current) inct_tcx
INC_HEADER Operation header information inct_header
INC_ADDRESS User information inct_address
INC_CUT_MODE Cutting mode (mill/lathe/none) inct_cut_mode
INC_OPERATION Operation inct_operation
INC_FEED_RATE Feed rate inct_feed_rate
INC_PLUNGE_RATE Plunge rate inct_plunge_rate
INC_WORLD_COORDS World coordinates (obsolete) inct_world_cords
INC_WORLD_COORDS_EX World coordinates (current) inct_world_cords_ex
INC_ROT_AXIS Rotary axis inct_rot_axis
INC_MISC_REAL Miscellaneous real info misct_real
(EDM)
INC_MISC_INT Miscellaneous integer info misct_int
(EDM)
INC_MISC_PARAM Miscellaneous parameters misct_param
INC_CUTTER_INFO Mill cutter info (obsolete) inct_cutter
INC_CUTTER_INFO_EX Mill cutter info (current) inct_cutterx
INC_LATHE_CUTTER_INFO Lathe cutter info (obsolete) inct_lather_cutter
INC_LATHE_CUTTER_INFO_EX Lathe cutter info (current) inct_lather_cutterx
INC_PLUNGE Linear plunge move to inct_line
position
INC_ARC_PLUNGE_CW Clockwise arc plunge move inct_arc
INC_ARC_PLUNGE_CCW Couner-clockwise arc plunge inct_arc
move
INC_3DCOMP_RAPID Linear comp rapid move inct_line_comp
INC_3DCOMP_LINE Linear comp feed move inct_line_comp
INC_3DCOMP_PLUNGE Linear comp plunge move inct_line_comp

402
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

INC_NCURVE NURB curve header inct_ncurve


INC_NCURVE_KNOT NURB curve knot inct_knot
INC_NCURVE_POINT NURB curve point inct_npoint
INC_ORIENTED_START Oriented start inct_line
INC_HOLE Drill hole inct_hole
INC_START_LATHE_THREAD Start of canned thread inct_start_thread
sequence
INC_MULTI_ON Multi-axis mode ON None
INC_MULTI_OFF Multi-axis mode OFF None
INC_RAPID5 Multi-axis linear rapid move inct_line5
INC_LINE5 Multi-axis linear feed move inct_line5
INC_PLUNGE5 Multi-axis linear plunge move inct_line5
INC_5DCOMP_RAPID Multi-axis linear comp rapid inct_line_comp5
move
INC_5DCOMP_LINE Multi-axis linear comp feed inct_line_comp5
move
INC_5DCOMP_PLUNGE Multi-axis linear comp plunge inct_line_comp5
move
INC_5DNCURVE Multi-axis NURB curve inct_ncurve
header
INC_5DNCURVE_POINT Multi-axis NURB curve point inct_npoint5
INC_HOLE5 Multi-axis drill hole inct_hole5
INC_CTEXT Comment text character string
INC_ITEXT Inline text character string
INC_ITEXT_PRE_TC Inline text before tool change character string
INC_ITEXT_POST_TC Inline text after tool change character string
INC_HOME Home location inct_home
INC_CUSTOM Custom inct_custom
INC_START_OF_ROW Flag start of toolpath row None
INC_END_OF_ROW Flag end of toolpath row None
INC_DATA character string
INC_END None

Every INC file must begin with the structure inct_header. This header gives basic
information about the INC file, such as the version of the INC file and the author.
The structure is explained in the table below.

403
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

Table 9-2 Member Descriptions of the Structure inct_header


Member Data Type Description Possible Values
signature unsigned INC file signature INC_SIGNATURE
short
version unsigned Database version INC_VERSION
short
author array of 32 Author name Character string
characters
serial array of 8 SIM serial number Character string
characters
sversion array of 8 SURFCAM version Character string
characters
reserved array of 4 Unused Empty
characters
title array of 38 Title of design Character string
characters

Table 9-3 Member Descriptions of the Structure inct_address


Member Data Type Description Possible Values
name array of 40 Author's name Character string
characters
addr1 array of 40 Address line 1 Character string
characters
addr2 array of 40 Address line 2 Character string
characters
city array of 40 City Character string
characters
state array of 20 State Character string
characters
country array of 20 Country Character string
characters
zip array of 10 Zip code Character string
characters

404
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

Table 9-4 Member Descriptions of the Structure inct_cutterx


Member Data Type Description Possible Values
library_type long Type of tool Mill tool = 0
Drill tool = 1
Lathe tool = 2
Lathe drill = 3
Digitizer = 4
EDM = 5
Thread mill tool = 6
library_num long Tool number in library Any integer from 0 to 255
desc array of 40 Tool description Character string
characters
library_mat long Tool material High speed steel = 0
Carbide = 1
TIC TIN carbide = 2
Cobalt = 3
TIC TIN steel = 4
Ceramic = 5
Diamond = 6
Tapping = 7
library_class long Subclass of tool type See Table 9-5
tip long Program reference point At tip of tool = TRUE
At center of tool =
FALSE
flutes long Number of flutes Any integer from 0 to 255
nExtra long Unused 0
nExtra1 long Unused 0
nExtra2 long Unused 0
ctipr double Cutter tip radius Any positive number
ctotr double Total radius of cutter Any positive number
cdifr double Difference between Total radius - Tip radius
cutter tip radius and
total radius
ctipoff double Cutter tip offset Tip radius + distance from
finish pass
shankr double Shank radius Any positive number
tip_angle double Tip angle (for drills Any positive number
only)
taper_angle double Taper angle of tool Any positive number
flute_height double Height of flutes Any positive number
total_height double Height of tool Any positive number
chip_load_factor double ??? Any positive number
surface_speed double ??? Any positive number
chip_load double ??? Any positive number
dummy double Unused 0
dummy1 double Unused 0
dummy2 double Unused 0

405
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

Table 9-5 Tool type for library_class member of inct_cutterx


Value Mill Drill Lathe Thread Mill Other
0 Ballnose Tool Center Drill Standard Tool Thread Mill Tool No Tool
1 Flat Endmill Standard Drill Round Tool
2 Bullnose Tool Tapping Drill Triangle Tool
3 Teardrop Tool Reamer Threading Tool
4 Key Tool Bore Grooving Tool
5 Facemill Tool Custom Drill 1
6 Tapered Tool Custom Drill 2
7 Plunge-Rough Custom Drill 3
(Non-center
cutting) Tool
8 Spot Drill

406
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

Table 9-6 Member Descriptions of the Structure inct_tcx


Member Data Type Description Possible Values
library_num long Material number in library Any integer from 0 to 255
desc array of 40 Material description Character string
characters
units long Units being used English = 0
Metric = 1
program_number long Program ID number Any integer from 0 to 255
seq_num long Sequence number Any integer from 0 to 255
seq_inc long Sequence increment Any integer from 0 to 255
t_num long Tool number Any integer from 0 to 255
d_offset long Diameter offset Any integer from 0 to 255
l_offset long Length offset Any integer from 0 to 255
w_offset long Work offset Any integer from 0 to 255
turret long Turret number Any integer from 0 to 255
spin_speed long Spindle speed Any integer from 0 to 255
css long Constant surface speed Any integer from 0 to 255
upr long Feed/plunge rate units Units per minute = 0
flag Units per revolution = 1
coolant long Coolant flag Off = 0
Flood = 1
Mist = 2
Flood (Low) = 3
Flood (High) = 4
Through (Low) = 5
Through (High) = 6
rotary_axis long Rotary axis flag None = 0
Along Y = 1
Along X = 2
nExtra long Unused 0
nExtra1 long Unused 0
nExtra2 long Unused 0
x_gauge_len double X calibration length Any positive number
z_gauge_len double Z calibration length Any positive number
z_rapid double Z rapid plane Any positive number
init_power double Initial power (EDM Any positive number
specific)
power double Power (EDM specific) Any positive number
spark_gap double Spark gap (EDM specific) Any positive number
wire_feed long Wire feed flag (EDM Off = 0
specific) On = 1
taper double Taper angle Any positive number
dummy double Unused 0
dummy1 double Unused 0
dummy2 double Unused 0

407
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

Table 9-7 Operation Types (from NCPostAPI.h)


Operation Pre-defined Symbol Value
Other NCOP_TYPE_OTHER 0
Lathe turning NCOP_TYPE_LATHE_TURN 1
Lathe facing NCOP_TYPE_LATHE_FACE 2
Lathe grooving NCOP_TYPE_LATHE_GROOVE 3
Lathe threading NCOP_TYPE_LATHE_THREAD 4
Lathe drilling NCOP_TYPE_LATHE_DRILL 5
Lathe box NCOP_TYPE_LATHE_BOX 29
Lath part NCOP_TYPE_LATHE_PART 30
2 Axis Pocketing NCOP_TYPE_2AXIS_POCKET 6
2 Axis Contouring NCOP_TYPE_2AXIS_CONTOUR 7
2 Axis Drilling NCOP_TYPE_2AXIS_DRILL 8
2 Axis Face Milling NCOP_TYPE_2AXIS_FACE_MILL 35
2 Axis Rest Machining NCOP_TYPE_2AXIS_REST 37
3 Axis Cutting NCOP_TYPE_3AXIS_CUT 9
3 Axis Projection Cutting NCOP_TYPE_3AXIS_PROJECT 10
3 Axis Z Rough Cutting NCOP_TYPE_3AXIS_ZROUGH 11
3 Axis Z Finishing NCOP_TYPE_3AXIS_ZFINISH 27
3 Axis Multi-surface Cutting NCOP_TYPE_3AXIS_MULTI_SURFACE 12
3 Axis Planar Cutting NCOP_TYPE_3AXIS_PLANAR 13
3 Axis Contouring NCOP_TYPE_3AXIS_CONTOUR 14
3 Axis Drilling NCOP_TYPE_3AXIS_DRILL 15
3 Axis Auto Roughing NCOP_TYPE_3AXIS_AUTO_ROUGH 33
3 Axis Thread Milling NCOP_TYPE_THREAD_MILL 38
3 Axis Pencil Milling NCOP_TYPE_PENCIL_MILL 40
3 Axis Plunge Roughing NCOP_TYPE_PLUNGE_ROUGH 41
4 Axis Cutting NCOP_TYPE_4AXIS_CUT 16
4 Axis Swarf Cutting NCOP_TYPE_4AXIS_SWARF 17
4 Axis Projection Cutting NCOP_TYPE_4AXIS_PROJECT 18
4 Axis Contouring NCOP_TYPE_4AXIS_CONTOUR 19
4 Axis Drilling NCOP_TYPE_4AXIS_DRILL 20
4 Axis Trimming NCOP_TYPE_4AXIS_TRIM 31
5 Axis Cutting NCOP_TYPE_5AXIS_CUT 21
5 Axis Swarf Cutting NCOP_TYPE_5AXIS_SWARF 22
5 Axis Projection Cutting NCOP_TYPE_5AXIS_PROJECT 23
5 Axis Contouring NCOP_TYPE_5AXIS_CONTOUR 24
5 Axis Drilling NCOP_TYPE_5AXIS_DRILL 25
5 Axis Trimming NCOP_TYPE_5AXIS_TRIM 32
2 Axis EDM Contouring NCOP_TYPE_EDM_CONTOUR 28
2 Axis EDM Trimming NCOP_TYPE_EDM_TRIM 34
4 Axis EDM Cutting NCOP_TYPE_4AXIS_EDM 26
Merged operation NCOP_TYPE_MERGED 36
2 Axis EDM Skim Cutting NCOP_TYPE_EDM_SKIM 39

408
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

WRITING A DLL

Using the functions and data structures described below, the programmer can
create a DLL which can then be utilized from within SURFCAM. This DLL is
incorporated into SURFCAM by making a slight modification to the
SURFCAM.ini file. Within the SURFCAM.ini file, there is a section entitled
[SystemOptional], which contains this code:

UserApplications=2
UserApp1=D:\SURFCAM\Surf2005\UserApp1.dll
UserApp2=D:\SURFCAM\Surf2005\UserApp2.dll

The line “UserApplications=” refers to the number of user applications that you
want to activate. You can give your DLL any name you choose, substituting the
name of your DLL for “UserApp1.dll”, “UserApp2.dll”, etc. You can add more
than two applications, or have less than two applications as desired.

After modifying the SURFCAM.ini file, you need to make a change in a file
called MNU.def. This file is found in the path of your default SURFCAM
directory\Surf2005\Def. Copy this file to your default SURFCAM directory\Def
(the directory that contains the program surfrc.exe). After removing the read-
only attribute from this file, open the file and proceed to the section: “mainmenu
"PlugIns" 7”.

Here you will find the menu listings for the SURFCAM PlugIns menu. You
replace the name "UserApp&1" or "UserApp&2", etc., with the name of your
application as you want it to appear in the menu, and save the file. Next, from the
DOS command prompt, you run the program Surfrc.exe from that same directory
using the syntax:

surfrc –c MNU.def

This creates a new copy of SURFCAM.mnu, which contains your new application
name as part of the PlugIns menu. Substitute your new SURFCAM.mnu file into
your Surf2005 directory. To access this from within SURFCAM, hold down the
Control key and the letter “B”.

When writing your program, be sure to include the header files "expfunc.h" and
"incstrct.h". These files contain the necessary function and structure prototypes to
access the SURFCAM toolpath API.

409
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

410
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

411
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

Chapter 10
The Toolpath API
Function Descriptions

412
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

413
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scNCOp_CreateOperation

PROTOTYPE: long scNCOp_CreateOperation(char* sIncFileName);

ACTION: Creates an NC Operations Manager project item that is identified


within the NC Operations Manager by the Operation Description
“Other”.

FUNCTION RETURN TYPE: long

RETURN: Returns zero if successful, otherwise returns –1.

OUTPUT ARGUMENTS: The character string sIncFileName will contain the full path of the
newly created NC Operations Manager project item, including the
name that is assigned to the newly created operation. The string
will be no longer than MAX_PATH.

414
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scNCOp_CreateOperationToo

PROTOTYPE: long scNCOp_CreateOperationToo(char* sIncFileName, char*


sComment1, char* sComment2, int nOpType, int nDrillCycle, int
nRestMachining);

ACTION: Creates an NC Operations Manager project item.

FUNCTION RETURN TYPE: long

RETURN: Returns zero if successful, otherwise returns –1.

OUTPUT ARGUMENTS: The character string sIncFileName will contain the full path of the
newly created NC Operations Manager project item, including the
name that is assigned to the newly created operation.

INPUT ARGUMENTS: The character string sComment1 for the first operation comment.

The character string sComment2 for the second operation


comment.

An integer nOpType for the operation type (see Table 9-7).

An integer nDrillCycle for the drill cycle if the operation is a drilling


operation.

An integer nRestMachining which indicates whether or not it is a


rest operation, 0 or FALSE indicating not, 1 or TRUE indicating
yes.

415
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scNCOp_SetCurrentDesc

PROTOTYPE: long scNCOp_SetCurrentDesc(char* sDescription);

ACTION: Sets the description for an NC Operations Manager project item


after the call to create one.

FUNCTION RETURN TYPE: long

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: The character string sDescription to be set.

416
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scNCOp_ CommitOperation

PROTOTYPE: long scNCOp_CommitOperation();

ACTION: Associates the toolpath code with the NC Operations Manager


project item name that is created by the call to
scNCOp_CreateOperation.

FUNCTION RETURN TYPE: long

RETURN: If successful, zero is returned. A non-zero value is returned if the


function is not successful.

INPUT ARGUMENTS: None

417
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scNCOp_ CommitBeforeLastOperation

PROTOTYPE: long scNCOp_CommitBeforeLastOperation();

ACTION: Associates the toolpath code with the NC Operations Manager


project item name that is created by the call to
scNCOp_CreateOperation.

FUNCTION RETURN TYPE: long

RETURN: If successful, zero is returned. A non-zero value is returned if the


function is not successful.

INPUT ARGUMENTS: None

418
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scNCOp_ReleaseOperation

PROTOTYPE: long scNCOp_ReleaseOperation();

ACTION: This function releases all memory associated with the newly
created NC Operations Manager project item. This function
should be called if an error condition is detected in any phase of
the scNCOp_CreateOperation or scNCOp_CommitOperation
processes, or if there is an error while performing other file
manipulation processes.

FUNCTION RETURN TYPE: long

RETURN: Zero

INPUT ARGUMENTS: None

419
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scNCOp_GetItemPacketHandle

PROTOTYPE: void *
scNCOp_GetItemPacketHandle(const char * sFileName)

ACTION: Returns the packet handle of the given INC file stored in the ICD
compound document.

FUNCTION RETURN TYPE: void *

RETURN: Handle of packet database associated with an INC file.

INPUT ARGUMENTS: const char * sFileName Name of INC file

420
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scNCOp_OpenNCProjectItem

PROTOTYPE: long
scNCOp_OpenNCProjectItem (const char * sFileName)

ACTION: Displays the cut control page associated with an INC file in the
compound document.

FUNCTION RETURN TYPE: long

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: const char * sFileName Name of INC file

421
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scNCOp_SelectNCProjectItem

PROTOTYPE: long
scNCOp_SelectNCProjectItem(const char * sFileName
long nReserved1,
long nReserved2)

ACTION: Displays a dialog with the operations tree, allowing the user to
select an operation using a graphical interface. The function fills
in the name of the INC file associated with the operation.

FUNCTION RETURN TYPE: long

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: long nReserved1 Set to zero


long nReserved2 Set to zero

OUTPUT ARGUMENTS: const char * sFileName Name of INC file

422
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_Open

PROTOTYPE: void* scICDAPI_Open(const char *filename, const char *mode);

ACTION: Opens an INC file for reading, writing, and/or appending.

FUNCTION RETURN TYPE: void*

RETURN: The handle to the character stream.

INPUT ARGUMENTS: const char *filename - Pointer to the name of the file.

const char *mode – The type of access desired. Choose from the
following:

"r+" - Read/Write – The file must exist


"w+" - Read/Write – The file will be created if it does not exist
"a+" - Read/Append - The file will be created if it does not exist
"r" – Read Only – The file must exist
"w" – Write - The file will be created if it does not exist
"a" – Append - The file will be created if it does not exist

423
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scICDAPI_Eof

PROTOTYPE: int scICDAPI_Eof(void* hStream);

ACTION: Checks to see if the end of the file has been reached.

FUNCTION RETURN TYPE: int

RETURN: Returns -1 if the end of file has been reached, otherwise zero.

INPUT ARGUMENTS: void* hStream – Handle to the file stream.

424
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_Getc

PROTOTYPE: int scICDAPI_Getc(void* hStream);

ACTION: Retrieves a character from the stream.

FUNCTION RETURN TYPE: int

RETURN: The character read as an integer, or –1 for end of file condition.

INPUT ARGUMENTS: void* hStream – Handle to the file stream.

425
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scICDAPI_Putc

PROTOTYPE: int scICDAPI_Putc(int ch, void* hStream);

ACTION: Writes a character to the stream.

FUNCTION RETURN TYPE: int

RETURN: The character written as an integer.

INPUT ARGUMENTS: int ch – The character to be written to the stream (as an integer).

void* hStream – Handle to the file stream.

426
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_Read

PROTOTYPE: size_t scICDAPI_Read(void *buffer, size_t size, size_t count,


void* hStream);

ACTION: Reads data from the stream.

FUNCTION RETURN TYPE: size_t

RETURN: The number of items that were read, or zero if nothing is read or
end of file.

INPUT ARGUMENTS: void* buffer – Address of storage location for the data.

size_t size - The size of the data in bytes.

size_t count – The maximum amount of data to be read.

void* hStream – Handle to the file stream.

427
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scICDAPI_Write

PROTOTYPE: size_t scICDAPI_Write(void *buffer, size_t size, size_t count,


void* hStream);

ACTION: Writes data to the stream.

FUNCTION RETURN TYPE: size_t

RETURN: The number of items that were written.

INPUT ARGUMENTS: void* buffer Pointer to buffer containing data


to be written.
size_t size The size of the data in bytes.
size_t count The maximum amount of data to
be written.
void* hStream Handle to the file stream

428
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_Seek

PROTOTYPE: int scICDAPI_Seek(void * hStream, long offset, int origin);

ACTION: Moves the pointer to the chosen location within the file.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: void* hStream –The handle to the stream.

long offset – The number of bytes from the origin.

int origin – The position of origin of the file pointer. Choose one
of the following constants:
SEEK_SET – The beginning of the file
SEEK_CUR – The current location of the file pointer
SEEK_END – The end of the file

429
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scICDAPI_Tell

PROTOTYPE: int scICDAPI_Tell(void * hStream);

ACTION: Retrieves the current position of the file pointer.

FUNCTION RETURN TYPE: int

RETURN: Returns the current position of the file pointer if successful,


otherwise returns –1.

INPUT ARGUMENTS: void* hStream The handle to the stream.

430
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_Close

PROTOTYPE: void scICDAPI_Close(void * hStream);

ACTION: Closes the stream.

FUNCTION RETURN TYPE: void

RETURN: None

INPUT ARGUMENTS: void* hStream The handle to the stream

431
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scICDAPI_Erase

PROTOTYPE: void scICDAPI_Erase(const char * sFileName);

ACTION: Erases an INC file in the compound document.

FUNCTION RETURN TYPE: void

RETURN: None

INPUT ARGUMENTS: const char * sFileName The name of INC file to erase

432
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_SetSize

PROTOTYPE: int scICDAPI_SetSize(void * hStream, unsigned int nSize);

ACTION: Sets the length of the INC file (in bytes). This is useful if the use
removes or shortens INC records in the INC file.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: void* hStream The handle to the stream


unsigned int nSize New stream size

433
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scICDAPI_Clone

PROTOTYPE: void* scICDAPI_Clone(void * hOldStream, void * hNewStream);

ACTION: Clones the file pointer to an existing stream. This allows the user
to read and write information at different positions in the same
INC file.

FUNCTION RETURN TYPE: void *

RETURN: Handle of new stream pointer

INPUT ARGUMENTS: void* hOldStream The handle to the old stream


void* hNewStream The handle to the new stream

434
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scNCOp_GetOpSectionName

PROTOTYPE: long scNCOp_GetOpSectionName(const char* sOperName,


char* sSectionName);

ACTION: Gets the Section Name for a given INC Operation Name.

FUNCTION RETURN TYPE: long

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: The character string sOperName,


Which is the INC file name, without the path description.

OUTPUT ARGUMENTS: char * sSectionName Name of Section file.

435
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scNCOp_AddSetupSection

PROTOTYPE: int scNCOp_AddSetupSection(


const char* sSectionName);

ACTION: Adds the new Setup Section Name.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: char * sSectionName Name of Section file.

OUTPUT ARGUMENTS: None

436
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scICDAPI_Query

PROTOTYPE: int scICDAPI_Query(const char* pBuffer);

ACTION: Will return the list of INC file names.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: char * pBuffer Pointer to a allocated char buffer


area.

OUTPUT ARGUMENTS: List of INC file names.

437
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scGetSURFCAMAPIVersion

PROTOTYPE: int scGetSURFCAMAPIVersion ( );

ACTION: Will return the Surfcam API version. For Surfcam 2005, it is 100.

FUNCTION RETURN TYPE: int

RETURN: Return Surfcam API version.

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

438
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scGetSURFCAMMajorVersion

PROTOTYPE: int scGetSURFCAMMajorVersion ( );

ACTION: Will return the Surfcam major version. For Surfcam 2005, it is
2005

FUNCTION RETURN TYPE: int

RETURN: Return Surfcam major version.

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

439
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scGetSURFCAMMinorVersion

PROTOTYPE: int scGetSURFCAMMinorVersion ( );

ACTION: Will return the Surfcam minor version. For Surfcam 2005 service
pack 1, it is zero.

FUNCTION RETURN TYPE: int

RETURN: Return Surfcam minor version.

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

440
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scGetSURFCAMBuildVersion

PROTOTYPE: int scGetSURFCAMBuildVersion ( );

ACTION: Will return the Surfcam build number.

FUNCTION RETURN TYPE: int

RETURN: Return Surfcam build number.

INPUT ARGUMENTS: None

OUTPUT ARGUMENTS: None

441
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scGetSURFCAMBuildString

PROTOTYPE: int scGetSURFCAMBuildString (char *buffer, int buffersize);

ACTION: Will return the full Surfcam build version and build number.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: char * pBuffer string to store the name.


int buffersize string size.

OUTPUT ARGUMENTS: char * pBuffer the returned name.

442
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scUpdateOperationNoUI

PROTOTYPE: int scUpdateOperationNoUI (const char * sOperName);

ACTION: Update the operation without GUI interference.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: const char * sOperName operation name.

OUTPUT ARGUMENTS: None.

443
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scRegenerateOperationNoUI

PROTOTYPE: int scRegenerateOperationNoUI (const char * sOperName);

ACTION: Regenerate the operation without GUI interference.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: const char * sOperName operation name.

OUTPUT ARGUMENTS: None.

444
SURFCAM 2005 • API Documentation Chapter 10 Toolpath API Function Descriptions

scUpdateAllOperationsNoUI

PROTOTYPE: int scUpdateAllOperationsNoUI ();

ACTION: Update the all operations without GUI interference. Only


operation shown red will be updated.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: None.

OUTPUT ARGUMENTS: None.

445
Chapter 10 Toolpath API Function Descriptions SURFCAM 2005 • API Documentation

scRegenerateAllOperationsNoUI

PROTOTYPE: int scRegenerateAllOperationsNoUI ();

ACTION: Regenerate all operations without GUI interference. All


operation, both shown red and green, will be updated.

FUNCTION RETURN TYPE: int

RETURN: Returns zero if successful, otherwise returns –1.

INPUT ARGUMENTS: None.

OUTPUT ARGUMENTS: None.

446
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

Chapter 11
Sample Code Using
the Toolpath API

4
4
7
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

448
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

Sample Code: Writing to INC file

The sample file UserApp.cpp demonstrates a brief example of how an INC file is created and written. Here the
program uses the API to create the INC file in two parts. First, the operation is created within the framework of the
NCPost API. Second, the INC file is created with an association to the operation just created in NCPost.
The program then writes informational INC records to provide the basic parameters for the toolpath. First, the
address header is written to give information about the author. Then the world coordinate system is recorded to give
the basic orientation of the toolpath. The operation type is necessary to indicate what kind of cutting operation is
described (milling, lathe, wire EDM, etc.) Multiaxis support is not required for the sample, so it is toggled off.
Finally, the cutter info and tool change information is written to the INC file to describe the tool and cutting
parameters.
After these parameters are given, the actual toolpath generation begins. Setting the feed rate to rapid, the program
then enters commands to move the tool to specific coordinates. By setting different feed rates and coordinates, the
program can produce any desired toolpath. Lines, arcs, and NURB curves can be programmed in three, four, and
five axes by using the appropriate INC records.

// UserApp.cpp : Defines the initialization routines for the DLL.


//

#include "stdafx.h"
#include "UserApp.h"

/* These two following include commands added by SURFCAM API user. */


#include <expfunc.h>
#include <incstrct.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//
// Note!
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//

/////////////////////////////////////////////////////////////////////////////
// CUserAppApp

449
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

BEGIN_MESSAGE_MAP(CUserAppApp, CWinApp)
//{{AFX_MSG_MAP(CUserAppApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CUserAppApp construction

CUserAppApp::CUserAppApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CUserAppApp object

CUserAppApp theApp;

/**************************************************************************/
/* Above code generated by Microsoft Visual C++. Sample code starts here */
/**************************************************************************/

/////////////////////////////////////////////////////////////////////////////
// Global objects

// Create the global pointer to the SURFCAM API functions.


// *** IMPORTANT NOTE: This pointer MUST be named ut_p_pSCFuncs. ***

pSCFuncs* ut_p_pSCFuncs = NULL;

// All SURFCAM INC files begin with an address header, which gives the author's
// address information. Create one to begin the INC file we are going to create.

inct_address AuthorInfo =
{
"Josh", // The author's name
"Josh's Machine Shop", // Address line 1
"5703 Corsa Avenue", // Address line 2
"Westlake Village", // City
"CA", // State
"USA" // Country
"91362" // Zip code
};

// Every operation requires a defined tool. Here we will define a sample tool:
// a 1/2" four fluted ceramic bullnose endmill. Every tool is defined by the
// SURFCAM structure inct_cutterx.

inct_cutterx HalfInchBullnose =
{
0, // Library type (mill = 0)
3, // Library reference number (arbitrarily chose 3)
"1/2 inch bullnose", // Cutter description
5, // Library tool material (ceramic = 5)
2, // Library tool class (bullnose = 2)
TRUE, // Programmed to the tip if true, to the center if false
4, // Number of flutes
0, // Unused
0, // Unused
0, // Unused
0.25, // Tip radius
0.25, // Total radius
0.0, // Difference between total radius and tip radius
0.25, // Tip radius + distance away from finish
0.05, // Shank radius
0.0, // Tool tip angle (defined for drills)
0.0, // Tool taper angle

450
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

1.3, // Flute height


1.55, // Total height
0.0, // Chip load factor (material dependent)
0.0, // Surface speed (material dependent)
0.00185, // Chip load
0.0, // Unused
0.0, // Unused
0.0 // Unused
};

// The "speeds and feeds" of the operation also need to be defined. The
// structure inct_tcx contains the material information, the speeds and feed
// rates, and other relevant cutting data. These are final values and must be
// calculated accurately according to the material and tool associated with the
// operation.

inct_tcx SampleToolChange =
{
0, // Material library reference number
"Sample Material", // Material description
0, // Unit mode (English = 0)
0, // Program number
0, // Sequence number
0, // Sequence increment
1, // Tool number
1, // Diameter offset
1, // Length offset
0, // Work offset
0, // Turret number
1000, // Spindle speed
0, // Spindle speed - constant surface speed
0, // Feed/plunge rate units (units per minute = 0)
0, // Coolant (none = 0)
0, // Rotary axis (none = 0)
0, // Unused
0, // Unused
0, // Unused
0.0, // X Calibration Length
0.0, // Z Calibration Length
1.0, // Z Rapid Plane
0.0, // Initial power (EDM specific)
0.0, // Power (EDM specific)
0.0, // Spark gap (EDM specific)
0, // Wire feed (EDM specific)
0.0, // Taper angle
0.0, // Unused
0.0, // Unused
0.0 // Unused
};

/////////////////////////////////////////////////////////////////////////////
// bWriteIncHeader
//
// This function writes the header information. A header record is unique in
// that there is no INC type associated with the record, hence this dedicated
// function (all other INC records in this sample are written using
// the function bWriteIncRecord().

static BOOL
bWriteIncHeader(void* pICDStream)
{
ULONG nCount; // Number of bytes to write
ULONG nActualWritten; // Number of bytes written
inct_header SampleHeader; // Header to write

// Set all the values in the structure to zero.


memset(&SampleHeader, 0, sizeof(inct_header));

SampleHeader.signature = INC_SIGNATURE; // Current INC signature


SampleHeader.version = INC_VERSION; // Current version number
strcpy(SampleHeader.author, "Josh"); // Author's name

451
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

strcpy(SampleHeader.serial, "0000"); // SIM serial number


strcpy(SampleHeader.sversion, "7.20"); // SURFCAM version number

nCount = sizeof(inct_header);

nActualWritten = scICDAPI_Write(&SampleHeader, nCount, 1, pICDStream);

if (nActualWritten != nCount)
return FALSE;

return TRUE; // Success


} // bPutIncHeader

/////////////////////////////////////////////////////////////////////////////
// bWriteIncRecord
//
// This function writes a single INC record, given the type and data of the
// record to be written. This is a great function that can be copied directly
// for use in user programs.

static BOOL
bWriteIncRecord(
int nType, // ii Type of INC record
int nSize, // ii Size of INC data
void* pData, // ii Data to be written
void* pICDStream) // io ICD stream to write to
{
BYTE Buffer; // Write byte buffer
ULONG nActualWritten; // Number of bytes written

// Assign the INC record type to the buffer, and write the buffer.
Buffer = (BYTE) nType;
nActualWritten = scICDAPI_Write(&Buffer, sizeof(Buffer), 1, pICDStream);

if (nActualWritten != 1)
return(FALSE);

// Assign the INC record size to the buffer, and write the buffer.
Buffer = (BYTE) nSize/2;
nActualWritten =scICDAPI_Write(&Buffer, sizeof(Buffer), 1, pICDStream);

if (nActualWritten != 1)
return(FALSE);

// If data has size, write out the data.


if (nSize > 0)
{
ASSERT(pData != NULL); // Size but nothing to write ?????

if (pData == NULL)
return(FALSE);

// Write the data.


nActualWritten = scICDAPI_Write(pData, nSize, 1, pICDStream);

if (nActualWritten != (ULONG) nSize)


return(FALSE);
} // if data has size

return(TRUE);
} // bWriteIncRecord

/////////////////////////////////////////////////////////////////////////////
//
// UserApp_nCallback
//
// All SURFCAM user applications must define UserApp_nCallback. SURFCAM
// searches for this function in the DLL and calls this function. SURFCAM
// passes the pointer to the API functions through the argument.

extern "C" long UserApp_nCallback(pSCFuncs *Funcs)

452
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

{
AFX_MANAGE_STATE(AfxGetStaticModuleState()); // Required Visual C++ macro

long nRes = 0;
char sIncFileName[MAX_PATH];
char sIncFileDesc[MAX_PATH];

// Assign passed argument to global function pointer.


ut_p_pSCFuncs = Funcs;

AfxMessageBox("Sample Write Toolpath Application!");

// Create the operation, which fills in the file name.


nRes = scNCOp_CreateOperation(sIncFileName);

// Check for failure to create operation (indicated by returning non-zero).


if (nRes != 0)
{
AfxMessageBox("Sorry, Create Operation Failed!");
return -1;
}

// Define stream pointer (set to NULL for now)


void* pICDStream = NULL;

// Open/initialize the ICD stream with read/write priviledges.


pICDStream = scICDAPI_Open(sIncFileName, "w+");

strcpy(sIncFileDesc, "UserAppWrite - Simple Toolpath");

scNCOp_SetCurrentDesc(sIncFileDesc);

// Check for failure to open the ICD stream (indicated by returning NULL).
if (pICDStream == NULL)
{
AfxMessageBox("Sorry, Open Stream Failed!");
return -1;
}

// Always Write INC Header Information First...


BOOL bRes = bWriteIncHeader(pICDStream);

// Check for an error when writing to the file.


if (bRes != 0)
{
AfxMessageBox("Error encountered. Toolpath creation aborted.");

// Clear the operation and free the memory.


scNCOp_ReleaseOperation();
return -1;
}

// Always write user information immediately after the INC header.


bRes = bWriteIncRecord(INC_ADDRESS, sizeof(inct_address),
&AuthorInfo, pICDStream);

// Check for an error when writing to the file.


if (bRes != 0)
{
AfxMessageBox("Error encountered. Toolpath creation aborted.");

// Clear the operation and free the memory.


scNCOp_ReleaseOperation();
return -1;
}

// Define coordinate system.


inct_world_coords WorldCoords;

// Initialize matrix to zero matrix.


memset(&WorldCoords.mat, 0, 4*3*sizeof(double));

// Set matrix for standard "top view".

453
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

WorldCoords.mat[0][0] = 1.0;
WorldCoords.mat[1][1] = 1.0;
WorldCoords.mat[2][2] = 1.0;

// Write coordinate system.


bRes = bWriteIncRecord(INC_WORLD_COORDS, sizeof(inct_world_coords),
&WorldCoords, pICDStream);

// Check for an error when writing to the file.


if (bRes != 0)
{
AfxMessageBox("Error encountered. Toolpath creation aborted.");

// Clear the operation and free the memory.


scNCOp_ReleaseOperation();
return -1;
}

// Optional operation type next


inct_operation SampleOperation;
SampleOperation.nOperation = NCOP_TYPE_2AXIS_CONTOUR;

bRes = bWriteIncRecord(INC_OPERATION, sizeof(inct_operation),


&SampleOperation, pICDStream);

// Write multi-axis mode (off)


bRes = bWriteIncRecord(INC_MULTI_OFF, 0, NULL, pICDStream);

// Write cutter information


bRes = bWriteIncRecord(INC_CUTTER_INFO_EX, sizeof(inct_cutterx),
&HalfInchBullnose, pICDStream);

// Write tool change information


bRes = bWriteIncRecord(INC_TOOL_CHANGE_EX, sizeof(inct_tcx),
&SampleToolChange, pICDStream);

// Write the feed rate.


inct_feed_rate SampleFeedRate;
SampleFeedRate.FeedRate = 3.0f;

bRes = bWriteIncRecord(INC_FEED_RATE, sizeof(inct_feed_rate),


&SampleFeedRate, pICDStream);

// Write the plunge rate.


inct_plunge_rate SamplePlungeRate;
SamplePlungeRate.PlungeRate = 2.0f;

bRes = bWriteIncRecord(INC_PLUNGE_RATE, sizeof(inct_plunge_rate),


&SamplePlungeRate, pICDStream);

// Write the toolpath.


inct_line line;

line.x = 0.0f;
line.y = 0.0f;
line.z = 1.0f;

// Write the initial rapid move to move the tool one inch above the origin.
bRes = bWriteIncRecord(INC_RAPID, sizeof(inct_line), &line,
pICDStream);

line.z = 0.1f;

// Write a rapid move to move the tool 0.1 inch above the origin (to the
// start of the plunge move).
bRes = bWriteIncRecord(INC_RAPID, sizeof(inct_line), &line,
pICDStream);

line.z = 0.0f;

// Write a plunge move to move the tool to the origin.


bRes = bWriteIncRecord(INC_PLUNGE, sizeof(inct_line), &line,
pICDStream);

454
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

line.x = 1.0f;

// Write a linear feed move to move the tool one inch along X.
bRes = bWriteIncRecord(INC_LINE, sizeof(inct_line), &line,
pICDStream);

line.z = 1.0f;

// Write the final rapid move to move the tool to the clearance plane.
bRes = bWriteIncRecord(INC_RAPID, sizeof(inct_line), &line,
pICDStream);

// Commit the operation.


scNCOp_CommitOperation();

// Close stream.
scICDAPI_Close(pICDStream);

// Return 0 for success.


return(0L);
} // UserApp_nCallback

///////////////////////////////////////////////////////////////////////////

455
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

Sample Code: Reading from INC file

The sample file UserAppRead.cpp illustrates a general method of reading an INC file. In order to read an INC file,
you must know the name of the file stream. Once the desired file stream is opened, the INC records may be read.
The first element in an INC file is the header record, which gives basic information about the author of the operation
and the version of the INC file. Because INC records may differ from version to version of SURFCAM, it is always
a good idea to check the signature member with the predefined INC_SIGNATURE of the API code being utilized.
After the header has been validated, the program enters a loop to read the INC records. Each INC record is a three-
part object, with a data type preceding the data size and actual data. The loop reads in the type of the INC record
first, then fills in the appropriate data structure depending on the record type. The loop continues until the end of the
INC file is reached.

// UserAppRead.cpp : Defines the initialization routines for the DLL.


//

#include "stdafx.h"
#include "UserAppRead.h"

/* These two following include commands added by SURFCAM API user. */


#include <expfunc.h>
#include <incstrct.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//
// Note!
//
// If this DLL is dynamically linked against the MFC
// DLLs, any functions exported from this DLL which
// call into MFC must have the AFX_MANAGE_STATE macro
// added at the very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//

/////////////////////////////////////////////////////////////////////////////
// CUserAppReadApp

BEGIN_MESSAGE_MAP(CUserAppReadApp, CWinApp)
//{{AFX_MSG_MAP(CUserAppReadApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

456
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

/////////////////////////////////////////////////////////////////////////////
// CUserAppReadApp construction

CUserAppReadApp::CUserAppReadApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CUserAppReadApp object

CUserAppReadApp theApp;

/**************************************************************************/
/* Above code generated by Microsoft Visual C++. Sample code starts here */
/**************************************************************************/

pSCFuncs* ut_p_pSCFuncs = NULL;

/////////////////////////////////////////////////////////////////////////////
//
// UserApp_nCallback
//
// All SURFCAM user applications must define UserApp_nCallback. SURFCAM
// searches for this function in the DLL and calls this function. SURFCAM
// passes the pointer to the API functions through the argument.

extern "C" long UserApp_nCallback(pSCFuncs* pFuncs)


{
AFX_MANAGE_STATE(AfxGetStaticModuleState());

// Create output file and initialize settings to write.


CFile OutFile("Outfile.inc", CFile::modeCreate | CFile::modeWrite |
CFile::shareDenyNone);

char sIncFileName[MAX_PATH];

// Assign passed argument to global function pointer.


ut_p_pSCFuncs = pFuncs;

AfxMessageBox("Sample Read Toolpath Application!");

BYTE Buffer[512]; // Read/write buffer


BYTE ch = 0; // Read byte buffer
int nCode = 0; // INC record type
int nSize = 0; // INC record size
ULONG nRecordsRead = 0; // Number of records read

void* pICDStream = NULL;

// ATTENTION: In order to open an INC file within the document, you must
// know the name of the file exactly. INC files are usually named
// "INCxxx.INC", with the xxx representing three letters.
strcpy(sIncFileName, "INCAAA.INC");

// Open/initialize the ICD stream with read/write priviledges.


pICDStream = scICDAPI_Open(sIncFileName, "r+");

// Check for failure to open the ICD stream (indicated by returning NULL).
if (pICDStream == NULL)
{
AfxMessageBox("Sorry, Open Stream Failed!");
return -1;
}

// INC header file structure


struct inc_header Header;

// Read INC file header (if it exists)


nRecordsRead = scICDAPI_Read(&Header, sizeof(inct_header), 1, pICDStream);

457
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

// If not successful, return fail (-1).


if (nRecordsRead != 1)
return -1;

// Check for valid INC signature


if (Header.signature != INC_SIGNATURE)
return -1;

// Check for valid INC version


if (Header.version != INC_VERSION)
return -1;

// Write the header to the output INC file.


OutFile.Write(&Header, sizeof(inct_header));

// Loop through the file reading code until no more records to be read.
while (nRecordsRead != 0)
{
// Read INC type of record.
nRecordsRead = scICDAPI_Read(&ch, 1, 1, pICDStream);

if (nRecordsRead != 0)
{
// INC record type successfully read.
nCode = ch;

// Read size of record.


nRecordsRead = scICDAPI_Read(&ch, 1, 1, pICDStream);

// If not successful, return fail (-1).


if (nRecordsRead != 1)
return -1;

// Inc record size


nSize = 2 * ch;

// Switch on INC type


switch(nCode)
{
case INC_ADDRESS:
{
inct_address Address;

// Read the address from the stream.


nRecordsRead = scICDAPI_Read(&Address, nSize, 1, pICDStream);

if (nRecordsRead != 1)
return -1;

ch = (BYTE) nCode;
OutFile.Write(&ch, 1);
ch =(BYTE) (nSize/2);
OutFile.Write(&ch, 1);
OutFile.Write(&Address, nSize);

break;
} // INC_ADDRESS

case INC_CUTTER_INFO_EX:
{
inct_cutterx Cutter;

ASSERT(nSize == sizeof(inct_cutterx));
nRecordsRead = scICDAPI_Read(&Cutter, nSize, 1, pICDStream);

if (nRecordsRead != 1)
return -1;

ch =(BYTE) nCode;
OutFile.Write(&ch, 1);
ch =(BYTE) (nSize/2);
OutFile.Write(&ch, 1);
OutFile.Write(&Cutter, nSize);

458
SURFCAM 2005 • API Documentation Chapter 11 Toolpath API Sample Code

break;
} // INC_CUTTER_INFO_EX

case INC_RAPID:
case INC_PLUNGE:
case INC_LINE:
{
inct_line Line;

ASSERT(nSize == sizeof(inct_line));
nRecordsRead = scICDAPI_Read(&Line, nSize, 1, pICDStream);

if (nRecordsRead != 1)
return -1;

ch =(BYTE) nCode;
OutFile.Write(&ch, 1);
ch =(BYTE) (nSize/2);
OutFile.Write(&ch, 1);
OutFile.Write(&Line, nSize);
break;
} // INC_RAPID, INC_PLUNGE, INC_LINE

case INC_CUT_MODE:
{
inct_cut_mode nCutMode;

// Verify sizes to be the same using an ASSERT.


ASSERT(nSize == sizeof(inct_cut_mode));
nRecordsRead = scICDAPI_Read(&nCutMode, nSize, 1, pICDStream);

if (nRecordsRead != 1)
return -1;

ch =(BYTE) nCode;
OutFile.Write(&ch, 1);
ch =(BYTE) (nSize/2);
OutFile.Write(&ch, 1);
OutFile.Write(&nCutMode, nSize);
break;
} // INC_CUT_MODE

case INC_TOOL_CHANGE_EX:
{
inct_tcx ToolChange;

ASSERT(nSize == sizeof(inct_tcx));

// Verify sizes to be the same using an if statement.


if (nSize != sizeof(inct_tcx))
return -1;

nRecordsRead = scICDAPI_Read(&ToolChange, nSize, 1, pICDStream);

if (nRecordsRead != 1)
return -1;

ch =(BYTE) nCode;
OutFile.Write(&ch, 1);
ch =(BYTE) (nSize/2);
OutFile.Write(&ch, 1);
OutFile.Write(&ToolChange, nSize);
break;
} // INC_TOOL_CHANGE_EX

default:
{
// If the INC record has data (not all records do), then read
// the data.
if (nSize != 0)
{
nRecordsRead = scICDAPI_Read(&Buffer, nSize, 1, pICDStream);

459
Chapter 11 Toolpath API Sample Code SURFCAM 2005 • API Documentation

if (nRecordsRead != 1)
return -1;
}

ch =(BYTE) nCode;
OutFile.Write(&ch, 1);
ch =(BYTE) (nSize/2);
OutFile.Write(&ch, 1);

if (nSize != 0)
OutFile.Write(Buffer, nSize);

break;
} // default
}
}
}

// Close read and write streams.


OutFile.Close();
scICDAPI_Close(pICDStream);

return 0;
}

460

You might also like