NOTE**********************************************
THIS INFORMATION IS OUT OF DATE   22 Aug 2000
**************************************************



              Developing External Modelers
            ===============================

Add in modelers are the most flexible elements of the external
module capabilities.
A single function resides in a DLL that is called
once it has been selected by the user from a file requester.

To develope external modelers a 32 bit compiler is required.
Watcom C++ >= v9.5/10, Visual C++ 32bit edition >= V8, Symantec C++ >= v 6.1
and possibly Borland C++ version 4.0.
all work satisfctorily for developing add in modelers. The comments about the
compilers in the Shaders readme file should be read for latest details.

External modelers are implemented as Windows NT dynamic link libraries
(DLL's) they may be used in Windows 3.1 if the program itself may be used in
Windows 3.1. That is, if Win32s has been installed.

Each modeler will have 4 files associated with it's development,
                   name.C
                   name.H
                   name.RC
                   name.BAT
The compiled modeler will have the name "name.DLL"  this is the only
file that need be distributed to users. It should be located in
the MODELER subdirectory, but a separate directory can be used if there
are likely to be any name conflicts.

The BAT file is used to build the DLL, section in the BAT file are specific
to each of the compilers mentioned above, and are called by typing
the name followed by the compiler to be used.
   eg.
        example vc         for Visual C++
        example wc         for Watcom C++
        example sc         for Symantec C++
        example mips       for compilation on MIPS systems

Some tweeking of the batch file may be needed on different systems.

Each external modeller also needs a file with name extension .MFX is needed
to accompany each of the .DLL library files. This is a dummy file and need
not contain any data. It is just a name holder to allow the selection dialog
to pick up modeller DLL's and not any other!

A template like example is provided that can server as a starting point
for producing external modelers, this example simply calls a dialog box
and returns when the dialog is dismissed. A more elaboroate example
SIMPLPLT is provided. This creates a window and some tools for
drawing in 2D. It has the option to build the 2D line drawing into vertices
and edges and illustrates how the functions within the modeler are called
to augment the internal database.

The DLL has a single externally callable function Xmodeler( ) with two
parameters.

  HWND parent_window,     /* parent window of caller                 */
  X__STRUCTURE *lpevi    /* pointer to database structure           */

lpevi points to an X__STRUCTURE structure define in STRUCT.H, this
file also gives definitions for the VERTEX EDGE etc structures.
A file DSTRUCT.H provides defines that allows conventional
C style function calls to be used while calling functions in the modeler.
(Read also the section "Calling functions.." in the Shaders
readme.txt file)

The entry code
--------------
/* compiler specific function naming                                  */
#if __XXX__
BOOL _Xmodeler
#else
BOOL _Xmodeler
#endif
 /* parameters                                                        */
 ( HWND parent_window,     /* parent window of caller                 */
   HWND info_window,       /* pointer to information window           */
   char *info_line,        /* pointer to string to put info text      */
   X__STRUCTURE *lpevi    /* pointer to database structure           */
 ){
 /* assign a static global variable that is used in DEFINE's for      */
 /* calls to functions and access to global variables                 */
 /* this name must NOT be changed lpEVI is typed in DSTRUCT.H         */

 lpEVI=lpevi;

 /* This is where the Modeler action takes place                      */
 /* can be almost anything required                                   */

 /* return TRUE if functions are successful FALSE otherwise           */
 return TRUE;
}

Very Important Note.
--------------------
Unlike the Renderer the Modeler uses double precision throughout, therefore
all references to variables of type "double" are truely double types!!!


Using Vertices Edges and Faces in the Database
-----------------------------------------------
The data is based on triangular facets, each facet (face) has number of
properties that define how it will be rendered, colour, surface
shader or map are important elements of this. A facet on it's own carries
no position information, this is provided by placing a vertex at each corner
and giving that a co-ordinate triple. The edges of the faces are not
used in rendering but are needed for a wireframe representation in the
modeler and animator. The data for a model is thus stored as three lists
one for vertices, one for edges and one for faces.
The Faces and Edges list have indices to the vertices to which they are
connected. A face has three integers and an edge has two. Thus a cube
is represented by 8 vertices, 12 faces and 18 edges.

To write a modeler you need to be familiar with the internal structures,
these are closely related to the SCE file format so it would
be a good idea to consult now the FFORM.TXT document included in this
archive.

Modeler Structures
-------------------
typedef struct VERTEX {
 struct SKELETON *sp;    /* pointer to Skeleton node to which the vertex
                            is attached, set to NULL if not attached     */
 char   status,gp;       /* status = 0  if vertex is Deselected
                            status = 1  if vertex is Selected
                            status = 2  if vertex is Hidden
                            gp = 0  if glue mapping off for vertex
                            gp = 1  if glue mapping is on for vertex     */
 long   id;              /* internal use only */
 float  x,y;             /* glue mapping co-ordinates for vertex         */
 long   xyz[3];          /* position vertex (x,y,z)                      */
} vertex;


typedef struct EDGE {
 long V[2];              /* zero based index into vertex list of vertices
                            to which the vertex is attached              */
} edge;

typedef struct FACE{
 long V[3];              /* zero based index into vertex list of vertices
                            at corners of face                           */
 unsigned char color[3], /* RGB face colours color[0]=Red range is 0-255 */
               matcol[3],/* secondary colour and other face properties   */
               texture,  /* shader identity and other surface properties */
               brush,    /* image maps id and other flags                */
               axis;     /* shader axis identity                         */
} face;

The details of the matco, texture, and brush bytes are described in
the File Format document if the following association is made,
     texture   = shader byte
     matcol[0] = shader_value_1
     matcol[1] = shader_value_2
     matcol[2] = shader_value_3
     brush     = map ID byte


Skeleton structure

typedef struct SKELETON {
 struct SKELETON *at,*next,*last; /* doubly linked list and parent joint */
 short  id,offset;                /* used internally */
 vector u,v,w;                    /* used internally */
 double t[4][4];                  /* used internally */
 point  xyz,tp,bx[8];             /* xyz position of joint
                                     tp is used internally
                                     bx is bounding box
                                     a point is an integer equivalent of
                                     a vector         */
 char   name[16];                 /* name of joint    */
} skel;


Shader Axis structure, up to 64 shader axes per model are permitted

typedef struct tagSHADERAXIS {
char    N[32];                    /* name of shader axis                  */
point   P,X,Y;                    /* P is long (x,y,z) co-ord of origin
                                       point of shader axis
                                     X and Y are (x,y,z) co-ords of
                                     the other control points             */
} SHADERAXIS;


External Shader structure, 4 external shaders per model are permitted

typedef struct tagXSHADER {
  long in_use;                    /* 0 if not in use 1 if in use          */
  char name[128],*parameters;     /* name of the shader DLL, pointer to
                                     character string containing the
                                     shaders parameters                   */
} XSHADER;


Image map structure, up to 64 image maps per model are permitted

typedef struct tagIMAGEMAP {
short   in_use;           /* used internally                               */
char    N[32],            /* name given to the map                         */
        *S,               /* pointer to string with name of surface map    */
        *R,               /* pointer to string with name of reflection map */
        *B;               /* pointer to string with name of bump map       */
                          /* the name pointer are NULL if no image         */
char    s,                /*    s = 1 if surface map in use 0 otherwise    */
        r,                /*    r = 1 if reflection map in use 0 otherwise */
        b;                /*    b = 1 if bump map in use 0 otherwise       */
short   sp,               /* mix in value for surface map                  */
        rp,               /* mix in value for reflection map               */
        bp;               /* mix in value for bump map                     */
char    Type,             /* 0 = static map 1 = animated map               */
        Map,              /* form of map   0 = Planar map
                                           1 = Cylindrical
                                           2 = Planar moziac
                                           3 = cylindrical miziac
                                           4 = Glue mapping                */
        Lock;             /* 0 if not locked 1 if locked to vertices       */
short   AnimFF,           /* if the map is an animated map AnimFF is the
        AnimDL,              first frame in the sequence AnimLD is the last
        AnimLF,              frame in sequence and AnimDL is the number of
                             frames holding the same image                 */
        Angle,            /* 0-360 is angle of rotation for cylindrical
                             type maps                                     */
        SkId;             /* -1 if not asigned to skeleton +1 is assigned  */
point   P,X,Y;            /* co-ordinates of map control points (x,y,z)
                             P = main point
                             X = Top-Right corner of map
                             Y = Bottom-Left corner of map                 */
skel    *Sk;              /* if maps is tied to Skeleton joint, pointer to
                             joint map is attached to                      */
long    Vlock[3];         /* vertex index if map is locked to vertices     */
unsigned char d_colour[3],s_colour[3],a_colour[3]; /* not used             */
} IMAGEMAP;


Accessing the structures
------------------------
Access to the internal structures is through pointers passed to the DLL in
an X__STRUCTURE. The parameter *lpevi to the function Xmodeler points
to a filled X__SRUCTURE.

The include file DSTRUCT.H contains macro definition that allow variable
names to be used directly in the code. For this reason the names appearing
in the file DSTRUCT.H are considered reserved and should not be used in
function code. (Unless you modify the file DSTRUCT.H, but this is not
recommended). An example of accessing and modifying the models description
is given in the file SIMPLPLT.C which provides a simple line drawing utility
that builds Vertices and Edges by calling functions defined in DSTRUCT.H.

  Code fragment.

 /* Nv is local variabl number of vertices drawn in SimplPlt's window.  */
 /* vc is locla variable defining the number of vertices to be added to */
 /* the model in the database.                                          */
 /* Nvert is a "Global Variable" passed to the DLL it is the number of  */
 /* vertices already in the Model.                                      */
 /* UpdateVertexHeap( ) is a function that is called to allocates extra */
 /* memory sufficient to accomodate vc aditional vertices               */

 UpdateVertexHeap(Nvert+vc);
 for(i=0;i<Nv;i++){ /* for all points drawn in window */
   ..
   ..
   /* CreateVertex is called to create a vertex in the modeler's database */
   /* creating a vertex automatically increments the variable Nvert and   */
   /* and assigned default values to the VERTEX structure members         */

   CreateVertex();

   /* MainVp is a pointer to the start of the Vertex List                 */
   /* thus (MainVp+Nvert-1) is a pointer to the Vertex structure added    */
   /* by the CreateVertex structure                                       */

   (MainVp+Nvert-1)->xyz[0]=TVlist[i].x*Scale;
   (MainVp+Nvert-1)->xyz[1]=NpointerY;
   (MainVp+Nvert-1)->xyz[2]=(rc.bottom-TVlist[i].y)*Scale;

   /* the 3 lines above assign (x,y,z) co-ordinates to the new vertex     */
   /* variable NpointerY is passed to the library and give the Y co-ord   */
   /* which the user have placed the 3D cursor                            */
   /* It would be a very good idea to look at the header file DSTRUCT.H   */
   /* and see the way that variables such as Nvert and functions such as  */
   /* CreateVertex() are defined. With the inclusion of DSTRUCT.H         */
   /* it should be possible to use pseudo function calls and global       */
   /* variables as shown above. Formal definitions for the members of the */
   /* X__STRUCTURE structure given below are in terms of global          */
   /* varaibles and function calls                                        */
   .
   .
 }

 Very Important Notes
 --------------------
 You will notice from the code fragment above that UpdateVertexHeap can
 make space available for mote than one vertex, this is necessary because
 when running under Windows 3.1 using the Win32s emulator the
 allocation of memory is VERY VERY SLOW, far, far too slow to allocate memory
 at each call to CreateVertex, therefore UpdateVertexHeap (UpdateEdgeHeap,
 UpdateFaceHeap) is called to add or remove space for all extra vertices at
 the same time.
 If your function does not add enough space before calling CreateVertex
 it will added in the CreateVertex function but the speed will go WAY DOWN
 (an audible waring MessageBeep() is given, so if your machine starts
 beeping at you look at these functions!).

 The pointers to the start of Vertex/Edge/Face lists MainVp, MainEp and
 MainFp deserve a special note.

     When the size of these lists is altered by calling Update????Heap(..)
     or Create???(..) Windows will MOVE THEM IN THE ADDRESS SPACE.

 If for example, you write code like.

    int i;
    vertex *MyVertexPointer;
    MyVertexPointer = MainVp;
    for(i=0;i<10;i++){
      UpdateVertexHeap(Nvert+1);
      CreateVertex();
      (MyVertexPointer+Nvert-1)->xyz[0]=1024;
    }

 IT WILL FAIL !!!!! because UpdateVertex Heap will move the array as it
 changes it size. The modeler automatically changes the MainVp variable to
 point to this new location.So to fix the example above, the line,
                    MyVertexPointer = MainVp;
 must be inserted after the call to UpdateVertexHeap(..)
 This note is particularly important if you are accessing elements in a loop
 and incrementing a pointer on each cycle through the loop.

 Note however that it IS valid to write code like.
    int i;
    vertex *MyVertexPointer;
    UpdateVertexHeap(Nvert+10);
    MyVertexPointer = (MainVp+Nvert);
    for(i=0;i<10;i++){
      CreateVertex();
      MyVertexPointer->xyz[0]=1024;
      MyVertexPointer++;
    }

 Symptoms of failure to comply with the above are;
    Windows NT  - Message "Attempt to write to memory location at 0x.... etc"
    Windows 3.1 - Just throws you out to Program Manager, with possible
                  system lock up!

Global Variables and Functions accessibe from External Modellers
-----------------------------------------------------------------

Variables
---------
vertex *MainVp   pointer to head of list of vertex structures
edge   *MainEp   pointer to head of list of edge structures
face   *MainFp   pointer to head of list of face structures
skel   *MainSp   pointer to last element(joint) of Skeleton linked list
skel   *FirstSp  pointer to first element of Skeleton linked list

unsigned long  Nvert            Number of vertices in the current model
unsigned long  NvertSelect      Number of vertices which are selected
unsigned long  NvertDeselect    Number of vertices which are deselected/hidden
unsigned long  NvertGlue        Number of vertices with glue mapping co-ordinates
unsigned long  Nedge            Number of edges in the current model
unsigned long  Nface            Number of faces in the current model
unsigned long  Nskel            Number of skelton joints in the current model

int  nImaps              Number of image maps in current model
int  nSha                Number of shader axes in current model
IMAGEMAP   *iMap         Pointer to head of array of up to 64 image maps
SHADERAXIS *iSha         Pointer to head of array of up to 64 shaderaxes
XSHADER    *xShaders     Pointer to head of array of 4 external shader blocks

long  NpointerX          x position (World Coords - see below) of 3D cursor
long  NpointerY          y  "                "
long  NpointerZ          z  "                "
long  TVsizeX            x size of the current WindowBox

The variables TVsizeY, TVsizeZ are not defined in DSTRUCT.H if you need to
access then then add lines like that for #define TVsizeX in your own function.
The co-ordinates of the Rear/Left/Bottom cornet of the WindowBox are given
by the variables TVpointX, TVpointY, TVpointZ which will need additional
defines.
The co-ordinate scale value "ruler" and its origin "orulerx, orulery and
orulerz" may be liekwise defined if necessary. See the README.TXT file for
external image processor functions of information on "ruler" variables.

Functions
---------

Memory allocation functions same as ANSI C functions malloc, free and realloc
void *X__Malloc(long size);
void  X__Free(void *ptr);
void *X__Realloc(void *ptr,long size);

void EraseAll(short w);
   Erase all or part of the database.
   w = 0 Erase vertices, edges, faces and skeleton only
   w = 1 Erase everything!

void CreateVertex(void);
  Add a vertex to the vertex list, Nvert and MainVp are updated accordingly.
  Memory allocation is normally handled by UpdatevertexHeap but if required
  within this function, failure is handled internally.

void CreateEdge(long v1,long v2);
  Add an edge to the edge list, the edge joins vertices v1 to v2, where
  v1 and v2 are indices into the vertex list, (0 is first entry). The
  vertices v1 and v2 must exist, no checking is done so it is the
  responsibility of the caller that bad values are not passed to the function.
  Bad values will result in program failure.

void CreateFace(long v1, long v2, long v3);
  Add an face to the face list, the faces three corners are joined to
  vertices v1, v2 or v3. No specific cyclic ordering is required!
  v1,v2 and v3 are indices into the vertex list, (0 is first entry).
  The existance rules for CreateEdge function apply here.

void CreateSkeleton(skel *at);
  Add a Skeleton node(joint) to the models skeleton. The joint must be
  attached to another joint by passing a pointer to it "at").
  A root joint is always present and will be pointed to by the variable
  "FirstSp".

BOOL UpdateVertexHeap(long n);
  Make space in the vertex list for n vertices, if n is greater than Nvert
  the list is extended by (n-Nvert) vertices if n is less than Nvert the
  list is trucated. The list pointer MainVp will point to new vertex list.
  Function returns TRUE if successful FALSE otherwise. Failure to find
  enough memory will be handled by the modeler. This function is always used
  with one or more calls to CreateVertex();

BOOL UpdateEdgeHeap(long n);
  Make space in the edge list for n edges, if n is greater than Nedge
  the list is extended by (n-Nedge) edges if n is less than Nedge the
  list is trucated. The list pointer MainEp will point to new edge list.
  Function returns TRUE if successful FALSE otherwise. Failure to find
  enough memory will be handled by the modeler. This function is always used
  with one or more calls to CreateEdge(v1,v2);

BOOL UpdateFaceHeap(long n);
  Make space in the face list for n faces, if n is greater than Nface
  the list is extended by (n-Nface) faces if n is less than Nface the
  list is trucated. The list pointer MainFp will point to new face list.
  Function returns TRUE if successful FALSE otherwise. Failure to find
  enough memory will be handled by the modeler. This function is always used
  with one or more calls to CreateFace(v1,v2,v3);

void  UpdateCounters(void);
  Update the data display window with the number and status of vertices.

void DrawModel(void);
  Redraw the Windowbox view windows to show modifications to model.

The following functions are at a higher level than basic vertex creation.

BOOL AddCopy(int wait);
 Add a copy of all parts of the model which are selected. A vertex is
 selected it's status structure member is set to 1.
 An edge is selected if it is attached to selected vertices at both ends.
 A face is selected if the vertices at its three corners are selected.
 If the parameter w is 1 an hourglass cursor is drawn while the function is
 working, if it is 0 the function proceeds silently.

int AutoFacetCurveWithHoles(int f, int visible, int atm,
                            double bevel_angle, double bevel_depth);
  This function will fill selected outlines with faces.
  Restrictions apply to the outlines that may be filled, consult the
  the modeler users manual for details of Filling Curves.
  f = 0 normal fill
  f = 1 Bevel curve
  f = 2 Round over curve
  f = 3 bevel with given angle and depth
  visible = 0  do it quietly
            1  show hourglass cursor and store old structure in Undo Buffer
  atm must be 0
  bevel_angle in degrees
  bevel_depth in floating point equivalent of world co-ords.
  Returns -1 if function fails  1 otherwise.

BOOL CreateAttachedCopy(1);
  Creates a copy of selected vertices edges and faces and attaches them
  to the original by a network of edges and faces. This routine performs
  the action of the Extrude function, it leaves the old vertices
  deselected and the new vertices selected. Nvert MainVp are updated
  accordingly.
  There is a mandatory parameter of unity, the function returns TRUE
  if successful and FALSE otherwise.


Internal Co-ordinates
---------------------
The modeler uses a long integer co-ordinate system (World co-ords). This
is scaled to a floating point (User co-ords) system for use in dialogs and
the co-ords window.
Animations are set up and Models are built in Internal units with a
co-ordinate system in which  X is +ve to the right Y is +ve in the forward
direction and Z is +ve in the up direction. Animation take place in this
integer world where the farthest anything can be is +/-2**31. The actors
and camera are positioned in this absolute frame of reference. As each frame
is renderered a transformation is derived that move the camera to (0,0,0)
looking in the direction (0,1,0) with up being (0,0,1).

We started with the basic premise that vertex co-ords should be stored as
long integers.  To allow some "numeric" room for calculation as floats/doubles
the range of long's that may be used are  2**11 = 2048 up to 2**30.

The animator obviously needs much more room than the modeler so the modeler
is restricted to the integer range  2**11 up to 2**22.

The default WindowBox size is 65536 (2**16).  The maximum zoom (zoom in-
smallest Box) is a Box size of 2048 (2**11) on each side. And the minimum
zoom (Zoom out) is a box size of 4,194,304 (2**22).

Thus a model has a "range of detail" of about 2048 times.  That is the
smallest detail on a model can be about 0.05% of the size of the model.

The maximum long integer in the animator is 1,073,741,824 (2**30), this gives
 the LARGEST possible models a Box of 256 times their size in which to move.

Usually models start to grow from the default Box size of 2**16 and end up
with a dimension of perhaps 4 times this (2**18 = 262,144). When animated
this model has a universe of 4096 times its size in which to move.

Of course, in the animator, the models may be scaled down or up as required
if the space available is not satisfactory.

Data imported from other packages has to be scaled so that it is not too
large or indeed too small.
3D Studio and DXF use floating point co-ords and that presents quite a
challenge. It is necessary to store all the floating point
data and then assess the size of the models and convert it to appropriate
long integers.  The Sculpt SCE data uses long int's but it looks like the
models wll always be too big and therefore some scaling must be applied.


Examples
--------
A template in files EXAMPLE.C EXAMPLE.BAT EXAMPLE.RC EXAMPLE.H can be used
to build external modelers. the name should be changed to reflect the
function of the modeler and this should be used to replace "example" in the
.BAT file and reference to example.h in example.c and example.rc

SIMPLPLT is provied as a working example so that you can test your development
example. DXFOUT.C DXFOUT.BAT are included even though it is NOT and
external modelers. The structure is basically similar and the code shows
how to access the skeleton data as well as the normal vertices, edges and
faces.













