[med-svn] [r-cran-rgl] 01/02: Imported Upstream version 0.95.1441+dfsg

Andreas Tille tille at debian.org
Thu Jun 30 14:41:38 UTC 2016


This is an automated email from the git hooks/post-receive script.

tille pushed a commit to branch master
in repository r-cran-rgl.

commit 1e2f9d435885fcf0990661cfa97135fdd8c6096f
Author: Andreas Tille <tille at debian.org>
Date:   Thu Jun 30 16:39:03 2016 +0200

    Imported Upstream version 0.95.1441+dfsg
---
 COPYING                                    |   342 +
 DESCRIPTION                                |    26 +
 MD5                                        |   365 +
 NAMESPACE                                  |    94 +
 R/Sweave_knitr.R                           |    98 +
 R/addNormals.mesh3d.R                      |    52 +
 R/animate.R                                |   206 +
 R/aspect3d.R                               |    24 +
 R/axes.R                                   |   199 +
 R/bgplot3d.R                               |   115 +
 R/callbacks.R                              |    13 +
 R/cylinder3d.R                             |   194 +
 R/device.R                                 |   171 +
 R/ellipse3d.R                              |    63 +
 R/enum.R                                   |    68 +
 R/fonts.R                                  |    67 +
 R/getscene.R                               |   393 +
 R/grid3d.R                                 |    63 +
 R/identify3d.R                             |    85 +
 R/internal.R                               |   146 +
 R/material.R                               |   171 +
 R/matrices.R                               |    81 +
 R/mesh3d.R                                 |   200 +
 R/obj.R                                    |   363 +
 R/oh3d.R                                   |    98 +
 R/par3d.R                                  |    66 +
 R/persp3d.R                                |   156 +
 R/plot3d.R                                 |   109 +
 R/plugin.R                                 |    19 +
 R/ply.R                                    |   323 +
 R/r3d.rgl.R                                |   293 +
 R/rgl.bringtotop.R                         |    15 +
 R/scene.R                                  |   908 ++
 R/selectpoints3d.R                         |    66 +
 R/shapelist3d.R                            |    85 +
 R/solids3d.R                               |   203 +
 R/stl.R                                    |   247 +
 R/subdivision.mesh3d.R                     |   250 +
 R/subscenes.R                              |   264 +
 R/triangulate.R                            |   310 +
 R/turn3d.R                                 |    61 +
 R/webGL.R                                  |    63 +
 R/webGLcontrols.R                          |   152 +
 R/zzz.R                                    |    91 +
 README                                     |   172 +
 build/vignette.rds                         |   Bin 0 -> 228 bytes
 cleanup                                    |     3 +
 configure                                  |  5770 +++++++++
 configure.ac                               |   210 +
 configure.win                              |   102 +
 demo/00Index                               |    13 +
 demo/abundance.r                           |    48 +
 demo/bivar.r                               |    49 +
 demo/envmap.r                              |    23 +
 demo/flag.R                                |    26 +
 demo/hist3d.r                              |   114 +
 demo/lollipop3d.R                          |   153 +
 demo/lsystem.r                             |   192 +
 demo/mouseCallbacks.R                      |   303 +
 demo/regression.r                          |    38 +
 demo/rgl.r                                 |     9 +
 demo/shapes3d.R                            |   107 +
 demo/stereo.R                              |   145 +
 demo/subdivision.r                         |    36 +
 inst/NEWS                                  |   733 ++
 inst/WebGL/template.html                   |    17 +
 inst/demodata/population.dat               |    86 +
 inst/demodata/region.dat                   |  2414 ++++
 inst/doc/WebGL.Rmd                         |   434 +
 inst/doc/WebGL.html                        |  2901 +++++
 inst/doc/rgl.Rmd                           |   596 +
 inst/doc/rgl.html                          |  3481 ++++++
 inst/fonts/FreeMono.ttf                    |   Bin 0 -> 292816 bytes
 inst/fonts/FreeSans.ttf                    |   Bin 0 -> 260792 bytes
 inst/fonts/FreeSerif.ttf                   |   Bin 0 -> 973940 bytes
 inst/textures/bump_dust.png                |   Bin 0 -> 207628 bytes
 inst/textures/nightfire.png                |   Bin 0 -> 197266 bytes
 inst/textures/particle.png                 |   Bin 0 -> 26418 bytes
 inst/textures/refmap.png                   |   Bin 0 -> 23635 bytes
 inst/textures/rgl2.png                     |   Bin 0 -> 197266 bytes
 inst/textures/sunsleep.png                 |   Bin 0 -> 83062 bytes
 inst/textures/world.png                    |   Bin 0 -> 68897 bytes
 inst/textures/worldsmall.png               |   Bin 0 -> 9958 bytes
 man/3dobjects.Rd                           |   103 +
 man/GramSchmidt.Rd                         |    48 +
 man/abclines.Rd                            |    52 +
 man/addNormals.Rd                          |    38 +
 man/ageSetter.Rd                           |    88 +
 man/aspect3d.Rd                            |    42 +
 man/attributes.Rd                          |    82 +
 man/axes3d.Rd                              |   100 +
 man/bbox.Rd                                |    68 +
 man/bg.Rd                                  |    71 +
 man/bgplot3d.Rd                            |    69 +
 man/callbacks.Rd                           |    75 +
 man/check3d.Rd                             |    21 +
 man/cylinder3d.Rd                          |    90 +
 man/ellipse3d.Rd                           |    99 +
 man/extrude3d.Rd                           |    56 +
 man/grid3d.Rd                              |    61 +
 man/hook_rgl.Rd                            |    58 +
 man/identify3d.Rd                          |    46 +
 man/light.Rd                               |    74 +
 man/material.Rd                            |   174 +
 man/matrices.Rd                            |   110 +
 man/mesh3d.Rd                              |   133 +
 man/mfrow3d.Rd                             |   121 +
 man/observer3d.Rd                          |    53 +
 man/par3d.Rd                               |   293 +
 man/par3dinterp.Rd                         |    71 +
 man/persp3d.Rd                             |   132 +
 man/persp3d.function.Rd                    |   172 +
 man/planes.Rd                              |    85 +
 man/play3d.Rd                              |    95 +
 man/plot3d.Rd                              |   108 +
 man/polygon3d.Rd                           |    72 +
 man/postscript.Rd                          |    67 +
 man/primitive.Rd                           |    76 +
 man/propertySetter.Rd                      |   210 +
 man/r3d.Rd                                 |   104 +
 man/readSTL.Rd                             |    91 +
 man/rgl-internal.Rd                        |    65 +
 man/rgl-package.Rd                         |    43 +
 man/rgl.Sweave.Rd                          |    89 +
 man/rgl.bringtotop.Rd                      |    30 +
 man/rgl.open.Rd                            |    94 +
 man/rgl.pixels.Rd                          |    41 +
 man/rgl.select.Rd                          |    29 +
 man/rgl.useNULL.Rd                         |    35 +
 man/rgl.user2window.Rd                     |    56 +
 man/scene.Rd                               |    85 +
 man/scene3d.Rd                             |    92 +
 man/select3d.Rd                            |    56 +
 man/selectpoints3d.Rd                      |    93 +
 man/shapelist3d.Rd                         |    48 +
 man/show2d.Rd                              |   135 +
 man/snapshot.Rd                            |    58 +
 man/spheres.Rd                             |    43 +
 man/spin3d.Rd                              |    56 +
 man/sprites.Rd                             |    66 +
 man/subdivision3d.Rd                       |    46 +
 man/subscene3d.Rd                          |   149 +
 man/subsceneInfo.Rd                        |    53 +
 man/surface.Rd                             |   102 +
 man/surface3d.Rd                           |    80 +
 man/texts.Rd                               |   142 +
 man/triangulate.Rd                         |    88 +
 man/turn3d.Rd                              |    42 +
 man/viewpoint.Rd                           |    65 +
 man/webGLcontrols.Rd                       |    95 +
 man/writeOBJ.Rd                            |   120 +
 man/writePLY.Rd                            |    92 +
 man/writeWebGL.Rd                          |   151 +
 src/ABCLineSet.cpp                         |   101 +
 src/ABCLineSet.h                           |    49 +
 src/BBoxDeco.cpp                           |   796 ++
 src/BBoxDeco.h                             |    75 +
 src/Background.cpp                         |   228 +
 src/Background.h                           |    47 +
 src/COPYING.GL2PS                          |    25 +
 src/ClipPlane.cpp                          |   122 +
 src/ClipPlane.h                            |    51 +
 src/Color.cpp                              |   267 +
 src/Color.h                                |    75 +
 src/Device.h                               |    80 +
 src/DeviceManager.h                        |    52 +
 src/Disposable.cpp                         |    36 +
 src/Disposable.h                           |    60 +
 src/Light.cpp                              |   107 +
 src/Light.h                                |    48 +
 src/LineSet.cpp                            |    24 +
 src/LineStripSet.cpp                       |    22 +
 src/Makevars.in                            |    18 +
 src/Material.cpp                           |   205 +
 src/Material.h                             |    66 +
 src/NULLgui.cpp                            |   122 +
 src/NULLgui.h                              |    23 +
 src/PlaneSet.cpp                           |   175 +
 src/PlaneSet.h                             |    50 +
 src/PointSet.cpp                           |    17 +
 src/PrimitiveSet.cpp                       |   336 +
 src/PrimitiveSet.h                         |   280 +
 src/R.h                                    |    43 +
 src/RenderContext.cpp                      |    12 +
 src/RenderContext.h                        |    39 +
 src/SceneNode.h                            |    92 +
 src/Shape.cpp                              |   154 +
 src/Shape.h                                |   177 +
 src/SphereMesh.cpp                         |   151 +
 src/SphereMesh.h                           |    64 +
 src/SphereSet.cpp                          |   115 +
 src/SphereSet.h                            |    65 +
 src/SpriteSet.cpp                          |   203 +
 src/SpriteSet.h                            |    71 +
 src/String.cpp                             |   145 +
 src/String.h                               |    54 +
 src/Surface.cpp                            |   311 +
 src/Surface.h                              |    70 +
 src/TextSet.cpp                            |   156 +
 src/TextSet.h                              |    54 +
 src/Texture.cpp                            |   279 +
 src/Texture.h                              |    54 +
 src/Viewpoint.cpp                          |   244 +
 src/Viewpoint.h                            |    75 +
 src/api.cpp                                |  1342 ++
 src/api.h                                  |   121 +
 src/assert.cpp                             |     9 +
 src/assert.h                               |    43 +
 src/build/autoconf/config.guess            |  1444 +++
 src/build/autoconf/config.sub              |  1813 +++
 src/build/autoconf/install-sh              |   527 +
 src/callbacks.cpp                          |   154 +
 src/config.h                               |    18 +
 src/device.cpp                             |   154 +
 src/devicemanager.cpp                      |   165 +
 src/ext/GLsdk/GL/gl.h                      |  1914 +++
 src/ext/GLsdk/GL/glext.h                   |  5924 +++++++++
 src/ext/GLsdk/GL/glprocs.c                 | 17859 +++++++++++++++++++++++++++
 src/ext/GLsdk/GL/glprocs.h                 |  2213 ++++
 src/ext/GLsdk/GL/wglext.h                  |   611 +
 src/ext/GLsdk/README                       |   110 +
 src/ext/GLsdk/glxdemo/Makefile             |    20 +
 src/ext/GLsdk/glxdemo/demo.c               |   358 +
 src/ext/GLsdk/windemo/Makefile             |    29 +
 src/ext/GLsdk/windemo/README               |    24 +
 src/ext/GLsdk/windemo/demogl.c             |   203 +
 src/ext/GLsdk/windemo/demogl.h             |    74 +
 src/ext/GLsdk/windemo/multithread/Makefile |    39 +
 src/ext/GLsdk/windemo/multithread/demo.c   |   340 +
 src/ext/GLsdk/windemo/multiwin/Makefile    |    37 +
 src/ext/GLsdk/windemo/multiwin/demo.c      |   313 +
 src/ext/GLsdk/windemo/singlewin/Makefile   |    29 +
 src/ext/GLsdk/windemo/singlewin/demo.c     |   245 +
 src/ext/ftgl/FTBuffer.cpp                  |    69 +
 src/ext/ftgl/FTCharToGlyphIndexMap.h       |   155 +
 src/ext/ftgl/FTCharmap.cpp                 |   106 +
 src/ext/ftgl/FTCharmap.h                   |   165 +
 src/ext/ftgl/FTContour.cpp                 |   245 +
 src/ext/ftgl/FTContour.h                   |   209 +
 src/ext/ftgl/FTFace.cpp                    |   232 +
 src/ext/ftgl/FTFace.h                      |   181 +
 src/ext/ftgl/FTFont/FTBitmapFont.cpp       |   106 +
 src/ext/ftgl/FTFont/FTBitmapFontImpl.h     |    62 +
 src/ext/ftgl/FTFont/FTBufferFont.cpp       |   349 +
 src/ext/ftgl/FTFont/FTBufferFontImpl.h     |    81 +
 src/ext/ftgl/FTFont/FTExtrudeFont.cpp      |    89 +
 src/ext/ftgl/FTFont/FTExtrudeFontImpl.h    |    81 +
 src/ext/ftgl/FTFont/FTFont.cpp             |   552 +
 src/ext/ftgl/FTFont/FTFontGlue.cpp         |   227 +
 src/ext/ftgl/FTFont/FTFontImpl.h           |   162 +
 src/ext/ftgl/FTFont/FTOutlineFont.cpp      |   129 +
 src/ext/ftgl/FTFont/FTOutlineFontImpl.h    |    73 +
 src/ext/ftgl/FTFont/FTPixmapFont.cpp       |   135 +
 src/ext/ftgl/FTFont/FTPixmapFontImpl.h     |    60 +
 src/ext/ftgl/FTFont/FTPolygonFont.cpp      |    89 +
 src/ext/ftgl/FTFont/FTPolygonFontImpl.h    |    60 +
 src/ext/ftgl/FTFont/FTTextureFont.cpp      |   267 +
 src/ext/ftgl/FTFont/FTTextureFontImpl.h    |   152 +
 src/ext/ftgl/FTGL/FTBBox.h                 |   180 +
 src/ext/ftgl/FTGL/FTBitmapGlyph.h          |    82 +
 src/ext/ftgl/FTGL/FTBuffer.h               |   127 +
 src/ext/ftgl/FTGL/FTBufferFont.h           |    99 +
 src/ext/ftgl/FTGL/FTBufferGlyph.h          |    69 +
 src/ext/ftgl/FTGL/FTExtrdGlyph.h           |   104 +
 src/ext/ftgl/FTGL/FTFont.h                 |   584 +
 src/ext/ftgl/FTGL/FTGLBitmapFont.h         |   103 +
 src/ext/ftgl/FTGL/FTGLExtrdFont.h          |   105 +
 src/ext/ftgl/FTGL/FTGLOutlineFont.h        |   103 +
 src/ext/ftgl/FTGL/FTGLPixmapFont.h         |   103 +
 src/ext/ftgl/FTGL/FTGLPolygonFont.h        |   104 +
 src/ext/ftgl/FTGL/FTGLTextureFont.h        |   103 +
 src/ext/ftgl/FTGL/FTGlyph.h                |   201 +
 src/ext/ftgl/FTGL/FTLayout.h               |   192 +
 src/ext/ftgl/FTGL/FTOutlineGlyph.h         |    94 +
 src/ext/ftgl/FTGL/FTPixmapGlyph.h          |    82 +
 src/ext/ftgl/FTGL/FTPoint.h                |   274 +
 src/ext/ftgl/FTGL/FTPolyGlyph.h            |    98 +
 src/ext/ftgl/FTGL/FTSimpleLayout.h         |   191 +
 src/ext/ftgl/FTGL/FTTextureGlyph.h         |    99 +
 src/ext/ftgl/FTGL/ftgl.h                   |   135 +
 src/ext/ftgl/FTGlyph/FTBitmapGlyph.cpp     |   128 +
 src/ext/ftgl/FTGlyph/FTBitmapGlyphImpl.h   |    71 +
 src/ext/ftgl/FTGlyph/FTBufferGlyph.cpp     |   121 +
 src/ext/ftgl/FTGlyph/FTBufferGlyphImpl.h   |    52 +
 src/ext/ftgl/FTGlyph/FTExtrudeGlyph.cpp    |   265 +
 src/ext/ftgl/FTGlyph/FTExtrudeGlyphImpl.h  |    69 +
 src/ext/ftgl/FTGlyph/FTGlyph.cpp           |   112 +
 src/ext/ftgl/FTGlyph/FTGlyphGlue.cpp       |   198 +
 src/ext/ftgl/FTGlyph/FTGlyphImpl.h         |    64 +
 src/ext/ftgl/FTGlyph/FTOutlineGlyph.cpp    |   149 +
 src/ext/ftgl/FTGlyph/FTOutlineGlyphImpl.h  |    69 +
 src/ext/ftgl/FTGlyph/FTPixmapGlyph.cpp     |   139 +
 src/ext/ftgl/FTGlyph/FTPixmapGlyphImpl.h   |    67 +
 src/ext/ftgl/FTGlyph/FTPolygonGlyph.cpp    |   156 +
 src/ext/ftgl/FTGlyph/FTPolygonGlyphImpl.h  |    66 +
 src/ext/ftgl/FTGlyph/FTTextureGlyph.cpp    |   153 +
 src/ext/ftgl/FTGlyph/FTTextureGlyphImpl.h  |    88 +
 src/ext/ftgl/FTGlyphContainer.cpp          |   119 +
 src/ext/ftgl/FTGlyphContainer.h            |   155 +
 src/ext/ftgl/FTInternals.h                 |   145 +
 src/ext/ftgl/FTLayout/FTLayout.cpp         |    80 +
 src/ext/ftgl/FTLayout/FTLayoutGlue.cpp     |   171 +
 src/ext/ftgl/FTLayout/FTLayoutImpl.h       |    56 +
 src/ext/ftgl/FTLayout/FTSimpleLayout.cpp   |   460 +
 src/ext/ftgl/FTLayout/FTSimpleLayoutImpl.h |   225 +
 src/ext/ftgl/FTLibrary.cpp                 |    91 +
 src/ext/ftgl/FTLibrary.h                   |   122 +
 src/ext/ftgl/FTList.h                      |   137 +
 src/ext/ftgl/FTPoint.cpp                   |    58 +
 src/ext/ftgl/FTSize.cpp                    |   123 +
 src/ext/ftgl/FTSize.h                      |   164 +
 src/ext/ftgl/FTUnicode.h                   |   237 +
 src/ext/ftgl/FTVector.h                    |   215 +
 src/ext/ftgl/FTVectoriser.cpp              |   328 +
 src/ext/ftgl/FTVectoriser.h                |   313 +
 src/ext/ftgl/config.h                      |     7 +
 src/fps.cpp                                |    43 +
 src/fps.h                                  |    32 +
 src/ftgl.cpp                               |    17 +
 src/geom.cpp                               |   195 +
 src/geom.h                                 |    65 +
 src/gl2ps.c                                |  6139 +++++++++
 src/gl2ps.h                                |   207 +
 src/glErrors.cpp                           |    38 +
 src/glgui.cpp                              |   193 +
 src/glgui.h                                |   173 +
 src/gui.cpp                                |   312 +
 src/gui.h                                  |   219 +
 src/init.cpp                               |   254 +
 src/init.h                                 |    30 +
 src/lib.h                                  |    20 +
 src/opengl.h                               |    29 +
 src/par3d.cpp                              |   757 ++
 src/pixmap.cpp                             |   157 +
 src/pixmap.h                               |    54 +
 src/platform.cpp                           |    77 +
 src/platform.h                             |    45 +
 src/pngpixmap.h                            |   414 +
 src/pragma.h                               |    52 +
 src/pretty.c                               |   216 +
 src/pretty.h                               |    17 +
 src/render.cpp                             |   139 +
 src/render.h                               |    79 +
 src/rgl-win.def                            |     3 +
 src/rglmath.cpp                            |   334 +
 src/rglmath.h                              |   232 +
 src/rglview.cpp                            |  1027 ++
 src/rglview.h                              |   203 +
 src/scene.cpp                              |   299 +
 src/scene.h                                |   157 +
 src/select.cpp                             |    35 +
 src/select.h                               |    27 +
 src/subscene.cpp                           |  1016 ++
 src/subscene.h                             |   234 +
 src/types.h                                |   162 +
 src/win32gui.cpp                           |   781 ++
 src/win32gui.h                             |    28 +
 src/win32lib.cpp                           |    71 +
 src/x11gui.cpp                             |   703 ++
 src/x11gui.h                               |    68 +
 src/x11lib.cpp                             |   138 +
 tests/demos.R                              |     8 +
 vignettes/WebGL.Rmd                        |   434 +
 vignettes/rgl.Rmd                          |   596 +
 vignettes/setup.R                          |    76 +
 365 files changed, 102863 insertions(+)

diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..cf93907
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,342 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+

+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+

+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+

+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+

+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+

+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year  name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.
+
+
diff --git a/DESCRIPTION b/DESCRIPTION
new file mode 100644
index 0000000..a4f27cd
--- /dev/null
+++ b/DESCRIPTION
@@ -0,0 +1,26 @@
+Package: rgl
+Version: 0.95.1441
+Title: 3D Visualization Using OpenGL
+Author: Daniel Adler <dadler at uni-goettingen.de>, Duncan Murdoch <murdoch at stats.uwo.ca>, and others (see README)
+Maintainer: Duncan Murdoch <murdoch at stats.uwo.ca>
+Depends: R (>= 2.15.0)
+Suggests: MASS, rglwidget (>= 0.1.1427), knitr, rmarkdown
+Imports: graphics, grDevices, stats, utils
+Description: Provides medium to high level functions for 3D interactive graphics, including
+    functions modelled on base graphics (plot3d(), etc.) as well as functions for 
+    constructing representations of geometric objects (cube3d(), etc.).  Output
+    may be on screen using OpenGL, or to various standard 3D file formats including 
+    WebGL, PLY, OBJ, STL as well as 2D image formats, including PNG, Postscript, SVG, PGF.
+License: GPL
+URL: https://r-forge.r-project.org/projects/rgl/
+SystemRequirements: OpenGL, GLU Library, zlib (optional), libpng
+        (>=1.2.9, optional), FreeType (optional)
+BugReports: https://r-forge.r-project.org/projects/rgl/
+VignetteBuilder: knitr
+Repository: CRAN
+Repository/R-Forge/Project: rgl
+Repository/R-Forge/Revision: 1442
+Repository/R-Forge/DateTimeStamp: 2016-01-04 13:08:15
+Date/Publication: 2016-01-04 17:37:50
+NeedsCompilation: yes
+Packaged: 2016-01-04 13:26:11 UTC; rforge
diff --git a/MD5 b/MD5
new file mode 100644
index 0000000..f41248a
--- /dev/null
+++ b/MD5
@@ -0,0 +1,365 @@
+e73499cb89e0d6e97b8ba271c46739fd *COPYING
+9a62087c208440d66a309931ac6d4577 *DESCRIPTION
+a014451fd81a551c82122c43cc854f91 *NAMESPACE
+f64cc2e1ab9f1df80bb580bd221393a3 *R/Sweave_knitr.R
+924eeb2faa0ef90099ad9176b1cc5013 *R/addNormals.mesh3d.R
+92dc0ff21b064f72560bec39afe6454e *R/animate.R
+853ac34ab3568c44d0326e6f89ccd68d *R/aspect3d.R
+df94371ac2c376befb4ddb0a6759af0f *R/axes.R
+8b2231cf74fa1b5302be2d5a6b6372d2 *R/bgplot3d.R
+ac4ab4a705386441e9b2b267244dca04 *R/callbacks.R
+03052da5ee72ea4d086fb4864878e35f *R/cylinder3d.R
+f83e313553f10c22ba366952058573bf *R/device.R
+5e855bf30c385ae3c1b662a862d3bb5a *R/ellipse3d.R
+cf746e286831527f2d8464802aed0e39 *R/enum.R
+ab542483bf671cb977c1680b2ad4568a *R/fonts.R
+7a8bf49f0116769eeeeadc33a9e257c2 *R/getscene.R
+bb2b4523126453a4617b5c753e3fc64c *R/grid3d.R
+ecdeca7d0766658fcb1189ce421c507d *R/identify3d.R
+f3867418939a2537a1480ae2a4d71126 *R/internal.R
+57795a5ea4d856c643fef7490c54476a *R/material.R
+a76f70f19e4e470afdac99d8173379b5 *R/matrices.R
+486aa71dba46d952b4019e3123655747 *R/mesh3d.R
+aabe16a4db2cb2ea47c771e8b84f8e89 *R/obj.R
+e7329453008644d2c2a8a474cc029c99 *R/oh3d.R
+9ed8cb0c40a57539861384a2b1f14b62 *R/par3d.R
+7dd311da50e2f1c9f264141e7ba8dcd5 *R/persp3d.R
+ca0f6afd6285375d5a8827fd3427d8b1 *R/plot3d.R
+af9a986f1752f610b392a47202f8cb59 *R/plugin.R
+79a52a922c71b43c80846e99d4beab3d *R/ply.R
+368f85f11145bc9522e071d492715e24 *R/r3d.rgl.R
+a82494d493925454323cd8102200995d *R/rgl.bringtotop.R
+f9809ffa8bab34eec585eba3c464491a *R/scene.R
+06ca697fc07bde9e5d06d936bb4ad5e9 *R/selectpoints3d.R
+aa9a2657ac58b40065c9926d32474ec7 *R/shapelist3d.R
+b8fcaff709d438c64fe31c712b04a30a *R/solids3d.R
+8dc214a6b3f270d593edfe45fe98f8b4 *R/stl.R
+ea7858f239f5b05f14d91a8d12e959ab *R/subdivision.mesh3d.R
+bdf9c3b07a395c078b6eaffeb79b7f60 *R/subscenes.R
+5bd916f84d651ec3c477700ea73ade49 *R/triangulate.R
+3447eb732f99d8015c8575c9a4e5077e *R/turn3d.R
+4019e0a87c9ec0cdb4b33a4b5b33634a *R/webGL.R
+f47ee03646e39a2c2a0c760f845b8078 *R/webGLcontrols.R
+5efd7ef0317fbcbb61bb85f87fce4700 *R/zzz.R
+e7996831955d45cd6c22631d1b5f482b *README
+7b89a396eeaff11c7633712daedbf021 *build/vignette.rds
+a6a183397bea52041e6eebb1e2609eb2 *cleanup
+8376b2299e2cf3b4b2bc5e0441b3d745 *configure
+2444ea34e44ac808c947509f88b4987e *configure.ac
+b1fc4079788ff0c2e7d0bd69721c9d0c *configure.win
+d86af288dff684f0ec416d0b74a9f1a0 *demo/00Index
+ae4a727a90b8e66e141906769a78404d *demo/abundance.r
+3e3a22e0505c12b6af3c02ab0c31e40f *demo/bivar.r
+88e4edcb3715776e731633a121078926 *demo/envmap.r
+8ac7af81caefec02b907eb42c1963a56 *demo/flag.R
+82060d1c5816aaf2f8bd19c81dd7d177 *demo/hist3d.r
+e0359e5a9fea398708925a890a856138 *demo/lollipop3d.R
+61c0c8ffa3ea434e77eea052edb8b61a *demo/lsystem.r
+c176e81cceb3b96d51330119fe4a69bc *demo/mouseCallbacks.R
+bb7b69a42a128d44ccc9232aa9b13eca *demo/regression.r
+82b233c31f47cb4e09662d9054f48fc4 *demo/rgl.r
+154cec7452c730564d63034357b897a0 *demo/shapes3d.R
+866ebfda71509e83a98a7a034e004269 *demo/stereo.R
+70324e9f3c6750f14dc5fdfe99003625 *demo/subdivision.r
+e04b25cceeb2128ebcd731be782f6d9e *inst/NEWS
+8c5d291e3f47c3395fff092f09f599b9 *inst/WebGL/template.html
+5bac46c36b13eac1302260ee06b16c0f *inst/demodata/population.dat
+5544dce93555cfaced50ee41283e9e58 *inst/demodata/region.dat
+feff7010f9f522214002265608f637ac *inst/doc/CanvasMatrix.js
+6178663d6c57d2f32a1f42ae5b4ec326 *inst/doc/WebGL.Rmd
+276180b5e44ba0ac17421bcf50166728 *inst/doc/WebGL.html
+a43773841e380f713b5206d03d9eef53 *inst/doc/rgl.Rmd
+615630eaf7eb4910ce4dcb9a4d981b6d *inst/doc/rgl.html
+b4ef592c88333c7c509dd74fcd1912d9 *inst/fonts/FreeMono.ttf
+867469f13ff81dec9adf2ae2f6ea2899 *inst/fonts/FreeSans.ttf
+dc0004a804503e126bc99998c7a1c677 *inst/fonts/FreeSerif.ttf
+6bce8d2ca5c1408d884dbabdaa06b42e *inst/textures/bump_dust.png
+ee4e831c7898e173f4303810bb962e04 *inst/textures/nightfire.png
+9bc95de401ad938293a31eeda3e634f9 *inst/textures/particle.png
+d0da68556f680ce0b2543bf7d528a3b8 *inst/textures/refmap.png
+d28cefd893c7df888fa432e7de20dd18 *inst/textures/rgl2.png
+67de745a59476bacb0c1be2078313f08 *inst/textures/sunsleep.png
+7080d7e4b8fce2d49ffb0b93313b973a *inst/textures/world.png
+26c41afa7c4554201ad8735d6cf7b3ab *inst/textures/worldsmall.png
+f93d86b65210d8f6e5f6a460bd2e256d *man/3dobjects.Rd
+36193edd2bf704e55ceeddbee64fc1ac *man/GramSchmidt.Rd
+e9bc0980d966600f346989489932253d *man/abclines.Rd
+20b13c30f7ebb52719caf1e5d950a14d *man/addNormals.Rd
+bdcf8375eaf8da09f3a479ad1ebcd665 *man/ageSetter.Rd
+65b24d9633bcc01ffa6fa3669bce6ea2 *man/aspect3d.Rd
+183627e084c7c208032a726536d1496e *man/attributes.Rd
+0cf6103623fa50a9279cc22d95c58a82 *man/axes3d.Rd
+550ac2cbf490eca10620e32be4ed5702 *man/bbox.Rd
+9002b792cbe9361484072d5924b0011d *man/bg.Rd
+44bcc64d7cc5caf6a96246184843db21 *man/bgplot3d.Rd
+1b8c90506228e7ebde8bed2feb54c2ae *man/callbacks.Rd
+34c5f36aad0b8b1b335c7a18b7d43c03 *man/check3d.Rd
+a2de782dfc00482e8beeaab90e004e43 *man/cylinder3d.Rd
+d9090b36676ab9ca34651bfbeb065216 *man/ellipse3d.Rd
+9341bca00a9c0c0170964684b215dbe7 *man/extrude3d.Rd
+b45b8c32e7731c5e6e886706da165451 *man/grid3d.Rd
+d4ab4c231c6bee4fb64778f48da0af03 *man/hook_rgl.Rd
+21fc712708f1c91188801630d568c427 *man/identify3d.Rd
+b01450ce1a78ff4ee2dd6cb749c7871a *man/light.Rd
+1e437c1601d4e195ef21877b85ad5cb3 *man/material.Rd
+7d57f553532670c6fb7e3dcc70afc75e *man/matrices.Rd
+60ef6811beea92beb03c488391fde59a *man/mesh3d.Rd
+8a3377db7f2cc5ce5ec7b2702761c35b *man/mfrow3d.Rd
+e70a34e3f2998e17d21caf686134d595 *man/observer3d.Rd
+3474678092d29421eb7f075335435ace *man/par3d.Rd
+dadfecaea140ed6ade5db10c4e150c46 *man/par3dinterp.Rd
+944801589884843a310907ae49cd9214 *man/persp3d.Rd
+93ff337035c1bc198a64ba51d04082b9 *man/persp3d.function.Rd
+7cae54c8a91e7a8e8d4ec0ae0823f372 *man/planes.Rd
+6ce301441c82ce57d32dc17affb388a4 *man/play3d.Rd
+51d81bc2e57d31519bd949ea1d0a6303 *man/plot3d.Rd
+ebc0b9d4e3956ffd0f6c7be6d8026043 *man/polygon3d.Rd
+4f2109b4c992a1811e3ab1365f7e5aa0 *man/postscript.Rd
+f8ee8a261f18f776c95d24b52e5a7683 *man/primitive.Rd
+dc0d895e9256056b493cb9ffacf33eed *man/propertySetter.Rd
+9a1f00cfcee7b35ed4a6bb068710d45e *man/r3d.Rd
+d4e5417c0c71b7789d9b9dcd34c911b1 *man/readSTL.Rd
+c1850ba50574ca2cb0cba4b39c6729e4 *man/rgl-internal.Rd
+99130e701de51fdcb670444476cc9742 *man/rgl-package.Rd
+96ec0d97c21724dffce48f8b041048b3 *man/rgl.Sweave.Rd
+377cbdac5434cadc5f5ef7c420b912a6 *man/rgl.bringtotop.Rd
+04539cf990a2b2f9a9b29e63ddc0cb76 *man/rgl.open.Rd
+37ed09923795b7aaf6a603e0420f3d86 *man/rgl.pixels.Rd
+4950beaac607cb06fdb40a96c98d7943 *man/rgl.select.Rd
+f0c6becdf88501d800daedb47458655a *man/rgl.useNULL.Rd
+eb39bd5b917064e17c1650fcbf600e53 *man/rgl.user2window.Rd
+44f1d74b906e924aa2383646cf2d7298 *man/scene.Rd
+0e84e27eb860aa6860cd59384d3c6d5f *man/scene3d.Rd
+b00012857289667a04f8a4e7d1fb724d *man/select3d.Rd
+aa00aee06c005e7cab45e5d213a1ac49 *man/selectpoints3d.Rd
+d71689c55996c3f624c5005eef65f77f *man/shapelist3d.Rd
+6167e9bcf217c971b217e9b2d85f5c69 *man/show2d.Rd
+9b86b26e37aeecb603a240a98fa3fe98 *man/snapshot.Rd
+97b4e51da2e8b3fb42d4da15509c8a1c *man/spheres.Rd
+5f61120678d8f38eef5ce8e6bffdc248 *man/spin3d.Rd
+439df94cebc4b49683b7f128f408666a *man/sprites.Rd
+1b7adc71a65e77bfa5357cfa77356430 *man/subdivision3d.Rd
+ce31e160db13ca4a6cebd877c62781c8 *man/subscene3d.Rd
+ba4f6386dc5690df779999495b6dde15 *man/subsceneInfo.Rd
+d5e4877306d55b96493dda8466d0e190 *man/surface.Rd
+d1dc2da38e4a718d48da8f6bb3730ffc *man/surface3d.Rd
+4cf34cec727de10e34c79b7c7a354590 *man/texts.Rd
+91734759b662229aca1cf379a5f7461f *man/triangulate.Rd
+67496ece74b19278232adbfdcbc40d1c *man/turn3d.Rd
+ddfd766c2131b58e6e3d9306bccfecd9 *man/viewpoint.Rd
+bd68d141e8b8053eee6a60c2a247662d *man/webGLcontrols.Rd
+18906fadefb3a0ec86750790d717d1da *man/writeOBJ.Rd
+f1d2b2c177293d4555d15f73abb78038 *man/writePLY.Rd
+9d377e3a0aa5819f7ea4b0da21a9747c *man/writeWebGL.Rd
+6d84d6f8a7d01e28e554663decb28967 *src/ABCLineSet.cpp
+4e93c61da331b4806ec9d481f17b47cb *src/ABCLineSet.h
+8c49ee4680b4c35df1166b40c1e69e8c *src/BBoxDeco.cpp
+6036e35683f44d9c752f86280dab247e *src/BBoxDeco.h
+ddb12d362a6ef5d6e7783b40caffa9f1 *src/Background.cpp
+155715f53cb395e9b5a9eeabd18d6da3 *src/Background.h
+07787092d891d8e841598acf6a1b267e *src/COPYING.GL2PS
+47e8a4a7e46351fe6e2659c4b7a23020 *src/ClipPlane.cpp
+3ba8e335135deb32583e586507a9db03 *src/ClipPlane.h
+92c8148c5c10e5ca9125a8fa6630d975 *src/Color.cpp
+3b231f79bf9228e58fd6fd658d2b4148 *src/Color.h
+ef44ecd70149fd1a8db74bea37073154 *src/Device.h
+c5bbe1cfd9588774823c353a17445231 *src/DeviceManager.h
+2fdf0fa29216eb97fff8bdf8c382da98 *src/Disposable.cpp
+b128eb378abdd8e63ea8287e7f9f6254 *src/Disposable.h
+ec3c3d5ec6c414702b1aca0f877ebebe *src/Light.cpp
+b03e2ab2e386594cd527d3cbad2b9f3a *src/Light.h
+70a705fe2978bd44a7a3db0a4c23dac5 *src/LineSet.cpp
+20e0919c074f065bca632ebce09636e3 *src/LineStripSet.cpp
+50ea12b8d68f27785bcd3f12795c5519 *src/Makevars.in
+990007f5f09f580ed175b8512a4bfe87 *src/Material.cpp
+5401f7c12f05bbfe42d8a646ec23495e *src/Material.h
+ed476450570763d8d9d2ffc76f9c4521 *src/NULLgui.cpp
+159a5bcfb884241441749baf6332fccb *src/NULLgui.h
+bba9b96f05da1669f40c04710a7e227d *src/PlaneSet.cpp
+1b510976127456879201e4e737a6fcb4 *src/PlaneSet.h
+63cabba14319bcaf9e15b9c65703ad4e *src/PointSet.cpp
+418bd6cc144844251966871e85756b21 *src/PrimitiveSet.cpp
+069cd2f8a8c94a7dc4f0b050d9f3a8a5 *src/PrimitiveSet.h
+a690ee6caf929116ca61fd2a97cd328e *src/R.h
+9dd4aa8ad74533c5cd129a03d93c81df *src/RenderContext.cpp
+2397bb9b330dc081bc2a8db7e8a6abcb *src/RenderContext.h
+6bc066169d8f88fe3f37ccd66c5711e9 *src/SceneNode.h
+3e7e2c4a716f4e1b978a5a9cad2371ff *src/Shape.cpp
+aad852a6ceba5afdc1236097f3bc17ec *src/Shape.h
+64f2c202ac923cf3bdc4edb720601439 *src/SphereMesh.cpp
+8003255fc83bb1d65cf1a4e9fec93898 *src/SphereMesh.h
+08cba2f2e8b2a26d1544bb8914022df4 *src/SphereSet.cpp
+e8735c2e620b730a21f69405c7682aea *src/SphereSet.h
+1cd2f5e7e424536f5029513c61b48641 *src/SpriteSet.cpp
+04d9ca4feb775d15bb0ce6c0ac6819ea *src/SpriteSet.h
+0b29e87abeba8671a0c4c5194d784a6b *src/String.cpp
+e9a31e14589146f498de32e1d7e1a706 *src/String.h
+7ed86344162a230d9e2cb26f1b7d52f6 *src/Surface.cpp
+efa53854024221fbe7a736fecc2f92a6 *src/Surface.h
+929430b988256eb8932956cb9869873b *src/TextSet.cpp
+eef1deddc0f22ebe8f8c34e139b32f62 *src/TextSet.h
+3edabc59652f715da748cc16eb58f92e *src/Texture.cpp
+57491612dd6fd9fd94519e1598a226b0 *src/Texture.h
+49f352b1355b0185b401d22c24d679ca *src/Viewpoint.cpp
+820bc232ed7b5fd0dac01ab5246026ad *src/Viewpoint.h
+cf49168c24b58fa6bf3a93ae327cd9e3 *src/api.cpp
+0c6947ff203bed73cbe033e6d7c1ecef *src/api.h
+bb5f3d08f63b9c2414e546a8b0afd335 *src/assert.cpp
+0e68374c29258e2b6fe6e88fa9b4958d *src/assert.h
+08478727a5b38779bc62b632166b9f7f *src/build/autoconf/config.guess
+b4b24b88055910a6b4dbb0f436af648e *src/build/autoconf/config.sub
+6e5fe73723cd40a28adc5b7b5650c8d1 *src/build/autoconf/install-sh
+43e64bf8f42f33eeeee8a2947d0a7c34 *src/callbacks.cpp
+bccfd3c1231fe09c743279715ed012b2 *src/config.h
+d45fe75de23128b1d44be991cbce841b *src/device.cpp
+adfc36a94a36e98cc5fbe2ad8a087db9 *src/devicemanager.cpp
+c83c1ea7f7c9b201cdcf087fa83d10ff *src/ext/GLsdk/GL/gl.h
+b3a541f71a25364db3f2128ecceb23cb *src/ext/GLsdk/GL/glext.h
+1d9b87c0753867872bde78597c327011 *src/ext/GLsdk/GL/glprocs.c
+2f815b593663fa05c0b4218da5e859f5 *src/ext/GLsdk/GL/glprocs.h
+7b7a17cf681ec55443208331ff7d2fa7 *src/ext/GLsdk/GL/wglext.h
+02bd9b0a9a5faf1589190ac51176a1c5 *src/ext/GLsdk/README
+3cdf0854d833c6aa64021c260776f3f7 *src/ext/GLsdk/glxdemo/Makefile
+a88d7c70039d75d1b7165b03c701c90e *src/ext/GLsdk/glxdemo/demo.c
+3919e1e751b49ca79d26a389ea6075c5 *src/ext/GLsdk/windemo/Makefile
+1a76796ea607f53471cf26be65754c87 *src/ext/GLsdk/windemo/README
+65fc121bbc52e6a33984ba1d2a28344c *src/ext/GLsdk/windemo/demogl.c
+c08368f55d809f294f0f5b8f65fff152 *src/ext/GLsdk/windemo/demogl.h
+a196c678e345d99dbfb3f321568da889 *src/ext/GLsdk/windemo/multithread/Makefile
+cc539fdc60be6768b85a7e21a949d15e *src/ext/GLsdk/windemo/multithread/demo.c
+8c37622620a17bbfe0ce031563efdc10 *src/ext/GLsdk/windemo/multiwin/Makefile
+ecbc58476e6d099e32553dcd1d8d54ea *src/ext/GLsdk/windemo/multiwin/demo.c
+66476d12bb3ea2a99ac8c86e93188e11 *src/ext/GLsdk/windemo/singlewin/Makefile
+eecd615847d389422cc5d70cdba4b0bc *src/ext/GLsdk/windemo/singlewin/demo.c
+dadfdb1523fa7cb2b605ca739d3dc7d8 *src/ext/ftgl/FTBuffer.cpp
+d3b0979057aa114e783a4d00348b3cba *src/ext/ftgl/FTCharToGlyphIndexMap.h
+df82479f6d77110ec9421d05a72bc22d *src/ext/ftgl/FTCharmap.cpp
+fbb46155bc03c58b0954c9c87b8c5489 *src/ext/ftgl/FTCharmap.h
+198a83b2cdc6c0c25dea814e9f87b287 *src/ext/ftgl/FTContour.cpp
+0df22d6e2afed2fa2c74b56d170666e3 *src/ext/ftgl/FTContour.h
+e3b1d4b91f5336ad1afed4bef3f7e60e *src/ext/ftgl/FTFace.cpp
+bc923b13aab60fc0d8345ce265d5c4f7 *src/ext/ftgl/FTFace.h
+6cee05988d95769959751a6bf982bcfa *src/ext/ftgl/FTFont/FTBitmapFont.cpp
+46cd76f77454183b656f840846f7962a *src/ext/ftgl/FTFont/FTBitmapFontImpl.h
+2a5ad552a3668fa622e598b74bcdf193 *src/ext/ftgl/FTFont/FTBufferFont.cpp
+e595560279739292d4040fc99ccb6f8d *src/ext/ftgl/FTFont/FTBufferFontImpl.h
+11894243a0b819ff86e47a32849cdb45 *src/ext/ftgl/FTFont/FTExtrudeFont.cpp
+c763a223ea70cb3c58aa0e5148d36091 *src/ext/ftgl/FTFont/FTExtrudeFontImpl.h
+9fe096169e2b693fb19392366db68da5 *src/ext/ftgl/FTFont/FTFont.cpp
+bda6bab0aef5e5df1db9aa5f96df4d3d *src/ext/ftgl/FTFont/FTFontGlue.cpp
+b8b501aceae7097953d3d3d07fb3f22d *src/ext/ftgl/FTFont/FTFontImpl.h
+578c3ed55e2991b90210e1f297a06d6f *src/ext/ftgl/FTFont/FTOutlineFont.cpp
+b30eda21f61429fb0a4680465f516237 *src/ext/ftgl/FTFont/FTOutlineFontImpl.h
+8ffaf4d3327d55283a9b7405e0a1c573 *src/ext/ftgl/FTFont/FTPixmapFont.cpp
+26853060924597f8ca076ae7d8e95752 *src/ext/ftgl/FTFont/FTPixmapFontImpl.h
+0f6d6e0fb2174d041b9f333a93ed1397 *src/ext/ftgl/FTFont/FTPolygonFont.cpp
+8fafdbb2666a3cc723e85bd6d4a6794a *src/ext/ftgl/FTFont/FTPolygonFontImpl.h
+fc9401eb562bf9f32c8a8b3dbd0f795b *src/ext/ftgl/FTFont/FTTextureFont.cpp
+516421d846a01598ea710a972aaae599 *src/ext/ftgl/FTFont/FTTextureFontImpl.h
+230bab96d6d850f1d33f2f1ad784a412 *src/ext/ftgl/FTGL/FTBBox.h
+9e4292443f1b1b93ca6b634bf6d987f0 *src/ext/ftgl/FTGL/FTBitmapGlyph.h
+f49bdff8007e603d0c82fdbda0c25d48 *src/ext/ftgl/FTGL/FTBuffer.h
+8c0b36ace135d7a55a97fdb6b663247d *src/ext/ftgl/FTGL/FTBufferFont.h
+9c8ee2aab0f0a76b4dccf143a046f965 *src/ext/ftgl/FTGL/FTBufferGlyph.h
+c6df401411611c571a953790afff6630 *src/ext/ftgl/FTGL/FTExtrdGlyph.h
+692a9fd4365ff11955e38a2e8feb6879 *src/ext/ftgl/FTGL/FTFont.h
+b1bdead397ff26e465fff6589b5c9830 *src/ext/ftgl/FTGL/FTGLBitmapFont.h
+e8548d181850f96793834feacd1c2856 *src/ext/ftgl/FTGL/FTGLExtrdFont.h
+da4d60ccfe6af055f6c7f66d381c5899 *src/ext/ftgl/FTGL/FTGLOutlineFont.h
+c8df9ea475390e02159833be3bdacc99 *src/ext/ftgl/FTGL/FTGLPixmapFont.h
+32ab997693e08eb0265e7195dfd439b8 *src/ext/ftgl/FTGL/FTGLPolygonFont.h
+0a03a39be54e5ef204c401b82cb536b5 *src/ext/ftgl/FTGL/FTGLTextureFont.h
+ce03934d2e2cf4bb3b0762c8ca8d150a *src/ext/ftgl/FTGL/FTGlyph.h
+0dafe4d5a2e125ab0a2edbc9bfd5936c *src/ext/ftgl/FTGL/FTLayout.h
+bc6155067c5c42eb06d1557df2e43cc2 *src/ext/ftgl/FTGL/FTOutlineGlyph.h
+ded998ac5c20d8811cfaa26eac09a650 *src/ext/ftgl/FTGL/FTPixmapGlyph.h
+992eddbbab7dfbd8eb5c15d6b876f14b *src/ext/ftgl/FTGL/FTPoint.h
+902a47c1182e16d9df04e047902d5ca1 *src/ext/ftgl/FTGL/FTPolyGlyph.h
+45b3c3fc72525a97df8314986e4760ab *src/ext/ftgl/FTGL/FTSimpleLayout.h
+4200c568f82b18dd5ea0c7b9ff30e9c6 *src/ext/ftgl/FTGL/FTTextureGlyph.h
+d8bdcc5af3624847c7309665736a3b8a *src/ext/ftgl/FTGL/ftgl.h
+c3c4abcfe56e325d430029e543fb4ce5 *src/ext/ftgl/FTGlyph/FTBitmapGlyph.cpp
+d2e52f923d89e7cfbe976b40037c088f *src/ext/ftgl/FTGlyph/FTBitmapGlyphImpl.h
+15cf3dce400cfa43d856ff827df54a3f *src/ext/ftgl/FTGlyph/FTBufferGlyph.cpp
+19af28d3ac6f2494166372082634f0a7 *src/ext/ftgl/FTGlyph/FTBufferGlyphImpl.h
+71ac13971b76de3508eb17827cd89da5 *src/ext/ftgl/FTGlyph/FTExtrudeGlyph.cpp
+21da928e25d0d370a2fac6af1b11e35d *src/ext/ftgl/FTGlyph/FTExtrudeGlyphImpl.h
+f017bd959547aaea736fc8a189eed2be *src/ext/ftgl/FTGlyph/FTGlyph.cpp
+568762d22d490f4140723be8fcbb2a55 *src/ext/ftgl/FTGlyph/FTGlyphGlue.cpp
+8a657973e2ce18aa4f4ab933acf9cb8c *src/ext/ftgl/FTGlyph/FTGlyphImpl.h
+45cb930c3377addd0eb4b36d0030fb2f *src/ext/ftgl/FTGlyph/FTOutlineGlyph.cpp
+653ea146597a007704711585ce3bb1cf *src/ext/ftgl/FTGlyph/FTOutlineGlyphImpl.h
+05cab235511ef9770ca0baa336e9753c *src/ext/ftgl/FTGlyph/FTPixmapGlyph.cpp
+d03c8a2e4118633d05661a4e97e44c47 *src/ext/ftgl/FTGlyph/FTPixmapGlyphImpl.h
+96a3b4a56383677889f9be218dccbf70 *src/ext/ftgl/FTGlyph/FTPolygonGlyph.cpp
+64f85eb98e1341f73e2aa96a2bdffb41 *src/ext/ftgl/FTGlyph/FTPolygonGlyphImpl.h
+2ae9cfe909e39faf9506958269f88b3b *src/ext/ftgl/FTGlyph/FTTextureGlyph.cpp
+eeedd5ced1be160b6ac16364d972c966 *src/ext/ftgl/FTGlyph/FTTextureGlyphImpl.h
+bde3d77f0b6fb23338977c08d94127dd *src/ext/ftgl/FTGlyphContainer.cpp
+72518f956e4124f14a3e3c7e56598928 *src/ext/ftgl/FTGlyphContainer.h
+7654111c5b48cdb929fba86311e3f82e *src/ext/ftgl/FTInternals.h
+e9bcef03564229b55c1f41e08b6deb29 *src/ext/ftgl/FTLayout/FTLayout.cpp
+63e9ec812b2e00b1e30dd2edd9225e16 *src/ext/ftgl/FTLayout/FTLayoutGlue.cpp
+923471cafec7828be0ac98e32654b0b7 *src/ext/ftgl/FTLayout/FTLayoutImpl.h
+bb750695c84dd48d2d7c9b1a55c2f78a *src/ext/ftgl/FTLayout/FTSimpleLayout.cpp
+2162c22bf4ab0dcecfce8a01df52840a *src/ext/ftgl/FTLayout/FTSimpleLayoutImpl.h
+c78f3e6fc5d8f1101ab4dbf9c39c8b2e *src/ext/ftgl/FTLibrary.cpp
+c89dd7f824e02ccb8f1417d9c749d14a *src/ext/ftgl/FTLibrary.h
+0bee532772a9a4e6731234ae4ad0e1dc *src/ext/ftgl/FTList.h
+0ad28cf7cb22082364ed3f7a757dbeac *src/ext/ftgl/FTPoint.cpp
+b44e9272b2622955623953a4e4f1519a *src/ext/ftgl/FTSize.cpp
+df0140033dc56cd6e35b2eb604c9be88 *src/ext/ftgl/FTSize.h
+b59a5cfe0e1c5e0506198a98f76a177b *src/ext/ftgl/FTUnicode.h
+66f64edb27e9343a06defee757372711 *src/ext/ftgl/FTVector.h
+022e12e6d95b7cecad4c1d869e2e9e7f *src/ext/ftgl/FTVectoriser.cpp
+f628642b6af28e07c8fff0a9464ba650 *src/ext/ftgl/FTVectoriser.h
+669126c660cd42496af6d02fe6a62741 *src/ext/ftgl/config.h
+ca5fc8b9582ffebd9baf824d9c37b7d3 *src/fps.cpp
+e5aa79236fa82468d5e415401e5ddd0f *src/fps.h
+1fdd71d5a6d05d33bf335c0c10283aba *src/ftgl.cpp
+8d50e9688f61e9298db1b86bdcf19fd8 *src/geom.cpp
+801de6ffecb85d9ad80257b168cfce48 *src/geom.h
+47c89c2fbae62d65ca73308469721f08 *src/gl2ps.c
+c2df43358f9dc57b02321b60feca6637 *src/gl2ps.h
+c22dabe5e4ff8257a905288ff35d01af *src/glErrors.cpp
+5040b4ccdd96de708170cfefd5b54af6 *src/glgui.cpp
+910b1ec13c167031ece01e7488397fe3 *src/glgui.h
+5ab05a5f288b7a9c7d690ad4d32387cc *src/gui.cpp
+2b8d8a5bba422113401c6ce5311129c2 *src/gui.h
+323a953ad8f25557b1dce1f0858d8da7 *src/init.cpp
+98b41399ac5f905f55cf3b051f7e7eae *src/init.h
+991226eae77aedeeb6cab28bcda90023 *src/lib.h
+77a8ca88c5a5ef57249475a4906932c4 *src/opengl.h
+f558e283f7aaba94b1a6acc0df11a494 *src/par3d.cpp
+c105329a33d82519ead8e6841a6110f7 *src/pixmap.cpp
+4823fcd47dff6930865d7fb056dd0b25 *src/pixmap.h
+56c23f46f775513981a5f8ae15e9a4e4 *src/platform.cpp
+990da172f3a90201bfc36f747d733427 *src/platform.h
+27ad47ba56a8785fa3c729983c8971ff *src/pngpixmap.h
+0f3cbcc107a805669552e140ede08ed7 *src/pragma.h
+92ea7a1b8a4633f4d0b1dfb3dfb60179 *src/pretty.c
+28ba9504069a992227eec0a430d4803e *src/pretty.h
+07d0048dff2eb0bd011ca3614a3132ec *src/render.cpp
+9682d9ed2f09de4c1e42f7be501190e7 *src/render.h
+d140e13b2a81bf64aca893a3de84c40f *src/rgl-win.def
+fe953c704bc921334d7f9a5dabda5dd1 *src/rglmath.cpp
+87a7067a1fe7250632e07d342c7f1f5d *src/rglmath.h
+181d701ef27887bd5a3fcc6ad2579972 *src/rglview.cpp
+df2d3d8bfc49477d4ff635f6367be958 *src/rglview.h
+6888e87fa9bafdd0cfbdb872ff833746 *src/scene.cpp
+52daa9d90b27b10fa738da5fceb577d8 *src/scene.h
+1d5d3cc76b12eab1f7be77c4e9564a39 *src/select.cpp
+f3fb1125c8e91830a0447f265c0d33e4 *src/select.h
+07a9ce77431b4643d379c95c86be9bef *src/subscene.cpp
+3461deb81bb709780b486b2cf57b907b *src/subscene.h
+b1c1e5e8d4dc94c9f6e3967575fab332 *src/types.h
+54ee84077be4682054b5e17097af5cb7 *src/win32gui.cpp
+922dbc57b271b783a941142f04d9b9c2 *src/win32gui.h
+ec44405ab8a3c4f584a6d4b33c53446f *src/win32lib.cpp
+182e39fe7fda9ef020b09506affbab4f *src/x11gui.cpp
+13bd0b1d57062d5715de47f204038a8c *src/x11gui.h
+8f57f7b292407932ab95440ceff7a637 *src/x11lib.cpp
+4da485d9aa2abecb68b5a099cd09ca5f *tests/demos.R
+6178663d6c57d2f32a1f42ae5b4ec326 *vignettes/WebGL.Rmd
+a43773841e380f713b5206d03d9eef53 *vignettes/rgl.Rmd
+c96592f71d957a9268ad7029c7af9fb9 *vignettes/setup.R
diff --git a/NAMESPACE b/NAMESPACE
new file mode 100644
index 0000000..143d941
--- /dev/null
+++ b/NAMESPACE
@@ -0,0 +1,94 @@
+export(.check3d, 
+        abclines3d, addNormals, addToSubscene3d, 
+        ageSetter, asEuclidean, asHomogeneous, aspect3d, axes3d, axis3d, box3d,
+        bbox3d, bg3d, bgplot3d, 
+	clear3d, clearSubsceneList, clipplanes3d, clipplaneSlider, cube3d, cuboctahedron3d, 
+        currentSubscene3d, cylinder3d,
+        decorate3d, delFromSubscene3d, dodecahedron3d, dot3d, ellipse3d, extrude3d,
+	gc3d, getr3dDefaults, GramSchmidt, grid3d, 
+	hook_rgl, hook_webgl,
+	icosahedron3d, identify3d, identityMatrix,  
+	layout3d, legend3d, light3d, lines3d, material3d, 
+        matrixSetter, mfrow3d, movie3d, mtext3d, 
+	newSubscene3d, next3d, observer3d, octahedron3d, oh3d, open3d, 
+	par3d, par3dinterp, par3dinterpSetter, particles3d, persp3d, planes3d, 
+        play3d, plot3d, points3d, 
+	polygon3d, pop3d, propertySetter, propertySlider,
+	qmesh3d, quads3d, readOBJ, readSTL, rgl.abclines, rgl.bbox, rgl.bg, rgl.bringtotop, rgl.clear,
+	rgl.getMouseCallbacks, rgl.getWheelCallback,
+	rgl.close, rgl.cur, rgl.ids, rgl.init, rgl.light, rgl.lines, rgl.linestrips,
+	rgl.clipplanes, rgl.material, rgl.open, rgl.pixels, rgl.planes, rgl.points, rgl.pop, rgl.postscript,
+	rgl.primitive, rgl.projection, rgl.quads, rgl.quit, rgl.Sweave, rgl.Sweave.off,
+	rgl.select, rgl.select3d, rgl.set, rgl.snapshot, rgl.spheres, rgl.sprites,
+	rgl.surface, rgl.texts, rgl.triangles, rgl.user2window,
+	rgl.attrib, rgl.attrib.count, rgl.dev.list, rgl.useNULL,
+	rgl.viewpoint, rgl.window2user, rglFonts, r3dDefaults, rotate3d, rotationMatrix,
+	scale3d, scaleMatrix, scene3d, segments3d, select3d, selectpoints3d,
+	rgl.setMouseCallbacks, rgl.setWheelCallback, setupKnitr, shade3d, 
+	shapelist3d, show2d, snapshot3d, 
+	spheres3d, spin3d, sprites3d, subdivision3d, 
+	subsceneInfo, subsceneList, subsetSetter, subsetSlider, Sweave.snapshot,
+	surface3d, terrain3d, 
+	tetrahedron3d, text3d,
+	texts3d, title3d, toggleButton, triangulate, 
+	tmesh3d, transform3d, translate3d, translationMatrix, triangles3d,
+	turn3d, useSubscene3d, vertexSetter, view3d, wire3d, writeOBJ, writePLY, writeSTL, writeWebGL)
+
+ S3method(dot3d, shapelist3d)
+ S3method(wire3d, shapelist3d)
+ S3method(shade3d, shapelist3d)  
+ S3method(translate3d, shapelist3d)
+ S3method(rotate3d, shapelist3d)
+ S3method(scale3d, shapelist3d)
+ S3method(addNormals, shapelist3d)
+ 
+ S3method(dot3d, mesh3d)
+ S3method(translate3d, mesh3d)
+ S3method(rotate3d, mesh3d)
+ S3method(scale3d, mesh3d)
+ 
+ S3method(wire3d, mesh3d)
+ S3method(shade3d, mesh3d) 
+ S3method(subdivision3d, mesh3d)
+ S3method(addNormals, mesh3d)
+ 
+ S3method(plot3d, mesh3d)
+ 
+ S3method(translate3d, default)
+ S3method(rotate3d, default)
+ S3method(scale3d, default)
+ 
+ S3method(ellipse3d, default)
+ S3method(ellipse3d, lm)
+ S3method(ellipse3d, glm)
+ S3method(ellipse3d, nls)
+ 
+ S3method(plot3d, default)
+ S3method(persp3d, default)
+ S3method(persp3d, "function")
+ 
+ S3method(plot3d, rglscene)
+ S3method(plot3d, rglobject)
+ S3method(plot3d, rglbboxdeco)
+ S3method(plot3d, rglbackground)
+ S3method(plot3d, rglsubscene)
+ S3method(plot3d, "function")
+ 
+ S3method(print, rglscene)
+ S3method(print, rglobject)
+ S3method(print, rglsubscene)
+ S3method(print, indexedSetter)
+ 
+ S3method(summary, rglscene)
+ S3method(summary, rglsubscene)
+ 
+ if(.Platform$OS.type == "windows") {
+   importFrom(utils, getWindowsHandle)
+ }
+ 
+ importFrom(graphics, legend, par, plot, polygon)
+ importFrom(grDevices, col2rgb, colorRamp, dev.off, png, 
+ 	    postscript, rgb, xy.coords, xyz.coords)
+ importFrom(stats, approxfun, qchisq, qf, splinefun, var)
+ importFrom(utils, file_test, flush.console,
+ 	    packageVersion, read.table)
diff --git a/R/Sweave_knitr.R b/R/Sweave_knitr.R
new file mode 100644
index 0000000..c133681
--- /dev/null
+++ b/R/Sweave_knitr.R
@@ -0,0 +1,98 @@
+##
+## Sweave device
+##
+##
+
+rgl.Sweave <- function(name, width, height, options, ...) {
+
+  # The 2.13.0 release called dev.off(), not rgl.Sweave.off()
+  
+  if (getRversion() == "2.13.0" && version$status == "") {
+  
+    postscript(tempfile()) # make dev.off() happy
+    if (length(getHook("on.rgl.close"))) rgl.Sweave.off() # to close the previous chunk
+  }
+  
+  if (length(hook <- getHook("on.rgl.close"))) {
+    if (is.list(hook)) hook <- hook[[1]]  # test is for compatibility with R < 3.0.0
+    dev <- environment(hook)$dev
+    rgl.set(dev)
+  } else {
+    wr <- c(0, 0, width*options$resolution, height*options$resolution)
+    open3d(windowRect=wr)
+    if (is.null(delay <- options$delay)) delay <- 0.1
+    Sys.sleep(as.numeric(delay))
+    wrnew <- par3d("windowRect")
+    if (wr[3] - wr[1] != wrnew[3] - wrnew[1] || 
+        wr[4] - wr[2] != wrnew[4] - wrnew[2])
+      stop("rgl window creation error; try reducing resolution, width or height")
+    dev <- rgl.cur()
+  } 
+  
+  snapshotDone <- FALSE
+  
+  stayOpen <- isTRUE(options$stayopen)
+  
+  type <- options$outputtype
+  if (is.null(type)) type <- "png"
+  
+  setHook("on.rgl.close", action="replace", function(remove=TRUE) {
+    prev.dev <- rgl.cur()
+    on.exit(rgl.set(prev.dev))
+    
+    if (!snapshotDone) {
+      rgl.set(dev)
+      switch(type,
+        png = rgl.snapshot(filename=paste(name, "png", sep=".")),
+        pdf = rgl.postscript(filename=paste(name, "pdf", sep="."), fmt="pdf"),
+        eps = rgl.postscript(filename=paste(name, "eps", sep="."), fmt="eps"),
+        stop(gettextf("Unrecognized rgl outputtype: '%s'", type), domain = NA)
+      )
+      snapshotDone <<- TRUE
+    }
+    
+    if (remove)
+      setHook("on.rgl.close", action="replace", NULL)
+  })
+}
+
+rgl.Sweave.off <- function() {
+  if (length(hook <- getHook("on.rgl.close"))) {
+    if (is.list(hook)) hook <- hook[[1]] # test is for R pre-3.0.0 compatibility
+    stayOpen <- environment(hook)$stayOpen
+    if (stayOpen) hook(FALSE)
+    else rgl.close()
+  }
+}
+  
+##
+## Sweave snapshot
+## 
+##
+
+Sweave.snapshot <- function() {
+  if (length(hook <- getHook("on.rgl.close"))) {
+    if (is.list(hook)) hook <- hook[[1]] # test is for R pre-3.0.0 compatibility
+    hook(remove = FALSE)
+  }
+}
+
+##
+## knitr hook functions
+##
+##
+
+hook_webgl <- function(before, options, envir) {
+  rglwidgetCheck()
+  rglwidget::.hook_webgl(before, options, envir)
+}
+
+hook_rgl <- function(before, options, envir) {
+  rglwidgetCheck()
+  rglwidget::.hook_rgl(before, options, envir)
+}
+
+setupKnitr <- function() {
+  rglwidgetCheck()
+  rglwidget::.setupKnitr()
+}
diff --git a/R/addNormals.mesh3d.R b/R/addNormals.mesh3d.R
new file mode 100644
index 0000000..14fe788
--- /dev/null
+++ b/R/addNormals.mesh3d.R
@@ -0,0 +1,52 @@
+addNormals <- function(x, ...) UseMethod("addNormals")
+  
+addNormals.mesh3d <- function(x, ...) {
+  v <- x$vb
+  
+  # Make sure v is homogeneous with unit w
+  if (nrow(v) == 3) v <- rbind(v, 1)
+  else v <- t( t(v)/v[4,] )
+  
+  normals <- v*0
+  v <- v[1:3,]
+  
+  if (length(x$it)) {
+    it <- x$it
+    for (i in 1:ncol(it)) {
+      normal <- normalize(xprod( v[, it[1, i]] - v[, it[3, i]], 
+                                 v[, it[2, i]] - v[, it[1, i]]))
+      for (j in 1:3) {
+      	if (sum(normals[1:3, it[j,i]]*normal) < 0)
+      	  normals[, it[j,i]] <- normals[, it[j,i]] + c(-normal, 1)
+      	else
+          normals[, it[j,i]] <- normals[, it[j,i]] + c(normal, 1)
+      }
+    }
+  }
+  
+  if (length(x$ib)) {
+    it <- x$ib
+    for (i in 1:ncol(it)) {
+      normal <- normalize(xprod( v[, it[1, i]] - v[, it[4, i]],
+                                 v[, it[2, i]] - v[, it[1, i]]))
+      for (j in 1:4) {
+      	if (sum(normals[1:3, it[j,i]]*normal) < 0)
+      	  normals[, it[j,i]] <- normals[, it[j,i]] + c(-normal, 1)
+      	else
+          normals[, it[j,i]] <- normals[, it[j,i]] + c(normal, 1)
+      }
+
+    }
+  }
+  normals <- t( t(normals)/normals[4,] )
+  x$normals <- normals
+  x
+}
+
+veclen <- function(v) sqrt(sum(v^2))
+
+normalize <- function(v) v/veclen(v)
+
+xprod <- function(v, w) c( v[2]*w[3] - v[3]*w[2],
+                           v[3]*w[1] - v[1]*w[3],
+                           v[1]*w[2] - v[2]*w[1] )
diff --git a/R/animate.R b/R/animate.R
new file mode 100644
index 0000000..eb0af57
--- /dev/null
+++ b/R/animate.R
@@ -0,0 +1,206 @@
+# These quaternion functions are adapted from the orientlib package
+
+# Convert an array of rotation matrices to a matrix of unit quaternions
+toQuaternions <- function(x) {
+    nicesqrt <- function(x) sqrt(pmax(x,0))
+    q4 <- nicesqrt((1 + x[1,1,] + x[2,2,] + x[3,3,])/4)  # may go negative by rounding
+    zeros <- zapsmall(q4) == 0 
+    q1 <- ifelse(!zeros, (x[2,3,] - x[3,2,])/4/q4, nicesqrt(-(x[2,2,]+x[3,3,])/2))
+    q2 <- ifelse(!zeros, (x[3,1,] - x[1,3,])/4/q4, 
+    			 ifelse(zapsmall(q1) != 0, x[1,2,]/2/q1, nicesqrt((1-x[3,3,])/2)))
+    q3 <- ifelse(!zeros, (x[1,2,] - x[2,1,])/4/q4, 
+    			 ifelse(zapsmall(q1) != 0, x[1,3,]/2/q1, 
+    				ifelse(zapsmall(q2) != 0, x[2,3,]/2/q2, 1)))
+    cbind(q1, q2, q3, q4)
+}
+
+# Convert a single quaternion to a rotation matrix
+
+toRotmatrix <- function(x) {
+    x <- x/sqrt(sum(x^2))
+    matrix(c(1-2*x[2]^2-2*x[3]^2, 
+	      2*x[1]*x[2]-2*x[3]*x[4],
+	      2*x[1]*x[3]+2*x[2]*x[4],
+	      2*x[1]*x[2]+2*x[3]*x[4],
+    	      1-2*x[1]^2-2*x[3]^2,
+    	      2*x[2]*x[3] - 2*x[4]*x[1],
+    	      2*x[1]*x[3] - 2*x[2]*x[4],
+    	      2*x[2]*x[3] + 2*x[1]*x[4],
+    	      1 - 2*x[1]^2 - 2*x[2]^2), 3,3)
+}
+
+par3dinterp <- function(times=NULL, userMatrix, scale, zoom, FOV, method=c("spline", "linear"), 
+                     extrapolate = c("oscillate","cycle","constant", "natural"),
+                     dev = rgl.cur(), subscene = currentSubscene3d(dev)) {  
+    force(dev)
+    force(subscene)
+    
+    if (is.list(times)) {
+    	for (n in setdiff(names(times), "times")) assign(n, times[[n]])
+    	if ("times" %in% names(times)) times <- times[["times"]]
+    	else times <- NULL
+    }
+    
+    if (!missing(userMatrix) && is.list(userMatrix)) userMatrix <- do.call(cbind, userMatrix)
+    if (!missing(scale) && is.list(scale)) scale <- do.call(rbind, scale)
+    if (!missing(zoom) && is.list(zoom)) zoom <- unlist(zoom)
+    if (!missing(FOV) && is.list(FOV)) FOV <- unlist(FOV)
+    
+    if (is.null(times)) {
+    	times <- if (!missing(userMatrix)) 0:(length(userMatrix)/16 - 1)
+    	    else if (!missing(scale)) 0:(dim(scale)[1] - 1)
+    	    else if (!missing(zoom)) 0:(length(zoom) - 1)
+    	    else if (!missing(FOV)) 0:(length(FOV) - 1)
+    }
+    data <- matrix(0, length(times), 0)
+    if (!missing(userMatrix)) {
+	stopifnot( length(userMatrix) == 16*length(times) )
+	userMatrix <- array(userMatrix, c(4,4,length(times)))
+	xlat <- ncol(data) + 1:4
+	data <- cbind(data, t(userMatrix[,4,]))
+	persp <- ncol(data) + 1:3
+	data <- cbind(data, t(userMatrix[4,1:3,]))
+	rot <- ncol(data) + 1:4
+	data <- cbind(data, toQuaternions(userMatrix[1:3,1:3,]))
+    } else {
+        xlat <- NULL
+    }
+    if (!missing(scale)) {
+    	stopifnot( dim(scale)[1] == length(times) )
+    	sc <- ncol(data) + 1:3
+    	data <- cbind(data, log(scale))
+    } else sc <- NULL
+    if (!missing(zoom)) {
+    	stopifnot( length(zoom) == length(times) )
+    	zm <- ncol(data) + 1
+    	data <- cbind(data, log(zoom))
+    } else zm <- NULL
+    if (!missing(FOV)) {
+        stopifnot( length(FOV) == length(times) )
+        fov <- ncol(data) + 1
+        data <- cbind(data, FOV)
+    } else fov <- NULL
+    
+    method <- match.arg(method)
+    extrapolate <- match.arg(extrapolate)
+    if (extrapolate == "oscillate") {
+        n <- length(times)
+    	times <- c(times[-n], -rev(times) + 2*times[length(times)])
+    	data <- rbind(data[-n,,drop=FALSE], data[n:1,,drop=FALSE])
+    	n <- 2*n - 1
+    	extrapolate <- "cycle"
+    } else if (extrapolate == "natural" && method != "spline")
+    	stop("'natural' extrapolation only supported for spline method")
+    
+    if (method == "spline") {
+    	fns <- apply(data, 2, function(col) splinefun(times, col, 
+    	                         method = ifelse(extrapolate == "cycle", "periodic", "natural")))
+    } else {
+    	fns <- apply(data, 2, function(col) approxfun(times, col, rule=2))
+    }
+    
+    mintime <- min(times)
+    maxtime <- max(times)
+    
+    function(time) {
+        if (time < mintime || time > maxtime) {
+            if (extrapolate == "constant")
+            	time <- ifelse(time < mintime, mintime, maxtime)
+            else if (extrapolate == "cycle")
+                time <- (time - mintime) %% (maxtime - mintime) + mintime
+        }
+    	data <- sapply(fns, function(f) f(time))
+    	result <- list(dev = dev, subscene = subscene)
+    	if (!is.null(xlat)) {
+    	    userMatrix <- matrix(0, 4,4)
+    	    userMatrix[,4] <- data[xlat]
+    	    userMatrix[4,1:3] <- data[persp]
+    	    userMatrix[1:3,1:3] <- toRotmatrix(data[rot])
+    	    result$userMatrix <- userMatrix
+    	}
+    	if (!is.null(sc)) 
+    	    result$scale <- exp(data[sc])
+    	if (!is.null(zm))
+    	    result$zoom <- exp(data[zm])
+    	if (!is.null(fov))
+    	    result$FOV <- data[fov]
+    	result
+    }
+}
+
+spin3d <- function(axis = c(0, 0, 1), rpm = 5, dev = rgl.cur(), subscene = currentSubscene3d(dev)) {
+    force(axis)
+    force(rpm)    
+    force(dev)
+    force(subscene)
+    M <- par3d("userMatrix", dev = dev, subscene = subscene)
+    function(time, base = M) 
+    	list(userMatrix = rotate3d(base, time*rpm*pi/30, axis[1], axis[2], axis[3]), dev = dev, subscene = subscene)
+}
+    
+play3d <- function(f, duration = Inf, dev = rgl.cur(), ..., startTime = 0) {
+    # Don't want to start timing until args are known: they may be obtained
+    # interactively
+    force(f)  
+    force(duration)
+    force(dev)
+    start <- proc.time()[3] - startTime
+    rgl.setselectstate("none")
+    repeat {
+       if(!missing(dev) && rgl.cur() != dev) rgl.set(dev)
+       time <- proc.time()[3] - start
+       if (time > duration || rgl.selectstate()$state == msABORT) return(invisible(NULL))
+       stopifnot(rgl.cur() != 0)
+       par3d(f(time, ...))
+    }
+}
+
+movie3d <- function(f, duration, dev = rgl.cur(), ..., fps=10, 
+                    movie = "movie", frames = movie, dir = tempdir(), 
+                    convert = TRUE, clean = TRUE, verbose=TRUE,
+                    top = TRUE, type = "gif", startTime = 0) {
+    
+    olddir <- setwd(dir)
+    on.exit(setwd(olddir))
+
+    for (i in round(startTime*fps):(duration*fps)) {
+	time <- i/fps        
+	if(rgl.cur() != dev) rgl.set(dev)
+	stopifnot(rgl.cur() != 0)
+	par3d(f(time, ...))
+	filename <- sprintf("%s%03d.png",frames,i)
+	if (verbose) {
+	    cat(gettextf("Writing '%s'\r", filename))
+	    flush.console()
+	}
+        rgl.snapshot(filename=filename, fmt="png", top=top)
+    }	
+    cat("\n")
+    if (.Platform$OS.type == "windows") system <- shell
+    if (is.logical(convert) && convert) {
+        # Check for ImageMagick
+        version <- system("convert --version", intern=TRUE)
+        if (!length(grep("ImageMagick", version)))
+            stop("'ImageMagick' not found")    
+        filename <- paste(movie, ".", type, sep="")
+        if (verbose) cat(gettextf("Will create: %s\n", file.path(dir, filename)))
+        convert <- "convert -delay 1x%d %s*.png %s.%s"
+    }
+    if (is.character(convert)) {
+    	convert <- sprintf(convert, fps, frames, movie, type, duration, dir)
+	if (verbose) {
+	    cat(gettextf("Executing: '%s'\n", convert))
+	    flush.console()
+	}
+	system(convert)
+	if (clean) {
+	    if (verbose)
+	    	cat(gettext("Deleting frames\n"))
+	    for (i in 0:(duration*fps)) {
+	    	filename <- sprintf("%s%03d.png",frames,i)
+	    	unlink(filename)
+	    }
+	}
+    }
+}
+
diff --git a/R/aspect3d.R b/R/aspect3d.R
new file mode 100644
index 0000000..49fdb26
--- /dev/null
+++ b/R/aspect3d.R
@@ -0,0 +1,24 @@
+aspect3d <- function(x, y = NULL, z = NULL) {
+    if (is.character(x) && pmatch(x, "iso") == 1) {
+    	scale <- c(1,1,1)
+    } else {
+	if (is.null(y)) {
+	    x <- rep(x, len=3)
+	    z <- x[3]
+	    y <- x[2]
+	    x <- x[1]
+	}
+        for (i in 1:5) { # To handle spheres, repeat this 
+  	    bbox <- .getRanges()
+	    scale <- c(diff(bbox$xlim), diff(bbox$ylim), diff(bbox$zlim))
+	    scale <- ifelse(scale <= 0, 1, scale)
+
+	    avgscale <- sqrt(sum(scale^2)/3)
+            scale <- c(x,y,z)*avgscale/scale
+            oldscale <- par3d(scale = scale)$scale
+            if (isTRUE(all.equal(scale, oldscale)))
+            	break
+        }
+    }
+    par3d(scale = scale)
+}
diff --git a/R/axes.R b/R/axes.R
new file mode 100644
index 0000000..1f3d589
--- /dev/null
+++ b/R/axes.R
@@ -0,0 +1,199 @@
+# This internal function returns a list with the following components:
+# xlim, ylim, zlim:  the bounding box expanded so no coordinate has zero or negative extent
+# strut:  a boolean indicating whether an expansion was done above
+# x, y, z:  the box above expanded by a factor of expand
+
+.getRanges <- function(expand = 1.03, ranges=par3d('bbox')) {
+    ranges <- list(xlim=ranges[1:2], ylim=ranges[3:4], zlim=ranges[5:6])
+
+    strut <- FALSE
+    
+    ranges <- lapply(ranges, function(r) {
+                       d <- diff(r)
+                       if (d > 0) return(r)
+                       strut <<- TRUE
+                       if (d < 0) return(c(0,1))
+                       else if (r[1] == 0) return(c(-1, 1))
+                       else return(r[1] + 0.4*abs(r[1])*c(-1,1))
+                     })
+                     
+    ranges$strut <- strut
+    
+    ranges$x <- (ranges$xlim - mean(ranges$xlim))*expand + mean(ranges$xlim)
+    ranges$y <- (ranges$ylim - mean(ranges$ylim))*expand + mean(ranges$ylim)
+    ranges$z <- (ranges$zlim - mean(ranges$zlim))*expand + mean(ranges$zlim)
+   
+    ranges
+}
+
+axis3d <- function (edge, at = NULL, labels = TRUE, tick = TRUE, line = 0,
+    pos = NULL, nticks = 5, ...)
+{
+        save <- par3d(skipRedraw = TRUE, ignoreExtent = TRUE)
+        on.exit(par3d(save))
+        
+	ranges <- .getRanges()
+
+	edge <- c(strsplit(edge, '')[[1]], '-', '-')[1:3]
+	coord <- match(toupper(edge[1]), c('X', 'Y', 'Z')) 
+	
+	# Put the sign in the appropriate entry of edge
+	if (coord == 2) edge[1] <- edge[2]
+	else if (coord == 3) edge[1:2] <- edge[2:3]
+	
+        range <- ranges[[coord]]
+
+        if (is.null(at)) {
+                at <- pretty(range, nticks)
+                at <- at[at >= range[1] & at <= range[2]]
+        }
+
+        if (is.logical(labels)) {
+                if (labels) labels <- format(at)
+                else labels <- NA
+        }
+
+	mpos <- matrix(NA,3,length(at))
+	if (edge[1] == '+') mpos[1,] <- ranges$x[2]
+	else mpos[1,] <- ranges$x[1]
+	if (edge[2] == '+') mpos[2,] <- ranges$y[2]
+	else mpos[2,] <- ranges$y[1]
+	if (edge[3] == '+') mpos[3,] <- ranges$z[2]
+	else mpos[3,] <- ranges$z[1]
+                
+        ticksize <- 0.05*(mpos[,1]-c(mean(ranges$x),mean(ranges$y),mean(ranges$z)))
+        ticksize[coord] <- 0
+               
+        if (!is.null(pos)) mpos <- matrix(pos,3,length(at))
+        mpos[coord,] <- at
+
+        x <- c(mpos[1,1],mpos[1,length(at)])
+        y <- c(mpos[2,1],mpos[2,length(at)])
+        z <- c(mpos[3,1],mpos[3,length(at)])
+        if (tick) {
+                x <- c(x,as.double(rbind(mpos[1,],mpos[1,]+ticksize[1])))
+                y <- c(y,as.double(rbind(mpos[2,],mpos[2,]+ticksize[2])))
+                z <- c(z,as.double(rbind(mpos[3,],mpos[3,]+ticksize[3])))
+        }
+        result <- c(ticks=segments3d(x,y,z,...))
+
+        if (!all(is.na(labels)))
+                result <- c(result, labels=text3d(mpos[1,]+3*ticksize[1],
+                       mpos[2,]+3*ticksize[2],
+                       mpos[3,]+3*ticksize[3],
+                       labels, ...))
+	invisible(result)
+}
+
+axes3d <- function(edges='bbox', labels=TRUE,
+                   tick=TRUE, nticks = 5, box = FALSE, expand = 1.03, ...)
+{
+    save <- par3d(skipRedraw = TRUE, ignoreExtent = TRUE)
+    on.exit(par3d(save))
+    if (identical(edges, 'bbox')) {
+        result <- do.call('bbox3d', c(list(nticks=nticks, draw_front=box, expand=expand), 
+                                      .fixMaterialArgs(..., Params = list(front='lines', back='lines'))))
+    } else {
+        result <- numeric(0)
+    	for (e in edges)
+            result <- c(result, axis3d(e,labels=labels,tick=tick,nticks=nticks, ...))
+	names(result) <- e
+    }	
+    invisible(result)  
+}
+
+box3d <- function(...)
+{
+        save <- par3d(ignoreExtent = TRUE)        
+        on.exit(par3d(save))
+        
+        result <- numeric(0)
+        
+        ranges <- .getRanges()          
+        if (ranges$strut) {
+            par3d(ignoreExtent = FALSE)
+            result <- c(result, strut=segments3d(rep(ranges$xlim, c(2,2)),
+                       rep(ranges$ylim, c(2,2)),
+                       rep(ranges$zlim, c(2,2))))
+            par3d(ignoreExtent = TRUE)
+        }
+                       
+        x <- c(rep(ranges$x[1],8),rep(ranges$x,4),rep(ranges$x[2],8))
+        y <- c(rep(ranges$y,2),rep(ranges$y,c(2,2)),rep(ranges$y,c(4,4)),
+               rep(ranges$y,2),rep(ranges$y,c(2,2)))
+        z <- c(rep(ranges$z,c(2,2)),rep(ranges$z,2),rep(rep(ranges$z,c(2,2)),2),
+               rep(ranges$z,c(2,2)),rep(ranges$z,2))
+        invisible(c(result, lines=segments3d(x,y,z,...)))
+}
+
+mtext3d <- function(text, edge, line = 0, at = NULL, pos = NA, ...)
+{
+        save <- par3d(ignoreExtent = TRUE)
+        on.exit(par3d(save))
+
+        ranges <- .getRanges()
+        
+	edge <- c(strsplit(edge, '')[[1]], '-', '-')[1:3]
+	coord <- match(toupper(edge[1]), c('X', 'Y', 'Z')) 
+	
+	# Put the sign in the appropriate entry of edge
+	if (coord == 2) edge[1] <- edge[2]
+	else if (coord == 3) edge[1:2] <- edge[2:3]
+
+        range <- ranges[[coord]]
+
+        if (is.null(at)) at <- mean(range)
+
+        newlen <- max(length(text),length(line),length(at))
+        text <- rep(text, len = newlen)
+        line <- rep(line, len = newlen)
+        at <- rep(at, len = newlen)
+
+        if (all(is.na(pos))) {
+                pos <- matrix(NA,3,length(at))
+                if (edge[1] == '+') pos[1,] <- ranges$x[2]
+                else pos[1,] <- ranges$x[1]
+                if (edge[2] == '+') pos[2,] <- ranges$y[2]
+                else pos[2,] <- ranges$y[1]
+                if (edge[3] == '+') pos[3,] <- ranges$z[2]
+                else pos[3,] <- ranges$z[1]
+        }
+        else pos <- matrix(pos,3,length(at))
+        pos[coord,] <- at
+        ticksize <- 0.05*(pos[,1]-c(mean(ranges$x),mean(ranges$y),mean(ranges$z)))
+        ticksize[coord] <- 0
+
+        invisible(text3d(pos[1,]+3*ticksize[1]*line,
+               pos[2,]+3*ticksize[2]*line,
+               pos[3,]+3*ticksize[3]*line,
+               text, ...))
+}   
+
+title3d <- function (main = NULL, sub = NULL, xlab = NULL, ylab = NULL, 
+    zlab = NULL, line = NA, ...) 
+{
+        save <- par3d(skipRedraw = TRUE, ignoreExtent = TRUE)
+        on.exit(par3d(save))
+	result <- numeric(0)
+        if (!is.null(main)) {
+            aline <- ifelse(is.na(line), 2, line)
+            result <- c(result, main=mtext3d(main, 'x++', line = aline, ...))
+        }
+        if (!is.null(sub)) {
+            aline <- ifelse(is.na(line), 3, line)
+            result <- c(result, sub=mtext3d(sub, 'x', line = aline, ...))
+        }
+        if (!is.null(xlab)) {
+            aline <- ifelse(is.na(line), 2, line)
+            result <- c(result, xlab=mtext3d(xlab, 'x', line = aline, ...))
+        }
+        if (!is.null(ylab)) {
+            aline <- ifelse(is.na(line), 2, line)
+            result <- c(result, ylab=mtext3d(ylab, 'y', line = aline, ...))
+        }
+        if (!is.null(zlab)) {
+            aline <- ifelse(is.na(line), 2, line)
+            result <- c(result, zlab=mtext3d(zlab, 'z', line = aline, ...))
+        }                  
+        invisible(result)
+}
diff --git a/R/bgplot3d.R b/R/bgplot3d.R
new file mode 100644
index 0000000..f549b30
--- /dev/null
+++ b/R/bgplot3d.R
@@ -0,0 +1,115 @@
+legend3d <- function(...) {
+  result <- bgplot3d({
+    par(mar=c(0,0,0,0))
+    plot(0,0, type="n", xlim=0:1, ylim=0:1, xaxs="i", yaxs="i", axes=FALSE, bty="n")
+    legend(...)
+  })
+  invisible(result)
+}
+
+bgplot3d <- function(expression) {
+  viewport <- par3d("viewport")
+  width <- viewport["width"]
+  height <- viewport["height"]
+  if (width > 0 && height > 0) {
+    filename <- tempfile(fileext = ".png")
+    png(filename = filename, width=width, height=height)
+    value <- try(expression)  
+    dev.off()
+    result <- bg3d(texture=filename, col="white")
+    unlink(filename)
+  } else {
+    value <- NULL
+    result <- bg3d(col="white")
+  }
+  invisible(structure(result, value = value))
+}
+
+show2d <- function(expression, 
+		   face = "z-",
+		   line = 0,
+		   reverse = FALSE,
+		   rotate = 0,
+		   x = NULL, y = NULL, z = NULL, 
+		   width = 480,
+		   height = 480,
+		   filename = NULL,
+		   ignoreExtent = TRUE,
+		   color = "white", specular = "black",
+		   lit = FALSE, 
+		   texmipmap = TRUE,
+		   texminfilter = "linear.mipmap.linear",
+		   expand = 1.03,
+		   texcoords = matrix(c(0,1,1,0,0,0,1,1), ncol=2),
+		   ...) {
+	
+  save <- par3d(ignoreExtent = ignoreExtent)
+  on.exit(par3d(save))
+  
+  if (is.null(filename)) {
+    stopifnot(width > 0, height > 0)
+    filename <- tempfile(fileext = ".png")
+    png(filename = filename, width=width, height=height)
+    value <- try(expression)  
+    dev.off()
+  } else
+    value <- filename
+  face <- c(strsplit(face, '')[[1]], '-')[1:2]
+  coord <- tolower(face[1])
+  lower <- face[2] == '-'
+  
+  calc <- c(x = is.null(x), y = is.null(y), z = is.null(z))
+  
+  ranges <- .getRanges(expand = expand)
+    switch(coord,
+      x = {
+      	if (is.null(x)) 
+      	  x <- with(ranges, if (lower) 
+      	  	               x[1] - 0.075*line*diff(x)
+      	  	            else
+      	  	               x[2] + 0.075*line*diff(x))
+      	if (is.null(y))
+      	  y <- with(ranges, c(y[1], y[2], y[2], y[1]))
+      	if (is.null(z))
+      	  z <- with(ranges, c(z[1], z[1], z[2], z[2]))
+      },
+      y = {
+      	if (is.null(x)) 
+      		x <- with(ranges, c(x[1], x[2], x[2], x[1]))
+      	if (is.null(y))
+      		y <- with(ranges, if (lower) 
+      			            y[1] - 0.075*line*diff(y)
+      			          else
+      				    y[2] + 0.075*line*diff(y))
+      	if (is.null(z))
+      		z <- with(ranges, c(z[1], z[1], z[2], z[2]))
+      },      	
+      z = {
+      	if (is.null(x)) 
+      		x <- with(ranges, c(x[1], x[2], x[2], x[1]))
+      	if (is.null(y))
+      		y <- with(ranges, c(y[1], y[1], y[2], y[2]))
+      	if (is.null(z))
+      		z <- with(ranges,  if (lower) 
+      			             z[1] - 0.075*line*diff(z)
+      			           else
+      				     z[2] + 0.075*line*diff(z))
+      }) 
+  x <- cbind(x, y, z)  
+  if (nrow(x) != 4) 
+    stop("Exactly 4 corners must be specified.")
+  
+  if (reverse) {
+    temp <- x[2,]
+    x[2,] <- x[4,]
+    x[4,] <- temp
+  }
+  if (rotate) 
+    x <- x[(0:3 + rotate) %% 4 + 1, ]
+  
+  result <- quads3d(x, texture=filename, texcoords = texcoords,
+  		  color = color, lit = lit, texmipmap = texmipmap, 
+  		  texminfilter = texminfilter, ...)
+  invisible(structure(result, value = value, xyz = x, texcoords = texcoords,
+  		      filename = filename))
+}
diff --git a/R/callbacks.R b/R/callbacks.R
new file mode 100644
index 0000000..2a0fc5a
--- /dev/null
+++ b/R/callbacks.R
@@ -0,0 +1,13 @@
+rgl.setMouseCallbacks <- function(button, begin=NULL, update=NULL, end=NULL) {
+    invisible(.Call(rgl_setMouseCallbacks, as.integer(button), begin, update, end))
+}
+
+rgl.getMouseCallbacks <- function(button) 
+    .Call(rgl_getMouseCallbacks, as.integer(button))
+
+rgl.setWheelCallback <- function(rotate=NULL) {
+    invisible(.Call(rgl_setWheelCallback, rotate))
+}
+
+rgl.getWheelCallback <- function() 
+    .Call(rgl_getWheelCallback)
diff --git a/R/cylinder3d.R b/R/cylinder3d.R
new file mode 100644
index 0000000..d95eaf6
--- /dev/null
+++ b/R/cylinder3d.R
@@ -0,0 +1,194 @@
+GramSchmidt <- function(v1, v2, v3, order=1:3) {
+  A <- rbind(v1, v2, v3)
+  A <- A[order,]
+  v1 <- A[1,]
+  v2 <- A[2,]
+  v3 <- A[3,]
+  if (isTRUE(all.equal(as.numeric(v1), c(0,0,0)))) v1 <- xprod(v2, v3)
+  v1 <- normalize(v1)
+  v2 <- v2 - sum(v2*v1)*v1
+  if (isTRUE(all.equal(as.numeric(v2), c(0,0,0)))) v2 <- xprod(v3, v1)
+  v2 <- normalize(v2)
+  v3 <- v3 - sum(v3*v1)*v1 - sum(v3*v2)*v2
+  if (isTRUE(all.equal(as.numeric(v3), c(0,0,0)))) v3 <- xprod(v1, v2)
+  v3 <- normalize(v3)
+  rbind(v1, v2, v3)[order(order),]
+}
+
+cylinder3d <- function(center, radius=1, twist=0, e1=NULL, e2=NULL, e3=NULL, 
+                       sides=8, section=NULL, closed=0, debug=FALSE, keepVars=FALSE) {
+  center <- as.matrix(as.data.frame(xyz.coords(center)[c("x", "y", "z")]))
+  n <- nrow(center)  
+  inds <- seq_len(n)
+  if (closed > 0) {
+    ind0 <- c(n-1-closed, n-closed, inds)
+    ind1 <- c(n-closed, inds, 1+closed)
+    ind2 <- c(inds, 1+closed, 2+closed)
+  } else {
+    ind0 <- c(1, 1, inds)
+    ind1 <- c(1, inds, n)
+    ind2 <- c(inds, n, n)
+  }  
+  
+  missings <- c(e1=is.null(e1), e2=is.null(e2), e3=is.null(e3))
+  
+  fixup <- function(coord) {
+    usable <- apply(coord, 1, function(v) all(is.finite(v)) & (veclen(v) > 0))
+    if (!any(usable) ) stop(gettextf("No usable coordinate values in '%s'", 
+    				     deparse(substitute(coord))), domain = NA)
+    firstgood <- min(which(usable))
+    inds <- seq_len(n)    
+    if (firstgood > 1) {
+      coord[inds[inds < firstgood],] <- coord[rep(firstgood,firstgood-1),]
+      usable[seq_len(firstgood)] <- TRUE
+    }
+    for (i in inds[-1]) inds[i] <- ifelse(usable[i], inds[i], inds[i-1])
+    coord[inds,]
+  }
+  
+  if (!is.null(e1)) {
+    e1 <- as.matrix(as.data.frame(xyz.coords(e1)[c("x", "y", "z")]))
+    e1 <- e1[rep(seq_len(nrow(e1)), len=n),] 
+  } else 
+    e1 <- (center[ind2,] - center[ind0,])[inds,]
+  
+  # Fix up degenerate cases by repeating existing ones, or using arbitrary ones
+  zeros <- rowSums(e1^2) == 0
+  if (all(zeros)) {
+    e1[,1] <- 1
+    zeros <- FALSE
+  } else if (any(zeros)) {
+    e1[1,] <- e1[which(!zeros)[1],]
+    zeros[1] <- FALSE
+    if (any(zeros)) {
+      zeros <- which(zeros)
+      for (i in zeros)
+        e1[i,] <- e1[i-1,]
+    }
+  }
+  if (!is.null(e2)) {
+    e2 <- as.matrix(as.data.frame(xyz.coords(e2)[c("x", "y", "z")]))
+    e2 <- e2[rep(seq_len(nrow(e2)), len=n),] 
+  } else
+    e2 <- (e1[ind2,] - e1[ind0,])[inds,]
+    
+  # Fix up degenerate e2's similarly, then force different than e1
+  zeros <- rowSums(e2^2) == 0
+  if (all(zeros)) {
+    e2[,2] <- 1
+    zeros <- FALSE
+  } else if (any(zeros)) {
+    e2[1,] <- e2[which(!zeros)[1],]
+    zeros[1] <- FALSE
+    if (any(zeros)) {
+      zeros <- which(zeros)
+      for (i in zeros)
+        e2[i,] <- e2[i-1,]
+    }
+  }
+  parallel <- sapply(inds, function(i) all(xprod(e1[i,], e2[i,])  == 0))
+  if (any(parallel)) {
+    # rotate in the xy plane
+    e2[parallel,] <- cbind(-e2[parallel,2], e2[parallel,1], e2[parallel,3])
+    parallel <- sapply(inds, function(i) all(xprod(e1[i,], e2[i,])  == 0))
+    if (any(parallel)) {
+      # if any are still parallel, they must be the z axis
+      e2[parallel,1] <- 1
+      e2[parallel,3] <- 0
+    }
+  }
+  
+  if (!is.null(e3)) {
+    e3 <- as.matrix(as.data.frame(xyz.coords(e3)[c("x", "y", "z")]))
+    e3 <- e3[rep(seq_len(nrow(e3)), len=n),] 
+  } else {
+    e3 <- matrix(NA_real_, n, 3)
+    for (i in inds) e3[i,] <- xprod(e1[i,], e2[i,])
+  }
+
+  for (i in inds) {
+    A <- GramSchmidt(e1[i,], e2[i,], e3[i,], order=order(missings))
+    e1[i,] <- A[1,]
+    e2[i,] <- A[2,]
+    e3[i,] <- A[3,]
+  }
+  e1 <- fixup(e1)
+  e2 <- fixup(e2)
+  e3 <- fixup(e3)
+
+  radius <- rep(radius, len=n)
+  twist <- rep(twist, len=n)
+  
+  if (debug) {
+    for (i in inds) {
+      segments3d(rbind(center[i,],center[i,]+e3[i,]*radius[i]*1.5,
+                     center[i,],center[i,]+e2[i,]*radius[i]*1.5,
+                     center[i,],center[i,]+e1[i,]*radius[i]*1.5), 
+                 col=rep(c("red", "green", "blue"), each=2))
+      text3d(center, texts=inds)
+    }
+  }
+  
+  if (closed > 0) n <- n-closed+1
+  
+  if (is.null(section)) {
+    theta <- seq(0, 2*pi, len=sides+1)[-1]
+    section <- cbind(cos(theta), sin(theta), 0)
+  } else 
+    sides <- nrow(section)
+    
+  vertices <- matrix(0, 3, sides*n)
+  indices <- matrix(0, 4, sides*(n-1))
+  
+  if (ncol(section) == 2)
+    section <- cbind(section, 0)
+    
+  for (i in seq_len(n-1)) {
+    transform <- rbind(e3[i,], e2[i,], e1[i,])
+    p <- rotate3d(section, twist[i], 0,0,1)
+    p <- radius[i] * p %*% transform
+    p[,1] <- p[,1] + center[i,"x"]
+    p[,2] <- p[,2] + center[i,"y"]
+    p[,3] <- p[,3] + center[i,"z"]
+    vertices[,(i-1)*sides+seq_len(sides)] <- t(p)
+    for (j in seq_len(sides)) 
+      indices[, (i-1)*sides + j] <- (c(0,0,1,1) + j) %% sides + 1 + 
+                                    c((i-1)*sides, i*sides, i*sides, (i-1)*sides)
+  }
+  transform <- rbind(e3[n,], e2[n,], e1[n,])
+  p <- rotate3d(section, twist[n], 0,0,1)
+  p <- radius[n] * p %*% transform
+  p[,1] <- p[,1] + center[n,"x"]
+  p[,2] <- p[,2] + center[n,"y"]
+  p[,3] <- p[,3] + center[n,"z"]
+  vertices[,(n-1)*sides+seq_len(sides)] <- t(p)
+  # Add end cap at start
+  if (closed < 0) {
+    vertices <- cbind(vertices, center[1,])
+    triangles <- rbind(ncol(vertices), seq_len(sides), c(2:sides, 1))
+  }
+  # Add end cap at end
+  if (closed < -1) {
+    vertices <- cbind(vertices, center[n,])
+    triangles <- cbind(triangles, rbind(ncol(vertices), c(2:sides, 1) + (n-1)*sides, 
+                                    seq_len(sides) + (n-1)*sides))
+  }
+  
+  result <- qmesh3d(vertices, indices, homogeneous=FALSE)
+  if (closed > 0) { # Look for repeated vertices, and edit the links
+    nv <- ncol(result$vb)
+    for (i in seq_len(sides)) {
+      dupe <- which(apply(result$vb[,(nv-sides+1):nv,drop=FALSE], 2, 
+                          function(x) isTRUE(all.equal(x, result$vb[,i]))))+nv-sides
+      for (j in dupe) {
+        f <- result$ib == j
+        result$ib[f] <- i
+      }
+    }
+  } else if (closed < 0)
+    result$it <- triangles
+    
+  if (keepVars)
+    attr(result, "vars") <- environment()
+  result
+}
diff --git a/R/device.R b/R/device.R
new file mode 100644
index 0000000..4a3858c
--- /dev/null
+++ b/R/device.R
@@ -0,0 +1,171 @@
+##
+## R source file
+## This file is part of rgl
+##
+## $Id: device.R 1438 2016-01-02 18:44:46Z murdoch $
+##
+
+##
+## ===[ SECTION: device management ]==========================================
+##
+
+rgl.useNULL <- function() {
+  opt <- getOption("rgl.useNULL", Sys.getenv("RGL_USE_NULL"))
+  if (is.logical(opt)) return(opt)
+  opt <- as.character(opt)
+  if (!nchar(opt)) return(FALSE)
+  opt <- pmatch(tolower(opt), c("yes", "true"), nomatch=3)
+  c(TRUE, TRUE, FALSE)[opt]
+}
+
+##
+## open device
+##
+##
+
+rgl.open <- function(useNULL = rgl.useNULL()) {
+
+  ret <- .C( rgl_dev_open, success=FALSE, useNULL=useNULL )
+
+  if (! ret$success)
+    stop("'rgl.open' failed")
+
+}
+
+
+##
+## close device
+##
+##
+
+rgl.close <- function() {
+
+  if (length(hook <- getHook("on.rgl.close"))) {
+    if (is.list(hook)) hook <- hook[[1]]  # test is for compatibility with R < 3.0.0
+    hook()
+  }
+  
+  ret <- .C( rgl_dev_close, success=FALSE )
+
+  if (! ret$success)
+    stop("No device opened")
+
+}
+
+## 
+## get current device
+##
+##
+
+rgl.cur <- function() {
+
+  .Call( rgl_dev_getcurrent )
+
+}
+
+## 
+## get all devices
+##
+##
+
+rgl.dev.list <- function() {
+
+  .Call( rgl_dev_list )
+  
+}
+
+
+##
+## set current device
+##
+##
+
+rgl.set <- function(which, silent = FALSE) {
+
+  idata <- c( as.integer(which), as.integer(silent) )
+
+  ret <- .C( rgl_dev_setcurrent, 
+    success=FALSE, 
+    idata
+  )
+
+  if (! ret$success)
+    stop(gettextf("No device opened with id %s", which), domain = NA)
+}
+
+
+
+##
+## export image
+##
+##
+
+rgl.snapshot <- function( filename, fmt="png", top=TRUE )
+{
+  force(filename)
+  force(fmt)
+  
+  if (top) rgl.bringtotop()
+  
+  idata <- as.integer(rgl.enum.pixfmt(fmt))
+
+  ret <- .C( rgl_snapshot,
+    success=FALSE,
+    idata,
+    normalizePath(filename, mustWork = FALSE)
+  )
+
+  if (! ret$success)
+    warning("'rgl.snapshot' failed")
+}
+
+##
+## export postscript image
+##
+##
+
+rgl.postscript <- function( filename, fmt="eps", drawText=TRUE )
+{
+  idata <- as.integer(c(rgl.enum.gl2ps(fmt), as.logical(drawText)))
+
+  ret <- .C( rgl_postscript,
+    success=FALSE,
+    idata,
+    normalizePath(filename, mustWork = FALSE)
+  )
+
+  if (! ret$success)
+    warning("Postscript conversion failed")
+}
+
+##
+## read image
+##
+##
+
+rgl.pixels <- function(component = c("red", "green", "blue"), viewport = par3d("viewport"), top=TRUE )
+{
+  if (top) rgl.bringtotop()
+  
+  compnum <- as.integer(sapply(component, rgl.enum.pixelcomponent))
+  stopifnot(length(viewport) == 4)
+  ll <- as.integer(viewport[1:2])
+  stopifnot(all(!is.na(ll)), all(ll >= 0))
+  size <- as.integer(viewport[3:4])
+  stopifnot(all(!is.na(size), all(size >= 0)))
+  result <- array(NA_real_, dim=c(size[1], size[2], length(component)))
+  dimnames(result) <- list(NULL, NULL, component)
+  if (length(result) > 0)
+    for (i in seq_along(compnum)) {
+      ret <- .C( rgl_pixels,
+        success=FALSE,
+        ll, size, compnum[i],
+        values = double(size[1]*size[2]))
+ 
+      if (! ret$success)
+        warning(gettextf("Error reading component '%s'", component[i]), domain = NA)
+      result[,,i] <- ret$values
+    }
+  if (length(component) > 1) return(result)
+  else return(result[,,1])
+}
diff --git a/R/ellipse3d.R b/R/ellipse3d.R
new file mode 100644
index 0000000..2cba8cf
--- /dev/null
+++ b/R/ellipse3d.R
@@ -0,0 +1,63 @@
+ellipse3d <- function (x, ...) 
+  UseMethod("ellipse3d")
+
+ellipse3d.default <-
+  function (x, scale = c(1, 1, 1), centre = c(0, 0, 0), level = 0.95, 
+            t = sqrt(qchisq(level, 3)), which = 1:3, subdivide = 3, smooth = TRUE, ...) 
+{
+  stopifnot(is.matrix(x))
+  
+  cov <- x[which, which]
+  chol <- chol(cov)
+
+  sphere <- subdivision3d(cube3d(...), subdivide) 
+  norm <- sqrt( sphere$vb[1,]^2 + sphere$vb[2,]^2 + sphere$vb[3,]^2 )
+  for (i in 1:3) sphere$vb[i,] <- sphere$vb[i,]/norm
+  sphere$vb[4,] <- 1
+  if (smooth)
+    sphere$normals <- sphere$vb
+  
+  result <-scale3d(transform3d( sphere, chol), t,t,t)
+  
+  if (!missing(scale)) 
+    result <- scale3d(result, scale[1], scale[2], scale[3])
+  if (!missing(centre))
+    result <- translate3d(result, centre[1], centre[2], centre[3])
+  return(result)
+}
+
+ellipse3d.lm <-
+  function (x, which = 1:3, level = 0.95, t = sqrt(3 * qf(level, 
+                                                3, x$df.residual)), ...) 
+{
+  s <- summary(x)  
+  names <- names(x$coefficients[which])
+  structure(c(ellipse3d.default(s$sigma^2 * s$cov.unscaled[which, which], 
+                              centre = x$coefficients[which], t = t, ...),
+              xlab=names[1], ylab=names[2], zlab=names[3]), class="mesh3d")
+}
+
+ellipse3d.glm <- function (x, which = 1:3, level = 0.95, t, dispersion, ...) 
+{
+  s <- summary(x)
+  est.disp <- missing(dispersion) & !(x$family$family %in% c('poisson','binomial'))
+  if (missing(dispersion)) dispersion <- s$dispersion
+  if (missing(t)) t <- ifelse(est.disp,sqrt(3 * qf(level, 3, s$df[2])),
+			                           sqrt(qchisq(level, 3)))
+			                           
+  names <- names(x$coefficients[which])			                           
+  structure(c(ellipse3d.default(dispersion * s$cov.unscaled[which, which], 
+                  centre = x$coefficients[which], t = t, ...),
+              xlab=names[1], ylab=names[2], zlab=names[3]), class="mesh3d")
+}
+
+ellipse3d.nls <- function (x, which = 1:3, level = 0.95, t = sqrt(3 * qf(level, 
+                                                3, s$df[2])), ...) 
+{
+  s <- summary(x)  
+  names <- names(x$m$getPars()[which])
+  structure(c(ellipse3d.default(s$sigma^2 * s$cov.unscaled[which, which], 
+                  centre = x$m$getPars()[which], t = t, ...),
+	      xlab=names[1], ylab=names[2], zlab=names[3]), class="mesh3d")                  
+}
+
diff --git a/R/enum.R b/R/enum.R
new file mode 100644
index 0000000..1abc77f
--- /dev/null
+++ b/R/enum.R
@@ -0,0 +1,68 @@
+# enumerations
+
+rgl.enum <- function ( name, ..., multi = FALSE)
+{
+  choices <- list( ... )
+  names   <- attr(choices,"names")
+
+  if (multi) pos <- pmatch( name, c(names, "all") )
+  else pos <- pmatch( name, names )
+ 
+  max <- length(names)
+
+  if ( any( is.na(pos) ) )
+    stop(gettextf("Symbolic value must be chosen from: %s", list(names)), domain = NA)
+  else if ( (max+1) %in% pos )
+    pos <- seq_along(names)
+    
+  id  <- unlist(choices[pos])
+  
+  if ( length(id) > 1 && !multi )
+    stop("Multiple choices not allowed")
+ 
+  return( id )
+}
+
+rgl.enum.nodetype <- function (type) 
+rgl.enum( type, shapes=1, lights=2, bboxdeco=3, userviewpoint=4, material=5, background=6, subscene=7, modelviewpoint=8, 
+          multi = TRUE )
+
+rgl.enum.attribtype <- function (attrib)
+rgl.enum( attrib, vertices=1, normals=2, colors=3, texcoords=4, dim=5, 
+          texts=6, cex=7, adj=8, radii=9, centers=10, ids=11, 
+          usermatrix=12, types=13, flags=14, offsets=15,
+	  family=16, font=17)
+
+rgl.enum.pixfmt <- function (fmt)
+rgl.enum( fmt, png=0 )
+
+rgl.enum.polymode <- function (mode)
+rgl.enum( mode, filled=1, lines=2, points=3, culled=4)
+
+rgl.enum.textype <- function (textype)
+rgl.enum( textype, alpha=1, luminance=2, luminance.alpha=3, rgb=4, rgba=5 )
+
+rgl.enum.fogtype <- function (fogtype)
+rgl.enum (fogtype, none=1, linear=2, exp=3, exp2=4)
+
+rgl.enum.primtype <- function (primtype)
+rgl.enum( primtype, points=1, lines=2, triangles=3, quadrangles=4, linestrips=5 )
+
+rgl.enum.halign <- function( halign)
+rgl.enum (halign, left=-1, center=0, right=1 )
+  
+rgl.enum.texminfilter <- function (minfiltertype)
+rgl.enum (minfiltertype, nearest=0, linear=1, nearest.mipmap.nearest=2, nearest.mipmap.linear=3, linear.mipmap.nearest=4, linear.mipmap.linear=5)
+  
+rgl.enum.texmagfilter <- function (magfiltertype)
+rgl.enum (magfiltertype, nearest=0, linear=1)
+
+rgl.enum.gl2ps <- function (postscripttype)
+rgl.enum (postscripttype, ps=0, eps=1, tex=2, pdf=3, svg=4, pgf=5)
+
+rgl.enum.pixelcomponent <- function(component)
+rgl.enum(component, red=0, green=1, blue=2, alpha=3, depth=4, luminance=5)
+
+rgl.enum.depthtest <- function(depthtest)
+rgl.enum(depthtest, never=0, less=1, equal=2, lequal=3, greater=4, 
+                    notequal=5, gequal=6, always= 7)
\ No newline at end of file
diff --git a/R/fonts.R b/R/fonts.R
new file mode 100644
index 0000000..6a1c8e7
--- /dev/null
+++ b/R/fonts.R
@@ -0,0 +1,67 @@
+# The rgl font database is only used when rgl is configured for freetype.  
+# Usually this is not true in Windows, and the windowsFonts are used instead.
+
+# This code is closely modelled on the Quartz font database.
+
+.rglEnv <- new.env()
+
+assign(".rglFonts", list(), envir = .rglEnv)
+
+# Check that the font has the correct structure and information
+checkrglFont <- function(font) {
+    if (!is.character(font) || length(font) != 4)
+        stop("Invalid rgl font:  must be 4 filenames")
+    font
+}
+
+setrglFonts <- function(fonts, fontNames) {
+    fonts <- lapply(fonts, checkrglFont)
+    fontDB <- get(".rglFonts", envir=.rglEnv)
+    existingFonts <- fontNames %in% names(fontDB)
+    if (sum(existingFonts) > 0)
+        fontDB[fontNames[existingFonts]] <- fonts[existingFonts]
+    if (sum(existingFonts) < length(fontNames))
+        fontDB <- c(fontDB, fonts[!existingFonts])
+    assign(".rglFonts", fontDB, envir=.rglEnv)
+}
+
+printFont <- function(font) {
+    paste(font, "\n", sep="")
+}
+
+printFonts <- function(fonts) {
+    cat(paste(names(fonts), ": ", unlist(lapply(fonts, printFont)),
+              sep="", collapse=""))
+}
+
+# If no arguments spec'ed, return entire font database
+# If no named arguments spec'ed, all args should be font names
+# to get info on from the database
+# Else, must specify new fonts to enter into database (all
+# of which must be valid filenames and
+# all of which must be named args)
+rglFonts <- function(...) {
+  ndots <- length(fonts <- list(...))
+  if (ndots==0) {
+    get(".rglFonts", .rglEnv)
+  } else {
+    fontNames <- names(fonts)
+    nnames <- length(fontNames)
+    if (nnames == 0) {
+      if (!all(sapply(fonts, is.character))) {
+        stop("Invalid arguments in 'rglFonts' (must be font names)")
+      } else {
+        get(".rglFonts", .rglEnv)[unlist(fonts)]
+      }
+    } else {
+      if (ndots != nnames) {
+        stop("Invalid arguments in 'rglFonts' (need named args)")
+      }
+      setrglFonts(fonts, fontNames)
+    }
+  }
+}
+
+rglFont <- function(family) {
+  checkrglFont(family)
+}
diff --git a/R/getscene.R b/R/getscene.R
new file mode 100644
index 0000000..3274d77
--- /dev/null
+++ b/R/getscene.R
@@ -0,0 +1,393 @@
+scene3d <- function() {
+  
+  defaultmaterial <- material3d()
+  
+  matdiff <- function(mat) {
+    for (m in names(mat)) {
+      if (identical(mat[[m]], defaultmaterial[[m]]))
+        mat[[m]] <- NULL
+    }
+    mat
+  }
+  
+  getObject <- function(id, type) {
+    result <- list(id=id, type=type)
+    
+    if (!(type %in% c("light", "clipplanes", "background")))
+      result$material <- matdiff(rgl.getmaterial(id=id))
+    
+    attribs <- c("vertices", "normals", "colors", "texcoords", "dim",
+          "texts", "cex", "adj", "radii", "ids",
+          "usermatrix", "types", "offsets", "centers",
+          "family", "font")
+    for (a in attribs) 
+      if (rgl.attrib.count(id, a))
+        result[[a]] <- rgl.attrib(id, a)
+    flags <- rgl.attrib(id, "flags")
+    if (length(flags) && "ignoreExtent" %in% rownames(flags)) 
+      result$ignoreExtent <- flags["ignoreExtent", 1]
+    if (!is.null(result$ids)) {
+      objlist <- vector("list", nrow(result$ids))
+      for (i in seq_len(nrow(result$ids)))
+        objlist[[i]] <- getObject(result$ids[i,1], result$types[i,1])
+      result$objects <- objlist
+    }
+    if (type == "background") {
+      flags <- rgl.attrib(id, "flags")
+      result$sphere <- flags["sphere", 1]
+      result$fogtype <- if (flags["linear_fog", 1]) "linear"
+                        else if (flags["exp_fog", 1]) "exp"
+			else if (flags["exp2_fog", 1]) "exp2"
+			else "none"
+    } else if (type == "bboxdeco") {
+      flags <- rgl.attrib(id, "flags")
+      result$draw_front <- flags["draw_front", 1]
+    } else if (type == "light") {
+      flags <- rgl.attrib(id, "flags")
+      result$viewpoint <- flags["viewpoint", 1]
+      result$finite    <- flags["finite", 1]
+    }
+    class(result) <- c(paste0("rgl", type), "rglobject")
+    result
+  }
+
+  getSubscene <- function(id) {
+    useSubscene3d(id)
+      
+    result <- list(id = id, type = "subscene", par3d = par3d())
+
+    result$embeddings <- subsceneInfo()$embeddings
+    
+    objs <- rgl.ids(c("background", "bboxdeco", "shapes", "lights"))
+    result$objects <- objs$id
+  
+    if (nrow(obj <- rgl.ids("subscene", subscene = id))) {
+      subscenes <- vector("list", nrow(obj))
+      ids <- obj$id
+      for (i in seq_len(nrow(obj)))
+        subscenes[[i]] <- getSubscene(ids[i])
+      result$subscenes <- subscenes
+    }
+    class(result) <- c("rglsubscene", "rglobject")
+    result
+  }
+  
+  result <- list()
+  result$material <- defaultmaterial
+  
+  result$rootSubscene <- getSubscene(rootSubscene())
+  
+  objs <- rgl.ids(c("shapes", "lights", "background", "bboxdeco"), subscene=0)  
+  objlist <- vector("list", nrow(objs))
+  ids <- objs$id
+  types <- as.character(objs$type)
+  for (i in seq_len(nrow(objs))) {
+    objlist[[i]] <- getObject(ids[i], types[i])
+    names(objlist)[i] <- as.character(ids[i])
+  }
+  result$objects <- objlist
+    
+  class(result) <- "rglscene"
+  result
+}
+
+print.rglscene <- function(x, ...) {
+  cat(gettext("RGL scene containing:\n"))
+  if (!is.null(x$par3d))
+    cat(gettext("  par3d:\tscene information\n"))
+  if (!is.null(x$material))
+    cat(gettext("  material:\tdefault material properties\n"))
+  if (!is.null(x$objects)) {
+    cat(gettextf("  objects:\tlist of %d object(s):\n", length(x$objects)))
+    cat("          \t", sapply(x$objects, function(obj) obj$type), "\n")
+  }
+  if (!is.null(x$root)) 
+    cat(gettext("  root:\ta root subscene\n"))
+  invisible(x)
+}
+
+summary.rglscene <- function(object, ...) {
+  result <- list()
+  nobjs <- length(object$objects)
+  if (nobjs) result$objects <- data.frame(type=sapply(object$objects, function(obj) obj$type))
+  if (!is.null(object$rootSubscene))
+    result$subscenes <- summary(object$rootSubscene)
+  result
+}
+
+summary.rglsubscene <- function(object, ...) {
+  result <- data.frame(id = object$id, parent = NA, objects = 0)
+  result$objects <- list(object$objects)
+  if (length(object$subscenes)) {
+    children <- do.call(rbind, lapply(object$subscenes, summary))
+    children[is.na(children$parent),"parent"] <- object$id
+    result <- rbind(result, children)
+  }
+  result
+}
+
+print.rglobject <- function(x, ...) {
+  cat(gettextf("RGL object of type %s containing components\n", x$type))
+  cat("  ")
+  cat(names(x), sep=", ")
+  cat("\n")
+}
+
+print.rglsubscene <- function(x, ...) {
+  cat(gettext("RGL subscene containing components\n"))
+  cat("  ")
+  cat(names(x), sep=", ")
+  cat("\n")
+}
+  
+
+plot3d.rglscene <- function(x, add=FALSE, ...) {
+  root <- x$rootSubscene
+  if (is.null(root)) root <- x  # Should work with pre-subscene objects
+  if (!add) {
+    params <- getr3dDefaults()
+    if (!is.null(x$material)) {
+      if (is.null(params$material)) params$material <- list()
+      params$material[names(x$material)] <- x$material
+    }
+    if (!is.null(root$bg)) {
+      if (is.null(params$bg)) params$bg <- list()
+      params$bg[names(params$material)] <- params$material
+      params$bg[names(x$bg$material)] <- x$bg$material
+      x$bg$material <- x$bg$id <- x$bg$type <- NULL
+      params$bg[names(x$bg)] <- x$bg
+    }
+    if (!is.null(root$par3d)) {
+      ind <- !(names(root$par3d) %in% .Par3d.readonly)
+      params[names(root$par3d)[ind]] <- root$par3d[ind]
+    }
+    open3d(params = params)
+    
+    # Some older scenes might not have a light in them, so only clear if one is there
+    for (i in seq_along(x$objects)) {
+      obj <- x$objects[[i]]
+      if (obj$type == "light") {
+        clear3d("lights")
+        break
+      }
+    }
+  } 
+  save <- par3d(skipRedraw = TRUE)
+  on.exit(par3d(save))
+  
+  if (is.null(x$rootSubscene)) {   
+    results <- c()
+    for (i in seq_along(x$objects)) {
+      obj <- x$objects[[i]]
+      results <- c(results, plot3d(obj))
+    }
+    if (!is.null(obj <- x$bbox)) 
+      plot3d(obj)  
+  } else 
+    results <- plot3d(root, x$objects, root = TRUE, ...)
+  
+  invisible(results)
+}   
+
+plot3d.rglsubscene <- function(x, objects, root = TRUE, ...) {
+  if (root) {
+    if (!is.null(x$embeddings)) {
+      info <- subsceneInfo(embeddings = x$embeddings)
+      subscene <- info$id
+    } else
+      subscene <- currentSubscene3d()
+    if (!is.null(x$par3d$viewport))
+      par3d(viewport = x$par3d$viewport)
+  } else
+    subscene <- newSubscene3d(viewport = x$embeddings["viewport"],
+			    projection = x$embeddings["projection"],
+			    model = x$embeddings["model"],
+			    newviewport = x$par3d$viewport,
+			    copyLights = FALSE)
+			    
+  if (!is.null(x$par3d$listeners))
+    par3d(listeners = x$par3d$listeners, subscene = subscene) 
+    
+  results <- subscene
+  names(results) <- paste0("subscene", as.character(x$id))
+  
+  objs <- x$objects
+  for (id in as.character(objs)) {
+    obj <- objects[[id]]
+    if (is.null(obj$newid)) 
+      results <- c(results, objects[[id]]$newid <- plot3d(obj, ...))
+    else
+      addToSubscene3d(obj$newid)
+  }
+  for (i in seq_along(x$subscenes)) {
+    useSubscene3d(subscene)
+    res <- plot3d(x$subscenes[[i]], objects, root=FALSE, ...)
+    results <- c(results, res$results)
+    objects <- res$objects
+  }
+  if (root) {
+    # Translate all the listener values
+    dotranslations <- function(id) {
+      info <- subsceneInfo(id = id)
+      oldlisteners <- par3d("listeners", subscene = id)
+      par3d(listeners = results[paste0("subscene", oldlisteners)], subscene = id)
+      for (child in info$children)
+        dotranslations(child)
+    }
+    dotranslations(subscene)
+    return(results)
+  } else
+    return(list(results=results, objects=objects))
+}
+       
+  
+
+plot3d.rglobject <- function(x, ...) {
+  type <- x$type
+  fn <- switch(type,
+    points = points3d,
+    lines = segments3d,
+    linestrip = lines3d,
+    triangles = triangles3d,
+    quads = quads3d,
+    text = texts3d,
+    spheres = spheres3d,
+    abclines = abclines3d,
+    planes = planes3d,
+    surface = surface3d,
+    sprites = sprites3d,
+    light = light3d,
+    clipplanes = clipplanes3d,
+    NULL)
+  if (is.null(fn)) {
+    warning(gettextf("Object type '%s' not handled.", type), 
+    	    domain = NA)
+    return()
+  }
+  if (!is.null(x$ignoreExtent)) {
+    save <- par3d(ignoreExtent = x$ignoreExtent)
+    on.exit(par3d(save))
+  }
+  args <- list()
+  args$x <- x$vertices
+  args$normals <- x$normals
+  args$texcoords <- x$texcoords
+  args$texts <- x$texts
+  args$cex <- x$cex
+  args$adj <- x$adj
+  args$radius <- x$radii
+  args$d <- x$offsets
+  
+  switch(type, 
+    abclines = {
+      odd <- seq_len(nrow(args$x)) %% 2 == 1
+      ends <- args$x[odd,,drop=FALSE]
+      args$a <- args$x[!odd,,drop=FALSE] - ends
+      args$x <- ends
+    },
+    planes =,
+    clipplanes = {
+      args$a <- args$normals
+      args$x <- NULL
+      args$normals <- NULL
+    },  
+    surface = {
+      dim <- x$dim
+      args$y <- matrix(args$x[,2], dim[1], dim[2])
+      args$z <- matrix(args$x[,3], dim[1], dim[2])
+      args$x <- matrix(args$x[,1], dim[1], dim[2])
+      if (!is.null(args$normals)) {
+        args$normal_x <- matrix(args$normals[,1], dim[1], dim[2])
+	args$normal_y <- matrix(args$normals[,2], dim[1], dim[2])
+	args$normal_z <- matrix(args$normals[,3], dim[1], dim[2])
+        args$normals <- NULL
+      }
+      if (!is.null(args$texcoords)) {
+        args$texture_s <- matrix(args$texcoords[,1], dim[1], dim[2])
+        args$texture_t <- matrix(args$texcoords[,2], dim[1], dim[2])
+        args$texcoords <- NULL
+      }
+    },
+    sprites = {
+      save2 <- par3d(skipRedraw = TRUE)
+      on.exit(par3d(save2), add=TRUE)
+  
+      if (!is.null(x$objects)) {
+        ids <- numeric(length(x$objects))
+        for (i in seq_along(ids)) 
+          ids[i] <- plot3d(x$objects[[i]])
+        args$shapes <- ids
+      }
+      args$userMatrix <- x$usermatrix
+    })
+      
+  mat <- x$material
+  if (is.null(mat)) mat <- list()
+  if (!is.null(col <- x$colors)) {
+    mat$color <- rgb(col[,1], col[,2], col[,3])
+    mat$alpha <- col[,4]
+  }
+
+  if (type == "light") {
+    if (!x$finite) {
+      args$x <- NULL
+      vx <- x$vertices[1]
+      vy <- x$vertices[2]
+      vz <- x$vertices[3]
+      args$phi <- atan2(vy, sqrt(vx^2 + vz^2))*180/pi
+      args$theta <- atan2(vx, vz)*180/pi
+    }
+    args$viewpoint.rel <- x$viewpoint
+    args$ambient <- mat$color[1]
+    args$diffuse <- mat$color[2]
+    args$specular <- mat$color[3]
+  } else 
+    args <- c(args, mat)
+  
+  do.call(fn, args)
+}
+
+plot3d.rglbboxdeco <- function(x, ...) {
+  args <- list()     
+  v <- x$vertices
+  t <- x$texts
+  ind <- is.na(v[,2]) & is.na(v[,3])
+  if (any(ind)) {
+    args$xat <- v[ind,1]
+    if (!is.null(t))
+      args$xlab <- t[ind]
+    else
+      args$xlab <- signif(args$xat, 4)
+  }
+  ind <- is.na(v[,1]) & is.na(v[,3])
+  if (any(ind)) {
+    args$yat <- v[ind,2]
+    if (!is.null(t))
+      args$ylab <- t[ind]
+    else
+      args$ylab <- signif(args$yat, 4)
+  }
+  ind <- is.na(v[,1]) & is.na(v[,2])
+  if (any(ind)) {
+    args$zat <- v[ind,3]
+    if (!is.null(t))
+      args$zlab <- t[ind]
+    else
+      args$zlab <- signif(args$zat, 4)
+  }
+  args$draw_front <- x$draw_front
+  args <- c(args, x$material)
+  
+  do.call("bbox3d", args)
+}
+
+plot3d.rglbackground <- function(x, ...) {
+  mat <- x$material 
+  if (is.null(mat)) mat <- list()
+  if (!is.null(col <- x$colors)) {
+    mat$color <- rgb(col[,1], col[,2], col[,3])
+    mat$alpha <- col[,4]
+  }
+  args <- c(list(sphere = x$sphere, fogtype = x$fogtype), mat)
+  do.call("bg3d", args)
+}
diff --git a/R/grid3d.R b/R/grid3d.R
new file mode 100644
index 0000000..91d26c9
--- /dev/null
+++ b/R/grid3d.R
@@ -0,0 +1,63 @@
+grid3d <- function (side, at = NULL, col="gray",
+                    lwd = 1, lty = 1, n = 5) {
+
+  save <- par3d(skipRedraw = TRUE, ignoreExtent = TRUE)
+  on.exit(par3d(save))
+
+  if (!missing(side) && length(side)>1)
+    return(invisible(sapply(side,grid3d,at=at,col=col,lwd=lwd,lty=lty,n=n)))
+  
+  ranges <- .getRanges()
+
+  side <- c(strsplit(side, '')[[1]], '-')[1:2]
+  coord <- match(toupper(side[1]), c('X', 'Y', 'Z'))
+  spos <- match(side[2],c('-','+'))
+
+  sidenames <- c('x', 'y', 'z')
+  
+  sides <- 1:3
+  sides <- sides[-coord]
+
+  if (is.null(at)) at <- list()
+  else if (is.numeric(at)) {
+    at <- list(x=at, y=at, z=at)
+    at[[coord]] <- NULL
+  }
+  
+  result <- c()
+  
+  for (cside in sides) {
+    range <- ranges[[cside]]
+    if (is.null(at1 <- at[[sidenames[cside]]]))
+      at1 <- pretty(range, n)
+    at1 <- at1[at1 >= range[1] & at1 <= range[2]]
+    mpos1 <- matrix(rep(c(ranges$x[1],ranges$y[1],ranges$z[1]),
+                        each=length(at1)),
+                    ncol=3)
+    mpos2 <- matrix(rep(c(ranges$x[2],ranges$y[2],ranges$z[2]),
+                        each=length(at1)),
+                  ncol=3)
+    mpos1[,cside] <- mpos2[,cside] <- at1
+    if (is.null(at[[sidenames[coord]]]))
+      mpos1[,coord] <- mpos2[,coord] <- ranges[c("x","y","z")][[coord]][spos]
+    else {
+      # may need to duplicate 
+      temp1 <- temp2 <- matrix(NA, nrow=0, ncol=3)
+      planes <- at[[sidenames[coord]]]
+      planes <- planes[planes >= ranges[[coord]][1] & planes <= ranges[[coord]][2]]
+      for (at2 in planes) {
+      	mpos1[,coord] <- mpos2[,coord] <- at2
+      	temp1 <- rbind(temp1, mpos1)
+      	temp2 <- rbind(temp2, mpos2)
+      }
+      mpos1 <- temp1
+      mpos2 <- temp2
+    }
+      
+    result[sidenames[cside]] <- segments3d(x=c(rbind(mpos1[,1],mpos2[,1])),
+               y=c(rbind(mpos1[,2],mpos2[,2])),
+               z=c(rbind(mpos1[,3],mpos2[,3])),
+               lwd=lwd,color=col)
+  }
+  invisible(result)
+}
diff --git a/R/identify3d.R b/R/identify3d.R
new file mode 100644
index 0000000..9df72bc
--- /dev/null
+++ b/R/identify3d.R
@@ -0,0 +1,85 @@
+identify3d <- function(x, y = NULL, z = NULL, labels = seq_along(x),
+              n = length(x), plot = TRUE, adj = c(-0.1, 0.5),
+              tolerance = 20, buttons = c("right", "middle")) {
+              
+    cat <- function(...) {
+      base::cat(...)
+      flush.console()
+    }
+    
+    opar <- par3d("mouseMode")
+    odisp <- rgl.cur()
+    
+    on.exit( {
+      disp <- rgl.cur()
+      if (odisp != disp) 
+        try(rgl.set(odisp), silent=TRUE)
+      if (rgl.cur() == odisp) 
+        par3d(mouseMode = opar) 
+      try(rgl.set(disp), silent=TRUE)
+    } )     
+    
+    xyz <- xyz.coords(x, y, z)
+    x <- xyz$x
+    y <- xyz$y
+    z <- xyz$z
+    if (length(x)==0) 
+        return(numeric())
+        
+    force(labels)
+    force(adj)
+        
+    buttons <- match.arg(buttons, c("left", "right", "middle"), several.ok = TRUE)
+    
+    if (length(buttons > 1))
+      cat(gettextf("Use the %s button to select, the %s button to quit\n", 
+      	           buttons[1], buttons[2]))
+    else
+      cat(gettextf("Use the %s button to select\n"), buttons[1])
+
+    buttons <- c(left=1, right=2, middle=3)[buttons]
+    
+    selected <- c()
+    
+    select <- function(mousex, mousey) {
+       disp <- rgl.cur()
+       if (disp != odisp) {
+         rgl.set(odisp)
+         on.exit(rgl.set(disp))
+       }
+       viewport <- par3d("viewport")
+       winxyz <- rgl.user2window(xyz)
+       winxyz[,1] <- winxyz[,1]*viewport[3]
+       winxyz[,2] <- (1-winxyz[,2])*viewport[4]
+      
+       dist <- sqrt( (mousex-winxyz[,1])^2 + (mousey - winxyz[,2])^2 )
+       dist[winxyz[,3] < 0 | winxyz[,3] > 1] <- Inf
+       sel <- which.min(dist)
+       if (dist[sel] > tolerance)
+       	  cat(gettext("Warning:  no point within tolerance\n"))
+       else if (sel %in% selected)
+          cat(gettext("Warning:  nearest point already identified\n"))
+       else {
+          selected <<- c(selected, sel)
+          if (plot) 
+              text3d(x[sel], y[sel], z[sel], texts=labels[sel], adj=adj)
+       }
+    }
+    
+    doquit <- FALSE
+    
+    quit <- function(mousex, mousey) {
+       doquit <<- TRUE
+    }
+    
+    rgl.setMouseCallbacks(buttons[1], begin=select)
+    if (length(buttons) > 1)
+    	rgl.setMouseCallbacks(buttons[2], begin=quit)
+    
+    while(!doquit && length(selected) < n) Sys.sleep(0.2)
+    selected
+}
+
+    
+    
+    
\ No newline at end of file
diff --git a/R/internal.R b/R/internal.R
new file mode 100644
index 0000000..c897120
--- /dev/null
+++ b/R/internal.R
@@ -0,0 +1,146 @@
+##
+## R source file
+## This file is part of rgl
+##
+## $Id: internal.R 1248 2015-05-18 20:33:32Z murdoch $
+##
+
+##
+## ===[ SECTION: internal ]===================================================
+##
+
+#
+# rgl.range
+#
+# ensure value x is between low and high
+#
+
+rgl.range <- function ( x, low, high )
+{
+  if (length(x) > 1)
+    stop( gettextf("'%s' must be a single numeric", deparse(substitute(x))), domain = NA)
+  if ( ( x < low ) || ( x > high ) )
+    stop( gettextf("'%s' must be a numeric in the range [%s, %s]", 
+    	           deparse(substitute(x)), low, high), domain = NA)
+}
+
+
+#
+# rgl.clamp
+#
+# clamp value if lower than low or higher than high
+#
+
+rgl.clamp <- function(value, low, high)
+{
+  if (value < low) {
+    warning( gettextf("Value clamped to %s",low), domain = NA )
+    result <- low
+  }
+  else if (value > high) {
+    warning( gettextf("Value clamped to %s",high), domain = NA )
+    result <- high
+  }
+  else {
+    result <- value
+  }
+
+  return (result);
+}
+
+##
+## types verification
+##
+
+
+#
+# single field bool
+#
+
+rgl.bool <- function ( x )
+{
+  if (length(x) > 1)
+    stop( gettextf("'%s' must be a single boolean value", deparse(substitute(x))),
+          domain = NA)
+}
+
+
+#
+# single field numeric
+#
+
+rgl.numeric <- function ( x )
+{
+  if (length(x) > 1)
+    stop( gettextf("'%s' must be a single numeric value", deparse(substitute(x))),
+          domain = NA)
+}
+
+
+#
+# vertex data object
+#
+
+rgl.vertex <- function (x,y=NULL,z=NULL)
+{
+  xyz <- xyz.coords(x,y,z,recycle=TRUE)
+  return ( matrix( rbind(xyz$x,xyz$y,xyz$z), nrow=3, dimnames=list( c("x","y","z"), NULL ) ) )
+}
+
+#
+# texture coordinate data object
+#
+
+rgl.texcoords <- function(s,t=NULL) 
+{
+  xy <- xy.coords(s, t, recycle=TRUE)
+  return( matrix( rbind(xy$x, xy$y), nrow=2, dimnames=list( c("s", "t"), NULL ) ) )
+}
+
+#
+# obtain number of vertices
+#
+
+rgl.nvertex <- function (vertex)
+{  
+  return ( ncol(vertex) )
+}
+
+
+#
+# rgl.color - single field color
+#
+
+rgl.color <- function ( color )
+{
+  if (length(color) > 1)
+    stop( gettextf("'%s' must be a single color character string", deparse(substitute(color))), 
+          domain = NA)
+  else
+    return (col2rgb(color))
+}
+
+
+#
+# rgl.mcolor - multiple field colors
+#
+
+rgl.mcolor <- function ( colors )
+{
+  return ( col2rgb(colors) )
+}
+
+
+#
+# if vattr > 1, recycle data
+#
+
+rgl.attr <- function (vattr, nvertex) 
+{
+  nvattr <- length(vattr)
+
+  if ((nvattr > 1) && (nvattr != nvertex))
+    vattr  <- rep(vattr,length.out=nvertex)
+  
+  return(vattr)
+}
diff --git a/R/material.R b/R/material.R
new file mode 100644
index 0000000..a237bdc
--- /dev/null
+++ b/R/material.R
@@ -0,0 +1,171 @@
+##
+## R source file
+## This file is part of rgl
+##
+## $Id: material.R 1248 2015-05-18 20:33:32Z murdoch $
+##
+
+##
+## ===[ SECTION: generic appearance function ]================================
+##
+
+rgl.material <- function (
+  color        = c("white"),
+  alpha        = c(1.0),
+  lit          = TRUE, 
+  ambient      = "black",
+  specular     = "white", 
+  emission     = "black", 
+  shininess    = 50.0, 
+  smooth       = TRUE,
+  texture      = NULL, 
+  textype      = "rgb", 
+  texmipmap    = FALSE, 
+  texminfilter = "linear", 
+  texmagfilter = "linear",
+  texenvmap    = FALSE,
+  front        = "fill", 
+  back         = "fill",
+  size         = 3.0,
+  lwd          = 1.0, 
+  fog          = TRUE,
+  point_antialias = FALSE,
+  line_antialias = FALSE,
+  depth_mask   = TRUE,
+  depth_test   = "less",
+  ...
+) {
+  # solid or diffuse component
+
+  color     <- rgl.mcolor(color)
+  if (length(color) < 1)
+    stop("There must be at least one color")
+
+  # light properties
+
+  ambient   <- rgl.color(ambient)
+  specular  <- rgl.color(specular)
+  emission  <- rgl.color(emission)
+
+  # others
+
+  rgl.bool(lit)
+  rgl.bool(fog)
+  rgl.bool(smooth)
+  rgl.bool(point_antialias)
+  rgl.bool(line_antialias)
+  rgl.bool(depth_mask)
+  rgl.clamp(shininess,0,128)
+  rgl.numeric(size)
+  rgl.numeric(lwd)
+  depth_test <- rgl.enum.depthtest(depth_test)
+  
+  # side-dependant rendering
+
+  front <- rgl.enum.polymode(front)
+  back  <- rgl.enum.polymode(back)
+
+  # texture mapping
+
+  rgl.bool(texmipmap)
+
+  if (length(texture) > 1)
+    stop("'texture' should be a single character string or NULL")
+
+  if (is.null(texture))
+    texture <- ""
+  else 
+    texture <- normalizePath(texture)
+
+  textype <- rgl.enum.textype( textype )
+  texminfilter <- rgl.enum.texminfilter( texminfilter )
+  texmagfilter <- rgl.enum.texmagfilter( texmagfilter )
+  rgl.bool(texenvmap)
+
+  # vector length
+
+  ncolor <- dim(color)[2]
+  nalpha <- length(alpha)
+
+  # pack data
+
+  idata <- as.integer( c( ncolor, lit, smooth, front, back, fog, 
+                          textype, texmipmap, texminfilter, texmagfilter, 
+                          nalpha, ambient, specular, emission, texenvmap, 
+                          point_antialias, line_antialias, 
+                          depth_mask, depth_test, color) )
+  cdata <- as.character(c( texture ))
+  ddata <- as.numeric(c( shininess, size, lwd, alpha ))
+
+  ret <- .C( rgl_material,
+    success = FALSE,
+    idata,
+    cdata,
+    ddata
+  )
+}
+
+rgl.getcolorcount <- function() .C( rgl_getcolorcount, count=integer(1) )$count
+  
+rgl.getmaterial <- function(ncolors, id = NULL) {
+
+  if (!length(id)) id <- 0L
+  if (missing(ncolors))
+    ncolors <- if (id) rgl.attrib.count(id, "colors") else rgl.getcolorcount()
+  
+  idata <- rep(0, 25+3*ncolors)
+  idata[1] <- ncolors
+  idata[11] <- ncolors
+  
+  cdata <- paste(rep(" ", 512), collapse="")
+  ddata <- rep(0, 3+ncolors)
+  
+  ret <- .C( rgl_getmaterial,
+    success = FALSE,
+    id = as.integer(id),
+    idata = as.integer(idata),
+    cdata = cdata,
+    ddata = as.numeric(ddata)
+  )
+  
+  if (!ret$success) stop('rgl.getmaterial')
+  
+  polymodes <- c("filled", "lines", "points", "culled")
+  textypes <- c("alpha", "luminance", "luminance.alpha", "rgb", "rgba")
+  minfilters <- c("nearest", "linear", "nearest.mipmap.nearest", "nearest.mipmap.linear", 
+                  "linear.mipmap.nearest", "linear.mipmap.linear")
+  magfilters <- c("nearest", "linear")
+  depthtests <- c("never", "less", "equal", "lequal", "greater", 
+                  "notequal", "gequal", "always")
+  idata <- ret$idata
+  ddata <- ret$ddata
+  cdata <- ret$cdata
+  
+  list(color = rgb(idata[23 + 3*(seq_len(idata[1]))], 
+                   idata[24 + 3*(seq_len(idata[1]))], 
+                   idata[25 + 3*(seq_len(idata[1]))], maxColorValue = 255),
+       alpha = if (idata[11]) ddata[seq(from=4, length=idata[11])] else 1,
+       lit = idata[2] > 0,
+       ambient = rgb(idata[12], idata[13], idata[14], maxColorValue = 255),
+       specular = rgb(idata[15], idata[16], idata[17], maxColorValue = 255),
+       emission = rgb(idata[18], idata[19], idata[20], maxColorValue = 255),
+       shininess = ddata[1],
+       smooth = idata[3] > 0,
+       texture = if (cdata == "") NULL else cdata,
+       textype      = textypes[idata[7]], 
+       texmipmap    = idata[8] == 1,
+       texminfilter = minfilters[idata[9] + 1],
+       texmagfilter = magfilters[idata[10] + 1],
+       texenvmap    = idata[21] == 1,
+       front = polymodes[idata[4]],
+       back = polymodes[idata[5]],
+       size = ddata[2],
+       lwd  = ddata[3],
+       fog = idata[6] > 0,
+       point_antialias = idata[22] == 1,
+       line_antialias = idata[23] == 1,
+       depth_mask = idata[24] == 1,
+       depth_test = depthtests[idata[25] + 1]
+       )
+                   
+}
diff --git a/R/matrices.R b/R/matrices.R
new file mode 100644
index 0000000..97912d7
--- /dev/null
+++ b/R/matrices.R
@@ -0,0 +1,81 @@
+# Functions for creating 4x4 graphics matrices
+
+identityMatrix <- function() diag(nrow=4)
+
+scaleMatrix <- function(x,y,z) diag(c(x,y,z,1))
+
+translationMatrix <- function(x,y,z)
+{
+    result <- diag(4)
+    result[4,1:3] <- c(x,y,z)
+    result
+}
+
+rotationMatrix <- function(angle,x,y,z,matrix)
+{
+    if (missing(matrix))
+    {
+    	if (angle == 0) return(identityMatrix())
+    	
+        u <- c(x,y,z)/sqrt(x^2+y^2+z^2)
+        cosa <- cos(angle)
+        sina <- sin(angle)
+        matrix <- (1-cosa)*outer(u,u)
+        matrix <- matrix + diag(3)*cosa
+        matrix[1,2] <- matrix[1,2] - sina*u[3]
+        matrix[1,3] <- matrix[1,3] + sina*u[2]
+        matrix[2,1] <- matrix[2,1] + sina*u[3]
+        matrix[2,3] <- matrix[2,3] - sina*u[1]
+        matrix[3,1] <- matrix[3,1] - sina*u[2]
+        matrix[3,2] <- matrix[3,2] + sina*u[1]
+    }
+    if (identical(all.equal(dim(matrix), c(3,3)), TRUE)) 
+        matrix <- cbind(rbind(matrix,c(0,0,0)),c(0,0,0,1))
+    return(matrix)    
+}
+
+# Coordinate conversions
+
+asHomogeneous <- function(x) {
+    if (is.matrix(x) && dim(x)[2] == 3) return(cbind(x,1))
+    else if (length(x) == 3) return(c(x,1))
+    else stop("'x' is not row vector(s)")
+}
+
+asEuclidean <- function(x) {
+    if (is.matrix(x) && dim(x)[2] == 4) return(x[,1:3]/x[,4])
+    else if (length(x) == 4) return(c(x[1]/x[4],x[2]/x[4],x[3]/x[4]))
+    else stop("'x' is not row vectors(s)")
+}
+
+# Default implementations of transformations
+
+translate3d.default <- function(obj,x,y,z,...) {
+    if (is.matrix(obj)) n <- dim(obj)[1]
+    else n <- 1
+        
+    if (length(obj) == 3 || (is.matrix(obj) && dim(obj)[2] == 3))
+    	return(obj + cbind(rep(x,n), rep(y,n), rep(z,n)))
+    else if (length(obj) == 4 || (is.matrix(obj) && dim(obj)[2] == 4))
+	return(obj %*% translationMatrix(x,y,z))
+    else stop("Unsupported object for translation")
+}
+	
+scale3d.default <- function(obj,x,y,z,...){
+    if (is.matrix(obj)) n <- dim(obj)[1]
+    else n <- 1
+        
+    if (length(obj) == 3 || (is.matrix(obj) && dim(obj)[2] == 3))
+    	return(obj * cbind(rep(x,n), rep(y,n), rep(z,n)))
+    else if (length(obj) == 4 || (is.matrix(obj) && dim(obj)[2] == 4))
+    	return(obj %*% scaleMatrix(x,y,z))
+    else stop("Unsupported object for scaling")
+}
+
+rotate3d.default <- function(obj,angle,x,y,z,matrix,...) {
+    if (length(obj) == 3 || (is.matrix(obj) && dim(obj)[2] == 3))
+    	return(asEuclidean(asHomogeneous(obj) %*% rotationMatrix(angle,x,y,z,matrix)))
+    else if (length(obj) == 4 || (is.matrix(obj) && dim(obj)[2] == 4))
+    	return(obj %*% rotationMatrix(angle,x,y,z,matrix))
+    else stop("Unsupported object for rotation")
+}    
diff --git a/R/mesh3d.R b/R/mesh3d.R
new file mode 100644
index 0000000..a0bba5f
--- /dev/null
+++ b/R/mesh3d.R
@@ -0,0 +1,200 @@
+#
+# triangle mesh object
+#
+
+tmesh3d <- function( vertices, indices, homogeneous=TRUE, material=NULL, normals=NULL,
+                     texcoords=NULL) {
+  if (homogeneous == TRUE)
+    vrows <- 4
+  else
+    vrows <- 3
+    
+  nvertex <- length(vertices)/vrows
+  if ( !is.null(normals) ) {
+    normals <- xyz.coords(normals, recycle=TRUE)
+    x <- rep(normals$x, len=nvertex)
+    y <- rep(normals$y, len=nvertex)
+    z <- rep(normals$z, len=nvertex)
+    normals <- rgl.vertex(x,y,z)
+  }
+  if ( !is.null(texcoords) ) {
+    texcoords <- xy.coords(texcoords, recycle=TRUE)
+    x <- rep(texcoords$x, len=nvertex)
+    y <- rep(texcoords$y, len=nvertex)
+    texcoords <- rbind(x,y)
+  }
+  object <- list(
+    vb=matrix(vertices,nrow=vrows),
+    it=matrix(indices,nrow=3),
+    primitivetype="triangle",
+    material=material,
+    normals=normals,
+    texcoords=texcoords
+  ) 
+  
+  if (!homogeneous) object$vb <- rbind(object$vb, 1)
+  
+  class(object) <- c("mesh3d", "shape3d")
+  return( object )
+}
+
+#
+# R 3d object : quad mesh
+#
+
+qmesh3d <- function( vertices, indices, homogeneous=TRUE, material=NULL, normals=NULL,
+                     texcoords=NULL) {
+  if (homogeneous == TRUE)
+    vrows <- 4
+  else
+    vrows <- 3    
+  nvertex <- length(vertices)/vrows
+  if ( !is.null(normals) ) {
+    normals <- xyz.coords(normals, recycle=TRUE)
+    x <- rep(normals$x, len=nvertex)
+    y <- rep(normals$y, len=nvertex)
+    z <- rep(normals$z, len=nvertex)
+    normals <- rgl.vertex(x,y,z)
+  }
+  if ( !is.null(texcoords) ) {
+    texcoords <- xy.coords(texcoords, recycle=TRUE)
+    x <- rep(texcoords$x, len=nvertex)
+    y <- rep(texcoords$y, len=nvertex)
+    texcoords <- rbind(x,y)
+  }  
+  object <- list(
+    vb=matrix(vertices,nrow=vrows),
+    ib=matrix(indices,nrow=4),
+    primitivetype="quad",
+    material=material,
+    normals=normals,
+    texcoords=texcoords
+  ) 
+  
+  if (!homogeneous) object$vb <- rbind(object$vb, 1)
+  
+  class(object) <- c("mesh3d", "shape3d")
+  return( object )
+}
+
+# rendering support
+
+dot3d.mesh3d <- function ( x, override = TRUE, ... ) {
+  if ( override ) {
+    material <- x$material
+    if (is.null(material)) material <- list()
+    material[names(list(...))] <- list(...)
+  } else {
+    material <- list(...)
+    material[names(x$material)] <- x$material
+  }
+  
+  do.call("points3d", args = c(list(x = x$vb[1,]/x$vb[4,], 
+                                    y = x$vb[2,]/x$vb[4,], 
+                                    z = x$vb[3,]/x$vb[4,]), 
+                               material ))
+}     
+
+dot3d.qmesh3d <- dot3d.mesh3d   # for back-compatibility
+  
+wire3d.mesh3d <- function ( x, override = TRUE, ... ) {
+  if ( override ) {
+    material <- x$material
+    if (is.null(material)) material <- list()    
+    material[names(list(...))] <- list(...)
+  } else {
+    material <- list(...)
+    material[names(x$material)] <- x$material
+  }
+  material["front"] <- "lines"
+  material["back"] <- "lines"
+  
+  result <- integer(0)
+  if (!is.null(x$it))
+    result <- c(triangles = do.call("triangles3d", args = c(list(x = x$vb[1,x$it]/x$vb[4,x$it],
+                                         y = x$vb[2,x$it]/x$vb[4,x$it],
+                                         z = x$vb[3,x$it]/x$vb[4,x$it]), 
+                                    material)))
+  if (!is.null(x$ib))
+    result <- c(result, quads = do.call("quads3d", args = c(list(x = x$vb[1,x$ib]/x$vb[4,x$ib],
+                                     y = x$vb[2,x$ib]/x$vb[4,x$ib],
+                                     z = x$vb[3,x$ib]/x$vb[4,x$ib]), 
+                                material)))
+  invisible(result)
+}
+
+shade3d.mesh3d <- function ( x, override = TRUE, ... ) {
+  if ( override ) {
+    material <- x$material
+    if (is.null(material)) material <- list()    
+    material[names(list(...))] <- list(...)
+  } else {
+    material <- list(...)
+    material[names(x$material)] <- x$material
+  }
+  result <- integer(0)
+  skipRows <- 0
+  if (!is.null(x$it)) {
+    args <- c(list(x = x$vb[1,x$it]/x$vb[4,x$it],
+                   y = x$vb[2,x$it]/x$vb[4,x$it],
+                   z = x$vb[3,x$it]/x$vb[4,x$it]), 
+                   material)
+    if (!is.null(x$normals) && is.null(args$normals)) 
+      args <- c(args, list(normals = t(x$normals[,x$it])))
+    if (!is.null(x$texcoords) && is.null(args$texcoords))
+      args <- c(args, list(texcoords = t(x$texcoords[,x$it])))
+      
+    result <- c(triangles = do.call("triangles3d", args = args ))
+  }
+  if (!is.null(x$ib)) {
+    args <- c(list(x = x$vb[1,x$ib]/x$vb[4,x$ib],
+                   y = x$vb[2,x$ib]/x$vb[4,x$ib],
+                   z = x$vb[3,x$ib]/x$vb[4,x$ib]), 
+                   material)
+    if (!is.null(x$normals) && is.null(args$normals)) 
+      args <- c(args, list(normals = t(x$normals[,x$ib])))
+    if (!is.null(x$texcoords) && is.null(args$texcoords))
+      args <- c(args, list(texcoords = t(x$texcoords[,x$ib])))
+    
+    result <- c(result, quads = do.call("quads3d", args = args ))
+  }
+  invisible(result)
+}
+
+# transformation support
+
+translate3d.mesh3d <- function ( obj, x, y, z, ... ) {
+  obj$vb <- t(translate3d(t(obj$vb), x, y, z))
+  return(obj)                            
+}  
+
+rotate3d.mesh3d <- function ( obj,angle,x,y,z,matrix, ... ) {
+  obj$vb <- t(rotate3d(t(obj$vb), angle, x, y, z, matrix))
+  if ( !is.null(obj$normals) ) {
+    if ( missing(matrix) ) 
+      obj$normals <- rotate3d(t(obj$normals), angle, x, y, z)
+    else {
+      if (nrow(matrix) == 4) matrix[4,1:3] <- 0
+      if (ncol(matrix) == 4) matrix[1:3,4] <- 0
+      obj$normals <- rotate3d(t(obj$normals), angle, x, y, z, t(solve(matrix)))
+    }
+    obj$normals <- t( obj$normals/sqrt(apply(obj$normals^2, 1, sum)) )
+  }
+  return(obj)                            
+}  
+
+scale3d.mesh3d <- function ( obj, x, y, z, ... ) {
+  obj$vb <- t(scale3d(t(obj$vb), x, y, z))
+  if ( !is.null(obj$normals) ) {
+    obj$normals <- scale3d(t(obj$normals), 1/x, 1/y, 1/z)
+    obj$normals <- t( obj$normals/sqrt(apply(obj$normals[,1:3]^2, 1, sum)) )
+    obj$normals[4,] <- 1
+  }
+  return(obj)
+}
+
+# for back-compatibility
+translate3d.qmesh3d <- translate3d.mesh3d
+rotate3d.qmesh3d <- rotate3d.mesh3d
+scale3d.qmesh3d <- scale3d.mesh3d
+
diff --git a/R/obj.R b/R/obj.R
new file mode 100644
index 0000000..dec7b8a
--- /dev/null
+++ b/R/obj.R
@@ -0,0 +1,363 @@
+writeOBJ <- function(con,
+                     pointRadius=0.005, 
+                     pointShape = icosahedron3d(),
+                     lineRadius = pointRadius,
+                     lineSides = 20,
+                     pointsAsPoints = FALSE,
+                     linesAsLines = FALSE,
+                     withNormals = TRUE,
+                     withTextures = TRUE,
+                     separateObjects = TRUE,
+                     ids = NULL) {
+ 
+  writeHeader <- function() {
+    ident <- paste(filename, " produced by RGL")
+    cat("#", ident, "\n", file=con)
+  }   
+    
+  Vertices <- 0
+  Normals <- 0
+  Texcoords <- 0
+  
+  writeData <- function(id) {
+    vbase <- Vertices
+    tbase <- Texcoords
+    nbase <- Normals
+    vertices <- rgl.attrib(id, "vertices")
+    cat(paste("v", vertices[,1], vertices[,2], vertices[,3]), 
+        sep="\n", file=con)
+    n <- nrow(vertices)
+    Vertices <<- Vertices + n
+    if (withTextures) {
+      textures <- rgl.attrib(id, "texcoords")
+      if (nrow(textures)) 
+        cat(paste("vt", textures[,1], textures[,2]),
+          sep="\n", file=con)
+      Texcoords <<- Texcoords + nrow(textures)
+    }
+    if (withNormals) {
+      normals <- rgl.attrib(id, "normals")
+      if (nrow(normals))
+        cat(paste("vn", normals[,1], normals[,2], normals[,3]),
+          sep="\n", file=con)
+      Normals <<- Normals + nrow(normals)
+    }
+    list(n=n, 
+         ntexcoords=if (withTextures) nrow(textures) else 0,
+         nnormals=if (withNormals) nrow(normals) else 0,
+         vbase=vbase,
+         tbase=tbase,
+         nbase=nbase)
+  }
+  
+  refnum <- function(n) sprintf("%d", n)
+  
+  writeTriangles <- function(id) {
+    if (separateObjects)
+      cat("o triangles", id, "\n", sep="", file=con)
+    x <- writeData(id)
+    indices <- refnum(x$vbase + seq_len(x$n))
+    if (x$ntexcoords)
+      indices <- paste0(indices, "/", refnum(x$tbase + seq_len(x$n)))
+    if (x$nnormals)
+      indices <- paste0(indices, if (!x$ntexcoords) "/", 
+      			"/", refnum(x$nbase + seq_len(x$n)))
+    indices <- matrix(indices, ncol=3, byrow=TRUE)
+    cat(paste("f", indices[,1], indices[,2], indices[,3]), 
+        sep="\n", file=con)
+  }
+  
+  writeQuads <- function(id) {
+    if (separateObjects)
+      cat("o quads", id, "\n", sep="", file=con)
+    x <- writeData(id)
+    indices <- refnum(x$vbase + seq_len(x$n))
+    if (x$ntexcoords)
+      indices <- paste0(indices, "/", refnum(x$tbase + seq_len(x$n)))
+    if (x$nnormals)
+      indices <- paste0(indices, if (!x$ntexcoords) "/", 
+      			"/", refnum(x$nbase + seq_len(x$n)))
+    indices <- matrix(indices, ncol=4, byrow=TRUE)
+    cat(paste("f", indices[,1], indices[,2], indices[,3], indices[,4]), 
+        sep="\n", file=con)
+  }
+      
+  writeSurface <- function(id) {
+    if (separateObjects)
+      cat("o surface", id, "\n", sep="", file=con)
+    x <- writeData(id)
+    dims <- rgl.attrib(id, "dim")
+    nx <- dims[1]
+    nz <- dims[2]
+    rows <- seq_len(nx)
+    
+    vertices <- matrix(character(0), ncol=3)
+    for (i in seq_len(nz)[-nz]) {
+      indices <- (i-1)*nx + 
+      		c(rows[-nx],rows[-nx],
+                  rows[-1]+nx,rows[-nx]+nx,
+                  rows[-1],rows[-1]+nx)
+      cindices <- refnum(x$vbase + indices)
+      if (x$ntexcoords)
+        cindices <- paste0(cindices, "/", refnum(x$tbase + indices))
+      if (x$nnormals)
+        cindices <- paste0(cindices, if (!x$ntexcoords) "/",
+                           "/", refnum(x$nbase + indices))
+      vertices <- rbind(vertices, matrix(cindices, ncol=3))
+    }
+    cat(paste("f", vertices[,1], vertices[,2], vertices[,3]),
+        sep="\n", file=con)
+  }      
+  
+  writeMesh <- function(mesh, scale=1, offset=c(0,0,0)) {
+    vertices <- asEuclidean(t(mesh$vb))*scale 
+    n <- nrow(vertices)
+    vertices <- vertices + rep(offset, each=n)
+    vbase <- Vertices
+    cat(paste("v", vertices[,1], vertices[,2], vertices[,3]), 
+        sep="\n", file=con)
+    Vertices <<- Vertices + n
+    if (withTextures && length(textures <- mesh$texcoords)) {
+      tbase <- Texcoords
+      textures <- asEuclidean(t(textures))
+      cat(paste("vt", textures[,1], textures[,2]),
+          sep="\n", file=con)
+      Texcoords <<- Texcoords + nrow(textures)
+    } else
+      withTextures <- FALSE
+    if (withNormals && length(normals <- mesh$normals)) {
+      nbase <- Normals
+      normals <- asEuclidean(t(normals))
+      cat(paste("vn", normals[,1], normals[,2], normals[,3]),
+          sep="\n", file=con)
+      Normals <<- Normals + nrow(normals)
+    } else
+      withNormals <- FALSE
+    nt <- length(mesh$it)/3
+    nq <- length(mesh$ib)/4
+    if (nt) {
+      indices <- t(mesh$it)
+      cindices <- refnum(vbase + indices)
+      if (withTextures)
+        cindices <- paste0(cindices, "/", refnum(tbase + indices))
+      if (withNormals)
+        cindices <- paste0(cindices, if (!withTextures) "/",
+                           "/", refnum(nbase + indices))
+      cindices <- matrix(cindices, ncol=3)
+      cat(paste("f", cindices[,1], cindices[,2], cindices[,3]), 
+          sep="\n", file=con)
+    }
+    if (nq) {
+      indices <- t(mesh$ib)
+      cindices <- refnum(vbase + indices)
+      if (withTextures)
+        cindices <- paste0(cindices, "/", refnum(tbase + indices))
+      if (withNormals)
+        cindices <- paste0(cindices, if (!withTextures) "/",
+                           "/", refnum(nbase + indices))
+      cindices <- matrix(cindices, ncol=4)
+      cat(paste("f", cindices[,1], cindices[,2], 
+                     cindices[,3], cindices[,4]), 
+          sep="\n", file=con)
+    }
+  }
+
+  writeSpheres <- function(id) {
+    if (separateObjects)
+      cat("o sphere", id, "\n", sep="", file=con) 
+    vertices <- rgl.attrib(id, "vertices")
+    n <- nrow(vertices)    
+    radii <- rgl.attrib(id, "radii")
+    radii <- rep(radii, length.out=n)
+    x <- subdivision3d(icosahedron3d(),3)
+    r <- sqrt(x$vb[1,]^2 + x$vb[2,]^2 + x$vb[3,]^2)
+    x$vb[4,] <- r
+    x$normals <- x$vb
+    for (i in seq_len(n)) 
+      writeMesh(x, radii[i], vertices[i,])
+  }  
+  
+  avgScale <- function() {
+    bbox <- par3d("bbox")
+    ranges <- c(bbox[2]-bbox[1], bbox[4]-bbox[3], bbox[6]-bbox[5])
+    if (prod(ranges) == 0) 1
+    else exp(mean(log(ranges)))
+  }  
+   
+  writePoints <- function(id) {
+    if (separateObjects)
+      cat("o points", id, "\n", sep="", file=con)
+    if (pointsAsPoints) {
+      x <- writeData(id)
+      cat("p", refnum(x$vbase + seq_len(x$n)), "\n", file=con)
+    } else {
+      vertices <- rgl.attrib(id, "vertices")
+      n <- nrow(vertices)
+      radius <- pointRadius*avgScale()
+      if (withNormals && is.null(pointShape$normals))
+        pointShape <- addNormals(pointShape)
+      for (i in seq_len(n)) 
+        writeMesh(pointShape, radius, vertices[i,])
+    }
+  }
+  
+  writeSegments <- function(id) {
+    if (separateObjects)
+      cat("o segments", id, "\n", sep="", file=con)
+    if (linesAsLines) {
+      x <- writeData(id)
+      indices <- matrix(refnum(x$vbase + seq_len(x$n)), ncol=2, byrow=TRUE)
+      cat(paste("l", indices[,1], indices[,2]), sep="\n", file=con)
+    } else {
+      vertices <- rgl.attrib(id, "vertices")
+      n <- nrow(vertices)    
+      n <- n/2
+      radius <- lineRadius*avgScale()
+      for (i in seq_len(n)) {
+        cyl <- cylinder3d( vertices[(2*i-1):(2*i),1:3],
+     			   radius = radius,
+     			   sides = lineSides, 
+     			   closed = -2 )
+        if (withNormals)
+          cyl <- addNormals(cyl)
+        writeMesh(cyl)
+      }
+    }
+  }
+  
+  writeLines <- function(id) {
+    if (separateObjects)
+      cat("o lines", id, "\n", sep="", file=con)
+    if (linesAsLines) {
+      x <- writeData(id)
+      indices <- refnum(x$vbase + seq_len(x$n))
+      cat("l", indices, "\n", file=con)
+    } else {
+      vertices <- rgl.attrib(id, "vertices")
+      n <- nrow(vertices) - 1
+      radius <- lineRadius*avgScale()
+      for (i in seq_len(n)) {
+        cyl <- cylinder3d( vertices[i:(i+1),],
+     			   radius = radius,
+     			   sides = lineSides, 
+     			   closed = -2 )
+        if (withNormals) 
+          cyl <- addNormals(cyl)
+        writeMesh(cyl)
+      }
+    }
+  }
+  
+  knowntypes <- c("triangles", "quads", #,
+                  "surface", "spheres", "points", 
+                  "linestrip", "lines", "planes")
+  
+  #  Execution starts here!
+
+  if (is.character(con)) {
+    con <- file(con, "w")
+    on.exit(close(con))
+  }
+  filename <- summary(con)$description
+  
+  if (NROW(bbox <- rgl.ids("bboxdeco")) && (is.null(ids) || bbox$id %in% ids)) {
+    ids <- setdiff(ids, bbox$id)
+    save <- par3d(skipRedraw = TRUE)
+    bbox <- convertBBox(bbox$id)
+    on.exit({ rgl.pop(id=bbox); par3d(save) }, add=TRUE)
+    dobbox <- TRUE
+  } else dobbox <- FALSE 
+  
+  if (is.null(ids)) {
+    ids <- rgl.ids()
+    types <- as.character(ids$type)
+    ids <- ids$id
+  } else {
+    if (dobbox) ids <- c(ids, bbox)
+    allids <- rgl.ids()
+    ind <- match(ids, allids$id)
+    keep <- !is.na(ind)
+    if (any(!keep)) warning(gettextf("Object(s) with id %s not found", paste(ids[!keep], collapse=" ")),
+    			    domain = NA)
+    ids <- ids[keep]
+    types <- allids$type[ind[keep]]
+  }  
+    
+  unknowntypes <- setdiff(types, knowntypes)
+  if (length(unknowntypes))
+    warning(gettextf("Object type(s) %s not handled", 
+      paste("'", unknowntypes, "'", sep="", collapse=", ")), domain = NA)
+
+  keep <- types %in% knowntypes
+  ids <- ids[keep]
+  types <- types[keep]
+  
+  writeHeader()
+
+  for (i in seq_along(ids)) 
+    switch(types[i],
+      planes =,
+      triangles = writeTriangles(ids[i]),
+      quads = writeQuads(ids[i]),
+      surface = writeSurface(ids[i]),
+      spheres = writeSpheres(ids[i]),
+      points = writePoints(ids[i]),
+      lines = writeSegments(ids[i]),
+      linestrip = writeLines(ids[i])
+    )
+  
+  invisible(filename)
+}
+
+readOBJ <- function(con, ...) {
+  lines <- readLines(con)
+  instrs <- sub(" .*", "", lines)
+  vertices <- read.table(textConnection(lines[instrs == "v"]),
+                         col.names = c("instr", "x", "y", "z"),
+                         colClasses = c(instr = "character", 
+                                        x="numeric",
+                                        y="numeric",
+                                        z="numeric"))
+  vertices <- with(vertices, rbind(x, y, z))
+  tfaces <- grepl("^f\\W+\\w+\\W+\\w+\\W+\\w+$", lines)
+  triangles <- read.table(textConnection(lines[tfaces]),
+                      col.names = c("instr", "v1", "v2", "v3"),
+                      colClasses = "character")
+  triangles <- with(triangles, rbind(v1, v2, v3))
+  if (length(grep("/", triangles))) {
+    warning("Normals and/or textures ignored")
+    triangles <- sub("/.*", "", triangles)   
+  }
+  triangles <- structure(as.numeric(triangles),
+                         dim = dim(triangles))
+  qfaces <- grepl("^f\\W+\\w+\\W+\\w+\\W+\\w+\\W+\\w+$", lines)
+  if (any(qfaces)) {
+    quads <- read.table(textConnection(lines[qfaces]),
+                        col.names = c("instr", "v1", "v2", "v3", "v4"),
+                        colClasses = "character")
+    quads <- with(quads, rbind(v1, v2, v3, v4))
+    if (length(grep("/", quads))) {
+      warning("Normals and/or textures ignored")
+      quads <- sub("/.*", "", quads)
+    }
+    quads <- structure(as.numeric(quads), dim = dim(quads))
+  }
+  others <- strsplit(lines[instrs == "f" & !tfaces & !qfaces], " ")
+  # FIXME:  this will be really slow if there are a lot of others
+  # Should pre-allocate extra space.
+  for (i in seq_along(others)) {
+    v <- as.numeric(others[[i]][-1])
+    tri <- triangulate(t(vertices[,v]))
+    tri <- structure(v[tri], dim = dim(tri))
+    triangles <- cbind(triangles, tri)
+  }  
+  ignored <- unique(instrs)
+  ignored <- ignored[!(ignored %in% c("v", "f", "", "#"))]
+  if (length(ignored))
+    warning(gettextf("Instructions %s ignored", paste0('"', ignored, '"', collapse = ", ")),
+    	    domain = NA)
+  result <- tmesh3d(vertices, triangles, homogeneous = FALSE, ...)
+  if (any(qfaces)) 
+    result$ib <- quads
+  result
+}
diff --git a/R/oh3d.R b/R/oh3d.R
new file mode 100644
index 0000000..baff80e
--- /dev/null
+++ b/R/oh3d.R
@@ -0,0 +1,98 @@
+#
+# R 3d object : o3d
+# $Id: oh3d.R 394 2005-08-08 13:28:14Z dmurdoch $
+#
+
+oh3d.vb <- c(   
+    -1.5, -1.5, -0.5, 1.0,   # 1
+    -0.5, -1.5, -0.5, 1.0,   # 2
+     0.5, -1.5, -0.5, 1.0,   # 3
+     1.5, -1.5, -0.5, 1.0,   # 4
+
+    -1.5, -0.5, -0.5, 1.0,   # 5
+    -0.5, -0.5, -0.5, 1.0,   # 6
+     0.5, -0.5, -0.5, 1.0,   # 7
+     1.5, -0.5, -0.5, 1.0,   # 8
+
+    -1.5,  0.5, -0.5, 1.0,   # 9
+    -0.5,  0.5, -0.5, 1.0,   # 10
+     0.5,  0.5, -0.5, 1.0,   # 11
+     1.5,  0.5, -0.5, 1.0,   # 12
+     
+    -1.5,  1.5, -0.5, 1.0,   # 13 
+    -0.5,  1.5, -0.5, 1.0,   # 14
+     0.5,  1.5, -0.5, 1.0,   # 15
+     1.5,  1.5, -0.5, 1.0,   # 16
+
+     
+    -1.5, -1.5,  0.5, 1.0,   # 17
+    -0.5, -1.5,  0.5, 1.0,   # 18
+     0.5, -1.5,  0.5, 1.0,   # 19
+     1.5, -1.5,  0.5, 1.0,   # 20
+
+    -1.5, -0.5,  0.5, 1.0,   # 21
+    -0.5, -0.5,  0.5, 1.0,   # 22
+     0.5, -0.5,  0.5, 1.0,   # 23 
+     1.5, -0.5,  0.5, 1.0,   # 24
+
+    -1.5,  0.5,  0.5, 1.0,   # 25
+    -0.5,  0.5,  0.5, 1.0,   # 26
+     0.5,  0.5,  0.5, 1.0,   # 27
+     1.5,  0.5,  0.5, 1.0,   # 28
+     
+    -1.5,  1.5,  0.5, 1.0,   # 29
+    -0.5,  1.5,  0.5, 1.0,   # 30
+     0.5,  1.5,  0.5, 1.0,   # 31
+     1.5,  1.5,  0.5, 1.0    # 32         
+)
+
+oh3d.ib <- c(
+    1,  5,  6,  2,    
+    2,  6,  7,  3,    
+    3,  7,  8,  4,
+    
+    5,  9, 10,  6,    
+    7, 11, 12,  8,
+    
+    9, 13, 14, 10,
+   10, 14, 15, 11,
+   11, 15, 16, 12,
+   
+   17, 18, 22, 21,
+   18, 19, 23, 22,
+   19, 20, 24, 23,
+   
+   21, 22, 26, 25,
+   23, 24, 28, 27,
+   
+   25, 26, 30, 29,
+   26, 27, 31, 30,
+   27, 28, 32, 31,
+   
+    1,  2, 18, 17,
+    2,  3, 19, 18,
+    3,  4, 20, 19,
+    
+    6, 22, 23,  7,
+   10, 11, 27, 26,
+   
+   13, 29, 30, 14,
+   14, 30, 31, 15,
+   15, 31, 32, 16,
+   
+   17, 21,  5,  1,
+   21, 25,  9,  5,
+   25, 29, 13,  9,
+   
+    4,  8, 24, 20,
+    8, 12, 28, 24,
+   12, 16, 32, 28,
+   
+    6, 10, 26, 22,
+    7, 23, 27, 11  
+)
+
+oh3d <- function( trans = identityMatrix(), ... ) {
+  return(rotate3d(qmesh3d( oh3d.vb, oh3d.ib, material=list(...) ), matrix=trans))
+}
+
diff --git a/R/par3d.R b/R/par3d.R
new file mode 100644
index 0000000..2a16e82
--- /dev/null
+++ b/R/par3d.R
@@ -0,0 +1,66 @@
+.Par3d <- c("antialias", "FOV", "ignoreExtent", "listeners",
+	   "mouseMode", "observer", 
+	   "modelMatrix", "projMatrix", "skipRedraw", "userMatrix", 
+	   "scale", "viewport", "zoom", "bbox", "windowRect",
+           "family", "font", "cex", "useFreeType", "fontname",
+	   "maxClipPlanes"
+	   )
+	   
+.Par3d.readonly <- c( 
+	   "antialias", "observer",
+	   "modelMatrix", "projMatrix",
+	   "bbox", "fontname",
+	   "maxClipPlanes"
+	   )
+
+par3d <- function (..., no.readonly = FALSE, dev = rgl.cur(), subscene = currentSubscene3d(dev))
+{
+    single <- FALSE
+    args <- list(...)
+    if (!length(args))
+	args <- as.list(if (no.readonly)
+                        .Par3d[-match(.Par3d.readonly, .Par3d)]
+        else .Par3d)
+    else {
+	if (is.null(names(args)) && all(unlist(lapply(args, is.character))))
+	    args <- as.list(unlist(args))
+	if (length(args) == 1) {
+	    if (is.list(args[[1]]) | is.null(args[[1]]))
+		args <- args[[1]]
+	    else
+		if(is.null(names(args)))
+		    single <- TRUE
+	}
+    }
+    if ("dev" %in% names(args)) {
+        if (!missing(dev) && dev != args[["dev"]]) stop("'dev' specified inconsistently")
+        dev <- args[["dev"]]
+        args[["dev"]] <- NULL
+    }
+    if ("subscene" %in% names(args)) {
+        if (!missing(subscene) && subscene != args[["subscene"]]) stop("'subscene' specified inconsistently")
+        subscene <- args[["subscene"]]
+        args[["subscene"]] <- NULL
+    }
+    dev <- as.integer(dev)
+    if (!dev) dev <- open3d()
+    subscene <- as.integer(subscene)
+     
+    if ("userMatrix" %in% names(args)) {
+        m <- args$userMatrix
+        svd <- svd(m[1:3, 1:3])
+        m[1:3, 1:3] <- svd$u %*% t(svd$v)
+        theta <- atan2(-m[1,3], m[1,1])
+	m <-  m %*% rotationMatrix(theta, 0,1,0)
+	svd <- svd(m[1:3, 1:3])
+	m[1:3,1:3] <- svd$u %*% t(svd$v)	
+	phi <- atan2(-m[2,3], m[3,3])
+	args$.position <- c(theta, phi)*180/pi
+    }
+    value <-
+        if (single) .Call(rgl_par3d, dev, subscene, args)[[1]] 
+        else .Call(rgl_par3d, dev, subscene, args)
+
+    if(!is.null(names(args))) invisible(value) else value
+}
+
diff --git a/R/persp3d.R b/R/persp3d.R
new file mode 100644
index 0000000..30abf81
--- /dev/null
+++ b/R/persp3d.R
@@ -0,0 +1,156 @@
+persp3d <- function(x, ...) UseMethod("persp3d")
+
+
+persp3d.default <-
+function (x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)),
+    z, xlim = NULL, ylim = NULL, zlim = NULL,
+    xlab = NULL, ylab = NULL, zlab = NULL, add = FALSE, aspect = !add, 
+    forceClipregion = FALSE, ...)
+{
+    if (!add) next3d()
+    skip <- par3d(skipRedraw=TRUE)
+    on.exit(par3d(skip))
+    
+    if (is.null(xlab))
+        xlab <- if (!missing(x)) deparse(substitute(x)) else "X"
+    if (is.null(ylab))
+        ylab <- if (!missing(y)) deparse(substitute(y)) else "Y"
+    if (is.null(zlab))
+        zlab <- if (!missing(z)) deparse(substitute(z)) else "Z"
+    ## labcex is disregarded since we do NOT yet put  ANY labels...
+    if (missing(z)) {
+        if (!missing(x)) {
+            if (is.list(x)) {
+                z <- x$z
+                y <- x$y
+                x <- x$x
+            }
+            else {
+                z <- x
+                x <- seq(0, 1, len = nrow(z))
+            }
+        }
+        else stop("No 'z' matrix specified")
+    }
+    else if (is.list(x)) {
+        y <- x$y
+        x <- x$x
+    }
+    if ( (!is.matrix(x) && any(diff(x) <= 0)) 
+      || (!is.matrix(y) && any(diff(y) <= 0)))
+        stop("Increasing 'x' and 'y' values expected")
+        
+    savesubscene <- currentSubscene3d()
+    result <- setClipregion(xlim, ylim, zlim, forceClipregion)
+    result <- c(result, surface=surface3d(x,y,z,...))
+    useSubscene3d(savesubscene)
+    if (!add) 
+      result <- c(result, decorate3d(xlim = xlim, ylim = ylim, zlim = zlim, 
+                          xlab = xlab, ylab = ylab, zlab = zlab, aspect = aspect, ...))
+    invisible(result)
+}
+
+setClipregion <- function(xlim = NULL, ylim = NULL, zlim = NULL, force = FALSE) {
+  if (force || length(c(xlim, ylim, zlim))) {
+    listeners <- par3d("listeners")
+    result <- c(clipregion = newSubscene3d("inherit", "inherit", "inherit"))
+    par3d(listeners = listeners)
+    normals <- matrix(nrow = 0, ncol = 3)
+    offsets <- c()
+    if (length(xlim)) {
+      normals <- rbind(normals, matrix(c(1, 0, 0,
+                                         -1, 0, 0), nrow = 2, byrow = TRUE))
+      offsets <- c(offsets, -xlim[1], xlim[2])
+    }
+    if (length(ylim)) {
+      normals <- rbind(normals, matrix(c(0, 1, 0,
+                                         0, -1, 0), nrow = 2, byrow = TRUE))
+      offsets <- c(offsets, -ylim[1], ylim[2])
+    }
+    if (length(zlim)) {
+      normals <- rbind(normals, matrix(c(0, 0, 1, 
+                                         0, 0, -1), nrow = 2, byrow = TRUE))
+      offsets <- c(offsets, -zlim[1], zlim[2])
+    }
+    keep <- is.finite(offsets)
+    if (length(offsets[keep]))
+      result <- c(result, clipplanes = clipplanes3d(normals[keep,], d = offsets[keep]))
+  } else 
+    result <- NULL
+  invisible(result)
+}
+
+persp3d.function <- function(x, xlim = c(0,1), ylim = c(0,1), 
+                             slim = NULL, tlim = NULL, n = 101,
+                             xvals = seq.int(min(xlim), max(xlim), length.out = n[1]), 
+                             yvals = seq.int(min(ylim), max(ylim), length.out = n[2]), 
+                             svals = seq.int(min(slim), max(slim), length.out = n[1]), 
+                             tvals = seq.int(min(tlim), max(tlim), length.out = n[2]),
+                             xlab = NULL, ylab = NULL, zlab = NULL, 
+                             col = "gray",
+                             otherargs = list(), 
+                             normal = NULL, texture = NULL, ...) {
+  f <- x
+  n <- rep(n, length.out = 2)
+  parametric <- !is.null(slim) || !is.null(tlim)
+  if (!parametric) {
+    n1 <- length(xvals)
+    n2 <- length(yvals)
+    xvals <- matrix(xvals, n1, n2)
+    yvals <- matrix(yvals, n1, n2, byrow = TRUE)
+    args <- c(list(c(xvals), c(yvals)), otherargs)
+    zvals <- do.call(f, args)
+    dim(zvals) <- dim(xvals)
+    argnames <- names(as.list(f))
+    if (is.null(xlab)) xlab <- argnames[1]
+    if (is.null(ylab)) ylab <- argnames[2]
+    if (is.null(zlab)) zlab <- deparse(substitute(x))
+  } else {
+    if (is.null(slim)) slim <- c(0,1)
+    if (is.null(tlim)) tlim <- c(0,1)
+    n1 <- length(svals)
+    n2 <- length(tvals)
+    svals <- matrix(svals, n1, n2)
+    tvals <- matrix(tvals, n1, n2, byrow = TRUE)
+    
+    args <- c(list(as.numeric(svals), as.numeric(tvals)), otherargs)
+    allvals <- do.call(f, args)
+    xvals <- matrix(allvals[,1], n1, n2)
+    yvals <- matrix(allvals[,2], n1, n2)
+    zvals <- matrix(allvals[,3], n1, n2)
+    if (!is.null(colnames <- colnames(allvals))) {
+      if (is.null(xlab)) xlab <- colnames[1]
+      if (is.null(ylab)) ylab <- colnames[2]
+      if (is.null(zlab)) zlab <- colnames[3]
+    }
+  }
+  
+  if (is.function(col)) {
+    zmin <- min(zvals, na.rm = TRUE)
+    zscale <- 1/(max(zvals, na.rm = TRUE) - zmin)
+    colfn <- colorRamp(col(100))
+    colrgba <- colfn(c((zvals - zmin)*zscale))
+    colrgba[is.na(colrgba)] <- 0
+    col <- rgb(colrgba, maxColorValue = 255)
+    dim(col) <- dim(zvals)
+  }
+  if (is.function(normal)) 
+    normal <- do.call(normal, args)	
+  if (is.function(texture))
+    texture <- do.call(texture, args)
+  
+  args <- list(xvals, yvals, zvals, col = col, 
+               xlab = xlab, ylab = ylab, zlab = zlab, ...)	
+  if (is.matrix(normal)) 
+    args <- c(args, list(normal_x = matrix(normal[,1], n1, n2),
+                         normal_y = matrix(normal[,2], n1, n2),
+                         normal_z = matrix(normal[,3], n1, n2)))	
+  if (is.matrix(texture))
+    args <- c(args, list(texture_s = matrix(texture[,1], n1, n2),
+                         texture_t = matrix(texture[,2], n1, n2)))
+  if (parametric)
+    args <- c(args, list(xlim = if (!missing(xlim)) xlim, 
+                         ylim = if (!missing(ylim)) ylim))
+  
+  do.call(persp3d, args)
+}
diff --git a/R/plot3d.R b/R/plot3d.R
new file mode 100644
index 0000000..1fcd0ba
--- /dev/null
+++ b/R/plot3d.R
@@ -0,0 +1,109 @@
+plot3d <- function(x, ...) UseMethod("plot3d")
+
+
+plot3d.default <- function(x, y = NULL, z = NULL, 
+        xlab = NULL, ylab = NULL, zlab = NULL, type = 'p', 
+        col = material3d("color")[1], size = material3d("size"), 
+        lwd = material3d("lwd"),
+        radius = avgscale*size/60, add = FALSE, aspect = !add, 
+        xlim = NULL, ylim = NULL, zlim = NULL,
+        forceClipregion = FALSE, ...)
+{
+    if (!add) next3d()
+    skip <- par3d(skipRedraw=TRUE)
+    on.exit(par3d(skip))
+     	
+    xlabel <- if (!missing(x)) deparse(substitute(x))
+    ylabel <- if (!missing(y)) deparse(substitute(y))
+    zlabel <- if (!missing(z)) deparse(substitute(z))
+ 
+    xyz <- xyz.coords(x,y,z, xlab=xlabel, ylab=ylabel, zlab=zlabel, recycle=TRUE)
+    x <- xyz$x
+    y <- xyz$y
+    z <- xyz$z
+
+    if (is.null(xlab)) xlab <- xyz$xlab
+    if (is.null(ylab)) ylab <- xyz$ylab
+    if (is.null(zlab)) zlab <- xyz$zlab
+
+    if (type == "s" && missing(radius)) {
+	avgscale <- sqrt(sum(c(diff(range(x,na.rm=TRUE)), 
+                               diff(range(y,na.rm=TRUE)), 
+                               diff(range(z,na.rm=TRUE)))^2/3))
+    }
+    savesubscene <- currentSubscene3d()
+    result <- setClipregion(xlim, ylim, zlim, forceClipregion)
+    result <- c(result, data=switch(type,
+		p = points3d(x, y, z, color=col, size=size, ...),
+	        s = spheres3d(x, y, z, radius=radius, color=col, ...),
+		l = lines3d(x, y, z, color=col, lwd=lwd, ...),
+		h = segments3d(rep(x,rep(2,length(x))),
+					   rep(y,rep(2,length(y))),
+					   rbind(rep(0,length(z)),z),
+					   color = rep(col, rep(2,length(col))), lwd=lwd, ...),
+	# this is a hack to plot invisible segments
+        n = if (!add) segments3d(rep(range(x, na.rm=TRUE), c(2,2)),
+                                 rep(range(y, na.rm=TRUE), c(2,2)),
+                                 rep(range(z, na.rm=TRUE), c(2,2))))
+	)
+    useSubscene3d(savesubscene)
+    if (!add) result <- c(result, decorate3d(xlab=xlab, ylab=ylab, zlab=zlab, aspect = aspect, 
+                                             xlim=xlim, ylim=ylim, zlim=zlim, ...))
+    invisible(result)
+}
+
+plot3d.mesh3d <- function(x, xlab = "x", ylab = "y", zlab = "z", type = c("shade", "wire", "dots"),
+	add = FALSE, ...)
+{
+    if (!add) next3d()
+    skip <- par3d(skipRedraw=TRUE)
+    on.exit(par3d(skip))
+    
+    if (missing(xlab) && !is.null(x$xlab)) xlab <- x$xlab
+    if (missing(ylab) && !is.null(x$ylab)) ylab <- x$ylab
+    if (missing(zlab) && !is.null(x$zlab)) zlab <- x$zlab
+    
+    result <- switch(match.arg(type),
+    	shade = shade3d(x, ...),
+    	wire = wire3d(x, ...),
+    	dots = dot3d(x, ...))
+    
+    if (!add) result <- c(result, decorate3d(xlab = xlab, ylab = ylab, zlab = zlab, ...))
+    invisible(result)
+}
+
+decorate3d <- function(xlim = NULL, ylim = NULL, zlim = NULL, 
+                       xlab = "x", ylab = "y", zlab = "z", 
+                       box = TRUE, axes = TRUE, main = NULL, sub = NULL,
+                       top = TRUE, aspect = FALSE, expand = 1.03, ...) {
+  
+  if (is.logical(aspect)) {
+    autoscale <- aspect
+    aspect <- c(1,1,1)
+  } else autoscale <- TRUE	
+  
+  result <- numeric(0)    
+  if (length(c(xlim, ylim, zlim))) {
+    ranges <- .getRanges()        
+    if (is.null(xlim))
+      xlim <- ranges$xlim
+    if (is.null(ylim))
+      ylim <- ranges$ylim
+    if (is.null(zlim))
+      zlim <- ranges$zlim
+    ind <- c(1,1,2,2)
+    result <- c(result, strut=segments3d(xlim[ind], ylim[ind], zlim[ind]))
+  }
+  
+  if (autoscale) aspect3d(aspect)
+  
+  if (axes) result <- c(result, axes=axes3d(box=box, expand=expand))
+  result <- c(result, title3d(xlab = xlab, ylab = ylab, zlab = zlab, 
+                              main = main, sub = sub))
+  
+  if (top) rgl.bringtotop()
+  
+  invisible(result)
+}
+
+plot3d.function <- function(x, ...) persp3d(x, ...)
diff --git a/R/plugin.R b/R/plugin.R
new file mode 100644
index 0000000..36240eb
--- /dev/null
+++ b/R/plugin.R
@@ -0,0 +1,19 @@
+##
+## R source file
+## This file is part of rgl
+##
+## $Id: plugin.R 376 2005-08-03 23:58:47Z dadler $
+##
+
+##
+## quit R plugin
+## 
+##
+
+rgl.quit <- function() {
+
+  unloadNamespace("rgl")
+
+}
+
+
diff --git a/R/ply.R b/R/ply.R
new file mode 100644
index 0000000..53652db
--- /dev/null
+++ b/R/ply.R
@@ -0,0 +1,323 @@
+writePLY <- function(con, format=c("little_endian", "big_endian", "ascii"), 
+                     pointRadius=0.005, 
+                     pointShape = icosahedron3d(),
+                     lineRadius = pointRadius,
+                     lineSides = 20,
+                     pointsAsEdges = FALSE,
+                     linesAsEdges = pointsAsEdges,
+                     withColors = TRUE,
+                     withNormals = !(pointsAsEdges || linesAsEdges),
+                     ids = NULL) {
+ 
+  writeData <- function() {
+    ident <- paste(filename, " produced by RGL\n")
+    cat("ply\n", file=con)
+    fmt <- switch(format,
+      little_endian = "binary_little_endian",
+      big_endian = "binary_big_endian",
+      ascii = "ascii")
+    
+    cat("format", fmt, "1.0\n", file=con)
+    cat("element vertex", nrow(Vertices), "\n", file=con)
+    cat("property float x
+property float y
+property float z\n", file=con)
+    if (withColors)
+      cat("property float red
+property float green
+property float blue
+property float alpha\n", file=con)
+    if (withNormals)
+      cat("property float nx
+property float ny
+property float nz\n", file=con)
+    cat("element face", nrow(Triangles)+nrow(Quads), "\n", file=con)
+    cat("property list int int vertex_indices\n", file=con)
+    if (nrow(Edges) > 0) {
+      cat("element edge", nrow(Edges), "\n", file=con)
+      cat("property int vertex1
+property int vertex2\n", file=con)
+    }
+    cat("end_header\n", file=con)
+    
+    if (format == "ascii") {
+      for (i in seq_len(nrow(Vertices))) 
+        cat(Vertices[i,], "\n", file=con)
+      for (i in seq_len(nrow(Triangles))) 
+        cat("3", Triangles[i,], "\n", file=con)
+      for (i in seq_len(nrow(Quads)))
+        cat("4", Quads[i,], "\n", file=con)
+      for (i in seq_len(nrow(Edges)))
+        cat(Edges[i,], "\n", file=con)
+    } else {
+      endian <- if (format == "little_endian") "little" else "big"
+      if (nrow(Vertices))
+        writeBin(as.numeric(t(Vertices)), con, size=4, endian=endian)
+      if (nrow(Triangles))
+        writeBin(as.integer(t(cbind(3L, Triangles))), con, size=4, endian=endian)
+      if (nrow(Quads))
+        writeBin(as.integer(t(cbind(4L, Quads))), con, size=4, endian=endian)
+      if (nrow(Edges))
+        writeBin(as.integer(t(Edges)), con, size=4, endian=endian)
+    }  
+  }  
+    
+  Vertices <- matrix(0, 0, 3 + 4*withColors + 3*withNormals)
+  Triangles <- matrix(1L, 0, 3)
+  Quads <- matrix(1L, 0, 4)
+  Edges <- matrix(1L, 0, 2)
+
+  getVertices <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    if (withColors) {
+      colors <- rgl.attrib(id, "colors")
+      if (nrow(colors) == 1)
+        colors <- colors[rep(1, nrow(vertices)),]
+    }
+    if (withNormals) {
+      normals <- rgl.attrib(id, "normals")
+      if (!nrow(normals))
+      	normals <- 0*vertices
+    }
+    cbind(vertices, 
+          if (withColors) 255*colors,
+          if (withNormals) normals)
+  }
+  
+  writeTriangles <- function(id) {
+    vertices <- getVertices(id)
+    n <- nrow(vertices)      
+    base <- nrow(Vertices)
+    Vertices <<- rbind(Vertices, vertices)
+    Triangles <<- rbind(Triangles, matrix(base + seq_len(n) - 1, 
+                        ncol=3, byrow=TRUE))
+  }
+  
+  writeQuads <- function(id) {
+    vertices <- getVertices(id)
+    n <- nrow(vertices)
+    base <- nrow(Vertices)
+    Vertices <<- rbind(Vertices, vertices)
+    Quads <<- rbind(Quads, matrix(base + seq_len(n) - 1, 
+                        ncol=4, byrow=TRUE))
+  }
+      
+  writeSurface <- function(id) {
+    vertices <- getVertices(id)
+    dims <- rgl.attrib(id, "dim")
+    nx <- dims[1]
+    nz <- dims[2]
+    base <- nrow(Vertices)
+    Vertices <<- rbind(Vertices, vertices)
+    rows <- seq_len(nx)
+    for (i in seq_len(nz)[-nz]) 
+      Triangles <<- rbind(Triangles, 
+                        matrix(base + (i-1)*nx + 
+                               c(rows[-nx],rows[-nx],
+                                 rows[-1]+nx,rows[-nx]+nx,
+                                 rows[-1],rows[-1]+nx) - 1,
+                               ncol=3))
+  }
+  
+  writeMesh <- function(mesh, scale=1, offset=c(0,0,0)) {
+    vertices <- asEuclidean(t(mesh$vb))*scale 
+    vertices <- vertices + rep(offset, each=nrow(vertices))
+    if (withColors) {
+      colors <- mesh$material$col
+      if (!length(colors)) colors <- material3d("color")
+      colors <- rep(colors, length=nrow(vertices))
+      colors <- t(col2rgb(colors, alpha=TRUE))
+    }
+    if (withNormals) 
+      normals <- asEuclidean(t(mesh$normals))
+    base <- nrow(Vertices)
+    Vertices <<- rbind(Vertices, cbind(vertices, 
+                                       if (withColors) colors,
+                                       if (withNormals) normals))
+    
+    nt <- length(mesh$it)/3
+    nq <- length(mesh$ib)/4
+    if (nt) 
+      Triangles <<- rbind(Triangles, t(mesh$it) - 1 + base)
+    if (nq)
+      Quads <<- rbind(Quads, t(mesh$ib) - 1 + base)
+  }
+
+  writeSpheres <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    n <- nrow(vertices)    
+    colors <- rgl.attrib(id, "colors")
+    if (nrow(colors) == 1)
+      colors <- colors[rep(1, n),]
+    radii <- rgl.attrib(id, "radii")
+    radii <- rep(radii, length.out=n)
+    x <- subdivision3d(icosahedron3d(),3)
+    r <- sqrt(x$vb[1,]^2 + x$vb[2,]^2 + x$vb[3,]^2)
+    x$vb[4,] <- r
+    x$normals <- x$vb
+    for (i in seq_len(n)) {
+      col <- colors[i,]
+      x$material$col <- rgb(col[1], col[2], col[3], col[4], maxColorValue = 255)
+      writeMesh(x, radii[i], vertices[i,])
+    }
+  }  
+  
+  avgScale <- function() {
+    bbox <- par3d("bbox")
+    ranges <- c(bbox[2]-bbox[1], bbox[4]-bbox[3], bbox[6]-bbox[5])
+    if (prod(ranges) == 0) 1
+    else exp(mean(log(ranges)))
+  }  
+   
+  writePoints <- function(id) {
+    vertices <- getVertices(id)
+    n <- nrow(vertices)
+    inds <- seq_len(n)    
+    if (pointsAsEdges) {
+      base <- nrow(Vertices)
+      Vertices <<- rbind(Vertices, vertices)
+      Edges <<- rbind(Edges, base + cbind(inds, inds) - 1 )  
+    } else {
+      radius <- pointRadius*avgScale()
+      if (withNormals && is.null(pointShape$normals))
+        pointShape <- addNormals(pointShape)
+      for (i in inds) {
+        if (withColors) {
+          col <- vertices[i,4:7]
+          pointShape$material$col <- rgb(col[1], col[2], col[3], col[4], maxColorValue = 255)
+        }
+        writeMesh(pointShape, radius, vertices[i,1:3])
+      }
+    }
+  }
+  
+  writeSegments <- function(id) {
+    vertices <- getVertices(id)
+    if (withColors) {
+      colors <- vertices[, 4:7, drop=FALSE]
+      vertices <- vertices[, 1:3, drop=FALSE]
+    }
+    n <- nrow(vertices)
+    n <- n/2
+    inds <- seq_len(n)
+    if (linesAsEdges) {
+      base <- nrow(Vertices)
+      Vertices <<- rbind(Vertices, vertices)
+      Edges <<- rbind(Edges, base + cbind(2*inds - 2, 2*inds - 1) )  
+    } else {
+      radius <- lineRadius*avgScale()
+      for (i in seq_len(n)) {
+        cyl <- cylinder3d( vertices[(2*i-1):(2*i),1:3],
+     			   radius = radius,
+     			   sides = lineSides, 
+     			   closed = -2 )
+	if (withColors) {
+          col1 <- colors[2*i-1,]
+          col1 <- rgb(col1[1], col1[2], col1[3], col1[4], maxColorValue = 255)
+          col2 <- colors[2*i,]
+          col2 <- rgb(col2[1], col2[2], col2[3], col2[4], maxColorValue = 255)
+        
+          cyl$material$col <- c(rep(col1, lineSides),
+                                rep(col2, lineSides), col1, col2)
+        }
+        if (withNormals)
+          cyl <- addNormals(cyl)
+        writeMesh(cyl)
+      }
+    }
+  }
+  
+  writeLines <- function(id) {
+    vertices <- getVertices(id)
+    if (linesAsEdges) {
+      n <- nrow(vertices)    
+      inds <- seq_len(n)
+      base <- nrow(Vertices)
+      Vertices <<- rbind(Vertices, vertices)
+      Edges <<- rbind(Edges, base + cbind(inds[-n], inds[-1]) - 1)  
+    } else {
+      n <- nrow(vertices) - 1
+      radius <- lineRadius*avgScale()
+      for (i in seq_len(n)) {
+        cyl <- cylinder3d( vertices[i:(i+1),1:3],
+     			   radius = radius,
+     			   sides = lineSides, 
+     			   closed = -2 )
+        if (withColors) {
+	  colors <- vertices[i, 4:7]
+          col1 <- colors[i,]
+          col1 <- rgb(col1[1], col1[2], col1[3], col1[4], maxColorValue = 255)
+          col2 <- colors[i+1,]
+          col2 <- rgb(col2[1], col2[2], col2[3], col2[4], maxColorValue = 255)
+        
+          cyl$material$col <- c(rep(col1, lineSides),
+                                rep(col2, lineSides), col1, col2)
+        }
+        if (withNormals) 
+          cyl <- addNormals(cyl)
+        writeMesh(cyl)
+      }
+    }
+  }
+  
+  knowntypes <- c("triangles", "quads",
+                  "surface", "spheres", "linestrip", "lines", "planes",
+                  "points")
+  
+  #  Execution starts here!
+  format <- match.arg(format)
+
+  if (is.character(con)) {
+    con <- file(con, if (format=="ascii") "w" else "wb")
+    on.exit(close(con))
+  }
+  filename <- summary(con)$description
+  
+  if (NROW(bbox <- rgl.ids("bboxdeco")) && (is.null(ids) || bbox$id %in% ids)) {
+    ids <- setdiff(ids, bbox$id)
+    save <- par3d(skipRedraw = TRUE)
+    bbox <- convertBBox(bbox$id)
+    on.exit({ rgl.pop(id=bbox); par3d(save) }, add=TRUE)
+    dobbox <- TRUE
+  } else dobbox <- FALSE 
+  
+  if (is.null(ids)) {
+    ids <- rgl.ids()
+    types <- as.character(ids$type)
+    ids <- ids$id
+  } else {
+    if (dobbox) ids <- c(ids, bbox)
+    allids <- rgl.ids()
+    ind <- match(ids, allids$id)
+    keep <- !is.na(ind)
+    if (any(!keep)) warning(gettextf("Object(s) with id %s not found", paste(ids[!keep], collapse=" ")), 
+    			    domain = NA)
+    ids <- ids[keep]
+    types <- allids$type[ind[keep]]
+  }  
+    
+  unknowntypes <- setdiff(types, knowntypes)
+  if (length(unknowntypes))
+    warning(gettextf("Object type(s) %s not handled", 
+      paste("'", unknowntypes, "'", sep="", collapse=", ")), domain = NA)
+
+  keep <- types %in% knowntypes
+  ids <- ids[keep]
+  types <- types[keep]
+
+  for (i in seq_along(ids)) 
+    switch(types[i],
+      planes =,
+      triangles = writeTriangles(ids[i]),
+      quads = writeQuads(ids[i]),
+      surface = writeSurface(ids[i]),
+      spheres = writeSpheres(ids[i]),
+      points = writePoints(ids[i]),
+      lines = writeSegments(ids[i]),
+      linestrip = writeLines(ids[i])
+    )
+  
+  writeData()
+  
+  invisible(filename)
+}
diff --git a/R/r3d.rgl.R b/R/r3d.rgl.R
new file mode 100644
index 0000000..5702bcf
--- /dev/null
+++ b/R/r3d.rgl.R
@@ -0,0 +1,293 @@
+#
+# R3D rendering functions - rgl implementation
+# $Id: r3d.rgl.R 1252 2015-06-28 05:26:12Z murdoch $
+# 
+
+# Node Management
+
+getr3dDefaults <- function() 
+    tryCatch(get("r3dDefaults", envir=.GlobalEnv),
+	     error = function(e) r3dDefaults)
+
+clear3d     <- function(type = c("shapes", "bboxdeco", "material"), 
+                        defaults=getr3dDefaults(),
+                        subscene = 0) {
+    .check3d()
+    rgl.clear( type, subscene = subscene )
+
+    type <- rgl.enum.nodetype(type)
+    if ( 4 %in% type ) { # userviewpoint
+	do.call("par3d", defaults["FOV"])
+    }
+    if ( 8 %in% type ) { # modelviewpoint
+        do.call("par3d", defaults["userMatrix"])
+    }
+    if ( 5 %in% type ) { # material
+        if (length(defaults$material))
+    	    do.call("material3d", defaults$material)
+    }
+}
+
+pop3d       <- function(...) {.check3d(); rgl.pop(...)}
+
+# Environment
+
+.material3d <- c("color", "alpha", "lit", "ambient", "specular",
+    "emission", "shininess", "smooth", "front", "back", "size", 
+    "lwd", "fog", "point_antialias", "line_antialias",
+    "texture", "textype", "texmipmap",
+    "texminfilter", "texmagfilter", "texenvmap",
+    "depth_mask", "depth_test")
+
+.material3d.writeOnly <- character(0)
+
+# This function expands a list of arguments by putting
+# all entries from Params (i.e. the current settings by default)
+# in place for any entries that are not listed.  
+# Unrecognized args are left in place.
+
+.fixMaterialArgs <- function(..., Params = material3d()) {
+   f <- function(...) list(...)
+   formals(f) <- c(Params, formals(f))
+   names <- as.list(names(Params))
+   names(names) <- names
+   names <- lapply(names, as.name)
+   b <- as.list(body(f))
+   body(f) <- as.call(c(b[1], names, b[-1]))
+   f(...)
+} 
+     
+     
+material3d  <- function (...)
+{
+    args <- list(...)
+    argnames <- names(args)
+    
+    if (!length(args))
+	argnames <- .material3d
+    else {
+	if (is.null(names(args)) && all(unlist(lapply(args, is.character)))) {
+	    argnames <- unlist(args)
+	    args <- NULL
+	}
+	
+	if (length(args) == 1) {
+	    if (is.list(args[[1]]) | is.null(args[[1]])) {
+		args <- args[[1]]
+		argnames <- names(args)
+	    }
+	}
+    }
+    value <- rgl.getmaterial()[argnames]
+    if (length(args)) {
+    	args <- do.call(".fixMaterialArgs", args)
+        do.call("rgl.material", args)
+        return(invisible(value))
+    } else if (length(argnames) == 1) return(value[[1]])
+    else return(value)
+}
+
+bg3d        <- function(...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  new <- .fixMaterialArgs(sphere = FALSE, fogtype = "none", 
+                          color = c("black", "white"), back = "lines", Params = save)
+  do.call("rgl.bg", .fixMaterialArgs(..., Params = new))
+}
+
+light3d     <- function(theta=0,phi=15,x=NULL, ...) {
+  .check3d()
+  if (is.null(x))
+    rgl.light(theta=theta,phi=phi,x=x, ...)
+  else
+    rgl.light(x=x, ...)
+}
+
+view3d      <- function(theta=0,phi=15,...) {
+  .check3d()
+  rgl.viewpoint(theta=theta,phi=phi,...)
+}
+
+bbox3d	    <- function(xat = NULL, 
+                        yat = NULL, 
+                        zat = NULL, 
+                        xunit = "pretty",
+                        yunit = "pretty",
+                        zunit = "pretty",
+		        expand = 1.03, draw_front = FALSE, ...) {  
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  ranges <- .getRanges(expand = expand)
+  do.call("rgl.bbox", c(list(xat=xat, yat=yat, zat=zat, 
+                             xunit=xunit, yunit=yunit, zunit=zunit, expand=expand,
+                             draw_front=draw_front), 
+                        .fixMaterialArgs(..., Params = save)))
+}
+
+observer3d <- function(x, y=NULL, z=NULL, auto=FALSE) {
+  if (missing(x))
+    location <- c(NA, NA, NA)
+  else {
+    xyz <- xyz.coords(x,y,z)
+    location <- c(xyz$x, xyz$y, xyz$z)
+    if (length(location) != 3) stop("A single point must be specified for the observer location") 
+  }    
+  prev <- .C(rgl_getObserver, success=integer(1), ddata=numeric(3), NAOK = TRUE)$ddata
+  .C(rgl_setObserver, success=as.integer(auto), ddata=as.numeric(location), NAOK = TRUE)
+  invisible(prev)
+}
+
+# Shapes
+
+points3d    <- function(x,y=NULL,z=NULL,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.points", c(list(x=x,y=y,z=z), .fixMaterialArgs(..., Params = save)))
+}
+
+lines3d     <- function(x,y=NULL,z=NULL,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.linestrips", c(list(x=x,y=y,z=z), .fixMaterialArgs(..., Params = save)))
+}
+
+segments3d  <- function(x,y=NULL,z=NULL,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.lines", c(list(x=x,y=y,z=z), .fixMaterialArgs(..., Params = save)))
+}
+
+triangles3d <- function(x,y=NULL,z=NULL,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.triangles", c(list(x=x,y=y,z=z), .fixMaterialArgs(..., Params = save)))
+}
+
+quads3d     <- function(x,y=NULL,z=NULL,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.quads", c(list(x=x,y=y,z=z), .fixMaterialArgs(..., Params = save)))
+}
+
+text3d      <- function(x,y=NULL,z=NULL,texts,adj=0.5,justify,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  new <- .fixMaterialArgs(..., Params = save)
+  if (!missing(justify)) new <- c(list(justify=justify), new)
+  do.call("rgl.texts", c(list(x=x,y=y,z=z,text=texts,adj=adj),new))
+}
+texts3d	    <- text3d
+
+spheres3d   <- function(x,y=NULL,z=NULL,radius=1,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.spheres", c(list(x=x,y=y,z=z,radius=radius), .fixMaterialArgs(..., Params = save)))
+}
+
+planes3d   <- function(a,b=NULL,c=NULL,d=0,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.planes", c(list(a=a,b=b,c=c,d=d), .fixMaterialArgs(..., Params = save)))
+}
+
+clipplanes3d   <- function(a,b=NULL,c=NULL,d=0) {
+  .check3d()
+  rgl.clipplanes(a=a,b=b,c=c,d=d)
+}
+
+abclines3d   <- function(x,y=NULL,z=NULL,a,b=NULL,c=NULL,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.abclines", c(list(x=x,y=y,z=z,a=a,b=b,c=c), .fixMaterialArgs(..., Params = save)))
+}
+
+sprites3d   <- function(x,y=NULL,z=NULL,radius=1,shapes=NULL,userMatrix,...) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  if (missing(userMatrix)) {
+    userMatrix <- getr3dDefaults()$userMatrix
+    if (is.null(userMatrix)) userMatrix <- diag(4)
+  }
+  savepar <- par3d(skipRedraw=TRUE, ignoreExtent=TRUE)
+  on.exit(par3d(savepar), add=TRUE)
+  force(shapes)
+  par3d(ignoreExtent=savepar$ignoreExtent)
+
+  do.call("rgl.sprites", c(list(x=x,y=y,z=z,radius=radius,shapes=shapes,
+                                userMatrix=userMatrix), 
+          .fixMaterialArgs(..., Params = save)))
+}
+
+terrain3d   <- function(x,y=NULL,z=NULL,...,normal_x=NULL,normal_y=NULL,normal_z=NULL) {
+  .check3d(); save <- material3d(); on.exit(material3d(save))
+  do.call("rgl.surface", c(list(x=x,y=z,z=y,coords=c(1,3,2),
+                                normal_x=normal_x,normal_y=normal_z,normal_z=normal_y), 
+                           .fixMaterialArgs(..., Params = save)))
+}
+surface3d   <- terrain3d
+
+# Interaction
+
+select3d    <- function(...) {.check3d(); rgl.select3d(...)}
+
+# 3D Generic Object Rendering Attributes
+
+dot3d <- function(x,...) UseMethod("dot3d")
+wire3d  <- function(x,...) UseMethod("wire3d")
+shade3d <- function(x,...) UseMethod("shade3d")
+
+# 3D Generic transformation
+
+
+translate3d <- function(obj,x,y,z,...) UseMethod("translate3d")
+scale3d <- function(obj,x,y,z,...) UseMethod("scale3d")
+rotate3d <- function(obj,angle,x,y,z,matrix,...) UseMethod("rotate3d")
+transform3d <- function(obj,matrix,...) rotate3d(obj, matrix=matrix, ...)
+
+subdivision3d <- function(x,...) UseMethod("subdivision3d")
+
+# 3D Custom shapes
+
+particles3d <- function(x,y=NULL,z=NULL,radius=1,...) sprites3d(
+  x=x,y=y,z=z,radius=radius,
+  lit=FALSE,alpha=0.2,
+  textype="alpha",
+  texture=system.file("textures/particle.png",package="rgl"),
+  ...
+)   
+
+# r3d default settings for new windows
+
+r3dDefaults <- list(userMatrix = rotationMatrix(290*pi/180, 1, 0, 0),
+		  mouseMode = c("trackball", "zoom", "fov"),
+		  FOV = 30,
+		  bg = list(color="white"),
+		  family = "sans",
+		  material = list(color="black", fog=FALSE))
+
+open3d <- function(..., params = getr3dDefaults(), 
+                   useNULL = rgl.useNULL()	)
+{
+    args <- list(...)
+    if (!is.null(args$antialias) 
+        || !is.null(args$antialias <- r3dDefaults$antialias)) {
+    	saveopt <- options(rgl.antialias = args$antialias)
+    	on.exit(options(saveopt))
+    	args$antialias <- NULL
+    }
+    
+    rgl.open(useNULL)
+    
+    if (!is.null(args$material)) {
+    	params$material <- do.call(.fixMaterialArgs, c(args$material, Params=list(params$material)))
+    	args$material <- NULL
+    }
+    
+    params[names(args)] <- args
+        
+    clear3d("material", defaults = params)
+    params$material <- NULL
+    
+    if (!is.null(params$bg)) {
+      do.call("bg3d", params$bg)
+      params$bg <- NULL
+    }
+ 
+    do.call("par3d", params)   
+    return(rgl.cur())
+}
+
+.check3d <- function() {
+    if (result<-rgl.cur()) return(result)
+    else return(open3d())
+}
+
+snapshot3d <- function(...) rgl.snapshot(...)
diff --git a/R/rgl.bringtotop.R b/R/rgl.bringtotop.R
new file mode 100644
index 0000000..0b0fda3
--- /dev/null
+++ b/R/rgl.bringtotop.R
@@ -0,0 +1,15 @@
+
+##
+## bring device to top
+##
+##
+
+rgl.bringtotop <- function(stay = FALSE) {
+
+  if ((.Platform$OS.type != "windows") && stay) warning("'stay' not implemented")
+  ret <- .C( rgl_dev_bringtotop, success=FALSE, as.logical(stay) )
+
+  if (! ret$success)
+    stop("'rgl.bringtotop' failed")
+
+}
diff --git a/R/scene.R b/R/scene.R
new file mode 100644
index 0000000..26879cb
--- /dev/null
+++ b/R/scene.R
@@ -0,0 +1,908 @@
+##
+## R source file
+## This file is part of rgl
+##
+## $Id: scene.R 1357 2015-09-30 19:49:19Z murdoch $
+##
+
+##
+## ===[ SECTION: scene management ]===========================================
+##
+
+
+##
+## clear scene
+##
+##
+
+rgl.clear <- function( type = "shapes", subscene = 0 )
+{
+  if (is.na(subscene)) 
+    subscene <- currentSubscene3d()
+
+  typeid <- rgl.enum.nodetype(type)
+  
+  userviewpoint <- 4 %in% typeid
+  material  <- 5 %in% typeid
+  modelviewpoint <- 8 %in% typeid
+
+  drop <- typeid %in% c(4:6, 8)
+  typeid <- typeid[!drop]
+  type <- names(typeid)
+  
+  if (subscene == 0) {
+    idata <- as.integer(c(length(typeid), typeid))    	
+    ret <- .C( rgl_clear, 
+      success = FALSE,
+      idata
+    )$success
+  } else {
+    sceneids <- rgl.ids(type=type, subscene = 0)$id
+    thisids <- rgl.ids(type=type, subscene = subscene)$id
+    if (length(thisids)) {
+      delFromSubscene3d(ids = thisids, subscene = subscene)
+      gc3d(protect = setdiff(sceneids, thisids))
+    }
+    ret <- 1
+  }
+  
+  if ( userviewpoint || modelviewpoint) 
+    rgl.viewpoint(type = c("userviewpoint", "modelviewpoint")[c(userviewpoint, modelviewpoint)])
+    
+  if ( material ) 
+    rgl.material()
+
+  if (! ret)
+    stop("'rgl_clear' failed")
+}
+
+
+##
+## pop node
+##
+##
+
+rgl.pop <- function( type = "shapes", id = 0)
+{
+  type <- rgl.enum.nodetype(type)
+  save <- par3d(skipRedraw = TRUE)
+  on.exit(par3d(save))
+  for (i in id) {
+    idata <- as.integer(c(type, i))
+
+    ret <- .C( rgl_pop,
+      success = FALSE,
+      idata
+    )
+
+    if (! ret$success)
+      stop(gettextf("'rgl.pop' failed for id %d", i), domain = NA)
+  }
+}
+
+rgl.ids <- function( type = "shapes", subscene = NA )
+{
+  type <- c(rgl.enum.nodetype(type), 0)
+  if (is.na(subscene)) 
+      subscene <- currentSubscene3d()
+  
+  count <- .C( rgl_id_count, as.integer(type), count = integer(1), subscene = as.integer(subscene))$count
+  
+  as.data.frame( .C( rgl_ids, as.integer(type), id=integer(count), 
+                                type=rep("",count), subscene = as.integer(subscene) )[2:3] )
+}
+
+rgl.attrib.count <- function( id, attrib )
+{
+  stopifnot(length(attrib) == 1)
+  if (is.character(attrib))
+    attrib <- rgl.enum.attribtype(attrib)
+  
+  result <- integer(length(id))
+  for (i in seq_along(id))
+    result[i] <- .C( rgl_attrib_count, as.integer(id[i]), as.integer(attrib), 
+                     count = integer(1))$count
+  names(result) <- names(id)
+  result
+}
+
+rgl.attrib <- function( id, attrib, first=1, 
+                        last=rgl.attrib.count(id, attrib) )
+{
+  stopifnot(length(attrib) == 1 && length(id) == 1 && length(first) == 1)
+  if (is.character(attrib))
+    attrib <- rgl.enum.attribtype(attrib)
+  ncol <- c(vertices=3, normals=3, colors=4, texcoords=2, dim=2, 
+            texts=1, cex=1, adj=2, radii=1, centers=3, ids=1,
+            usermatrix=4, types=1, flags=1, offsets=1,
+  	    family=1, font=1)[attrib]
+  count <- max(last - first + 1, 0)
+  if (attrib %in% c(6, 13, 16)) { # texts, types and family
+    if (count)
+      result <- .C (rgl_text_attrib, as.integer(id), as.integer(attrib), 
+                    as.integer(first-1), as.integer(count), 
+                result = character(count*ncol))$result
+    else
+      result <- character(0)
+  } else {
+    if (count)
+      result <- .C (rgl_attrib, as.integer(id), as.integer(attrib), 
+                  as.integer(first-1), as.integer(count), 
+                  result = numeric(count*ncol))$result
+    else
+      result <- numeric(0)
+  }
+  if (attrib == 14) 
+    result <- as.logical(result)
+  result <- matrix(result, ncol=ncol, byrow=TRUE)
+  colnames(result) <- list(c("x", "y", "z"), # vertices
+                           c("x", "y", "z"), # normals
+                           c("r", "g", "b", "a"), # colors
+                           c("s", "t"),	     # texcoords
+                           c("r", "c"),      # dim
+                           c("text"),	     # texts
+                           c("cex"), 	     # cex
+                           c("x", "y"),	     # adj
+                           "r",		     # radii
+                           c("x", "y", "z"), # centers
+                           "id",	     # ids
+                           c("x", "y", "z", "w"), # usermatrix
+                           "type",	     # types
+                           "flag",	     # flags
+			   "offset",         # offsets
+  			   "family",         # family
+  			   "font"            # font
+                           )[[attrib]]
+  if (attrib == 14 && count)
+    if (id %in% rgl.ids("lights", subscene = 0)$id)
+      rownames(result) <- c("viewpoint", "finite")[first:last]
+    else if (id %in% rgl.ids("background", subscene = 0)$id)
+      rownames(result) <- c("sphere", "linear_fog", "exp_fog", "exp2_fog")[first:last]
+    else if (id %in% rgl.ids("bboxdeco", subscene = 0)$id)
+      rownames(result) <- "draw_front"[first:last]
+    else if (id %in% rgl.ids("shapes", subscene = 0)$id)
+      rownames(result) <- "ignoreExtent"[first:last]
+ 
+  result
+}
+
+##
+## ===[ SECTION: environment ]================================================
+##
+
+
+
+##
+## set viewpoint
+##
+##
+
+rgl.viewpoint <- function( theta = 0.0, phi = 15.0, fov = 60.0, zoom = 1.0, scale = par3d("scale"),
+                           interactive = TRUE, userMatrix, type = c("userviewpoint", "modelviewpoint") )
+{
+  zoom <- rgl.clamp(zoom,0,Inf)
+  phi  <- rgl.clamp(phi,-90,90)
+  fov  <- rgl.clamp(fov,0,179)
+  
+  type <- match.arg(type, several.ok = TRUE)
+
+  polar <- missing(userMatrix)
+  if (polar) userMatrix <- diag(4)
+  
+  idata <- as.integer(c(interactive,polar, "userviewpoint" %in% type, "modelviewpoint" %in% type))
+  ddata <- as.numeric(c(theta,phi,fov,zoom,scale,userMatrix[1:16]))
+
+  ret <- .C( rgl_viewpoint,
+    success = FALSE,
+    idata,
+    ddata
+  )
+
+  if (! ret$success)
+    stop("'rgl_viewpoint' failed")
+}
+
+##
+## set background
+##
+##
+
+rgl.bg <- function(sphere=FALSE, fogtype="none", color=c("black","white"), back="lines", ... )
+{
+  rgl.material( color=color, back=back, ... )
+
+  fogtype <- rgl.enum.fogtype(fogtype)
+
+  idata   <- as.integer(c(sphere,fogtype))
+
+  ret <- .C( rgl_bg, 
+    success = as.integer(FALSE),
+    idata
+  )
+
+  if (! ret$success)
+    stop("'rgl_bg' failed")
+    
+  invisible(ret$success)
+}
+
+
+##
+## bbox
+##
+##
+
+rgl.bbox <- function( 
+  xat=NULL, xlab=NULL, xunit=0, xlen=5,
+  yat=NULL, ylab=NULL, yunit=0, ylen=5,
+  zat=NULL, zlab=NULL, zunit=0, zlen=5,
+  marklen=15.0, marklen.rel=TRUE, expand=1, draw_front=FALSE,
+  ...) {
+
+  rgl.material( ... )
+
+  if (is.null(xat)) 
+    xlab <- NULL
+  else {
+    xlen <- length(xat)
+    if (is.null(xlab)) 
+      xlab <- format(xat)
+    else 
+      xlab <- rep(xlab, length.out=xlen)
+  }
+  if (is.null(yat)) 
+    ylab <- NULL
+  else {
+    ylen <- length(yat)
+    if (is.null(ylab)) 
+      ylab <- format(yat)
+    else 
+      ylab <- rep(ylab, length.out=ylen)
+  }
+  if (is.null(zat)) 
+    zlab <- NULL
+  else {
+    zlen <- length(zat)
+    if (is.null(zlab)) 
+      zlab <- format(zat)
+    else 
+      zlab <- rep(zlab,length.out=length(zat))
+  }
+  xticks <- length(xat)
+  yticks <- length(yat)
+  zticks <- length(zat)
+
+  if (identical(xunit, "pretty")) xunit = -1;
+  if (identical(yunit, "pretty")) yunit = -1;
+  if (identical(zunit, "pretty")) zunit = -1;
+
+  length(xlen)        <- 1
+  length(ylen)        <- 1
+  length(zlen)        <- 1
+  length(marklen.rel) <- 1
+  length(draw_front)  <- 1
+  length(xunit)       <- 1
+  length(yunit)       <- 1
+  length(zunit)       <- 1
+  length(marklen)     <- 1
+  length(expand)      <- 1
+
+  idata <- as.integer(c(xticks,yticks,zticks, xlen, ylen, zlen, marklen.rel, draw_front))
+  ddata <- as.numeric(c(xunit, yunit, zunit, marklen, expand))
+
+  ret <- .C( rgl_bbox,
+    success = FALSE,
+    idata,
+    ddata,
+    as.numeric(xat),
+    as.character(xlab),
+    as.numeric(yat),
+    as.character(ylab),
+    as.numeric(zat),
+    as.character(zlab)
+  )
+
+  if (! ret$success)
+    stop("'rgl_bbox' failed")
+    
+  invisible(ret$success)
+
+}
+
+##
+## set lights
+##
+##
+
+rgl.light <- function( theta = 0, phi = 0, viewpoint.rel = TRUE, ambient = "#FFFFFF", diffuse = "#FFFFFF", specular = "#FFFFFF", x = NULL, y = NULL, z = NULL)
+{
+  ambient  <- rgl.color(ambient)
+  diffuse  <- rgl.color(diffuse)
+  specular <- rgl.color(specular)
+  
+  # if a complete set of x, y, z is given, the light source is assumed to be part of the scene, theta and phi are ignored
+  # else the light source is infinitely far away and its direction is determined by theta, phi (default) 
+  if ( !is.null(x) ) {
+    if ( !missing(theta) || !missing(phi) )
+      warning("'theta' and 'phi' ignored when 'x' is present")
+    xyz <- xyz.coords(x,y,z)
+    x <- xyz$x
+    y <- xyz$y
+    z <- xyz$z
+    if (length(x) > 1) stop("A light can only be in one place at a time")
+    finite.pos <- TRUE
+  }
+  else {
+    
+    if ( !is.null(y) || !is.null(z) ) 
+      warning("'y' and 'z' ignored, spherical coordinates used")
+    finite.pos <- FALSE
+    x <- 0
+    y <- 0
+    z <- 0
+    
+  }
+    
+
+  idata <- as.integer(c(viewpoint.rel, ambient, diffuse, specular, finite.pos))
+  ddata <- as.numeric(c(theta, phi, x, y, z))
+
+  ret <- .C( rgl_light,
+    success = as.integer(FALSE),
+    idata,
+    ddata
+  )
+
+  if (! ret$success)
+    stop("Too many lights; maximum is 8 sources per scene")
+    
+  invisible(ret$success)
+}
+
+##
+## ===[ SECTION: shapes ]=====================================================
+##
+
+##
+## add primitive
+##
+##
+
+rgl.primitive <- function( type, x, y=NULL, z=NULL, normals=NULL, texcoords=NULL, ... )
+{
+  rgl.material( ... )
+
+  type <- rgl.enum.primtype(type)
+  
+  xyz <- xyz.coords(x,y,z,recycle=TRUE)
+  x <- xyz$x
+  y <- xyz$y
+  z <- xyz$z
+
+  vertex  <- rgl.vertex(x,y,z)
+  nvertex <- rgl.nvertex(vertex)
+  if (nvertex > 0) {
+    
+    perelement <- c(points=1, lines=2, triangles=3, quadrangles=4, linestrips=1)[type]
+    if (nvertex %% perelement) 
+      stop("Illegal number of vertices")
+    
+    idata   <- as.integer( c(type, nvertex, !is.null(normals), !is.null(texcoords) ) )
+    
+    if (is.null(normals)) normals <- 0
+    else {
+    
+      normals <- xyz.coords(normals, recycle=TRUE)
+      x <- rep(normals$x, len=nvertex)
+      y <- rep(normals$y, len=nvertex)
+      z <- rep(normals$z, len=nvertex)
+      normals <- rgl.vertex(x,y,z)
+    }
+    
+    if (is.null(texcoords)) texcoords <- 0
+    else {
+    
+      texcoords <- xy.coords(texcoords, recycle=TRUE)
+      s <- rep(texcoords$x, len=nvertex)
+      t <- rep(texcoords$y, len=nvertex)
+      texcoords <- rgl.texcoords(s,t)
+    } 
+    
+    ret <- .C( rgl_primitive,
+      success = as.integer(FALSE),
+      idata,
+      as.numeric(vertex),
+      as.numeric(normals),
+      as.numeric(texcoords),
+      NAOK = TRUE
+    );      
+        
+    if (! ret$success)
+      stop("'rgl_primitive' failed")
+      
+    invisible(ret$success)
+  }
+}
+
+rgl.points <- function ( x, y=NULL, z=NULL, ... )
+{
+  rgl.primitive( "points", x, y, z, ... )
+}
+
+rgl.lines <- function (x, y=NULL, z=NULL, ... )
+{
+  rgl.primitive( "lines", x, y, z, ... )
+}
+
+rgl.triangles <- function (x, y=NULL, z=NULL, normals=NULL, texcoords=NULL, ... )
+{
+  rgl.primitive( "triangles", x, y, z, normals, texcoords, ... )
+}
+
+rgl.quads <- function ( x, y=NULL, z=NULL, normals=NULL, texcoords=NULL, ... )
+{
+  rgl.primitive( "quadrangles", x, y, z, normals, texcoords, ... )
+}
+
+rgl.linestrips<- function ( x, y=NULL, z=NULL, ... )
+{
+  rgl.primitive( "linestrips", x, y, z, ... )
+}
+
+##
+## add surface
+##
+##
+
+# Utility function:
+# calculates the parity of a permutation of integers
+
+perm_parity <- function(p) {  
+  x <- seq_along(p)
+  result <- 0
+  for (i in x) {
+    if (x[i] != p[i]) {
+      x[x==p[i]] <- x[i]
+      result <- result+1
+    }
+  }
+  return(result %% 2)
+}
+
+rgl.surface <- function( x, z, y, coords=1:3,  ..., normal_x=NULL, normal_y=NULL, normal_z=NULL,
+                         texture_s=NULL, texture_t=NULL)
+{
+  rgl.material(...)
+  
+  flags <- rep(FALSE, 4)
+  
+  if (is.matrix(x)) {
+    nx <- nrow(x)
+    flags[1] <- TRUE
+    if ( !identical( dim(x), dim(y) ) ) stop(gettextf("Bad dimension for %s", "rows"),
+    					     domain = NA)
+  } else nx <- length(x)
+  
+  if (is.matrix(z)) {
+    nz <- ncol(z)
+    flags[2] <- TRUE
+    if ( !identical( dim(z), dim(y) ) ) stop(gettextf("Bad dimension for %s", "cols"),
+                                             domain = NA)     
+  } else nz <- length(z)
+  
+  ny <- length(y)
+
+  if ( nx*nz != ny)
+    stop("'y' length != 'x' rows * 'z' cols")
+
+  if ( nx < 2 )
+    stop("rows < 2")
+  
+  if ( nz < 2 )   
+    stop("cols < 2")
+    
+  if ( length(coords) != 3 || !identical(all.equal(sort(coords), 1:3), TRUE) )
+    stop("'coords' must be a permutation of 1:3")
+  
+  nulls <- c(is.null(normal_x), is.null(normal_y), is.null(normal_z))
+  if (!all( nulls ) ) {
+    if (any( nulls )) stop("All normals must be supplied")
+    if ( !identical(dim(y), dim(normal_x)) 
+      || !identical(dim(y), dim(normal_y))
+      || !identical(dim(y), dim(normal_z)) ) stop(gettextf("Bad dimension for %s", "normals"),
+      					    domain = NA)
+    flags[3] <- TRUE
+  }
+  
+  nulls <- c(is.null(texture_s), is.null(texture_t))
+  if (!all( nulls ) ) {
+    if (any( nulls )) stop("Both texture coordinates must be supplied")
+    if ( !identical(dim(y), dim(texture_s))
+      || !identical(dim(y), dim(texture_t)) ) stop(gettextf("Bad dimension for %s", "textures"),
+      					     domain = NA)
+    flags[4] <- TRUE
+  }
+
+  idata <- as.integer( c( nx, nz ) )
+
+  parity <- (perm_parity(coords) + (x[2] < x[1]) + (z[2] < z[1]) ) %% 2
+  
+  ret <- .C( rgl_surface,
+    success = as.integer(FALSE),
+    idata,
+    as.numeric(x),
+    as.numeric(z),
+    as.numeric(y),
+    as.numeric(normal_x),
+    as.numeric(normal_z),
+    as.numeric(normal_y),
+    as.numeric(texture_s),
+    as.numeric(texture_t),
+    as.integer(coords),
+    as.integer(parity),
+    as.integer(flags),
+    NAOK=TRUE
+  );
+
+  if (! ret$success)
+    stop("'rgl_surface' failed")
+    
+  invisible(ret$success)
+}
+
+##
+## add spheres
+##
+
+rgl.spheres <- function( x, y=NULL, z=NULL, radius=1.0,...)
+{
+  rgl.material(...)
+
+  vertex  <- rgl.vertex(x,y,z)
+  nvertex <- rgl.nvertex(vertex)
+  radius  <- rgl.attr(radius, nvertex)
+  nradius <- length(radius)
+  if (!nradius) stop("No radius specified")
+  
+  idata <- as.integer( c( nvertex, nradius ) )
+   
+  ret <- .C( rgl_spheres,
+    success = as.integer(FALSE),
+    idata,
+    as.numeric(vertex),    
+    as.numeric(radius),
+    NAOK=TRUE
+  )
+
+  if (! ret$success)
+    stop("'rgl_spheres' failed")
+    
+  invisible(ret$success)
+
+}
+
+##
+## add planes
+##
+
+rgl.planes <- function( a, b=NULL, c=NULL, d=0,...)
+{
+  rgl.material(...)
+
+  normals  <- rgl.vertex(a, b, c)
+  nnormals <- rgl.nvertex(normals)
+  noffsets <- length(d)
+  
+  idata <- as.integer( c( nnormals, noffsets ) )
+   
+  ret <- .C( rgl_planes,
+    success = as.integer(FALSE),
+    idata,
+    as.numeric(normals),    
+    as.numeric(d),
+    NAOK=TRUE
+  )
+
+  if (! ret$success)
+    stop("'rgl_planes' failed")
+    
+  invisible(ret$success)
+
+}
+
+##
+## add clip planes
+##
+
+rgl.clipplanes <- function( a, b=NULL, c=NULL, d=0)
+{
+  normals  <- rgl.vertex(a, b, c)
+  nnormals <- rgl.nvertex(normals)
+  noffsets <- length(d)
+  
+  idata <- as.integer( c( nnormals, noffsets ) )
+   
+  ret <- .C( rgl_clipplanes,
+    success = as.integer(FALSE),
+    idata,
+    as.numeric(normals),    
+    as.numeric(d),
+    NAOK=TRUE
+  )
+
+  if (! ret$success)
+    stop("'rgl_clipplanes' failed")
+    
+  invisible(ret$success)
+
+}
+
+
+##
+## add abclines
+##
+
+rgl.abclines <- function(x, y=NULL, z=NULL, a, b=NULL, c=NULL, ...)
+{
+  rgl.material(...)
+
+  bases  <- rgl.vertex(x, y, z)
+  nbases <- rgl.nvertex(bases)
+  directions <- rgl.vertex(a, b, c)
+  ndirs <-  rgl.nvertex(directions)
+  
+  idata <- as.integer( c( nbases, ndirs ) )
+   
+  ret <- .C( rgl_abclines,
+    success = as.integer(FALSE),
+    idata,
+    as.numeric(bases),    
+    as.numeric(directions),
+    NAOK=TRUE
+  )
+
+  if (! ret$success)
+    stop("'rgl_abclines' failed")
+    
+  invisible(ret$success)
+
+}
+
+
+##
+## add texts
+##
+
+rgl.texts <- function(x, y=NULL, z=NULL, text, adj = 0.5, justify, family=par3d("family"), 
+                      font=par3d("font"), cex=par3d("cex"), useFreeType=par3d("useFreeType"), ... )
+{
+  rgl.material( ... )
+
+  if (!missing(justify)) {
+     warning("'justify' is deprecated: please use 'adj' instead")
+     if (!missing(adj)) {
+        warning("'adj' and 'justify' both specified: 'justify' ignored")
+     } else adj <- switch(justify,left=0,center=0.5,right=1)
+  }
+  if (length(adj) == 0) adj = c(0.5, 0.5)
+  if (length(adj) == 1) adj = c(adj, 0.5)
+  if (length(adj) > 2) warning("Only the first two entries of 'adj' are used")
+  
+  vertex  <- rgl.vertex(x,y,z)
+  nvertex <- rgl.nvertex(vertex)
+  if (!length(text)) {
+    if (nvertex)
+      warning("No text to plot")
+    return(invisible(integer(0)))
+  }
+    
+  text    <- rep(text, length.out=nvertex)
+  
+  idata <- as.integer(nvertex)
+  
+  nfonts <- max(length(family), length(font), length(cex)) 
+  family <- rep(family, len=nfonts)
+  font <- rep(font, len=nfonts)
+  cex <- rep(cex, len=nfonts)  
+  
+  family[font == 5] <- "symbol"
+  font <- ifelse( font < 0 | font > 4, 1, font)  
+  
+  ret <- .C( rgl_texts,
+    success = as.integer(FALSE),
+    idata,
+    as.double(adj),
+    as.character(text),
+    as.numeric(vertex),
+    as.integer(nfonts),
+    as.character(family), 
+    as.integer(font),
+    as.numeric(cex),
+    as.integer(useFreeType),
+    NAOK=TRUE
+  )
+  
+  if (! ret$success)
+    stop("'rgl_texts' failed")
+
+  invisible(ret$success)
+}
+
+##
+## add sprites
+##
+
+rgl.sprites <- function( x, y=NULL, z=NULL, radius=1.0, shapes=NULL, 
+                         userMatrix=diag(4), ... )
+{
+  rgl.material(...)
+
+  center  <- rgl.vertex(x,y,z)
+  ncenter <- rgl.nvertex(center)
+  radius  <- rgl.attr(radius, ncenter)
+  nradius <- length(radius)
+  if (!nradius) stop("No radius specified")
+  if (length(shapes) && length(userMatrix) != 16) stop("Invalid 'userMatrix'")
+  
+  idata   <- as.integer( c(ncenter,nradius,length(shapes)) )
+  
+  ret <- .C( rgl_sprites,
+    success = as.integer(FALSE),
+    idata,
+    as.numeric(center),
+    as.numeric(radius),
+    as.integer(shapes),
+    as.numeric(userMatrix),
+    NAOK=TRUE
+  )
+
+  if (! ret$success)
+    stop("'rgl_sprites' failed")
+
+  invisible(ret$success)
+}
+
+##
+## convert user coordinate to window coordinate
+## 
+
+rgl.user2window <- function( x, y=NULL, z=NULL, projection = rgl.projection())
+{
+  xyz <- xyz.coords(x,y,z,recycle=TRUE)
+  points <- rbind(xyz$x,xyz$y,xyz$z)
+  
+  idata  <- as.integer(ncol(points))
+  
+  ret <- .C( rgl_user2window,
+  	success = FALSE,
+	idata,
+	as.double(points),
+	window=double(length(points)),
+	model=as.double(projection$model),
+	proj=as.double(projection$proj),
+	view=as.integer(projection$view)
+  )
+
+  if (! ret$success)
+    stop("'rgl_user2window' failed")
+  return(matrix(ret$window, ncol(points), 3, byrow = TRUE))
+}
+
+##
+## convert window coordinate to user coordiante
+## 
+
+rgl.window2user <- function( x, y = NULL, z = 0, projection = rgl.projection())
+{
+  xyz <- xyz.coords(x,y,z,recycle=TRUE)
+  window <- rbind(xyz$x,xyz$y,xyz$z)
+  idata  <- as.integer(ncol(window))
+  
+  ret <- .C( rgl_window2user,
+  	success = FALSE,
+	idata,
+	point=double(length(window)),
+	window,
+	model=as.double(projection$model),
+	proj=as.double(projection$proj),
+	view=as.integer(projection$view)
+  )
+
+  if (! ret$success)
+    stop("'rgl_window2user' failed")
+  return(matrix(ret$point, ncol(window), 3, byrow = TRUE))
+}
+
+# Selectstate values
+msNONE     <- 1
+msCHANGING <- 2
+msDONE     <- 3
+msABORT    <- 4
+
+rgl.selectstate <- function()
+{
+	ret <- .C( rgl_selectstate,
+    	success = FALSE,
+    	state = as.integer(0),
+    	mouseposition = double(4)
+  	)
+
+  	if (! ret$success)
+    	  stop("'rgl_selectstate' failed")
+    return(ret)
+}
+
+
+rgl.select <- function(button = c("left", "middle", "right"))
+{
+	button <- match.arg(button)
+	
+	newhandler <- par3d("mouseMode")
+	newhandler[button] <- "selecting"
+	oldhandler <- par3d(mouseMode = newhandler)
+	on.exit(par3d(mouseMode = oldhandler))
+	
+	while ((result <- rgl.selectstate())$state < msDONE)
+		Sys.sleep(0.1)
+	
+	rgl.setselectstate("none")
+	
+	if (result$state == msDONE)
+	    return(result$mouseposition)
+	else
+	    return(NULL)
+}
+
+rgl.setselectstate <- function(state = "current")
+{
+	state = rgl.enum(state, current=0, none = 1, middle = 2, done = 3, abort = 4)
+	idata <- as.integer(c(state))
+	
+	  ret <- .C( rgl_setselectstate, 
+	    success = FALSE,
+	    state = idata
+	  )
+	
+	  if (! ret$success)
+	    stop("'rgl_setselectstate' failed")
+
+	c("none", "middle", "done", "abort")[ret$state]
+}
+
+rgl.projection <- function()
+{
+    list(model = par3d("modelMatrix"),
+    	 proj = par3d("projMatrix"),
+    	 view = par3d("viewport"))
+}   
+     
+rgl.select3d <- function(button = c("left", "middle", "right")) {
+  rect <- rgl.select(button = button)
+  if (is.null(rect)) return(NULL)
+  
+  llx <- rect[1]
+  lly <- rect[2]
+  urx <- rect[3]
+  ury <- rect[4]
+  
+  if ( llx > urx ){
+  	temp <- llx
+  	llx <- urx
+  	urx <- temp
+  }
+  if ( lly > ury ){
+  	temp <- lly
+  	lly <- ury
+  	ury <- temp
+  }
+  proj <- rgl.projection()
+  function(x,y=NULL,z=NULL) {
+    pixel <- rgl.user2window(x,y,z,projection=proj)
+    x <- pixel[,1]
+    y <- pixel[,2]
+    z <- pixel[,3]
+    (llx <= x) & (x <= urx) & (lly <= y) & (y <= ury) & 
+    (0 <= z) & (z <= 1)
+  }
+}
+
diff --git a/R/selectpoints3d.R b/R/selectpoints3d.R
new file mode 100644
index 0000000..16262eb
--- /dev/null
+++ b/R/selectpoints3d.R
@@ -0,0 +1,66 @@
+selectpoints3d <- function(objects = rgl.ids()$id, value = TRUE, closest = TRUE, 
+                           multiple = FALSE, ...) {
+
+  if (value) result <- cbind(x = numeric(0), y = numeric(0), z = numeric(0))
+  else result <- cbind(id = integer(0), index = integer(0))
+  rdist <- I
+
+  first <- TRUE
+  while (first || is.function(multiple) || multiple) {
+    f <- select3d(...)
+    if (is.null(f)) break
+    
+    e <- environment(f)
+    
+    dist <- Inf
+    prev <- nrow(result)
+    
+    for (id in objects) {
+      verts <- rgl.attrib(id, "vertices")
+      hits <- f(verts)
+      
+      if (any(hits)) dist <- 0
+      else if (closest && dist > 0 && nrow(verts)) {
+        wincoords <- rgl.user2window(verts, projection = e$proj)
+        wz <- wincoords[,3]
+        keep <- (0 <= wz) && (wz <= 1)
+        wincoords <- wincoords[keep,,drop=FALSE]
+  
+        if (!nrow(wincoords)) next 
+  
+        wx <- wincoords[,1]
+        xdist <- ifelse(wx < e$llx, (wx-e$llx)^2, ifelse(wx < e$urx, 0, (wx-e$urx)^2))
+   
+        wy <- wincoords[,2]      
+        ydist <- ifelse(wy < e$lly, (wy-e$lly)^2, ifelse(wy < e$ury, 0, (wy-e$ury)^2))  
+  
+        dists <- xdist + ydist
+        hits <- (dists < dist) & (dists == min(dists))
+        dist <- min(c(dist, dists))
+      }
+      
+      if (!any(hits)) next
+      
+      if (prev && nrow(result) > prev  && rdist > dist)
+        result <- result[seq_len(prev),,drop=FALSE]
+        
+      if (value)
+        result <- rbind(result, verts[hits,])
+      else
+        result <- rbind(result, cbind(id, which(hits)))
+        
+      if (is.function(multiple) && nrow(result) > prev
+          && !multiple(result[(prev+1):nrow(result),,drop=FALSE]))
+        break  
+        
+      rdist <- dist
+      
+      first <- FALSE
+    }
+    
+    if (value)
+      result <- unique(result)
+  
+  }
+  result
+}
diff --git a/R/shapelist3d.R b/R/shapelist3d.R
new file mode 100644
index 0000000..0b6ed51
--- /dev/null
+++ b/R/shapelist3d.R
@@ -0,0 +1,85 @@
+shapelist3d <- function(shapes,x=0,y=NULL,z=NULL,size=1,matrix=NULL,override=TRUE, ..., plot=TRUE) {
+    # This function gets an element with recycling
+    e <- function(x, i) x[[ (i-1) %% length(x) + 1 ]]
+    
+    xyz <- xyz.coords(x, y, z, recycle = TRUE)
+    x <- xyz$x
+    y <- xyz$y
+    if (length(y) == 0) y <- 0
+    z <- xyz$z
+    if (length(z) == 0) z <- 0
+    
+    if (inherits(shapes, "shape3d")) shapes <- list(shapes)
+
+    material <- list(...)
+    
+    if (!is.null(matrix)) {
+	if (!is.list(matrix)) matrix <- list(matrix)
+	len <- length(matrix)
+    } else len <- 0
+    
+    len <- max(len, length(x), length(shapes), length(size), length(override))
+    if (length(material)) len <- max(len, sapply(material, length))
+    
+    result <- vector("list", len)
+    class(result) <- c("shapelist3d", "shape3d")
+
+    for (i in seq_len(len)) {
+	if (is.null(matrix)) this <- e(shapes, i)
+	else this <- rotate3d(e(shapes,i), matrix=e(matrix,i))
+	thissize <- e(size, i)
+	this <- translate3d(scale3d(this, thissize, thissize, thissize), e(x,i), e(y,i), e(z,i))
+	thismaterial <- lapply(material, function(item) e(item,i))
+	if (!e(override,i))
+	    thismaterial[names(this$material)] <- this$material
+	this$material[names(thismaterial)] <- thismaterial
+	result[[i]] <- this
+    }
+    if (plot) shade3d(result)
+    invisible(result)
+}
+
+dot3d.shapelist3d <- function(x, override = TRUE, ...) {
+    .check3d()
+    save <- par3d(skipRedraw = TRUE)
+    on.exit(par3d(save))
+    
+    invisible(unlist(sapply( x, function(item) dot3d(item, override=override, ...) ) ) )
+}
+
+wire3d.shapelist3d <- function(x, override = TRUE, ...) {
+    .check3d()
+    save <- par3d(skipRedraw = TRUE)
+    on.exit(par3d(save))
+    
+    invisible(unlist(sapply( x, function(item) wire3d(item, override=override, ...) ) ) )
+}
+
+
+shade3d.shapelist3d <- function(x, override = TRUE, ...) {
+    .check3d()
+    save <- par3d(skipRedraw = TRUE)
+    on.exit(par3d(save))
+    
+    invisible(unlist(sapply( x, function(item) shade3d(item, override=override, ...) ) ) )
+}
+
+translate3d.shapelist3d <- function ( obj, x, y, z, ... ) {
+  structure(lapply( obj, function(item) translate3d(item, x, y, z, ...) ),
+            class = class(obj))
+}  
+
+rotate3d.shapelist3d <- function ( obj,angle,x,y,z,matrix, ... ) {
+  structure(lapply( obj, function(item) rotate3d(item, x,y,z,matrix,...) ),
+            class = class(obj))
+}  
+
+scale3d.shapelist3d <- function ( obj, x, y, z, ... ) {
+  structure(lapply( obj, function(item) scale3d(item, x,y,z,...) ),
+            class = class(obj))
+}
+
+addNormals.shapelist3d <- function ( x, ... ) {
+  structure(lapply( x, function(item) addNormals(item, ...) ),
+            class = class(x))
+}
diff --git a/R/solids3d.R b/R/solids3d.R
new file mode 100644
index 0000000..21d5fd0
--- /dev/null
+++ b/R/solids3d.R
@@ -0,0 +1,203 @@
+#
+# R 3d object : cube3d
+#
+
+cube3d.vb <- c(
+  -1.0, -1.0, -1.0, 1.0,
+   1.0, -1.0, -1.0, 1.0,
+  -1.0,  1.0, -1.0, 1.0,
+   1.0,  1.0, -1.0, 1.0,
+  -1.0, -1.0,  1.0, 1.0,
+   1.0, -1.0,  1.0, 1.0,
+  -1.0,  1.0,  1.0, 1.0,
+   1.0,  1.0,  1.0, 1.0
+)
+
+cube3d.ib <- c(
+  1, 3, 4, 2,
+  3, 7, 8, 4,
+  2, 4, 8, 6,
+  1, 5, 7, 3,
+  1, 2, 6, 5,
+  5, 6, 8, 7      
+)
+  
+cube3d <- function( trans = identityMatrix(), ... ) {
+  return( rotate3d( qmesh3d( cube3d.vb, cube3d.ib, material=list(...) ), matrix = trans) )
+}  
+
+# 
+# tetrahedron
+#
+
+tetra3d.vb <- c(
+  -1.0, -1.0, -1.0, 1.0,
+   1.0,  1.0, -1.0, 1.0,
+   1.0, -1.0,  1.0, 1.0,
+  -1.0,  1.0,  1.0, 1.0
+)
+
+tetra3d.it <- c(
+  1, 2, 3,
+  3, 2, 4,
+  4, 2, 1,
+  1, 3, 4
+)
+
+tetrahedron3d <- function( trans = identityMatrix(), ... ) {
+  return( rotate3d( tmesh3d( tetra3d.vb, tetra3d.it, material=list(...) ), matrix = trans) )
+}
+
+# 
+# octahedron
+#
+
+octa3d.vb <- c(
+  -1.0,  0.0,  0.0, 1.0,
+   1.0,  0.0,  0.0, 1.0,
+   0.0, -1.0,  0.0, 1.0,
+   0.0,  1.0,  0.0, 1.0,
+   0.0,  0.0, -1.0, 1.0,
+   0.0,  0.0,  1.0, 1.0
+)
+
+octa3d.it <- c(
+  1,5,3, 
+  1,3,6, 
+  1,4,5, 
+  1,6,4, 
+  2,3,5, 
+  2,6,3, 
+  2,5,4, 
+  2,4,6
+)
+
+octahedron3d <- function( trans = identityMatrix(), ... ) {
+  return( rotate3d( tmesh3d( octa3d.vb, octa3d.it, material=list(...) ), matrix = trans) )
+}
+
+#
+# icosahedron
+#
+
+phi <- (1+sqrt(5))/2
+ico3d.vb <- c(
+  0, 1/phi,  1, 1,        
+  0, 1/phi, -1,	1,	
+  0, -1/phi, 1,	1,	
+  0, -1/phi,-1,	1,	
+  1/phi,  1, 0,	1,	
+  1/phi, -1, 0,	1,	
+ -1/phi,  1, 0,	1,	
+ -1/phi, -1, 0,	1,	
+  1, 0,  1/phi,	1,	
+ -1, 0,  1/phi,	1,	
+  1, 0, -1/phi,	1,	
+ -1, 0, -1/phi, 1   )		
+ 
+ 
+ ico3d.it <- c(
+  1, 3, 9, 
+  1, 9, 5,
+  1, 5, 7,
+  1, 7, 10,
+  1, 10, 3,
+  4, 12, 2,
+  4, 2, 11,
+  4, 11, 6,
+  4, 6,  8,
+  4, 8, 12,
+  9, 3, 6,
+  5, 9, 11,
+  7, 5, 2,
+  10, 7, 12,
+  3, 10, 8,
+  2, 12, 7,
+  11, 2, 5,
+  6, 11, 9,
+  8, 6, 3,
+  12, 8, 10)
+  
+icosahedron3d <- function( trans = identityMatrix(), ... ) {
+    return( rotate3d( tmesh3d( ico3d.vb, ico3d.it, material=list(...) ), matrix = trans) )
+}
+
+dodec3d.vb <- c(
+  -1/phi, -1/phi, -1/phi, 1, 
+   1/phi, -1/phi, -1/phi, 1, 
+  -1/phi,  1/phi, -1/phi, 1, 
+   1/phi,  1/phi, -1/phi, 1, 
+  -1/phi, -1/phi,  1/phi, 1, 
+   1/phi, -1/phi,  1/phi, 1, 
+  -1/phi,  1/phi,  1/phi, 1, 
+   1/phi,  1/phi,  1/phi, 1, 
+   0, -1/phi^2, 1, 1,	     
+   0,  1/phi^2, 1, 1,	     
+   0, -1/phi^2,-1, 1,	     
+   0,  1/phi^2,-1, 1,	     
+   -1/phi^2, 1,	0, 1,	     
+    1/phi^2, 1,	0, 1,	     
+   -1/phi^2,-1,	0, 1,	     
+    1/phi^2,-1,	0, 1,	     
+    1, 0,-1/phi^2, 1,	     
+    1, 0, 1/phi^2, 1,	     
+   -1, 0,-1/phi^2, 1,	     
+   -1, 0, 1/phi^2, 1	     
+)		   
+
+dodec3d.if <- c(
+  1, 11, 2, 16, 15, 
+  1, 15, 5, 20, 19,
+  1, 19, 3, 12, 11,
+  2, 11, 12, 4, 17,
+  2, 17, 18, 6, 16,
+  3, 13, 14, 4, 12,
+  3, 19, 20, 7, 13,
+  4, 14, 8, 18, 17,
+  5,  9, 10, 7, 20,
+  5, 15, 16, 6,  9,
+  6, 18,  8,10,  9,
+  7, 10,  8,14, 13)
+  
+dodecahedron3d <- function( trans = identityMatrix(), ...) {
+  m <- matrix(dodec3d.if, 5, 12)
+  return( rotate3d( tmesh3d( dodec3d.vb, c(m[c(1,2,3, 1,3,4, 1,4,5),]), material=list(...) ), matrix=trans) )
+}
+
+cuboct3d.vb <- c(
+ -1, -1, 0, 1,
+ -1,  1, 0, 1,
+  1, -1, 0, 1,
+  1,  1, 0, 1,
+ -1,  0,-1, 1,
+ -1,  0, 1, 1,
+  1,  0,-1, 1,
+  1,  0, 1, 1,
+  0, -1,-1, 1,
+  0, -1, 1, 1,
+  0,  1,-1, 1,
+  0,  1, 1, 1)
+  
+cuboct3d.ib <- c(
+  1, 6, 2, 5,
+  1, 9, 3, 10,
+  2, 12,4, 11,
+  3, 7, 4, 8,
+  5, 11, 7, 9,
+  6, 10, 8, 12)
+  
+cuboct3d.it <- c(
+  1, 5, 9,
+  1, 10, 6,
+  2, 11, 5,
+  2, 6, 12,
+  3, 9, 7,
+  3, 8, 10,
+  4, 7, 11,
+  4, 12, 8)
+  
+cuboctahedron3d <- function( trans = identityMatrix(), ...) {
+  result <- rotate3d( qmesh3d( cuboct3d.vb, cuboct3d.ib, material=list(...) ), matrix = trans)
+  result$it <- matrix(cuboct3d.it, nrow=3)
+  result
+}  
diff --git a/R/stl.R b/R/stl.R
new file mode 100644
index 0000000..d328ca4
--- /dev/null
+++ b/R/stl.R
@@ -0,0 +1,247 @@
+writeSTL <- function(con, ascii=FALSE, pointRadius=0.005, 
+                     pointShape = icosahedron3d(),
+                     lineRadius = pointRadius,
+                     lineSides = 20,
+                     ids = NULL) {
+ 
+  writeHeader <- function() {
+    ident <- paste(filename, " produced by RGL\n")
+    if (ascii) 
+      cat("solid ", ident, file=con)
+    else {
+      padding <- paste(rep(" ", 80), collapse="")
+      ident <- substr( paste("binary", ident, padding), 1, 80)
+      writeChar(ident, con, nchars=80, useBytes=TRUE, eos=NULL)
+      writeBin(0L, con, size=4, endian="little")
+    }
+  }
+      
+  triangles <- 0
+  
+  writeTriangles <- function(vertices) {
+    if (nrow(vertices) %% 3 != 0) stop("Need 3N vertices")
+    n <- nrow(vertices) / 3
+    for (i in seq_len(n)) {
+      vec0 <- vertices[3*i - 2,]
+      vec1 <- vertices[3*i - 1,]
+      vec2 <- vertices[3*i,]
+      normal <- normalize(xprod(vec2-vec0, vec1-vec0))
+      if (ascii) {
+        cat("facet normal ", normal, "\n", file=con)
+        cat("outer loop\n", file=con)
+        cat("vertex ", vec0, "\n", file=con)
+        cat("vertex ", vec1, "\n", file=con)
+        cat("vertex ", vec2, "\n", file=con)
+        cat("endloop\n", file=con)
+        cat("endfacet\n", file=con)
+      } else {
+        writeBin(c(normal, vec0, vec1, vec2), con, size=4, endian="little")
+        writeBin(0L, con, size=2, endian="little")
+      }
+    }
+    triangles <<- triangles + n
+  }
+  
+  writeQuads <- function(vertices) {
+    if (nrow(vertices) %% 4 != 0) stop("Need 4N vertices")
+    n <- nrow(vertices) / 4
+    indices <- rep(seq_len(n)*4, each=6) - rep(c(3, 2, 1, 3, 1, 0), n)
+    writeTriangles( vertices[indices,] )
+  }
+      
+  writeSurface <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    dims <- rgl.attrib(id, "dim")
+    nx <- dims[1]
+    nz <- dims[2]
+    indices <- integer(0)
+    for (j in seq_len(nx-1) - 1) {
+      v1 <- j + nx*(seq_len(nz) - 1) + 1
+      indices <- c(indices, rbind(v1[-nz], v1[-nz]+1, v1[-1]+1, v1[-1]))
+    }
+    writeQuads(vertices[indices,])
+  }
+  
+  writeMesh <- function(mesh, scale=1, offset=c(0,0,0)) {
+    vertices <- asEuclidean(t(mesh$vb))*scale 
+    vertices <- vertices + rep(offset, each=nrow(vertices))
+    nt <- length(mesh$it)/3
+    nq <- length(mesh$ib)/4
+    newverts <- matrix(NA, 3*nt+6*nq, 3)
+    if (nt) 
+      newverts[1:(3*nt),] <- vertices[c(mesh$it),]
+    if (nq)
+      newverts[3*nt+1:(6*nq),] <- vertices[c(mesh$ib[1:3,], 
+      				    mesh$ib[c(1,3,4),]),]
+    writeTriangles(newverts)
+  }
+
+  writeSpheres <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    radii <- rgl.attrib(id, "radii")
+    n <- nrow(vertices)
+    radii <- rep(radii, length.out=n)
+    x <- subdivision3d(icosahedron3d(),3)
+    r <- sqrt(x$vb[1,]^2 + x$vb[2,]^2 + x$vb[3,]^2)
+    x$vb[4,] <- r
+    for (i in seq_along(radii)) 
+      writeMesh(x, radii[i], vertices[i,])
+  }  
+  
+  avgScale <- function() {
+    bbox <- par3d("bbox")
+    ranges <- c(bbox[2]-bbox[1], bbox[4]-bbox[3], bbox[6]-bbox[5])
+    if (prod(ranges) == 0) 1
+    else exp(mean(log(ranges)))
+  }  
+   
+  writePoints <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    n <- nrow(vertices)
+    radius <- pointRadius*avgScale()
+    for (i in seq_len(n))
+      writeMesh(pointShape, radius, vertices[i,])
+  }
+  
+  writeSegments <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    n <- nrow(vertices)/2
+    radius <- lineRadius*avgScale()
+    for (i in seq_len(n)) {
+      cyl <- cylinder3d(vertices[(2*i-1):(2*i),], 
+      			radius = radius,
+      			sides = lineSides,
+      			closed = -2)
+      writeMesh(cyl)
+    }
+  }
+  
+  writeLines <- function(id) {
+    vertices <- rgl.attrib(id, "vertices")
+    n <- nrow(vertices) - 1
+    radius <- lineRadius*avgScale()
+    for (i in seq_len(n)) 
+      writeMesh( cylinder3d( vertices[i:(i+1),],
+     			   radius = radius,
+     			   sides = lineSides, 
+     			   closed = -2) )
+  }
+  
+  knowntypes <- c("triangles", "quads",
+                  "surface", "planes", "spheres",
+                  "points", "lines", "linestrip")
+  
+  #  Execution starts here!
+
+  if (is.character(con)) {
+    con <- file(con, if (ascii) "w" else "wb")
+    on.exit(close(con))
+  }
+  filename <- summary(con)$description
+  
+  if (NROW(bbox <- rgl.ids("bboxdeco")) && (is.null(ids) || bbox$id %in% ids)) {
+    ids <- setdiff(ids, bbox$id)
+    save <- par3d(skipRedraw = TRUE)
+    bbox <- convertBBox(bbox$id)
+    on.exit({ rgl.pop(id=bbox); par3d(save) }, add=TRUE)
+    dobbox <- TRUE
+  } else dobbox <- FALSE 
+  
+  if (is.null(ids)) {
+    ids <- rgl.ids()
+    types <- as.character(ids$type)
+    ids <- ids$id
+  } else {
+    if (dobbox) ids <- c(ids, bbox)
+    allids <- rgl.ids()
+    ind <- match(ids, allids$id)
+    keep <- !is.na(ind)
+    if (any(!keep)) warning(gettextf("Object(s) with id %s not found", paste(ids[!keep], collapse=" ")),
+    			    domain = NA)
+    ids <- ids[keep]
+    types <- allids$type[ind[keep]]
+  }  
+    
+  unknowntypes <- setdiff(types, knowntypes)
+  if (length(unknowntypes))
+    warning(gettextf("Object type(s) %s not handled", 
+      paste("'", unknowntypes, "'", sep="", collapse=", ")), domain = NA)
+
+  keep <- types %in% knowntypes
+  ids <- ids[keep]
+  types <- types[keep]
+
+  writeHeader()
+  
+  for (i in seq_along(ids)) 
+    switch(types[i],
+      planes =,
+      triangles = writeTriangles(rgl.attrib(ids[i], "vertices")),
+      quads = writeQuads(rgl.attrib(ids[i], "vertices")),
+      surface = writeSurface(ids[i]),
+      spheres = writeSpheres(ids[i]),
+      points = writePoints(ids[i]),
+      lines = writeSegments(ids[i]),
+      linestrip = writeLines(ids[i])
+    )
+  
+  if (!ascii) {
+    seek(con, 80)
+    writeBin(as.integer(triangles), con, size=4, endian="little")
+  }
+    
+  invisible(filename)
+}
+
+readSTL <- function(con, ascii=FALSE, plot=TRUE, ...) {
+ 
+  # Utility functions and constants defined first; execution starts way down there...
+  
+  triangles <- NULL
+  
+  readHeader <- function() {
+    if (ascii) {
+      ident <- readLines(con, 1)
+      if (!grepl("^solid ", ident)) stop("This does not appear to be an ASCII STL file")
+    }
+    if (!ascii) {
+      seek(con, 80)
+      triangles <<- readBin(con, "integer", n=1, size=4, endian="little")
+    }
+  }
+  
+  readTriangles <- function(n) {
+    
+    if (ascii) {
+      lines <- readLines(con)
+      if (is.null(n)) n <- lines %/% 7
+    }
+   
+    vertices <- matrix(NA, 3*n, 3)
+    
+    if (!ascii) {
+      for (i in seq_len(n)) {
+        m <- matrix(readBin(con, "double", n=12, size=4, endian="little"), 4, 3, byrow=TRUE)
+        vertices[3*i + c(-2,-1,0),] <- m[2:4,]
+        count <- readBin(con, "integer", n=1, size=2, endian="little")
+      }
+    }
+    vertices
+  }
+      
+  #  Execution starts here!
+  
+  if (ascii) stop("ASCII input not yet supported")
+
+  if (is.character(con)) {
+    con <- file(con, if (ascii) "rt" else "rb")
+    on.exit(close(con))
+  }
+  
+  readHeader()
+  vertices <- readTriangles(triangles)
+  if (plot)
+    triangles3d(vertices, ...)
+  else
+    vertices
+}
diff --git a/R/subdivision.mesh3d.R b/R/subdivision.mesh3d.R
new file mode 100644
index 0000000..d96a503
--- /dev/null
+++ b/R/subdivision.mesh3d.R
@@ -0,0 +1,250 @@
+# 
+# subdivision.mesh3d
+#
+# an *efficient* algorithm for subdivision of mesh3d objects
+# using addition operations and homogenous coordinates 
+# by Daniel Adler 
+#
+# $Id: subdivision.mesh3d.R 1113 2014-07-16 13:03:01Z murdoch $
+# 
+
+edgemap <- function( size ) {
+  data<-vector( mode="numeric", length=( size*(size+1) )/2 )
+  data[] <- -1
+  return(data)
+}
+
+edgeindex <- function( from, to, size, row=min(from,to), col=max(from,to) )
+  return( row*size - ( row*(row+1) )/2 - (size-col) )
+
+divide.mesh3d <- function (mesh,vb=mesh$vb, ib=mesh$ib, it=mesh$it ) {
+  nv    <- dim(vb)[2]
+  inds <- seq_len(nv)
+  nq <- if (is.null(ib)) 0 else dim(ib)[2]
+  nt <- if (is.null(it)) 0 else dim(it)[2]
+  primout <- c()
+  nvmax <- nv + nq + ( nv*(nv+1) )/2
+  outvb <- matrix(data=0,nrow=4,ncol=nvmax)  
+  # copy old points
+  outvb[,seq_len(nv)] <- vb  
+  vcnt <- nv
+  em    <- edgemap( nv )
+  
+  if (!is.null(mesh$normals)) {
+    if (NROW(mesh$normals) == 4)
+      mesh$normals <- t(asEuclidean(t(mesh$normals)))
+    newnormals <- matrix(data=0,nrow=3,ncol=nvmax)
+    newnormals[,inds] <- mesh$normals
+  } else newnormals <- NULL
+  
+  if (!is.null(mesh$texcoords)) {
+    newtexcoords <- matrix(data=0,nrow=2,ncol=nvmax)
+    newtexcoords[,inds] <- mesh$texcoords
+  } else newtexcoords <- NULL
+  
+  if (!is.null(newnormals) || !is.null(newtexcoords)) {
+    newcount <- rep(0, nvmax)
+    newcount[inds] <- 1
+  }
+  
+  result <- structure(list(material=mesh$material), class="mesh3d")
+  
+  if (nq) {
+    newnq <- nq*4
+
+    outib <- matrix(nrow=4,ncol=newnq)
+    vcnt  <- vcnt + nq
+  
+    for (i in 1:nq ) {
+      isurf <- nv + i
+      for (j in 1:4 ) {
+      
+        iprev <- ib[((j+2)%%4) + 1, i]
+        ithis <- ib[j,i]
+        inext <- ib[ (j%%4)    + 1, i]
+      
+        # get or alloc edge-point this->next
+        mindex <- edgeindex(ithis, inext, nv)
+        enext <- em[mindex]
+        if (enext == -1) {
+          vcnt       <- vcnt + 1
+          enext      <- vcnt
+          em[mindex] <- enext
+        }
+
+        # get or alloc edge-point prev->this
+        mindex <- edgeindex(iprev, ithis, nv)
+        eprev <- em[mindex]
+        if (eprev == -1) {
+          vcnt       <- vcnt + 1
+          eprev      <- vcnt
+          em[mindex] <- eprev
+        }
+
+        # gen grid      
+        outib[, (i-1)*4+j ] <- c( ithis, enext, isurf, eprev )
+
+        # calculate surface point
+        outvb[,isurf] <- outvb[,isurf] + vb[,ithis]
+      
+        # calculate edge point
+        outvb[,enext] <- outvb[,enext] + vb[,ithis] 
+        outvb[,eprev] <- outvb[,eprev] + vb[,ithis] 
+        
+        if (!is.null(newnormals)) {
+          thisnorm <- mesh$normals[,ithis]
+          newnormals[,isurf] <- newnormals[,isurf] + thisnorm
+          newnormals[,enext] <- newnormals[,enext] + thisnorm
+          newnormals[,eprev] <- newnormals[,eprev] + thisnorm
+        }
+        
+        if (!is.null(newtexcoords)) {
+          thistexcoord <- mesh$texcoords[,ithis]
+          newtexcoords[,isurf] <- newtexcoords[,isurf] + thistexcoord
+          newtexcoords[,enext] <- newtexcoords[,enext] + thistexcoord
+          newtexcoords[,eprev] <- newtexcoords[,eprev] + thistexcoord
+        }
+        
+        if (!is.null(newnormals) || !is.null(newtexcoords)) {
+          newcount[isurf] <- newcount[isurf] + 1
+          newcount[enext] <- newcount[enext] + 1
+          newcount[eprev] <- newcount[eprev] + 1
+        }
+      }
+    }
+    primout <- "quad"
+    result$ib <- outib
+  }
+  if (nt) {
+    newnt <- nt*4
+    outit <- matrix(nrow=3,ncol=newnt)
+  
+    for (i in 1:nt ) {
+      for (j in 1:3 ) {
+      
+        iprev <- it[((j+1)%%3) + 1, i]
+        ithis <- it[j,i]
+        inext <- it[ (j%%3)    + 1, i]
+        
+        # get or alloc edge-point this->next
+        mindex <- edgeindex(ithis, inext, nv)
+        enext <- em[mindex]
+        if (enext == -1) {
+          vcnt       <- vcnt + 1
+          enext      <- vcnt
+          em[mindex] <- enext
+        }
+
+        # get or alloc edge-point prev->this
+        mindex <- edgeindex(iprev, ithis, nv)
+        eprev <- em[mindex]
+        if (eprev == -1) {
+          vcnt       <- vcnt + 1
+          eprev      <- vcnt
+          em[mindex] <- eprev
+        }
+
+        # gen grid      
+        outit[, (i-1)*4+j ] <- c( ithis, enext, eprev )
+      
+        # calculate edge point
+        outvb[,enext] <- outvb[,enext] + vb[,ithis] 
+        outvb[,eprev] <- outvb[,eprev] + vb[,ithis] 
+        
+        if (!is.null(newnormals)) {
+          thisnorm <- mesh$normals[,ithis]
+          newnormals[,enext] <- newnormals[,enext] + thisnorm
+          newnormals[,eprev] <- newnormals[,eprev] + thisnorm
+        }
+        
+        if (!is.null(newtexcoords)) {
+          thistexcoord <- mesh$texcoords[,ithis]
+          newtexcoords[,enext] <- newtexcoords[,enext] + thistexcoord
+          newtexcoords[,eprev] <- newtexcoords[,eprev] + thistexcoord
+        }
+        
+        if (!is.null(newnormals) || !is.null(newtexcoords)) {
+          newcount[enext] <- newcount[enext] + 1
+          newcount[eprev] <- newcount[eprev] + 1
+        }        
+
+      }
+      # Now central triangle
+      
+      outit[, (i-1)*4+4 ] <- c( em[edgeindex(ithis, inext, nv)],
+                                em[edgeindex(inext, iprev, nv)],
+                                em[edgeindex(iprev, ithis, nv)] )
+    }
+    primout <- c(primout, "triangle")
+    result$it <- outit
+  }
+  
+  if (!is.null(newnormals) || !is.null(newtexcoords)) 
+    newcount <- newcount[seq_len(vcnt)]
+    
+  if (!is.null(newnormals)) 
+    newnormals <- newnormals[, seq_len(vcnt)]/rep(newcount, each=3)
+    
+  if (!is.null(newtexcoords))
+    newtexcoords <- newtexcoords[, seq_len(vcnt)]/rep(newcount, each=2)
+    
+  result$vb <- outvb[,seq_len(vcnt)]
+  result$normals <- newnormals
+  result$texcoords <- newtexcoords
+  
+  result$primitivetype <- primout
+  return ( result )
+}
+
+normalize.mesh3d <- function (mesh) {
+  mesh$vb[1,] <- mesh$vb[1,]/mesh$vb[4,]
+  mesh$vb[2,] <- mesh$vb[2,]/mesh$vb[4,]
+  mesh$vb[3,] <- mesh$vb[3,]/mesh$vb[4,]
+  mesh$vb[4,] <- 1
+  return (mesh)
+}
+
+deform.mesh3d <- function( mesh, vb=mesh$vb, ib=mesh$ib, it=mesh$it )
+{
+  nv <- dim(vb)[2]
+  nq <- if (is.null(ib)) 0 else dim(ib)[2]
+  nt <- if (is.null(it)) 0 else dim(it)[2]
+  out <- matrix(0, nrow=4, ncol=nv )
+  if (nq) {
+    for ( i in 1:nq ) {
+      for (j in 1:4 ) {
+        iprev <- ib[((j+2)%%4) + 1, i]
+        ithis <- ib[j,i]
+        inext <- ib[ (j%%4)    + 1, i]
+        out[ ,ithis ] <- out[ , ithis ] + vb[,iprev] + vb[,ithis] + vb[,inext]
+      }
+    }
+    mesh$vb <- out
+  }
+  if (nt) {
+    for ( i in 1:nt ) {
+      for (j in 1:3 ) {
+        iprev <- it[((j+1)%%3) + 1, i]
+        ithis <- it[j,i]
+        inext <- it[ (j%%3)    + 1, i]
+        out[ ,ithis ] <- out[ , ithis ] + vb[,iprev] + vb[,ithis] + vb[,inext]
+      }
+    }
+    mesh$vb <- out
+  }  
+  return(mesh)
+}
+
+subdivision3d.mesh3d <- function(x,depth=1,normalize=FALSE,deform=TRUE,...) {
+  mesh <- x
+  if (depth) {
+    mesh <- divide.mesh3d(mesh)
+    if (normalize)
+      mesh <- normalize.mesh3d(mesh)
+    if (deform)
+      mesh <- deform.mesh3d(mesh)      
+    mesh<-subdivision3d.mesh3d(mesh,depth-1,normalize,deform)
+  }
+  return(mesh)  
+}
+
diff --git a/R/subscenes.R b/R/subscenes.R
new file mode 100644
index 0000000..07b3b4f
--- /dev/null
+++ b/R/subscenes.R
@@ -0,0 +1,264 @@
+currentSubscene3d <- function(dev = rgl.cur()) {
+  .C(rgl_getsubsceneid, id = 1L, dev = as.integer(dev))$id
+}
+
+subsceneInfo <- function(id = NA, embeddings, recursive = FALSE) {
+  if (is.na(id)) 
+    id <- currentSubscene3d()
+  else if (is.character(id) && id == "root") 
+    id <- .C(rgl_getsubsceneid, id = 0L, dev = as.integer(rgl.cur()))$id
+  if (!id) stop("No subscene info available.")
+  id <- as.integer(id)
+  result <- list(id = id)
+  
+  parent <- .C(rgl_getsubsceneparent, id = id)$id
+  
+  if (is.na(parent)) stop(gettextf("Subscene %s not found", id), domain = NA)
+  if (!parent) parent <- NULL
+  result[["parent"]] <- parent
+  
+  n <- .C(rgl_getsubscenechildcount, id = id, n = integer(1))$n
+  if (n) {
+    children <- .C(rgl_getsubscenechildren, id = id, children=integer(n))$children
+    if (recursive) {
+      childlist <- list()
+      for (i in seq_len(n))
+        childlist[[i]] <- subsceneInfo(id = children[i], recursive = TRUE)
+      result[["children"]] <- childlist
+    } else
+      result[["children"]] <- children
+  }
+  
+  embeddingNames <- c("inherit", "modify", "replace")
+  if (!missing(embeddings)) {
+    embeddings <- pmatch(embeddings, embeddingNames, duplicates.ok = TRUE)
+    if (any(is.na(embeddings)) || length(embeddings) != 3)
+      stop(gettextf("Three embeddings must be specified; names chosen from %s", 
+      	            paste(dQuote(embeddingNames), collapse=", ")), domain = NA)
+    .C(rgl_setEmbeddings, id = id, embeddings = embeddings)
+  }
+  embeddings <- .C(rgl_getEmbeddings, id = id, embeddings = integer(3))$embeddings
+  embeddings <- embeddingNames[embeddings]
+  names(embeddings) <- c("viewport", "projection", "model")
+  result[["embeddings"]] <- embeddings
+  result
+}
+
+newSubscene3d <- function(viewport = "replace", 
+                       projection = "replace",
+		       model = "replace",
+                       parent = currentSubscene3d(), copyLights = TRUE,
+                       copyShapes = FALSE,
+                       copyBBoxDeco = copyShapes,
+                       copyBackground = FALSE,
+                       newviewport,
+                       ignoreExtent) {
+  embedding <- c("inherit", "modify", "replace")
+  viewport <- pmatch(viewport, embedding)
+  projection <- pmatch(projection, embedding)
+  model <- pmatch(model, embedding)
+  if (missing(ignoreExtent))
+    ignoreExtent <- model != 1
+  stopifnot(length(viewport) == 1, length(projection) == 1, length(model) == 1,
+            !is.na(viewport), !is.na(projection), !is.na(model))
+  embedding <- c(viewport, projection, model)
+  
+  id <- .C(rgl_newsubscene, id = integer(1), parent = as.integer(parent),
+               embedding = as.integer(embedding),
+               as.integer(ignoreExtent))$id
+               
+  if (id) {
+    if (copyLights || copyShapes || copyBBoxDeco || copyBackground) {
+      useSubscene3d(parent)
+      ids <- rgl.ids(type = 
+        c("lights", "shapes", "bboxdeco", "background")[c(copyLights, copyShapes, copyBBoxDeco, copyBackground)])$id
+      if (length(ids)) 
+        addToSubscene3d(ids, subscene = id)
+    }
+    useSubscene3d(id)
+    if (!missing(newviewport)) {
+      embedding <- subsceneInfo(id)$embeddings
+      if (embedding[1] > 1)
+        par3d(viewport = as.integer(newviewport))
+    }
+  } else
+    stop("Subscene creation failed")
+  invisible(id)
+}
+
+useSubscene3d <- function(subscene) {
+  result <- .C(rgl_setsubscene, id=as.integer(subscene))$id
+  if (!result) stop(gettextf("Subscene %d not found.", subscene), domain = NA)
+  invisible(subscene)
+}
+
+addToSubscene3d <- function(ids, subscene = currentSubscene3d()) {
+  ids <- as.integer(ids)
+  dups <- intersect(ids, rgl.ids("all", subscene)$id)
+  if (length(dups))
+    stop(gettextf("Cannot add %s, already present", paste(dups, collapse = ", ")), domain = NA)
+  result <- .C(rgl_addtosubscene, success = as.integer(subscene), 
+     n = as.integer(length(ids)), ids = ids)$success
+  if (!result)
+    stop(gettextf("Failed to add objects to subscene %s", subscene), domain = NA)
+  invisible(subscene)
+}
+
+delFromSubscene3d <- function(ids, subscene = currentSubscene3d()) {
+  result <- .C(rgl_delfromsubscene, success = as.integer(subscene), 
+     n = as.integer(length(ids)), ids = as.integer(ids))$success
+  if (!result)
+    stop(gettextf("Failed to delete objects from subscene %s", subscene), domain = NA)
+  invisible(subscene)
+}
+
+# This destroys any objects that are in the scene but
+# not in either the protect vector or visible in a subscene
+
+gc3d <- function(protect=NULL) {
+  protect <- as.integer(protect)
+  invisible( .C(rgl_gc, n = length(protect), protect)$n )
+}
+
+subsceneList <- function(value, window = rgl.cur()) {
+  alllists <- .rglEnv$subsceneLists  
+  # This cleans up lists for closed windows:
+  alllists <- alllists[names(alllists) %in% rgl.dev.list()]
+  if (!missing(value)) {
+    if (is.null(alllists)) alllists <- list()
+    alllists[[as.character(window)]] <- value
+    assign("subsceneLists", alllists, envir = .rglEnv)
+  }
+  if (is.null(alllists)) return(NULL)
+  else return(alllists[[as.character(window)]])
+}
+
+next3d <- function(current = NA, clear = TRUE, reuse = TRUE) {
+  .check3d()
+  if (is.na(current))
+    current <- currentSubscene3d()
+  subscenes <- subsceneList()
+  if (is.null(subscenes)) 
+    subscenes <- current
+  if (current %in% subscenes) {
+    this <- which(current == subscenes)
+    if (reuse && !nrow(rgl.ids(subscene = current))) {
+      # do nothing
+    } else if (this == length(subscenes)) 
+      this <- 1
+    else 
+      this <- this + 1
+  } else {
+    warning("Current subscene is not in the subsceneList()")
+    this <- 1
+  }  
+  repeat{
+    current <- subscenes[this]
+    result <- try(useSubscene3d(current))
+    if (inherits(result, "try-error")) {
+      subsceneList(subscenes <- subscenes[-this])
+      if (length(subscenes) == 0)
+      	stop("'subsceneList()' contained no valid subscenes")
+      if (this > length(subscenes)) this <- 1
+    } else break
+  }
+      
+  if (clear)
+    clear3d(subscene = current)
+}
+  
+clearSubsceneList <- function(delete = currentSubscene3d() %in% subsceneList(),
+                              window = rgl.cur()) {
+  if (!missing(window))
+    rgl.set(window)  
+  thelist <- subsceneList()
+  if (delete && length(thelist)) {
+    parent <- subsceneInfo(thelist[1])$parent
+    if (is.null(parent))
+      parent <- rootSubscene()
+    pop3d(type="subscene", id=thelist)
+    useSubscene3d(parent)
+    gc3d()
+  }
+  subsceneList(attr(thelist, "prev"))
+  invisible(currentSubscene3d())
+}
+
+mfrow3d <- function(nr, nc, byrow = TRUE, parent = NA, sharedMouse = FALSE,
+                           ...) {
+  stopifnot(nr >= 1, nc >= 1)
+  .check3d()
+  if (missing(parent))
+    clearSubsceneList()
+  if (is.na(parent))
+    parent <- currentSubscene3d()
+  useSubscene3d(parent)
+  result <- integer(nr*nc)
+  parentvp <- par3d("viewport")
+  if (byrow)
+    for (i in seq_len(nr))
+      for (j in seq_len(nc)) {
+        newvp <- c(parentvp[1] + (j - 1)*parentvp[3]/nc,
+                   parentvp[2] + (nr - i)*parentvp[4]/nr,
+                   parentvp[3]/nc, parentvp[4]/nr)
+        result[(i-1)*nc + j] <- newSubscene3d(newviewport = newvp, parent = parent, ...)
+      }
+  else
+    for (j in seq_len(nc))
+      for (i in seq_len(nr)) {
+        newvp <- c(parentvp[1] + (j - 1)*parentvp[3]/nc,
+                   parentvp[2] + (nr - i)*parentvp[4]/nr,
+                   parentvp[3]/nc, parentvp[4]/nr)
+        result[(j-1)*nr + i] <- newSubscene3d(newviewport = newvp, parent = parent, ...)
+      }
+  if (sharedMouse)
+    for (sub in result)
+      par3d(listeners = result, subscene = sub)
+  useSubscene3d(result[1])
+  attr(result, "prev") <- subsceneList()
+  subsceneList(result)
+  invisible(result)
+}
+
+layout3d <- function(mat, widths = rep.int(1, ncol(mat)), 
+                          heights = rep.int(1, nrow(mat)),
+                          parent = NA, sharedMouse = FALSE,
+                          ...) {
+  storage.mode(mat) <- "integer"
+  mat <- as.matrix(mat)
+  num.figures <- max(mat)
+  if (!all(seq_len(num.figures) %in% as.integer(mat)))
+    stop(gettextf("Layout matrix must contain at least one reference\nto each of the values {1 ... %d}\n", 
+            num.figures), domain = NA)
+  dm <- dim(mat)
+  num.rows <- dm[1L]
+  num.cols <- dm[2L]
+
+  .check3d()
+  if (missing(parent))
+    clearSubsceneList()
+  if (is.na(parent))
+    parent <- currentSubscene3d()
+  useSubscene3d(parent)
+  parentvp <- par3d("viewport")
+  
+  widths <- parentvp["width"]*widths/sum(widths)
+  heights <- parentvp["height"]*heights/sum(heights)
+  xs <- c(0, cumsum(widths))
+  ys <- rev(c(0, cumsum(rev(heights))))[-1]
+  
+  result <- integer(num.figures)
+  for (i in seq_len(num.figures)) {
+    rows <- range(row(mat)[mat == i])
+    cols <- range(col(mat)[mat == i])
+    newvp <- c(xs[cols[1]], ys[rows[1]], sum(widths[cols[1]:cols[2]]), sum(heights[rows[1]:rows[2]]))
+    result[i] <- newSubscene3d(newviewport = newvp, parent = parent,  ...)
+  }
+  if (sharedMouse)
+    for (sub in result)
+      par3d(listeners = result, subscene = sub)
+  useSubscene3d(result[1])
+  attr(result, "prev") <- subsceneList()
+  subsceneList(result)
+  invisible(result)
+}
diff --git a/R/triangulate.R b/R/triangulate.R
new file mode 100644
index 0000000..8162ab0
--- /dev/null
+++ b/R/triangulate.R
@@ -0,0 +1,310 @@
+
+pointInPoly <- function(poly, pt) {
+  # polygon is 2 x n, columns are vertices
+  # point is 2 vector
+  n <- ncol(poly)
+  i1 <- seq_len(n)
+  i2 <- i1 %% n + 1
+  x <- poly[1,i1] + (poly[1,i2] - poly[1,i1])*(pt[2] - poly[2,i1])/(poly[2,i2] - poly[2,i1])
+  crossings <- ((poly[2,i1] < pt[2]) & (pt[2] <= poly[2,i2]) 
+              | (poly[2,i2] < pt[2]) & (pt[2] <= poly[2,i1])) & pt[1] < x
+  sum(crossings) %% 2 == 1
+}
+	
+intersectSegSeg <- function(seg1,seg2) {
+  # do segments intersect?
+  # both segments have endpoints as columns
+  coeffs <- try(solve(cbind(seg1[,2]-seg1[,1], seg2[,1]-seg2[,2]), seg2[,1]-seg1[,1]), silent=TRUE)
+  if (inherits(coeffs, "try-error")) return (FALSE)
+  all(zapsmall(coeffs) >= 0) && all(zapsmall(1-coeffs) >= 0)
+}
+  
+  
+intersectTriSeg <- function(tri, seg) {
+  # intersect a triangle with a segment
+  # tri is 2 x 3, columns are vertices
+  # seg is 2 x 2, columns are endpoints
+  coeffs <- try(solve(rbind(tri,1), rbind(seg,1)), silent=TRUE)
+  if (inherits(coeffs, "try-error")) return(TRUE)
+  coeffs <- zapsmall(coeffs)  
+  if (any(apply(coeffs <= 0, 1, all))) return(FALSE)
+  if (any(apply(coeffs > 0, 2, all))) return(TRUE)
+  up <- coeffs[,1] < 0
+  dn <- coeffs[,2] < 0  
+#  if (!any(up) || !any(dn)) return(TRUE)
+  lb <- max( -coeffs[up,1]/(coeffs[up,2]-coeffs[up,1]) )
+  ub <- 1 - max( -coeffs[dn,2]/(coeffs[dn,1] - coeffs[dn,2]) )
+  lb <= ub
+}
+
+triangulateSimple <- function(x,y, random=TRUE, plot=FALSE, partial=NA) {
+  n <- length(x)
+  stopifnot(n == length(y))
+  stopifnot(n > 2)
+  
+  it <- matrix(NA_integer_, nrow=3, ncol=n-2)
+  verts <- seq_len(n)
+  while((m <- length(verts)) > 3) {
+    i1 <- 1:m
+    i2 <- i1 %% m + 1
+    i3 <- i2 %% m + 1
+    theta3 <- atan2(y[verts[i3]]-y[verts[i1]], x[verts[i3]]-x[verts[i1]])
+    theta2 <- atan2(y[verts[i2]]-y[verts[i1]], x[verts[i2]]-x[verts[i1]])
+    # diff <- (theta3-theta2+4*pi) %% (2*pi)
+    diff <- ( (theta3-theta2)/pi + 4 ) %% 2
+    convex <- which(diff < 1) 
+    if (random && length(convex) > 1)
+      convex <- sample(convex)
+    good <- FALSE  # just in case none are convex
+    for (k in convex) {
+      i <- c(i1[k],i2[k],i3[k])
+      tri <- rbind(x[verts[i]], y[verts[i]])
+      good <- TRUE
+      for (j in 2:(m-1)) {
+        i4 <- (i1[k] + j - 1) %% m + 1
+        i5 <- (i1[k] + j) %% m + 1
+        j <- c(i4,i5)
+        if (intersectTriSeg(tri, rbind(x[verts[j]], y[verts[j]]))) {
+	  good <- FALSE
+	  break
+        }
+      }
+      if (good) {
+        if (plot)
+          polygon(x[verts[i]], y[verts[i]], col=m)
+        it[, m-2] <- verts[i]
+        verts <- verts[-i2[k]]
+        break
+      }
+    }
+    if (!good) break
+  }
+  if (!good) {
+    if (is.na(partial)) {
+      warning("Triangulation is incomplete")
+      partial <- TRUE
+    }
+    if (partial)
+      it <- it[,seq_len(n-m)+m-2, drop=FALSE]
+    else
+      it <- NULL
+  } else {
+    if (plot)
+      polygon(x[verts], y[verts], col=3)
+    it[, 1] <- verts
+  }
+  it
+}
+
+triangulate <- function(x, y = NULL, z = NULL, random=TRUE, plot=FALSE, partial=NA) {
+  xyz <- xyz.coords(x, y, z)
+  if (xyz$xlab == "Index" && is.null(z) && (is.null(ncol(x)) || ncol(x) == 2L)) {
+    x <- xyz$y
+    y <- xyz$z
+  } else {
+    x <- xyz$x
+    y <- xyz$y
+    if (!diff(range(x))) 
+      x <- xyz$z
+    else if (!diff(range(y))) 
+      y <- xyz$z
+  } 
+  nesting <- nestPolys(x, y)
+  verts <- nesting$verts
+  nextvert <- rep(NA, length(x))
+  
+  processInside <- function(v) {
+    for (i in nesting$nesting[[v]])
+      processOutside(i)
+  }
+  
+  processOutside <- function(fwd) {
+    fwd1 <- verts[[fwd]]
+    nextvert[fwd1] <<- c(fwd1[-1], fwd1[1])
+    reversed <- nesting$nesting[[fwd]]   
+    for (rev in reversed) {
+      rev1 <- rev(verts[[rev]])
+      nextvert[rev1] <<- c(rev1[-1], rev1[1])
+      
+      processInside(rev)
+      done <- FALSE
+      # we know at least one point of rev is in fwd, so merge them.
+      # If this fails, the polygons are messed up.
+      # We look for a segment from fwd to rev that intersects no other segments 
+      # in either loop.
+      pairs <- expand.grid(seq_along(fwd1), seq_along(rev1))
+      if (random)
+        pairs <- pairs[sample(nrow(pairs)),]
+      for (p in seq_len(nrow(pairs))) {
+        i <- fwd1[pairs[p,1]]
+	j <- rev1[pairs[p,2]]
+	seg <- cbind( c(x[i], y[i]),
+	              c(x[j], y[j]) )
+	clear <- TRUE
+	for (q in seq_along(verts)) {
+	  i1 <- verts[[q]]
+	  if (!length(i1)) next
+	  i2 <- c(i1[-1], i1[1])
+	  for (v in seq_along(i1)) 
+	    if (length(intersect(c(i1[v], i2[v]), c(i,j))) == 0
+		&& intersectSegSeg(seg, cbind( c(x[i1[v]], y[i1[v]]), c(x[i2[v]], y[i2[v]]) ))) {
+	      clear <- FALSE
+	      break
+	    }
+	  if (!clear) break
+	}
+	if (clear) {  # Found a segment that doesn't intersect anything, so join the two polys
+	  i <- pairs[p,1]
+	  j <- pairs[p,2]
+	  ind <- c(fwd1[seq_len(i)], rev1[j:length(rev1)], rev1[seq_len(j)])
+	  if (i < length(fwd1))
+	    ind <- c(ind, fwd1[i:length(fwd1)])
+	  verts[[fwd]] <<- fwd1 <- ind
+	  verts[[rev]] <<- integer(0)
+	  done <- TRUE
+	  break
+	}
+      }
+      if (!done)
+        stop("Cannot simplify polygon")
+    }
+    ind <- verts[[fwd]]
+    tri <- triangulateSimple(x[ind], y[ind], random, plot, partial=FALSE)
+    if (is.null(tri)) 
+      stop("Cannot triangulate polygon")
+    # Convert back to original numbering
+    dim <- dim(tri)
+    tri <- ind[tri]
+    dim(tri) <- dim
+    # Put in place as triangulation of the forward poly
+    subtri[[fwd]] <<- tri
+  }
+  
+  subtri <- list()
+  for (i in nesting$toplevel)
+    processOutside(i)
+  
+  # Done all polys, now combine
+  res <- matrix(nrow=3, ncol=0)
+  for (i in seq_along(subtri))
+    res <- cbind(res, subtri[[i]])
+  attr(res, "nextvert") <- nextvert
+  res
+}
+
+# Rewrite a complex polygon as a list of the individual parts, oriented correctly,
+# with attribute showing nesting
+
+nestPolys <- function(x,y = NULL) {
+  xy <- xy.coords(x, y)
+  x <- xy$x
+  y <- xy$y
+  n <- length(x)
+  nas <- c(which(is.na(x) | is.na(y)), n + 1L)
+  prev <- 0L
+  verts <- list()
+  for (i in seq_along(nas)) {
+    verts[[i]] <- ind <- (prev + 1L):(nas[i] - 1L)
+    tri <- triangulateSimple(x[ind], y[ind], random=TRUE, plot=FALSE, partial=FALSE)
+    if (is.null(tri))
+      verts[[i]] <- rev(verts[[i]])
+    prev <- nas[i]
+  }
+  # nesting is a list of vectors
+  # of poly numbers that are directly nested within the corresponding element of verts
+  # The last one at length(verts)+1 lists polys not nested anywhere
+  
+  nesting <- rep(list(integer()), length(verts)+1)
+  place <- function(new, toplevel) {    
+    placed <- FALSE
+    contains <- integer()
+    if (length(nesting[[toplevel]])) {
+      newverts <- rbind(x[verts[[new]]], y[verts[[new]]])
+    
+      for (j in nesting[[toplevel]]) {
+        prev <- rbind(x[verts[[j]]], y[verts[[j]]])    
+        if (pointInPoly(prev, newverts[,1])) {
+	  place(new, j)
+	  placed <- TRUE
+	  break
+        }
+        if (pointInPoly(newverts, prev[,1]))
+	  contains <- c(contains, j)
+      }
+    }
+    if (!placed) {
+      nesting[[toplevel]] <<- c(setdiff(nesting[[toplevel]], contains), new)
+      nesting[[new]] <<- contains
+    }
+  }
+    
+  for (i in seq_along(verts)) {
+    place(i, length(verts)+1)
+  }
+  
+  list(verts=verts, nesting=nesting[-length(nesting)], 
+       toplevel=nesting[length(nesting)])
+} 
+      
+      
+extrude3d <- function(x,y = NULL, thickness=1, smooth=FALSE, ...) {
+  xy <- xy.coords(x, y)
+  x <- xy$x
+  y <- xy$y
+  it <- triangulate(x, y, partial=FALSE)
+  nextvert <- attr(it, "nextvert")
+  n <- length(x)
+  res <- tmesh3d(rbind(c(x,x), c(y,y), c(rep(thickness,n), rep(0,n)), 1),
+                 cbind(it, it[c(1,3,2),]+n), ...)
+  i1 <- seq_len(n)
+  i2 <- nextvert
+  i3 <- i2 + n
+  i4 <- i1 + n
+  keep <- !is.na(nextvert)
+  res$ib <- rbind(i4,i3,i2,i1)[,keep]
+  if (smooth) {
+    res$ib <- res$ib + ncol(res$vb)
+    res$vb <- cbind(res$vb, res$vb)
+    i3 <- nextvert[nextvert]
+    diff <- cbind(x[i3] - x[i1],  y[i3] - y[i1])
+    len <- sqrt(apply(diff^2, 1, sum))
+    diff <- diff/len
+    
+    res$normals <- cbind( rbind(0,0,c(rep(1, n), rep(-1, n))) )
+    res$normals <- cbind(res$normals, res$normals)
+    i2 <- c(i2 + 2*n, i2 + 3*n)
+    keep <- !is.na(i2)
+    res$normals[,i2[keep]] <- rbind(rep(diff[,2], 2), -rep(diff[,1], 2), 0)[,keep]   
+  }
+  res
+}
+
+polygon3d <- function(x, y = NULL, z = NULL, fill = TRUE, plot = TRUE, 
+                      coords = 1:2, random = TRUE, ...) {
+  xyz <- xyz.coords(x,y,z)
+  if (!fill) {
+    n <- length(xyz$x)
+    nas <- with(xyz, c(which(is.na(x) | is.na(y) | is.na(z)), n + 1L))
+    prev <- 0L
+    loop <- integer()
+    for (i in seq_along(nas)) {
+      loop <- c(loop, if (i > 1) NA, (prev + 1L):(nas[i] - 1L), prev + 1L)
+      prev <- nas[i]
+    }
+    res <- cbind(xyz$x[loop], xyz$y[loop], xyz$z[loop])
+    if (plot)
+      lines3d(res, ...)
+    else
+      res
+  } else {
+    cnames <- c("x", "y", "z")
+    x <- xyz[[cnames[coords[1]]]]
+    y <- xyz[[cnames[coords[2]]]]
+    tri <- triangulate(x, y, random = random)
+    shape <- tmesh3d(rbind(xyz$x, xyz$y, xyz$z, 1), indices = tri)
+    if (plot)
+      shade3d(shape, ...)
+    else
+      shape
+  }
+}  
diff --git a/R/turn3d.R b/R/turn3d.R
new file mode 100644
index 0000000..e9297ed
--- /dev/null
+++ b/R/turn3d.R
@@ -0,0 +1,61 @@
+
+turn3d <- function(x, y = NULL, n = 12, smooth = FALSE, ...) {
+  xy <- xy.coords(x, y)
+  x <- xy$x
+  y <- zapsmall(xy$y)
+  stopifnot(all(y >= 0))
+  len <- length(x)
+  inds <- seq_len(len)
+  
+  if (smooth) {
+    nx <- -diff(y)
+    nx <- c(nx, 0) + c(0, nx)
+    ny <- diff(x)
+    ny <- c(ny, 0) + c(0, ny)
+    nlen <- sqrt(nx^2 + ny^2)
+    nlen[nlen == 0] <- 1
+    nx <- nx/nlen
+    ny <- ny/nlen
+    normals <- matrix(nrow=4, ncol=0)
+  }
+  zero <- y == 0
+  vb <- matrix(nrow=4, ncol=0)
+  ib <- matrix(nrow=4, ncol=0)
+  it <- matrix(nrow=3, ncol=0)
+  
+  theta <- seq(0, 2*pi, len = n + 1)[-(n + 1)]
+  for (i in inds) {
+    vb <- cbind(vb, rbind(x[i], sin(theta)*y[i], cos(theta)*y[i], 1))
+    if (smooth)
+      normals <- cbind(normals, rbind(nx[i], sin(theta)*ny[i], cos(theta)*ny[i], 1))
+    if (i > 1) {
+      if (zero[i] && zero[i-1]) { # do nothing 
+      } else if (!zero[i] && zero[i-1]) { # draw triangles
+        prev <- ncol(vb) - n - 0:(n-1)
+        curr <- ncol(vb) - 0:(n-1)
+        curr2 <- curr + 1
+        curr2[1] <- curr2[1] - n
+        
+        it <- cbind(it, rbind(prev, curr, curr2))
+      } else if (zero[i] && !zero[i-1]) { # other triangles
+        prev <- ncol(vb) - n - 0:(n-1)
+        curr <- ncol(vb) - 0:(n-1)
+        prev2 <- prev + 1
+        prev2[1] <- prev2[1] - n
+        it <- cbind(it, rbind(prev, curr, prev2))
+      } else { # quads
+        prev <- ncol(vb) - n - 0:(n-1)
+        prev2 <- prev + 1
+        prev2[1] <- prev2[1] - n
+        curr <- ncol(vb) - 0:(n-1)
+        curr2 <- curr + 1
+        curr2[1] <- curr2[1] - n
+        ib <- cbind(ib, rbind(prev, curr, curr2, prev2))
+      }
+    }
+  }
+  
+  result <- tmesh3d(vb, it, normals=if(smooth) t(normals), ...)
+  if (length(ib)) result$ib <- ib
+  result
+}
diff --git a/R/webGL.R b/R/webGL.R
new file mode 100644
index 0000000..bd95f1f
--- /dev/null
+++ b/R/webGL.R
@@ -0,0 +1,63 @@
+subst <- function(strings, ..., digits=7) {
+  substitutions <- list(...)
+  names <- names(substitutions)
+  if (is.null(names)) names <- rep("", length(substitutions))
+  for (i in seq_along(names)) {
+    if ((n <- names[i]) == "")
+      n <- as.character(sys.call()[[i+2]])
+    value <- substitutions[[i]]
+    if (is.numeric(value))
+      value <- formatC(value, digits=digits, width=1)
+    strings <- gsub(paste("%", n, "%", sep=""), value, strings)
+  }
+  strings
+}
+
+rglwidgetCheck <- function() {
+  if (!requireNamespace("rglwidget", quietly = TRUE))
+    stop("This function requires the rglwidget package to be installed.")
+}
+
+convertBBox <- function(id) {
+  verts <- rgl.attrib(id, "vertices")
+  text <- rgl.attrib(id, "text")
+  if (!length(text))
+    text <- rep("", NROW(verts))
+  mat <- rgl.getmaterial(id = id)
+  if (length(mat$color) > 1)
+    mat$color <- mat$color[2] # We ignore the "box" colour
+
+  if(any(missing <- text == ""))
+    text[missing] <- apply(verts[missing,], 1, function(row) format(row[!is.na(row)]))
+
+  res <- integer(0)
+  if (any(inds <- is.na(verts[,2]) & is.na(verts[,3])))
+    res <- c(res, do.call(axis3d, c(list(edge = "x", at = verts[inds, 1], labels = text[inds]), mat)))
+  if (any(inds <- is.na(verts[,1]) & is.na(verts[,3])))
+    res <- c(res, do.call(axis3d, c(list(edge = "y", at = verts[inds, 2], labels = text[inds]), mat)))
+  if (any(inds <- is.na(verts[,1]) & is.na(verts[,2])))
+    res <- c(res, do.call(axis3d, c(list(edge = "z", at = verts[inds, 3], labels = text[inds]), mat)))
+  res <- c(res, do.call(box3d, mat))
+  res
+}
+
+rootSubscene <- function() {
+  id <- currentSubscene3d()
+  repeat {
+    info <- subsceneInfo(id)
+    if (is.null(info$parent)) return(id)
+    else id <- info$parent
+  }
+}
+
+writeWebGL <- function(dir="webGL", filename=file.path(dir, "index.html"),
+                       template = system.file(file.path("WebGL", "template.html"), package = "rgl"),
+                       prefix = "",
+                       snapshot = TRUE, commonParts = TRUE, reuse = NULL,
+		       font="Arial",
+                       width = NULL, height = NULL) {
+
+  rglwidgetCheck()
+  rglwidget::.writeWebGL(dir, filename, template, prefix, snapshot, commonParts,
+  		         reuse, font, width, height)
+}
diff --git a/R/webGLcontrols.R b/R/webGLcontrols.R
new file mode 100644
index 0000000..404e565
--- /dev/null
+++ b/R/webGLcontrols.R
@@ -0,0 +1,152 @@
+
+# This displays an HTML5 input widget to show a subset of objects.  It assigns a random id
+# and returns that invisibly.
+
+subsetSlider <- function(subsets, labels = names(subsets),
+                         fullset = Reduce(union, subsets), 
+                         subscenes = currentSubscene3d(), prefixes = "", 
+                         accumulate = FALSE, ...) {
+  propertySlider(subsetSetter(subsets, fullset = fullset,
+                              subscenes = subscenes, prefixes = prefixes,
+                              accumulate = accumulate),
+                 labels = labels, ...)
+}
+
+subsetSetter <- function(subsets, subscenes = currentSubscene3d(), prefixes = "",  
+			 fullset = Reduce(union, subsets),
+			 accumulate = FALSE) {
+  rglwidgetCheck()
+  rglwidget::.subsetSetter(subsets, subscenes, prefixes, fullset, accumulate)
+}
+
+toggleButton <- function(subset, subscenes = currentSubscene3d(), prefixes = "", 
+			 label = deparse(substitute(subset)), 
+			 id = paste0(basename(tempfile("input"))), name = id) {
+  rglwidgetCheck()
+  nsubs <- max(length(subscenes), length(prefixes))
+  subscenes <- rep(subscenes, length.out = nsubs)
+  prefixes <- rep(prefixes, length.out = nsubs)
+  result <- subst(
+'<button type="button" id="%id%" name="%name%" onclick = "(function(){
+  var subset = [%subset%], i;',
+    name, id, subset = paste(subset, collapse=","))
+  for (i in seq_len(nsubs)) 
+    result <- c(result, subst(
+'  if (%prefix%rgl.inSubscene(subset[0], %subscene%)) {
+    for (i=0; i<subset.length; i++)
+      %prefix%rgl.delFromSubscene(subset[i], %subscene%);
+  } else {
+    for (i=0; i<subset.length; i++)
+      %prefix%rgl.addToSubscene(subset[i], %subscene%);
+  }', prefix = prefixes[i], subscene = subscenes[i]))
+  prefixes <- unique(prefixes)
+  for (i in seq_along(prefixes))
+    result <- c(result, subst(
+'  %prefix%rgl.drawScene();', prefix = prefixes[i]))
+  result <- c(result, subst(
+'})()">%label%</button>', label)) 
+  cat(result, sep = "\n")
+  invisible(id)
+}
+
+clipplaneSlider <- function(a=NULL, b=NULL, c=NULL, d=NULL, 
+			    plane = 1, clipplaneids, prefixes = "", 
+			    labels = signif(values[,1],3), 
+			      ...) {
+  values <- cbind(a = a, b = b, c = c, d = d)
+  col <- which(colnames(values) == letters[1:4]) - 1
+  propertySlider(values = values, entries = 4*(plane-1) + col,
+  	         properties = "vClipplane", objids = clipplaneids, 
+  	         prefixes = prefixes, labels = labels, ...)
+}
+
+propertySlider <- function(setter = propertySetter,
+                           minS = NULL, maxS = NULL, step = 1, init = minS, 
+                           labels, 
+                           id = basename(tempfile("input")), name = id,
+			   outputid = paste0(id, "text"),
+			   index = NULL,
+                           ...)  {
+  rglwidgetCheck()
+  rglwidget::.propertySlider(setter, minS, maxS, step, init, labels, id, name, outputid,
+  			     index, ...)
+}
+
+propertySetter <- function(values = NULL, entries, properties, objids, prefixes = "",
+                           param = seq_len(NROW(values)), interp = TRUE,
+			   digits = 7)  {
+  rglwidgetCheck()
+  rglwidget::.propertySetter(values, entries, properties, objids, prefixes,
+  			     param, interp, digits)
+}
+
+vertexSetter <- function(values = NULL, vertices = 1, attributes, objid, prefix = "",
+			 param = seq_len(NROW(values)), interp = TRUE,
+			 digits = 7)  {
+  rglwidgetCheck()
+  rglwidget::.vertexSetter(values, vertices, attributes, objid, prefix, param, interp,
+  			   digits)
+}
+
+
+par3dinterpSetter <- function(fn, from, to, steps, subscene = NULL,
+			      omitConstant = TRUE, rename = character(), ...) {
+  rglwidgetCheck()
+  rglwidget::.par3dinterpSetter(fn, from, to, steps, subscene,
+  			        omitConstant, rename, ...)
+}
+
+matrixSetter <- function(fns, from, to, steps, subscene = currentSubscene3d(), matrix = "userMatrix",
+			omitConstant = TRUE, prefix = "", ...) {
+  n <- length(fns)
+  from <- rep(from, length.out = n)
+  to <- rep(to, length.out = n)
+  steps <- rep(steps, length.out = n)
+  settername <- basename(tempfile("fn", ""))
+  propname <- paste0("userMatrix", settername) # Needs to match "^userMatrix" regexp
+  param <- numeric()
+  prefixes <- character()
+  result <- subst(
+'%prefix%rgl.%settername% = function(value, index){
+     var fns = new Array();', prefix, settername)
+  product <- ''
+  for (i in seq_len(n)) {
+    setter <- par3dinterpSetter(fns[[i]], from[i], to[i], steps[i],
+    			        omitConstant = TRUE, subscene = i-1, prefixes = prefix,
+    			        rename = c(userMatrix = propname), ...)
+    result <- c(result, subst(
+'     fns[%i%] = ', i=i-1), setter)
+    param <- c(param, attr(setter, "param"))
+  }
+  result <- c(result, 
+'   fns[index](value);
+   var newmatrix = new CanvasMatrix4();',
+    paste0(subst(
+'   newmatrix.multLeft(%prefix%rgl.%propname%[', prefix, propname), 0:(n-1), ']);'),
+    subst(
+'   %prefix%rgl.%matrix%[%subscene%].load(newmatrix);
+ }
+ %prefix%rgl.%propname% = new Array();', prefix, subscene, propname, matrix),
+    paste0(subst(
+' %prefix%rgl.%propname%[', prefix, propname), 0:(n-1), '] = new CanvasMatrix4();'))
+  structure(paste(result, collapse="\n"),
+  	    param = sort(unique(param)),
+  	    prefixes = prefix,
+  	    name = subst('%prefix%rgl.%settername%', prefix, settername),
+  	    class = c("matrixSetter", "indexedSetter", "propertySetter"))
+}
+
+print.indexedSetter <- function(x, inScript = FALSE, ...) {
+  if (!inScript) cat("<script>\n")
+  cat(x)
+  if (!inScript) cat("\n</script>")
+}
+
+ageSetter <- function(births, ages, colors = NULL, alpha = NULL, 
+		      radii = NULL, vertices = NULL, normals = NULL, 
+		      origins = NULL, texcoords = NULL, objids, prefixes = "",
+		      digits = 7, param = seq(floor(min(births)), ceiling(max(births))))  {
+  rglwidgetCheck()
+  rglwidget::.ageSetter(births, ages, colors, alpha, radii, vertices, normals, 
+  		      origins, texcoords, objids, prefixes, digits, param)
+}
diff --git a/R/zzz.R b/R/zzz.R
new file mode 100644
index 0000000..dbe71b9
--- /dev/null
+++ b/R/zzz.R
@@ -0,0 +1,91 @@
+##
+## R source file
+## This file is part of rgl
+##
+## $Id: zzz.R 1415 2015-11-26 20:31:02Z murdoch $
+##
+
+##
+## ===[ SECTION: package entry/exit point ]===================================
+##
+
+##
+## entry-point
+##
+##
+
+.onLoad <- function(lib, pkg)
+{
+  # OS-specific 
+  initValue <- 0  
+  
+  dynlib <- "rgl"
+  
+  onlyNULL <- rgl.useNULL()
+  
+  if ( .Platform$OS.type == "unix" ) {
+    unixos <- system("uname",intern=TRUE)
+    if ( unixos == "Darwin" ) {
+          
+      # For MacOS X we have to remove /usr/X11R6/lib from the DYLD_LIBRARY_PATH
+      # because it would override Apple's OpenGL framework
+      Sys.setenv("DYLD_LIBRARY_PATH"=gsub("/usr/X11R6/lib","",Sys.getenv("DYLD_LIBRARY_PATH")))
+    }
+  } 
+  dll <- library.dynam(dynlib, pkg, lib)
+
+  routines <- getDLLRegisteredRoutines(dynlib, addNames = FALSE)
+  ns <- asNamespace(pkg)
+  for(i in 1:4)
+    lapply(routines[[i]],
+      function(sym) assign(sym$name, sym, envir = ns))
+      
+  if ( .Platform$OS.type == "windows" && !onlyNULL) {
+    frame <- getWindowsHandle("Frame")    
+    ## getWindowsHandle was numeric pre-2.6.0 
+    if ( !is.null(frame) ) initValue <- getWindowsHandle("Console")
+  } 
+ 
+  if (onlyNULL) {
+    rglFonts(serif = rep("serif", 4), sans = rep("sans", 4), mono = rep("mono", 4), symbol = rep("symbol", 4))
+  } else if ( .Platform$OS.type == "windows" ) {
+    rglFonts(serif = rglFont(c("times.ttf", "timesbd.ttf", "timesi.ttf", "timesbi.ttf")),
+             sans = rglFont(c("arial.ttf", "arialbd.ttf", "ariali.ttf", "arialbi.ttf")),
+             mono = rglFont(c("cour.ttf", "courbd.ttf", "couri.ttf", "courbi.ttf")),
+             symbol = rglFont(rep("symbol.ttf", 4)))
+  } else {
+    rglFonts(serif = rep(system.file("fonts/FreeSerif.ttf", package="rgl"), 4),
+             sans  = rep(system.file("fonts/FreeSans.ttf", package="rgl"), 4),
+             mono  = rep(system.file("fonts/FreeMono.ttf", package="rgl"), 4),
+             symbol = rep(system.file("fonts/FreeSerif.ttf", package="rgl"), 4))
+  }
+  
+  .rglEnv$subsceneList <- NULL
+	 
+  ret <- rgl.init(initValue, onlyNULL)
+  
+  if (!ret) {
+    warning("'rgl_init' failed, running with rgl.useNULL = TRUE", call. = FALSE)
+    options(rgl.useNULL = TRUE)
+    rgl.quit()
+    rgl.init(initValue, TRUE)	
+  }
+  
+}
+
+rgl.init <- function(initValue = 0, onlyNULL = FALSE) .Call( rgl_init, 
+    initValue, onlyNULL, environment(rgl.init) )
+
+##
+## exit-point
+##
+##
+
+.onUnload <- function(libpath)
+{ 
+  # shutdown
+  
+  ret <- .C( rgl_quit, success=FALSE )
+  
+}
+
diff --git a/README b/README
new file mode 100644
index 0000000..ac28405
--- /dev/null
+++ b/README
@@ -0,0 +1,172 @@
+RGL - 3D visualization device system for R using OpenGL
+=======================================================
+
+INTRODUCTION
+------------
+The RGL package is a visualization device system for R, using 
+OpenGL as the rendering backend. An rgl device at its core 
+is a real-time 3D engine written in C++. It provides an 
+interactive viewpoint navigation facility (mouse + wheel support)
+and an R programming interface.
+
+
+LICENSE
+-------
+The software is released under the GNU Public License. 
+See "COPYING" textfile for details.
+
+
+FEATURES
+--------
+- portable R Plug-in using OpenGL on MacOSX, Win32 and X11
+- R programming interface 
+- interactive viewpoint navigation
+- automatic data focus
+- geometry primitives: 
+  points, lines, triangles, quads, texts, point sprites
+- high-level geometry:
+  surface, spheres
+- up to 8 light sources
+- alpha-blending (transparency)
+- side-dependant fill-mode rendering (dots,wired and filled)
+- texture-mapping with mipmapping and environment mapping support
+- environmental effects:
+  fogging, background sphere
+- bounding box with axis ticks marks
+- undo operation:
+  shapes and light-sources are managed on type stacks,
+  where the top-most objects can be pop'ed, or any item specified by
+  an identifier can be removed
+
+
+PLATFORMS
+---------
+Mac OS X
+Windows 2000/XP/Vista
+Unix-derivatives
+
+
+BUILD TOOLS
+-----------
+R recommended tools (gcc toolchain)
+
+
+REQUIREMENTS
+------------
+Windowing System (osx/carbon, unix/x11 or win32)
+OpenGL Library 
+OpenGL Utility Library (GLU)
+
+Installation on Debian:
+-----------------------
+aptitude install libgl1-mesa-dev libglu1-mesa-dev
+
+
+OPTIONS
+-------
+libpng library version 1.0.4 or newer (pixmap import/export support)
+freetype library for resizable anti-aliased fonts
+
+
+BUILDING/INSTALLING FROM SOURCE PACKAGE
+---------------------------------------
+The R build tool is the primary tool to build the RGL package.
+
+
+BUILDING ON MICROSOFT WINDOWS
+-----------------------------
+
+Libpng support:
+
+Make sure bitmap dll has been built as described in the 
+R Build Instructions for Windows.
+
+These two files are needed:
+
+%R_HOME%\src\gnuwin32\bitmap\libpng\libpng.a
+%R_HOME%\bin\Rzlib.dll (or %R_HOME%\src\extra\zlib\libz.a, in older R versions)
+
+Freetype support:
+
+You need to obtain a Windows build of the Freetype library, version 2.3.5 or better.
+A version is available at http://gnuwin32.sourceforge.net/packages/freetype.htm.
+Set the environment variable LIB_FREETYPE to give the full path to the
+install directory.
+
+BUILDING ON UNIX-STYLE OS (MacOS X, Linux, FreeBSD, ... ) 
+---------------------------------------------------------
+
+The build is controlled by an autoconf configure script.
+You provide the options through the R CMD build/INSTALL command
+
+  e.g. 
+    $ R CMD INSTALL --configure-args="<configure args...>" rgl
+
+
+  COMMON UNIX-STYLE OS OPTIONS
+  ----------------------------
+
+  --with-gl-includes=<path>
+    GL C header files include path
+
+  --with-gl-libraries=<path>
+    GL library linkage path
+
+  --with-gl-prefix=<libprefix>
+    GL library prefix (e.g. Mesa)
+  
+  --disable-libpng
+    disable libpng support
+
+  --with-libpng-prefix=<install location>
+    force LibPNG library install prefix (e.g. /usr/local)
+
+  --disable-libpng-config
+    explicitly disable libpng-config
+  
+  --disable-libpng-dynamic
+    use static libpng library
+    
+You may find that your distro doesn't have all necessary development
+libraries installed:  read the error messages for hints!  This line
+has been reported to be sufficient on FC 5 or 6:
+
+ yum install mesa-libGL-devel mesa-libGLU-devel libpng-devel
+
+
+
+
+  X11 WINDOWING SYSTEM OPTIONS
+  ----------------------------
+
+  --x-includes=<path>
+    X11 C header files include path
+
+  --x-libraries=<path>
+    X11 library linkage path
+
+
+FIRST DEMOS: LOADING LIBRARY AND RUNNING DEMONSTRATIONS
+-------------------------------------------------------
+
+> library(rgl)
+> demo(rgl)
+
+
+CREDITS
+-------
+Daniel Adler <dadler at uni-goettingen.de>
+Duncan Murdoch <murdoch at stats.uwo.ca>
+Oleg Nenadic <onenadi at uni-goettingen.de>
+Simon Urbanek <simon.urbanek at math.uni-augsburg.de>
+Ming Chen <mchen34 at uwo.ca>
+Albrecht Gebhardt <albrecht.gebhardt at uni-klu.ac.at>
+Ben Bolker <bolker at zoo.ufl.edu>
+Gabor Csardi <csardi at rmki.kfki.hu>
+Adam Strzelecki <ono at java.pl>
+Alexander Senger <senger at physik.hu-berlin.de>
+
+WEBSITE
+-------
+http://rgl.neoscientists.org
+
diff --git a/build/vignette.rds b/build/vignette.rds
new file mode 100644
index 0000000..052b99a
Binary files /dev/null and b/build/vignette.rds differ
diff --git a/cleanup b/cleanup
new file mode 100755
index 0000000..d79b3c3
--- /dev/null
+++ b/cleanup
@@ -0,0 +1,3 @@
+#! /bin/sh
+rm -f config.* src/Makevars src/Makedeps src/*.o src/osx/*.o src/*.so src/*.dll 
+rm -rf src/AGL autom4te.cache
diff --git a/configure b/configure
new file mode 100755
index 0000000..4ce8e16
--- /dev/null
+++ b/configure
@@ -0,0 +1,5770 @@
+#! /bin/sh
+# Guess values for system-dependent variables and create Makefiles.
+# Generated by GNU Autoconf 2.69.
+#
+#
+# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
+#
+#
+# This configure script is free software; the Free Software Foundation
+# gives unlimited permission to copy, distribute and modify it.
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+# Use a proper internal environment variable to ensure we don't fall
+  # into an infinite loop, continuously re-executing ourselves.
+  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
+    _as_can_reexec=no; export _as_can_reexec;
+    # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+as_fn_exit 255
+  fi
+  # We don't want this to propagate to other subprocesses.
+          { _as_can_reexec=; unset _as_can_reexec;}
+if test "x$CONFIG_SHELL" = x; then
+  as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '\${1+\"\$@\"}'='\"\$@\"'
+  setopt NO_GLOB_SUBST
+else
+  case \`(set -o) 2>/dev/null\` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+"
+  as_required="as_fn_return () { (exit \$1); }
+as_fn_success () { as_fn_return 0; }
+as_fn_failure () { as_fn_return 1; }
+as_fn_ret_success () { return 0; }
+as_fn_ret_failure () { return 1; }
+
+exitcode=0
+as_fn_success || { exitcode=1; echo as_fn_success failed.; }
+as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; }
+as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; }
+as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; }
+if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
+
+else
+  exitcode=1; echo positional parameters were not saved.
+fi
+test x\$exitcode = x0 || exit 1
+test -x / || exit 1"
+  as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
+  as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
+  eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
+  test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1
+test \$(( 1 + 1 )) = 2 || exit 1"
+  if (eval "$as_required") 2>/dev/null; then :
+  as_have_required=yes
+else
+  as_have_required=no
+fi
+  if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then :
+
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+as_found=false
+for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  as_found=:
+  case $as_dir in #(
+	 /*)
+	   for as_base in sh bash ksh sh5; do
+	     # Try only shells that exist, to save several forks.
+	     as_shell=$as_dir/$as_base
+	     if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+		    { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  CONFIG_SHELL=$as_shell as_have_required=yes
+		   if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then :
+  break 2
+fi
+fi
+	   done;;
+       esac
+  as_found=false
+done
+$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } &&
+	      { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then :
+  CONFIG_SHELL=$SHELL as_have_required=yes
+fi; }
+IFS=$as_save_IFS
+
+
+      if test "x$CONFIG_SHELL" != x; then :
+  export CONFIG_SHELL
+             # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+exit 255
+fi
+
+    if test x$as_have_required = xno; then :
+  $as_echo "$0: This script requires a shell more modern than all"
+  $as_echo "$0: the shells that I found on your system."
+  if test x${ZSH_VERSION+set} = xset ; then
+    $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
+    $as_echo "$0: be upgraded to zsh 4.3.4 or later."
+  else
+    $as_echo "$0: Please tell bug-autoconf at gnu.org about your system,
+$0: including any error possibly output before this
+$0: message. Then install a modern shell, or manually run
+$0: the script under such a shell if you do have one."
+  fi
+  exit 1
+fi
+fi
+fi
+SHELL=${CONFIG_SHELL-/bin/sh}
+export SHELL
+# Unset more variables known to interfere with behavior of common tools.
+CLICOLOR_FORCE= GREP_OPTIONS=
+unset CLICOLOR_FORCE GREP_OPTIONS
+
+## --------------------- ##
+## M4sh Shell Functions. ##
+## --------------------- ##
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+
+  as_lineno_1=$LINENO as_lineno_1a=$LINENO
+  as_lineno_2=$LINENO as_lineno_2a=$LINENO
+  eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" &&
+  test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || {
+  # Blame Lee E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
+    sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
+      N
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
+      t loop
+      s/-\n.*//
+    ' >$as_me.lineno &&
+  chmod +x "$as_me.lineno" ||
+    { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
+
+  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
+  # already done that, so ensure we don't try to do so again and fall
+  # in an infinite loop.  This has already happened in practice.
+  _as_can_reexec=no; export _as_can_reexec
+  # Don't try to exec as it changes $[0], causing all sort of problems
+  # (the dirname of $[0] is not the place where we might find the
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
+  # Exit status is that of the last command.
+  exit
+}
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+test -n "$DJDIR" || exec 7<&0 </dev/null
+exec 6>&1
+
+# Name of the host.
+# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status,
+# so uname gets run too.
+ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
+
+#
+# Initializations.
+#
+ac_default_prefix=/usr/local
+ac_clean_files=
+ac_config_libobj_dir=.
+LIBOBJS=
+cross_compiling=no
+subdirs=
+MFLAGS=
+MAKEFLAGS=
+
+# Identity of this package.
+PACKAGE_NAME=
+PACKAGE_TARNAME=
+PACKAGE_VERSION=
+PACKAGE_STRING=
+PACKAGE_BUGREPORT=
+PACKAGE_URL=
+
+# Factoring default headers for most tests.
+ac_includes_default="\
+#include <stdio.h>
+#ifdef HAVE_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_STAT_H
+# include <sys/stat.h>
+#endif
+#ifdef STDC_HEADERS
+# include <stdlib.h>
+# include <stddef.h>
+#else
+# ifdef HAVE_STDLIB_H
+#  include <stdlib.h>
+# endif
+#endif
+#ifdef HAVE_STRING_H
+# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
+#  include <memory.h>
+# endif
+# include <string.h>
+#endif
+#ifdef HAVE_STRINGS_H
+# include <strings.h>
+#endif
+#ifdef HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+#ifdef HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#ifdef HAVE_UNISTD_H
+# include <unistd.h>
+#endif"
+
+ac_subst_vars='LTLIBOBJS
+LIBOBJS
+CXXFLAGS
+HAVE_FREETYPE_CONFIG
+XMKMF
+EGREP
+GREP
+HAVE_LIBPNG_CONFIG
+F77_VISIBILITY
+C_VISIBILITY
+CPP
+OBJEXT
+EXEEXT
+ac_ct_CC
+CPPFLAGS
+LDFLAGS
+CFLAGS
+CC
+target_alias
+host_alias
+build_alias
+LIBS
+ECHO_T
+ECHO_N
+ECHO_C
+DEFS
+mandir
+localedir
+libdir
+psdir
+pdfdir
+dvidir
+htmldir
+infodir
+docdir
+oldincludedir
+includedir
+localstatedir
+sharedstatedir
+sysconfdir
+datadir
+datarootdir
+libexecdir
+sbindir
+bindir
+program_transform_name
+prefix
+exec_prefix
+PACKAGE_URL
+PACKAGE_BUGREPORT
+PACKAGE_STRING
+PACKAGE_VERSION
+PACKAGE_TARNAME
+PACKAGE_NAME
+PATH_SEPARATOR
+SHELL'
+ac_subst_files=''
+ac_user_opts='
+enable_option_checking
+enable_libpng
+enable_libpng_config
+enable_libpng_dynamic
+with_x
+with_gl_includes
+with_gl_libs
+with_gl_libname
+with_glu_libname
+enable_ftgl
+'
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP
+XMKMF'
+
+
+# Initialize some variables set by options.
+ac_init_help=
+ac_init_version=false
+ac_unrecognized_opts=
+ac_unrecognized_sep=
+# The variables have the same names as the options, with
+# dashes changed to underlines.
+cache_file=/dev/null
+exec_prefix=NONE
+no_create=
+no_recursion=
+prefix=NONE
+program_prefix=NONE
+program_suffix=NONE
+program_transform_name=s,x,x,
+silent=
+site=
+srcdir=
+verbose=
+x_includes=NONE
+x_libraries=NONE
+
+# Installation directory options.
+# These are left unexpanded so users can "make install exec_prefix=/foo"
+# and all the variables that are supposed to be based on exec_prefix
+# by default will actually change.
+# Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
+bindir='${exec_prefix}/bin'
+sbindir='${exec_prefix}/sbin'
+libexecdir='${exec_prefix}/libexec'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
+sysconfdir='${prefix}/etc'
+sharedstatedir='${prefix}/com'
+localstatedir='${prefix}/var'
+includedir='${prefix}/include'
+oldincludedir='/usr/include'
+docdir='${datarootdir}/doc/${PACKAGE}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
+
+ac_prev=
+ac_dashdash=
+for ac_option
+do
+  # If the previous option needs an argument, assign it.
+  if test -n "$ac_prev"; then
+    eval $ac_prev=\$ac_option
+    ac_prev=
+    continue
+  fi
+
+  case $ac_option in
+  *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *=)   ac_optarg= ;;
+  *)    ac_optarg=yes ;;
+  esac
+
+  # Accept the important Cygnus configure options, so we can diagnose typos.
+
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
+
+  -bindir | --bindir | --bindi | --bind | --bin | --bi)
+    ac_prev=bindir ;;
+  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
+    bindir=$ac_optarg ;;
+
+  -build | --build | --buil | --bui | --bu)
+    ac_prev=build_alias ;;
+  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
+    build_alias=$ac_optarg ;;
+
+  -cache-file | --cache-file | --cache-fil | --cache-fi \
+  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
+    ac_prev=cache_file ;;
+  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
+  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
+    cache_file=$ac_optarg ;;
+
+  --config-cache | -C)
+    cache_file=config.cache ;;
+
+  -datadir | --datadir | --datadi | --datad)
+    ac_prev=datadir ;;
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
+    datadir=$ac_optarg ;;
+
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
+  -disable-* | --disable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
+
+  -enable-* | --enable-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid feature name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"enable_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval enable_$ac_useropt=\$ac_optarg ;;
+
+  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
+  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
+  | --exec | --exe | --ex)
+    ac_prev=exec_prefix ;;
+  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
+  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
+  | --exec=* | --exe=* | --ex=*)
+    exec_prefix=$ac_optarg ;;
+
+  -gas | --gas | --ga | --g)
+    # Obsolete; use --with-gas.
+    with_gas=yes ;;
+
+  -help | --help | --hel | --he | -h)
+    ac_init_help=long ;;
+  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
+    ac_init_help=recursive ;;
+  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
+    ac_init_help=short ;;
+
+  -host | --host | --hos | --ho)
+    ac_prev=host_alias ;;
+  -host=* | --host=* | --hos=* | --ho=*)
+    host_alias=$ac_optarg ;;
+
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
+  -includedir | --includedir | --includedi | --included | --include \
+  | --includ | --inclu | --incl | --inc)
+    ac_prev=includedir ;;
+  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
+  | --includ=* | --inclu=* | --incl=* | --inc=*)
+    includedir=$ac_optarg ;;
+
+  -infodir | --infodir | --infodi | --infod | --info | --inf)
+    ac_prev=infodir ;;
+  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
+    infodir=$ac_optarg ;;
+
+  -libdir | --libdir | --libdi | --libd)
+    ac_prev=libdir ;;
+  -libdir=* | --libdir=* | --libdi=* | --libd=*)
+    libdir=$ac_optarg ;;
+
+  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
+  | --libexe | --libex | --libe)
+    ac_prev=libexecdir ;;
+  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
+  | --libexe=* | --libex=* | --libe=*)
+    libexecdir=$ac_optarg ;;
+
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
+  -localstatedir | --localstatedir | --localstatedi | --localstated \
+  | --localstate | --localstat | --localsta | --localst | --locals)
+    ac_prev=localstatedir ;;
+  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
+    localstatedir=$ac_optarg ;;
+
+  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
+    ac_prev=mandir ;;
+  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
+    mandir=$ac_optarg ;;
+
+  -nfp | --nfp | --nf)
+    # Obsolete; use --without-fp.
+    with_fp=no ;;
+
+  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
+  | --no-cr | --no-c | -n)
+    no_create=yes ;;
+
+  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
+  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
+    no_recursion=yes ;;
+
+  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
+  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
+  | --oldin | --oldi | --old | --ol | --o)
+    ac_prev=oldincludedir ;;
+  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
+  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
+  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
+    oldincludedir=$ac_optarg ;;
+
+  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
+    ac_prev=prefix ;;
+  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
+    prefix=$ac_optarg ;;
+
+  -program-prefix | --program-prefix | --program-prefi | --program-pref \
+  | --program-pre | --program-pr | --program-p)
+    ac_prev=program_prefix ;;
+  -program-prefix=* | --program-prefix=* | --program-prefi=* \
+  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
+    program_prefix=$ac_optarg ;;
+
+  -program-suffix | --program-suffix | --program-suffi | --program-suff \
+  | --program-suf | --program-su | --program-s)
+    ac_prev=program_suffix ;;
+  -program-suffix=* | --program-suffix=* | --program-suffi=* \
+  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
+    program_suffix=$ac_optarg ;;
+
+  -program-transform-name | --program-transform-name \
+  | --program-transform-nam | --program-transform-na \
+  | --program-transform-n | --program-transform- \
+  | --program-transform | --program-transfor \
+  | --program-transfo | --program-transf \
+  | --program-trans | --program-tran \
+  | --progr-tra | --program-tr | --program-t)
+    ac_prev=program_transform_name ;;
+  -program-transform-name=* | --program-transform-name=* \
+  | --program-transform-nam=* | --program-transform-na=* \
+  | --program-transform-n=* | --program-transform-=* \
+  | --program-transform=* | --program-transfor=* \
+  | --program-transfo=* | --program-transf=* \
+  | --program-trans=* | --program-tran=* \
+  | --progr-tra=* | --program-tr=* | --program-t=*)
+    program_transform_name=$ac_optarg ;;
+
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil)
+    silent=yes ;;
+
+  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
+    ac_prev=sbindir ;;
+  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
+  | --sbi=* | --sb=*)
+    sbindir=$ac_optarg ;;
+
+  -sharedstatedir | --sharedstatedir | --sharedstatedi \
+  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
+  | --sharedst | --shareds | --shared | --share | --shar \
+  | --sha | --sh)
+    ac_prev=sharedstatedir ;;
+  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
+  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
+  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
+  | --sha=* | --sh=*)
+    sharedstatedir=$ac_optarg ;;
+
+  -site | --site | --sit)
+    ac_prev=site ;;
+  -site=* | --site=* | --sit=*)
+    site=$ac_optarg ;;
+
+  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
+    ac_prev=srcdir ;;
+  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
+    srcdir=$ac_optarg ;;
+
+  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
+  | --syscon | --sysco | --sysc | --sys | --sy)
+    ac_prev=sysconfdir ;;
+  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
+  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
+    sysconfdir=$ac_optarg ;;
+
+  -target | --target | --targe | --targ | --tar | --ta | --t)
+    ac_prev=target_alias ;;
+  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
+    target_alias=$ac_optarg ;;
+
+  -v | -verbose | --verbose | --verbos | --verbo | --verb)
+    verbose=yes ;;
+
+  -version | --version | --versio | --versi | --vers | -V)
+    ac_init_version=: ;;
+
+  -with-* | --with-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=\$ac_optarg ;;
+
+  -without-* | --without-*)
+    ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'`
+    # Reject names that are not valid shell variable names.
+    expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null &&
+      as_fn_error $? "invalid package name: $ac_useropt"
+    ac_useropt_orig=$ac_useropt
+    ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'`
+    case $ac_user_opts in
+      *"
+"with_$ac_useropt"
+"*) ;;
+      *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig"
+	 ac_unrecognized_sep=', ';;
+    esac
+    eval with_$ac_useropt=no ;;
+
+  --x)
+    # Obsolete; use --with-x.
+    with_x=yes ;;
+
+  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
+  | --x-incl | --x-inc | --x-in | --x-i)
+    ac_prev=x_includes ;;
+  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
+  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
+    x_includes=$ac_optarg ;;
+
+  -x-libraries | --x-libraries | --x-librarie | --x-librari \
+  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
+    ac_prev=x_libraries ;;
+  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
+  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
+    x_libraries=$ac_optarg ;;
+
+  -*) as_fn_error $? "unrecognized option: \`$ac_option'
+Try \`$0 --help' for more information"
+    ;;
+
+  *=*)
+    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
+    # Reject names that are not valid shell variable names.
+    case $ac_envvar in #(
+      '' | [0-9]* | *[!_$as_cr_alnum]* )
+      as_fn_error $? "invalid variable name: \`$ac_envvar'" ;;
+    esac
+    eval $ac_envvar=\$ac_optarg
+    export $ac_envvar ;;
+
+  *)
+    # FIXME: should be removed in autoconf 3.0.
+    $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
+    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
+      $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
+    ;;
+
+  esac
+done
+
+if test -n "$ac_prev"; then
+  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
+  as_fn_error $? "missing argument to $ac_option"
+fi
+
+if test -n "$ac_unrecognized_opts"; then
+  case $enable_option_checking in
+    no) ;;
+    fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;;
+    *)     $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;;
+  esac
+fi
+
+# Check all directory arguments for consistency.
+for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
+		datadir sysconfdir sharedstatedir localstatedir includedir \
+		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+		libdir localedir mandir
+do
+  eval ac_val=\$$ac_var
+  # Remove trailing slashes.
+  case $ac_val in
+    */ )
+      ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'`
+      eval $ac_var=\$ac_val;;
+  esac
+  # Be sure to have absolute directory names.
+  case $ac_val in
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
+  esac
+  as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val"
+done
+
+# There might be people who depend on the old broken behavior: `$host'
+# used to hold the argument of --host etc.
+# FIXME: To remove some day.
+build=$build_alias
+host=$host_alias
+target=$target_alias
+
+# FIXME: To remove some day.
+if test "x$host_alias" != x; then
+  if test "x$build_alias" = x; then
+    cross_compiling=maybe
+  elif test "x$build_alias" != "x$host_alias"; then
+    cross_compiling=yes
+  fi
+fi
+
+ac_tool_prefix=
+test -n "$host_alias" && ac_tool_prefix=$host_alias-
+
+test "$silent" = yes && exec 6>/dev/null
+
+
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  as_fn_error $? "working directory cannot be determined"
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  as_fn_error $? "pwd does not report name of working directory"
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
+  ac_srcdir_defaulted=yes
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$as_myself" ||
+$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_myself" : 'X\(//\)[^/]' \| \
+	 X"$as_myself" : 'X\(//\)$' \| \
+	 X"$as_myself" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_myself" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  srcdir=$ac_confdir
+  if test ! -r "$srcdir/$ac_unique_file"; then
+    srcdir=..
+  fi
+else
+  ac_srcdir_defaulted=no
+fi
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir"
+fi
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+	cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg"
+	pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
+
+#
+# Report the --help message.
+#
+if test "$ac_init_help" = "long"; then
+  # Omit some internal or obsolete options to make the list less imposing.
+  # This message is too long to be a string in the A/UX 3.1 sh.
+  cat <<_ACEOF
+\`configure' configures this package to adapt to many kinds of systems.
+
+Usage: $0 [OPTION]... [VAR=VALUE]...
+
+To assign environment variables (e.g., CC, CFLAGS...), specify them as
+VAR=VALUE.  See below for descriptions of some of the useful variables.
+
+Defaults for the options are specified in brackets.
+
+Configuration:
+  -h, --help              display this help and exit
+      --help=short        display options specific to this package
+      --help=recursive    display the short help of all the included packages
+  -V, --version           display version information and exit
+  -q, --quiet, --silent   do not print \`checking ...' messages
+      --cache-file=FILE   cache test results in FILE [disabled]
+  -C, --config-cache      alias for \`--cache-file=config.cache'
+  -n, --no-create         do not create output files
+      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
+
+Installation directories:
+  --prefix=PREFIX         install architecture-independent files in PREFIX
+                          [$ac_default_prefix]
+  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
+                          [PREFIX]
+
+By default, \`make install' will install all the files in
+\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
+an installation prefix other than \`$ac_default_prefix' using \`--prefix',
+for instance \`--prefix=\$HOME'.
+
+For better control, use the options below.
+
+Fine tuning of the installation directories:
+  --bindir=DIR            user executables [EPREFIX/bin]
+  --sbindir=DIR           system admin executables [EPREFIX/sbin]
+  --libexecdir=DIR        program executables [EPREFIX/libexec]
+  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
+  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
+  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --libdir=DIR            object code libraries [EPREFIX/lib]
+  --includedir=DIR        C header files [PREFIX/include]
+  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
+  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR           info documentation [DATAROOTDIR/info]
+  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR            man documentation [DATAROOTDIR/man]
+  --docdir=DIR            documentation root [DATAROOTDIR/doc/PACKAGE]
+  --htmldir=DIR           html documentation [DOCDIR]
+  --dvidir=DIR            dvi documentation [DOCDIR]
+  --pdfdir=DIR            pdf documentation [DOCDIR]
+  --psdir=DIR             ps documentation [DOCDIR]
+_ACEOF
+
+  cat <<\_ACEOF
+
+X features:
+  --x-includes=DIR    X include files are in DIR
+  --x-libraries=DIR   X library files are in DIR
+_ACEOF
+fi
+
+if test -n "$ac_init_help"; then
+
+  cat <<\_ACEOF
+
+Optional Features:
+  --disable-option-checking  ignore unrecognized --enable/--with options
+  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
+  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
+  --disable-libpng           compile without PNG image support
+
+  --disable-libpng-config    disable libpng-config test and configuration
+
+  --disable-libpng-dynamic   disable dynamic libpng linkage, force static version linkage (only with --enable-libpng-config)
+
+  --disable-ftgl             compile without FTGL font support
+
+
+Optional Packages:
+  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
+  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
+  --with-x                use the X Window System
+  --with-gl-includes=DIR  specify location of OpenGL headers
+  --with-gl-libs=DIR      specify location of OpenGL libs
+  --with-gl-libname=NAME  specify Library name (defaults to "GL")
+  --with-glu-libname=NAME specify GLU Library name (defaults to "GLU")
+
+Some influential environment variables:
+  CC          C compiler command
+  CFLAGS      C compiler flags
+  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+              nonstandard directory <lib dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
+  CPP         C preprocessor
+  XMKMF       Path to xmkmf, Makefile generator for X Window System
+
+Use these variables to override the choices made by `configure' or to help
+it to find libraries and programs with nonstandard names/locations.
+
+Report bugs to the package provider.
+_ACEOF
+ac_status=$?
+fi
+
+if test "$ac_init_help" = "recursive"; then
+  # If there are subdirs, report their specific --help.
+  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
+    test -d "$ac_dir" ||
+      { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } ||
+      continue
+    ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
+    else
+      $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
+  done
+fi
+
+test -n "$ac_init_help" && exit $ac_status
+if $ac_init_version; then
+  cat <<\_ACEOF
+configure
+generated by GNU Autoconf 2.69
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This configure script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it.
+_ACEOF
+  exit
+fi
+
+## ------------------------ ##
+## Autoconf initialization. ##
+## ------------------------ ##
+
+# ac_fn_c_try_compile LINENO
+# --------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_compile
+
+# ac_fn_c_try_cpp LINENO
+# ----------------------
+# Try to preprocess conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_cpp ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } > conftest.i && {
+	 test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+    ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_cpp
+
+# ac_fn_f77_try_compile LINENO
+# ----------------------------
+# Try to compile conftest.$ac_ext, and return whether this succeeded.
+ac_fn_f77_try_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext
+  if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_f77_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_f77_try_compile
+
+# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists, giving a warning if it cannot be compiled using
+# the include files in INCLUDES and setting the cache variable VAR
+# accordingly.
+ac_fn_c_check_header_mongrel ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if eval \${$3+:} false; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+else
+  # Is the header compilable?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5
+$as_echo_n "checking $2 usability... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_header_compiler=yes
+else
+  ac_header_compiler=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5
+$as_echo "$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5
+$as_echo_n "checking $2 presence... " >&6; }
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <$2>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  ac_header_preproc=yes
+else
+  ac_header_preproc=no
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5
+$as_echo "$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #((
+  yes:no: )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5
+$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+    ;;
+  no:yes:* )
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5
+$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     check for missing prerequisite headers?" >&5
+$as_echo "$as_me: WARNING: $2:     check for missing prerequisite headers?" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5
+$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&5
+$as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
+$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
+    ;;
+esac
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  eval "$3=\$ac_header_compiler"
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+fi
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_header_mongrel
+
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_run
+
+# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
+# -------------------------------------------------------
+# Tests whether HEADER exists and can be compiled using the include files in
+# INCLUDES, setting the cache variable VAR accordingly.
+ac_fn_c_check_header_compile ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
+$as_echo_n "checking for $2... " >&6; }
+if eval \${$3+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+$4
+#include <$2>
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  eval "$3=yes"
+else
+  eval "$3=no"
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+eval ac_res=\$$3
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+
+} # ac_fn_c_check_header_compile
+
+# ac_fn_c_try_link LINENO
+# -----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded.
+ac_fn_c_try_link ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  rm -f conftest.$ac_objext conftest$ac_exeext
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    grep -v '^ *+' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+    mv -f conftest.er1 conftest.err
+  fi
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && {
+	 test -z "$ac_c_werror_flag" ||
+	 test ! -s conftest.err
+       } && test -s conftest$ac_exeext && {
+	 test "$cross_compiling" = yes ||
+	 test -x conftest$ac_exeext
+       }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+	ac_retval=1
+fi
+  # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
+  # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
+  # interfere with the next link command; also delete a directory that is
+  # left behind by Apple's compiler.  We do this before executing the actions.
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_link
+cat >config.log <<_ACEOF
+This file contains any messages produced by compilers while
+running configure, to aid debugging if configure makes a mistake.
+
+It was created by $as_me, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  $ $0 $@
+
+_ACEOF
+exec 5>>config.log
+{
+cat <<_ASUNAME
+## --------- ##
+## Platform. ##
+## --------- ##
+
+hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
+
+/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
+/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
+/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
+
+_ASUNAME
+
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    $as_echo "PATH: $as_dir"
+  done
+IFS=$as_save_IFS
+
+} >&5
+
+cat >&5 <<_ACEOF
+
+
+## ----------- ##
+## Core tests. ##
+## ----------- ##
+
+_ACEOF
+
+
+# Keep a trace of the command line.
+# Strip out --no-create and --no-recursion so they do not pile up.
+# Strip out --silent because we don't want to record it for future runs.
+# Also quote any args containing shell meta-characters.
+# Make two passes to allow for proper duplicate-argument suppression.
+ac_configure_args=
+ac_configure_args0=
+ac_configure_args1=
+ac_must_keep_next=false
+for ac_pass in 1 2
+do
+  for ac_arg
+  do
+    case $ac_arg in
+    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
+    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+    | -silent | --silent | --silen | --sile | --sil)
+      continue ;;
+    *\'*)
+      ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    esac
+    case $ac_pass in
+    1) as_fn_append ac_configure_args0 " '$ac_arg'" ;;
+    2)
+      as_fn_append ac_configure_args1 " '$ac_arg'"
+      if test $ac_must_keep_next = true; then
+	ac_must_keep_next=false # Got value, back to normal.
+      else
+	case $ac_arg in
+	  *=* | --config-cache | -C | -disable-* | --disable-* \
+	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
+	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
+	  | -with-* | --with-* | -without-* | --without-* | --x)
+	    case "$ac_configure_args0 " in
+	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
+	    esac
+	    ;;
+	  -* ) ac_must_keep_next=true ;;
+	esac
+      fi
+      as_fn_append ac_configure_args " '$ac_arg'"
+      ;;
+    esac
+  done
+done
+{ ac_configure_args0=; unset ac_configure_args0;}
+{ ac_configure_args1=; unset ac_configure_args1;}
+
+# When interrupted or exit'd, cleanup temporary files, and complete
+# config.log.  We remove comments because anyway the quotes in there
+# would cause problems or look ugly.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
+trap 'exit_status=$?
+  # Save into config.log some information that might help in debugging.
+  {
+    echo
+
+    $as_echo "## ---------------- ##
+## Cache variables. ##
+## ---------------- ##"
+    echo
+    # The following way of writing the cache mishandles newlines in values,
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+  (set) 2>&1 |
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      sed -n \
+	"s/'\''/'\''\\\\'\'''\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
+    *)
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+)
+    echo
+
+    $as_echo "## ----------------- ##
+## Output variables. ##
+## ----------------- ##"
+    echo
+    for ac_var in $ac_subst_vars
+    do
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      $as_echo "$ac_var='\''$ac_val'\''"
+    done | sort
+    echo
+
+    if test -n "$ac_subst_files"; then
+      $as_echo "## ------------------- ##
+## File substitutions. ##
+## ------------------- ##"
+      echo
+      for ac_var in $ac_subst_files
+      do
+	eval ac_val=\$$ac_var
+	case $ac_val in
+	*\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+	esac
+	$as_echo "$ac_var='\''$ac_val'\''"
+      done | sort
+      echo
+    fi
+
+    if test -s confdefs.h; then
+      $as_echo "## ----------- ##
+## confdefs.h. ##
+## ----------- ##"
+      echo
+      cat confdefs.h
+      echo
+    fi
+    test "$ac_signal" != 0 &&
+      $as_echo "$as_me: caught signal $ac_signal"
+    $as_echo "$as_me: exit $exit_status"
+  } >&5
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
+    exit $exit_status
+' 0
+for ac_signal in 1 2 13 15; do
+  trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal
+done
+ac_signal=0
+
+# confdefs.h avoids OS command line length limits that DEFS can exceed.
+rm -f -r conftest* confdefs.h
+
+$as_echo "/* confdefs.h */" > confdefs.h
+
+# Predefined preprocessor variables.
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_NAME "$PACKAGE_NAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_VERSION "$PACKAGE_VERSION"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_STRING "$PACKAGE_STRING"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
+_ACEOF
+
+cat >>confdefs.h <<_ACEOF
+#define PACKAGE_URL "$PACKAGE_URL"
+_ACEOF
+
+
+# Let the site file select an alternate cache file if it wants to.
+# Prefer an explicitly selected file to automatically selected ones.
+ac_site_file1=NONE
+ac_site_file2=NONE
+if test -n "$CONFIG_SITE"; then
+  # We do not want a PATH search for config.site.
+  case $CONFIG_SITE in #((
+    -*)  ac_site_file1=./$CONFIG_SITE;;
+    */*) ac_site_file1=$CONFIG_SITE;;
+    *)   ac_site_file1=./$CONFIG_SITE;;
+  esac
+elif test "x$prefix" != xNONE; then
+  ac_site_file1=$prefix/share/config.site
+  ac_site_file2=$prefix/etc/config.site
+else
+  ac_site_file1=$ac_default_prefix/share/config.site
+  ac_site_file2=$ac_default_prefix/etc/config.site
+fi
+for ac_site_file in "$ac_site_file1" "$ac_site_file2"
+do
+  test "x$ac_site_file" = xNONE && continue
+  if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
+$as_echo "$as_me: loading site script $ac_site_file" >&6;}
+    sed 's/^/| /' "$ac_site_file" >&5
+    . "$ac_site_file" \
+      || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "failed to load site script $ac_site_file
+See \`config.log' for more details" "$LINENO" 5; }
+  fi
+done
+
+if test -r "$cache_file"; then
+  # Some versions of bash will fail to source /dev/null (special files
+  # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
+  if test /dev/null != "$cache_file" && test -f "$cache_file"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5
+$as_echo "$as_me: loading cache $cache_file" >&6;}
+    case $cache_file in
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
+    esac
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5
+$as_echo "$as_me: creating cache $cache_file" >&6;}
+  >$cache_file
+fi
+
+# Check that the precious variables saved in the cache have kept the same
+# value.
+ac_cache_corrupted=false
+for ac_var in $ac_precious_vars; do
+  eval ac_old_set=\$ac_cv_env_${ac_var}_set
+  eval ac_new_set=\$ac_env_${ac_var}_set
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
+  case $ac_old_set,$ac_new_set in
+    set,)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,set)
+      { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5
+$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
+      ac_cache_corrupted=: ;;
+    ,);;
+    *)
+      if test "x$ac_old_val" != "x$ac_new_val"; then
+	# differences in whitespace do not lead to failure.
+	ac_old_val_w=`echo x $ac_old_val`
+	ac_new_val_w=`echo x $ac_new_val`
+	if test "$ac_old_val_w" != "$ac_new_val_w"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5
+$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
+	  ac_cache_corrupted=:
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5
+$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;}
+	  eval $ac_var=\$ac_old_val
+	fi
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   former value:  \`$ac_old_val'" >&5
+$as_echo "$as_me:   former value:  \`$ac_old_val'" >&2;}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}:   current value: \`$ac_new_val'" >&5
+$as_echo "$as_me:   current value: \`$ac_new_val'" >&2;}
+      fi;;
+  esac
+  # Pass precious variables to config.status.
+  if test "$ac_new_set" = set; then
+    case $ac_new_val in
+    *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *) ac_arg=$ac_var=$ac_new_val ;;
+    esac
+    case " $ac_configure_args " in
+      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
+      *) as_fn_append ac_configure_args " '$ac_arg'" ;;
+    esac
+  fi
+done
+if $ac_cache_corrupted; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+  { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5
+$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;}
+  as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5
+fi
+## -------------------- ##
+## Main body of script. ##
+## -------------------- ##
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+ac_aux_dir=
+for ac_dir in src/build/autoconf "$srcdir"/src/build/autoconf; do
+  if test -f "$ac_dir/install-sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install-sh -c"
+    break
+  elif test -f "$ac_dir/install.sh"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/install.sh -c"
+    break
+  elif test -f "$ac_dir/shtool"; then
+    ac_aux_dir=$ac_dir
+    ac_install_sh="$ac_aux_dir/shtool install -c"
+    break
+  fi
+done
+if test -z "$ac_aux_dir"; then
+  as_fn_error $? "cannot find install-sh, install.sh, or shtool in src/build/autoconf \"$srcdir\"/src/build/autoconf" "$LINENO" 5
+fi
+
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
+ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
+
+
+
+## pick up compiler as will be used by R CMD INSTALL/SHLIB
+if test -n "${R_HOME}"; then
+  CC=`${R_HOME}/bin/R CMD config CC`
+  CPP=`${R_HOME}/bin/R CMD config CPP`
+  CFLAGS=`${R_HOME}/bin/R CMD config CFLAGS`
+  CXX=`${R_HOME}/bin/R CMD config CXX`
+  CXXFLAGS=`${R_HOME}/bin/R CMD config CXXFLAGS`
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out"
+# Try to create an executable without -o first, disregard a.out.
+# It will help us diagnose broken compilers, and finding out an intuition
+# of exeext.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5
+$as_echo_n "checking whether the C compiler works... " >&6; }
+ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
+
+# The possible output files:
+ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*"
+
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { { ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link_default") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
+do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj )
+	;;
+    [ab].out )
+	# We found the default executable, but exeext='' is most
+	# certainly right.
+	break;;
+    *.* )
+	if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+	then :; else
+	   ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	fi
+	# We set ac_cv_exeext here because the later test for it is not
+	# safe: cross compilers may not add the suffix if given an `-o'
+	# argument, so we may need to know it at that point already.
+	# Even if this section looks crufty: it has the advantage of
+	# actually working.
+	break;;
+    * )
+	break;;
+  esac
+done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
+else
+  ac_file=''
+fi
+if test -z "$ac_file"; then :
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+$as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error 77 "C compiler cannot create executables
+See \`config.log' for more details" "$LINENO" 5; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; }
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
+$as_echo_n "checking for C compiler default output file name... " >&6; }
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
+$as_echo "$ac_file" >&6; }
+ac_exeext=$ac_cv_exeext
+
+rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5
+$as_echo_n "checking for suffix of executables... " >&6; }
+if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  # If both `conftest.exe' and `conftest' are `present' (well, observable)
+# catch `conftest.exe'.  For instance with Cygwin, `ls conftest' will
+# work properly (i.e., refer to `conftest.exe'), while it won't with
+# `rm'.
+for ac_file in conftest.exe conftest conftest.*; do
+  test -f "$ac_file" || continue
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;;
+    *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+	  break;;
+    * ) break;;
+  esac
+done
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of executables: cannot compile and link
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest conftest$ac_cv_exeext
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
+$as_echo "$ac_cv_exeext" >&6; }
+
+rm -f conftest.$ac_ext
+EXEEXT=$ac_cv_exeext
+ac_exeext=$EXEEXT
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdio.h>
+int
+main ()
+{
+FILE *f = fopen ("conftest.out", "w");
+ return ferror (f) || fclose (f) != 0;
+
+  ;
+  return 0;
+}
+_ACEOF
+ac_clean_files="$ac_clean_files conftest.out"
+# Check that the compiler produces executables we can run.  If not, either
+# the compiler is broken, or we cross compile.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5
+$as_echo_n "checking whether we are cross compiling... " >&6; }
+if test "$cross_compiling" != yes; then
+  { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+  if { ac_try='./conftest$ac_cv_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+    cross_compiling=no
+  else
+    if test "$cross_compiling" = maybe; then
+	cross_compiling=yes
+    else
+	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot run C compiled programs.
+If you meant to cross compile, use \`--host'.
+See \`config.log' for more details" "$LINENO" 5; }
+    fi
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
+$as_echo "$cross_compiling" >&6; }
+
+rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
+ac_clean_files=$ac_clean_files_save
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
+$as_echo_n "checking for suffix of object files... " >&6; }
+if ${ac_cv_objext+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.o conftest.obj
+if { { ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compile") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; then :
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;;
+    *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
+       break;;
+  esac
+done
+else
+  $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "cannot compute suffix of object files: cannot compile
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+rm -f conftest.$ac_cv_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
+$as_echo "$ac_cv_objext" >&6; }
+OBJEXT=$ac_cv_objext
+ac_objext=$OBJEXT
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+struct stat;
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
+$as_echo_n "checking how to run the C preprocessor... " >&6; }
+# On Suns, sometimes $CPP names a directory.
+if test -n "$CPP" && test -d "$CPP"; then
+  CPP=
+fi
+if test -z "$CPP"; then
+  if ${ac_cv_prog_CPP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+      # Double quotes because CPP needs to be expanded
+    for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
+    do
+      ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+  break
+fi
+
+    done
+    ac_cv_prog_CPP=$CPP
+
+fi
+  CPP=$ac_cv_prog_CPP
+else
+  ac_cv_prog_CPP=$CPP
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5
+$as_echo "$CPP" >&6; }
+ac_preproc_ok=false
+for ac_c_preproc_warn_flag in '' yes
+do
+  # Use a header file that comes with gcc, so configuring glibc
+  # with a fresh cross-compiler works.
+  # Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+  # <limits.h> exists even on freestanding compilers.
+  # On the NeXT, cc -E runs the code through the compiler's parser,
+  # not just through cpp. "Syntax error" is here to catch this case.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+		     Syntax error
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+
+else
+  # Broken: fails on valid input.
+continue
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+  # OK, works on sane cases.  Now check whether nonexistent headers
+  # can be detected and how.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ac_nonexistent.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # Broken: success on invalid input.
+continue
+else
+  # Passes both tests.
+ac_preproc_ok=:
+break
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+
+done
+# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped.
+rm -f conftest.i conftest.err conftest.$ac_ext
+if $ac_preproc_ok; then :
+
+else
+  { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
+See \`config.log' for more details" "$LINENO" 5; }
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+if test -n "$ac_tool_prefix"; then
+  # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$ac_cv_prog_CC"; then
+  ac_ct_CC=$CC
+  # Extract the first word of "gcc", so it can be a program name with args.
+set dummy gcc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="gcc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+else
+  CC="$ac_cv_prog_CC"
+fi
+
+if test -z "$CC"; then
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+set dummy ${ac_tool_prefix}cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="${ac_tool_prefix}cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+fi
+if test -z "$CC"; then
+  # Extract the first word of "cc", so it can be a program name with args.
+set dummy cc; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+  ac_prog_rejected=no
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
+       ac_prog_rejected=yes
+       continue
+     fi
+    ac_cv_prog_CC="cc"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+if test $ac_prog_rejected = yes; then
+  # We found a bogon in the path, so make sure we never use it.
+  set dummy $ac_cv_prog_CC
+  shift
+  if test $# != 0; then
+    # We chose a different compiler from the bogus one.
+    # However, it has the same basename, so the bogon will be chosen
+    # first if we set CC to just the basename; use the full file name.
+    shift
+    ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@"
+  fi
+fi
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+fi
+if test -z "$CC"; then
+  if test -n "$ac_tool_prefix"; then
+  for ac_prog in cl.exe
+  do
+    # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
+set dummy $ac_tool_prefix$ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$CC"; then
+  ac_cv_prog_CC="$CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+CC=$ac_cv_prog_CC
+if test -n "$CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5
+$as_echo "$CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+    test -n "$CC" && break
+  done
+fi
+if test -z "$CC"; then
+  ac_ct_CC=$CC
+  for ac_prog in cl.exe
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$ac_ct_CC"; then
+  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_ac_ct_CC="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+ac_ct_CC=$ac_cv_prog_ac_ct_CC
+if test -n "$ac_ct_CC"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5
+$as_echo "$ac_ct_CC" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$ac_ct_CC" && break
+done
+
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5
+$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
+fi
+
+fi
+
+
+test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
+$as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
+as_fn_error $? "no acceptable C compiler found in \$PATH
+See \`config.log' for more details" "$LINENO" 5; }
+
+# Provide some information about the compiler.
+$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
+set X $ac_compile
+ac_compiler=$2
+for ac_option in --version -v -V -qversion; do
+  { { ac_try="$ac_compiler $ac_option >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_compiler $ac_option >&5") 2>conftest.err
+  ac_status=$?
+  if test -s conftest.err; then
+    sed '10a\
+... rest of stderr output deleted ...
+         10q' conftest.err >conftest.er1
+    cat conftest.er1 >&5
+  fi
+  rm -f conftest.er1 conftest.err
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }
+done
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
+$as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
+if ${ac_cv_c_compiler_gnu+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+#ifndef __GNUC__
+       choke me
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_compiler_gnu=yes
+else
+  ac_compiler_gnu=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ac_cv_c_compiler_gnu=$ac_compiler_gnu
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5
+$as_echo "$ac_cv_c_compiler_gnu" >&6; }
+if test $ac_compiler_gnu = yes; then
+  GCC=yes
+else
+  GCC=
+fi
+ac_test_CFLAGS=${CFLAGS+set}
+ac_save_CFLAGS=$CFLAGS
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
+$as_echo_n "checking whether $CC accepts -g... " >&6; }
+if ${ac_cv_prog_cc_g+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+else
+  CFLAGS=""
+      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+
+else
+  ac_c_werror_flag=$ac_save_c_werror_flag
+	 CFLAGS="-g"
+	 cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_g=yes
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5
+$as_echo "$ac_cv_prog_cc_g" >&6; }
+if test "$ac_test_CFLAGS" = set; then
+  CFLAGS=$ac_save_CFLAGS
+elif test $ac_cv_prog_cc_g = yes; then
+  if test "$GCC" = yes; then
+    CFLAGS="-g -O2"
+  else
+    CFLAGS="-g"
+  fi
+else
+  if test "$GCC" = yes; then
+    CFLAGS="-O2"
+  else
+    CFLAGS=
+  fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
+$as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
+if ${ac_cv_prog_cc_c89+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_cv_prog_cc_c89=no
+ac_save_CC=$CC
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdarg.h>
+#include <stdio.h>
+struct stat;
+/* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
+struct buf { int x; };
+FILE * (*rcsopen) (struct buf *, struct stat *, int);
+static char *e (p, i)
+     char **p;
+     int i;
+{
+  return p[i];
+}
+static char *f (char * (*g) (char **, int), char **p, ...)
+{
+  char *s;
+  va_list v;
+  va_start (v,p);
+  s = g (p, va_arg (v,int));
+  va_end (v);
+  return s;
+}
+
+/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
+   function prototypes and stuff, but not '\xHH' hex character constants.
+   These don't provoke an error unfortunately, instead are silently treated
+   as 'x'.  The following induces an error, until -std is added to get
+   proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
+   array size at least.  It's necessary to write '\x00'==0 to get something
+   that's true only with -std.  */
+int osf4_cc_array ['\x00' == 0 ? 1 : -1];
+
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
+int test (int i, double x);
+struct s1 {int (*f) (int a);};
+struct s2 {int (*f) (double a);};
+int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int);
+int argc;
+char **argv;
+int
+main ()
+{
+return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
+  ;
+  return 0;
+}
+_ACEOF
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+	-Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+do
+  CC="$ac_save_CC $ac_arg"
+  if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_prog_cc_c89=$ac_arg
+fi
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
+done
+rm -f conftest.$ac_ext
+CC=$ac_save_CC
+
+fi
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5
+$as_echo "none needed" >&6; } ;;
+  xno)
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5
+$as_echo "unsupported" >&6; } ;;
+  *)
+    CC="$CC $ac_cv_prog_cc_c89"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5
+$as_echo "$ac_cv_prog_cc_c89" >&6; } ;;
+esac
+if test "x$ac_cv_prog_cc_c89" != xno; then :
+
+fi
+
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether __attribute__((visibility())) is supported" >&5
+$as_echo_n "checking whether __attribute__((visibility())) is supported... " >&6; }
+if ${r_cv_visibility_attribute+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat > conftest.c <<EOF
+int foo __attribute__ ((visibility ("hidden"))) = 1;
+int bar __attribute__ ((visibility ("default"))) = 1;
+EOF
+r_cv_visibility_attribute=no
+if { ac_try='${CC-cc} -Werror -S conftest.c -o conftest.s 1>&5'
+  { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5
+  (eval $ac_try) 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then
+ if grep '\.hidden.*foo' conftest.s >/dev/null; then
+    r_cv_visibility_attribute=yes
+ fi
+fi
+rm -f conftest.cs
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $r_cv_visibility_attribute" >&5
+$as_echo "$r_cv_visibility_attribute" >&6; }
+if test $r_cv_visibility_attribute = yes; then
+
+$as_echo "#define HAVE_VISIBILITY_ATTRIBUTE 1" >>confdefs.h
+
+fi
+## test if visibility flag is accepted: NB Solaris compilers do and ignore,
+## so only make use of this if HAVE_VISIBILITY_ATTRIBUTE is true.
+r_save_CFLAGS=$CFLAGS
+CFLAGS="$CFLAGS -fvisibility=hidden"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -fvisibility" >&5
+$as_echo_n "checking whether $CC accepts -fvisibility... " >&6; }
+if ${r_cv_prog_cc_vis+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  r_cv_prog_cc_vis=yes
+else
+  r_cv_prog_cc_vis=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $r_cv_prog_cc_vis" >&5
+$as_echo "$r_cv_prog_cc_vis" >&6; }
+CFLAGS=$r_save_CFLAGS
+if test "${r_cv_prog_cc_vis}" = yes; then
+  if test "${r_cv_visibility_attribute}" = yes; then
+    C_VISIBILITY="-fvisibility=hidden"
+  fi
+fi
+## Need to exclude Intel compilers, where this does not work.
+## The flag is documented, and is effective but also hides
+## unsatisfied references. We cannot test for GCC, as icc passes that test.
+case  "${CC}" in
+  ## Intel compiler: note that -c99 may have been appended
+  *icc*)
+    C_VISIBILITY=
+    ;;
+esac
+
+ac_ext=f
+ac_compile='$F77 -c $FFLAGS conftest.$ac_ext >&5'
+ac_link='$F77 -o conftest$ac_exeext $FFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_f77_compiler_gnu
+
+r_save_FFLAGS=$FFLAGS
+FFLAGS="$FFLAGS -fvisibility=hidden"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $F77 accepts -fvisibility" >&5
+$as_echo_n "checking whether $F77 accepts -fvisibility... " >&6; }
+if ${r_cv_prog_f77_vis+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat > conftest.$ac_ext <<_ACEOF
+      program main
+
+      end
+_ACEOF
+if ac_fn_f77_try_compile "$LINENO"; then :
+  r_cv_prog_f77_vis=yes
+else
+  r_cv_prog_f77_vis=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $r_cv_prog_f77_vis" >&5
+$as_echo "$r_cv_prog_f77_vis" >&6; }
+FFLAGS=$r_save_FFLAGS
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
+
+if test "${r_cv_prog_f77_vis}" = yes; then
+  if test "${r_cv_visibility_attribute}" = yes; then
+    F77_VISIBILITY="-fvisibility=hidden"
+  fi
+fi
+## need to exclude Intel compilers.
+case  "${F77}" in
+  ## Intel compiler
+  *ifc|*ifort)
+    F77_VISIBILITY=
+    ;;
+esac
+
+
+
+if test `uname` = "Darwin" ; then
+  darwin="yes"
+  ## we want the *build* cputype and not the host one.
+  cmd=`echo $CC $CFLAGS | grep -E 'x86_64|ppc64|-m64'`
+  if test -n "$cmd"; then
+    have_64bit="yes"
+  else
+    have_64bit="no"
+  fi
+else
+  darwin="no"
+fi
+
+## --- LibPNG ----------------------------------------------------------------
+
+# Check whether --enable-libpng was given.
+if test "${enable_libpng+set}" = set; then :
+  enableval=$enable_libpng;
+fi
+
+# Check whether --enable-libpng-config was given.
+if test "${enable_libpng_config+set}" = set; then :
+  enableval=$enable_libpng_config;
+fi
+
+# Check whether --enable-libpng-dynamic was given.
+if test "${enable_libpng_dynamic+set}" = set; then :
+  enableval=$enable_libpng_dynamic;
+fi
+
+
+if test "x$enable_libpng" != "xno"; then
+
+  if test "x$enable_libpng_config" != "xno"; then
+    # Extract the first word of "libpng-config", so it can be a program name with args.
+set dummy libpng-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_HAVE_LIBPNG_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$HAVE_LIBPNG_CONFIG"; then
+  ac_cv_prog_HAVE_LIBPNG_CONFIG="$HAVE_LIBPNG_CONFIG" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_HAVE_LIBPNG_CONFIG="yes"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_prog_HAVE_LIBPNG_CONFIG" && ac_cv_prog_HAVE_LIBPNG_CONFIG="no"
+fi
+fi
+HAVE_LIBPNG_CONFIG=$ac_cv_prog_HAVE_LIBPNG_CONFIG
+if test -n "$HAVE_LIBPNG_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAVE_LIBPNG_CONFIG" >&5
+$as_echo "$HAVE_LIBPNG_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  fi
+
+  if test "x$HAVE_LIBPNG_CONFIG" = "xyes" ; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: using libpng-config" >&5
+$as_echo "$as_me: using libpng-config" >&6;}
+    CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H `libpng-config --I_opts`"
+    if test "x$enable_libpng_dynamic" != "xno"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: using libpng dynamic linkage" >&5
+$as_echo "$as_me: using libpng dynamic linkage" >&6;}
+      LIBS="${LIBS} `libpng-config --ldflags`"
+    else
+      { $as_echo "$as_me:${as_lineno-$LINENO}: using libpng static linkage" >&5
+$as_echo "$as_me: using libpng static linkage" >&6;}
+      LIBS="${LIBS} `libpng-config --static --L_opts`/libpng.a"
+    fi
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking libpng" >&5
+$as_echo_n "checking libpng... " >&6; }
+    save_LIBS="${LIBS}"
+    save_CPPFLAGS="${CPPFLAGS}"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
+$as_echo_n "checking for grep that handles long lines and -e... " >&6; }
+if ${ac_cv_path_GREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -z "$GREP"; then
+  ac_path_GREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in grep ggrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_GREP" || continue
+# Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_GREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_GREP"; then
+    as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_GREP=$GREP
+fi
+
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
+$as_echo "$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
+$as_echo_n "checking for egrep... " >&6; }
+if ${ac_cv_path_EGREP+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     if test -z "$EGREP"; then
+  ac_path_EGREP_found=false
+  # Loop through the user's path and test for each of PROGNAME-LIST
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_prog in egrep; do
+    for ac_exec_ext in '' $ac_executable_extensions; do
+      ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+      as_fn_executable_p "$ac_path_EGREP" || continue
+# Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  $as_echo_n 0123456789 >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    $as_echo 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    as_fn_arith $ac_count + 1 && ac_count=$as_val
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+      $ac_path_EGREP_found && break 3
+    done
+  done
+  done
+IFS=$as_save_IFS
+  if test -z "$ac_cv_path_EGREP"; then
+    as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5
+  fi
+else
+  ac_cv_path_EGREP=$EGREP
+fi
+
+   fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
+$as_echo "$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
+# On IRIX 5.3, sys/types and inttypes.h are conflicting.
+for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
+		  inttypes.h stdint.h unistd.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default
+"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+
+for ac_header in png.h
+do :
+  ac_fn_c_check_header_mongrel "$LINENO" "png.h" "ac_cv_header_png_h" "$ac_includes_default"
+if test "x$ac_cv_header_png_h" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_PNG_H 1
+_ACEOF
+
+fi
+
+done
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking for png_read_update_info in -lpng" >&5
+$as_echo_n "checking for png_read_update_info in -lpng... " >&6; }
+if ${ac_cv_lib_png_png_read_update_info+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpng  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char png_read_update_info ();
+int
+main ()
+{
+return png_read_update_info ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_png_png_read_update_info=yes
+else
+  ac_cv_lib_png_png_read_update_info=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_png_png_read_update_info" >&5
+$as_echo "$ac_cv_lib_png_png_read_update_info" >&6; }
+if test "x$ac_cv_lib_png_png_read_update_info" = xyes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBPNG 1
+_ACEOF
+
+  LIBS="-lpng $LIBS"
+
+fi
+
+    if test "${ac_cv_header_png_h}"; then
+      if test "${ac_cv_lib_png_png_read_update_info}"; then
+	CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H"
+	LIBS="${LIBS} -lpng"
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: libpng header and lib found" >&5
+$as_echo "$as_me: libpng header and lib found" >&6;}
+	if test "x$enable_libpng_dynamic" != "xno"; then
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: using libpng dynamic linkage" >&5
+$as_echo "$as_me: using libpng dynamic linkage" >&6;}
+	else
+	  { $as_echo "$as_me:${as_lineno-$LINENO}: using libpng static linkage" >&5
+$as_echo "$as_me: using libpng static linkage" >&6;}
+	fi
+      else
+	LIBS=${save_LIBS}
+	CPPFLAGS=${save_CPPFLAGS}
+	{ $as_echo "$as_me:${as_lineno-$LINENO}: libpng header and lib not found" >&5
+$as_echo "$as_me: libpng header and lib not found" >&6;}
+      fi
+    fi
+  fi
+
+fi
+
+# ---[ X11 ]------------------------------------------------------------------
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking for X" >&5
+$as_echo_n "checking for X... " >&6; }
+
+
+# Check whether --with-x was given.
+if test "${with_x+set}" = set; then :
+  withval=$with_x;
+fi
+
+# $have_x is `yes', `no', `disabled', or empty when we do not yet know.
+if test "x$with_x" = xno; then
+  # The user explicitly disabled X.
+  have_x=disabled
+else
+  case $x_includes,$x_libraries in #(
+    *\'*) as_fn_error $? "cannot use X directory names containing '" "$LINENO" 5;; #(
+    *,NONE | NONE,*) if ${ac_cv_have_x+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  # One or both of the vars are not set, and there is no cached value.
+ac_x_includes=no ac_x_libraries=no
+rm -f -r conftest.dir
+if mkdir conftest.dir; then
+  cd conftest.dir
+  cat >Imakefile <<'_ACEOF'
+incroot:
+	@echo incroot='${INCROOT}'
+usrlibdir:
+	@echo usrlibdir='${USRLIBDIR}'
+libdir:
+	@echo libdir='${LIBDIR}'
+_ACEOF
+  if (export CC; ${XMKMF-xmkmf}) >/dev/null 2>/dev/null && test -f Makefile; then
+    # GNU make sometimes prints "make[1]: Entering ...", which would confuse us.
+    for ac_var in incroot usrlibdir libdir; do
+      eval "ac_im_$ac_var=\`\${MAKE-make} $ac_var 2>/dev/null | sed -n 's/^$ac_var=//p'\`"
+    done
+    # Open Windows xmkmf reportedly sets LIBDIR instead of USRLIBDIR.
+    for ac_extension in a so sl dylib la dll; do
+      if test ! -f "$ac_im_usrlibdir/libX11.$ac_extension" &&
+	 test -f "$ac_im_libdir/libX11.$ac_extension"; then
+	ac_im_usrlibdir=$ac_im_libdir; break
+      fi
+    done
+    # Screen out bogus values from the imake configuration.  They are
+    # bogus both because they are the default anyway, and because
+    # using them would break gcc on systems where it needs fixed includes.
+    case $ac_im_incroot in
+	/usr/include) ac_x_includes= ;;
+	*) test -f "$ac_im_incroot/X11/Xos.h" && ac_x_includes=$ac_im_incroot;;
+    esac
+    case $ac_im_usrlibdir in
+	/usr/lib | /usr/lib64 | /lib | /lib64) ;;
+	*) test -d "$ac_im_usrlibdir" && ac_x_libraries=$ac_im_usrlibdir ;;
+    esac
+  fi
+  cd ..
+  rm -f -r conftest.dir
+fi
+
+# Standard set of common directories for X headers.
+# Check X11 before X11Rn because it is often a symlink to the current release.
+ac_x_header_dirs='
+/usr/X11/include
+/usr/X11R7/include
+/usr/X11R6/include
+/usr/X11R5/include
+/usr/X11R4/include
+
+/usr/include/X11
+/usr/include/X11R7
+/usr/include/X11R6
+/usr/include/X11R5
+/usr/include/X11R4
+
+/usr/local/X11/include
+/usr/local/X11R7/include
+/usr/local/X11R6/include
+/usr/local/X11R5/include
+/usr/local/X11R4/include
+
+/usr/local/include/X11
+/usr/local/include/X11R7
+/usr/local/include/X11R6
+/usr/local/include/X11R5
+/usr/local/include/X11R4
+
+/usr/X386/include
+/usr/x386/include
+/usr/XFree86/include/X11
+
+/usr/include
+/usr/local/include
+/usr/unsupported/include
+/usr/athena/include
+/usr/local/x11r5/include
+/usr/lpp/Xamples/include
+
+/usr/openwin/include
+/usr/openwin/share/include'
+
+if test "$ac_x_includes" = no; then
+  # Guess where to find include files, by looking for Xlib.h.
+  # First, try using that file with no special directory specified.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <X11/Xlib.h>
+_ACEOF
+if ac_fn_c_try_cpp "$LINENO"; then :
+  # We can compile using X headers with no special include directory.
+ac_x_includes=
+else
+  for ac_dir in $ac_x_header_dirs; do
+  if test -r "$ac_dir/X11/Xlib.h"; then
+    ac_x_includes=$ac_dir
+    break
+  fi
+done
+fi
+rm -f conftest.err conftest.i conftest.$ac_ext
+fi # $ac_x_includes = no
+
+if test "$ac_x_libraries" = no; then
+  # Check for the libraries.
+  # See if we find them without any special options.
+  # Don't add to $LIBS permanently.
+  ac_save_LIBS=$LIBS
+  LIBS="-lX11 $LIBS"
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <X11/Xlib.h>
+int
+main ()
+{
+XrmInitialize ()
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  LIBS=$ac_save_LIBS
+# We can link X programs with no special library path.
+ac_x_libraries=
+else
+  LIBS=$ac_save_LIBS
+for ac_dir in `$as_echo "$ac_x_includes $ac_x_header_dirs" | sed s/include/lib/g`
+do
+  # Don't even attempt the hair of trying to link an X program!
+  for ac_extension in a so sl dylib la dll; do
+    if test -r "$ac_dir/libX11.$ac_extension"; then
+      ac_x_libraries=$ac_dir
+      break 2
+    fi
+  done
+done
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+fi # $ac_x_libraries = no
+
+case $ac_x_includes,$ac_x_libraries in #(
+  no,* | *,no | *\'*)
+    # Didn't find X, or a directory has "'" in its name.
+    ac_cv_have_x="have_x=no";; #(
+  *)
+    # Record where we found X for the cache.
+    ac_cv_have_x="have_x=yes\
+	ac_x_includes='$ac_x_includes'\
+	ac_x_libraries='$ac_x_libraries'"
+esac
+fi
+;; #(
+    *) have_x=yes;;
+  esac
+  eval "$ac_cv_have_x"
+fi # $with_x != no
+
+if test "$have_x" != yes; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $have_x" >&5
+$as_echo "$have_x" >&6; }
+  no_x=yes
+else
+  # If each of the values was on the command line, it overrides each guess.
+  test "x$x_includes" = xNONE && x_includes=$ac_x_includes
+  test "x$x_libraries" = xNONE && x_libraries=$ac_x_libraries
+  # Update the cache value to reflect the command line values.
+  ac_cv_have_x="have_x=yes\
+	ac_x_includes='$x_includes'\
+	ac_x_libraries='$x_libraries'"
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: libraries $x_libraries, headers $x_includes" >&5
+$as_echo "libraries $x_libraries, headers $x_includes" >&6; }
+fi
+
+  if test x$no_x = xyes ; then
+    as_fn_error $? "X11 not found but required, configure aborted." "$LINENO" 5
+  fi
+  if test -n "${x_includes}"; then
+    CPPFLAGS="${CPPFLAGS} -I${x_includes}"
+  fi
+  if test -n "${x_libraries}"; then
+    LIBS="${LIBS} -L${x_libraries} -lX11"
+  else
+    LIBS="${LIBS} -lX11"
+  fi
+  if test $darwin = yes; then
+    CPPFLAGS="${CPPFLAGS} -DDarwin"
+    # Apple's OpenGL is different from the X11 one - it must be loaded *before* X11
+    if test -e /System/Library/Frameworks/OpenGL.framework ; then
+      CPPFLAGS="-I/System/Library/Frameworks/OpenGL.framework/Headers ${CPPFLAGS} -DNO_GL_PREFIX"
+      # OSX 10.5 messes up X11; this works around it
+      LIBS="-framework OpenGL -dylib_file /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib ${LIBS}"
+    fi
+    if test -e /System/Library/Frameworks/GLKit.framework ; then
+      LIBS="-framework GLKit ${LIBS}"
+    fi
+    # some X11 installations on OSX 10.5 feature -rpath which doesn't work when used in
+    # conjunction with 10.4u SDK (and is redundant anyway since OS X always uses full paths)
+    if test rpath`echo "${LIBS}" | sed -n 's/.*-Wl,-rpath,.*/Yes/p' 2>/dev/null` = rpathYes; then
+      LIBS=`echo "${LIBS}" | sed 's:-Wl,-rpath,[^ ]*::'`
+    fi
+    # X11 must come *after* the OpenGL stuff
+    CPPFLAGS="${CPPFLAGS} -I/opt/X11/include"
+  fi
+
+## --- OpenGL ----------------------------------------------------------------
+
+
+# Check whether --with-gl-includes was given.
+if test "${with_gl_includes+set}" = set; then :
+  withval=$with_gl_includes; CPPFLAGS="${CPPFLAGS} -I${withval}"
+
+fi
+
+
+if test $darwin != yes; then
+  for ac_header in GL/gl.h GL/glu.h
+do :
+  as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
+ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default"
+if eval test \"x\$"$as_ac_Header"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
+fi
+
+done
+
+  if test "x$ac_cv_header_GL_gl_h" = xno; then
+    as_fn_error $? "missing required header GL/gl.h" "$LINENO" 5
+  fi
+  if test "x$ac_cv_header_GL_glu_h" = xno; then
+    as_fn_error $? "missing required header GL/glu.h" "$LINENO" 5
+  fi
+fi
+
+
+# Check whether --with-gl-libs was given.
+if test "${with_gl_libs+set}" = set; then :
+  withval=$with_gl_libs; LDFLAGS="${LDFLAGS} -L${withval}"
+L_LIB="-L${withval}"
+
+fi
+
+
+
+# Check whether --with-gl-libname was given.
+if test "${with_gl_libname+set}" = set; then :
+  withval=$with_gl_libname; lGL=${withval}
+else
+  lGL=GL
+
+fi
+
+as_ac_Lib=`$as_echo "ac_cv_lib_$lGL''_glEnd" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for glEnd in -l$lGL" >&5
+$as_echo_n "checking for glEnd in -l$lGL... " >&6; }
+if eval \${$as_ac_Lib+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-l$lGL  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char glEnd ();
+int
+main ()
+{
+return glEnd ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_LIB$lGL" | $as_tr_cpp` 1
+_ACEOF
+
+  LIBS="-l$lGL $LIBS"
+
+fi
+
+this=`eval echo '${'$as_ac_Lib'}'`
+if test "x$this" != xyes; then
+  as_fn_error $? "missing required library ${lGL}" "$LINENO" 5
+fi
+
+
+# Check whether --with-glu-libname was given.
+if test "${with_glu_libname+set}" = set; then :
+  withval=$with_glu_libname; lGLU=${withval}
+else
+  lGLU=GLU
+
+fi
+
+as_ac_Lib=`$as_echo "ac_cv_lib_$lGLU''_gluProject" | $as_tr_sh`
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for gluProject in -l$lGLU" >&5
+$as_echo_n "checking for gluProject in -l$lGLU... " >&6; }
+if eval \${$as_ac_Lib+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-l$lGLU  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char gluProject ();
+int
+main ()
+{
+return gluProject ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  eval "$as_ac_Lib=yes"
+else
+  eval "$as_ac_Lib=no"
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+eval ac_res=\$$as_ac_Lib
+	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
+$as_echo "$ac_res" >&6; }
+if eval test \"x\$"$as_ac_Lib"\" = x"yes"; then :
+  cat >>confdefs.h <<_ACEOF
+#define `$as_echo "HAVE_LIB$lGLU" | $as_tr_cpp` 1
+_ACEOF
+
+  LIBS="-l$lGLU $LIBS"
+
+fi
+
+this=`eval echo '${'$as_ac_Lib'}'`
+if test "x$this" != xyes; then
+  as_fn_error $? "missing required library ${lGLU}" "$LINENO" 5
+fi
+
+if test x$L_LIB != x; then
+  LIBS="${L_LIB} ${LIBS}"
+fi
+
+## --- FTGL ------------------------------------------------------------------
+
+# Check whether --enable-ftgl was given.
+if test "${enable_ftgl+set}" = set; then :
+  enableval=$enable_ftgl;
+fi
+
+if test "x$enable_ftgl" != "xno"; then
+  if test "x$darwin" = "xyes"; then
+    { $as_echo "$as_me:${as_lineno-$LINENO}: Darwin, so ensuring /opt/X11/bin is at the head of the PATH..." >&5
+$as_echo "$as_me: Darwin, so ensuring /opt/X11/bin is at the head of the PATH..." >&6;}
+    PATH=/opt/X11/bin:${PATH}
+  fi
+  # Extract the first word of "freetype-config", so it can be a program name with args.
+set dummy freetype-config; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_HAVE_FREETYPE_CONFIG+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$HAVE_FREETYPE_CONFIG"; then
+  ac_cv_prog_HAVE_FREETYPE_CONFIG="$HAVE_FREETYPE_CONFIG" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_HAVE_FREETYPE_CONFIG="yes"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_prog_HAVE_FREETYPE_CONFIG" && ac_cv_prog_HAVE_FREETYPE_CONFIG="no"
+fi
+fi
+HAVE_FREETYPE_CONFIG=$ac_cv_prog_HAVE_FREETYPE_CONFIG
+if test -n "$HAVE_FREETYPE_CONFIG"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $HAVE_FREETYPE_CONFIG" >&5
+$as_echo "$HAVE_FREETYPE_CONFIG" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  if test "x$HAVE_FREETYPE_CONFIG" = "xyes"; then
+    CPPFLAGS="${CPPFLAGS} -DHAVE_FREETYPE -Iext/ftgl `freetype-config --cflags`"
+    LIBS="${LIBS} `freetype-config --libs`"
+    { $as_echo "$as_me:${as_lineno-$LINENO}: using Freetype and FTGL" >&5
+$as_echo "$as_me: using Freetype and FTGL" >&6;}
+  fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: compiling without FTGL support" >&5
+$as_echo "$as_me: compiling without FTGL support" >&6;}
+fi
+
+## --- Output ----------------------------------------------------------------
+
+
+
+
+
+ac_config_files="$ac_config_files src/Makevars"
+
+cat >confcache <<\_ACEOF
+# This file is a shell script that caches the results of configure
+# tests run on this system so they can be shared between configure
+# scripts and configure runs, see configure's option --config-cache.
+# It is not useful on other systems.  If it contains results you don't
+# want to keep, you may remove or edit it.
+#
+# config.status only pays attention to the cache file if you give it
+# the --recheck option to rerun configure.
+#
+# `ac_cv_env_foo' variables (set or unset) will be overridden when
+# loading this file, other *unset* `ac_cv_foo' will be assigned the
+# following values.
+
+_ACEOF
+
+# The following way of writing the cache mishandles newlines in values,
+# but we know of no workaround that is simple, portable, and efficient.
+# So, we kill variables containing newlines.
+# Ultrix sh set writes to stderr and can't be redirected directly,
+# and sets the high bit in the cache file unless we assign to the vars.
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5
+$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #(
+      *) { eval $ac_var=; unset $ac_var;} ;;
+      esac ;;
+    esac
+  done
+
+  (set) 2>&1 |
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
+      # `set' does not quote correctly, so add quotes: double-quote
+      # substitution turns \\\\ into \\, and sed turns \\ into \.
+      sed -n \
+	"s/'/'\\\\''/g;
+	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
+      ;; #(
+    *)
+      # `set' quotes correctly as required by POSIX, so do not add quotes.
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
+      ;;
+    esac |
+    sort
+) |
+  sed '
+     /^ac_cv_env_/b end
+     t clear
+     :clear
+     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
+     t end
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    if test "x$cache_file" != "x/dev/null"; then
+      { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
+$as_echo "$as_me: updating cache $cache_file" >&6;}
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
+    fi
+  else
+    { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
+$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
+  fi
+fi
+rm -f confcache
+
+test "x$prefix" = xNONE && prefix=$ac_default_prefix
+# Let make expand exec_prefix.
+test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
+
+# Transform confdefs.h into DEFS.
+# Protect against shell expansion while executing Makefile rules.
+# Protect against Makefile macro expansion.
+#
+# If the first sed substitution is executed (which looks for macros that
+# take arguments), then branch to the quote section.  Otherwise,
+# look for a macro that doesn't take arguments.
+ac_script='
+:mline
+/\\$/{
+ N
+ s,\\\n,,
+ b mline
+}
+t clear
+:clear
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
+t quote
+b any
+:quote
+s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
+s/\[/\\&/g
+s/\]/\\&/g
+s/\$/$$/g
+H
+:any
+${
+	g
+	s/^\n//
+	s/\n/ /g
+	p
+}
+'
+DEFS=`sed -n "$ac_script" confdefs.h`
+
+
+ac_libobjs=
+ac_ltlibobjs=
+U=
+for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
+  # 1. Remove the extension, and $U if already installed.
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`$as_echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo'
+done
+LIBOBJS=$ac_libobjs
+
+LTLIBOBJS=$ac_ltlibobjs
+
+
+
+: "${CONFIG_STATUS=./config.status}"
+ac_write_fail=0
+ac_clean_files_save=$ac_clean_files
+ac_clean_files="$ac_clean_files $CONFIG_STATUS"
+{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
+$as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
+as_write_fail=0
+cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
+#! $SHELL
+# Generated by $as_me.
+# Run this file to recreate the current configuration.
+# Compiler output produced by configure, useful for debugging
+# configure, is in config.log if it exists.
+
+debug=false
+ac_cs_recheck=false
+ac_cs_silent=false
+
+SHELL=\${CONFIG_SHELL-$SHELL}
+export SHELL
+_ASEOF
+cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1
+## -------------------- ##
+## M4sh Initialization. ##
+## -------------------- ##
+
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then :
+  emulate sh
+  NULLCMD=:
+  # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in #(
+  *posix*) :
+    set -o posix ;; #(
+  *) :
+     ;;
+esac
+fi
+
+
+as_nl='
+'
+export as_nl
+# Printing a long string crashes Solaris 7 /usr/bin/printf.
+as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo
+as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo
+# Prefer a ksh shell builtin over an external printf program on Solaris,
+# but without wasting forks for bash or zsh.
+if test -z "$BASH_VERSION$ZSH_VERSION" \
+    && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='print -r --'
+  as_echo_n='print -rn --'
+elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then
+  as_echo='printf %s\n'
+  as_echo_n='printf %s'
+else
+  if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then
+    as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"'
+    as_echo_n='/usr/ucb/echo -n'
+  else
+    as_echo_body='eval expr "X$1" : "X\\(.*\\)"'
+    as_echo_n_body='eval
+      arg=$1;
+      case $arg in #(
+      *"$as_nl"*)
+	expr "X$arg" : "X\\(.*\\)$as_nl";
+	arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;;
+      esac;
+      expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl"
+    '
+    export as_echo_n_body
+    as_echo_n='sh -c $as_echo_n_body as_echo'
+  fi
+  export as_echo_body
+  as_echo='sh -c $as_echo_body as_echo'
+fi
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  PATH_SEPARATOR=:
+  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {
+    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||
+      PATH_SEPARATOR=';'
+  }
+fi
+
+
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+IFS=" ""	$as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
+case $0 in #((
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+  done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  exit 1
+fi
+
+# Unset variables that we do not need and which cause bugs (e.g. in
+# pre-3.0 UWIN ksh).  But do not cause bugs in bash 2.01; the "|| exit 1"
+# suppresses any "Segmentation fault" message there.  '((' could
+# trigger a bug in pdksh 5.2.14.
+for as_var in BASH_ENV ENV MAIL MAILPATH
+do eval test x\${$as_var+set} = xset \
+  && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || :
+done
+PS1='$ '
+PS2='> '
+PS4='+ '
+
+# NLS nuisances.
+LC_ALL=C
+export LC_ALL
+LANGUAGE=C
+export LANGUAGE
+
+# CDPATH.
+(unset CDPATH) >/dev/null 2>&1 && unset CDPATH
+
+
+# as_fn_error STATUS ERROR [LINENO LOG_FD]
+# ----------------------------------------
+# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are
+# provided, also output the error to LOG_FD, referencing LINENO. Then exit the
+# script with STATUS, using 1 if that was 0.
+as_fn_error ()
+{
+  as_status=$1; test $as_status -eq 0 && as_status=1
+  if test "$4"; then
+    as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+    $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4
+  fi
+  $as_echo "$as_me: error: $2" >&2
+  as_fn_exit $as_status
+} # as_fn_error
+
+
+# as_fn_set_status STATUS
+# -----------------------
+# Set $? to STATUS, without forking.
+as_fn_set_status ()
+{
+  return $1
+} # as_fn_set_status
+
+# as_fn_exit STATUS
+# -----------------
+# Exit the shell with STATUS, even in a "trap 0" or "set -e" context.
+as_fn_exit ()
+{
+  set +e
+  as_fn_set_status $1
+  exit $1
+} # as_fn_exit
+
+# as_fn_unset VAR
+# ---------------
+# Portably unset VAR.
+as_fn_unset ()
+{
+  { eval $1=; unset $1;}
+}
+as_unset=as_fn_unset
+# as_fn_append VAR VALUE
+# ----------------------
+# Append the text in VALUE to the end of the definition contained in VAR. Take
+# advantage of any shell optimizations that allow amortized linear growth over
+# repeated appends, instead of the typical quadratic growth present in naive
+# implementations.
+if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then :
+  eval 'as_fn_append ()
+  {
+    eval $1+=\$2
+  }'
+else
+  as_fn_append ()
+  {
+    eval $1=\$$1\$2
+  }
+fi # as_fn_append
+
+# as_fn_arith ARG...
+# ------------------
+# Perform arithmetic evaluation on the ARGs, and store the result in the
+# global $as_val. Take advantage of shells that can avoid forks. The arguments
+# must be portable across $(()) and expr.
+if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then :
+  eval 'as_fn_arith ()
+  {
+    as_val=$(( $* ))
+  }'
+else
+  as_fn_arith ()
+  {
+    as_val=`expr "$@" || test $? -eq 1`
+  }
+fi # as_fn_arith
+
+
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
+  as_expr=expr
+else
+  as_expr=false
+fi
+
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
+  as_basename=basename
+else
+  as_basename=false
+fi
+
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+as_me=`$as_basename -- "$0" ||
+$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
+	 X"$0" : 'X\(//\)$' \| \
+	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X/"$0" |
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\/\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in #(((((
+-n*)
+  case `echo 'xy\c'` in
+  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
+  xy)  ECHO_C='\c';;
+  *)   echo `echo ksh88 bug on AIX 6.1` > /dev/null
+       ECHO_T='	';;
+  esac;;
+*)
+  ECHO_N='-n';;
+esac
+
+rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir 2>/dev/null
+fi
+if (echo >conf$$.file) 2>/dev/null; then
+  if ln -s conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s='ln -s'
+    # ... but there are two gotchas:
+    # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+    # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+    # In both cases, we have to default to `cp -pR'.
+    ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
+      as_ln_s='cp -pR'
+  elif ln conf$$.file conf$$ 2>/dev/null; then
+    as_ln_s=ln
+  else
+    as_ln_s='cp -pR'
+  fi
+else
+  as_ln_s='cp -pR'
+fi
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
+
+
+# as_fn_mkdir_p
+# -------------
+# Create "$as_dir" as a directory, including parents if necessary.
+as_fn_mkdir_p ()
+{
+
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || eval $as_mkdir_p || {
+    as_dirs=
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
+$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$as_dir" : 'X\(//\)[^/]' \| \
+	 X"$as_dir" : 'X\(//\)$' \| \
+	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$as_dir" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+      test -d "$as_dir" && break
+    done
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir"
+
+
+} # as_fn_mkdir_p
+if mkdir -p . 2>/dev/null; then
+  as_mkdir_p='mkdir -p "$as_dir"'
+else
+  test -d ./-p && rmdir ./-p
+  as_mkdir_p=false
+fi
+
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
+
+# Sed expression to map a string onto a valid CPP name.
+as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
+
+# Sed expression to map a string onto a valid variable name.
+as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
+
+
+exec 6>&1
+## ----------------------------------- ##
+## Main body of $CONFIG_STATUS script. ##
+## ----------------------------------- ##
+_ASEOF
+test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# Save the log message, to keep $0 and so on meaningful, and to
+# report actual input values of CONFIG_FILES etc. instead of their
+# values after options handling.
+ac_log="
+This file was extended by $as_me, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
+
+  CONFIG_FILES    = $CONFIG_FILES
+  CONFIG_HEADERS  = $CONFIG_HEADERS
+  CONFIG_LINKS    = $CONFIG_LINKS
+  CONFIG_COMMANDS = $CONFIG_COMMANDS
+  $ $0 $@
+
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
+_ACEOF
+
+case $ac_config_files in *"
+"*) set x $ac_config_files; shift; ac_config_files=$*;;
+esac
+
+
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+# Files that config.status was made for.
+config_files="$ac_config_files"
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+ac_cs_usage="\
+\`$as_me' instantiates files and other configuration actions
+from templates according to the current configuration.  Unless the files
+and actions are specified as TAGs, all are instantiated by default.
+
+Usage: $0 [OPTION]... [TAG]...
+
+  -h, --help       print this help, then exit
+  -V, --version    print version number and configuration settings, then exit
+      --config     print configuration, then exit
+  -q, --quiet, --silent
+                   do not print progress messages
+  -d, --debug      don't remove temporary files
+      --recheck    update $as_me by reconfiguring in the same conditions
+      --file=FILE[:TEMPLATE]
+                   instantiate the configuration file FILE
+
+Configuration files:
+$config_files
+
+Report bugs to the package provider."
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
+ac_cs_version="\\
+config.status
+configured by $0, generated by GNU Autoconf 2.69,
+  with options \\"\$ac_cs_config\\"
+
+Copyright (C) 2012 Free Software Foundation, Inc.
+This config.status script is free software; the Free Software Foundation
+gives unlimited permission to copy, distribute and modify it."
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+test -n "\$AWK" || AWK=awk
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# The default lists apply if the user does not specify any file.
+ac_need_defaults=:
+while test $# != 0
+do
+  case $1 in
+  --*=?*)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
+    ac_shift=:
+    ;;
+  --*=)
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=
+    ac_shift=:
+    ;;
+  *)
+    ac_option=$1
+    ac_optarg=$2
+    ac_shift=shift
+    ;;
+  esac
+
+  case $ac_option in
+  # Handling of the options.
+  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
+    ac_cs_recheck=: ;;
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    $as_echo "$ac_cs_version"; exit ;;
+  --config | --confi | --conf | --con | --co | --c )
+    $as_echo "$ac_cs_config"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
+    debug=: ;;
+  --file | --fil | --fi | --f )
+    $ac_shift
+    case $ac_optarg in
+    *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;;
+    '') as_fn_error $? "missing file argument" ;;
+    esac
+    as_fn_append CONFIG_FILES " '$ac_optarg'"
+    ac_need_defaults=false;;
+  --he | --h |  --help | --hel | -h )
+    $as_echo "$ac_cs_usage"; exit ;;
+  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
+  | -silent | --silent | --silen | --sile | --sil | --si | --s)
+    ac_cs_silent=: ;;
+
+  # This is an error.
+  -*) as_fn_error $? "unrecognized option: \`$1'
+Try \`$0 --help' for more information." ;;
+
+  *) as_fn_append ac_config_targets " $1"
+     ac_need_defaults=false ;;
+
+  esac
+  shift
+done
+
+ac_configure_extra_args=
+
+if $ac_cs_silent; then
+  exec 6>/dev/null
+  ac_configure_extra_args="$ac_configure_extra_args --silent"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+if \$ac_cs_recheck; then
+  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  shift
+  \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
+  CONFIG_SHELL='$SHELL'
+  export CONFIG_SHELL
+  exec "\$@"
+fi
+
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  $as_echo "$ac_log"
+} >&5
+
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+
+# Handling of arguments.
+for ac_config_target in $ac_config_targets
+do
+  case $ac_config_target in
+    "src/Makevars") CONFIG_FILES="$CONFIG_FILES src/Makevars" ;;
+
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
+  esac
+done
+
+
+# If the user did not use the arguments to specify the items to instantiate,
+# then the envvar interface is used.  Set only those that are not.
+# We use the long form for the default assignment because of an extremely
+# bizarre bug on SunOS 4.1.3.
+if $ac_need_defaults; then
+  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
+fi
+
+# Have a temporary directory for convenience.  Make it in the build tree
+# simply because there is no reason against having it here, and in addition,
+# creating and moving files from /tmp can sometimes cause problems.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
+$debug ||
+{
+  tmp= ac_tmp=
+  trap 'exit_status=$?
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
+' 0
+  trap 'as_fn_exit 1' 1 2 13 15
+}
+# Create a (secure) tmp directory for tmp files.
+
+{
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
+  test -d "$tmp"
+}  ||
+{
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
+} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
+
+# Set up the scripts for CONFIG_FILES section.
+# No need to generate them if there are no CONFIG_FILES.
+# This happens for instance with `./config.status config.h'.
+if test -n "$CONFIG_FILES"; then
+
+
+ac_cr=`echo X | tr X '\015'`
+# On cygwin, bash can eat \r inside `` if the user requested igncr.
+# But we know of no other shell where ac_cr would be empty at this
+# point, so we can use a bashism as a fallback.
+if test "x$ac_cr" = x; then
+  eval ac_cr=\$\'\\r\'
+fi
+ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
+if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
+  ac_cs_awk_cr='\\r'
+else
+  ac_cs_awk_cr=$ac_cr
+fi
+
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
+_ACEOF
+
+
+{
+  echo "cat >conf$$subs.awk <<_ACEOF" &&
+  echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
+  echo "_ACEOF"
+} >conf$$subs.sh ||
+  as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'`
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  . ./conf$$subs.sh ||
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+
+  ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X`
+  if test $ac_delim_n = $ac_delim_num; then
+    break
+  elif $ac_last_try; then
+    as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
+  fi
+done
+rm -f conf$$subs.sh
+
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
+_ACEOF
+sed -n '
+h
+s/^/S["/; s/!.*/"]=/
+p
+g
+s/^[^!]*!//
+:repl
+t repl
+s/'"$ac_delim"'$//
+t delim
+:nl
+h
+s/\(.\{148\}\)..*/\1/
+t more1
+s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/
+p
+n
+b repl
+:more1
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t nl
+:delim
+h
+s/\(.\{148\}\)..*/\1/
+t more2
+s/["\\]/\\&/g; s/^/"/; s/$/"/
+p
+b
+:more2
+s/["\\]/\\&/g; s/^/"/; s/$/"\\/
+p
+g
+s/.\{148\}//
+t delim
+' <conf$$subs.awk | sed '
+/^[^""]/{
+  N
+  s/\n//
+}
+' >>$CONFIG_STATUS || ac_write_fail=1
+rm -f conf$$subs.awk
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+_ACAWK
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
+  for (key in S) S_is_set[key] = 1
+  FS = ""
+
+}
+{
+  line = $ 0
+  nfields = split(line, field, "@")
+  substed = 0
+  len = length(field[1])
+  for (i = 2; i < nfields; i++) {
+    key = field[i]
+    keylen = length(key)
+    if (S_is_set[key]) {
+      value = S[key]
+      line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3)
+      len += length(value) + length(field[++i])
+      substed = 1
+    } else
+      len += 1 + keylen
+  }
+
+  print line
+}
+
+_ACAWK
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
+  sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
+else
+  cat
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
+  || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
+_ACEOF
+
+# VPATH may cause trouble with some makes, so we remove sole $(srcdir),
+# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[	 ]*VPATH[	 ]*=[	 ]*/{
+h
+s///
+s/^/:/
+s/[	 ]*$/:/
+s/:\$(srcdir):/:/g
+s/:\${srcdir}:/:/g
+s/:@srcdir@:/:/g
+s/^:*//
+s/:*$//
+x
+s/\(=[	 ]*\).*/\1/
+G
+s/\n//
+s/^[^=]*=[	 ]*$//
+}'
+fi
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+fi # test -n "$CONFIG_FILES"
+
+
+eval set X "  :F $CONFIG_FILES      "
+shift
+for ac_tag
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$ac_tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
+	 # because $ac_f cannot contain `:'.
+	 test -f "$ac_f" ||
+	   case $ac_f in
+	   [\\/$]*) false;;
+	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+	   esac ||
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
+      esac
+      case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
+      as_fn_append ac_file_inputs " '$ac_f'"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input='Generated from '`
+	  $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g'
+	`' by configure.'
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5
+$as_echo "$as_me: creating $ac_file" >&6;}
+    fi
+    # Neutralize special characters interpreted by sed in replacement strings.
+    case $configure_input in #(
+    *\&* | *\|* | *\\* )
+       ac_sed_conf_input=`$as_echo "$configure_input" |
+       sed 's/[\\\\&|]/\\\\&/g'`;; #(
+    *) ac_sed_conf_input=$configure_input;;
+    esac
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
+    esac
+    ;;
+  esac
+
+  ac_dir=`$as_dirname -- "$ac_file" ||
+$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	 X"$ac_file" : 'X\(//\)[^/]' \| \
+	 X"$ac_file" : 'X\(//\)$' \| \
+	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
+$as_echo X"$ac_file" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)[^/].*/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\/\)$/{
+	    s//\1/
+	    q
+	  }
+	  /^X\(\/\).*/{
+	    s//\1/
+	    q
+	  }
+	  s/.*/./; q'`
+  as_dir="$ac_dir"; as_fn_mkdir_p
+  ac_builddir=.
+
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
+  ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'`
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
+
+case $srcdir in
+  .)  # We are building in place.
+    ac_srcdir=.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
+    ac_srcdir=$srcdir$ac_dir_suffix;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
+esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
+
+_ACEOF
+
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+ac_sed_dataroot='
+/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p'
+case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+  s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
+_ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
+cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
+ac_sed_extra="$ac_vpsub
+$extrasub
+_ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
+:t
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
+s|@configure_input@|$ac_sed_conf_input|;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@top_build_prefix@&$ac_top_build_prefix&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+$ac_datarootdir_hack
+"
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&5
+$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined" >&2;}
+
+  rm -f "$ac_tmp/stdin"
+  case $ac_file in
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
+  esac \
+  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+ ;;
+
+
+
+  esac
+
+done # for ac_tag
+
+
+as_fn_exit 0
+_ACEOF
+ac_clean_files=$ac_clean_files_save
+
+test $ac_write_fail = 0 ||
+  as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5
+
+
+# configure is writing to config.log, and then calls config.status.
+# config.status does its own redirection, appending to config.log.
+# Unfortunately, on DOS this fails, as config.log is still kept open
+# by configure, so config.status won't be able to write to it; its
+# output is simply discarded.  So we exec the FD to /dev/null,
+# effectively closing config.log, so it can be properly (re)opened and
+# appended to by config.status.  When coming back to configure, we
+# need to make the FD available again.
+if test "$no_create" != yes; then
+  ac_cs_success=:
+  ac_config_status_args=
+  test "$silent" = yes &&
+    ac_config_status_args="$ac_config_status_args --quiet"
+  exec 5>/dev/null
+  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
+  exec 5>>config.log
+  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
+  # would make configure fail if this is the last instruction.
+  $ac_cs_success || as_fn_exit 1
+fi
+if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5
+$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;}
+fi
+
+
diff --git a/configure.ac b/configure.ac
new file mode 100644
index 0000000..2b2c5ff
--- /dev/null
+++ b/configure.ac
@@ -0,0 +1,210 @@
+## 
+## This file is part of RGL
+##
+## It uses some R-specific macros, so process it in two steps:
+## 1. Copy m4/R.m4 from the R source directory to rgl/aclocal.m4
+## 2. Process configure.ac with autoconf to produce a configure script.
+## NB:  the files in src/build/autoconf may need updating for a new
+##      version of autoconf
+##
+##
+## $Id: configure.ac 1372 2015-10-15 19:47:06Z murdoch $
+##
+
+AC_PREREQ(2.50)
+
+## ---[ VERSION ]-------------------------------------------------------------
+
+AC_INIT()
+AC_CONFIG_AUX_DIR(src/build/autoconf)
+
+## pick up compiler as will be used by R CMD INSTALL/SHLIB
+if test -n "${R_HOME}"; then
+  CC=`${R_HOME}/bin/R CMD config CC`
+  CPP=`${R_HOME}/bin/R CMD config CPP`
+  CFLAGS=`${R_HOME}/bin/R CMD config CFLAGS`
+  CXX=`${R_HOME}/bin/R CMD config CXX`
+  CXXFLAGS=`${R_HOME}/bin/R CMD config CXXFLAGS`
+fi
+
+AC_PROG_CPP
+AC_PROG_CC
+
+R_GCC4_VISIBILITY
+
+if test `uname` = "Darwin" ; then
+  darwin="yes"
+  ## we want the *build* cputype and not the host one.
+  cmd=`echo $CC $CFLAGS | grep -E 'x86_64|ppc64|-m64'`
+  if test -n "$cmd"; then
+    have_64bit="yes"
+  else
+    have_64bit="no"
+  fi 
+else
+  darwin="no"
+fi
+
+## --- LibPNG ----------------------------------------------------------------
+
+AC_ARG_ENABLE([libpng],
+[  --disable-libpng           compile without PNG image support]
+)
+AC_ARG_ENABLE([libpng-config],
+[  --disable-libpng-config    disable libpng-config test and configuration]
+)
+AC_ARG_ENABLE([libpng-dynamic],
+[  --disable-libpng-dynamic   disable dynamic libpng linkage, force static version linkage (only with --enable-libpng-config)]
+)
+
+if test "x$enable_libpng" != "xno"; then
+
+  if test "x$enable_libpng_config" != "xno"; then
+    AC_CHECK_PROG([HAVE_LIBPNG_CONFIG],[libpng-config],[yes],[no])
+  fi
+
+  if test "x$HAVE_LIBPNG_CONFIG" = "xyes" ; then
+    AC_MSG_NOTICE([using libpng-config])
+    CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H `libpng-config --I_opts`"
+    if test "x$enable_libpng_dynamic" != "xno"; then
+      AC_MSG_NOTICE([using libpng dynamic linkage])
+      LIBS="${LIBS} `libpng-config --ldflags`"
+    else
+      AC_MSG_NOTICE([using libpng static linkage])
+      LIBS="${LIBS} `libpng-config --static --L_opts`/libpng.a"
+    fi
+  else
+    AC_MSG_CHECKING([libpng])
+    save_LIBS="${LIBS}"
+    save_CPPFLAGS="${CPPFLAGS}"
+    AC_CHECK_HEADERS(png.h)
+    AC_CHECK_LIB(png, png_read_update_info)
+    if test "${ac_cv_header_png_h}"; then
+      if test "${ac_cv_lib_png_png_read_update_info}"; then
+	CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H"
+	LIBS="${LIBS} -lpng"
+	AC_MSG_NOTICE([libpng header and lib found])
+	if test "x$enable_libpng_dynamic" != "xno"; then
+	  AC_MSG_NOTICE([using libpng dynamic linkage])
+	else
+	  AC_MSG_NOTICE([using libpng static linkage])
+	fi
+      else
+	LIBS=${save_LIBS}
+	CPPFLAGS=${save_CPPFLAGS}
+	AC_MSG_NOTICE([libpng header and lib not found])
+      fi
+    fi
+  fi
+
+fi
+
+# ---[ X11 ]------------------------------------------------------------------
+
+  AC_PATH_X
+  if test x$no_x = xyes ; then
+    AC_MSG_ERROR([X11 not found but required, configure aborted.])
+  fi
+  if test -n "${x_includes}"; then
+    CPPFLAGS="${CPPFLAGS} -I${x_includes}"
+  fi
+  if test -n "${x_libraries}"; then
+    LIBS="${LIBS} -L${x_libraries} -lX11"
+  else
+    LIBS="${LIBS} -lX11"
+  fi
+  if test $darwin = yes; then
+    CPPFLAGS="${CPPFLAGS} -DDarwin"
+    # Apple's OpenGL is different from the X11 one - it must be loaded *before* X11
+    if test -e /System/Library/Frameworks/OpenGL.framework ; then
+      CPPFLAGS="-I/System/Library/Frameworks/OpenGL.framework/Headers ${CPPFLAGS} -DNO_GL_PREFIX"
+      # OSX 10.5 messes up X11; this works around it
+      LIBS="-framework OpenGL -dylib_file /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib ${LIBS}"
+    fi
+    if test -e /System/Library/Frameworks/GLKit.framework ; then
+      LIBS="-framework GLKit ${LIBS}"
+    fi    
+    # some X11 installations on OSX 10.5 feature -rpath which doesn't work when used in
+    # conjunction with 10.4u SDK (and is redundant anyway since OS X always uses full paths)
+    if test rpath`echo "${LIBS}" | sed -n 's/.*-Wl,-rpath,.*/Yes/p' 2>/dev/null` = rpathYes; then
+      LIBS=`echo "${LIBS}" | sed 's:-Wl,-rpath,[[^ ]]*::'`
+    fi
+    # X11 must come *after* the OpenGL stuff
+    CPPFLAGS="${CPPFLAGS} -I/opt/X11/include"
+  fi
+
+## --- OpenGL ----------------------------------------------------------------
+
+AC_ARG_WITH(gl-includes,
+[  --with-gl-includes=DIR  specify location of OpenGL headers],
+[CPPFLAGS="${CPPFLAGS} -I${withval}"]
+)
+
+if test $darwin != yes; then
+  AC_CHECK_HEADERS(GL/gl.h GL/glu.h)
+  if test "x$ac_cv_header_GL_gl_h" = xno; then
+    AC_ERROR([missing required header GL/gl.h])
+  fi
+  if test "x$ac_cv_header_GL_glu_h" = xno; then
+    AC_ERROR([missing required header GL/glu.h])
+  fi
+fi
+
+AC_ARG_WITH(gl-libs,
+[  --with-gl-libs=DIR      specify location of OpenGL libs],
+[LDFLAGS="${LDFLAGS} -L${withval}"
+L_LIB="-L${withval}"]
+)
+
+AC_ARG_WITH(gl-libname,
+[  --with-gl-libname=NAME  specify Library name (defaults to "GL")], 
+[lGL=${withval}], [lGL=GL]
+)
+AC_CHECK_LIB($lGL, glEnd)
+this=`eval echo '${'$as_ac_Lib'}'`
+if test "x$this" != xyes; then
+  AC_ERROR([missing required library ${lGL}])
+fi
+
+AC_ARG_WITH(glu-libname,
+[  --with-glu-libname=NAME specify GLU Library name (defaults to "GLU")],
+[lGLU=${withval}], [lGLU=GLU]
+)
+AC_CHECK_LIB($lGLU, gluProject)
+this=`eval echo '${'$as_ac_Lib'}'`
+if test "x$this" != xyes; then
+  AC_ERROR([missing required library ${lGLU}])
+fi
+
+if test x$L_LIB != x; then
+  LIBS="${L_LIB} ${LIBS}"
+fi
+
+## --- FTGL ------------------------------------------------------------------
+
+AC_ARG_ENABLE([ftgl],
+[  --disable-ftgl             compile without FTGL font support]
+)
+if test "x$enable_ftgl" != "xno"; then
+  if test "x$darwin" = "xyes"; then
+    AC_MSG_NOTICE([Darwin, so ensuring /opt/X11/bin is at the head of the PATH...])
+    PATH=/opt/X11/bin:${PATH}
+  fi
+  AC_CHECK_PROG([HAVE_FREETYPE_CONFIG],[freetype-config],[yes],[no])
+  if test "x$HAVE_FREETYPE_CONFIG" = "xyes"; then
+    CPPFLAGS="${CPPFLAGS} -DHAVE_FREETYPE -Iext/ftgl `freetype-config --cflags`"
+    LIBS="${LIBS} `freetype-config --libs`"
+    AC_MSG_NOTICE([using Freetype and FTGL])
+  fi
+else
+  AC_MSG_NOTICE([compiling without FTGL support])
+fi
+
+## --- Output ----------------------------------------------------------------
+
+AC_SUBST(CPPFLAGS)
+AC_SUBST(CXXFLAGS)
+AC_SUBST(LIBS)
+
+AC_OUTPUT(src/Makevars)
+
diff --git a/configure.win b/configure.win
new file mode 100755
index 0000000..f45310a
--- /dev/null
+++ b/configure.win
@@ -0,0 +1,102 @@
+#
+# png pixmap support
+# test zlib and libpng libraries are available 
+#
+echo "  configure.win32..."
+
+# --- win32 base configuration -----------------------------------------------
+
+CPPFLAGS=
+CXXFLAGS="-fno-exceptions -fno-rtti"
+LIBS="-lgdi32 -lopengl32 -lglu32"
+LOCAL_SOFT=`R CMD config LOCAL_SOFT`
+
+# --- for pre 2.9.0 compatibility
+
+if test -z "$R_PACKAGE_DIR" ; then
+     R_PACKAGE_DIR=${DPKG}
+fi
+
+# --- libpng -----------------------------------------------------------------
+
+echo -n "  checking for zlib..."
+if [ -e "${LOCAL_SOFT}/lib${R_ARCH_BIN}/libz.a" ]; then
+   CPPFLAGS="${CPPFLAGS} "
+   LIBS="$LIBS -lz"
+   havezlib=yes   
+elif [ -e "${R_HOME}/bin${R_ARCH_BIN}/Rzlib.dll" ]; then
+   CPPFLAGS="${CPPFLAGS} -I${R_HOME}/include "
+   LIBS="$LIBS -L${R_HOME}/bin${R_ARCH_BIN} -lRzlib "
+   havezlib=yes
+elif [ -e "${R_HOME}/src/extra/zlib/libz.a" ]; then
+   CPPFLAGS="${CPPFLAGS} -I${R_HOME}/src/extra/zlib "
+   LIBS="$LIBS -L${R_HOME}/src/extra/zlib -lz"
+   havezlib=yes
+else
+   havezlib=no
+fi
+echo ${havezlib}
+
+if [ "${havezlib}" = "yes" ]; then
+  echo -n "  checking for libpng..."
+  if [ -n "${HAVE_PNG}" ]; then
+    echo "yes"
+    CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H "
+    LIBS="-lpng $LIBS "
+  elif [ -e "${LOCAL_SOFT}/lib${R_ARCH_BIN}/libpng.a" ]; then
+    echo "yes"
+    CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H "
+    LIBS="-lpng $LIBS "  
+  elif [ -e "${R_HOME}/src/gnuwin32/bitmap/libpng/libpng.a" ]; then
+    echo "yes"
+    CPPFLAGS="${CPPFLAGS} -DHAVE_PNG_H -I${R_HOME}/src/gnuwin32/bitmap/libpng "
+    LIBS="-L${R_HOME}/src/gnuwin32/bitmap/libpng -lpng $LIBS "
+  else
+    echo "no"
+  fi
+else
+  echo "  libpng requires zlib, so not installed."
+fi
+
+# --- freetype and ftgl ------------------------------------------------------
+
+if [ "${havezlib}" = "yes" ]; then
+  echo -n "  checking for freetype..."
+  if [ -n "$LIB_FREETYPE" ]; then
+    echo "yes, LIB_FREETYPE=$LIB_FREETYPE" 
+    mkdir -p $R_PACKAGE_DIR/libs${R_ARCH}
+    cp $LIB_FREETYPE/bin${R_ARCH_BIN}/freetype6.dll $R_PACKAGE_DIR/libs${R_ARCH}
+    if [ -e "${R_HOME}/bin${R_ARCH_BIN}/Rzlib.dll" ]; then
+      cp ${R_HOME}/bin${R_ARCH_BIN}/Rzlib.dll $R_PACKAGE_DIR/libs${R_ARCH}/zlib1.dll
+    else
+      echo "  Note:  freetype may require zlib1.dll"
+    fi
+    CPPFLAGS="${CPPFLAGS} -Iext/ftgl -I${LIB_FREETYPE}/include -I${LIB_FREETYPE}/include/freetype2 -DHAVE_FREETYPE"
+    LIBS="-L$R_PACKAGE_DIR/libs${R_ARCH} -lfreetype6 $LIBS "
+  else
+    echo "no, LIB_FREETYPE undefined"
+  fi
+else
+  echo "  freetype requires zlib, so not installed."
+fi
+
+# --- dump configuration -----------------------------------------------------
+# Debugging code removed -- cat was hanging on WinBuilder
+#cat <<EOF
+#---------- win32 configuration: ----------
+#PKG_CPPFLAGS = $CPPFLAGS
+#PKG_CXXFLAGS = $CXXFLAGS
+#PKG_LIBS     = $LIBS
+#------------------------------------------  
+#EOF
+
+# --- output Makevars --------------------------------------------------------
+
+rm src/Makevars
+sed \
+-e "s^@CPPFLAGS@^$CPPFLAGS^" \
+-e "s^@CXXFLAGS@^$CXXFLAGS^" \
+-e "s^@LIBS@^$LIBS^" \
+-e "s^@C_VISIBILITY@^#^" \
+src/Makevars.in >src/Makevars
+
diff --git a/demo/00Index b/demo/00Index
new file mode 100644
index 0000000..f3d838c
--- /dev/null
+++ b/demo/00Index
@@ -0,0 +1,13 @@
+rgl           RGL Demonstration
+hist3d        3D histogram using basic building blocks
+bivar         Bivariate densities: kernel smoothing using rgl.surface and alpha-channel (requires MASS package)
+abundance     Animal abundance, visualization of multi-dimension data using multiple techniques
+lsystem       Plant modelling using a turtle and L-system
+subdivision   Subdivision surfaces using generic meshes (preview of generic 3D interface)
+regression    Bivariate regression
+envmap        Environment mapping
+shapes3d      3D shape primitives (cones, ellipsoids, cubes), some taken from qmesh3d
+lollipop3d    "Lollipop" plots (3D scatterplot with lines between points and a surface)
+flag	      play3d() function that waves a flag
+mouseCallbacks	Standard mouse handlers implemented in R, for a stereo view
+stereo	      Stereo views using a random dot stereogram & an anaglyph
diff --git a/demo/abundance.r b/demo/abundance.r
new file mode 100644
index 0000000..2b8d3da
--- /dev/null
+++ b/demo/abundance.r
@@ -0,0 +1,48 @@
+# RGL-Demo: animal abundance
+# Authors: Oleg Nenadic, Daniel Adler
+# $Id: abundance.r 564 2007-02-22 09:56:01Z dmurdoch $
+
+rgl.demo.abundance <- function()
+{
+  open3d()
+  clear3d("all")               # remove all shapes, lights, bounding-box, and restore viewpoint
+  
+  # Setup environment:
+  bg3d(col="#cccccc")     # setup background
+  light3d()               # setup head-light
+  
+  # Importing animal data (created with wisp)
+  terrain<-dget(system.file("demodata/region.dat",package="rgl"))
+  pop<-dget(system.file("demodata/population.dat",package="rgl"))
+  
+  # Define colors for terrain
+  zlim <- range(terrain)
+  zlen <- zlim[2] - zlim[1] + 1
+  colorlut <- terrain.colors(82) 
+  col1 <- colorlut[9*sqrt(3.6*(terrain-zlim[1])+2)]
+  
+  # Set color to (water-)blue for regions with zero 'altitude' 
+  col1[terrain==0]<-"#0000FF"
+  
+  # Add terrain surface shape (i.e. population density):
+  surface3d( 
+      1:100,seq(1,60,length=100),terrain,
+      col=col1,spec="#000000", ambient="#333333", back="lines"
+  )
+  
+  # Define colors for simulated populations (males:blue, females:red):
+  col2<-pop[,4]
+  col2[col2==0]<-"#3333ff"
+  col2[col2==1]<-"#ff3333"
+  
+  # Add simulated populations as sphere-set shape
+  spheres3d(
+    pop[,1],
+    pop[,2],
+    terrain[cbind( ceiling(pop[,1]),ceiling(pop[,2]*10/6) )]+0.5,
+    radius=0.2*pop[,3], col=col2, alpha=(1-(pop[,5])/10 )
+  )
+
+}
+rgl.demo.abundance()
+
diff --git a/demo/bivar.r b/demo/bivar.r
new file mode 100644
index 0000000..a3312fc
--- /dev/null
+++ b/demo/bivar.r
@@ -0,0 +1,49 @@
+# rgl demo: rgl-bivar.r
+# author: Daniel Adler
+# $Id: bivar.r 564 2007-02-22 09:56:01Z dmurdoch $
+
+rgl.demo.bivar <- function()
+{
+  require(MASS);
+  
+  # parameters:
+  n<-50; ngrid<-40
+  
+  # generate samples:
+  set.seed(31415)
+  x<-rnorm(n); y<-rnorm(n)
+  
+  # estimate non-parameteric density surface via kernel smoothing
+  denobj<-kde2d(x, y, n=ngrid)
+  den.z <-denobj$z
+  
+  # generate parametric density surface of a bivariate normal distribution
+  xgrid <- denobj$x
+  ygrid <- denobj$y
+  bi.z <- dnorm(xgrid)%*%t(dnorm(ygrid))
+  
+  # visualize:
+  zscale<-20
+  
+  # New window
+  open3d()
+  
+  # clear scene:
+  clear3d("all")
+  
+  # setup env:
+  bg3d(color="#887777")
+  light3d()
+  
+  # Draws the simulated data as spheres on the baseline
+  spheres3d(x,y,rep(0,n),radius=0.1,color="#CCCCFF")
+  
+  # Draws non-parametric density
+  surface3d(xgrid,ygrid,den.z*zscale,color="#FF2222",alpha=0.5)
+  
+  # Draws parametric density
+  surface3d(xgrid,ygrid,bi.z*zscale,color="#CCCCFF",front="lines") 
+}
+
+rgl.demo.bivar()
+
diff --git a/demo/envmap.r b/demo/envmap.r
new file mode 100644
index 0000000..85ae02f
--- /dev/null
+++ b/demo/envmap.r
@@ -0,0 +1,23 @@
+# RGL-Demo: environment mapping
+# Author: Daniel Adler
+# $Id$
+
+rgl.demo.envmap <- function()
+{
+  open3d()
+  # Clear scene:
+  clear3d("all")
+  light3d()
+  bg3d(sphere=T, color="white", back="filled"
+  , texture=system.file("textures/refmap.png",package="rgl")
+  )
+  data(volcano)
+
+  surface3d( 10*1:nrow(volcano),10*1:ncol(volcano),5*volcano
+  , texture=system.file("textures/refmap.png",package="rgl")
+  , texenvmap=TRUE
+  , color = "white"
+  )
+}
+rgl.demo.envmap()
+
diff --git a/demo/flag.R b/demo/flag.R
new file mode 100644
index 0000000..5cff8ae
--- /dev/null
+++ b/demo/flag.R
@@ -0,0 +1,26 @@
+
+wave <- function(time) {
+  x <- seq(0,2, len=100)
+  
+  wavefn <- function(x) x * sin(-5*time + 1.5 * (x/2) * 2*pi)/10
+  deriv <- function(x) (wavefn(x + 0.01) - wavefn(x - 0.01))/0.02
+
+  arclen <- cumsum(sqrt(1 + deriv(x)^2))*(x[2]-x[1])
+  keep <- arclen < 2
+  x <- x[keep]
+  y <- matrix(wavefn(x), length(x),20)
+  z <- matrix(seq(0,1, len=20), length(x), 20, byrow=TRUE)
+  arclen <- arclen[keep]
+  
+  par3d(skipRedraw = TRUE)
+  if (nrow(rgl.ids())) rgl.pop()
+  surface3d(x,y,z, texture_s=matrix(arclen/2, length(x), 20), texture_t=z, col="white")
+  c(list(skipRedraw = FALSE), spin(time))
+}
+
+open3d()
+material3d(texture = system.file("textures","rgl2.png", package="rgl"))
+spin <- spin3d(rpm=6,axis=c(0,0,1))
+if (!rgl.useNULL())
+  play3d(wave, 10, startTime = 5)
+
diff --git a/demo/hist3d.r b/demo/hist3d.r
new file mode 100644
index 0000000..315b8cf
--- /dev/null
+++ b/demo/hist3d.r
@@ -0,0 +1,114 @@
+
+##########
+### 3D HIST EXAMPLE:
+##########
+
+################################################################################
+
+##### Required functions 'binplot' and 'hist3d':
+
+binplot.3d<-function(x,y,z,alpha=1,topcol="#ff0000",sidecol="#aaaaaa")
+{
+  save <- par3d(skipRedraw=TRUE)
+  on.exit(par3d(save))
+    
+  x1<-c(rep(c(x[1],x[2],x[2],x[1]),3),rep(x[1],4),rep(x[2],4))
+  z1<-c(rep(0,4),rep(c(0,0,z,z),4))
+  y1<-c(y[1],y[1],y[2],y[2],rep(y[1],4),rep(y[2],4),rep(c(y[1],y[2],y[2],y[1]),2))
+  x2<-c(rep(c(x[1],x[1],x[2],x[2]),2),rep(c(x[1],x[2],rep(x[1],3),rep(x[2],3)),2))
+  z2<-c(rep(c(0,z),4),rep(0,8),rep(z,8) )
+  y2<-c(rep(y[1],4),rep(y[2],4),rep(c(rep(y[1],3),rep(y[2],3),y[1],y[2]),2) )
+  rgl.quads(x1,z1,y1,col=rep(sidecol,each=4),alpha=alpha)
+  rgl.quads(c(x[1],x[2],x[2],x[1]),rep(z,4),c(y[1],y[1],y[2],y[2]),
+              col=rep(topcol,each=4),alpha=1) 
+  rgl.lines(x2,z2,y2,col="#000000")
+}
+
+hist3d<-function(x,y=NULL,nclass="auto",alpha=1,col="#ff0000",scale=10)
+  {
+  save <- par3d(skipRedraw=TRUE)
+  on.exit(par3d(save))
+  xy <- xy.coords(x,y)
+  x <- xy$x
+  y <- xy$y
+  n<-length(x)
+  if (nclass == "auto") { nclass<-ceiling(sqrt(nclass.Sturges(x))) }
+  breaks.x <- seq(min(x),max(x),length=(nclass+1))
+  breaks.y <- seq(min(y),max(y),length=(nclass+1))
+  z<-matrix(0,(nclass),(nclass))
+  for (i in 1:nclass) 
+    {
+    for (j in 1:nclass) 
+      {
+      z[i, j] <- (1/n)*sum(x < breaks.x[i+1] & y < breaks.y[j+1] & 
+                            x >= breaks.x[i] & y >= breaks.y[j])
+      binplot.3d(c(breaks.x[i],breaks.x[i+1]),c(breaks.y[j],breaks.y[j+1]),
+                 scale*z[i,j],alpha=alpha,topcol=col)
+      }
+    }
+}
+################################################################################
+
+rgl.open()
+
+rgl.bg(color="gray")
+rgl.light()
+
+# Drawing a 'bin' for given coordinates:
+binplot.3d(c(-0.5,0.5),c(4.5,5.5),2,alpha=0.6)
+
+# Setting the viewpoint ('theta' and 'phi' have the same meaning as in persp):
+rgl.viewpoint(theta=40,phi=40)
+
+# Choosing a lightgrey background:
+rgl.bg(col="#cccccc")
+
+
+##### QUADS FORMING BIN:
+
+# Waiting for user-input to create next scenery:
+# readline()
+
+rgl.open()
+
+# Defining transparency and colors:
+alpha<-0.7; topcol<-"#ff0000"; sidecol<-"#aaaaaa"
+
+# Setting up coordinates for the quads and adding them to the scene:
+y<-x<-c(-1,1) ; z<-4; of<-0.3
+x12<-c(x[1],x[2],x[2],x[1]); x11<-rep(x[1],4); x22<-rep(x[2],4)
+z00<-rep(0,4); z0z<-c(0,0,z,z); zzz<-rep(z,4); y11<-rep(y[1],4)
+y1122<-c(y[1],y[1],y[2],y[2]); y12<-c(y[1],y[2],y[2],y[1]); y22<-rep(y[2],4)
+
+rgl.quads(c(x12,x12,x11-of,x12,x22+of,x12),
+          c(z00-of,rep(z0z,4),zzz+of),
+          c(y1122,y11-of,y12,y22+of,y12,y1122),
+          col=rep(c(rep(sidecol,5),topcol),each=4),alpha=c(rep(alpha,5),1))
+
+# Setting up coordinates for the border-lines of the quads and drawing them:
+yl1<-c(y[1],y[2],y[1],y[2]); yl2<-c(y[1]-of,y[1]-of)
+xl<-c(rep(x[1],8),rep(x[1]-of,8),rep(c(x[1],x[2]),8),rep(x[2],8),rep(x[2]+of,8))
+zl<-c(0,z,0,z,z+of,z+of,-of,-of,0,0,z,z,0,z,0,z,rep(0,4),rep(z,4),rep(-of,4),
+      rep(z+of,4),z+of,z+of,-of,-of,rep(c(0,z),4),0,0,z,z)
+yl<-c(yl2,y[2]+of,y[2]+of,rep(c(y[1],y[2]),4),y[1],y[1],y[2],y[2],yl2,
+      rep(y[2]+of,4),yl2,y[2],y[2],rep(y[1],4),y[2],y[2],yl1,yl2,y[2]+of,
+      y[2]+of,y[1],y[1],y[2],y[2],yl1)
+
+rgl.lines(xl,zl,yl,col="#000000")
+
+
+##### COMPLETE HISTOGRAM:
+
+# Waiting for user-input to create next scenery:
+# readline()
+
+rgl.open()
+
+# Choosing a lightgrey background:
+rgl.bg(col="#cccccc")
+
+# Setting the rng to a fixed value:
+set.seed(1000)
+
+# Drawing a 3d histogramm of 2500 normaly distributed observations:
+hist3d(rnorm(2500),rnorm(2500),alpha=0.4,nclass=7,scale=30)
diff --git a/demo/lollipop3d.R b/demo/lollipop3d.R
new file mode 100644
index 0000000..ba931ba
--- /dev/null
+++ b/demo/lollipop3d.R
@@ -0,0 +1,153 @@
+
+cone3d <- function(base,tip,rad,n=30,...) {
+  degvec <- seq(0,2*pi,length=n)
+  ax <- tip-base
+  ## what do if ax[1]==0?
+  if (ax[1]!=0) {
+    p1 <- c(-ax[2]/ax[1],1,0)
+    p1 <- p1/sqrt(sum(p1^2))
+    if (p1[1]!=0) {
+      p2 <- c(-p1[2]/p1[1],1,0)
+      p2[3] <- -sum(p2*ax)
+      p2 <- p2/sqrt(sum(p2^2))
+    } else {
+      p2 <- c(0,0,1)
+    }
+  } else if (ax[2]!=0) {
+    p1 <- c(0,-ax[3]/ax[2],1)
+    p1 <- p1/sqrt(sum(p1^2))
+    if (p1[1]!=0) {
+      p2 <- c(0,-p1[3]/p1[2],1)
+      p2[3] <- -sum(p2*ax)
+      p2 <- p2/sqrt(sum(p2^2))
+    } else {
+      p2 <- c(1,0,0)
+    }
+  } else {
+    p1 <- c(0,1,0); p2 <- c(1,0,0)
+  }
+  ecoord2 <- function(theta) {
+    base+rad*(cos(theta)*p1+sin(theta)*p2)
+  }
+    for (i in 1:(n-1)) {
+      li <- ecoord2(degvec[i])
+      lj <- ecoord2(degvec[i+1])
+      triangles3d(c(li[1],lj[1],tip[1]),c(li[2],lj[2],tip[2]),c(li[3],lj[3],tip[3]),...)
+    }   
+}
+
+lollipop3d <- function(data.x,data.y,data.z,surf.fun,surf.n=50,
+                         xlim=range(data.x),
+			 ylim=range(data.y),
+			 zlim=range(data.z),
+                         asp=c(y=1,z=1),
+			 xlab=deparse(substitute(x)),
+			 ylab=deparse(substitute(y)),
+			 zlab=deparse(substitute(z)),
+			 alpha.surf=0.4,
+                         col.surf=fg,col.stem=c(fg,fg),
+                         col.pt="gray",type.surf="line",ptsize,
+                         lwd.stem=2,lit=TRUE,bg="white",fg="black",
+                         col.axes=fg,col.axlabs=fg,
+                         axis.arrow=TRUE,axis.labels=TRUE,
+                         box.col=bg,
+                         axes=c("lines","box")) {
+  axes <- match.arg(axes)
+  col.stem <- rep(col.stem,length=2)
+  x.ticks <- pretty(xlim)
+  x.ticks <- x.ticks[x.ticks>=min(xlim) & x.ticks<=max(xlim)]
+  x.ticklabs <- if (axis.labels) as.character(x.ticks) else NULL
+  y.ticks <- pretty(ylim)
+  y.ticks <- y.ticks[y.ticks>=min(ylim) & y.ticks<=max(ylim)]
+  y.ticklabs <- if (axis.labels) as.character(y.ticks) else NULL
+  z.ticks <- pretty(zlim)
+  z.ticks <- z.ticks[z.ticks>=min(zlim) & z.ticks<=max(zlim)]
+  z.ticklabs <- if (axis.labels) as.character(z.ticks) else NULL
+  if (!missing(surf.fun)) {
+    surf.x <- seq(xlim[1],xlim[2],length=surf.n)
+    surf.y <- seq(ylim[1],ylim[2],length=surf.n)
+    surf.z <- outer(surf.x,surf.y,surf.fun)  ## requires surf.fun be vectorized
+    z.interc <- surf.fun(data.x,data.y)
+    zdiff <- diff(range(c(surf.z,data.z)))
+  } else {
+    z.interc <- rep(min(data.z),length(data.x))
+    zdiff <- diff(range(data.z))
+  }
+  xdiff <- diff(xlim)
+  ydiff <- diff(ylim)
+  y.adj <- if (asp[1]<=0) 1 else asp[1]*xdiff/ydiff
+  data.y <- y.adj*data.y
+  y.ticks <- y.adj*y.ticks
+  ylim <- ylim*y.adj
+  ydiff <- diff(ylim)
+  z.adj <- if (asp[2]<=0) 1 else asp[2]*xdiff/zdiff
+  data.z <- z.adj*data.z
+  if (!missing(surf.fun)) {
+    surf.y <- y.adj*surf.y
+    surf.z <- z.adj*surf.z
+  }
+  z.interc <- z.adj*z.interc
+  z.ticks <- z.adj*z.ticks
+  zlim <- z.adj*zlim
+  open3d()
+  clear3d("all")
+  light3d()
+  bg3d(color=c(bg,fg))
+  if (!missing(surf.fun)) 
+    surface3d(surf.x,surf.y,surf.z,alpha=alpha.surf,
+                front=type.surf,back=type.surf,
+                col=col.surf,lit=lit)
+  if (missing(ptsize)) ptsize <- 0.02*xdiff
+  ## draw points
+  spheres3d(data.x,data.y,data.z,r=ptsize,lit=lit,color=col.pt)
+  ## draw lollipops
+  apply(cbind(data.x,data.y,data.z,z.interc),1,
+        function(X) {
+          lines3d(x=rep(X[1],2),
+                  y=rep(X[2],2),
+                  z=c(X[3],X[4]),
+                  col=ifelse(X[3]>X[4],col.stem[1],
+                    col.stem[2]),lwd=lwd.stem)
+        })
+  bbox <- par3d("bbox")
+  if (axes=="box") {
+    bbox3d(xat=x.ticks,xlab=x.ticklabs,
+             yat=y.ticks,ylab=y.ticklabs,
+             zat=z.ticks,zlab=z.ticklabs,lit=lit)
+  } else if (axes=="lines") { ## set up axis lines
+    bbox <- par3d("bbox")
+    axis3d(edge="x",at=x.ticks,labels=x.ticklabs,
+           col=col.axes,arrow=axis.arrow)
+    axis3d(edge="y",at=y.ticks,labels=y.ticklabs,
+           col=col.axes,arrow=axis.arrow)
+    axis3d(edge="z",at=z.ticks,labels=z.ticklabs,
+           col=col.axes,arrow=axis.arrow)
+    box3d(col=col.axes)
+  }
+  decorate3d(xlab=xlab, ylab=ylab, zlab=zlab, box=FALSE, axes=FALSE, col=col.axlabs)
+}
+
+x <- 1:5
+y <- x*10
+z <- (x+y)/20
+open3d()
+spheres3d(x,y,z)
+axes3d()
+set.seed(1001)
+x <- runif(30)
+y <- runif(30,max=2)
+dfun <- function(x,y) { 2*x+3*y+2*x*y+3*y^2 }
+z <- dfun(x,y)+rnorm(30,sd=0.5)
+## lollipops only
+lollipop3d(x,y,z)
+
+## lollipops plus theoretical surface
+
+lollipop3d(x,y,z,dfun,col.pt="red",col.stem=c("red","blue"))
+## lollipops plus regression fit
+
+linmodel <- lm(z~x+y)
+dfun <- function(x,y) {predict(linmodel,newdata=data.frame(x=x,y=y))}
+lollipop3d(x,y,z,dfun,col.pt="red",col.stem=c("red","blue"))
+
+####
diff --git a/demo/lsystem.r b/demo/lsystem.r
new file mode 100644
index 0000000..45f3872
--- /dev/null
+++ b/demo/lsystem.r
@@ -0,0 +1,192 @@
+# demo: lsystem.r
+# author: Daniel Adler
+# $Id: lsystem.r 491 2006-07-31 13:17:19Z dmurdoch $
+
+#
+# geometry 
+#
+
+deg2rad <- function( degree ) {
+  return( degree*pi/180 )
+}
+
+rotZ.m3x3 <- function( degree ) {
+  kc <- cos(deg2rad(degree))
+  ks <- sin(deg2rad(degree))
+  return( 
+    matrix(
+      c(
+        kc, -ks,   0, 
+        ks,  kc,   0,
+         0,   0,   1
+      ),ncol=3,byrow=T
+    ) 
+  )
+}
+
+rotX.m3x3 <- function( degree ) {
+  kc <- cos(deg2rad(degree))
+  ks <- sin(deg2rad(degree))
+  return(
+    matrix(
+      c(
+         1,   0,   0,
+         0,  kc, -ks,
+         0,  ks,  kc
+      ),ncol=3,byrow=T
+    )
+  )
+}
+
+rotY.m3x3 <- function( degree ) {
+  kc <- cos(deg2rad(degree))
+  ks <- sin(deg2rad(degree))
+  return(
+    matrix(
+      c(
+        kc,   0,   ks,
+         0,   1,    0,
+       -ks,   0,   kc
+      ),ncol=3,byrow=T
+    )
+  )
+}
+
+rotZ <- function( v, degree ) {
+  return ( rotZ.m3x3(degree) %*% v)
+}
+
+rotX <- function( v, degree ) {
+  return ( rotX.m3x3(degree) %*% v)
+}
+
+rotY <- function( v, degree ) {
+  return ( rotY.m3x3(degree) %*% v)
+}
+
+
+#
+# turtle graphics, rgl implementation:
+#
+
+turtle.init <- function(pos=c(0,0,0),head=0,pitch=90,roll=0,level=0) {
+  rgl.clear("all")
+  rgl.bg(color="black")
+  rgl.light()
+  return( list(pos=pos,head=head,pitch=pitch,roll=roll,level=level) )
+}
+
+
+turtle.move <- function(turtle, steps, color) {
+  
+  rm <- rotX.m3x3(turtle$pitch) %*% rotY.m3x3(turtle$head) %*% rotZ.m3x3(turtle$roll)
+  
+  from <- as.vector( turtle$pos )  
+  dir  <- rm %*% c(0,0,-1)
+  to   <- from + dir * steps
+    
+  x <- c( from[1], to[1] )
+  y <- c( from[2], to[2] )
+  z <- c( from[3], to[3] )
+  rgl.lines(x,y,z,col=color,size=1.5,alpha=0.5)
+  turtle$pos <- to
+  return (turtle)
+}
+
+turtle.pitch <- function(turtle, degree) {
+  turtle$pitch <- turtle$pitch + degree
+  return(turtle)
+}
+
+turtle.head <- function(turtle, degree) {
+  turtle$head <- turtle$head + degree
+  return(turtle)
+}
+
+turtle.roll <- function(turtle, degree) {
+  turtle$roll <- turtle$roll + degree
+  return(turtle)
+}
+
+#
+# l-system general
+#
+
+
+lsystem.code <- function( x )
+  substitute( x )
+
+lsystem.gen <- function( x, grammar, levels=0 ) {
+  code <- eval( substitute( substitute( REPLACE , grammar ), list(REPLACE=x) ) )
+  if (levels)
+    return( lsystem.gen( code , grammar , levels-1 ) )
+  else
+    return( code )
+}
+
+#
+# l-system plot
+#
+
+lsystem.plot <- function( expr, level ) {
+  turtle <- turtle.init(level=level)
+  lsystem.eval( expr, turtle )
+}
+
+lsystem.eval <- function( expr, turtle ) {
+  if ( length(expr) == 3 ) {
+    turtle <- lsystem.eval( expr[[2]], turtle )
+    turtle <- lsystem.eval( expr[[3]], turtle )
+    turtle <- lsystem.eval( expr[[1]], turtle )
+  } else if ( length(expr) == 2 ) {
+    saved <- turtle
+    turtle <- lsystem.eval( expr[[1]], turtle )
+    turtle <- lsystem.eval( expr[[2]], turtle )
+    turtle <- saved
+  } else if ( length(expr) == 1 ) {          
+    if ( as.name(expr) == "stem" )      turtle <- turtle.move(turtle, 5, "brown")
+    else if ( as.name(expr) == "short") turtle <- turtle.move(turtle, 5, "brown")
+    else if ( as.name(expr) == "leaf" ) {
+      rgl.spheres(turtle$pos[1],turtle$pos[2],turtle$pos[3],radius=0.1+turtle$level*0.3,color="green")
+      rgl.sprites(turtle$pos[1],turtle$pos[2],turtle$pos[3],radius=0.5+turtle$level*0.3 ,color="green",texture=system.file("textures/particle.png",package="rgl"),textype="alpha",alpha=0.5)     
+    }
+    else if ( as.name(expr) == "roll" ) turtle <- turtle.head(turtle, 60)
+    else if ( as.name(expr) == "down" ) turtle <- turtle.pitch(turtle,10)
+    else if ( as.name(expr) == "up" )   turtle <- turtle.pitch(turtle,-10)
+    else if ( as.name(expr) == "left" ) turtle <- turtle.head(turtle, 1)
+    else if ( as.name(expr) == "right") turtle <- turtle.head(turtle,-1.5)
+    else if ( as.name(expr) == "turnleft") turtle <- turtle.head(turtle,20)
+    else if ( as.name(expr) == "turnright") turtle <- turtle.head(turtle,-20)
+    else if ( as.name(expr) == "turn") turtle <- turtle.roll(turtle,180)
+  }
+  return (turtle)
+}
+
+
+#
+# example
+#
+
+simple <- function (level=0) {
+  grammar <- list(
+    stem=lsystem.code(
+      stem-(up-stem-leaf)-stem-(down-stem-leaf)-stem-leaf
+    )
+  )
+  plant <- lsystem.gen(lsystem.code(stem), grammar, level )
+  lsystem.plot(plant,level)
+}
+
+rgl.demo.lsystem <- function (level=0) {
+  gen   <- list(
+    stem=lsystem.code( 
+      stem-left-stem-branch( turnleft-down-short-turnleft-down-stem-leaf)-right-right-stem--branch( turnright-up-short-turnright-up-short-turnright-short-stem-leaf)-left-left-left-stem-branch( turnleft-down-short-turnright-down-stem-leaf )-branch( up-turnright-short-up-turnleft-up-stem-leaf ) 
+    )
+  )    
+  plant <- lsystem.gen(lsystem.code(stem), gen, level )
+  lsystem.plot(plant,level)  
+}
+
+rgl.open()
+rgl.demo.lsystem(level=1)
+
diff --git a/demo/mouseCallbacks.R b/demo/mouseCallbacks.R
new file mode 100644
index 0000000..ec72aaf
--- /dev/null
+++ b/demo/mouseCallbacks.R
@@ -0,0 +1,303 @@
+xprod <- function(a, b) 
+    c(a[2]*b[3] - a[3]*b[2],
+       a[3]*b[1] - a[1]*b[3],
+       a[1]*b[2] - a[2]*b[1])
+       
+vlen <- function(a) sqrt(sum(a^2))
+
+angle <- function(a,b) {
+    dot <- sum(a*b)
+    acos(dot/vlen(a)/vlen(b))
+}
+ 
+clamp <- function(x, min, max)  pmin(pmax(x, min), max)
+
+mouseNone <- function(button = 1, dev = rgl.cur() ) {
+
+    cur <- rgl.cur()
+    
+    for (i in dev) {
+        rgl.set(i, TRUE)
+        rgl.setMouseCallbacks(button, begin = NULL, update = NULL, end = NULL)
+    }
+    rgl.set(cur)
+}
+
+mouseTrackball <- function(button = 1, dev = rgl.cur() ) {
+    width <- height <- rotBase <- NULL
+    userMatrix <- list()
+    cur <- rgl.cur()
+    
+    screenToVector <- function(x, y) {
+      radius <- max(width, height)/2
+      centre <- c(width, height)/2
+      pt <- (c(x, y) - centre)/radius
+      len <- vlen(pt)
+
+      if (len > 1.e-6) pt <- pt/len
+
+      maxlen <- sqrt(2)
+      angle <- (maxlen - len)/maxlen*pi/2
+      z <- sin(angle)
+      len <- sqrt(1 - z^2)
+      pt <- pt * len
+      return (c(pt, z))
+    }
+    
+    trackballBegin <- function(x, y) {
+        vp <- par3d("viewport")
+        width <<- vp[3]
+        height <<- vp[4]
+        cur <<- rgl.cur()
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else userMatrix[[i]] <<- par3d("userMatrix")
+        }
+        rgl.set(cur, TRUE)
+        rotBase <<- screenToVector(x, height - y)
+    }
+    
+    trackballUpdate <- function(x,y) {
+        rotCurrent <- screenToVector(x, height - y)
+        angle <- angle(rotBase, rotCurrent)
+        axis <- xprod(rotBase, rotCurrent)
+        mouseMatrix <- rotationMatrix(angle, axis[1], axis[2], axis[3])
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else par3d(userMatrix = mouseMatrix %*% userMatrix[[i]])
+        }
+        rgl.set(cur, TRUE)
+    }
+    
+    for (i in dev) {
+        rgl.set(i, TRUE)
+        rgl.setMouseCallbacks(button, begin = trackballBegin, update = trackballUpdate, end = NULL)
+    }
+    rgl.set(cur, TRUE)
+}
+
+mouseXAxis<- function(button = 1, dev = rgl.cur() , left=TRUE) {
+    mouseOneAxis(button, dev, axis=c(1,0,0), left=left) 
+}
+
+mouseYAxis<- function(button = 1, dev = rgl.cur(), left = TRUE ) {
+    mouseOneAxis(button, dev, axis=c(0,1,0), left=left) 
+}
+
+mouseZAxis<- function(button = 1, dev = rgl.cur(), left=TRUE) {
+    mouseOneAxis(button, dev, axis=c(0,0,1), left=left) 
+}
+
+mouseOneAxis <- function(button = 1, dev = rgl.cur(), axis = c(1,0,0), left = TRUE ) {
+    width <- height <- rotBase <- NULL
+    userMatrix <- list()
+    cur <- rgl.cur()
+    
+    screenToVector <- function(x, y) {
+      radius <- max(width, height)/2
+      centre <- c(width, height)/2
+      pt <- (c(x, y) - centre)/radius
+      len <- vlen(pt)
+
+      if (len > 1.e-6) pt <- pt/len
+
+      maxlen <- sqrt(2)
+      angle <- (maxlen - len)/maxlen*pi/2
+      z <- sin(angle)
+      len <- sqrt(1 - z^2)
+      pt <- pt * len
+      return (c(pt, z))
+    }
+
+    oneAxisBegin <- function(x, y) {
+        vp <- par3d("viewport")
+        width <<- vp[3]
+        height <<- vp[4]
+        cur <<- rgl.cur()
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else userMatrix[[i]] <<- par3d("userMatrix")
+        }
+        rgl.set(cur, TRUE)
+        rotBase <<- screenToVector(x, height/2)
+    }
+    
+    oneAxisUpdate <- function(x,y) {
+        rotCurrent <- screenToVector(x, height/2)
+        angle <- rotCurrent[1] - rotBase[1]
+        mouseMatrix <- rotationMatrix(angle, axis[1], axis[2], axis[3])
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else {
+		if (left)
+		    par3d(userMatrix = mouseMatrix %*% userMatrix[[i]])
+		else
+		    par3d(userMatrix = userMatrix[[i]] %*% mouseMatrix)
+	    }
+        }
+        rgl.set(cur, TRUE)
+    }
+    
+    for (i in dev) {
+        rgl.set(i, TRUE)
+        rgl.setMouseCallbacks(button, begin = oneAxisBegin, update = oneAxisUpdate, end = NULL)
+    }
+    rgl.set(cur, TRUE)
+}
+
+mousePolar <- function(button = 1, dev = rgl.cur()) {
+   
+    screenToPolar <- function(x,y) {
+    	r <- min(width, height)/2
+    	dx <- clamp(x - width/2, -r, r)
+    	dy <- clamp(y - height/2, -r, r)
+    	return( asin( c(dx, -dy)/r ) )
+    }
+
+    cur <- rgl.cur()
+    width <- height <- dragBase <- dragCurrent <- NULL
+    camBase <- list()
+    
+    polarBegin <- function(x, y) {
+        vp <- par3d("viewport")
+        width <<- vp[3]
+        height <<- vp[4]
+        dragBase <<- screenToPolar(x, y)
+    	cur <<- rgl.cur()
+    	for (i in dev) {
+	    if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else {
+		m <- par3d("userMatrix")
+		svd <- svd(m[1:3, 1:3])
+		m[1:3, 1:3] <- svd$u %*% t(svd$v)
+		theta <- atan2(-m[1,3], m[1,1])
+		m <-  m %*% rotationMatrix(theta, 0,1,0)
+		svd <- svd(m[1:3, 1:3])
+		m[1:3,1:3] <- svd$u %*% t(svd$v)	
+		phi <- atan2(-m[2,3], m[3,3])
+		camBase[[i]] <<- c(theta, phi)
+	    }
+	}
+        rgl.set(cur, TRUE)
+    }   
+    
+    polarUpdate <- function(x,y) {
+        dragCurrent <<- screenToPolar(x, y)        
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else {
+		newpos <- camBase[[i]] - ( dragCurrent - dragBase )
+		newpos[2] <- clamp(newpos[2], -pi/2, pi/2)
+		mouseMatrix <- rotationMatrix(newpos[2], 1, 0, 0) %*% rotationMatrix(-newpos[1], 0, 1, 0)
+		par3d(userMatrix = mouseMatrix) 
+	    }
+        }
+        rgl.set(cur, TRUE)
+    }
+    
+    for (i in dev) {
+	rgl.set(i, TRUE)
+	rgl.setMouseCallbacks(button, begin = polarBegin, update = polarUpdate, end = NULL)
+    }
+    rgl.set(cur, TRUE)
+}
+
+# Set background colour based on x,y position in the window
+
+mouseBG <- function(button = 1, dev = rgl.cur(), init = "white", rate = cbind(c(1,0,1),c(0,1,1)), space = c("rgb", "hsv")) {
+    cur <- rgl.cur()
+    space <- match.arg(space)
+    init <- col2rgb(init)/255
+    if (space == "hsv")
+    	init <- rgb2hsv(init*255)
+
+    lambda0 <- lambda <- NULL
+    
+    bgBegin <- function(x, y) {
+        lambda0 <<- c(x/width, 1-y/height)    
+        vp <- par3d("viewport")
+    	width <<- vp[3]
+    	height <<- vp[4]
+    }
+        
+    bgUpdate <- function(x,y) {
+        lambda <<- c(x/width, 1-y/height) - lambda0
+        color <- clamp(init + rate %*% lambda, 0, 1)
+        x <- color[1]
+        y <- color[2]
+        z <- color[3]
+        if (space == "rgb")
+            color <- rgb(x,y,z)    
+        else
+            color <- hsv(x,y,z)
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else bg3d(color=color)  
+        }
+        rgl.set(cur, TRUE)
+    }
+    
+    bgEnd <- function() {
+        init <<- clamp(init + rate %*% lambda, 0, 1)
+    }
+    
+    for (i in dev) {
+        rgl.set(i, TRUE)
+        rgl.setMouseCallbacks(button, begin = bgBegin, update = bgUpdate, end = bgEnd)
+    }
+    rgl.set(cur, TRUE)
+}
+
+# Set time using an arbitrary par3dinterp function
+
+mouseInterp <- function(button = 1, dev = rgl.cur(), fn, init = 0, range = NULL, direction=c(1,0)) {
+    cur <- rgl.cur()
+    time <- init
+    x0 <- width <- height <- NULL
+    
+    interpBegin <- function(x, y) {
+    	vp <- par3d("viewport")
+        width <<- vp[3]
+        height <<- vp[4]
+        x0 <<- sum(direction*c(x,y))
+    }
+        
+    interpUpdate <- function(x,y) {
+        time <<- init + (sum(direction*c(x,y)) - x0)/width
+        if (!is.null(range)) time <<- clamp(time, range[1], range[2])
+        for (i in dev) {
+            if (inherits(try(rgl.set(i, TRUE)), "try-error")) dev <<- dev[dev != i]
+            else par3d(fn(time))
+        }
+        rgl.set(cur, TRUE)
+    }
+    
+    interpEnd <- function() {
+        init <<- time
+    }
+    
+    for (i in dev) {
+        rgl.set(i, TRUE)
+        rgl.setMouseCallbacks(button, begin = interpBegin, update = interpUpdate, end = interpEnd)
+    }
+    rgl.set(cur, TRUE)
+}
+
+mouseZoom <- function(button = 1, dev = rgl.cur()) 
+    mouseInterp(button,dev=dev,fn=par3dinterp(times=c(-4,4)/4, zoom=c(10^(-4),10^4),method="linear"),
+                      init=log10(par3d("zoom"))/4,range=c(-4,4)/4,direction=c(0,-1))
+ 
+mouseFOV <- function(button = 1, dev = rgl.cur())
+    mouseInterp(button,dev=dev,fn=par3dinterp(times=c(1,179)/180, FOV=c(1,179),method="linear"), 
+                      init=par3d("FOV")/180, range = c(1,179)/180, direction=c(0,1))
+                      
+# Synchronize mouse control of two windows for stereo view
+example(surface3d, echo = FALSE)
+par3d(windowRect= c(0,32,512,544), userMatrix = rotationMatrix(5*pi/180, 0,1,0) %*% par3d("userMatrix") )
+w1 <- rgl.cur()
+example(surface3d, echo = FALSE)
+par3d(windowRect = c(512,32,1024,544))
+w2 <- rgl.cur()
+mouseTrackball(dev=c(w1,w2))
+mouseZoom(2,dev=c(w1,w2))
+mouseFOV(3,dev=c(w1,w2))
diff --git a/demo/regression.r b/demo/regression.r
new file mode 100644
index 0000000..428ca66
--- /dev/null
+++ b/demo/regression.r
@@ -0,0 +1,38 @@
+# demo: regression
+# author: Daniel Adler
+# $Id: regression.r 1023 2014-04-06 19:38:12Z murdoch $
+
+rgl.demo.regression <- function(n=100,xa=3,za=8,xb=0.02,zb=0.01,xlim=c(0,100),zlim=c(0,100)) {
+
+  rgl.clear("all")
+  rgl.bg(sphere = TRUE, color = c("black", "green"), lit = FALSE, size=2, alpha=0.2, back = "lines")
+  rgl.light()
+  rgl.bbox()
+
+  x  <- runif(n,min=xlim[1],max=xlim[2])
+  z  <- runif(n,min=zlim[1],max=zlim[2])
+  ex <- rnorm(n,sd=3)
+  ez <- rnorm(n,sd=2)
+  
+  esty  <- (xa+xb*x) * (za+zb*z) + ex + ez
+
+  rgl.spheres(x,esty,z,color="gray",radius=1.5,specular="green",texture=system.file("textures/bump_dust.png",package="rgl"),texmipmap=T, texminfilter="linear.mipmap.linear")
+
+  regx  <- seq(xlim[1],xlim[2],len=100)
+  regz  <- seq(zlim[1],zlim[2],len=100)
+  regy  <- (xa+regx*xb) %*% t(za+regz*zb)
+  
+  rgl.surface(regx,regz,regy,color="blue",alpha=0.5,shininess=128)
+  # rgl.surface(regx,regz,regy,color="blue",front="lines",back="lines")
+  
+  lx <- c(xlim[1],xlim[2],xlim[2],xlim[1])
+  lz <- c(zlim[1],zlim[1],zlim[2],zlim[2])
+  f <- function(x,z) { return ( (xa+x*xb) * t(za+z*zb) ) }
+  ly <- f(lx,lz)
+  
+  rgl.quads(lx,ly,lz,color="red",size=5,front="lines",back="lines",lit=FALSE)
+}
+
+rgl.open()
+rgl.demo.regression()
+
diff --git a/demo/rgl.r b/demo/rgl.r
new file mode 100644
index 0000000..5be349f
--- /dev/null
+++ b/demo/rgl.r
@@ -0,0 +1,9 @@
+# all rgl demos
+demo(hist3d)
+demo(abundance)
+demo(regression)
+demo(lsystem)
+demo(subdivision)
+# requires MASS library
+demo(bivar)
+
diff --git a/demo/shapes3d.R b/demo/shapes3d.R
new file mode 100644
index 0000000..c4d9f83
--- /dev/null
+++ b/demo/shapes3d.R
@@ -0,0 +1,107 @@
+
+cone3d <- function(base=c(0,0,0),tip=c(0,0,1),rad=1,n=30,draw.base=TRUE,qmesh=FALSE,
+                   trans = par3d("userMatrix"), ...) {
+  ax <- tip-base
+  if (missing(trans) && !rgl.cur()) trans <- diag(4)
+  ### is there a better way?
+  if (ax[1]!=0) {
+    p1 <- c(-ax[2]/ax[1],1,0)
+    p1 <- p1/sqrt(sum(p1^2))
+    if (p1[1]!=0) {
+      p2 <- c(-p1[2]/p1[1],1,0)
+      p2[3] <- -sum(p2*ax)
+      p2 <- p2/sqrt(sum(p2^2))
+    } else {
+      p2 <- c(0,0,1)
+    }
+  } else if (ax[2]!=0) {
+    p1 <- c(0,-ax[3]/ax[2],1)
+    p1 <- p1/sqrt(sum(p1^2))
+    if (p1[1]!=0) {
+      p2 <- c(0,-p1[3]/p1[2],1)
+      p2[3] <- -sum(p2*ax)
+      p2 <- p2/sqrt(sum(p2^2))
+    } else {
+      p2 <- c(1,0,0)
+    }
+  } else {
+    p1 <- c(0,1,0); p2 <- c(1,0,0)
+  }
+  degvec <- seq(0,2*pi,length=n+1)[-1]
+  ecoord2 <- function(theta) {
+    base+rad*(cos(theta)*p1+sin(theta)*p2)
+  }
+  i <- rbind(1:n,c(2:n,1),rep(n+1,n))
+  v <- cbind(sapply(degvec,ecoord2),tip)
+  if (qmesh) 
+    ## minor kluge for quads -- draw tip twice
+    i <- rbind(i,rep(n+1,n))
+  if (draw.base) {
+    v <- cbind(v,base)
+    i.x <- rbind(c(2:n,1),1:n,rep(n+2,n))
+    if (qmesh)  ## add base twice
+      i.x <-  rbind(i.x,rep(n+2,n))
+    i <- cbind(i,i.x)
+  }
+  if (qmesh) v <- rbind(v,rep(1,ncol(v))) ## homogeneous
+  if (!qmesh)
+    triangles3d(v[1,i],v[2,i],v[3,i],...)
+  else
+    return(rotate3d(qmesh3d(v,i,material=...), matrix=trans))
+}     
+
+
+ellipsoid3d <- function(rx=1,ry=1,rz=1,n=30,ctr=c(0,0,0),
+                        qmesh=FALSE,
+                        trans = par3d("userMatrix"),...) {
+  if (missing(trans) && !rgl.cur()) trans <- diag(4)
+  degvec <- seq(0,pi,length=n)
+  ecoord2 <- function(p) {
+    c(rx*cos(p[1])*sin(p[2]),ry*sin(p[1])*sin(p[2]),rz*cos(p[2])) }
+  v <- apply(expand.grid(2*degvec,degvec),1,ecoord2)
+  if (qmesh) v <- rbind(v,rep(1,ncol(v))) ## homogeneous
+  e <- expand.grid(1:(n-1),1:n)
+  i1 <- apply(e,1,function(z)z[1]+n*(z[2]-1))
+  i2 <- i1+1
+  i3 <- (i1+n-1) %% n^2 + 1
+  i4 <- (i2+n-1) %% n^2 + 1
+  i <- rbind(i1,i2,i4,i3)
+  if (!qmesh)
+    quads3d(v[1,i],v[2,i],v[3,i],...)
+  else return(rotate3d(qmesh3d(v,i,material=list(...)),matrix=trans))
+}
+
+############
+open3d()
+ellipsoid3d(ctr=c(2,2,2),rx=3,ry=2,col="red",alpha=0.4)
+cone3d(base=c(-2,-2,-2),rad=0.5,tip=c(-3,0,-4),col="blue",front="lines",back="lines")
+shade3d(translate3d(cube3d(),3,-2,3,col="purple"))
+
+### now with qmesh()
+open3d()
+q1 <- cone3d(qmesh=TRUE,trans=diag(4))  ## the "unit cone";
+                                        ## height=1,radius=1, base at (0,0,0)
+shade3d(q1)
+## various transformations and rotations
+wire3d(translate3d(q1,3,0,0),col="green")
+wire3d(translate3d(scale3d(q1,1,1,2),6,0,0),col="green")
+dot3d(translate3d(q1,0,3,0),col="green")
+dot3d(translate3d(scale3d(q1,2,1,1),0,6,0),col="green")
+shade3d(translate3d(q1,0,0,3),col="red")
+shade3d(translate3d(rotate3d(scale3d(q1,1,1,2),pi/4,0,1,0),0,0,6),col="red")
+
+axes3d()
+open3d()
+
+s1 <- ellipsoid3d(qmesh=TRUE,trans=diag(4))  ## the "unit sphere";
+                                        ## radius=1, ctr at (0,0,0)
+shade3d(s1)
+## various transformations and rotations
+wire3d(translate3d(s1,3,0,0),col="green")
+wire3d(translate3d(scale3d(s1,1,1,2),6,0,0),col="green")
+dot3d(translate3d(s1,0,3,0),col="green")
+dot3d(translate3d(scale3d(s1,2,1,1),0,6,0),col="green")
+shade3d(translate3d(s1,0,0,3),col="red")
+shade3d(translate3d(rotate3d(scale3d(s1,1,1,2),pi/4,0,1,0),0,0,6),col="red")
+
+axes3d()
diff --git a/demo/stereo.R b/demo/stereo.R
new file mode 100644
index 0000000..19f154d
--- /dev/null
+++ b/demo/stereo.R
@@ -0,0 +1,145 @@
+randomDot <- function(left, right, rightOffset=c(200, 0), n=3000, ...) {
+  old <- rgl.cur()
+  on.exit(rgl.set(old))  
+  force(left)
+  force(right)
+  rgl.set(left)
+  leftViewport <- par3d("viewport")
+  leftSize <- leftViewport[3:4]
+  leftProj <- rgl.projection()
+  leftDepth <- rgl.pixels("depth")  
+  leftUR <- leftViewport[1:2] + leftSize - 1
+  rgl.set(right)
+  rightViewport <- par3d("viewport")
+  rightSize <- rightViewport[3:4]
+  rightProj <- rgl.projection()
+  rightDepth <- rgl.pixels("depth")
+  rightUR <- rightViewport[1:2] + rightSize - 1
+
+  ll <- pmin(leftViewport[1:2], rightViewport[1:2]+rightOffset)
+  size <- pmax(leftViewport[3:4], rightViewport[3:4]+rightOffset)
+  
+  pts <- matrix(c(sample(leftSize[1], n, replace=T),
+                  sample(leftSize[2], n, replace=T)), n, 2)
+  # for debugging:                
+  # pts <-matrix(c(seq(1, size[1], len=n), seq(1, size[2], len=n)), n, 2)
+  cols <- 1:n
+  startpt <- pts
+  startcols <- cols
+  keep <- startpt[,1] < leftSize[1] & startpt[,2] < leftSize[2]
+  pt <- startpt[keep,,drop=FALSE]
+  cl <- startcols[keep]
+  while (length(pt)) {
+    depth <- leftDepth[pt]
+
+    user <- rgl.window2user((pt[,1]-0.5)/leftSize[1], (pt[,2]-0.5)/leftSize[2],
+                          depth, projection=leftProj)
+    win <- rgl.user2window(user, projection=rightProj)
+    bkgd <- cbind((pt[,1] - 0.5)/rightSize[1], (pt[,2] - 0.5)/rightSize[2], 1)
+    usewin <- rep(depth < 1, 3)
+    rightPt <- structure(ifelse(usewin, win, bkgd), dim=dim(win))
+    rightPti <- round(cbind(rightSize[1]*rightPt[,1], rightSize[2]*rightPt[,2]) + 0.5)
+    
+    keep <- rightPti[,1] >= 1 & rightPti[,1] <= rightUR[1] &
+            rightPti[,2] >= 1 & rightPti[,2] <= rightUR[2]
+            
+    rightPti <- rightPti[keep,,drop=FALSE]
+    rightPt <- rightPt[keep,,drop=FALSE]
+    cl <- cl[keep]            
+    keep <- TRUE | rightPt[,3] <= rightDepth[ rightPti ]+0.001
+    rightPti <- rightPti[keep,,drop=FALSE]            
+    cl <- cl[keep]
+
+    pt <- cbind(rightPti[,1] + rightOffset[1], rightPti[,2] + rightOffset[2])
+    pts <- rbind(pts, pt)
+    cols <- c(cols, cl)
+    keep <- apply(pt, 1, min) >= 1 &
+            pt[,1] <= leftUR[1] &
+            pt[,2] <= leftUR[2] 
+    pt <- pt[keep,,drop=FALSE]
+    cl <- cl[keep]
+  } 
+  
+  pt <- cbind(startpt[,1] - rightOffset[1], startpt[,2] - rightOffset[2])
+  keep <- pt[,1] > 1 & pt[,1] < rightSize[1] & 
+          pt[,2] > 1 & pt[,2] < rightSize[2] 
+  pt <- pt[ keep,,drop=FALSE ]
+  cl <- startcols[ keep ]
+  
+  while (length(pt)) {
+    depth <- rightDepth[pt]
+    user <- rgl.window2user((pt[,1]-0.5)/rightSize[1], (pt[,2]-0.5)/rightSize[2],
+                          depth, projection=rightProj)
+    win <- rgl.user2window(user, projection=leftProj)
+    bkgd <- cbind((pt[,1] - 0.5)/leftSize[1], (pt[,2] - 0.5)/leftSize[2], 1)
+    usewin <- rep(depth < 1, 3)
+    leftPt <- structure(ifelse(usewin, win, bkgd), dim=dim(win))
+    leftPti <- round(cbind(leftSize[1]*leftPt[,1], leftSize[2]*leftPt[,2]) + 0.5)
+
+    keep <- leftPti[,1] >= 1 & leftPti[,1] <= leftUR[1] &
+            leftPti[,2] >= 1 & leftPti[,2] <= leftUR[2]
+            
+    leftPti <- leftPti[keep,,drop=FALSE]
+    leftPt <- leftPt[keep,,drop=FALSE]
+    cl <- cl[keep]            
+    keep <- TRUE | leftPt[,3] <= leftDepth[ leftPti ]+0.001
+    leftPti <- leftPti[keep,,drop=FALSE]            
+    cl <- cl[keep]
+    
+    pt <- leftPti
+    pts <- rbind(pts, pt)
+    cols <- c(cols, cl)
+    pt <- cbind(pt[,1] - rightOffset[1], pt[,2] - rightOffset[2])
+    keep <- apply(pt, 1, min) >= 1 &
+            pt[,1] <= rightUR[1] &
+            pt[,2] <= rightUR[2]
+    pt <- pt[keep,,drop=FALSE]
+    cl <- cl[keep] 
+  }
+  plot(pts, col = cols, pch=16, axes=FALSE,cex=0.25+cols/n/2,xlab="",ylab="",...)
+  rug((size[1] + c(-1,1)*rightOffset[1])/2, side=1)
+  rug((size[1] + c(-1,1)*rightOffset[1])/2, side=3)
+  rug((size[2] + c(-1,1)*rightOffset[2])/2, side=2)
+  rug((size[2] + c(-1,1)*rightOffset[2])/2, side=4)
+}
+
+                                                #red                   #cyan 
+anaglyph <- function(left, right, leftColor = c(1,0,0), rightColor = c(0,1,1)) {
+  old <- rgl.cur()
+  on.exit(rgl.set(old))  
+  force(left)
+  force(right)
+
+  rgl.set(left)
+  vp <- par3d("viewport")
+  leftPixels <- rgl.pixels(viewport=vp)
+  leftPixels <- (leftPixels[,,1]+leftPixels[,,2]+leftPixels[,,3])/3
+  rgl.set(right)
+  rightPixels <- rgl.pixels(viewport=vp)
+  rightPixels <- (rightPixels[,,1]+rightPixels[,,2]+rightPixels[,,3])/3
+  red <- leftPixels*leftColor[1] + rightPixels*rightColor[1]
+  green <- leftPixels*leftColor[2] + rightPixels*rightColor[2]
+  blue <- leftPixels*leftColor[3] + rightPixels*rightColor[3]
+  col <- rgb(pmin(red,1), pmin(green,1), pmin(blue,1))
+  colf <- factor(col)
+  z <- as.numeric(colf)
+  dim(z) <- dim(leftPixels)
+  image(z,col=levels(colf),breaks=min(z):(max(z)+1) - 0.5, axes=FALSE)
+}
+
+if (!rgl.useNULL()) {
+  source(system.file("demo/mouseCallbacks.R", package="rgl"), echo=FALSE )
+
+# This version assumes the eyes diverge for the stereo view.  
+# Reverse the two arguments for the cross-eyed view.
+
+  dev.new(width=9, height=7)
+
+  randomDot(rgl.cur()-1, rgl.cur())
+
+# A red-cyan anaglyph (for 3D glasses).  Use optional args to anaglyph for other glasses.
+
+  dev.new()
+  anaglyph(rgl.cur()-1, rgl.cur())
+} else
+  cat("Can't read pixels from a NULL device\n")
\ No newline at end of file
diff --git a/demo/subdivision.r b/demo/subdivision.r
new file mode 100644
index 0000000..e91e673
--- /dev/null
+++ b/demo/subdivision.r
@@ -0,0 +1,36 @@
+# RGL-demo: subdivision surfaces
+# author: Daniel Adler
+# $Id: subdivision.r 568 2007-03-11 18:15:27Z dmurdoch $
+
+rgl.demo.subdivision <- function()
+{
+  # setup environment
+  clear3d("all")
+  view3d()
+  bg3d(color="gray")
+  light3d()
+
+  # generate basic mesh
+  obj <- oh3d()
+
+  part <- function( level, tx, ... )
+  {
+    shade3d( translate3d( obj, tx, 0, 0 )
+    , color="gray30", front="lines",alpha=0.5,back="lines", override=TRUE
+    )
+    shade3d( translate3d( subdivision3d( obj, depth=level ), tx, 0, 0 )
+    , override=TRUE, ... )
+  }
+  
+  common <- c(alpha=0.5)
+  
+  part(0, -5.50, color="blue"   , common )
+  part(1, -1.75, color="yellow" , common )
+  part(2,  1.75, color="red"    , common )
+  part(3,  5.50, color="green"  , common )
+
+}
+
+open3d()
+rgl.demo.subdivision()
+
diff --git a/inst/NEWS b/inst/NEWS
new file mode 100644
index 0000000..942243c
--- /dev/null
+++ b/inst/NEWS
@@ -0,0 +1,733 @@
+v0.60 
+  - (mini-thesis release)
+
+v0.61 (workshop release)
+  - added: rgl.sprites
+  - added: fps counter
+  - added: autoUpdate, modified win32 mainloop, on hide, autoUpdate disabled, on show enabled
+  - modified material: added alpha vector
+
+v0.62
+  - modified sphere set
+  - support R color strings
+  - use system.file( <subpath>, package="rgl" ) in examples to retrieve texture files
+  - rewrote R code : 
+    * clear enum types
+    * vertex vector datatype (internal representation matrix)
+
+v0.63
+  - api: added rgl_init, rgl_quit: explicit client initialization
+  - added setup.bat: build setup for windows
+  - win32 setup: mingw compiler
+  - win32 setup: visual c++ compiler through gui environment
+
+v0.64
+  - autoconf build system
+  - moved textures to inst/ directory
+  - x11 port
+  - win32/vc: fixed fpu control word precision to remain on 64 bit
+    links with fp10.obj
+  - changed texture mapping t coordinate for Surface node
+
+v0.64-2
+  - rgl.quads: enum id was broken, fixed ("quads" -> "quadrangles")
+  
+v0.64-3
+  - configure.ac: X11 library path broken, fixed
+  - x11gui: glXChooseVisual part fixed
+  - code cleanup: rglview.h  
+  - added: man/maintainer.Rd maintainer information
+
+v0.64-4
+  - manual update
+  - aquired valid CRAN package status, 
+    rcmd check runs through with 2 WARNINGS 
+    (acording to latex, and codoc)
+  - uploaded to cvs
+
+v0.64-5
+  - MacOS X/X11 port
+
+v0.64-6
+  - updated build system: added setversion.sh 
+  - with MinGW version 3.0.1 pixmap loading does work
+  - project.mk , win32.mk and x11.mk in src/build changed
+    now a single variable MODS will extend.  
+  - MinGW build system changed.
+    rgl.dll now contains an R compilant Resource information
+    generated by R perl script
+  - bug fix: R 1.8.0/win32 does not detach packages when quit
+    it is safe now to call rgl_quit and lib_quit multiple times
+    win32lib.cpp: added dllmain that calls rgl_quit on process exit    
+  - added core support for devcpp IDE
+
+v0.64-7
+  - added mouse capturing
+  - rgl.sprites 'radius' bug fixed
+  - memory leak bugfix: texture objects are now AutoDestroy and used through Ref's
+  - resource management improvment: pixmaps gets free'd when they become unused
+    e.g. texture objects are created.
+  - no limitations on pixmap sizes
+  - mipmap support
+  - support for different texture minification and magnification filters
+
+v0.64-8
+  - build bugfix : removed rgl/src/Makefile
+  - updated configure to check and setup LDFLAGS for OpenGLU library
+
+v0.64-9
+  - MacOS X 'Panther' G5 fix for OpenGL library loading in .first.lib
+  - removed lpng and zlib from source tree 
+  - support for automatic downloading of zlib and lpng on win32 
+  - added demo directory with several examples using demo(rgl)
+
+v0.64-10
+  - updated .C() calls using PACKAGE="rgl"
+  - updated Maintainer.mk using correct zlib version
+  - improved dynamic unload using library.dynam.unload()
+  - conditional macos x darwin code in .First.lib()
+
+v0.64-11
+  - removed several redundant semicolons, required by gcc 3.4 ansi-pedantic mode.
+  - win32: uses R's zlib and libpng sources
+  - win32: added virtual destructor in Win32GUIFactory (removes warning)
+ 
+v0.64-12
+  - cran bugfix: permissions of cleanup fixed.
+
+v0.64-13
+  - DESCRIPTION fix: moved R 1.41 -> R 1.4.1 dependency
+
+v0.65
+  - simplified build system: uses 'R' build system
+  - added generic visualization/rendering interface (R3D)
+  - text justification from 0 to 1
+  - added primitive type: linestrips
+  - fixed rgl.bringtotop, added stay option (win32)
+  - added 4x4 matrix functions from djmrgl
+  - added rgl.user2window and rgl.window2user functions
+  - added user-selectable mouse handlers
+  - added selection mouse handler
+  - added trackball mouse handler
+  - added z-distance sorted rendering of alpha-blended faces 
+  - added gl2ps patch ( contributed by Albrecht Gebhard )
+  - added port: native Mac OS X Carbon
+  - bugfix: rgl.close() , rgl.quit() crashed on X11 occasionally.
+  - generalized rgl.surface() to allow surface over any coordinate plane.
+  - added r3dDefaults variable to allow user to set defaults
+  - added environment texture-mapping
+
+v0.66
+  - added "all" and "viewpoint" to rgl.clear and clear3d
+  - added static libpng build support and user customizable prefix (unix)
+  - used xyz.coords in all functions taking x, y, z coordinates, allowing
+    matrix or dataframe arguments (among others)
+  - added par3d(skipRedraw=TRUE) to allow drawing to be done without
+    being rendered
+  - fixed display list memory leak when drawing shapes (e.g. spheres)
+  - Changes for compatibility with strict enforcement of file naming rules in R 2.3.0.
+
+v0.67
+  - added support for png files with palettes, and grayscale pngs with 1, 2 or 4 bits 
+    per pixel
+  - added "ignoreExtent" option to par3d:  objects plotted when this is true
+    are ignored when calculating the bounding box
+  - added axis3d, axes3d, box3d, mtext3d, title3d functions from djmrgl for 
+    annotating plots.
+  - added plot3d high level plot function
+  - added material3d, which can both set and query material properties; changed
+    most *3d functions so they leave material invariant across calls.
+  - changed open3d() to set background and material defaults
+  - added aspect3d to control the aspect ratio of the bounding box.
+  - added xAxis, yAxis and zAxis mouse modes, set zAxis as r3d default.
+  - added persp3d function
+  - changed error messages to go through REprintf in X11 and OSX
+  - fixed segfault if rgl_init failed
+  - converted type of viewport arg in user2window and window2user calls
+  - if the rgl_init call fails, the package will still load with a warning (but
+    most function calls will result in errors).
+  - added par3d("scale") to handle aspect3d operations internally.
+  - added ellipse3d() generic and methods for drawing confidence ellipsoids
+  - added decorate3d() to draw all the decorations, plot3d.qmesh3d() method.
+  - changed zoom to use ratio scale over larger range
+  - fixed bug causing jump after resize in Mac OSX (and maybe other platforms)  
+  - rgl.primitive now does sanity checks on inputs
+
+v0.67-2
+  - minor correction
+
+v0.68
+  - fixed sphere drawing so spheres are spheres regardless of par3d("scale")
+  - added type="s" to plot3d to draw spheres
+  - fixed handling of "..." in axis related functions
+  - added full MDI support
+  - removed use of List and ListIterator internally
+  - fixed handling of axes and boxes when a coordinate had zero extent
+  - changed rgl.viewpoint default to be compatible with r3dDefaults
+  - added id return values to primitives and higher level functions, 
+    and to rgl.pop(); added rgl.ids() to report on them.
+  - updated gl2ps to version 1.3.1, adding support for svg and pgf output formats.
+  - added grid3d(), added nticks argument to bbox3d, axis3d and axes3d.
+    
+v0.69
+  - persp3d partially ignored add=TRUE
+  - plot3d.qmesh3d did not return result
+  - allow selection to use any button
+  - allow NA in primitives, surfaces, texts, and sprites
+  - report error in OSX if the wrong configure options were used.
+  - display was not being updated properly in OSX
+  
+v0.70
+  - OSX now builds two libraries, one for AGL, one for X11
+  - resolve entry points at load time, not call time
+  - updated gl2ps to version 1.3.2
+  - fixed bug in rgl.postscript in Linux, added text support to it
+  - tweaked positioning of labels in bounding box decoration
+  - snapshot3d wasn't being exported, and snapshots were from the back buffer
+  - fixed bug that could cause crash on shutdown
+  - moved this file (ChangeLog) to inst directory, so it will be installed,
+    and added code to display it to the rgl help topic.
+
+v0.71
+  - changes to configure script from Laszlo Kajan and Brian Ripley:  should 
+    now be much more portable
+  - removed deprecated OSX font setting calls
+  - texture properties are now returned by material3d()
+  - allowed normals and texture coordinates to be specified in triangles, quads and surfaces
+  - normals may be specified in qmesh objects, but (at present) subdivide removes them
+  - material3d() now preserves the values of unspecified parameters (as documented,
+    but not previously functioning)
+  - clear3d() can now reset material properties to the defaults, and
+    open3d() does this.
+  - minor fix for gcc 4.3 compatibility
+  - minor fix for R 2.5+ compatibility
+  - allowed more general surfaces to be plotted by rgl.surface, surface3d and 
+    persp3d, by specifying matrices for x and y coordinates
+  - added world map texture, used in example(persp3d)
+  
+v0.72
+  - declaration changes for compatibility with R 2.6.0 (from Brian Ripley)
+
+v0.73
+  - partial changes to avoid crash on MacOSX with Xvfb
+  - change to rgl_init for R 2.6.0 compatibility
+  
+v0.74
+  - clean up #includes
+  - clean up some calls for SunStudio 12 compiler
+  - add rgl.setMouseCallbacks to allow user actions
+  
+v0.75
+  - add play3d, movie3d, par3dinterp, and spin3d functions, with flag demo
+  - rounding error could cause par3d(userMatrix) to generate NaNs and fail
+  - workaround for Xvfb on MacOSX problems
+  
+v0.76
+  - put our own assert() macro in place to avoid crashing R.
+  - rename ChangeLog file to NEWS, as per discussion on R-devel
+  - add "windowRect" to par3d parameters to allow window size to be
+    controlled from R.
+    
+ v0.77
+  - par3d("windowRect") returned garbage if there was no window open.
+  - persp3d() and plot3d() sometimes miscalculated ranges involving NAs.
+  - select3d() and rgl.select() produced a very inefficient test function.
+  
+ v0.78
+  - fix miscalculation of mouseMatrix that caused disappearing views.
+  - rgl.texts() and text3d() can now handle font and size specifications
+    using the FreeType library on any platform, or GDI on Windows. 
+  - adj is supported both horizontally and vertically in drawing text.
+  - rgl.pop was very slow when given a long list of ids.
+  - a workaround for OSX 10.5 OpenGL problems has been incorporated
+    (thanks to mkv22 at cam.ac.uk).
+
+v0.79
+  - rgl.pop() could cause corruption when multiple windows were open.
+  - added mouseCallbacks demo, to show R implementations of standard
+    mouse handlers, multiple connected windows, stereo view, etc.
+  - added "silent" argument to rgl.set(), to allow temporary changes
+    to focus without changing window labels.
+  - added natural spline extrapolation to par3dinterp.
+
+v0.80
+  - worked around bug(?) in Mac OSX FTGL rendering
+  - updated FTGL to 2.1.3rc5
+  
+v0.81
+  - converted Freetype font error into warning
+  - rglFonts was being set at install time, but it should be set at load
+    time.
+  - fixed configuration problems in OS X
+  - fixed executable marker on a number of files
+  
+v0.82
+  - rewrote internal rendering of transparent and anti-aliased shapes,
+    so they will be rendered better when there are several in the same 
+    scene
+  - added material properties "point_antialias", which causes points to be 
+    drawn as smooth circles, and "line_antialias", which causes
+    lines to be antialiased.
+  - fixed a bug in the bounding box decoration which caused axis labels
+    to be plotted in the wrong place.
+  - fixed a bug in the Windows driver which caused the standard system 
+    font to disappear when justified.
+  - added material parameter lwd for line width; size now applies only
+    to points.
+  - increased default point size to 3 pixels across.
+  - fixed bug in open3d:  "..." was being ignored.
+  - fixed bug in qmesh3d:  homogeneous=FALSE coordinates were not
+    handled properly.
+  - movie3d gains a "type" argument to set the output type, and the 
+    "convert" argument is more flexible.
+  - rgl.snapshot() gives more informative error messages when libpng is
+    not available.
+  - axis3d() now uses format() rather than as.character() to give
+    nicer looking labels.
+  - the clipping volume calculation was incorrect when scaling was used.
+  - use R warning() to report messages, rather than popups or REprintf.
+  - added rgl.pixels() to read the generated image, and demo("stereo")
+    to illustrate its use.
+  - corrected the ?rgl example to display this file.
+
+v0.83-1
+  - Don't try to build Carbon driver in 64 bit Mac OS (contributed by
+    Brian Ripley).
+  - Fixed rgl.pixels example for weird displays.
+  - Did not assume OpenGL 1.2 was available in material properties.
+  - Added numerous error checks.
+  - Fixed demo(stereo) to add sync in X11:  X windows seemed to grab
+    images before they were redrawn.
+  - Rearranged headers for Win64 compatibility (contributed by Alex 
+    Chen).
+    
+v0.83-3
+  - Quick fix for R 2.9.x compatibility, and to remove accidental change
+    introduced in v0.83 which caused errors on plotting without open3d().
+
+v0.84
+  - Added triangle meshes, shape lists, the Platonic solids and a cuboctahedron.
+  - Added classes mesh3d and shapelist3d; qmesh3d is only kept for 
+    back compatibility. 
+  - Bug fix to stop crashes when material is set before the first window is
+    opened.
+    
+v0.85
+  - Added some namespace declarations to the C++, and renamed math.h, for
+    compatibility with Sun compilers (contributed by Brian Ripley).  
+  - Fixed visibility of some shade3d, wire3d and points3d methods.
+  - Added addNormals generic, to add normals for smooth surface rendering.
+  - Added cylinder3d function, to make cylindrical or "tube" plots.
+  - Fixed material3d("color") bug introduced in 0.82.
+  
+v0.87
+  - Allowed FOV to be set to 0, for an orthogonal projection.
+  - Fixed crash when zero-length color vector was used.
+  - Fixed crash in X11 after closing a window
+  - Changed seq(along=...) to seq_along(...).
+  - Fixed typo in cylinder3d.
+  - Cleaned up bad links in Rd files.
+  
+v0.88
+  - Add keepVars argument to cylinder3d(), for debugging or special
+    effects.
+  - Add BugReports field to DESCRIPTION.
+  
+v0.89 
+  - Fixed rounding errors and Xvfb errors in rgl.pixels examples
+    and demo.
+    
+v0.90
+  - Added startTime argument to play3d() and movie3d().
+  - Fixed configure.ac as suggested by Jens Elkner.
+  - Updated declarations for libpng 1.4.0 compatibility.
+  - An off-by-one error caused the "alpha" component of the material
+    properties to be messed up. (Bug #809)
+
+v0.91
+  - Fixed bug in rgl.texts:  zero-length texts argument caused crash.
+    (Reported by Michael Friendly.)
+  - Added R_ARCH* macros to configure.win for Win64 compatibility
+  - Fixed bad declaration in rglmath.h
+  
+v0.92
+  - Added detection of 64 bit MacPorts compiler to configure script. 
+    (Bug #861)
+  - Allowed texture coordinates to be specified in mesh objects.
+  - Updated gl2ps to version 1.3.5
+  - Should now install using --merge-multiarch on Windows
+
+v0.92.858
+  - Added declarations for Solaris compatibility (from Brian Ripley)
+  - Fixed configure.win for bi-arch compatibility.  Windows installers can
+    set HAVE_PNG to a non-empty value, and rgl will look for 
+    the libpng files in the default LOCAL_SOFT location when installing.
+  - Added depth_mask and depth_test material properties, to allow control
+    over how objects are obscured by each other.
+  - Added Sweave support through the rgl.Sweave driver and the Sweave.snapshot
+    function. 
+  - Added iterative computation of the bounding box to handle objects like
+    spheres, which need to maintain their apparent shape as the scaling
+    changes.
+  - Improved the bounding box decoration in two ways:  it can now draw the
+    front faces (to surround the whole graph), and can label edges with pretty
+    labels.  plot3d() was modified to use this instead of manually setting axis
+    locations and using box3d() to draw a box, allowing resizeable labelled
+    axes.
+  - Removed some unnecessary declarations from rglmath.h that were causing
+    problems in an old version of gcc on Solaris.
+  - Added rgl.abclines(), rgl.planes(), abclines3d() and planes3d() to draw 
+    lines and planes intersecting with the bounding box.
+  - rgl.postscript() now adjusts the size of text following the cex setting.
+    The font and family settings are still ignored.
+  - Transparency in material textures was not always rendered properly.
+  - In OSX, the Carbon system has been replaced by a Cocoa system.
+    (Code contributed by Adam Strzelecki).  For compatibility with the
+    Windows build system, the new files have been put into src/osx.
+  - Hardware antialiasing is now used if the OpenGL driver supports
+    it.  Set options(rgl.antialias=0) to disable it.
+  - Bug fix for divide.mesh3d() in handling normals.
+  - Functions rgl.attrib.count() and rgl.attrib() (and internal function
+    rgl.getmaterial()) added to allow objects in the scene to be examined.
+  - rgl.ids() did not return all object ids as documented.
+  - Updated gl2ps to version 1.3.6
+  
+v0.92.861
+  - Fixed segfault on startup on Windows in MDI mode.
+  - Added rgl.save.texture() to get texture from an object.
+  
+v0.92.879
+  - Removed rgl.save.texture():  textures are not saveable!
+  - Added writeWebGL() function, to allow scenes to be viewed in a web
+    browser.
+  - Added "centers" to the attributes that can be queried, for depth sorted 
+    transparent rendering.
+  
+ v0.92.880
+  - Rearranged declarations for compatibility with gcc 4.7.
+  
+ v0.92.881
+  - Fixed degenerate (e.g. straight line) cases in cylinder3d
+  
+ v0.92.883
+  - Added 3d "sprites" -- shapes that maintain their initial orientation.
+  
+ v0.92.887  
+  - Added "caps" to the end of cylinder3d() objects.
+  
+ v0.92.891
+  - Added support for 3d sprites to writeWebGL.
+  
+ v0.92.892
+  - Added declaration needed by Solaris.
+  
+ v0.92.893
+  - rgl.light() and light3d() did not return the light ID value. 
+  
+ v0.92.894
+  - remove debugging code from configure.win that was causing problems
+    on the CRAN WinBuilder system
+  
+ v0.93
+  - Added readSTL and writeSTL functions
+  - Added expand argument to decorate3d and axes3d
+  - Added base argument to spin3d result
+  - Added writePLY and writeOBJ functions
+  - Added scene3d function
+  - Added section argument to cylinder3d()
+  - Added res_name="rgl" and res_class="R_x11" to the WM_CLASS property of X11 
+    windows.  (Contributed by Philip Johnson.)
+  - Added code to work with R 3.0.0 setHook changes
+  - Added selectpoints3d function to select points from the scene.
+  - The rgl window now handles ESC key presses.  During selection
+    and play3d they abort the process; otherwise they are ignored.
+  - writeWebGL did not render semi-transparent surfaces properly.
+    (Reported by Robert Esswein.)
+  - Copied the R_pretty0 function from R sources to avoid warning.
+
+v0.93.928
+  - Updated the configure file using autoconf 2.69
+  - Forced OSX installs to put /usr/X11/bin at the head of the path
+    when looking for freetype-config
+
+v0.93.930
+  - writeWebGL did not handle snapshot=FALSE properly.  (Reported
+    by Yihui Xie.)
+  - Now handles local (not just directional) lighting.  Based on
+    code contributed by Alexander Senger.)  
+  - writeWebGL handles lighting properly.  Based on code contributed 
+    by Alexander Senger.
+    
+v0.93.932 
+  - calling rgl.material() before any rendering caused a crash on OSX.
+    (Reported by Dan Tenenbaum.)
+
+v0.93.935
+  - in certain circumstances since 0.93.930, text would fail to appear.
+    (Reported by Karline Soetaert.)
+    
+v0.93.944
+  - write the rgl version into the webGL file
+  - cleaned up use of CHECKGLERROR, so that setting USE_GLGETERROR to 1 in 
+    R.h will enable detailed checking
+  - added identify3d() function
+  - fixed bbox bug in writeOBJ (reported by Matthias Zeeman), writePLY
+    and writeSTL.
+  - aspect3d() (called by plot3d()) caused the scene to be redrawn,
+    even if par3d("skipRedraw") was TRUE.
+  - addNormals.mesh3d() failed on objects when the matrices
+    of triangles or quadrilaterals had zero columns.
+  - rotate3d.mesh3d() did not transform normals properly
+  - the writeWebGL() function produced fragment shaders that would not
+    work in some browsers (e.g. Firefox and Chrome with the ANGLE
+    WebGL engine).
+  
+v0.93.952
+  - added triangulate(), polygon3d() , extrude3d() and turn3d() 
+     for display of shapes based on two-dimensional polygons or curves.
+  - fixed formatting of vertex reference numbers in writeOBJ() (issue
+    4732, reported by Alejandro Baranek). 
+  - added support for "headless" operation:  see help for new
+    function rgl.useNULL().  
+  - added name of device to result returned from rgl.cur(); added function
+    rgl.dev.list() to list all open devices.
+  - examples and demos now check rgl.useNULL(), and don't run invisible
+    animations.
+    
+v0.93.960
+  - writeWebGL now forces the position attribute to location 0, a
+    recommended optimization strategy.  The colour attribute is
+    forced to location 1.
+  - we now check for invalid characters when drawing text using bitmapped
+    fonts (bug 4787)
+  - gl2ps has been updated to version 1.3.8 and support for point and line
+    sizes has been added (bug 4792)
+  - internal functions .check3d() and rgl.select() have been exported,
+    as they were used by the car package.
+  - writePLY had errors writing points and lines.
+  - rgl now prints a warning when a requested font is unavailable and the
+    default font is substituted.
+    
+v0.93.963
+  - font selection assumed rgl was on the search path; now it may be 
+    imported but not attached.  Similarly, r3dDefaults need not be on
+    the search path.
+    
+v0.93.975
+  - rgl.texts without a window failed because it queried the window
+    before opening it.
+  - the scene3d() function now records complete information about the
+    bounding box and the background.
+  - rgl declares most of its C++ objects in the global namespace.  
+    Recently this has caused clashes with the igraph package, which 
+    does the same, and which also has a Shape class.  As a temporary 
+    workaround the rgl class has been renamed to rglShape.  A full 
+    rgl namespace will eventually be added, with only the API functions 
+    left in the global namespace.
+    
+v0.93.984
+  - most rgl C++ functions and classes are now in namespace "rgl".  
+    Others have prefix rgl_, with the exception of gl2ps functions,
+    which all have that prefix, and FTGL functions, which generally
+    have an FT prefix.
+  - entry points to the rgl DLL are now registered within the DLL,
+    and on systems that support it, all entry points other than the
+    registration function are hidden.
+  - writeWebGL() and the other write methods did not handle material
+    information properly after 0.93.975.
+    
+v0.93.986
+  - The FTGL functions were mistakenly added to the rgl namespace
+    on some OSX compiles.
+  - Changes have been made to satisfy the stringent requirements of
+    the Solaris compiler.
+    
+v0.93.987
+  - Added clipplanes3d function to implement clip planes.  (Still
+    only partially implemented.)
+    
+v0.93.991
+  - Some cleanup of the declarations (submitted by Karl Millar).
+  
+v0.93.995
+  - Improved the approximation to the surface normal for degenerate
+    grids in surface3d and persp3d.  (Problem found by Graham Griffiths
+    using polar coordinates; all r=0 points were at the same location.)
+  - The new surface normals are now saved in memory, so rgl.attrib
+    will return them even if they were calculated by rgl.
+  - Bounding box calculations for surfaces with user normals were 
+    incorrect.
+  - An array-overrun bug in rgl.attrib() showed up in writeWebGL.  
+    (Reported by Brian Ripley.)
+  - scene3d() now records light settings.
+  
+v0.93.1098
+  - rgl.material() (for textures), rgl.postscript() and rgl.snapshot()
+    now call normalizePath() on filenames, so tilde expansion should
+    be supported.
+  - par3d() could generate an error if an unnamed list was passed in.
+  - material3d() lost settings for textures
+  - internals are updated to be consistent with MacOS 10.9 requirements
+  - fixed a bug in triangulation code:  it failed on locator() input.
+  - The Aqua support now works again, XQuartz is only needed for command
+    line use in Mac OSX.
+    
+v0.94
+  - Added "subscenes", i.e. scenes of objects nested within the 
+    main window.  This affects a lot of other functions as well,
+    which now act either on a single subscene or on the 
+    overall scene.
+  - Allowed the coordinates of the viewport to be set.
+  - Changed the behaviour of pop3d() and rgl.pop():  the type is
+    now ignored if id is non-zero.
+  - par3d("modelMatrix") no longer includes the observer translation
+  - Added configurable mouse wheel actions via par3d() or 
+    rgl.setWheelCallback().
+  - The par3d(), par3dinterp(), and spin3d() functions now
+    have arguments dev and subscene to specify where they apply.
+  - Included a copy of the source to CanvasMatrix.js (used by
+    writeWebGL()) at the request of the Debian administrators.
+  - The NULL device was not removed from the device list when
+    it was closed.  (Reported by Henrik Bengtsson.)
+  - Some of the animations have been sped up at the request of CRAN
+
+0.94.1143
+  - Added function methods for persp3d() and plot3d(), to allow
+    surfaces to be plotted just by specifying the function.
+  - Fixed a bug introduced in 0.94 that made user callbacks crash R.
+    (Reported by Dave Hadka.)
+  - Fixed a bug exposed in 0.94 (but really introduced in 0.93.952)
+    that caused writeWebGL() to fail when a NULL device was active.
+  - Fixed a bug introduced in 0.94 with writing 3D sprite objects.
+  - Fixed a bug computing the bounding box of an embedded subscene.
+    
+0.95.1157
+  - Allowed background of window to show bitmap;  added bgplot3d()
+    and legend3d() functions.
+  - Reverted misguided changes to par3d("modelMatrix") from 0.94.
+    This affects rgl.projection() as well.
+  - Fixed bug (introduced in 0.94) causing loss of rectangle showing 
+    selection area.  (Reported by John Fox and others.)
+  - The NULL device now does not make any spurious OpenGL calls.
+  
+0.95.1158
+  - rgl.snapshot() now works with the NULL device (but produces a 
+    black snapshot).  This allows testing with RGL_USE_NULL.
+
+0.95.1196
+  - writeWebGL() now includes an argument "commonParts", to allow
+    omission of common code in multi-figure displays.
+  - If template is NULL in writeWebGL(), no template file is used. 
+  - The NULL device did not handle changes to par3d("windowRect")
+    properly.
+  - The persp.function() method is now smarter about setting default
+    axis labels.
+  - The package now contains a vignette giving an overview of
+    the functions. 
+  - Subscenes with "ignoreExtent" set to TRUE were not plotted.
+  - The bounding box calculations now take clipping planes into account.
+  - writeWebGL() did not display the bboxdeco properly when working
+    in a subscene.
+  - Added clipping regions to plot3d() and persp3d().
+  - Export the GramSchmidt function (request of Remko Duursma)
+  - Added readOBJ(), with a very limited ability to read OBJ 
+    shapefiles.
+  - triangulate() now supports polygons expressed with 3
+    coordinates (though they are still assumed to be planar).
+  - par3d() now includes "listeners", a list of subscenes that
+    respond to mouse actions in the current subscene.
+  - The Windows configuration file has been modified to work in 
+    R-devel (to become R 3.2.0).
+
+0.95.1247
+  - If a template file is used in writeWebGL(), the string %prefix%
+    will be replaced in it by the prefix argument.
+  - writeWebGL() now outputs a Javascript global variable named
+    "<prefix>rgl" of class "rglClass" that allows access to many of the
+    scene internals.  (Inspired by patch submitted by Jeff Allen.)
+  - User mouse callbacks can now be retrieved within R using
+    rgl.getMouseCallbacks() and rgl.getWheelCallback(), and 
+    may be included in WebGL output.
+  - writeWebGL() now outputs information on object ids to allow
+    them to be re-used in multiple figures on the same page.
+    See the "reuse" parameter and attribute of the result.
+  - Started a vignette describing user interaction in WebGL.
+  - Set the class of the main "canvas" element in 
+    writeWebGL() output to "rglWebGL". 
+  - rgl.snapshot() now evaluates the "top" argument after "filename"
+    and "fmt", so windows created when those are evaluated don't
+    overlay the rgl window.  (Suggestion of Keith Jewell.)
+  - Added subsetSlider(), subsetSetter(), clipplaneSlider(), 
+    propertySlider(), ageSetter(), propertySetter(), par3dinterpSetter() and 
+    toggleButton() functions to output HTML/Javascript controls for WebGL.
+  - Fixed bug in abclines3d() that caused it to skip lines that passed
+    through the corners of the bounding box.  (Reported by Sven Laur.)
+  - Added hook_rgl() and hook_webgl() functions, based on the knitr
+    functions. 
+    
+0.95.1336
+  - Made error and warning text more consistent.
+  - Dropped chunk option "rgl.keepopen"; replaced it
+    with "rgl.newwindow". 
+  - Added matrixSetter() function to allow multiple controls to
+    modify one matrix.
+  - Added "accumulate" argument to the subset WebGL controls.
+  - The "nticks" argument to bbox3d() was never used and has
+    been removed.  Use "xlen", "ylen" or "zlen".  
+  - Setting "xlen" etc. to zero in bbox3d or rgl.bbox() now
+    (correctly) suppresses tick marks. (Reported by 
+    Philipp Angerer.)
+  - Dependencies and imports have been updated.
+  - Specifying "normals" or "texcoords" in both a
+    "mesh3d" object and a call to shade3d() to display
+    it caused an error; now the shade3d() specified
+    value has priority if "override" is TRUE (the default).
+  - Added vertexSetter() function to allow easier access to 
+    vertex attributes.
+  - Used Jeroen Ooms' js::jshints() function to clean up the
+    WebGL Javascript code.
+  - Allowed "values = NULL" in propertySetter() and vertexSetter()
+    to allow code to directly set values.
+  - When used with clipping on the bounds, persp3d() and plot3d()
+    did not work properly with a shared mouse.  (Reported by
+    Marian Talbert.)
+  - Shaders are now stored in Javascript strings, not separate
+    <script> sections.
+  - Shape centers are now stored by scene3d().
+  - Font family and numeric font number (style) are now returned
+    by rgl.attrib() and are stored by scene3d().
+  - Fixed a bug (reported by Dominick Samperi) that caused
+    vignettes using WebGL code in knitr to fail to initialize
+    properly.  This required adding the setupKnitr() function, 
+    which should be called at the start of each vignette.  
+    It is *not* called automatically.
+  - Fixed a bug (reported by Kurt Hornik) that caused rgl to
+    fail to compile when libfreetype 2.6 was linked.
+  - Fixed a bug in writePLY (reported by Kurt Hornik).
+
+0.95.1367
+  - Added show2d() to allow a 2d plot on a quadrilateral
+    in a scene.
+  - Fixed bug that sometimes prevented textures from displaying.
+  - rgl.bbox() (and hence bbox3d(), decorate3d(), plot3d(), etc.)
+    did not return the correct id for the bounding box decoration.
+  - Modified configure script to work with OS X 10.11 (suggestion of
+    Brian Ripley).
+
+0.95.1435
+  - The Mac OS X native windowing system (aglrgl.so) has been 
+    dropped; it appears not to work in Yosemite and El Capitan.
+  - A memory leak when drawing semi-transparent objects has been
+    fixed.  (Reported by Felix Kuehnl.)
+  - WebGL code has been moved to the rglwidget package (though
+    the functions in rgl still work).
+  - Bounding box objects sometimes had miscalculated vertices
+    in scene3d().
+  - If rgl.init() fails, continue with the NULL device (with warnings).
+  - scene3d() now returns the normals and offsets of "planes"
+    objects, as with "clipplanes" objects.  It still returns the triangles from embedding the
+    planes in the most recent subscene.
+    
+0.95.1441
+  - Changed rgl.pixels() to attempt to avoid segfault on
+    OSX.  (Thanks to Greg Jefferis for testing and workaround.)
diff --git a/inst/WebGL/template.html b/inst/WebGL/template.html
new file mode 100644
index 0000000..ceb6af1
--- /dev/null
+++ b/inst/WebGL/template.html
@@ -0,0 +1,17 @@
+    <html><head>
+	<TITLE>RGL model</TITLE>
+    </head>
+    <body onload="%prefix%rgl.start();"> 
+    
+    <div align="center">
+    %WebGL%
+    </div>
+    
+	<br>Drag mouse to rotate model. Use mouse wheel or middle button
+	to zoom it.
+	<hr>
+	<br>
+	Object written from rgl %rglVersion% by writeWebGL.
+
+	</body>
+	</html>
diff --git a/inst/demodata/population.dat b/inst/demodata/population.dat
new file mode 100644
index 0000000..9cb966e
--- /dev/null
+++ b/inst/demodata/population.dat
@@ -0,0 +1,86 @@
+structure(c(1.42180393552915, 86.5899178491882, 58.4279463385297, 
+72.5782084880812, 94.7650395805866, 90.716798083558, 4.69523086857405, 
+66.0275494756707, 99.5966041105792, 28.8464020557810, 32.5199596913345, 
+32.8230902358943, 76.092718318592, 90.9491131042477, 67.7715461039384, 
+92.797656673891, 62.8763250044725, 37.8377486848826, 94.8318271447979, 
+16.9384257460335, 66.7528590475565, 72.7664750532169, 86.8409342723528, 
+42.6672130775794, 99.405982755219, 9.87878796385573, 74.0013561791278, 
+73.1367197183745, 95.3562400020557, 69.6064585052911, 74.8777135121351, 
+78.0631738216763, 93.8781220125682, 56.9874829819862, 61.3674564946833, 
+63.7014637339631, 72.5482760946146, 88.150868900621, 59.5874643583287, 
+36.0187577356162, 75.6129656479724, 58.5589693499633, 61.5365704196823, 
+45.4041207738696, 13.9846302678307, 68.6129614502687, 81.1038195579554, 
+54.9328748464894, 56.0090012748281, 63.7824110302102, 71.9080963099627, 
+76.2898655697447, 68.1971407037222, 1.79949925742100, 34.2445376879174, 
+67.752421253536, 70.0160933011249, 59.9881388477488, 62.1375791537896, 
+67.5026055163477, 55.4749773697637, 67.6559503769167, 99.8921368552586, 
+99.7317640238283, 59.5870514252659, 61.1156890017716, 67.7897419835883, 
+93.7373116639762, 64.8624836653151, 66.1630357404153, 70.3541452797023, 
+50.3392945568402, 60.5756891936938, 65.6381806437015, 70.7699265549355, 
+84.263331400059, 36.1455168687146, 63.4268691110022, 50.8403640938551, 
+84.6038580009723, 99.253448377888, 44.5136280754846, 18.3862017952805, 
+35.7157337732417, 84.9943843632923, 96.2500336638768, 51.939143733573, 
+73.937482003108, 20.8390646918768, 13.3791143487625, 2.59180364981103, 
+16.35253761228, 78.7863353881487, 77.0761412272873, 12.7493216227156, 
+97.408350521328, 2.360943911914, 49.5031567931881, 40.9086587196003, 
+89.0041084624836, 0.153641843226189, 0.7205303565414, 2.12973220584209, 
+1.95184155151989, 2.36672693229437, 3.97881615724853, 4.6945903958973, 
+4.97023833854362, 5.02848534249433, 5.93632710737556, 6.5305134302309, 
+7.18124749660055, 7.59205544134417, 8.11782658102872, 9.7053179911583, 
+9.69966472967054, 10.7491681958896, 11.7805969476189, 11.8846419362548, 
+13.2638113615252, 13.6102190943924, 13.3331649454155, 13.3510625511294, 
+14.2866348278910, 14.9188862315656, 17.1073522001289, 17.3771351386274, 
+17.4970376938342, 17.6769213814467, 18.2937976371715, 18.1794471174431, 
+18.4072881564515, 20.2907827372874, 20.7863900870053, 20.8977102997940, 
+20.7898134065768, 21.4861476674877, 21.7151264355786, 22.4866743996941, 
+22.9652880267625, 23.4036320422319, 24.3239211351899, 24.5629717030476, 
+24.9067464934910, 25.3250969786023, 25.569835321831, 25.214928868463, 
+26.3005548932358, 26.5032754860593, 27.9258713661520, 28.3114428871105, 
+29.1348144906887, 29.5927445701307, 30.4762347883257, 30.0503599176301, 
+30.0058225611238, 30.1513380348103, 30.9686341509616, 31.2913000003182, 
+31.5440713840872, 32.7657602884727, 32.5231659352135, 32.5262426292818, 
+33.3124010171537, 33.8478211625125, 33.8467915869427, 33.7026977228706, 
+34.0596679268078, 34.7846046615822, 38.1673741083982, 37.9665159877312, 
+38.8029702374719, 39.0682120522177, 39.5640346008735, 39.4240171975978, 
+40.0765304172124, 41.6115850103115, 43.1095386110501, 43.3832096504008, 
+45.4365823266182, 45.5690791790302, 46.1239852830125, 46.6768080701299, 
+46.7602784573008, 47.285367886742, 48.2420712810108, 50.5906685558592, 
+50.5316655747899, 51.3195670861564, 52.8660801235275, 54.8554989863782, 
+54.8768757654533, 55.6908773693933, 57.0974418796826, 57.7205567191636, 
+57.7134194371089, 58.3266436293085, 58.6607370311536, 59.3980795544102, 
+59.9830194632018, 4, 3, 2, 3, 4, 2, 4, 4, 3, 3, 8, 2, 2, 6, 8, 
+2, 4, 6, 5, 4, 8, 6, 3, 4, 4, 2, 1, 4, 3, 4, 4, 4, 3, 7, 4, 4, 
+2, 6, 3, 8, 3, 2, 5, 3, 5, 8, 3, 8, 5, 1, 3, 8, 5, 7, 4, 3, 5, 
+4, 6, 3, 5, 3, 6, 3, 5, 1, 2, 3, 3, 2, 5, 7, 3, 7, 1, 7, 3, 6, 
+5, 5, 5, 2, 5, 6, 3, 2, 4, 6, 3, 2, 3, 2, 3, 2, 7, 3, 6, 4, 1, 
+4, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 
+1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 
+0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 
+0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 
+0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 7.57114372433513, 
+6.85515173418126, 7.52609590470221, 3.5563844241623, 7.14112545928597, 
+5.12301007753458, 3.87663849439702, 5.79586417334239, 4.70184865517279, 
+6.21920562188609, 5.44360907485348, 4.51873716824026, 6.33491917603443, 
+5.20292601299676, 6.59676653073395, 5.81501493098883, 7.54559052637168, 
+5.6635169145202, 5.88625186391175, 6.18255547931158, 3.9011827688165, 
+7.92338945754762, 7.08656410296135, 7.25722570643227, 6.23413330258138, 
+5.88738222841769, 6.80735796658865, 5.28594790472374, 4.39548032693523, 
+6.12184517302476, 6.74384685192469, 7.60827115628042, 5.07457171988406, 
+8.50778221649775, 4.38150950099637, 7.52973226807595, 6.5506735931328, 
+3.87367222602665, 6.3649749543402, 5.84328626826638, 4.12479223028613, 
+5.88500632343836, 6.93493363615338, 6.66363247928469, 4.65955611058411, 
+8.15391551804086, 6.76397691227767, 5.36981173805678, 5.98744841170566, 
+7.11136219546026, 5.78287045204801, 6.14081537593665, 3.82726802701466, 
+3.20879873107543, 6.17821147407116, 7.37261655390293, 6.52738206698354, 
+7.04683222470034, 4.8916109987783, 6.56523496429719, 6.83082908120187, 
+7.87149902967823, 5.62770948691443, 3.2651491532768, 3.59665266985329, 
+6.54074671207657, 5.77568350127988, 5.96246550437346, 7.05488722838375, 
+6.38605274449675, 4.96442316344611, 6.48378363921246, 3.84255493400238, 
+4.38857837779543, 6.19366965736775, 4.84260035340659, 5.07260834973452, 
+2.88965797522147, 7.15143574153486, 7.12539568924814, 7.40644952344348, 
+6.59220641889174, 4.81483959103117, 5.32577121795078, 4.23104750753301, 
+8.90629459075072, 7.92242700824242, 6.06571137725015, 6.31187612654388, 
+6.60321800321983, 5.8189575929551, 7.40216872384802, 5.58163040684314, 
+4.68926346360419, 4.50539905884038, 6.21368299483713, 3.96679382670128, 
+5.61336655902108, 3.52559103095651, 6.69183050760578), .Dim = c(100, 
+5), .Dimnames = list(NULL, c("x1", "x2", "x3", "x4", "x5")))
diff --git a/inst/demodata/region.dat b/inst/demodata/region.dat
new file mode 100644
index 0000000..3cb0eeb
--- /dev/null
+++ b/inst/demodata/region.dat
@@ -0,0 +1,2414 @@
+structure(c(3.71114253706474, 4.01779675877195, 4.28656904179763, 
+4.50076660092056, 4.64619071647352, 4.71349254349867, 4.70016541088465, 
+4.6115552355105, 4.46032928164021, 4.26421093830594, 4.04246933185776, 
+3.81237141855995, 3.58704556714176, 3.3755855810663, 3.18495554003389, 
+3.02218397671240, 2.89530357041327, 2.81254466310459, 2.78056540241673, 
+2.80300294351220, 2.88011139818937, 3.00931780934633, 3.18596283700096, 
+0, 0, 0, 0, 4.4710591748498, 4.70948819878899, 4.89872181207017, 
+5.02051921157744, 5.06013125543746, 5.00806359728137, 4.86128360217772, 
+4.62371056612909, 4.3059981576005, 3.92478071983061, 3.50164515839338, 
+3.06203621718930, 2.63406742028284, 2.24685725266602, 1.92776393521573, 
+1.69808969649104, 1.56769252810029, 1.53026304325852, 1.56198954045970, 
+1.62591227445305, 1.68203461740870, 1.70009636765875, 1.66977099576159, 
+1.60362803966042, 1.53152411467252, 1.48923433055194, 1.50658148407650, 
+1.59976708640559, 1.76980341966483, 2.00588212663519, 2.29087619783296, 
+2.60634981646881, 2.93570324219523, 3.26537586715308, 3.58475345647643, 
+3.88553154486786, 4.16105219094723, 4.40584254917525, 4.61538792773383, 
+4.78608624645687, 4.9153144358217, 5.00154838089022, 5.04449334533078, 
+5.04519407167202, 5.00610295131046, 4.93109270334441, 4.82540890084237, 
+4.69556887426935, 4.54922639597066, 4.39503116727252, 4.24250812929838, 
+4.10195127908395, 3.98426397117676, 3.90059628895129, 3.86157237320898, 
+3.875930868916, 3.94857501129059, 4.07834266816769, 4.25616177675292, 
+4.46446713258873, 4.67862714035609, 4.87058793953534, 5.01412481357765, 
+5.09033389715201, 5.09168693783603, 5.02332625411098, 4.90119624927908, 
+4.74770066164599, 4.58635961145821, 4.43710111451504, 4.3133594571693, 
+4.22135156130706, 4.16114656990489, 3.89700585253865, 4.22886109942203, 
+4.51989598517139, 4.75159744128911, 4.90823191543841, 4.97952661958404, 
+4.96293748642882, 4.86476859750004, 4.6994670657364, 4.48686171586016, 
+4.24795638915308, 4.00078219162283, 3.75810141673599, 3.52794979776719, 
+3.31638022180937, 3.13041853986297, 2.97924097477999, 2.87297940538678, 
+2.82023105721542, 2.82600130300695, 2.89112371800521, 3.01296791072630, 
+3.18648583748062, 0, 0, 0, 0, 4.50221868296492, 4.7516899946142, 
+4.9516531839248, 5.082955652852, 5.1300650773303, 5.08292656463883, 
+4.93823727132185, 4.69997410774362, 4.37919223567675, 3.99328528742998, 
+3.56498907339343, 3.1213377615046, 2.69250181926538, 2.31002585322016, 
+2.00370441153561, 1.79658133865914, 1.69859792364187, 1.70098738444312, 
+1.77466075574443, 1.87532702065300, 1.95543750057437, 1.97928918103662, 
+1.93507581107475, 1.83836096274211, 1.72538731886278, 1.63955718677841, 
+1.61732045387912, 1.67905006815417, 1.82715792126502, 2.05006946864233, 
+2.32873107131955, 2.64253414898331, 2.97302597060795, 3.30531446627761, 
+3.62793280033241, 3.93205639715069, 4.21068787819006, 4.4580836524531, 
+4.66946367582298, 4.84094343206792, 4.96960661004997, 5.05364903135097, 
+5.09254206573137, 5.08717842625571, 5.03997454196596, 4.95491342105982, 
+4.83752207099119, 4.69478986941448, 4.53504840526328, 4.36784376135249, 
+4.20382689937575, 4.05465166788792, 3.93279588797054, 3.85112544719211, 
+3.82195505112571, 3.85539873784604, 3.95701349573957, 4.12511594726059, 
+4.34857545942243, 4.60613454167730, 4.86814875657774, 5.10098478490398, 
+5.27333376568751, 5.36279239738902, 5.36069847492058, 5.27363958658383, 
+5.1211611847113, 4.93051219370601, 4.73020510080281, 4.54435513247573, 
+4.38920343104757, 4.27226439017113, 4.19362928795208, 4.07491302868166, 
+4.43137640497536, 4.74406166052454, 4.9926297010233, 5.15982359856952, 
+5.23448867730731, 5.21412680149075, 5.10612385396442, 4.92684837773999, 
+4.69834717863986, 4.44338253639325, 4.18064029313238, 3.92227731972436, 
+3.67496540712135, 3.44357440615526, 3.23497684833404, 3.05949095243323, 
+2.92925673262058, 2.85494715648567, 2.84303490375728, 2.89496815677644, 
+3.00804511559018, 3.17680092865961, 0, 0, 0, 0, 4.51256600745384, 
+4.77118198839211, 4.98039115601543, 5.12027121224973, 5.17461961486849, 
+5.1328918519855, 4.99153538658068, 4.75455222836937, 4.43331664565167, 
+4.04585702517308, 3.61590167934052, 3.17189678677550, 2.74588183039085, 
+2.37164001810793, 2.08122868154864, 1.89929185486929, 1.83576647020625, 
+1.87941363534475, 1.99593213579537, 2.13383002199728, 2.23816559651834, 
+2.26793236038767, 2.20992248050721, 2.08269328009899, 1.92880792169203, 
+1.79920002605776, 1.73685986555595, 1.76628213628716, 1.89127491418130, 
+2.09953411782598, 2.37014302001071, 2.68039813788614, 3.01007734098488, 
+3.34304116504317, 3.66705045981566, 3.97283202531075, 4.25310580572896, 
+4.50189387402052, 4.71416321029967, 4.88573462611568, 5.01336445036647, 
+5.09491781913378, 5.12957205259379, 5.11800578767904, 5.06254334590535, 
+4.96723546090745, 4.83786880428998, 4.68190988310029, 4.50840402964777, 
+4.32786160512497, 4.15215729250468, 3.99442669625632, 3.86885892017108, 
+3.79017369120736, 3.77249647693588, 3.82739440219987, 3.96108511064196, 
+4.17127365178147, 4.4445675267108, 4.75570559773734, 5.06964350463872, 
+5.34676455354722, 5.55032940147435, 5.65421722586217, 5.64858771723579, 
+5.54160930140493, 5.35670754719982, 5.12633272245133, 4.88434721757477, 
+4.65934894211133, 4.47058257016638, 4.32695132260256, 4.2285720486294, 
+4.24122540292336, 4.62116113538191, 4.95438657223701, 5.21876415677214, 
+5.39555008410446, 5.47275846063356, 5.44800604047671, 5.32984611012871, 
+5.13665838969873, 4.89277650468045, 4.62273732336765, 4.34582023497493, 
+4.07343636722213, 3.810702008461, 3.56110913684306, 3.33122436372728, 
+3.13241919836277, 2.97880859607307, 2.88313687697481, 2.85334285313893, 
+2.89148043165617, 2.99476492550612, 3.15731440882888, 0, 0, 0, 
+0, 4.50171657383887, 4.76725753659364, 4.98391420212611, 5.13116282900903, 
+5.1922661357174, 5.15627751914707, 5.01942414072968, 4.78570024311716, 
+4.46670539018071, 4.08095251099637, 3.65296076842997, 3.21233916861373, 
+2.79270466101750, 2.42975911543662, 2.15750800485746, 2.00194697805369, 
+1.97290760545717, 2.05680079909251, 2.21448505094414, 2.38783204204583, 
+2.51511906195553, 2.55050705299750, 2.47956187763093, 2.32366368567253, 
+2.13125434717041, 1.96024829618887, 1.85969010927111, 1.85789019005685, 
+1.95995656723782, 2.15292894462235, 2.41419938144864, 2.71917457572363, 
+3.04605980854715, 3.37763903739759, 3.70104207993791, 4.0066596719188, 
+4.28701275012887, 4.53594203423922, 4.74818224238988, 4.91924859716058, 
+5.0455312332008, 5.1245042206177, 5.15497690116675, 5.13733511295875, 
+5.07373669524447, 4.96823945877397, 4.82685190757809, 4.65751022716956, 
+4.47000078714063, 4.27586004803647, 4.08827750731205, 3.92198115254226, 
+3.79298841716358, 3.71798094621164, 3.7129773306653, 3.79103740160411, 
+3.95902096501416, 4.21393440130147, 4.53996622440893, 4.90763596210863, 
+5.2762508723412, 5.59996715677052, 5.83641800129229, 5.95565099187045, 
+5.94663664988127, 5.81921394310418, 5.60085503437514, 5.32941642729954, 
+5.04431237182853, 4.77878912630848, 4.55520577161284, 4.38390793508276, 
+4.26504410647743, 4.39225106037538, 4.79396804520538, 5.14611996984028, 
+5.42483326807406, 5.60993793463673, 5.68867132093289, 5.65880980205548, 
+5.53010717831344, 5.32297639746498, 5.06405217388541, 4.77965665147626, 
+4.48967031795952, 4.2047542989952, 3.92843467196028, 3.66273953019106, 
+3.41378301857579, 3.19379583799207, 3.01865975830088, 2.90300820605021, 
+2.85611884970752, 2.88058823266243, 2.9735423438331, 0, 0, 0, 
+0, 0, 4.46990199737718, 4.73987574167139, 4.96190456482528, 5.11505470389628, 
+5.18220991309226, 5.1521245533833, 5.02084405362733, 4.79232338272826, 
+4.47828509589732, 4.09755449206992, 3.67519853986911, 3.24167134108731, 
+2.83177400292007, 2.48267477890587, 2.22987001970025, 2.10034909124184, 
+2.10372263900162, 2.22431142235542, 2.41881776360557, 2.62348424628304, 
+2.77088172818290, 2.81114872275059, 2.72890006867141, 2.54799419315954, 
+2.32192590149148, 2.11457523794484, 1.98014614227148, 1.95019548051183, 
+2.03093866001168, 2.20886850617957, 2.45996734876978, 2.75808668983349, 
+3.08017203900379, 3.40819131657945, 3.72884861202347, 4.0323551632616, 
+4.31114613407575, 4.55895262928926, 4.77030771005267, 4.94041222908187, 
+5.06524654553613, 5.14182247384686, 5.1684913753007, 5.14524718176656, 
+5.07398365091871, 4.95868121045947, 4.80551075245565, 4.62285369501289, 
+4.42125318798466, 4.21332585330744, 4.01365902931349, 3.83866990671195, 
+3.70629693370025, 3.63525496763948, 3.64349213032120, 3.74555519446323, 
+3.94889875892279, 4.2497504163714, 4.62978257035287, 5.05520033820381, 
+5.47958685929801, 5.85082565729932, 6.12090902055605, 6.2560655785137, 
+6.24410445923309, 6.0965665384933, 5.84499696590647, 5.53267619305043, 
+5.20458022402375, 4.89860926258534, 4.64024189155383, 4.4412730926733, 
+4.30189217947355, 4.52437843842459, 4.94563928171095, 5.31461493278886, 
+5.60579355197354, 5.79766253426646, 5.87673715030005, 5.84096762741382, 
+5.70128032214276, 5.48006656370948, 5.20621525860416, 4.90783916928748, 
+4.60550604955838, 4.30927790978361, 4.02123569485505, 3.74198478298928, 
+3.47705295448595, 3.23922363790154, 3.04574632229705, 2.91276616126612, 
+2.8506343693205, 2.86236864768995, 2.94500619894028, 0, 0, 0, 
+0, 4.12222479140656, 4.41797158524696, 4.68967588389628, 4.91477578678273, 
+5.07213798082884, 5.14444018331966, 5.1202545958934, 4.99549272909628, 
+4.77404215624414, 4.46764166314082, 4.09524084058210, 3.68217814680073, 
+3.25937678434531, 2.86233933325241, 2.52912956051951, 2.29614783229777, 
+2.19091846344185, 2.22269982825905, 2.37410529101064, 2.59864656642528, 
+2.82834566045499, 2.99156227602585, 3.03553236305217, 2.94428795541026, 
+2.74366537143984, 2.49103886233603, 2.25481679152423, 2.09309511383225, 
+2.03986703294317, 2.10217310107382, 2.26609933197402, 2.50659806475214, 
+2.79641767544558, 3.11166318452061, 3.43383089199968, 3.74946598763345, 
+4.04880064228538, 4.32432820259532, 4.56976229176694, 4.77947640978951, 
+4.94835162817009, 5.0719107669163, 5.14662085877274, 5.17026705559572, 
+5.14232768936262, 5.06430542447896, 4.93998767039331, 4.77561956268827, 
+4.57998103510349, 4.36437362187791, 4.14254024951007, 3.93054203452818, 
+3.74656882028543, 3.61054702563459, 3.54325576201809, 3.56455833759209, 
+3.69043278348098, 3.9288500657618, 4.27518835558542, 4.70857618845026, 
+5.19094717819963, 5.67028165339388, 6.08837049564086, 6.39176004025996, 
+6.54301567131396, 6.52885584921441, 6.3624875003779, 6.07939557972459, 
+5.72808957229962, 5.35889914276413, 5.01420232528685, 4.7224820692474, 
+4.4969364326753, 4.33780790914313, 4.63421938830739, 5.07227150071444, 
+5.45551299468007, 5.7569257384984, 5.95375956164311, 6.03186111487858, 
+5.98933751524211, 5.83819900578265, 5.60268443709929, 5.31382887495504, 
+5.00153336867663, 4.68721254691924, 4.3806286030896, 4.08273662556706, 
+3.79288595030719, 3.51590031888879, 3.2647051722316, 3.05733804039149, 
+2.91089328509889, 2.83639988339644, 2.83712101701803, 2.91001356693944, 
+0, 0, 0, 0, 4.0543607583253, 4.34736224864797, 4.61795771556188, 
+4.8436641730507, 5.00337316297953, 5.07974246107731, 5.06129049907384, 
+4.94385172790372, 4.73122381735371, 4.43505553174343, 4.07422493220536, 
+3.67404450441306, 3.26548937511235, 2.88421419523044, 2.56851599557929, 
+2.35501014538399, 2.27121533388073, 2.32588941918418, 2.50041178801474, 
+2.74628426000971, 2.99302708185691, 3.16661181858213, 3.21273515564775, 
+3.11529049044952, 2.901474139069, 2.63109859583607, 2.37533608091850, 
+2.19461689755169, 2.12437094604672, 2.17210895143643, 2.32367111983467, 
+2.55343394154111, 2.83358575614840, 3.13989495230659, 3.45379970060349, 
+3.76200642296972, 4.05500907683318, 4.32553334507004, 4.56738891660688, 
+4.7748450398943, 4.94246285798426, 5.06525723075913, 5.13905691870026, 
+5.16095262730448, 5.12975404584442, 5.04640853204392, 4.91435404130698, 
+4.73978391717514, 4.53180134197104, 4.30245183870978, 4.06664520380553, 
+3.8419899662917, 3.64852363251879, 3.50820520953431, 3.44387022921621, 
+3.47723195202623, 3.625593168207, 3.89733066737768, 4.28691161216511, 
+4.77096401128823, 5.30733666655624, 5.83873597184363, 6.30127921832531, 
+6.63648269389814, 6.80355558332298, 6.78824153148795, 6.60530669563235, 
+6.29387482578498, 5.90726611599113, 5.50072664962259, 5.12074485150309, 
+4.79856590173797, 4.54868793977738, 4.37142159085302, 4.7187537334399, 
+5.17038151825482, 5.56492718242987, 5.87402972368622, 6.07382604157255, 
+6.14954753947655, 6.09941609168555, 5.93638765885159, 5.68635505133456, 
+5.38233892247458, 5.05601431996438, 4.72985390975367, 4.41373154731433, 
+4.10793127797224, 3.81081313222161, 3.52639439536079, 3.26725180149393, 
+3.05149037241562, 2.89644672123608, 2.81333110434166, 2.80543617425376, 
+2.86965475010813, 0, 0, 0, 0, 3.97276990451914, 4.26003827386985, 
+4.52662843436359, 4.75038429011679, 4.91045465809386, 4.98967195069152, 
+4.97663788054682, 4.86717522795664, 4.66497712374533, 4.38150211772178, 
+4.03536286842535, 3.65154249683142, 3.26063219669426, 2.89785357656792, 
+2.60102157708710, 2.40621480555622, 2.34035190548911, 2.41152425671554, 
+2.60039579848306, 2.85775890850993, 3.11252956113543, 3.29030690300051, 
+3.33675835840157, 3.23613351553983, 3.01630841857296, 2.737940830149, 
+2.47301318314949, 2.28256188320369, 2.20233976406911, 2.2399254990554, 
+2.38108202905808, 2.60010443649768, 2.86921683847191, 3.16440717976567, 
+3.46751559778716, 3.76576988490860, 4.05020054491997, 4.3139677763999, 
+4.5511127295829, 4.75587093369906, 4.92249161473922, 5.0454315521492, 
+5.1197785152016, 5.14177936138252, 5.10938726619937, 5.02278285546114, 
+4.88484459005568, 4.70153796336422, 4.48217798052837, 4.23952307863794, 
+3.98969096073363, 3.75191916753923, 3.54817065938062, 3.40246917042756, 
+3.33966775355409, 3.38321937126527, 3.55159762097857, 3.85344158868433, 
+4.28224854432901, 4.81225009743090, 5.39753065171361, 5.97605304705234, 
+6.47891727676002, 6.84324649908228, 7.02535203845866, 7.01016403787899, 
+6.81383246277487, 6.4786560782124, 6.06213079339533, 5.62375927405432, 
+5.21358637646652, 4.86525276239859, 4.5943970849878, 4.40141421275043, 
+4.77546662845339, 5.23706235859208, 5.6396119297589, 5.95360135952351, 
+6.15419628043112, 6.2260694989708, 6.16750298426093, 5.99223302771255, 
+5.7275764863723, 5.40834472437697, 5.06795586800001, 4.73016670230584, 
+4.40542273210376, 4.09385713114715, 3.79315858297812, 3.50644401879233, 
+3.24540859071695, 3.02742952271926, 2.86930348489247, 2.78187582184568, 
+2.76823579037145, 2.82523519053189, 0, 0, 0, 0, 3.87978717178604, 
+4.15840456595246, 4.41811953779152, 4.63735115314415, 4.79573949470505, 
+4.87648947745451, 4.86842849995224, 4.76744071693814, 4.57711001969853, 
+4.30861626343306, 3.98012512985339, 3.61599788647548, 3.24601284159768, 
+2.90437370106838, 2.62768987153482, 2.45073550259769, 2.39921458462532, 
+2.48036807259369, 2.67465472685892, 2.93346486607224, 3.18703015316856, 
+3.36262512130317, 3.40742927317881, 3.3065633091387, 3.08790545990051, 
+2.81135161723768, 2.54771570179163, 2.35688407219232, 2.27379476309823, 
+2.30567581129097, 2.43837355966422, 2.64659616284687, 2.90320645446021, 
+3.18498162837201, 3.474642893516, 3.76032259671493, 4.03388750059585, 
+4.28915894929571, 4.52056679695071, 4.72240115387749, 4.888619823768, 
+5.0130766434524, 5.09001008090792, 5.11465230098389, 5.08387080641865, 
+4.99680776886555, 4.8555012931597, 4.6654467300428, 4.43601388338495, 
+4.18062732793338, 3.91666534239503, 3.6651017464766, 3.4499250982844, 
+3.2972618002663, 3.23392854340511, 3.28497616207010, 3.46985570012423, 
+3.79728930839534, 4.25973082572584, 4.82915138004083, 5.45629424288163, 
+6.07508712789851, 6.61249218490676, 7.00208872258732, 7.19789390827433, 
+7.18423025782933, 6.97839584318949, 6.62525644206309, 6.18565703788797, 
+5.72249974146896, 5.28866546469499, 4.91971103171681, 4.63220334211714, 
+4.42663627985062, 4.80247001974546, 5.27011984986897, 5.67710917415651, 
+5.99297990875967, 6.1920811930721, 6.25859178170409, 6.19080433947539, 
+6.0030744433197, 5.72391457799209, 5.38972528172021, 5.03561747695123, 
+4.68682724142573, 4.35479710821947, 4.04000121045724, 3.73975859791, 
+3.45618724819807, 3.19957112216633, 2.98577352569701, 2.83028377649005, 
+2.74305417182548, 2.72675266739475, 2.77821840223208, 0, 0, 0, 
+0, 3.77799821273446, 4.0451988389428, 4.29527887839908, 4.50747407829273, 
+4.66214473016431, 4.74306393537978, 4.73942888709712, 4.64726453978517, 
+4.47005239376277, 4.21862203745574, 3.91053285711592, 3.5692593131588, 
+3.22337051905335, 2.90550429476842, 2.65037921316086, 2.49072978166204, 
+2.45044578003383, 2.53571639760076, 2.72724328731843, 2.97821386434215, 
+3.22195787365123, 3.38934015348133, 3.43050612202610, 3.33195066185616, 
+3.12094566484782, 2.85514474475821, 2.60235786695393, 2.41968393932387, 
+2.34017744180246, 2.37031303278676, 2.49615784678524, 2.69328648233986, 
+2.93576354761783, 3.20169818691637, 3.47516141836105, 3.74557766914899, 
+4.00596416322597, 4.25104989168577, 4.47583230700778, 4.67476556528333, 
+4.84155526598606, 4.96942026972381, 5.05164194277751, 5.08224630517719, 
+5.05673694463811, 4.97286837074075, 4.83146355008879, 4.63721748976397, 
+4.39934022568186, 4.13186305316887, 3.85350688050387, 3.58714199106592, 
+3.35893523856651, 3.19718841270064, 3.13063968044945, 3.18578743988191, 
+3.38284051465872, 3.73038101535741, 4.21969441824634, 4.82060119165937, 
+5.48097166753056, 6.13154589915124, 6.69623301907905, 7.10612256961282, 
+7.31368087262304, 7.30287233450894, 7.09185969716232, 6.72735312017427, 
+6.2725696847365, 5.79279915422354, 5.3429061428228, 4.95979278259604, 
+4.66069645025358, 4.44621974538603, 4.79860028523471, 5.26818118744296, 
+5.67586205647178, 5.99045848687793, 6.18566518356959, 6.24524371809209, 
+6.16747362750522, 5.9672101989973, 5.67398017565461, 5.32560026115805, 
+4.95880616361247, 4.60043058473645, 4.26321394554523, 3.94833086278696, 
+3.65293865547108, 3.37803332202554, 3.13200584711355, 2.92851767527852, 
+2.78109765660189, 2.69837299276269, 2.68242570116859, 2.73011443197831, 
+0, 0, 0, 0, 3.67012243594377, 3.92336961540529, 4.16124489744943, 
+4.36402907112446, 4.51302016005368, 4.59274747878707, 4.59291996744294, 
+4.50978748110112, 4.34674844919528, 4.11423170043855, 3.82906175490214, 
+3.51360340906885, 3.19487578232719, 2.9034725414926, 2.67161600734074, 
+2.52934242352246, 2.49817540779703, 2.58303543420119, 2.76520599139444, 
+3.0006606739691, 3.22732978128740, 3.38130321466654, 3.41695207805157, 
+3.32260734787202, 3.12445336790189, 2.87667284560786, 2.6425295108776, 
+2.47494704538026, 2.40417987802154, 2.43559163585020, 2.55557107065122, 
+2.74093494065728, 2.96743054869448, 3.21497767734516, 3.4694279090718, 
+3.72187123433537, 3.96679308934991, 4.20009137352893, 4.41753157285494, 
+4.61386708248057, 4.78261784834966, 4.91635929340923, 5.00731746407215, 
+5.04810232990364, 5.03251676161986, 4.95647863238416, 4.8190966484354, 
+4.62381882883875, 4.37940811596318, 4.10043587619462, 3.80710271694531, 
+3.52442723654263, 3.28100292878479, 3.10745670064492, 3.03445813751898, 
+3.08983017901495, 3.29431218824815, 3.65606030142776, 4.16494679171776, 
+4.78862365602126, 5.47250834207583, 6.14509006302842, 6.7285090651162, 
+7.15263446380243, 7.36926941872251, 7.36231427498401, 7.15047829911452, 
+6.78151390553348, 6.3199354818303, 5.83230999794829, 5.37454732821478, 
+4.9842607055508, 4.6790643453964, 4.45966912577065, 4.7634856335994, 
+5.23076900575989, 5.63529075412713, 5.94535452443002, 6.13416198359387, 
+6.18514947255902, 6.09660462278803, 5.88384180215846, 5.57731514373678, 
+5.21615202759857, 4.83863476552199, 4.47319293099221, 4.13395930843905, 
+3.82293806528228, 3.53716203774516, 3.27633243203328, 3.04654801236977, 
+2.85875886266293, 2.7240914258893, 2.6495936061982, 2.63669325733159, 
+2.68230312557212, 0, 0, 0, 0, 3.55889181126306, 3.79594771068907, 
+4.01931107143418, 4.21051792131906, 4.35200445658842, 4.42923138352605, 
+4.43255526596698, 4.35853750062431, 4.21052526831992, 3.99851988778449, 
+3.73851929427134, 3.45160874590754, 3.16298948564507, 2.90082773675253, 
+2.69435640992194, 2.5703659877223, 2.54753586126203, 2.62928854357335, 
+2.79768573910094, 3.01219107666590, 3.21645166373023, 3.35302627013252, 
+3.38149648473676, 3.29242683457909, 3.11060265631865, 2.88585172770531, 
+2.67575439064467, 2.52801921172838, 2.46939931592673, 2.50385738417156, 
+2.61815868255717, 2.79063294160187, 2.99907671408684, 3.22560597861603, 
+3.45822286881537, 3.69002612717348, 3.91728021029953, 4.13732273336216, 
+4.34690939191277, 4.54125968138225, 4.71381302806997, 4.85653078244177, 
+4.96050740798815, 5.01671212005329, 5.01684043272585, 4.95439695021873, 
+4.82611405788608, 4.63359335579182, 4.38477145477466, 4.09469359599033, 
+3.78526629606398, 3.48405142062912, 3.22247076890368, 3.03376104727827, 
+2.95064289135499, 3.00222025713222, 3.20955346363039, 3.57998755983265, 
+4.10150103756086, 4.73926847566972, 5.43648881936621, 6.12037394678793, 
+6.71280568240996, 7.14396878714872, 7.36606453278633, 7.36327269215247, 
+7.15450409877892, 6.78770415429329, 6.32756779313453, 5.8407931148302, 
+5.38336348402251, 4.99293816218283, 4.68718950595144, 4.46691971061376, 
+4.69757891029593, 5.15833718320386, 5.55582856579325, 5.85804226439464, 
+6.03783803563582, 6.07843403802448, 5.9782073782275, 5.75300153549868, 
+5.4342476440385, 5.0623829469143, 4.67716123492882, 4.30846801165701, 
+3.97165680185852, 3.66938359593077, 3.39835858017991, 3.1567365882599, 
+2.94802503287358, 2.78019128707897, 2.66181278484295, 2.59836226726451, 
+2.59068853468894, 2.63579375395151, 0, 0, 0, 0, 3.44693260499254, 
+3.66591909353684, 3.87278899234073, 4.05052278041977, 4.18287369302662, 
+4.25639153578144, 4.2622064772513, 4.19727810136438, 4.06494567962549, 
+3.87478083678907, 3.64190313848658, 3.38600753643480, 3.1302926568833, 
+2.90022415967459, 2.72168450510276, 2.61780382286102, 2.60403081730423, 
+2.68205361867667, 2.83475031096862, 3.02545346316872, 3.20419874371826, 
+3.32080452789023, 3.34072612333029, 3.25707944082382, 3.09313046323638, 
+2.89386250328332, 2.71050184252012, 2.58490456492980, 2.53987223674973, 
+2.57775810509896, 2.68570866826787, 2.84371768025971, 3.03186441761490, 
+3.2347352122373, 3.44277607762599, 3.65139453604868, 3.85892854314071, 
+4.06443074725669, 4.26589154423311, 4.45920230865071, 4.63787942450616, 
+4.79335499867336, 4.91555325333559, 4.99356849345013, 5.01649976832395, 
+4.97470124064199, 4.86165776558416, 4.67632840308658, 4.42532897311606, 
+4.12412219381925, 3.79667769381832, 3.47370220716348, 3.1900731270557, 
+2.98213144353705, 2.88495564266196, 2.92903863614969, 3.13560230704533, 
+3.51063656133243, 4.03933253218333, 4.68354556016222, 5.38411550899288, 
+6.06794065661645, 6.65846353627748, 7.0881032627675, 7.31076184568369, 
+7.31130239155569, 7.10846201214203, 6.74950276616621, 6.2981912279164, 
+5.82023721715296, 5.37074647706468, 4.98676170346079, 4.68568020452808, 
+4.46835448130839, 4.60215383659388, 5.05226742776673, 5.43891969104848, 
+5.72995327304418, 5.89801692942429, 5.92622972127119, 5.81320742197126, 
+5.57552300620124, 5.24579898853505, 4.86591441281175, 4.47703875130912, 
+4.11022672391526, 3.78158811108863, 3.49390500928120, 3.24308915916836, 
+3.02538968250961, 2.84152048657846, 2.69646476542108, 2.59646435043476, 
+2.54575487559735, 2.54487406447010, 2.59094677305295, 0, 0, 0, 
+0, 3.33665719647678, 3.53610669512673, 3.72487822429742, 3.88756488980770, 
+4.00939130688132, 4.07813280841131, 4.08580568729736, 4.02985149668746, 
+3.91365442663768, 3.74637764030111, 3.54225028317313, 3.31952628563305, 
+3.09930249040823, 2.90418533796918, 2.75648424196924, 2.67539528529486, 
+2.67285012869733, 2.74856602238639, 2.88612093755650, 3.05276886421297, 
+3.20515479320831, 3.30068473203858, 3.31101972959487, 3.23205880337121, 
+3.08561788191272, 2.91174422699507, 2.75511253171016, 2.65149904924011, 
+2.61956085029432, 2.65991867187630, 2.76005604427085, 2.90166058375622, 
+3.06719064523968, 3.2438592740398, 3.42476481264968, 3.6078714589543, 
+3.79386080942959, 3.98377555355549, 4.17710831013604, 4.3706750550028, 
+4.55829441326756, 4.7310296683252, 4.87765208755995, 4.9851447288948, 
+5.03942606726333, 5.0267668491283, 4.93627330280364, 4.76322009932108, 
+4.51226584406615, 4.19925375346751, 3.85075130384167, 3.50149033381804, 
+3.1907404033999, 2.95874060952439, 2.84351757830052, 2.87730400737198, 
+3.08141353219187, 3.45969318691837, 3.99299890232162, 4.6381704789745, 
+5.33293446850391, 6.00479717775991, 6.58103895596515, 6.99880610184325, 
+7.215358359247, 7.21672436277878, 7.02104281064125, 6.67398971985216, 
+6.23733798050489, 5.77477054362346, 5.33963458646905, 4.9677268484968, 
+4.67583093682652, 4.46477635134101, 4.47926509606809, 4.91482817825166, 
+5.28698242329011, 5.56355255431041, 5.71707883282257, 5.73070678084673, 
+5.6035057911057, 5.35311112710058, 5.01372233718404, 4.62893586750874, 
+4.24131480388836, 3.88266603637585, 3.56911035028463, 3.30268521238054, 
+3.07773961839196, 2.88812668375766, 2.73163941325851, 2.61054677043347, 
+2.52936888944549, 2.49184180398565, 2.49870155329940, 0, 0, 0, 
+0, 0, 3.23017308556017, 3.40906799032475, 3.57855020799175, 3.72497534993697, 
+3.83516794636285, 3.89824116634359, 3.90719331057992, 3.86002572242012, 
+3.7602268320787, 3.61659294495419, 3.44248712307173, 3.25472765361836, 
+3.07229114563930, 2.91487484108862, 2.8011248718597, 2.74616591476099, 
+2.75822653530803, 2.83482562398059, 2.95999120091270, 3.10465835665471, 
+3.23189208047814, 3.30658960326434, 3.30664250881027, 3.230879776214, 
+3.0999036661104, 2.94909257748605, 2.81680175405271, 2.73287461221186, 
+2.71186749418326, 2.75262609604792, 2.84288421813823, 2.96594285597348, 
+3.10660817077224, 3.25476307583297, 3.40628074223116, 3.56187250678000, 
+3.72480266294644, 3.89837378190258, 4.08387148675017, 4.27934362658137, 
+4.47921957278528, 4.67445046343636, 4.85274751112202, 4.9987535163439, 
+5.09451770022406, 5.12106641091667, 5.0616877091622, 4.90663578065608, 
+4.65780570637303, 4.33141124723265, 3.95737499831703, 3.57568492909152, 
+3.23133501077393, 2.96965110914430, 2.83258760726373, 2.85481264661715, 
+3.05779381541624, 3.44210288909926, 3.98177775273799, 4.62572292632957, 
+5.3069194193525, 5.95434525584665, 6.50205366900407, 6.89523167870392, 
+7.09665432697269, 7.09409918614135, 6.90460025584298, 6.57130051258724, 
+6.15297636131757, 5.71036744799306, 5.29429220278684, 4.93873052332892, 
+4.65951484307744, 4.45733782852156, 4.33167479118716, 4.74909910063414, 
+5.10334209735486, 5.36229619107485, 5.49846336248573, 5.49514087676297, 
+5.35211964347078, 5.08854273463045, 4.74072171474158, 4.35437588265863, 
+3.97347988957932, 3.63007770987852, 3.33932666269526, 3.10135509648407, 
+2.90792391225931, 2.74986011270857, 2.62194916591391, 2.52426041983072, 
+2.4606168066579, 2.43543542182541, 2.45043950744652, 0, 0, 0, 
+0, 2.97344218018593, 3.12921608661597, 3.28701407566672, 3.43645213099226, 
+3.56578448860047, 3.66353842806582, 3.72025128160923, 3.72997992123203, 
+3.69135414653498, 3.60802865711773, 3.48849020909223, 3.3452904882166, 
+3.19386559091311, 3.05112343314247, 2.93389702996387, 2.85719566616386, 
+2.8320574429166, 2.86291610088224, 2.94488459695206, 3.06209302955571, 
+3.18868524901235, 3.29362421082383, 3.3488525175471, 3.33825944936905, 
+3.26367282051659, 3.144845635162, 3.01304121369429, 2.90087499419422, 
+2.83270996951723, 2.81924091573587, 2.85756488811465, 2.93554698813950, 
+3.03793126398214, 3.15173279579461, 3.26944748333081, 3.38976442452100, 
+3.51627269359202, 3.65502131737835, 3.81183198170264, 3.99009599803087, 
+4.18946013319694, 4.40536874700664, 4.62903177529908, 4.84728759143595, 
+5.04222914967591, 5.19124105222819, 5.26869587263126, 5.25028022328335, 
+5.11955915865457, 4.87466338821773, 4.532196732451, 4.12644981139801, 
+3.70430667601366, 3.31828736850245, 3.02047149832711, 2.8582030784654, 
+2.86971551759795, 3.07686048023836, 3.47536510633018, 4.02877907539078, 
+4.67359920474169, 5.33531818784261, 5.9451845723945, 6.44780557744068, 
+6.80077245255206, 6.97517023185617, 6.96123207716454, 6.77426781787476, 
+6.45387392807673, 6.05489912357131, 5.63437453429027, 5.23996024422837, 
+4.90332532684795, 4.6390188912505, 4.4474352959063, 4.16274941799028, 
+4.5588652692192, 4.89213696675141, 5.13057148024099, 5.24667313206902, 
+5.22400969537815, 5.06339116608385, 4.78598361581786, 4.43084091263388, 
+4.04629681549938, 3.67778778827195, 3.35702517790374, 3.09708589854954, 
+2.89482980120673, 2.73821417840603, 2.61428656725282, 2.51474547462886, 
+2.43816872232292, 2.38908506680046, 2.37421532265966, 2.39734769007181, 
+0, 0, 0, 0, 2.89906013805462, 3.03511400935256, 3.1717544869414, 
+3.30083496397157, 3.41263464558465, 3.49746135667763, 3.54733586830952, 
+3.55742872391485, 3.52705455336936, 3.4600947411168, 3.36479364371859, 
+3.2529686886872, 3.13876446201234, 3.03712710631874, 2.96214658363033, 
+2.92531688215127, 2.93367673474855, 2.98785817960997, 3.08039281875047, 
+3.19511050554772, 3.30873662905555, 3.39537648745556, 3.43331946153897, 
+3.41202661423296, 3.33632538510119, 3.22556274347878, 3.10763523632784, 
+3.01024030310296, 2.95292957427452, 2.94291719943478, 2.97563134333662, 
+3.03893004687893, 3.11876653402510, 3.20414471831733, 3.29003502221851, 
+3.37791023170032, 3.47430721859514, 3.58821901818592, 3.72822827945377, 
+3.90016215909498, 4.10569332493038, 4.34178683219985, 4.60040757521324, 
+4.86781711600791, 5.12338335705618, 5.3389354454232, 5.48053766940134, 
+5.51414148822056, 5.41460771601759, 5.1750937798981, 4.81263613422296, 
+4.36716562102616, 3.89453348147839, 3.45709893535271, 3.11588615819973, 
+2.92561491280031, 2.92968434741858, 3.15074107459817, 3.57762081538562, 
+4.15842101728362, 4.81106543872888, 5.44960003977639, 6.00826012272442, 
+6.4468939322818, 6.74098990483432, 6.8734235267304, 6.83772395108897, 
+6.6467401631873, 6.33544635349738, 5.95392167572155, 5.55489864212975, 
+5.18241046913411, 4.86541006287187, 4.61683879663252, 4.43657905487276, 
+3.97633259201855, 4.34848512451084, 4.65819775208086, 4.87361353771054, 
+4.96726076030818, 4.92308577938877, 4.74321299247322, 4.45135170375098, 
+4.08993872162705, 3.71042586201945, 3.3597686858072, 3.06876935823662, 
+2.84727868731623, 2.68747467674014, 2.57222191178495, 2.48396558326460, 
+2.41122662993522, 2.35192102756040, 2.31297262152434, 2.30539076496224, 
+2.33634987114765, 0, 0, 0, 0, 2.83153026896765, 2.94878488244903, 
+3.06466998087394, 3.17350788351283, 3.26771921308467, 3.33944499779784, 
+3.38222103841321, 3.39236358276451, 3.36991325690597, 3.31903238764742, 
+3.24779338526998, 3.16736990205453, 3.09073063373577, 3.03100590072448, 
+2.99971929373339, 3.00504262922821, 3.05018334841783, 3.13203943916300, 
+3.24043080331649, 3.35847691968396, 3.46478465934995, 3.53771783049348, 
+3.56106401030619, 3.52930556952157, 3.4502126350067, 3.34319565997406, 
+3.23362916200651, 3.14524437108951, 3.09357270341429, 3.08281321835009, 
+3.10684158178854, 3.15336458952563, 3.20927529066909, 3.2652936140982, 
+3.31866473920329, 3.37354897164441, 3.43944047556447, 3.52838664756657, 
+3.65194664902691, 3.81872193526978, 4.03289005429385, 4.29353837760983, 
+4.59400687818541, 4.92039148599671, 5.24921202705784, 5.54578683653053, 
+5.76601271095609, 5.86366217923944, 5.8025601719825, 5.56948755595432, 
+5.18196008025102, 4.68701325790465, 4.15191648255108, 3.65170100020195, 
+3.25904020663015, 3.03847890775467, 3.0405808209992, 3.28934656549153, 
+3.76426258224486, 4.39190420179898, 5.06400119187248, 5.67812054147124, 
+6.17206159783088, 6.52628725261033, 6.74056390123656, 6.8135830525179, 
+6.74312919372171, 6.538795727515, 6.22986822826848, 5.86095679581458, 
+5.48011106056629, 5.12744539060914, 4.82888674493855, 4.59545438141169, 
+4.42625258002827, 3.77659940928052, 4.12273595443875, 4.40689908580827, 
+4.5973858157634, 4.66676902570298, 4.5994699087366, 4.3991830661453, 
+4.09260605457652, 3.72610103033774, 3.35465454598279, 3.02676345251464, 
+2.77178315881945, 2.59529297988016, 2.48349371245741, 2.41295368647685, 
+2.36072226387708, 2.31205086645285, 2.26505559285676, 2.23085989105553, 
+2.22691575509856, 2.26522236485806, 0, 0, 0, 0, 2.77096329340621, 
+2.87076905384715, 2.96671280368765, 3.05581916732458, 3.1327487301397, 
+3.19150094160704, 3.22712991738684, 3.23710548292177, 3.22221769137659, 
+3.18695348610930, 3.13928043610568, 3.08982300732643, 3.05050216558398, 
+3.03280126763361, 3.04588978114086, 3.09485981998592, 3.17931655856058, 
+3.29255697105795, 3.42161669023175, 3.54853086542541, 3.65309173939183, 
+3.71700770541613, 3.72866123079236, 3.68694405722511, 3.60246319274612, 
+3.49513881623100, 3.38867281422055, 3.30380730404465, 3.25287863497306, 
+3.23756772058768, 3.25033528110471, 3.27859957309134, 3.30991488733271, 
+3.33641828128333, 3.35738773057208, 3.37951989929339, 3.41521494618795, 
+3.47962907801373, 3.58747556079393, 3.75046152131317, 3.97578150974308, 
+4.26532167502292, 4.61452265342356, 5.0098351342609, 5.42488000707292, 
+5.81750101564328, 6.13145390118676, 6.30568538487825, 6.29043926040268, 
+6.06460491662167, 5.6461932569541, 5.09073589868851, 4.47954053853865, 
+3.90372457763539, 3.45080963091094, 3.19784911138688, 3.20471708495402, 
+3.49737243496062, 4.04330357228846, 4.74099960258526, 5.44769800618729, 
+6.03887265613734, 6.45620580197203, 6.706205424001, 6.81947284160728, 
+6.81466776571767, 6.69485543088777, 6.46567350305626, 6.14983739322152, 
+5.78604328356676, 5.41752870346985, 5.08038918193803, 4.79731631512887, 
+4.57710713573164, 4.41777495437382, 3.56789876672984, 3.88664062177226, 
+4.14398003768039, 4.30840904718231, 4.35258781294774, 4.26149868888499, 
+4.04058486472658, 3.71981627568066, 3.34980626466824, 2.98929498807042, 
+2.68825444087012, 2.47413356152744, 2.3474250529762, 2.28736050506937, 
+2.26328331975812, 2.24622513712234, 2.21811870423259, 2.17807247564713, 
+2.14307410392058, 2.13902119491254, 2.18407511680987, 0, 0, 0, 
+0, 2.71730993084346, 2.80128737521429, 2.87843071720471, 2.94866151700838, 
+3.00894289854844, 3.05512512882298, 3.08375472724777, 3.09343821893772, 
+3.08571881116011, 3.06543719139277, 3.04051362361533, 3.02111340581506, 
+3.01823908125481, 3.0419044316063, 3.09915538899459, 3.19227752459288, 
+3.31754749791225, 3.46485282263715, 3.61844149110566, 3.75896375335697, 
+3.86676902657477, 3.92604734095404, 3.92889620479501, 3.87799457556051, 
+3.78663799794285, 3.67563754095677, 3.56780013384325, 3.48179446817262, 
+3.42754818228495, 3.40470853466195, 3.40446729683216, 3.4138343020348, 
+3.42075892617112, 3.41849242211591, 3.40807720839415, 3.39854743891005, 
+3.40509635223444, 3.44597969383978, 3.53918995543674, 3.69984195666981, 
+3.93866109348705, 4.26104422598751, 4.66532438829371, 5.13891499620287, 
+5.65257992397829, 6.1557998494768, 6.57825048650009, 6.8413953398006, 
+6.87936295823035, 6.66177773471189, 6.20707552070228, 5.57980045616913, 
+4.87751834342646, 4.2118569150382, 3.68906500555838, 3.40114539303782, 
+3.41905462172027, 3.7711600857035, 4.41049646717339, 5.20147620586737, 
+5.95922889999484, 6.5318081425021, 6.86465366467221, 6.99473666945029, 
+6.98901049209942, 6.88966361922856, 6.7060372843336, 6.43945842049027, 
+6.10566065906394, 5.73741203369638, 5.3733344602206, 5.04561444356019, 
+4.77360406758822, 4.56360041958991, 4.41217936291879, 3.35459043807896, 
+3.64528018227744, 3.87533272162249, 4.01352653174248, 4.03269736232261, 
+3.91846917867983, 3.67810178899181, 3.3448831692826, 2.97367821866426, 
+2.62689753658539, 2.35577975751455, 2.18551410500624, 2.11103579562234, 
+2.10409253235635, 2.12634363401394, 2.14252027658199, 2.1313027644062, 
+2.09340902136285, 2.05289978831835, 2.04555121784742, 2.09663254047198, 
+0, 0, 0, 0, 2.67048956741527, 2.7403101211381, 2.80000791770546, 
+2.85249790205626, 2.897045736795, 2.93130408863033, 2.95325570572498, 
+2.96260215469286, 2.96162257507743, 2.95552279786498, 2.95221844823384, 
+2.96149366688900, 2.99355346330721, 3.05711630368322, 3.15734007875519, 
+3.29399366065968, 3.4603319535582, 3.64307859473147, 3.82376878676735, 
+3.98146838364582, 4.09657047290969, 4.15499346058377, 4.1517496628285, 
+4.09270922164694, 3.99366908179732, 3.87661632903924, 3.76411314559936, 
+3.67354609522914, 3.61312891117978, 3.58091542042977, 3.56697352847246, 
+3.55780953480374, 3.5415295746332, 3.51220786974913, 3.47236791686811, 
+3.43313995978013, 3.41233447772712, 3.43122560623353, 3.51114100479252, 
+3.67084734284009, 3.92507291045114, 4.28341510257027, 4.7478964843256, 
+5.30754978786203, 5.93043527381376, 6.55696650273776, 7.10104395721, 
+7.46427310426379, 7.56255284606779, 7.35557738013864, 6.86196038307621, 
+6.15304848396789, 5.34327441137094, 4.57152433930050, 3.96810557914353, 
+3.64138288183969, 3.67392464937056, 4.09648924847856, 4.84588750848624, 
+5.74842726648532, 6.57196816801213, 7.13324412294515, 7.38066468123711, 
+7.38371069389517, 7.248609170289, 7.04312311469008, 6.78370353949187, 
+6.46766489515861, 6.10416658622602, 5.72067473273998, 5.35179661123596, 
+5.02614602315886, 4.75974206394064, 4.55613964643839, 4.41011822849517, 
+3.14088432885009, 3.40359917705138, 3.60676320845211, 3.71960444213394, 
+3.71528688548001, 3.58015524186393, 3.32322138250247, 2.98084383715788, 
+2.61173596445998, 2.28151755556621, 2.04230118498996, 1.91678609161437, 
+1.89430358438933, 1.93921235769805, 2.00566091536894, 2.05229383899859, 
+2.05480224872650, 2.01586296148607, 1.96704779427740, 1.95444225699088, 
+2.01067486525502, 0, 0, 0, 0, 2.63046977257235, 2.68761707105262, 
+2.73131412714189, 2.76740277983112, 2.7973598705751, 2.82054288285505, 
+2.83628371181846, 2.84531322049920, 2.85060794524701, 2.85773040371859, 
+2.87461539336677, 2.91072618821718, 2.97557550025195, 3.07674910182225, 
+3.21774786156653, 3.39612110497025, 3.60243417321788, 3.82054361311801, 
+4.02943047659954, 4.20649467786359, 4.33180243812622, 4.39239221904954, 
+4.38550405034041, 4.3196508557569, 4.21290698684653, 4.08860583105834, 
+3.96955400571817, 3.87248498440708, 3.80447002321572, 3.76234600704290, 
+3.73519490467666, 3.70895278079344, 3.67168053857061, 3.61800484306997, 
+3.55163866472917, 3.48552765015361, 3.43985953795976, 3.43876635667718, 
+3.50688042295492, 3.66677424239622, 3.93755705020269, 4.33362279088033, 
+4.86140760298578, 5.51221376158566, 6.25167628668956, 7.0107485466791, 
+7.68636582716565, 8.15857467932695, 8.32392641277419, 8.13303033492234, 
+7.60407266339695, 6.80754237417285, 5.87203188539307, 4.97482452146988, 
+4.27840895676929, 3.90697327036445, 3.95290597301953, 4.44847755811869, 
+5.31366579762761, 6.33599514655835, 7.23512075028946, 7.79514546332882, 
+7.96582382924355, 7.8475177025166, 7.58454513129263, 7.26987077385593, 
+6.92758545030435, 6.5522189626106, 6.14789388996675, 5.73821695174993, 
+5.35484165202111, 5.02337714302335, 4.75663052458874, 4.55522559502561, 
+4.41180256215167, 2.93069002877573, 3.16621342559867, 3.34373683134264, 
+3.43318235805533, 3.40826793780982, 3.25614003066633, 2.98735867467201, 
+2.64079346962257, 2.27817174168776, 1.96745478985646, 1.76103502094789, 
+1.67901820699985, 1.70554033378606, 1.79833547838306, 1.90493548549391, 
+1.97870949522303, 1.99288123623077, 1.95210968295862, 1.89492051108615, 
+1.87682083260713, 1.93713255340154, 0, 0, 0, 0, 2.59725770492085, 
+2.64283211169289, 2.67195370394137, 2.69311324055598, 2.70979527898147, 
+2.7229103368618, 2.73302225583074, 2.74180300920132, 2.75286732365775, 
+2.77210521750345, 2.80747323165808, 2.86815266091363, 2.96304881818309, 
+3.09876039539758, 3.27735207895690, 3.49445256099218, 3.73829065635408, 
+3.99020139693295, 4.22685534517716, 4.4240289292659, 4.56124482128938, 
+4.62621212607346, 4.61783819639964, 4.54678699385445, 4.43315084203131, 
+4.30165808334177, 4.17567513369992, 4.07173431754297, 3.99619950990590, 
+3.94499474860153, 3.90634288389397, 3.86557113813202, 3.81053130875373, 
+3.73615530029516, 3.64704836127708, 3.55765348101761, 3.49023127474187, 
+3.47152649555714, 3.52934390076991, 3.69009392396166, 3.9774965673251, 
+4.41116734591979, 5.00251940851281, 5.74570237870044, 6.60433425266361, 
+7.49995654330209, 8.3121489408904, 8.89881773227751, 9.13752183331333, 
+8.97237491897058, 8.41976971319293, 7.53518171888935, 6.454696568358, 
+5.40988158394625, 4.60666567155930, 4.18227345899916, 4.23424138050449, 
+4.79430784416509, 5.76646354257127, 6.9030624058498, 7.88006861955056, 
+8.45106418152925, 8.56465289259888, 8.3459930578016, 7.97126675834142, 
+7.5552694545348, 7.1298401338749, 6.68900870762301, 6.23466480775634, 
+5.7888669128835, 5.38182586208392, 5.03692528806415, 4.76399385430463, 
+4.56060925389635, 4.41697980425133, 2.7274852158865, 2.93723317171141, 
+3.09112835111875, 3.16010727726025, 3.11873537454509, 2.95504413748439, 
+2.68080988036966, 2.33656658682861, 1.98582366888244, 1.69764167467021, 
+1.52391323912367, 1.48216566262718, 1.55217416248747, 1.68644742194713, 
+1.82749402365235, 1.92481678573146, 1.94996454042724, 1.90927102081138, 
+1.84661977158542, 1.82466243205682, 1.88777976283807, 0, 0, 0, 
+0, 2.57079596354694, 2.60542685674782, 2.62130990575043, 2.62908531742244, 
+2.63392769034692, 2.6380966866048, 2.64324402593544, 2.65187496842788, 
+2.66816427320271, 2.69828003694764, 2.75018124605378, 2.8327831760547, 
+2.95444614757391, 3.12090783078064, 3.3330046128452, 3.58474228595963, 
+3.86238389659017, 4.14513395455165, 4.40767755069159, 4.62433020106473, 
+4.77400441484487, 4.84478630137484, 4.83681507476603, 4.76247083719335, 
+4.64357134456754, 4.50617095284446, 4.37434210545033, 4.26469479606899, 
+4.18318634587034, 4.12505917859546, 4.0777899217226, 4.02608222955441, 
+3.95744882348718, 3.86690012877755, 3.7596302502574, 3.65122542430324, 
+3.56565198718497, 3.53193606886032, 3.58081098936982, 3.74241011524621, 
+4.04509898673008, 4.51389868426603, 5.16551898675086, 5.99739382448138, 
+6.97165568619586, 8.00103986376478, 8.94847456448094, 9.65067976917799, 
+9.96796533248832, 9.84062154842272, 9.2803304190552, 8.31181349570841, 
+7.07101984454836, 5.85893378113683, 4.93595881691178, 4.44879194102041, 
+4.49363473115277, 5.09852130023022, 6.15372499197171, 7.38442652038774, 
+8.43301714227922, 9.02827613119029, 9.11448023249484, 8.83120347999217, 
+8.37531980897472, 7.87710817838605, 7.37578403470041, 6.86809642489001, 
+6.35761803332862, 5.86789173145916, 5.42953762962525, 5.06464548146878, 
+4.78039980384675, 4.57131161987348, 4.42495114215577, 2.53421118462931, 
+2.72011615943038, 2.85300341923453, 2.90519804947298, 2.8524547816582, 
+2.68377248987657, 2.41171291156281, 2.07740899897806, 1.74461953702026, 
+1.48198082103023, 1.33997150105553, 1.33365527620950, 1.43961853732567, 
+1.60704419943099, 1.77556464509530, 1.89270276793779, 1.92934165105760, 
+1.89291040921661, 1.83020216873038, 1.80759494298872, 0, 0, 0, 
+0, 2.48918136174444, 2.55079919421979, 2.57470342535592, 2.57858429936695, 
+2.57455206695902, 2.56906215395669, 2.56547874957470, 2.56637675969028, 
+2.57497128364860, 2.59590277891122, 2.63554962511253, 2.70183323108199, 
+2.80339648661491, 2.94809482168631, 3.14091118526168, 3.3816478618729, 
+3.66298268315183, 3.96959827886201, 4.2789995449002, 4.56428374981886, 
+4.79857591982774, 4.96024688746697, 5.03760665174635, 5.03170389169992, 
+4.95625205328373, 4.83447318828757, 4.69357418024436, 4.55832856531413, 
+4.44554736441134, 4.36096044652253, 4.29929176407554, 4.24736788616121, 
+4.18927021115577, 4.11206710204873, 4.01063409281969, 3.89044146387618, 
+3.76782996428519, 3.66804596066751, 3.6219832629581, 3.66294698093175, 
+3.82451931745257, 4.13952255864519, 4.63827836505577, 5.34280626769745, 
+6.25406131366127, 7.33332550333899, 8.48576890707182, 9.55971539433808, 
+10.3735166357038, 10.7727078610951, 10.6930690611438, 10.1359405665549, 
+9.08837608148785, 7.68402161160696, 6.29697388798957, 5.24619361042816, 
+4.68669985211064, 4.70767134447054, 5.32949185407167, 6.43197890030913, 
+7.72458186520583, 8.8306989938654, 9.46301834708647, 9.55807082573969, 
+9.25644248629193, 8.76092011991896, 8.20868547774631, 7.64550075596836, 
+7.07458069482475, 6.50572447270615, 5.9673439641739, 5.49244409481865, 
+5.10280631156478, 4.80338220757185, 4.58570674242587, 4.43462614717222, 
+2.35320236345218, 2.51756446465764, 2.63245862005482, 2.67199107681924, 
+2.6134641760817, 2.44691916067040, 2.18521635023211, 1.86890700388932, 
+1.56031273704002, 1.32598412550823, 1.21401696490579, 1.23720035374202, 
+1.37030516615607, 1.56137197042896, 1.74960621534692, 1.88268618061421, 
+1.93193945491839, 1.90515253793803, 1.84912172238643, 1.82993107971309, 
+0, 0, 0, 0, 2.48511060022732, 2.53660229848625, 2.54977908093329, 
+2.54283544688290, 2.52858142972784, 2.51429791687079, 2.50418805830229, 
+2.50157348631018, 2.51024509075478, 2.53520221405369, 2.58295047358448, 
+2.66131575046851, 2.77864240189102, 2.94230097594528, 3.15660784748144, 
+3.42051220827332, 3.72565471631403, 4.05553328572906, 4.38641567853637, 
+4.69026813550976, 4.93938466365049, 5.11177545164295, 5.19593925838841, 
+5.1936078157627, 5.11949095930829, 4.99787278873228, 4.85685464321291, 
+4.72178203206265, 4.6096612140301, 4.52607066440634, 4.46531820701356, 
+4.4136560485275, 4.35454962492979, 4.27452919571564, 4.16812485273032, 
+4.04075638948042, 3.90909746152691, 3.79919734737178, 3.74333162683068, 
+3.77691784557464, 3.93656105113424, 4.25912804204893, 4.77983570282564, 
+5.52569400911278, 6.50117789215991, 7.66742310927255, 8.92392172117137, 
+10.1079147264498, 11.0243124716946, 11.5067932349023, 11.4805228065412, 
+10.9270898506646, 9.8026615257441, 8.24438222099197, 6.69454395836211, 
+5.51505869528966, 4.87617964673346, 4.8567904808988, 5.46503337889872, 
+6.57373944723597, 7.88970766312196, 9.03413483060018, 9.71401195893566, 
+9.85508545376471, 9.58471511334539, 9.095581327482, 8.52230175444343, 
+7.91599694728247, 7.28999439373371, 6.66475011300998, 6.07674461112536, 
+5.56317218323831, 5.14641925580262, 4.82965873133224, 4.60166105903879, 
+4.44460963105653, 2.18615401155911, 2.33147512138044, 2.43154169420566, 
+2.46260933011599, 2.40386425436048, 2.24644935215608, 2.00303107914507, 
+1.71240547069632, 1.43379099086349, 1.23002367769882, 1.14588922189432, 
+1.19213653011999, 1.34313498009064, 1.54798979332901, 1.7479225041859, 
+1.89286390467722, 1.95564749913148, 1.94366212853676, 1.90084817663536, 
+1.88906900726808, 0, 0, 0, 0, 2.48784666611036, 2.52709547937699, 
+2.52959749029701, 2.5130221393433, 2.49013269286312, 2.46859140817617, 
+2.45317798024781, 2.44778267523289, 2.45663309830342, 2.48497255862730, 
+2.53933978121376, 2.62739344549079, 2.75713763181817, 2.93546176168889, 
+3.16608852341744, 3.44728292377754, 3.76993327084702, 4.11675286557328, 
+4.46325507310223, 4.78077355799657, 5.04119650418263, 5.22244018213885, 
+5.31324921244186, 5.31588952319771, 5.24577094087536, 5.12788693888328, 
+4.99091535134283, 4.86055247755703, 4.75389549975115, 4.67636572861515, 
+4.62190407330455, 4.57623836045583, 4.52221561879092, 4.44572973846253, 
+4.34074487938065, 4.21228372201708, 4.07690037292331, 3.96092807781107, 
+3.8974825291285, 3.9235550622725, 4.07822609015741, 4.40180742155019, 
+4.93374146089095, 5.70540039138742, 6.72453365070441, 7.95285430415555, 
+9.28661820836957, 10.5568841213412, 11.5622193707845, 12.1287247044626, 
+12.1620530366758, 11.6107725539074, 10.4051631085523, 8.68345432942746, 
+7.02347246399391, 5.71910527234693, 4.99828576767851, 4.92698237870272, 
+5.49535618688456, 6.57205202076107, 7.87377466771425, 9.03575846498451, 
+9.76971586172651, 9.98861363845765, 9.79407144274035, 9.35420404553007, 
+8.79232330782743, 8.16350998948944, 7.49405676064897, 6.81857485423036, 
+6.1840483350735, 5.63318717116485, 5.18969520104399, 4.85542545838042, 
+4.61671685907145, 4.4533129466213, 2.03412859237132, 2.16294815403227, 
+2.25126199369108, 2.27777633894250, 2.22383731952961, 2.08172463790495, 
+1.86346259351669, 1.60504663477616, 1.3611192420883, 1.18937478351013, 
+1.13049903436992, 1.19345322961877, 1.35350309745098, 1.56279533783913, 
+1.76670514269714, 1.91919806484991, 1.99548194827741, 2.00190943286615, 
+1.97723168393029, 1.97591662420701, 0, 0, 0, 0, 2.4951692111281, 
+2.52078918319345, 2.51298060946788, 2.48805384989154, 2.4581103363518, 
+2.43081474911840, 2.41128659175990, 2.40381458353105, 2.41292446225033, 
+2.44398520997621, 2.50346834119990, 2.59878518700403, 2.73754761734534, 
+2.92615644164646, 3.16780200575315, 3.46022317599021, 3.79383220271446, 
+4.15095459311913, 4.50683847266356, 4.83270470944862, 5.10050075183307, 
+5.28837297808136, 5.3854353022629, 5.39439940106919, 5.33111632098913, 
+5.22093931807658, 5.09277219945559, 4.9723828477099, 4.87678807554634, 
+4.81118552065404, 4.76915189863359, 4.73590799516898, 4.69365554232599, 
+4.62753128801385, 4.53068864516324, 4.40737955411096, 4.27355705274528, 
+4.15528862515246, 4.08595428320877, 4.10353683033133, 4.24897731368991, 
+4.56532043656676, 5.09538785409189, 5.87405558847084, 6.91188969707187, 
+8.17185752617379, 9.54974948636217, 10.8762681763014, 11.952408152049, 
+12.6034921614212, 12.7095963821235, 12.1709315848717, 10.8994407405519, 
+9.0529224721195, 7.25905811148125, 5.83390609751141, 5.03549854409491, 
+4.910162793399, 5.42276893061381, 6.4394150709056, 7.6968941820341, 
+8.85767141569128, 9.64708352957119, 9.9648884403333, 9.87839682169243, 
+9.52071714981243, 8.99726862434646, 8.36564109858221, 7.66657675861329, 
+6.9507327013967, 6.27679803310619, 5.6936048765709, 5.22658544932844, 
+4.87670088373727, 4.62830297322504, 4.45907971083568, 1.89759724653608, 
+2.01234788772209, 2.09168647630904, 2.1169698760942, 2.07188901234193, 
+1.94986508460679, 1.76191744456867, 1.54042360994558, 1.33431244279957, 
+1.19505003456062, 1.15864831803422, 1.23252920949391, 1.39391012833550, 
+1.59952608185143, 1.80051068839159, 1.95613042611781, 2.04454263877208, 
+2.07063442719238, 2.06648430457382, 2.07718441480537, 0, 0, 0, 
+0, 2.50427129385027, 2.51599757566291, 2.49871661128628, 2.46684615136025, 
+2.43141344257659, 2.39980775719830, 2.37729289934151, 2.36840100778523, 
+2.37782274467254, 2.41093582902773, 2.47404331798631, 2.57422643791626, 
+2.71864887251054, 2.9132097939168, 3.16062113666318, 3.45824396799634, 
+3.79627896411591, 4.15704839362882, 4.51601528462398, 4.84480709970159, 
+5.11590911136409, 5.30805138857643, 5.41088291447177, 5.42751865397792, 
+5.37402953698831, 5.27579753473932, 5.16159731615537, 5.05696452285448, 
+4.9786273648358, 4.93145180898637, 4.90861148197413, 4.8947964189187, 
+4.87149484878442, 4.82292418801489, 4.7411427656167, 4.62922325384856, 
+4.50200793757161, 4.38472891306743, 4.3104448794834, 4.31754895489206, 
+4.44823537740554, 4.74756632186432, 5.26085547990002, 6.02552527065688, 
+7.05435734275163, 8.31212574174283, 9.69689217458477, 11.0448780986016, 
+12.1684832062527, 12.9008728510732, 13.0965274769561, 12.5938710758196, 
+11.2815905491785, 9.35431859210125, 7.37201844220321, 5.83387479738699, 
+4.97294605927871, 4.80407978508779, 5.25901936966817, 6.20213152039266, 
+7.39712114048219, 8.54227831408041, 9.38293115161734, 9.80698897256262, 
+9.8441012175374, 9.58739812309495, 9.12083798221783, 8.5031409344399, 
+7.78931966290077, 7.04601078133739, 6.34334502642348, 5.73605107402748, 
+5.25135079591565, 4.88968450624849, 4.63395222526803, 4.46031439738531, 
+1.77650917173984, 1.87940622365401, 1.95210248770907, 1.97868398474010, 
+1.9452620837687, 1.84637084165127, 1.69177444875207, 1.50970681080349, 
+1.34267041193203, 1.23524378036628, 1.21845484513846, 1.29841503575975, 
+1.45502888006276, 1.65062233126866, 1.84304345324694, 1.99752284218379, 
+2.09541473278899, 2.13995483008131, 2.15601676271013, 2.17866130479253, 
+0, 0, 0, 0, 2.51230805597391, 2.51108016294049, 2.48566250854132, 
+2.44837440418327, 2.40897833276683, 2.37442197046277, 2.34996485106885, 
+2.34024662480189, 2.34999889640925, 2.38449695752686, 2.44977846208635, 
+2.55251516446994, 2.69936890734359, 2.89572455721868, 3.14386634819420, 
+3.4409171826444, 3.77711515175976, 4.13514205947947, 4.49113115491975, 
+4.81761398595632, 5.08808044272563, 5.28220198302789, 5.39034991925628, 
+5.41603481382573, 5.37536570352238, 5.29345684077655, 5.19862084004685, 
+5.11586346778194, 5.06140605659799, 5.03964985944301, 5.04328784731348, 
+5.0564051824568, 5.05965000662126, 5.03609814005259, 4.976374031422, 
+4.88191947395619, 4.76592778054468, 4.6522150609483, 4.57294664463384, 
+4.56639448258106, 4.67549288587896, 4.94673647535492, 5.42717392763591, 
+6.15588864796632, 7.14723478051295, 8.3681433705429, 9.72120493476256, 
+11.0529201745332, 12.1940138300532, 12.9928987730693, 13.2830122579865, 
+12.8349631100172, 11.48647895911, 9.44698520435983, 7.32275055170774, 
+5.69512775242125, 4.80167390963627, 4.61296075849017, 5.02209237398498, 
+5.89283992961107, 7.0193265999462, 8.13934318241592, 9.02172831443447, 
+9.54553941684167, 9.7046600652096, 9.56098050078914, 9.15220994888641, 
+8.56131597664301, 7.84767438489529, 7.09193258388646, 6.3739938793188, 
+5.75346890696851, 5.25909473767731, 4.89109147719361, 4.6315036494888, 
+4.4556017803458, 1.67037933889657, 1.76335171712258, 1.83121894670606, 
+1.86074999079595, 1.84044031119523, 1.76587639243934, 1.64543967509192, 
+1.50300672075006, 1.37439262076982, 1.29708057588848, 1.29707878527945, 
+1.37938898312202, 1.52699589373580, 1.70825513084903, 1.88803890907202, 
+2.0376320344437, 2.14153615651960, 2.20137147136424, 2.23511398950068, 
+2.26829523651567, 0, 0, 0, 0, 2.5169054403656, 2.504661847782, 
+2.47283370903927, 2.43171755865972, 2.38981224674195, 2.35355585813413, 
+2.32809840592153, 2.31807106528536, 2.32813432302842, 2.36335948402351, 
+2.42943097788537, 2.53254077121636, 2.67880359336745, 2.87308331135043, 
+3.11728789859888, 3.40843385445842, 3.73702651369883, 4.08643905923348, 
+4.43389059565212, 4.75327260604256, 5.01951209907872, 5.21356177769464, 
+5.32670686181397, 5.36287238125814, 5.33806678391916, 5.27689013265322, 
+5.20690621227528, 5.15232618555997, 5.12865890796121, 5.13969603481176, 
+5.17753483094664, 5.22552141953563, 5.26326277410553, 5.27239389772408, 
+5.24169920645492, 5.17048801685093, 5.06973677566776, 4.96125947892874, 
+4.87578781582479, 4.8510352275608, 4.93034528706804, 5.16133280976874, 
+5.59234181901631, 6.26349468222401, 7.19015459990983, 8.3415023781885, 
+9.62602893758016, 10.9030887851826, 12.0244562609207, 12.856603110322, 
+13.2178525330765, 12.8174074428160, 11.4372897007839, 9.2975347896573, 
+7.0724873994259, 5.40441527285881, 4.52439853836277, 4.34941711383963, 
+4.73401929730131, 5.5441480960504, 6.60529831695207, 7.69427598658427, 
+8.60442861133145, 9.2100947240149, 9.4756677771742, 11.0070105074411, 
+9.0863562861471, 8.531079385428, 7.83197710039442, 7.07995549421753, 
+6.36193219115038, 5.74077617616276, 5.24619822643, 4.87842616133017, 
+4.6192686790549, 4.44380610638197, 1.57838429201714, 1.66304686434006, 
+1.72737466217328, 1.76066170032533, 1.75365120256807, 1.70289559915564, 
+1.61538229498841, 1.51070727893428, 1.41815532578149, 1.36832181038292, 
+1.38240821927248, 1.46447594315356, 1.60066726045558, 1.76530397761755, 
+1.93004421022512, 2.07186175603605, 2.17813668369441, 2.24907205732595, 
+2.29664088583873, 2.33814399763739, 0, 0, 0, 0, 2.51647733084520, 
+2.49576878804313, 2.45945900534221, 2.41608610775369, 2.37301684845839, 
+2.33618110069259, 2.31054767871754, 2.30064172969243, 2.31095412142299, 
+2.34626329032706, 2.41182583708335, 2.51329757626183, 2.65621452178116, 
+2.84492373204992, 3.08101253096381, 3.36151561361129, 3.67741302027234, 
+4.01306232081835, 4.34713174188077, 4.65527031222434, 4.91422177476704, 
+5.10652439135911, 5.22455982376708, 5.27270720664495, 5.26678253831666, 
+5.23068827755951, 5.19101842242827, 5.17097920478782, 5.18519195265323, 
+5.2366918022505, 5.31682747475204, 5.40800261141339, 5.48849348490946, 
+5.53810509157051, 5.54330048223133, 5.50070259940333, 5.4184736963565, 
+5.31583532546797, 5.22158545177214, 5.17256700636295, 5.21245897178684, 
+5.3900884301228, 5.75515205323046, 6.34863961568705, 7.1865670699185, 
+8.2401899649041, 9.42416182084014, 10.6105759207556, 11.6699498219255, 
+12.4837340515773, 12.8608484137322, 12.4696535813820, 11.0571372616460, 
+8.85943104739656, 6.60606167202327, 4.97223906717111, 4.16182448696471, 
+4.03658677007398, 4.41994529255244, 5.18496561967392, 6.18782536680549, 
+7.24105247248146, 8.16169149683667, 8.82391262182217, 9.17060437912843, 
+9.79474366912428, 8.92270736532926, 8.40963317250536, 7.73835843434309, 
+7.00623724458038, 6.30382848665447, 5.69529138908518, 5.21060478320733, 
+4.85016458847983, 4.5961447130041, 4.42414122563700, 1.49945678734891, 
+1.57711804384436, 1.63872653839866, 1.67585748650205, 1.68128907447904, 
+1.65243613979010, 1.59497792160065, 1.52454297795299, 1.46437982506593, 
+1.43873498963183, 1.4644103412092, 1.54466405066029, 1.66861862290093, 
+1.81611233409004, 1.96495790604231, 2.09715888788684, 2.20258176331726, 
+2.28030159375940, 2.33747517157711, 2.3848496722315, 0, 0, 0, 
+0, 2.51029596657563, 2.48385775494629, 2.44499383857533, 2.40083270476060, 
+2.35780176757706, 2.32136052123693, 2.29624680082857, 2.28679806365053, 
+2.29725142244545, 2.33201844985901, 2.39586964009487, 2.49388603828370, 
+2.63101113778332, 2.81109411142833, 3.03546413208480, 3.30129213799474, 
+3.60021558509235, 3.91782465058201, 4.23453804551324, 4.52808929764088, 
+4.77735180050369, 4.96670510263903, 5.08979104988904, 5.15149914153371, 
+5.16741071782829, 5.16061982677224, 5.15660978206894, 5.17744139734991, 
+5.23671655737288, 5.33657118992896, 5.4674131324302, 5.61042236348722, 
+5.74215586709215, 5.84010316003595, 5.88785151598753, 5.87873948436238, 
+5.81749459396392, 5.72014943851274, 5.61310253981775, 5.53214760483436, 
+5.52152777135892, 5.63187815819184, 5.91494836058505, 6.41303116586691, 
+7.14276172598473, 8.07707261126662, 9.13598034426014, 10.2018577139994, 
+11.1577113811886, 11.8926176312343, 12.2118249254316, 11.7739993739031, 
+10.3295921089896, 8.139582042131, 5.95619572057033, 4.44267829180161, 
+3.75534050456659, 3.70815152318242, 4.10727852212514, 4.83925528109783, 
+5.78917659094294, 6.80059597089343, 7.71242226625984, 8.40287439532384, 
+8.80217113155368, 8.8860650242433, 8.66768650706328, 8.2006960587575, 
+7.56900450703507, 6.87187353861381, 6.20002465857028, 5.61687894288707, 
+5.15192516505756, 4.80582795158565, 4.56166629048139, 4.39620651601538, 
+1.43237228746685, 1.50406714194092, 1.56339949615569, 1.60392888646832, 
+1.62020928745191, 1.61040816286244, 1.57905290487032, 1.53828082260547, 
+1.50602619452782, 1.50094527864752, 1.53596934680369, 1.61365765620337, 
+1.72575844791200, 1.85692899576568, 1.99028246989441, 2.11206116292724, 
+2.21419403668266, 2.29494547643291, 2.35787986817062, 0, 0, 0, 
+0, 0, 2.4983583645165, 2.46875753031928, 2.42909910731742, 2.38544837088782, 
+2.34348968987344, 2.30825879815419, 2.28422458712786, 2.27546851686572, 
+2.28590437705771, 2.3195190756803, 2.38055702438073, 2.47350608663771, 
+2.60272391919892, 2.77159798891926, 2.98127052179582, 3.22916070650597, 
+3.50772003197963, 3.80397117013846, 4.10031699510367, 4.37682420628588, 
+4.61473345151534, 4.80046437964433, 4.92905744897372, 5.00598212426463, 
+5.04659339539922, 5.07314368131692, 5.10995272546462, 5.17787407257413, 
+5.2894083193513, 5.44565616776305, 5.63584922602454, 5.83957699482984, 
+6.03118323053453, 6.18526422475194, 6.28192307165544, 6.31059952492682, 
+6.27196244591415, 6.17825010898878, 6.05300647185257, 5.93090549080871, 
+5.85728683592661, 5.88573889448707, 6.07149429633454, 6.45929274337035, 
+7.06676292486413, 7.8679818870619, 8.78675350972279, 9.711981706078, 
+10.5315463908670, 11.1340851389619, 11.3275108041878, 10.7943680316534, 
+9.32967282898245, 7.2240996664462, 5.21022145325165, 3.89116674798176, 
+3.36195431154378, 3.40402025868286, 3.82333245673302, 4.52573028499586, 
+5.42248851594828, 6.38316700839612, 7.26632336240472, 7.95751136448811, 
+8.38198559939036, 8.50488664458807, 8.33272288758558, 7.91415882224313, 
+7.3317748635362, 6.68257812343122, 6.0543074146674, 5.50780472562043, 
+5.07135677498206, 4.74594458488367, 4.51599249457905, 4.35998777388975, 
+1.37582314148465, 1.44235951176019, 1.49959095977461, 1.54274578942494, 
+1.56787965105252, 1.57380769075585, 1.56410354311551, 1.54797433053553, 
+1.53887400582627, 1.55072761017196, 1.59316965081921, 1.66812988874313, 
+1.76952804602821, 1.88602882597932, 2.0051223290515, 2.11650113132646, 
+2.21377140551706, 2.29469136189550, 2.36032433055767, 0, 0, 0, 
+0, 2.49859643589447, 2.48114729666650, 2.45056413467425, 2.41160097827543, 
+2.36954969740515, 2.32951523024998, 2.2961473924465, 2.27361335353661, 
+2.26568169136098, 2.27588764120952, 2.30775226786186, 2.36497301027632, 
+2.45144735654128, 2.5709754131927, 2.72653742885273, 2.91916939736611, 
+3.14664509556696, 3.40236033472388, 3.67492085418472, 3.9488778639063, 
+4.20679894767227, 4.43245087521633, 4.61443142793509, 4.74928898343998, 
+4.84315279725952, 4.91120848993955, 4.97491096218256, 5.05745267877949, 
+5.17849851856086, 5.34941698254553, 5.57014225216724, 5.82844510732893, 
+6.10186384317467, 6.36192825266677, 6.57968992847393, 6.73115046602325, 
+6.80127922754853, 6.7861026225879, 6.69345147517189, 6.54352654186786, 
+6.36985342326598, 6.21964714982411, 6.15111637802044, 6.22514012934982, 
+6.49078024918842, 6.96747933955074, 7.62989283514535, 8.40364352013914, 
+9.18037379998823, 9.8466744135374, 10.2855391435888, 10.3143949476916, 
+9.6664009030031, 8.20967378558434, 6.26018608041607, 4.49037510358825, 
+3.40668317787488, 3.04075612553028, 3.16159226030582, 3.5909276173844, 
+4.25718501274439, 5.09403058715656, 5.99232890791816, 6.82807859725506, 
+7.4962056864029, 7.92255880908457, 8.06796574818454, 7.9340145580762, 
+7.56509909590137, 7.03920511911996, 6.44785715134165, 5.87330536157647, 
+5.37233597506213, 4.97143968716634, 4.67191339561957, 4.45983767361976, 
+4.3158265813969, 1.32847894222033, 1.39048803496155, 1.44563259035269, 
+1.49050633393587, 1.52240587355204, 1.54070393209805, 1.54823429323292, 
+1.55184898664591, 1.56136199381108, 1.58681801106845, 1.63510224338895, 
+1.70754522931699, 1.7997493324903, 1.90357132606927, 2.0100042090987, 
+2.11149919284358, 2.20303886458939, 2.28214974862465, 2.34827536096727, 
+0, 0, 0, 0, 2.47772947694326, 2.45938712743726, 2.42953236309223, 
+2.39244736370943, 2.35286249881562, 2.31541985095754, 2.28440516832705, 
+2.26365329027946, 2.25657324257794, 2.26628024131742, 2.29580457169627, 
+2.34829453516536, 2.42708085338430, 2.53545549488122, 2.67606383001568, 
+2.84992558371957, 3.05526994847046, 3.28654179727896, 3.53403264657306, 
+3.78453864861364, 4.02321699607095, 4.23644206636322, 4.41506709485808, 
+4.55722688830908, 4.66979703721869, 4.76789446423048, 4.87229223448571, 
+5.00517528264662, 5.18511366227674, 5.42235877829222, 5.71554468771339, 
+6.0506371784326, 6.4025586053153, 6.7393207887896, 7.02774258394759, 
+7.23917817084513, 7.35370077484042, 7.36222891192322, 7.26757535542422, 
+7.08601100363595, 6.84981490642998, 6.60897852613645, 6.42840251502251, 
+6.37740753868595, 6.51191051733564, 6.85441508931346, 7.3796439948058, 
+8.01300317201422, 8.64589264030354, 9.1605840078726, 9.433882504481, 
+9.29926255494085, 8.55423382026633, 7.1477690928431, 5.40678197834047, 
+3.91428501754484, 3.06418631125657, 2.8354573679138, 3.00551652486643, 
+3.42326100555404, 4.03931676532813, 4.80502987441205, 5.6284689535018, 
+6.40103545275006, 7.0278073037093, 7.43854000572773, 7.59354967041763, 
+7.49153373762878, 7.17220769081254, 6.70702076771977, 6.1798050577098, 
+5.66561204515428, 5.21615488446086, 4.85569325464417, 4.58579452480237, 
+4.39435952263885, 4.26436522310411, 1.28903354024552, 1.3470165869893, 
+1.40001838442632, 1.44573110124208, 1.48246723269283, 1.51008979067056, 
+1.53090224729185, 1.54993512484811, 1.57412613455558, 1.61039603365406, 
+1.66334409265717, 1.73368655148299, 1.81823154321226, 1.91128706121808, 
+2.00660349393934, 2.09885118695899, 2.18419709251151, 2.26018243064254, 
+2.32529584589393, 0, 0, 0, 0, 2.45134425318502, 2.43385932185581, 
+2.40599123998748, 2.37167144121148, 2.33520574762311, 2.3008446279568, 
+2.27251603231286, 2.25369369122068, 2.24738995329613, 2.25627146321668, 
+2.28286796220143, 2.32979379976205, 2.39985562556477, 2.49590585299694, 
+2.62034327882711, 2.77426925425175, 2.95646356772239, 3.16250091893084, 
+3.38441696217958, 3.6112870033271, 3.83087353738269, 4.03216804285098, 
+4.2082991009094, 4.35903551598269, 4.49208820962468, 4.62264155726228, 
+4.77096296437984, 4.9584207711161, 5.20264735977708, 5.51282651811249, 
+5.88614381601368, 6.30634112303107, 6.7450432804349, 7.1659454347636, 
+7.53096745720493, 7.80646286291578, 7.96748325037485, 7.99961175217142, 
+7.90005944464966, 7.68040185187624, 7.37135072483379, 7.0265064044373, 
+6.71972388819803, 6.53197184899673, 6.52903048490644, 6.73805998522611, 
+7.13346618617274, 7.63853618090317, 8.14245770509429, 8.52321985625904, 
+8.65492275691076, 8.39214884305961, 7.59671039143536, 6.28664635544501, 
+4.77954066854441, 3.55520669943093, 2.90032685420737, 2.76097901635789, 
+2.94061183024626, 3.32057330461252, 3.87002543860800, 4.5528798731979, 
+5.29098056738028, 5.98927304035438, 6.5627404891082, 6.94645536258757, 
+7.10223285197093, 7.02706258934952, 6.75581501032446, 6.35237107099348, 
+5.89170157513582, 5.44076935257165, 5.04567725145219, 4.72819060528927, 
+4.49006071813468, 4.32102276863074, 4.20647640443917, 1.25624030360506, 
+1.31060775691633, 1.36141056070413, 1.40722473778967, 1.44720408162005, 
+1.48166286768850, 1.51256619909665, 1.54357829427647, 1.57939199426391, 
+1.62440750670214, 1.68127694174955, 1.75003464276783, 1.82825638122995, 
+1.91208077489821, 1.99744130408185, 2.08086455219464, 2.15962762594591, 
+2.23151802404519, 2.29455355700041, 0, 0, 0, 0, 2.42073372771172, 
+2.40529758182597, 2.38029222323388, 2.34936590433156, 2.31647754649424, 
+2.28552204454185, 2.26006465369887, 2.24319211234791, 2.23749209767720, 
+2.24516595771293, 2.26824669306665, 2.30884504486796, 2.36930256899639, 
+2.45211665790091, 2.55954065869373, 2.69286108369783, 2.85149733861128, 
+3.03221282029364, 3.22880637185471, 3.43261190252393, 3.63394888374743, 
+3.82437185143262, 3.99925283763219, 4.16001209004611, 4.31528210933897, 
+4.48047517213112, 4.67557390783204, 4.92137418223268, 5.23477339858561, 
+5.62395510151678, 6.08447633757187, 6.59734256535088, 7.13006868330411, 
+7.64115444326442, 8.08705489029211, 8.42912050499299, 8.63775560273426, 
+8.69337461058996, 8.58707021348233, 8.3246915401444, 7.93466230797674, 
+7.47471378265132, 7.0298044543094, 6.6958273182291, 6.55161694907472, 
+6.63080340841573, 6.90729218174897, 7.3006110364242, 7.69648913570317, 
+7.97036705789654, 7.99881326199578, 7.66012948834808, 6.87041571020083, 
+5.69367369168079, 4.41847378519406, 3.42237820331211, 2.90465984299650, 
+2.80072908219947, 2.95157304312457, 3.27069835831637, 3.74034924914542, 
+4.3322448455849, 4.97921371159353, 5.59800629854559, 6.11258249573004, 
+6.46343666439151, 6.61462478405522, 6.56203368477586, 6.33580039479886, 
+5.99203231790645, 5.59660702481531, 5.2082541080984, 4.8673720245234, 
+4.59313094505726, 4.3873443940084, 4.241457568315, 4.14318753565034, 
+1.22893752346215, 1.28003950319424, 1.32863344628759, 1.37402502528539, 
+1.41609264980611, 1.45559383478089, 1.49432297712145, 1.53493603152758, 
+1.58035135876304, 1.63286807787271, 1.69338266751314, 1.76112086956132, 
+1.83403646950529, 1.90961625493292, 1.98558754652073, 2.06014982511333, 
+2.131733641375, 2.19860680168126, 2.25866989477328, 0, 0, 0, 
+0, 2.38696514967807, 2.37434974724438, 2.3527852161458, 2.32566669228692, 
+2.29664331452775, 2.26926745734447, 2.24673103621401, 2.23171223106684, 
+2.22635480760866, 2.23238867388055, 2.25136550175786, 2.28493515352429, 
+2.33504574540716, 2.40393594169488, 2.49382343249508, 2.60628594035165, 
+2.74146441246969, 2.89735018604688, 3.06949097858768, 3.25141319218737, 
+3.43589192565623, 3.61693763521817, 3.79208924728295, 3.96440707120976, 
+4.14352259350775, 4.34524717222693, 4.58952479568825, 4.89685375544058, 
+5.28362265198176, 5.75708032898116, 6.31092564941276, 6.92280465550127, 
+7.55517039857036, 8.16039270915537, 8.68908874512601, 9.0981289340105, 
+9.3543589434394, 9.43375234944676, 9.3208832533337, 9.01450450360187, 
+8.53946500541417, 7.95758407672075, 7.36659702754773, 6.88022841194575, 
+6.59335524097765, 6.54793781702217, 6.71749519509717, 7.01657626809259, 
+7.32657188195435, 7.52218282825858, 7.48675694897398, 7.12206598466895, 
+6.38414806537986, 5.3585102382366, 4.2913022242345, 3.46941113999732, 
+3.02982512733957, 2.91562247074262, 3.00970677890596, 3.25365441502007, 
+3.63731721118023, 4.1364808410929, 4.69271842014371, 5.23289777597018, 
+5.68867528106453, 6.00536056710982, 6.1492544315125, 6.11543283433204, 
+5.92968687297854, 5.64081808195374, 5.30613408532858, 4.97659413101387, 
+4.68716579359682, 4.45446210394022, 4.28021107405351, 4.15732945633887, 
+4.07560828637782, 1.20606565288663, 1.25421421282435, 1.30066231864060, 
+1.34535251309758, 1.38882993234567, 1.43231836345282, 1.47758328423813, 
+1.52652944811658, 1.58060424229874, 1.64023439342099, 1.70459891933358, 
+1.77192509955108, 1.8402014178506, 1.90791570764917, 1.97437800581131, 
+2.03944576924146, 2.10285736712601, 2.16361281530643, 2.21976679180033, 
+0, 0, 0, 0, 2.35089953806267, 2.34158013771217, 2.32381174154831, 
+2.30074283653064, 2.27572561380628, 2.25197053668352, 2.23228443464743, 
+2.21892085022508, 2.21356871104365, 2.21748961046812, 2.23177878097753, 
+2.25767722249045, 2.29681983761623, 2.35128978590875, 2.42338271637842, 
+2.51507236637938, 2.62729468303392, 2.75929072256875, 2.90831563086255, 
+3.06998649255612, 3.23939155869329, 3.41284833973909, 3.58994922458977, 
+3.77535578958465, 3.97976033218111, 4.21954013050206, 4.51485020612870, 
+4.88617199026598, 5.34961100892964, 5.91152601072113, 6.56346617897762, 
+7.27898070336888, 8.01437975586553, 8.71495390934437, 9.32539546847843, 
+9.79929235162343, 10.1019024448376, 10.2061711103796, 10.0899111547744, 
+9.74303765319415, 9.18487488359958, 8.48052053919352, 7.74132397195514, 
+7.10089653754508, 6.67250267780056, 6.50814278068918, 6.58147626452975, 
+6.80152477879146, 7.04474217052064, 7.18600354384817, 7.11736935015841, 
+6.76125805258769, 6.09966551369841, 5.22085069484382, 4.32396685645033, 
+3.62237259265737, 3.21377150759756, 3.05982791041228, 3.08341420779945, 
+3.24833467153915, 3.54780709997840, 3.95925910220801, 4.43120625347217, 
+4.8989601736221, 5.30048362169184, 5.58501598367906, 5.72075471200924, 
+5.70211842826168, 5.55117512325328, 5.31037936020038, 5.02952733685511, 
+4.75270509050335, 4.50999262598091, 4.31559099792489, 4.17098131264011, 
+4.070233138594, 4.00486791374166, 1.18667765607189, 1.23216214884194, 
+1.27661051373452, 1.32056633404268, 1.36523790816362, 1.41236683981667, 
+1.46380718883518, 1.52087558405586, 1.58369648671110, 1.65087449337239, 
+1.71976439227842, 1.78734262843177, 1.85132701122618, 1.91097857589350, 
+1.96713623572600, 2.02144815241893, 2.07521429963710, 2.12844640652063, 
+2.17957951246521, 0, 0, 0, 0, 2.31324207856646, 2.30748785729263, 
+2.29370531132109, 2.27478919657539, 2.25379495815632, 2.23358680751080, 
+2.21657687292294, 2.20458418104395, 2.19883969949914, 2.20014781391917, 
+2.20917954954549, 2.22682516430250, 2.25449085839079, 2.29420933499682, 
+2.34846644565757, 2.41973135880834, 2.50979826870736, 2.61916409970780, 
+2.74672883058054, 2.89007241399503, 3.04642446235736, 3.21423027364242, 
+3.39499314771191, 3.59491104751698, 3.82577636917009, 4.10467933250215, 
+4.45221694772085, 4.88911504609991, 5.43139867398959, 6.08454690739054, 
+6.8376091837589, 7.65921130548991, 8.4983595747814, 9.29237007209738, 
+9.980286477217, 10.5143519806139, 10.8611227963603, 10.9926120596909, 
+10.8797848056906, 10.5016430286641, 9.86942035294467, 9.04985689949563, 
+8.16764927243616, 7.37705601593919, 6.8110000934521, 6.53287417714597, 
+6.51750501069021, 6.6688107450653, 6.85824294007336, 6.96084437223142, 
+6.87685238678253, 6.54477455362544, 5.96143099255248, 5.20718335766344, 
+4.43752018517431, 3.81064072823252, 3.40213644491087, 3.19561964416985, 
+3.14770871759873, 3.23846103773240, 3.46189523958871, 3.79587514915668, 
+4.19438933636943, 4.59955122424253, 4.9542911073487, 5.21085818354018, 
+5.33878909373255, 5.33187390739138, 5.20930159003085, 5.00850376081484, 
+4.77312172833259, 4.54149607019016, 4.33952063165366, 4.17920162293066, 
+4.06161281762631, 3.98161683761619, 3.93206613057439, 1.16994340640654, 
+1.21304013272826, 1.25571536077983, 1.29912620821700, 1.34518620837775, 
+1.39622976605656, 1.45429568531838, 1.52019536440507, 1.59274634247182, 
+1.66862973792080, 1.74314548434927, 1.811711737981, 1.87149903335033, 
+1.92241015845596, 1.96688650142564, 2.00861885406513, 2.05080416285709, 
+2.09477459438702, 2.13955077449285, 0, 0, 0, 0, 2.27459154764584, 
+2.27252541347698, 2.2627926206159, 2.24802002505989, 2.23096117859329, 
+2.21412933714842, 2.19953633101943, 2.18856328709272, 2.18198736214093, 
+2.18017363960115, 2.18340651110356, 2.19228666322309, 2.20807621331569, 
+2.23285924845593, 2.26941750540511, 2.32080536720233, 2.38972630858839, 
+2.47792502121998, 2.58586789007695, 2.7129527809588, 2.85836047380605, 
+3.02246490576831, 3.2085158258222, 3.4241578106264, 3.68229350588584, 
+4.00083864226083, 4.40102351501945, 4.90403705169121, 5.52598522397428, 
+6.27144185821721, 7.12657695257184, 8.05424874053263, 8.99502746225112, 
+9.8775227192836, 10.6358138279517, 11.2234006648209, 11.6117439932324, 
+11.7744851501521, 11.6757203242273, 11.2812578305583, 10.5913226927977, 
+9.67201520802684, 8.65993623766617, 7.72828900961081, 7.03014321645144, 
+6.64436846750306, 6.54345830329711, 6.62980824988952, 6.77074556319454, 
+6.84118151339995, 6.74745013141078, 6.43892775702012, 5.91943722367799, 
+5.25763088590064, 4.57347346232937, 3.98663528137074, 3.56152535364551, 
+3.30166001895060, 3.18933100471787, 3.21571242674804, 3.37453703849588, 
+3.64378395842255, 3.98171835729106, 4.33574981220292, 4.65269825076043, 
+4.88701365862487, 5.00845290003945, 5.00969548552707, 4.90842240523296, 
+4.73896653520659, 4.54019380417687, 4.34574966799579, 4.17805859407902, 
+4.04718276214137, 3.95364436507638, 3.89273848881779, 3.858238621134, 
+1.15514894949594, 1.19612582682779, 1.23732228394382, 1.28055809539945, 
+1.32852773954161, 1.38424932980366, 1.4500241190378, 1.52617845412254, 
+1.61013812545242, 1.69644543108620, 1.77802324030755, 1.8483847386571, 
+1.90389952474165, 1.94505210152343, 1.97605169190590, 2.00296720518222, 
+2.03128406534258, 2.06398501069747, 2.10087184818367, 0, 0, 0, 
+0, 2.23547517908129, 2.23711097794002, 2.23139286236143, 2.22066250721248, 
+2.20736518225758, 2.19366057296698, 2.18115953579781, 2.17080841064772, 
+2.16294144945914, 2.15750810562381, 2.15444727959763, 2.15413155233648, 
+2.15775987052441, 2.16756169666548, 2.18670893977409, 2.2189173091196, 
+2.26783630113496, 2.33643693155641, 2.42666213474849, 2.5395731596979, 
+2.67610278593241, 2.83834371878788, 3.03111212238366, 3.26338566918785, 
+3.54915266909298, 3.90721994028471, 4.35958490337302, 4.92805705479792, 
+5.62893287717366, 6.46583278631527, 7.42169860200956, 8.4528859194901, 
+9.49060498789824, 10.4543464289842, 11.2743219962568, 11.9083018112911, 
+12.3364970385716, 12.5366995420882, 12.4659534111347, 12.0746015911347, 
+11.3491105561784, 10.3524984363824, 9.2308463936093, 8.12890161367402, 
+7.25108809323415, 6.86230806980814, 6.6745294834076, 6.69281459774883, 
+6.78263801853232, 6.81895414276739, 6.7117918733413, 6.41648541847007, 
+5.93873711041304, 5.33572921501037, 4.70138952716579, 4.13016316849818, 
+3.68127226730480, 3.37345522824251, 3.20677370682689, 3.17962250709848, 
+3.28536704668414, 3.50230842383782, 3.79208352025031, 4.1063092731464, 
+4.39550439562052, 4.61587298756253, 4.73391844634879, 4.73856003960357, 
+4.64946365420038, 4.50198552076855, 4.331177846978, 4.16624879148418, 
+4.02662348856374, 3.92065362711973, 3.84819504680122, 3.80465076849706, 
+3.78433618785478, 1.14169155629438, 1.18080815893123, 1.22086669278678, 
+1.26442139705819, 1.31504246459453, 1.37652876568757, 1.45150518815679, 
+1.53978949179532, 1.63726609395243, 1.73605475974759, 1.8263295841792, 
+1.89933788387611, 1.95041761514602, 1.98062230399381, 1.99614662999498, 
+2.00581406620747, 2.01781214628319, 2.03710818862552, 0, 0, 0, 
+0, 2.18261118504317, 2.19636750074306, 2.20163353684381, 2.19981486049210, 
+2.19295019676112, 2.18317110148287, 2.17228430392275, 2.16150422597762, 
+2.1513518588606, 2.14173573875310, 2.13221825915690, 2.12243604623615, 
+2.11259299274029, 2.10389881586543, 2.09881051426766, 2.10096889423559, 
+2.11480990748984, 2.14494960346525, 2.19555106635462, 2.26993589189022, 
+2.37067062203381, 2.50023949031142, 2.66224085196883, 2.86286699940368, 
+3.11229271936026, 3.42552869144426, 3.82228208721348, 4.32538073648985, 
+4.95733844825089, 5.73469799153308, 6.66008382285581, 7.71298024585169, 
+8.84278798375668, 9.9708802197353, 11.0077301376417, 11.8811586252550, 
+12.5562249200948, 13.0252371694272, 13.2718501220904, 13.2453324038565, 
+12.8785602037281, 12.1423912900149, 11.0949293671124, 9.88883882995543, 
+8.5467218774983, 7.38690239704012, 7.20028586517441, 6.92043014430779, 
+6.86143897644225, 6.89059907129659, 6.88405298591553, 6.75375272735434, 
+6.45704940593019, 5.99827023740558, 5.42489406846863, 4.81312363509525, 
+4.24164599830188, 3.76717516319476, 3.41849141084796, 3.20687868985864, 
+3.13531160799788, 3.19726936232059, 3.37187355001604, 3.62363677543904, 
+3.90835991174716, 4.18271251920784, 4.40525039755585, 4.52804728137545, 
+4.52660271870405, 4.43310912163146, 4.29534519965863, 4.14419234461087, 
+4.00209980777877, 3.88513476360589, 3.80006647929475, 3.74600714192558, 
+3.71820914728559, 3.71121514895179, 1.12907174741704, 1.16657503920103, 
+1.20585455515754, 1.25027802286868, 1.30438875168590, 1.37285790802295, 
+1.45867934271824, 1.56111418076886, 1.67432970685413, 1.78772224047499, 
+1.88834590715381, 1.96484058717613, 2.01131146996977, 2.02939422600685, 
+2.02749713054915, 2.017566957081, 2.01088694359659, 2.01472049875274, 
+0, 0, 0, 0, 2.14106436937397, 2.15769709688887, 2.16645279746909, 
+2.16835275671587, 2.16511658361561, 2.15855887975471, 2.15013770888115, 
+2.14068077509741, 2.13029921693778, 2.11849889035789, 2.10448787534990, 
+2.08764460278591, 2.06805976147979, 2.04701820758887, 2.02727166803889, 
+2.01298976888780, 2.00936771450538, 2.02199095204544, 2.05616791944931, 
+2.11649542949621, 2.20688808432580, 2.33118528688089, 2.49428034835324, 
+2.70354544055190, 2.97019564338028, 3.31016017147592, 3.74399425930201, 
+4.29534153748999, 4.98742454365918, 5.83703986372478, 6.84581573225755, 
+7.9897683612796, 9.21136267386093, 10.4223586065191, 11.5250256568069, 
+12.4465668740278, 13.1619399067332, 13.6774765121676, 13.9827265434522, 
+14.0174649685661, 13.6956202838429, 12.972263545503, 11.9002302195401, 
+10.6362347126091, 9.34161440054387, 8.2488564383788, 7.66401998970449, 
+7.28287742927576, 7.13308039718399, 7.08700701496978, 7.0241709780143, 
+6.85774670783103, 6.54442480070732, 6.0851708912103, 5.5195858110821, 
+4.91214095201913, 4.33161677927973, 3.83278821984338, 3.44986296786115, 
+3.20049046074421, 3.09064101768301, 3.11467707821387, 3.25325229041775, 
+3.47387581742023, 3.73870854457766, 4.01901163307043, 4.27864379610441, 
+4.42603391976134, 4.39727270511581, 4.26429950241995, 4.11597565992685, 
+3.97577724902600, 3.85118814414364, 3.75269361262722, 3.68536079333201, 
+3.64751843520065, 3.63409589415079, 3.63963599884458, 1.11688373731934, 
+1.15300022096017, 1.19184407594847, 1.23766659626951, 1.29606689322007, 
+1.37266166545810, 1.47084267985751, 1.58926037216047, 1.72020225812903, 
+1.85007694348328, 1.96250284019761, 2.04322996587519, 2.08497157275856, 
+2.0899661002218, 2.06903191016032, 2.03754764277234, 2.01021774039954, 
+1.99685779115398, 0, 0, 0, 0, 2.10052554036014, 2.11984620894457, 
+2.13189612790536, 2.13728110665595, 2.13738903470545, 2.13371732847486, 
+2.12738347627678, 2.11884315624598, 2.10781888823772, 2.09344232101834, 
+2.07460353686438, 2.05046674091682, 2.02105950660020, 1.98779468185492, 
+1.95376872129204, 1.92371904727234, 1.90361759239201, 1.90000364560147, 
+1.91927230689419, 1.96718838753431, 2.04886113090591, 2.16929682817279, 
+2.33447938215127, 2.55276197050079, 2.83622444353239, 3.20157080027028, 
+3.67008977667765, 4.26614716749673, 5.013600320537, 5.92946873971242, 
+7.01446010012979, 8.2414125807649, 9.54649567372274, 10.8329766324908, 
+11.9965841671648, 12.9613224645721, 13.7274244183203, 14.3015555286402, 
+14.6811613493057, 14.7935647529786, 14.5329897428001, 13.8407001792527, 
+12.7659258918045, 11.4677283177979, 10.1621040379609, 9.0483827073821, 
+8.24549741800722, 7.75411718136203, 7.49807943177817, 7.35969717590859, 
+7.22477095174145, 7.00803658123804, 6.66409980910448, 6.18955101284335, 
+5.61755260720478, 5.00451339516068, 4.41217241250260, 3.89250573714906, 
+3.48126355315427, 3.19903741029168, 3.05398784809124, 3.04231150818417, 
+3.14714937391073, 3.33993058860954, 3.59453190784398, 3.91419386929792, 
+4.27455190741087, 4.48400173261203, 4.3886753952194, 4.15270259423548, 
+3.96081669218834, 3.82163577293503, 3.71069325406455, 3.62790352015387, 
+3.57614276736261, 3.55294955067899, 3.55285289535755, 3.57026733138316, 
+1.10480588951478, 1.13973162005644, 1.17843198443470, 1.2260872133063, 
+1.28940317363614, 1.37498417524279, 1.48663118671564, 1.62234087119777, 
+1.77240892207476, 1.92008131109204, 2.04533581806943, 2.13085143587836, 
+2.16784817585825, 2.1591805155286, 2.11820167367268, 2.06391821677194, 
+2.01466346755079, 1.98297010969913, 0, 0, 0, 0, 2.06135881741654, 
+2.08314695574494, 2.09825417536246, 2.10684992459736, 2.10998321025265, 
+2.10883765811510, 2.10420204500342, 2.09617942249999, 2.08413034146384, 
+2.06684578792876, 2.04293721230291, 2.01139763444192, 1.9722350149735, 
+1.92703007919652, 1.87925540372025, 1.83423323987825, 1.79870787627895, 
+1.78013891287312, 1.78593848109967, 1.82292987154011, 1.89726915130456, 
+2.01495126868194, 2.18285495801099, 2.41011538483469, 2.70948566853317, 
+3.09826405257952, 3.59829975373812, 4.23451290313271, 5.03124981506028, 
+6.00569320793327, 7.15779911939937, 8.45785116316068, 9.83703725607356, 
+11.1922022626508, 12.4150425494835, 13.429023634366, 14.2584506108118, 
+14.9094824933427, 15.382049538181, 15.5868770037456, 15.3986609694871, 
+14.7487072048178, 13.6857805326760, 12.3708418675633, 11.0208794507340, 
+9.83358911217194, 8.9267386569962, 8.3168854357185, 7.93984863736648, 
+7.69228884269417, 7.4694352068031, 7.18864091443858, 6.80205916532897, 
+6.30176804201687, 5.71571489134189, 5.09419634748297, 4.49255684214331, 
+3.95800974971464, 3.52438396348523, 3.21271543602515, 3.03306250979564, 
+2.98458543785135, 3.05416906913482, 3.21877790913008, 3.47143818277871, 
+3.87017025185080, 4.4110412396696, 4.73015199042386, 4.51870743560812, 
+4.10015754496742, 3.82506291242926, 3.67709851184234, 3.57758799314518, 
+3.50919055327683, 3.47186580712054, 3.46239311652179, 3.47491689112451, 
+3.50369239351861, 1.09259269147293, 1.12648339577914, 1.16524806343820, 
+1.21500253681346, 1.28356356219863, 1.37852245442349, 1.50408149356672, 
+1.65756594079698, 1.82725089434319, 1.99318083806216, 2.13164880624121, 
+2.22222201355131, 2.25460013174145, 2.23224829147454, 2.17107291958425, 
+2.09374520194346, 2.02227160734264, 1.97194195927519, 0, 0, 0, 
+0, 2.02385469450301, 2.04787621287714, 2.06577585061504, 2.07727974459240, 
+2.08309786312332, 2.08410746087856, 2.08078412841083, 2.07290215729709, 
+2.05949197482675, 2.03904228088324, 2.00992787943252, 1.97101190133932, 
+1.92231837591571, 1.86562144672995, 1.80478164335074, 1.74570116043695, 
+1.69587162858016, 1.66362349825449, 1.65730755902768, 1.68469548948433, 
+1.75284901504695, 1.86858419878932, 2.03948826027335, 2.2752808678303, 
+2.58918415954514, 2.99887867182532, 3.52655048868287, 4.1974420706442, 
+5.03618119754002, 6.06003094517858, 7.26844923641765, 8.63008352683753, 
+10.0730401286278, 11.490609498157, 12.7735953381492, 13.859570732391, 
+14.7582444727795, 15.5082139254609, 16.0933365680617, 16.403500205769, 
+16.2953983287967, 15.6944155728285, 14.6507378870934, 13.3276769786089, 
+11.9417718903158, 10.6869744463448, 9.68007697911116, 8.94571807706118, 
+8.43589070391587, 8.06494045040962, 7.74038200218037, 7.38356170095187, 
+6.94461424064093, 6.4118111914697, 5.8092350770206, 5.18202740304209, 
+4.57827642745096, 4.03754234763704, 3.5883017366014, 3.24998128814764, 
+3.03455908826655, 2.94550183256647, 2.97501293051948, 3.10727837905074, 
+3.35925100133783, 3.85699179802917, 4.62207194042947, 5.07742364844644, 
+4.72240672794806, 4.07745934275981, 3.69818066439022, 3.5372794716143, 
+3.44906817798646, 3.39508750413308, 3.37199116091975, 3.37589375486047, 
+3.4006519255279, 3.44041619577327, 1.08006941171753, 1.11303351990491, 
+1.15196055072232, 1.20385925895660, 1.27760313584406, 1.38171852944129, 
+1.52078082950781, 1.6914625903671, 1.88009741953985, 2.06366082483967, 
+2.21491584050317, 2.31044780039043, 2.33849642650003, 2.30310586541981, 
+2.22262209449609, 2.12322295416734, 2.03043406280274, 1.96219133030469, 
+0, 0, 0, 0, 1.98822513480713, 2.01424941184788, 2.03466233903327, 
+2.04875622803230, 2.05690969807065, 2.05970509849795, 2.05732383739838, 
+2.04923971406282, 2.03419017985666, 2.01040495418473, 1.97606651803535, 
+1.92994662703966, 1.87211138967514, 1.80453746605977, 1.73146436715107, 
+1.65934812215865, 1.59638497251012, 1.55171516746302, 1.53454527461601, 
+1.55348748741996, 1.61637556392836, 1.73068938353014, 1.90454718696872, 
+2.14805801548179, 2.47469950028785, 2.90229819262905, 3.45311387834772, 
+4.15242914554776, 5.02489680007215, 6.08775452521722, 7.34026435846657, 
+8.75054013360485, 10.2458641616154, 11.7192773124281, 13.0640222316845, 
+14.2248586067824, 15.2200764777282, 16.0902680999717, 16.8052834716266, 
+17.2329313614732, 17.2157969596821, 16.6738148072042, 15.652824301889, 
+14.3189478582656, 12.8957048652500, 11.5756912917554, 10.4705437171529, 
+9.60911487249641, 8.9593041871031, 8.45516520067462, 8.01872120775808, 
+7.5767285976454, 7.07833864314502, 6.50949506182001, 5.89209572424734, 
+5.26660327920551, 4.67201804160830, 4.13660293493871, 3.67985213986765, 
+3.31766935872385, 3.06417573767813, 2.92873110016263, 2.91071774297832, 
+3.00249836411837, 3.24126650706821, 3.8065945528039, 4.73998983425282, 
+5.29924711404113, 4.83471715932010, 4.01829740614448, 3.56322341568362, 
+3.39745293558043, 3.32289991287684, 3.28445457161840, 3.27611273462255, 
+3.29351067730285, 3.3303752413731, 3.38087173527404, 1.06713002335740, 
+1.09922749153532, 1.13829306041276, 1.19213039961673, 1.27055123700846, 
+1.38290919050791, 1.53410399776426, 1.72021668235851, 1.92583964625228, 
+2.12520203281832, 2.28791045343511, 2.38788469246961, 2.41205938506642, 
+2.36499607544323, 2.26722168779241, 2.14805012207708, 2.03615596930510, 
+1.95184537704106, 0, 0, 0, 0, 1.95459748064579, 1.98241176742155, 
+2.00505871223768, 2.0214232339632, 2.03156768928051, 2.03579441987043, 
+2.03401290541399, 2.02542949632247, 2.00853196825542, 1.98134013289368, 
+1.94189083024759, 1.88889856749748, 1.82248446930261, 1.74481620732901, 
+1.6604797095875, 1.57643821492466, 1.50153701323129, 1.44566114759945, 
+1.41879317146479, 1.43028514825263, 1.48861824734302, 1.60178789861258, 
+1.77827291839082, 2.02837869529967, 2.36561880680999, 2.80771321005069, 
+3.37670570693602, 4.09760315226874, 4.9947922372049, 6.08535313334075, 
+7.36864872697784, 8.81338684659615, 10.3483193389227, 11.8694830388866, 
+13.2755167451802, 14.5188886570903, 15.6240161744333, 16.6279181930830, 
+17.4839414521584, 18.0430092103202, 18.1420802389593, 17.6863773225027, 
+16.6925310275615, 15.3295980154114, 13.8512616554676, 12.4605649283117, 
+11.2589700457949, 10.2719300141831, 9.48031532413198, 8.83838744821754, 
+8.28418213055386, 7.75129254868271, 7.189454422257, 6.5843832704453, 
+5.95771108233163, 5.3453706760025, 4.77480329209743, 4.258811065195, 
+3.8040825604423, 3.42113261463858, 3.12661209595853, 2.93761053594246, 
+2.86279814919386, 2.90280003875365, 3.10247055966783, 3.65148959664572, 
+4.59463912741762, 5.16456011917996, 4.68797264296615, 3.85669885566685, 
+3.40469996560978, 3.25417010726751, 3.19768589086478, 3.17661919791165, 
+3.18403606951675, 3.21535790931586, 3.26437442727869, 3.32542452905029, 
+1.05373826206938, 1.08498750668122, 1.12405115101024, 1.17937436795693, 
+1.26152462447726, 1.38052009457523, 1.54151654111819, 1.74010774056429, 
+1.95946602784159, 2.17158529555505, 2.34350552182260, 2.44698094094939, 
+2.46788870926009, 2.41121638280840, 2.29927054024881, 2.16392142663445, 
+2.03640976401455, 1.93897380325536, 0, 0, 0, 0, 1.92300341189822, 
+1.95242368059682, 1.97704055614641, 1.99537258319747, 2.00718593941892, 
+2.01251970427202, 2.01103672537121, 2.00171498124666, 1.98284430746182, 
+1.95229170163348, 1.90799800852569, 1.84864756140624, 1.77440997945218, 
+1.68760354421847, 1.59309813272143, 1.49829673939532, 1.41263250243384, 
+1.34667873815119, 1.31113017384015, 1.31599419230321, 1.37028674365481, 
+1.48237787144252, 1.66094017154617, 1.91628269879467, 2.26173177423158, 
+2.71463974300915, 3.29653188143405, 4.03180738357422, 4.94427625174843, 
+6.05069938841322, 7.35077555435101, 8.81479446015053, 10.3749771964701, 
+11.933047648378, 13.3950862941261, 14.7208014855859, 15.9372886349607, 
+17.0746191726552, 18.0728327922758, 18.7819689109905, 19.0498215546726, 
+18.7413749319490, 17.7851491559766, 16.3529971717198, 14.7784924757846, 
+13.3011177454035, 12.0045899517902, 10.8975281102768, 9.96758708178804, 
+9.18823880386408, 8.51451087277347, 7.88851115379281, 7.26274118402454, 
+6.62517372760472, 5.99894341616321, 5.41508807658444, 4.88653615271766, 
+4.40625227493652, 3.96431661130635, 3.56410940312005, 3.22536472505094, 
+2.974961224473, 2.83320110592435, 2.80905957708161, 2.94110106049522, 
+3.38107326319098, 4.1585850375097, 4.63589378141589, 4.25474719101611, 
+3.58154148214524, 3.21965569624523, 3.10653197426286, 3.07300734355814, 
+3.07142764969769, 3.09580823819109, 3.14162071114107, 3.20291526187436, 
+3.2743752788748, 1.03993096743807, 1.07032506278931, 1.10915422040637, 
+1.16530236003887, 1.24985351040254, 1.37327921592104, 1.54090578269681, 
+1.74798197608328, 1.97668728999166, 2.19745668079912, 2.37554255859186, 
+2.4811943005693, 2.49956039740852, 2.43593723946017, 2.3138853166153, 
+2.16706883744929, 2.02852574841233, 1.92184611431169, 0, 0, 0, 
+0, 1.89335692834254, 1.92423545781155, 1.95059195453422, 1.97062812081397, 
+1.98383390417540, 1.99000074286832, 1.98857312252786, 1.97834856081856, 
+1.95748385704106, 1.92376298043183, 1.87508502212178, 1.81011977154413, 
+1.72904799651139, 1.63425395678879, 1.53078650933030, 1.42639734853349, 
+1.33105062474711, 1.25597923457848, 1.21256311962543, 1.211411446722, 
+1.26197998777612, 1.37287780156612, 1.55280284612479, 1.81187155803477, 
+2.16299676879371, 2.6229005437734, 3.21228713952599, 3.95461727220578, 
+4.87281016789061, 5.98311729788887, 7.2857057106199, 8.7531697265089, 
+10.3226590640286, 11.9033762536789, 13.4096698359776, 14.8068372803984, 
+16.1210409587582, 17.3744911103895, 18.5038525980048, 19.3847990086172, 
+19.9041130512343, 19.8464802537508, 18.9532559612267, 17.3896685486017, 
+15.6493351107782, 14.0569217638778, 12.6670247632186, 11.4495894290264, 
+10.3894065779757, 9.4770002289530, 8.6852423654237, 7.96709030326162, 
+7.28076695178615, 6.61908452410128, 6.00774301348632, 5.47163844031236, 
+5.00582514077527, 4.57919786790578, 4.16177142964374, 3.74830792210543, 
+3.36234228104793, 3.04275693243495, 2.82403385935268, 2.72463338607132, 
+2.77043376386471, 3.05127103059847, 3.57237838895841, 3.90393146915024, 
+3.67272405948706, 3.24593091793093, 3.01946034615338, 2.95629916357576, 
+2.94937582021758, 2.96921223283823, 3.01170241753335, 3.07255030832972, 
+3.14624127435675, 3.22796105396074, 1.02582227735342, 1.05535398010028, 
+1.09366666455625, 1.14984267233729, 1.23520043808051, 1.36041691508426, 
+1.53089004583244, 1.74169333963475, 1.97451871926256, 2.19904037891091, 
+2.3796420139239, 2.48584769501000, 2.50246639841505, 2.43496755809966, 
+2.30754814471535, 2.15476873636519, 2.01055731316446, 0, 0, 0, 
+0, 0, 1.86541400026264, 1.89764559278251, 1.92557064266269, 1.94712147246933, 
+1.96152283961485, 1.96832814962070, 1.96679499632654, 1.95560239003385, 
+1.93286068677209, 1.89636171443199, 1.84402491466019, 1.77450279970846, 
+1.68790028616861, 1.58651274585118, 1.47539821025578, 1.36253540125810, 
+1.25838046817508, 1.17485391772142, 1.12406298478324, 1.11721975882330, 
+1.16415227772011, 1.27357620378512, 1.45403703985966, 1.71525169820105, 
+2.06948817308672, 2.53257843880859, 3.12411413435815, 3.86630317586712, 
+4.7808723243819, 5.88335331639968, 7.17439714024284, 8.6293046100876, 
+10.1909711212168, 11.7768733985851, 13.3092807134415, 14.7565594420184, 
+16.1405702081968, 17.4768492530923, 18.7118810468321, 19.7776776555536, 
+20.6336883419751, 20.9567254733387, 20.1905312905105, 18.4368799194418, 
+16.4358974300351, 14.6880865090464, 13.2078603818306, 11.8937715287394, 
+10.7151077223166, 9.67680551964508, 8.7707404423834, 7.96405347528263, 
+7.22451050750371, 6.55214557735801, 5.97508532814266, 5.50966420860472, 
+5.12941704385461, 4.77545403140032, 4.39492809181753, 3.97286574558289, 
+3.53742652035223, 3.14175059845003, 2.83714487530986, 2.65388962117223, 
+2.60835772508618, 2.73527565521623, 3.0181145572862, 3.21518880476227, 
+3.12034977198468, 2.91958396012209, 2.81995730616512, 2.80662444296583, 
+2.82800835642973, 2.87069122287679, 2.93216716840114, 3.00844211571620, 
+3.09456735506986, 3.1863558190438, 1.01160692005338, 1.04030039310963, 
+1.07782166782766, 1.13318975351891, 1.21765094975431, 1.34181858340324, 
+1.51105468975107, 1.72044037845002, 1.95172517475660, 2.17468391714116, 
+2.35382349043897, 2.4587847402046, 2.47445847719687, 2.40634217928974, 
+2.2786037271608, 2.12573034201601, 1.98155804488291, 0, 0, 0, 
+0, 1.80571245523669, 1.83870729719839, 1.87223773454329, 1.90165705271267, 
+1.92465775213268, 1.94018807590714, 1.94755953591264, 1.94587816313595, 
+1.93378904125657, 1.90947818779140, 1.87087092489650, 1.81598263814625, 
+1.74341723463298, 1.65303825066996, 1.54678659087214, 1.42945912233753, 
+1.3090961678708, 1.19664226746488, 1.10483148670934, 1.04665642590097, 
+1.03402305912932, 1.07710666674731, 1.18459803298698, 1.36469201085675, 
+1.62647743890647, 1.98133527911457, 2.44395176251166, 3.03253294660888, 
+3.76774852598455, 4.66985828454912, 5.75345862370587, 7.01959745320356, 
+8.44638212353566, 9.9826787329912, 11.5541925777933, 13.089971779318, 
+14.5586816027459, 15.9751365178099, 17.3501886522649, 18.6507911295221, 
+19.8825028983498, 21.1011581492899, 21.9076135585424, 21.3991627093274, 
+19.4573344121182, 17.1016779487026, 15.1550901622987, 13.5923416173947, 
+12.1995553630542, 10.9170582732069, 9.76201466768818, 8.74701461383123, 
+7.85772770074768, 7.0759989785008, 6.41101138509752, 5.89178733369965, 
+5.52255782341881, 5.25170513338048, 4.98970874147798, 4.65891959304474, 
+4.23385970992346, 3.74809644009125, 3.27115150847581, 2.87371813795380, 
+2.60068769548145, 2.46676036581926, 2.47372129758928, 2.59176441179691, 
+2.69808088644139, 2.69127447932974, 2.64064813640115, 2.63139328360380, 
+2.66067468964316, 2.71053522530999, 2.77682909505654, 2.85775480882934, 
+2.94960469240545, 3.0480705784283, 3.14967137491526, 0.997560833168382, 
+1.02550650870025, 1.06203178454735, 1.11582761818357, 1.19775845870028, 
+1.31810176223002, 1.48207287757926, 1.68494000934542, 1.90905194218795, 
+2.12514213213168, 2.29882976606676, 2.40071305212298, 2.41618607260544, 
+2.35063044824133, 2.22752001009542, 2.08029734653683, 1.94172058476645, 
+0, 0, 0, 0, 1.77844961285460, 1.81245387349484, 1.84729560355688, 
+1.87828754911457, 1.9028723207533, 1.91966875185731, 1.92771836301546, 
+1.92601592787383, 1.91329259713944, 1.88798811774479, 1.84834189971688, 
+1.79256304977836, 1.71913294370706, 1.62738893422765, 1.51848345492207, 
+1.39652960430952, 1.2693994152888, 1.14857967646170, 1.04789722601920, 
+0.981568187364813, 0.962421739139982, 1.00101935893633, 1.10589406182318, 
+1.28465681062745, 1.54550250291555, 1.8986620078655, 2.35742179991282, 
+2.93835197471374, 3.66033604349328, 4.54193169491662, 5.59659737110635, 
+6.82562257656828, 8.20979359859746, 9.70373901076467, 11.2408219115957, 
+12.7554843511631, 14.2143872003541, 15.6234904712394, 16.990295021882, 
+18.3046725687164, 19.6358834173618, 21.1306534213728, 22.4193711475810, 
+22.3317915446646, 20.3087811164344, 17.5741399424383, 15.4169231902559, 
+13.7915701342804, 12.3424419361091, 10.9732112904132, 9.71257058497935, 
+8.5959430797656, 7.63238090969573, 6.8225536703692, 6.18608786672666, 
+5.75024942052392, 5.50305044944623, 5.36462829290447, 5.21315129344, 
+4.94511203633521, 4.52394758664736, 3.98914260286382, 3.42837028305348, 
+2.93396977353382, 2.56785806383231, 2.34997571673175, 2.26918428036199, 
+2.29002893094672, 2.34526432339046, 2.3814311638208, 2.41038952347654, 
+2.4569403207109, 2.52113916551417, 2.59873921282632, 2.68868722828663, 
+2.78904477181651, 2.89632728488181, 3.00688157151414, 3.11795975784644, 
+0.984037617612806, 1.01142577913925, 1.04688246331256, 1.09852127422955, 
+1.17653306272647, 1.29060180722814, 1.44568764038464, 1.63740576875896, 
+1.84919936749818, 2.05354893195050, 2.21809699771135, 2.31517460981324, 
+2.33106855504908, 2.27091151955522, 2.15686636572407, 2.02042677837346, 
+1.89235158995455, 0, 0, 0, 0, 1.75046567422901, 1.78544347752892, 
+1.82170404672001, 1.85457966148879, 1.88118542316903, 1.89969050580836, 
+1.90879934625308, 1.90744212002496, 1.89460870245747, 1.8692541895626, 
+1.83019492870750, 1.77596590734405, 1.70479202840582, 1.61502809557940, 
+1.50636097477801, 1.38157747456271, 1.24805851934897, 1.11797049930290, 
+1.00673427444189, 0.930388249777948, 0.903113906686615, 0.935989418225768, 
+1.03725336190731, 1.21364634387706, 1.4721459822684, 1.82153491212993, 
+2.27344110884513, 2.84257092452241, 3.54581550106296, 4.39984306342527, 
+5.41680175869754, 6.59804067283221, 7.92676641837584, 9.36292478732141, 
+10.8467825920663, 12.317049538971, 13.7370919754603, 15.1033319566973, 
+16.4199189104114, 17.6933213203939, 19.0237410563955, 20.6095439135118, 
+22.2188626310053, 22.6063942969818, 20.6879126499616, 17.7190356512176, 
+15.4310682503249, 13.7853663323208, 12.3063087472732, 10.8697740238746, 
+9.51748017916185, 8.30960819619003, 7.2829633190412, 6.46116886212965, 
+5.87487364340106, 5.54652397299636, 5.4442169056116, 5.45799949366485, 
+5.43344230965492, 5.24090197752489, 4.8320995086088, 4.25239832010788, 
+3.60876548925047, 3.01689490316301, 2.55734624787037, 2.25913678351461, 
+2.10939421956693, 2.07127145460335, 2.09703828474162, 2.14898225717742, 
+2.21566338306058, 2.29684069169086, 2.39036364004672, 2.49435124963134, 
+2.60729066599064, 2.72657623840116, 2.84885288638491, 2.97107923724482, 
+3.09121785707345, 0.971459825966679, 0.998608387801888, 1.03310739535480, 
+1.08227516275883, 1.15537359751239, 1.26126590969737, 1.40455577620029, 
+1.58133197252920, 1.77654366860293, 1.96508015610592, 2.11737513845789, 
+2.20814765403943, 2.22490652083426, 2.17242098419243, 2.07101385167732, 
+1.94944995496044, 1.83568867163124, 0, 0, 0, 0, 1.72013756557919, 
+1.75593099331962, 1.79385886230853, 1.82926913088081, 1.85877049157812, 
+1.87986245279258, 1.89078723474865, 1.89046453866286, 1.8783891512508, 
+1.85441023343660, 1.81829942659656, 1.76909963657125, 1.70456629821716, 
+1.62138418292203, 1.51676866200750, 1.39123951801067, 1.25123677804825, 
+1.10985515997004, 0.984909542681677, 0.895210507253769, 0.856990131620135, 
+0.882096804517931, 0.978332001473723, 1.15120605394432, 1.40607555683809, 
+1.74992462178705, 2.19244991741391, 2.74628547671905, 3.42616592921611, 
+4.24673419917158, 5.21869864711565, 6.34329575596431, 7.60585055526862, 
+8.97111210415583, 10.3855659085724, 11.7916028342807, 13.1492077446017, 
+14.4457194156585, 15.6810222003548, 16.8677818483120, 18.1010066263597, 
+19.5734998698562, 21.2063283183735, 21.8932605275869, 20.2567827517088, 
+17.3918329834376, 15.1670487856400, 13.5658197212973, 12.0854091878812, 
+10.6032646693369, 9.17723319793398, 7.89306432177594, 6.81798063906048, 
+6.00112326851375, 5.48402595584097, 5.28177355884121, 5.34043238069579, 
+5.52007898796947, 5.63495465499833, 5.52966047127258, 5.14333444614876, 
+4.52639616282374, 3.80530853151601, 3.11996347561404, 2.57024913967037, 
+2.19554051486398, 1.98546433293506, 1.90347862236651, 1.90702297218895, 
+1.96153189552628, 2.04660978120843, 2.15167149821511, 2.27045950715575, 
+2.39889469376168, 2.53352868353043, 2.67080017165063, 2.80736152759876, 
+2.94069055277642, 3.06939451619883, 0.960304672553514, 0.987677299121674, 
+1.02154740039932, 1.06826304251503, 1.13595183804885, 1.23247101413344, 
+1.36197799310928, 1.52111886785725, 1.69665042694228, 1.86636462022055, 
+2.00406363665093, 2.08734910026752, 2.10520025245428, 2.0619317077013, 
+1.97561219993721, 1.87166102921054, 1.77459698802378, 0, 0, 0, 
+0, 1.68527264287413, 1.72157695304012, 1.76162662482731, 1.80069387835730, 
+1.83456306635897, 1.85970677738001, 1.87369910893414, 1.87551085349473, 
+1.86548337196194, 1.84489140260310, 1.81499122388366, 1.77558308756392, 
+1.72364403229993, 1.65321331791367, 1.55761724599420, 1.43379341370010, 
+1.28663014722083, 1.13053587657899, 0.986890539118945, 0.878663861761312, 
+0.82517221100699, 0.839441049516308, 0.928684413003913, 1.09673007501431, 
+1.34680764216297, 1.68368345913019, 2.11482577465671, 2.65060143279348, 
+3.30346349199873, 4.08594462150438, 5.00723262382784, 6.06831290531273, 
+7.25634340697171, 8.54039808108924, 9.87267756652758, 11.1992210893923, 
+12.4775644811400, 13.6873659481387, 14.8233752228127, 15.8956791010380, 
+16.9716607077361, 18.1909248319357, 19.5496972662868, 20.2207474975313, 
+18.9591158259112, 16.572309222692, 14.6320193187002, 13.1402849439639, 
+11.6854023349000, 10.1813034950558, 8.70423833413912, 7.36432636824328, 
+6.25912159862487, 5.46350230607213, 5.0290873101669, 4.96239808572317, 
+5.18786565697386, 5.53818949960021, 5.79921302317837, 5.79082766217718, 
+5.43850076788906, 4.79598841851855, 4.00818186708345, 3.23874264422896, 
+2.60650405166979, 2.1609912627801, 1.89527366584608, 1.77378330784233, 
+1.75537409197107, 1.80557447497989, 1.90006431843874, 2.02283956497768, 
+2.16320722078109, 2.31358228336464, 2.46809783519404, 2.62205527429776, 
+2.77196559636319, 2.91569578505082, 3.05239980169906, 0.95108431862122, 
+0.979296291134575, 1.01309687174522, 1.05773805474051, 1.12006525818608, 
+1.20679335420813, 1.32155811949481, 1.46159975713152, 1.6156611535216, 
+1.7647417172567, 1.88637429982743, 1.96135587235192, 1.98029209092176, 
+1.94697638701850, 1.87693656735675, 1.79180994307366, 1.71220806897508, 
+0, 0, 0, 0, 1.64313780895901, 1.67950006823137, 1.72241378354199, 
+1.76687450374331, 1.80734742429013, 1.83874514594204, 1.85766267787651, 
+1.86318868704515, 1.85696672644755, 1.84241223274065, 1.82297720053463, 
+1.79955286195461, 1.7679242287051, 1.71818378613949, 1.63788293426548, 
+1.51863469676055, 1.36297933160555, 1.18717661192765, 1.01776123889828, 
+0.883743431564935, 0.808937460543945, 0.808126858991371, 0.887779735982757, 
+1.04948459952473, 1.29372161134567, 1.62253971874503, 2.04084954081546, 
+2.55656402380479, 3.17976387245663, 3.92083331079112, 4.78740695862813, 
+5.78012414830259, 6.88773443428403, 8.08323190163563, 9.32420037641722, 
+10.5606676796553, 11.7492516880401, 12.8639236355331, 13.8941630674096, 
+14.8431696557821, 15.7459705448660, 16.6729213615750, 17.6154514033032, 
+18.0500693150149, 17.1520604402034, 15.4217580767356, 13.8783653683135, 
+12.5310254397431, 11.1230212238664, 9.62188792597147, 8.12109991371683, 
+6.75148798548525, 5.63761875990788, 4.87763738861606, 4.53185936986394, 
+4.59877947886043, 4.98445002216841, 5.49937412237967, 5.90565188495454, 
+6.00040288398029, 5.69441361842045, 5.04222512395637, 4.20451983294783, 
+3.36656361762337, 2.66443738885096, 2.15674249219377, 1.83994160584543, 
+1.68008881535013, 1.63756973029919, 1.67839321125631, 1.77638327608945, 
+1.91185591043523, 2.06991836427751, 2.23927423955255, 2.41148672357498, 
+2.58056674055624, 2.74271608348126, 2.89603813126163, 3.04011558962406, 
+0.944321349231223, 0.97413216462925, 1.00864314347021, 1.05193401519828, 
+1.10947861334332, 1.18676344310755, 1.28684332786640, 1.40754381463176, 
+1.53964993106133, 1.66748411922763, 1.77245602370390, 1.83868758872101, 
+1.85847301947430, 1.83504086330994, 1.78121552444379, 1.71459162057188, 
+1.65157546381819, 0, 0, 0, 0, 1.59066540136799, 1.6265162393636, 
+1.67341322380626, 1.72574728140143, 1.77596143762750, 1.81666697296651, 
+1.84304217216708, 1.85436023334117, 1.85414512378412, 1.84886751201615, 
+1.84508388963736, 1.84520621633481, 1.84331604339017, 1.82393503158163, 
+1.7664861778473, 1.65508736015079, 1.48894656788663, 1.28686141641603, 
+1.08252593839058, 0.91336341077317, 0.809477951249996, 0.788166530985535, 
+0.854986314439343, 1.00862756370898, 1.24608383898218, 1.56610736518297, 
+1.97068886507764, 2.46510587815061, 3.05700531631018, 3.75462542712121, 
+4.56405793658297, 5.4855433235809, 6.50922894777293, 7.61169038632372, 
+8.75565883442602, 9.89561594094782, 10.9889300900854, 12.0060563680472, 
+12.9318772742126, 13.7624067607966, 14.5073926251239, 15.1830224441504, 
+15.7536867068034, 15.9347596638694, 15.3176922803559, 14.1616865657102, 
+12.9769006224760, 11.7707795854786, 10.4244574754927, 8.95139450492716, 
+7.45736349516749, 6.08803266404915, 4.9886916550443, 4.27580596401902, 
+4.01648451833252, 4.20330973257952, 4.72969740190946, 5.39136964768243, 
+5.93305041105437, 6.13233062231567, 5.88492361990525, 5.24301829243355, 
+4.37868390070267, 3.49447306420965, 2.74043206381528, 2.18251099439081, 
+1.82047048549797, 1.62307473198842, 1.55371786424714, 1.58038465460896, 
+1.67651266359201, 1.81974534784172, 1.99138408158093, 2.17649225264571, 
+2.36399380578766, 2.54646223877838, 2.71961641540144, 2.88163580103803, 
+3.03240626237118, 0.940520392826103, 0.972813640618701, 1.00900436813902, 
+1.05196900200722, 1.10577428392406, 1.17463950837842, 1.26099578674977, 
+1.36320596725615, 1.47404390910284, 1.58110007216261, 1.66961137203939, 
+1.72698791228199, 1.74718853113531, 1.73285216638162, 1.69404702753879, 
+1.64421882698868, 1.59541751656278, 0, 0, 0, 0, 1.52490024895367, 
+1.55962774542444, 1.61208515856043, 1.67559440691135, 1.73964973418194, 
+1.79359552085616, 1.83061657529745, 1.85022844834583, 1.85852800423004, 
+1.86614411384209, 1.88383365622318, 1.91605687159231, 1.95461277726707, 
+1.97657209774334, 1.95049907378614, 1.85049900161375, 1.67130934836900, 
+1.43506886513072, 1.18496673358818, 0.96960564997879, 0.827476146612508, 
+0.779286287713264, 0.829515407999217, 0.973218459144729, 1.20307745135217, 
+1.51390885409132, 1.90439867220483, 2.37701508957244, 2.93693583458744, 
+3.59028980438135, 4.34167150068762, 5.190904694509, 6.12937868503407, 
+7.13695184995947, 8.1812797710307, 9.22168143450828, 10.2177330283435, 
+11.1383812060573, 11.9650592230322, 12.6882945965448, 13.3030426732305, 
+13.7976665799820, 14.1261695848349, 14.1499407790244, 13.7122720225944, 
+12.9247537182098, 11.9857068901775, 10.8975519295202, 9.62293084625415, 
+8.20186265486921, 6.74578945161239, 5.40796298625173, 4.34605635211064, 
+3.68814073987062, 3.50577693763167, 3.78869060652350, 4.42490758274026, 
+5.20426466826687, 5.86204719724194, 6.16129629004797, 5.98349048239127, 
+5.37512166132239, 4.51347830628261, 3.61173227650245, 2.82888864940137, 
+2.23593771907048, 1.83610214877894, 1.60252940303681, 1.50375661143898, 
+1.51166476345846, 1.60074379941130, 1.74685331232132, 1.92791289939314, 
+2.12547072498189, 2.32576502208277, 2.51979714497249, 2.70263936429807, 
+2.87239409212799, 3.02912819319809, 0.940137068732055, 0.975889392626321, 
+1.01487076475651, 1.05876035020866, 1.11022734736570, 1.17222542804948, 
+1.24653527418860, 1.33197959112864, 1.42318074121202, 1.51080437555082, 
+1.58370599640577, 1.63241103046983, 1.65244818468030, 1.64585658752975, 
+1.61998352854213, 1.58414362717846, 1.54599696937540, 0, 0, 0, 
+0, 1.44371219856101, 1.47678383050616, 1.53688786050227, 1.61567928262773, 
+1.69856483431866, 1.7704449494099, 1.82179996350593, 1.85242568123711, 
+1.87176717880221, 1.89585460621644, 1.94088038579939, 2.01396453507321, 
+2.10403531722876, 2.17872407094179, 2.19283540370433, 2.10778475397795, 
+1.91262732692944, 1.63369508909225, 1.32615447957068, 1.05273034101848, 
+0.862535190925361, 0.780654754585628, 0.81033019850482, 0.94221818904408, 
+1.16383536907563, 1.46540847182790, 1.84193693851122, 2.29292302944723, 
+2.82106569533526, 3.43044967863505, 4.12424553199568, 4.90186856467112, 
+5.75581987459988, 6.66895748061567, 7.61359535989933, 8.55407723726236, 
+9.45325548844007, 10.2802197381240, 11.0142092677115, 11.6422054105729, 
+12.1525880542070, 12.5255697225560, 12.7216429219752, 12.6753583411735, 
+12.3348472040677, 11.7383740124419, 10.9446852039132, 9.95151747934865, 
+8.75591687676917, 7.4081264134003, 6.01910050400593, 4.74211475321368, 
+3.73812106318327, 3.1393066725737, 3.01900719997446, 3.36723467703441, 
+4.07410761766882, 4.93296374264173, 5.67880276340669, 6.06702697031743, 
+5.96739433944242, 5.41757558500513, 4.592450504489, 3.70698982387233, 
+2.9225673607012, 2.31242542198641, 1.88372574324765, 1.61619752025296, 
+1.48604497533583, 1.47113203530700, 1.54843495700823, 1.69287680709756, 
+1.87941417065286, 2.08622333930752, 2.29683744401105, 2.50058081155786, 
+2.69174250301902, 2.86821510562679, 3.03013683520428, 0.94354564375181, 
+0.983787386357153, 1.02675280552026, 1.07295699757722, 1.12371510950438, 
+1.18074845445232, 1.24517546475670, 1.31618367801439, 1.39004416549649, 
+1.46020800792066, 1.51882724818684, 1.55927229317398, 1.57849612815685, 
+1.57793900104003, 1.56232788310408, 1.53695717193831, 0, 0, 0, 
+0, 1.35271072387667, 1.34672504611843, 1.37785678824035, 1.44819982498715, 
+1.54703011471877, 1.65436466257631, 1.74932452688019, 1.81887070844607, 
+1.86308633196447, 1.89556572055070, 1.9390322954291, 2.01639759254752, 
+2.13810363653531, 2.28969692155518, 2.427504372846, 2.48982672335683, 
+2.42285040369026, 2.20879317432130, 1.87897606141514, 1.50288071153121, 
+1.16013063439487, 0.912573335938535, 0.790591133594649, 0.796045458530972, 
+0.914487103973513, 1.12747697504965, 1.42005384450062, 1.78319316238872, 
+2.21331005740126, 2.71064434367517, 3.27732646536599, 3.91519716760642, 
+4.62329005734311, 5.39510456168936, 6.21621757327717, 7.06327301242258, 
+7.9056052297844, 8.70999107284356, 9.4469034688277, 10.0945462295239, 
+10.6377911612855, 11.0628781323255, 11.3507040461026, 11.4727456489421, 
+11.3958976497151, 11.1004131347047, 10.5939821656954, 9.88658154300633, 
+8.97332299910585, 7.86228671352143, 6.60515880166245, 5.30766424451044, 
+4.11621685142323, 3.18646404006103, 2.64746228968406, 2.57146590101964, 
+2.95124046979819, 3.68553460661292, 4.58003896186162, 5.37921139998847, 
+5.83940340887789, 5.8229104324573, 5.35607422557408, 4.60293024962532, 
+3.76997450626262, 3.01328345100888, 2.40527823300771, 1.9577693963065, 
+1.65955376513281, 1.49713048904909, 1.45637228309705, 1.51806507254699, 
+1.65697080329399, 1.84549145126302, 2.05860725754754, 2.27717769870547, 
+2.48879719654197, 2.68687859175995, 2.86900330070003, 3.03529057594503, 
+0.95100699763883, 0.996777418088754, 1.04493853403867, 1.09489171735182, 
+1.14666407008325, 1.20080029597647, 1.25775824488018, 1.31698976653930, 
+1.37618399211406, 1.43123344170487, 1.47719934470206, 1.50996994964733, 
+1.52774809125958, 1.53138611245173, 1.52313790116606, 1.50445774682786, 
+0, 0, 0, 0, 1.25717033989132, 1.23631649997316, 1.26567685675133, 
+1.34927921487272, 1.47323274442430, 1.61079077120577, 1.73390142958542, 
+1.82514919323654, 1.88487390658289, 1.93156622510922, 1.99585310968938, 
+2.10856640545299, 2.28413007258993, 2.50438077278172, 2.71289653815108, 
+2.82930920342713, 2.78256120706929, 2.54710393882458, 2.15985337690282, 
+1.70642682024983, 1.28551561074783, 0.97335542336343, 0.806345766466208, 
+0.784860642541372, 0.888796920438674, 1.09315143126948, 1.37732370797529, 
+1.72802632558869, 2.13852609768343, 2.60665928553805, 3.13271442675496, 
+3.71731220065095, 4.35914436375287, 5.05260755479131, 5.78571780613993, 
+6.53906689754941, 7.28675649935905, 7.9997713338195, 8.65082460150697, 
+9.21808220509489, 9.68525907585324, 10.0381560450378, 10.2604089776522, 
+10.3321653603728, 10.2343516080589, 9.95575171538123, 9.49350282273242, 
+8.8439393319599, 8.00210252152164, 6.97951179241517, 5.82576825235773, 
+4.63806265082522, 3.55043386770376, 2.70615779064204, 2.22498257869636, 
+2.17526501123687, 2.55386996610945, 3.27295854630929, 4.15800711278785, 
+4.97239170287795, 5.48289914436722, 5.5499692083799, 5.18702264977242, 
+4.53896565214011, 3.79326171665902, 3.09279857136931, 2.50610459938342, 
+2.05040417954058, 1.72595044009793, 1.53189208252267, 1.46381202181983, 
+1.50738416128486, 1.63787149840531, 1.82552799994552, 2.04237436114477, 
+2.26670819978793, 2.48441575204783, 2.6879987672148, 2.87466592179464, 
+3.04445098675135, 0.962638766407284, 1.01493860768696, 1.0694611551687, 
+1.12455298837906, 1.17903163013805, 1.23233516045771, 1.28427466268385, 
+1.33447119597981, 1.38179651568390, 1.42422544856909, 1.45931987873487, 
+1.48513962227921, 1.50095527745115, 1.50705398216142, 1.50339897192472, 
+1.48784167048130, 0, 0, 0, 0, 1.15582885129295, 1.11845060027401, 
+1.14687235533435, 1.24701547383466, 1.40101680322886, 1.574053465753, 
+1.72959445735005, 1.84504100250775, 1.92092301293643, 1.98122831494475, 
+2.06546046634203, 2.21333398343283, 2.44384371760246, 2.73507944527938, 
+3.01716561082883, 3.1899368554317, 3.16401988849397, 2.90558224317328, 
+2.45740739780048, 1.92214812768634, 1.41864848471555, 1.03836076112613, 
+0.824060586871835, 0.774576625384017, 0.863875564125216, 1.06009187759571, 
+1.33678016028384, 1.67630866118825, 2.06882214094618, 2.50985322138440, 
+2.9979826054215, 3.53273226158439, 4.11250145569231, 4.73249455572551, 
+5.38289428164228, 6.04782807996747, 6.70580904613466, 7.3320351253735, 
+7.90199073879248, 8.3946253993592, 8.79320211278241, 9.08352898775428, 
+9.25152754880851, 9.2827756499107, 9.16487693270687, 8.88988780971758, 
+8.4528090167962, 7.84811864990748, 7.0730449039241, 6.14113140479597, 
+5.09867483929346, 4.03223862561108, 3.05970217261452, 2.30697453157639, 
+1.87990324937794, 1.84043047804881, 2.18969061962957, 2.8559619426594, 
+3.68989268434652, 4.48195280417731, 5.01857471122153, 5.16452133132806, 
+4.91978395647558, 4.40311269282096, 3.77353370012533, 3.15367626124512, 
+2.60543954053048, 2.1520488739111, 1.8070468380001, 1.58389552573572, 
+1.48899451597961, 1.51361062547930, 1.63402370037281, 1.81875932438784, 
+2.03720584533219, 2.26531873101537, 2.48739127399064, 2.69504803998947, 
+2.88510824513838, 3.05747959769399, 0.978389826513545, 1.03813366409216, 
+1.10007752811983, 1.16157462697492, 1.22031632545043, 1.27471197345863, 
+1.32395084031110, 1.36774223687365, 1.40592127165896, 1.43820233855814, 
+1.46425397202840, 1.48397280984886, 1.49752542336446, 1.50467194900804, 
+1.50329881247949, 1.48794868948076, 0, 0, 0, 0, 1.05709619079297, 
+1.00305150595891, 1.03220828539262, 1.15217992513101, 1.34038110092724, 
+1.55282393715889, 1.74345625430759, 1.88385599320229, 1.97465376049709, 
+2.04569999655414, 2.14595535941778, 2.32458327286331, 2.60559224037445, 
+2.96366597768010, 3.31578864106576, 3.54230933990802, 3.5357812336089, 
+3.25414662311207, 2.74587039503826, 2.1302653105808, 1.54590855345934, 
+1.09915102497817, 0.838997519291495, 0.76273694887476, 0.83850002303247, 
+1.02768326158842, 1.29812302143778, 1.62797108260356, 2.00438808882176, 
+2.42075480076785, 2.87409929395491, 3.36297456965993, 3.88554367635094, 
+4.43774166523155, 5.01166154797571, 5.59455071851085, 6.16890329556817, 
+6.71394387367587, 7.20819344433113, 7.63201776894453, 7.96882915560246, 
+8.20456069716965, 8.32655819498416, 8.32351701974324, 8.18669176875442, 
+7.91056465626032, 7.49141734951126, 6.92599733293301, 6.21523289241848, 
+5.37472215879375, 4.44700857293932, 3.5069433059011, 2.65422556307159, 
+1.99458964805460, 1.61716226714645, 1.57550060664533, 1.87426515142982, 
+2.45859358391074, 3.20733255644979, 3.94401805812457, 4.48238796568358, 
+4.69733798684732, 4.57603232131514, 4.20631227259223, 3.71189458582795, 
+3.18990842922118, 2.69353254025187, 2.25217334812197, 1.89351647770082, 
+1.64594462224690, 1.52696437239695, 1.53367160366248, 1.64371328895448, 
+1.82433426272097, 2.04273146507718, 2.27286457470668, 2.49765381101943, 
+2.70795405608894, 2.90022442043484, 3.07423178856951, 0.998021522634223, 
+1.06599193535286, 1.13625821691098, 1.20524093898920, 1.26958929611484, 
+1.32676579415690, 1.37537343261551, 1.41514899165220, 1.44670231100576, 
+1.47118287959050, 1.49001119269525, 1.50461881104138, 1.51591961397429, 
+1.52320460244987, 1.52253001599029, 0, 0, 0, 0, 0, 0.972530748310331, 
+0.903652747420896, 0.936146147682005, 1.07891424140846, 1.3040367114461, 
+1.55766448773798, 1.78362889201175, 1.94733442562736, 2.04942578295794, 
+2.12567843298615, 2.23457370640998, 2.43476691847413, 2.75550769134523, 
+3.16883327409701, 3.58008607076567, 3.85213060874572, 3.86123366657837, 
+3.55785080230452, 2.99540733027766, 2.30800631595915, 1.65177413137852, 
+1.14629653275103, 0.846065077276777, 0.746906208714226, 0.811640146078131, 
+0.995542024076472, 1.26124249505557, 1.58304567249008, 1.94539200193690, 
+2.33971780030030, 2.76167349935783, 3.20897824116357, 3.67961965035758, 
+4.17019935526695, 4.67448772742593, 5.18245530312672, 5.68012075060947, 
+6.15042970961559, 6.57499702276399, 6.93603977479963, 7.21763948728686, 
+7.40599676237211, 7.48926813769046, 7.45787634505296, 7.30529734448447, 
+7.02822804455271, 6.62554792895963, 6.09779696280771, 5.4502614749264, 
+4.70058043875242, 3.88733193833194, 3.07339783517054, 2.33983097283263, 
+1.77134631066104, 1.43921123844401, 1.38734951416898, 1.62270673564244, 
+2.10646236722098, 2.74633362867571, 3.40207518672835, 3.91981417491746, 
+4.18918162452068, 4.18612518308838, 3.96577393150584, 3.61317407285830, 
+3.19725774590358, 2.76125180718354, 2.34035575503723, 1.97599371421654, 
+1.71079927613797, 1.57274383841660, 1.56448005581144, 1.66520486009922, 
+1.84136756699013, 2.05853715091498, 2.28915460822616, 2.51509137194218, 
+2.72661114233193, 2.91988532118113, 3.09454875014395, 1.02109811365829, 
+1.09790342533427, 1.17719009048300, 1.25450575084211, 1.32554067992114, 
+1.38689493588371, 1.43663133811434, 1.47447683105750, 1.50166585111370, 
+1.52052859982120, 1.53393542575763, 1.54459492985968, 1.55404924406943, 
+1.56119995998691, 0, 0, 0, 0, 0, 0, 0.915847593483214, 0.836178187324251, 
+0.875480130812127, 1.04332674785114, 1.30606534444417, 1.59982787176808, 
+1.85833499845374, 2.04086468873261, 2.14802588501659, 2.22124836777596, 
+2.32801635511758, 2.53592940752266, 2.87944091474338, 3.32909590659129, 
+3.78127729870511, 4.08506749972566, 4.10379415256363, 3.78185336753706, 
+3.17637374494268, 2.43287500555873, 1.72107155818744, 1.17076414429705, 
+0.840588188079475, 0.72505655214225, 0.782638398039884, 0.963599267521557, 
+1.22626441339956, 1.54170030578401, 1.89201579739259, 2.26696334976238, 
+2.66100738159669, 3.07117041737781, 3.49532733412199, 3.93069437616132, 
+4.37251379082112, 4.81311646953738, 5.24159839168944, 5.64425894952087, 
+6.00571113154896, 6.31026924221787, 6.54309629105133, 6.69087657669489, 
+6.74229376488013, 6.6887408728011, 6.52514406252388, 6.25019178285313, 
+5.86570934984937, 5.37637703463917, 4.79176790447123, 4.13124097277968, 
+3.42930154841628, 2.73724520476704, 2.11821535980161, 1.63660232929412, 
+1.34607659103837, 1.28045981934670, 1.44764883334241, 1.82300341445903, 
+2.34171244382718, 2.89992350191968, 3.3781526383509, 3.68364261009139, 
+3.78353529376821, 3.70155861445238, 3.48457317695637, 3.17341483169433, 
+2.80105752002886, 2.40749067506522, 2.04615779488076, 1.77198432394136, 
+1.62185467835522, 1.60322642431847, 1.69687763630723, 1.86898490450481, 
+2.08416487647675, 2.31393362349772, 2.53952899506404, 2.75086226826116, 
+2.94392521474323, 3.11824870798495, 1.04698870124727, 1.13302591180298, 
+1.22179279190668, 1.30802470296969, 1.38653678222321, 1.45315414868666, 
+1.50545649829038, 1.54314808464400, 1.56797825694887, 1.58325629897395, 
+1.59305535739375, 1.60114856913319, 1.60961659810622, 0, 0, 0, 
+0, 0, 0, 0, 0, 0.81691646749394, 0.867125300745832, 1.06128177128617, 
+1.35988257768077, 1.68951397339454, 1.97448497955243, 2.16845745132994, 
+2.27202631803578, 2.33168781075535, 2.42284394184180, 2.62091209999590, 
+2.96522795905121, 3.42629756241166, 3.89521364154706, 4.2124161656575, 
+4.23296354613966, 3.89720643703607, 3.26426960091667, 2.48644635383678, 
+1.74157674767460, 1.16551106082893, 0.819179027180778, 0.695990753155584, 
+0.75139246948324, 0.932172577397676, 1.19358073071636, 1.50426052920568, 
+1.84448284332969, 2.20262009069874, 2.57215357606824, 2.94954499328021, 
+3.33261809474438, 3.71916167562529, 4.10571197600133, 4.48663879076049, 
+4.85369981623029, 5.19616183053425, 5.50143883339176, 5.75602686729301, 
+5.9464551535049, 6.0601320482048, 6.08622711336624, 6.01675634857708, 
+5.84766706022691, 5.5793693166554, 5.21648480606116, 4.76753249734669, 
+4.24580282314573, 3.67182507608913, 3.07601097925181, 2.49889834633584, 
+1.98726553989541, 1.5869197986809, 1.33521914606134, 1.25612577941662, 
+1.35734387230074, 1.62599999458328, 2.02177020221556, 2.4747138105083, 
+2.89875488006732, 3.21978978640451, 3.39908688355389, 3.43302494959382, 
+3.33424684601163, 3.11813968400205, 2.80797251378519, 2.44698704747002, 
+2.09779480929386, 1.82456958601457, 1.67081156251671, 1.64764684741713, 
+1.73734479132087, 1.90635779973579, 2.11910753107059, 2.34686295539809, 
+2.57070788873595, 2.78048174931621, 2.97212921515105, 3.14511870004991, 
+1.07488233402268, 1.17030687045977, 1.26875038845306, 1.36420104678364, 
+1.45068622401101, 1.52334886742425, 1.5793545116302, 1.61839580979482, 
+1.64266533324465, 1.65629750065933, 1.66436886814943, 1.67154218303007, 
+0, 0, 0, 0, 0, 0, 0, 0, 0, 0.859988926328235, 0.925387645432164, 
+1.14571378157589, 1.47581342112195, 1.83384838008954, 2.1361120403578, 
+2.33163001235434, 2.42110196592037, 2.45524539856815, 2.51582174010639, 
+2.68445471255491, 3.00477213172692, 3.44883593178079, 3.90673049854943, 
+4.21631183063711, 4.22989168356035, 3.88617155301026, 3.2442822533598, 
+2.45783834117892, 1.70638443567208, 1.12692378908942, 0.780509371398886, 
+0.659702823351634, 0.718496349117792, 0.9020081073232, 1.16385755570947, 
+1.47121450837058, 1.80307376959759, 2.14675786597573, 2.49497171626316, 
+2.84374669331355, 3.19091299455228, 3.53479653522567, 3.87307431254636, 
+4.2018756273931, 4.51524726296719, 4.80504711380782, 5.06123645568000, 
+5.2724558151044, 5.42676050042888, 5.51249437202479, 5.51940221771552, 
+5.44002264525108, 5.27109890601879, 5.0144804236469, 4.67718291527662, 
+4.27091814387309, 3.8118625830857, 3.3210717114422, 2.82492775611449, 
+2.35430162974645, 1.94159241695243, 1.61634970510073, 1.4015304432725, 
+1.31202473176993, 1.35451811405628, 1.52532890180802, 1.80463870786004, 
+2.15197834004424, 2.51133629491611, 2.8267262644497, 3.05668703867201, 
+3.17624594293406, 3.17035656642909, 3.03349663987821, 2.78042638937409, 
+2.45575336694569, 2.12764802490539, 1.86578134979490, 1.71749999905522, 
+1.69622209978043, 1.78553685769358, 1.95272359282419, 2.16280027422348, 
+2.38750286356452, 2.60826803791570, 2.81516136192555, 3.00422340300394, 
+3.17490815514169, 1.10381703385098, 1.20852101478370, 1.31655895366297, 
+1.42124541840417, 1.51591497159556, 1.59512964508367, 1.65572359371210, 
+1.69741251796481, 1.72279361400564, 1.73670819100034, 1.74506637690714, 
+0, 0, 0, 0, 0, 0, 1.58913223619438, 1.41598580635647, 0, 0, 0, 
+1.05925270670365, 1.30399724473805, 1.65876206107144, 2.03498685710559, 
+2.34294928940853, 2.5284247028218, 2.59243961947721, 2.58892076466361, 
+2.60411397348901, 2.7239117871326, 2.9954225156128, 3.39380705770754, 
+3.81254480068033, 4.09319738622028, 4.09107973534012, 3.74575018104702, 
+3.11429412472072, 2.34599761313982, 1.61545190923992, 1.05573713201989, 
+0.725783429075148, 0.617577325805072, 0.685296595311754, 0.874276045471402, 
+1.13801459150929, 1.44319834524063, 1.76812814386961, 2.09941166780816, 
+2.42917935805868, 2.75315378304392, 3.06922240301793, 3.37621589099452, 
+3.67281862841475, 3.95667819631171, 4.22380357634307, 4.46829496713612, 
+4.68238567601624, 4.85674315443798, 4.98100425324561, 5.04460155967666, 
+5.03798725563302, 4.9542488933575, 4.79081835849201, 4.55071524650956, 
+4.24284502913428, 3.88133186127395, 3.48433190076046, 3.07279612182018, 
+2.66921594808487, 2.29599474279330, 1.9732859808457, 1.71691514719209, 
+1.53762662129107, 1.44235879801677, 1.43627176974171, 1.52240752253846, 
+1.69706257147505, 1.94371483086022, 2.23161503426386, 2.52125760340776, 
+2.77150663783849, 2.94297735906016, 3.00081056505363, 2.92413923044157, 
+2.72079671722104, 2.43476422239831, 2.13588014014083, 1.89531933285732, 
+1.76136131097607, 1.74826635091782, 1.84073166298714, 2.00738559330348, 
+2.21460928602487, 2.43529942720185, 2.65173708957056, 2.85450211587011, 
+3.03986921048686, 3.20732533533317, 1.13272223312905, 1.24632293455985, 
+1.36358966899601, 1.47724946083230, 1.58005075000077, 1.66608872427905, 
+1.73196718078598, 1.77748593064693, 1.80563656441920, 1.82186428430149, 
+0, 0, 0, 0, 0, 0, 1.82818274792173, 1.72016401595309, 1.55700193551130, 
+1.36868976861155, 0, 0, 0, 1.53597772554033, 1.90652038010271, 
+2.28879729360916, 2.58949630434193, 2.75280829160933, 2.78039345977335, 
+2.72830941004451, 2.68528190015393, 2.73940138154712, 2.94029224481665, 
+3.26751165421069, 3.62194296080942, 3.85464596586699, 3.82925217272897, 
+3.48850329820454, 2.88556260501965, 2.16019138272887, 1.47590045361875, 
+0.95717773124494, 0.65877166581228, 0.572360077705241, 0.653835610052532, 
+0.85050967163483, 1.11717347627125, 1.42096130239861, 1.74003134534842, 
+2.06059400838958, 2.37439379202220, 2.67695382320466, 2.96626084636526, 
+3.24161781556638, 3.50259770530758, 3.74815701729101, 3.97598286572712, 
+4.18210424208891, 4.36075396658593, 4.50446462788384, 4.60443402299454, 
+4.65127275375803, 4.63626288703977, 4.5531137158434, 4.39989760941735, 
+4.18056056977183, 3.9053845573589, 3.59012602149661, 3.25406002823669, 
+2.91747866220481, 2.5991759676545, 2.31428090153480, 2.07277699111193, 
+1.87924141228758, 1.73440438482568, 1.63850419670026, 1.5949200855714, 
+1.61121794429414, 1.69551117374148, 1.84946241051312, 2.06225374677320, 
+2.30865166050146, 2.55055388604577, 2.74106308917444, 2.83352556384665, 
+2.79745406797097, 2.63546264693904, 2.38905259253247, 2.12603127237674, 
+1.91530178534082, 1.80333911765207, 1.80388271163292, 1.90252165188919, 
+2.06969163634698, 2.27381927211465, 2.48957817820306, 2.70052759208614, 
+2.89801328975798, 3.07866320134031, 3.24203739251773, 1.16047268182674, 
+1.28231270322883, 1.4081653948512, 1.53027180036267, 1.64091679830306, 
+1.73386207323319, 1.80561094102969, 1.8561470204207, 1.88887360650809, 
+0, 0, 0, 0, 0, 0, 2.01418402420495, 1.97624829064800, 1.88429332146759, 
+1.74071683852030, 1.57565607668087, 0, 0, 0, 1.83317610261374, 
+2.20917224394844, 2.58449486166266, 2.86486217669856, 2.99465770613541, 
+2.97652371644275, 2.86759278060010, 2.75711638453790, 2.73336636045576, 
+2.84744219422562, 3.08419094421777, 3.35507215725952, 3.52530950966963, 
+3.47115320328226, 3.14042553627108, 2.58087208424029, 1.91855345224886, 
+1.30097184626700, 0.840271230334566, 0.585374590846591, 0.527887622155729, 
+0.626679012147843, 0.832489312112698, 1.10257752089357, 1.40531312469854, 
+1.71918780033912, 2.03029545585425, 2.33016276382057, 2.61420843496804, 
+2.88055056744862, 3.12892949038351, 3.35969784384671, 3.57293671785234, 
+3.76776421208188, 3.94186102690868, 4.09120402558669, 4.21001221043862, 
+4.29097605444281, 4.32591917657511, 4.30704428959211, 4.22875710043187, 
+4.08974523390393, 3.89466620166816, 3.65470572080841, 3.38654492531177, 
+3.10982300742053, 2.84371874449599, 2.60355302706262, 2.39829274084098, 
+2.22964599656710, 2.09320019655252, 1.98170753505404, 1.88993629468463, 
+1.81939886972948, 1.78033608030089, 1.78883517476457, 1.85940534877062, 
+1.99605318128625, 2.18547832946248, 2.39478422166905, 2.57564192534864, 
+2.6767961741364, 2.66332683367458, 2.53425155373529, 2.32707536404968, 
+2.10445345286167, 1.92983436474716, 1.84558890843558, 1.86378911776330, 
+1.97072235947375, 2.13899429322787, 2.33962223127864, 2.54954626345937, 
+2.75394380164527, 2.9451195256032, 3.12014276090564, 3.27867437111918, 
+1.18595047135674, 1.31511065825414, 1.44864681779150, 1.57843303827926, 
+1.69643347083971, 1.79624008561057, 1.87443825326451, 1.93136601543285, 
+0, 0, 0, 0, 0, 0, 2.15144608160418, 2.16785899957252, 2.14820253853788, 
+2.07882004428627, 1.96271667087556, 1.82926638892322, 1.73348908286837, 
+0, 0, 0, 2.54982295880739, 2.90541488482461, 3.15352329687586, 
+3.24043237613358, 3.17009607183148, 2.99974886426401, 2.81740345559856, 
+2.70969959801621, 2.72816397847552, 2.86332985971484, 3.03927896800437, 
+3.13851951428038, 3.05282821077945, 2.73641011421366, 2.23061882110381, 
+1.64504013412787, 1.10788737008959, 0.716468790280311, 0.512806000269353, 
+0.488623369603515, 0.60665191459664, 0.82208438674549, 1.09549046658595, 
+1.39705821044548, 1.70598346089853, 2.00847460191902, 2.29598371206182, 
+2.56390483545322, 2.8105093472821, 3.03593638340988, 3.2412156599455, 
+3.42738749676315, 3.59478404302079, 3.74249423233591, 3.8680071662102, 
+3.96705070318566, 4.03371567002569, 4.06103561038481, 4.04219082045169, 
+3.97234165321069, 3.85077014853933, 3.68265790155845, 3.47968141934326, 
+3.25883838660123, 3.03950057885107, 2.83937676540556, 2.67054750625636, 
+2.53680934213301, 2.43325180583861, 2.34844118940113, 2.26893998786809, 
+2.18516611111501, 2.09678572660448, 2.01524643982469, 1.96142924738289, 
+1.95818318054281, 2.01993211659863, 2.14312681804187, 2.30160260188047, 
+2.4503770832384, 2.53935243399608, 2.53338289364685, 2.42929154999747, 
+2.25953243925632, 2.07931202733739, 1.94427691908829, 1.89100205875764, 
+1.92904601158496, 2.04523934393604, 2.21460125997096, 2.41111114475552, 
+2.61430439073402, 2.8111982755683, 2.99517584889536, 3.1637975036378, 
+3.31683700654693, 1.20811063964749, 1.34343611054927, 1.48352257051535, 
+1.62001447179709, 1.74472404169159, 1.85128780450055, 0, 0, 0, 
+0, 0, 0, 0, 2.25610851203507, 2.30456781263028, 2.33881140971639, 
+2.34122637984402, 2.29910136927369, 2.21573094371425, 2.11890438431439, 
+2.05945474842546, 2.09494824937105, 0, 0, 0, 3.23085001614218, 
+3.43693271846854, 3.47448795653554, 3.34902735700967, 3.11702236962071, 
+2.86375195333720, 2.67270206297544, 2.59482500609754, 2.62622289095952, 
+2.70442325756072, 2.73064634307501, 2.61357143475623, 2.31443496760008, 
+1.86779887676710, 1.36554349466498, 0.915126777142455, 0.597915673658236, 
+0.448577993970889, 0.459094835268186, 0.596530133416168, 0.821075779667278, 
+1.09708573932872, 1.39692330789751, 1.70074174564101, 1.99504000482028, 
+2.27131258069640, 2.52499367503291, 2.75452039344010, 2.9603882619978, 
+3.14420568951296, 3.30782125493992, 3.45258834864133, 3.57878975055936, 
+3.68522007563787, 3.76894981696584, 3.82537057286111, 3.84870060595031, 
+3.83312820316907, 3.77460717037644, 3.67299051428576, 3.53382069757677, 
+3.36891350158564, 3.19507503161619, 3.03089436455697, 2.89233678433220, 
+2.78846749367076, 2.71877045640911, 2.67312552894624, 2.6347446672627, 
+2.58552063267218, 2.51249767926561, 2.41358853397694, 2.30035601024567, 
+2.19602761519184, 2.12827746375067, 2.11843893406658, 2.17081927974661, 
+2.26683709461991, 2.36814661873962, 2.42988927325365, 2.41973767887059, 
+2.3334382677585, 2.1978440966363, 2.05933648360871, 1.96434499586503, 
+1.94263432220751, 2.00073852574286, 2.12592085823554, 2.29572799126509, 
+2.48728263585603, 2.68286896858281, 2.87143736413667, 3.04748950901527, 
+3.20908548219699, 3.35610768063108, 1.22604506057333, 1.36618376375796, 
+1.51149646899304, 1.65355354641900, 1.78421819221163, 0, 0, 0, 
+0, 0, 0, 0, 2.34789685662057, 2.40845413416048, 2.47159455942912, 
+2.52496139211373, 2.55155656496459, 2.53909369520177, 2.49059728757422, 
+2.43155284246791, 2.40768225020221, 2.46948798159920, 0, 0, 0, 
+3.53862790656612, 3.69571964862813, 3.68083836417071, 3.50116054516308, 
+3.21163213829372, 2.89359183302795, 2.62616721611798, 2.45881418270592, 
+2.39262949090085, 2.3782798814911, 2.33554799706293, 2.18996274470457, 
+1.90983237280123, 1.52306842303713, 1.10406243944429, 0.739750171634011, 
+0.495749881858436, 0.399506344069225, 0.443344558959055, 0.598740635461294, 
+0.830984311298498, 1.10833924712990, 1.40548630030094, 1.70367792390586, 
+1.98982753210891, 2.25556440451787, 2.49641424251601, 2.71098419981336, 
+2.90008058148339, 3.06579545108281, 3.21064608412376, 3.3368336581044, 
+3.44564476698143, 3.53699626747860, 3.60915052859866, 3.65870287991286, 
+3.68102082351696, 3.67131340106537, 3.62635058298124, 3.54652923252766, 
+3.43761047028734, 3.31125367573521, 3.18365479363746, 3.07220547462993, 
+2.99092102908619, 2.94605959441686, 2.93352069821074, 2.93915247915308, 
+2.94220024476678, 2.92115701161484, 2.86053175900124, 2.75663524714938, 
+2.62040230265254, 2.47565919754716, 2.35235539647253, 2.27611572902241, 
+2.25751268133508, 2.28576694832718, 2.33102843506127, 2.35613328098747, 
+2.33347911679211, 2.25856455726405, 2.15256798552461, 2.05255193639809, 
+1.9952128903169, 2.00314599753532, 2.07967446787523, 2.21242684136470, 
+2.38146506925647, 2.56705178813062, 2.75420362719664, 2.93377357033393, 
+3.10134663493129, 3.2554526412217, 3.39606347133714, 1.23903912121117, 
+1.38249131269775, 1.53156446701519, 1.67792781627440, 0, 0, 0, 
+0, 0, 0, 2.37558064060418, 2.44436689354214, 2.50873926007134, 
+2.57734105000107, 2.65242379262148, 2.72396788656705, 2.77483241507891, 
+2.79202633007052, 2.77741333966449, 2.75353108568906, 2.7605234457676, 
+2.8416420119923, 3.0208696560738, 0, 0, 0, 3.91207927758807, 
+3.84506437763035, 3.61566723194194, 3.27662405486756, 2.90438724617906, 
+2.57281359890838, 2.3290360976616, 2.17822678137015, 2.08299063422304, 
+1.98026459945442, 1.81123195549146, 1.55082885982748, 1.2208956190649, 
+0.879716887738974, 0.595306331979489, 0.418769654631335, 0.370927418846663, 
+0.444493544282463, 0.615119260895567, 0.852928467641754, 1.12993777245864, 
+1.42311336620650, 1.71485702721190, 1.99257692882189, 2.24810859326581, 
+2.47710924276053, 2.67835397636956, 2.85291227474585, 3.00326826667825, 
+3.1324781816075, 3.24343354064689, 3.33825490148798, 3.41781844730609, 
+3.48144313316361, 3.52683737457090, 3.55047851625861, 3.54859769363507, 
+3.51879161662979, 3.46197123667605, 3.38399295111442, 3.29611356696794, 
+3.21357847103744, 3.15225316105981, 3.12405164835344, 3.13261532252379, 
+3.17087221251100, 3.22161501778013, 3.26126807530427, 3.26597905445538, 
+3.21844207421044, 3.11357039717430, 2.96123026587739, 2.78470152775824, 
+2.61448594389697, 2.47864116439284, 2.39267284379267, 2.35328674026335, 
+2.33977229945632, 2.32373005447298, 2.28321268344814, 2.21404157464721, 
+2.13204274449874, 2.06521527069588, 2.0407754002183, 2.07435270493022, 
+2.16615325656306, 2.30414046780150, 2.47076976958298, 2.64928019857049, 
+2.82725783486654, 2.99732172966528, 3.15604101124509, 3.30235350404580, 
+3.43628994501087, 1.24661611499534, 1.39179213671918, 1.54307424172695, 
+0, 0, 0, 0, 0, 0, 2.43060842126561, 2.54237249483591, 2.63024833964687, 
+2.69890941290796, 2.76714144462936, 2.84740751009105, 2.9333628480457, 
+3.00643340627799, 3.05105829361992, 3.06663280466995, 3.07211920444284, 
+3.10200531795, 3.19271331889607, 3.362816040078, 3.59646762917577, 
+0, 0, 0, 3.95602813629378, 3.68433378704683, 3.30672322120981, 
+2.89402542326643, 2.51415333603156, 2.21119166855654, 1.99326343734887, 
+1.83312934868986, 1.68264151616750, 1.49668531171301, 1.25606097455875, 
+0.977410936433074, 0.705073415315327, 0.490652503607115, 0.3726733705991, 
+0.366242537884173, 0.464478173035092, 0.646756393582717, 0.887527138594408, 
+1.16221195493624, 1.44991052148943, 1.73415985423387, 2.00291134841989, 
+2.24826211170257, 2.46603201507261, 2.65515739643772, 2.81692277379015, 
+2.95411690466575, 3.0702144739631, 3.16865379173592, 3.25223637194869, 
+3.32265162033971, 3.38015282538813, 3.42347679573661, 3.45016881417882, 
+3.45747430365819, 3.4438171971261, 3.41059109544556, 3.36364217678308, 
+3.31362398699383, 3.27456159269035, 3.2605425831304, 3.28127816805857, 
+3.33797006692024, 3.42109133616192, 3.51118546648375, 3.58279748225431, 
+3.61060329287770, 3.57610505423249, 3.47306754052286, 3.31009256323332, 
+3.10924546864765, 2.90050156805307, 2.71307869610434, 2.56628393903703, 
+2.46358562581604, 2.39313401835895, 2.33530717421169, 2.27399040375227, 
+2.20568721950417, 2.14148044362069, 2.10112150936363, 2.10318092279693, 
+2.15695554667143, 2.25984236239613, 2.40013789612733, 2.56248563412111, 
+2.73281547739397, 2.90100891705192, 3.06123527352589, 3.21090193438083, 
+3.34927089972272, 3.47639424058882, 1.24856530173493, 1.39384819316798, 
+0, 0, 0, 0, 0, 0, 2.41819411523256, 2.59777130642435, 2.7567185519997, 
+2.86513147984249, 2.92852500415571, 2.98265142049340, 3.05686560052103, 
+3.1504889786602, 3.2417121396971, 3.30979107320048, 3.34990577481436, 
+3.37677519958257, 3.41942873702670, 3.5083315627451, 3.65797351069995, 
+3.85271982266417, 0, 0, 0, 4.007093672664, 3.7025015391757, 3.29901939373993, 
+2.86127284730575, 2.45074073164693, 2.10783817275225, 1.84245188969289, 
+1.63545452101794, 1.45098207452119, 1.25530784147137, 1.03417868531941, 
+0.800053756191255, 0.585859332504032, 0.42974064283669, 0.359908028759545, 
+0.386812262300497, 0.503974411126009, 0.693939455739319, 0.934853627055834, 
+1.20509874496898, 1.48569362645017, 1.76126063304262, 2.02032306415148, 
+2.25528359349319, 2.46214924893792, 2.64000798219648, 2.79031214266137, 
+2.91607281156416, 3.02107191851490, 3.10916366862723, 3.18369185760342, 
+3.24702644914452, 3.30024234475556, 3.34302307732855, 3.37393548274495, 
+3.39122131776857, 3.39412192162006, 3.38448067878475, 3.36804591506348, 
+3.35471139344925, 3.35707968699715, 3.38728238679617, 3.45277645656877, 
+3.55249620645451, 3.67489914944607, 3.79894447591149, 3.89806790394557, 
+3.94619400389797, 3.9241712628075, 3.82489394376102, 3.6556847256857, 
+3.43707534556907, 3.19790021684427, 2.96768524257795, 2.76856019292168, 
+2.60977070252456, 2.4874308694533, 2.38999328011322, 2.30683392472665, 
+2.23533581345614, 2.18261792169177, 2.16135563743933, 2.18268329549423, 
+2.25047675977652, 2.3597724406411, 2.49921817826900, 2.65538723697543, 
+2.81653760622159, 2.97450283377708, 3.12473866714307, 3.26531820069744, 
+3.39573267870688, 3.51601611227033, 1.2449510949895, 0, 0, 0, 
+0, 0, 0, 2.31877747181360, 2.55084585109469, 2.80833448869359, 
+3.02929729686779, 3.15896040672430, 3.20428289247598, 3.22641672531111, 
+3.27986866984907, 3.37214302074471, 3.47605982429608, 3.56256010020446, 
+3.62054739521273, 3.65977952285755, 3.7041803454781, 3.77939621530557, 
+3.89740574913533, 4.04435529505723, 4.17905109559009, 0, 0, 0, 
+3.66949889339742, 3.25334363040277, 2.80615975372559, 2.38264213361332, 
+2.01902487876089, 1.72583035069756, 1.49001085173346, 1.28533599837908, 
+1.08712593126027, 0.885141371675876, 0.688678137370672, 0.521807461035736, 
+0.412193878879833, 0.380018890060422, 0.432142670980614, 0.562482154738458, 
+0.756181810512439, 0.994438459794531, 1.25813413037513, 1.52997879692287, 
+1.79561860253198, 2.04416773214968, 2.26837091071543, 2.46444202821530, 
+2.63160950406052, 2.77144855090943, 2.88711640423451, 2.98260065428365, 
+3.06205251915758, 3.12923194458304, 3.18706739104822, 3.23734864047664, 
+3.28062353217357, 3.31642609256387, 3.34396355340408, 3.36327289038583, 
+3.37661251973715, 3.38956346404198, 3.41114763423052, 3.45241031205621, 
+3.52342286889907, 3.62938988315687, 3.76715524019138, 3.92354079582932, 
+4.07646899151008, 4.19888987740432, 4.26456325590382, 4.25414232936117, 
+4.15993644465779, 3.98809303836819, 3.75752527912844, 3.49562352749531, 
+3.2316566977389, 2.98972379035988, 2.78373564014786, 2.61652823940039, 
+2.48351228821768, 2.37890062550632, 2.30103503282786, 2.25391263461343, 
+2.2444692072627, 2.27779224768849, 2.35338367218992, 2.46443725431281, 
+2.59998236025051, 2.74824163246063, 2.89940567576053, 3.04688890518693, 
+3.18715256019502, 3.31875582467781, 3.44132381917822, 3.55483591674010, 
+0, 0, 0, 0, 0, 0, 2.15489970590758, 2.39081310549088, 2.70536239050772, 
+3.06090377551620, 3.35795956294746, 3.50897440518838, 3.52297505081532, 
+3.49485470341704, 3.51245175323197, 3.59397755823822, 3.70480841404044, 
+3.80449022030639, 3.873613293625, 3.9162838016825, 3.95173549867233, 
+4.00202500133583, 4.07825614238096, 4.16989339296694, 4.24318720787045, 
+4.25135957634614, 0, 0, 0, 3.17225638684078, 2.73017172866809, 
+2.30993363850969, 1.94320406748616, 1.64016164728746, 1.39201138625677, 
+1.17975080823682, 0.985614424206795, 0.8025231631086, 0.637532847885169, 
+0.508182716659592, 0.434364441369483, 0.430310037901873, 0.500258716036647, 
+0.63851807622943, 0.832315555040257, 1.06531253191588, 1.32047370033431, 
+1.58199314447030, 1.83648436200484, 2.0736685340943, 2.28666395635014, 
+2.47190749946052, 2.62875642069685, 2.7588671134083, 2.86547380412696, 
+2.95267819454637, 3.02482133384418, 3.0859645345613, 3.13948119527874, 
+3.18777236391576, 3.23216367810119, 3.27309063424794, 3.31067927201531, 
+3.34572652678189, 3.38086839897939, 3.42146738918477, 3.47560620802839, 
+3.55270554116043, 3.66074686442612, 3.80274081265035, 3.97363091380934, 
+4.15893836037867, 4.33599842838345, 4.47777238419762, 4.55832138912471, 
+4.55848161148757, 4.47024800846079, 4.29875988683818, 4.06136748756696, 
+3.78390747897819, 3.49501707425565, 3.22002482595880, 2.97638274496369, 
+2.77228129909174, 2.60880042454835, 2.48419006422399, 2.39774760134698, 
+2.35116558412482, 2.34698391725088, 2.38564914090003, 2.46335043303097, 
+2.57196584870496, 2.70094187243720, 2.83987470665108, 2.98049811821300, 
+3.11744443498035, 3.24790922524557, 3.37076801120264, 3.48569302136469, 
+3.59257900027179, 0, 0, 0, 0, 0, 1.96510614229525, 2.16942873207622, 
+2.46280470152225, 2.87093302981427, 3.33763845491763, 3.71985841195565, 
+3.89201955996671, 3.8656092079168, 3.77475026536904, 3.74600362628862, 
+3.80993827792461, 3.92305779597308, 4.03135851021596, 4.10563873491944, 
+4.14385710300896, 4.16098935517456, 4.17668454579957, 4.20272383323769, 
+4.23329174013053, 4.2429180806114, 4.19454052733131, 0, 0, 0, 
+3.06065031214002, 2.63618381206430, 2.23306592381181, 1.8781284990826, 
+1.58042843272462, 1.33390934270248, 1.12478018673622, 0.940394008315007, 
+0.776105981994396, 0.637496821658005, 0.537514653805246, 0.490544793255309, 
+0.506612515848655, 0.588151344607697, 0.729859942842646, 0.920622062654355, 
+1.14607947867995, 1.39093655089365, 1.64070410028482, 1.88292047271246, 
+2.10793042001900, 2.30925350613365, 2.48356273726449, 2.63033277275432, 
+2.75126354577641, 2.84960477071336, 2.92949108748288, 2.99535775748613, 
+3.05146331679129, 3.10151975726206, 3.14843711414796, 3.1942261370379, 
+3.2401446022253, 3.28717307000321, 3.33681757410609, 3.39205077497573, 
+3.4579829735831, 3.54173388500537, 3.6510979911925, 3.79201022130004, 
+3.96540309783438, 4.16452844429218, 4.37390824581615, 4.57065809261371, 
+4.72813692459467, 4.82106392634924, 4.83075555117925, 4.74912859131509, 
+4.58050067337631, 4.34078528062473, 4.05426525912366, 3.74869638275875, 
+3.45000764026545, 3.17814193689904, 2.94530956246004, 2.75697134059101, 
+2.61458888613107, 2.51835699848749, 2.46839430296415, 2.46408142618946, 
+2.50252613540869, 2.57759000024291, 2.68032584311639, 2.80063312452758, 
+2.92923049119615, 3.05904075064743, 3.18558675791509, 3.30655731470082, 
+3.42099705265026, 3.52855370291116, 3.62901647669827, 0, 0, 0, 
+0, 1.77244922681495, 1.94359970066235, 2.17435363713948, 2.52460626678491, 
+3.02565009375498, 3.60282356621945, 4.06970043177021, 4.26286776359110, 
+4.1961567218787, 4.04254961855753, 3.9669779498333, 4.01216789613556, 
+4.12557411215034, 4.23934601800604, 4.31414771842082, 4.34169391885483, 
+4.33314815465628, 4.30679707310553, 4.27645971817758, 4.24222999890118, 
+4.18753563607219, 4.0849828395871, 3.90876804178728, 0, 0, 0, 
+2.52814598084648, 2.15301131862877, 1.82153524313441, 1.54109509184299, 
+1.3072045346518, 1.10969925072650, 0.939628180391214, 0.79419349647664, 
+0.678082935892959, 0.601160465165412, 0.574071901603192, 0.603997806084035, 
+0.69220674997142, 0.833795014777213, 1.01897728925256, 1.23500633057837, 
+1.46806706349688, 1.70486432452605, 1.93383459535406, 2.14596362264024, 
+2.33519612783253, 2.49845159166775, 2.63531120363672, 2.74748531143051, 
+2.83818568113983, 2.91150929674246, 2.97190150957415, 3.02372425215154, 
+3.07092847630907, 3.11683170539890, 3.16403046986294, 3.21451190805152, 
+3.27002915913330, 3.33273130182279, 3.40588278105038, 3.49432389992020, 
+3.60422769509665, 3.74182144749493, 3.91110453897710, 4.11110144082727, 
+4.33360127366316, 4.56240286010961, 4.77470094026124, 4.94454327889799, 
+5.04756569962799, 5.06578333141435, 4.99122424271838, 4.82755965237284, 
+4.5894149877291, 4.29957267669513, 3.98473974877174, 3.67092494635606, 
+3.37963969114084, 3.1259121379487, 2.91840608806161, 2.76102165324091, 
+2.65475827376112, 2.59876869971583, 2.59033354202060, 2.62434512058174, 
+2.69318929233023, 2.78751851551428, 2.89771772549129, 3.01541416037564, 
+3.13441940329611, 3.25087229609419, 3.36275656333311, 3.46916897940182, 
+3.56968009734216, 3.66396289281138, 0, 0, 0, 1.58470883618565, 
+1.73502766441058, 1.91293748271447, 2.16544683257109, 2.56279486334244, 
+3.14071030794898, 3.80962124506377, 4.34822143472737, 4.5625616679788, 
+4.46801453198972, 4.26831134239462, 4.15880707713804, 4.19171357318822, 
+4.30688595677406, 4.42476880035141, 4.49705839511362, 4.50967433307981, 
+4.47044307900645, 4.3971506361736, 4.30675574453578, 4.20618317953089, 
+4.08813920853112, 3.93466889864969, 3.72704295875385, 3.45666894480143, 
+0, 0, 0, 2.07119345927457, 1.77153447615679, 1.51696945227641, 
+1.30373832209976, 1.12412172397465, 0.971788558414307, 0.84532620851451, 
+0.748933935238174, 0.690484264697459, 0.678174931411305, 0.717341715064971, 
+0.808562478853373, 0.947342251813863, 1.12499555121899, 1.33012327782522, 
+1.55020887240436, 1.77306835145094, 1.98802249249218, 2.18671472401152, 
+2.36353430355025, 2.51565455685885, 2.64275303480229, 2.74652211509233, 
+2.83009040977700, 2.89745726584049, 2.95300543293126, 3.00111668580166, 
+3.04588818196336, 3.0909447941045, 3.13936399280101, 3.19375729885602, 
+3.25655272678010, 3.33046259982005, 3.41899429843264, 3.52671360829156, 
+3.6588974593937, 3.82031683572445, 4.01320455905818, 4.23489384431806, 
+4.47595838785879, 4.71972970936481, 4.94372373201054, 5.12288798436222, 
+5.23394880968571, 5.25976584826393, 5.19261651848062, 5.03567216853659, 
+4.80241207716812, 4.51419053256754, 4.19655349565783, 3.87517187638026, 
+3.57235651203448, 3.30493488999421, 3.08376397042768, 2.91450441882712, 
+2.79884787394118, 2.73545344532717, 2.72035274358822, 2.74713253033366, 
+2.80739463046763, 2.89173615357247, 2.99105436225786, 3.09771388920992, 
+3.20617693777928, 3.31298428740456, 3.41626448554906, 3.51508274826301, 
+3.60889977955296, 3.69727166427682, 0, 0, 1.40762850517197, 1.54356551208450, 
+1.69184062105183, 1.8731953670748, 2.13897022493002, 2.56499922078711, 
+3.18930796011415, 3.91429815709294, 4.50000495051887, 4.7359189632402, 
+4.63751260733886, 4.42391051723218, 4.30583069472527, 4.33998243423948, 
+4.46159729941088, 4.58386050158338, 4.65211122168397, 4.64746249937767, 
+4.57491313819493, 4.45241172893453, 4.30086310124321, 4.13463683569654, 
+3.95583914784051, 3.75554805686767, 3.52141052758602, 3.24706978452943, 
+0, 0, 0, 1.98926544665286, 1.72672626326508, 1.50364941129365, 
+1.31643121693145, 1.15895130047359, 1.02670983981757, 0.919318892883576, 
+0.840740438080126, 0.797596361491718, 0.796524857007629, 0.841709965392032, 
+0.933371164639679, 1.06743530404756, 1.23616251375303, 1.42932555000198, 
+1.63558552166351, 1.84381662366256, 2.04421756417642, 2.22910289706122, 
+2.39332030253168, 2.53430107868726, 2.65180966256681, 2.74749683820238, 
+2.82437102693737, 2.88628442542472, 2.93749580103737, 2.98233361193315, 
+3.02495599808626, 3.06919786732236, 3.11850971285308, 3.17601367169845, 
+3.24470271999271, 3.32776162479576, 3.42888834359992, 3.55237961749726, 
+3.70269327697016, 3.88329507548647, 4.09486493876461, 4.33329713894825, 
+4.58821014935076, 4.84270664801166, 5.07481954142049, 5.26054212545999, 
+5.37779567929201, 5.41036819680875, 5.35087569738822, 5.20210074949845, 
+4.97649669847743, 4.69406139213703, 4.3791044158219, 4.05663461616103, 
+3.74914895739608, 3.47445266574726, 3.24477267635244, 3.06696422013101, 
+2.94328978443445, 2.87225556851223, 2.84928663597351, 2.86735808637113, 
+2.91781627508257, 2.99146594492362, 3.07973671498197, 3.17560163018607, 
+3.27399728079993, 3.37171249340596, 3.46691809257337, 3.55859634057817, 
+3.6460842941179, 3.72882937020616, 1.13862439837727, 1.24886650514417, 
+1.36948426978059, 1.49964412963501, 1.64438996768607, 1.82517052719911, 
+2.09350010878334, 2.5247872389276, 3.15666083030701, 3.89225552970043, 
+4.49355225877902, 4.7512440155177, 4.67912065116954, 4.49227214427259, 
+4.39772056850018, 4.4504005229523, 4.58479882844077, 4.7126502454617, 
+4.77643622746442, 4.75380896887505, 4.64746264417377, 4.47597619611878, 
+4.26469412878976, 4.0357064359194, 3.80035946397417, 3.55818295357547, 
+3.30244306870974, 3.02840488196622, 2.73916485990489, 0, 0, 0, 
+1.68613205732468, 1.49764140040155, 1.33955628661032, 1.20676675017779, 
+1.09603487279523, 1.00771312839694, 0.94565792284478, 0.915708967998724, 
+0.92352189044543, 0.972584307882505, 1.06297865845425, 1.19106585655980, 
+1.34995342006370, 1.53047221973131, 1.72238265750590, 1.91558238798266, 
+2.10114324511268, 2.27205856250902, 2.42364193695782, 2.55358327388246, 
+2.66172502758510, 2.74965738377641, 2.82023944527764, 2.87713688734118, 
+2.92443420540394, 2.96634394541410, 3.00700845039080, 3.05038017292837, 
+3.10017489650203, 3.15990716064601, 3.23301746388505, 3.32306490053411, 
+3.43388304152265, 3.56951146775960, 3.73368342299261, 3.92873710150251, 
+4.15404228724653, 4.40432849588217, 4.66852444425504, 4.92972589817951, 
+5.16664160640235, 5.3564066501984, 5.4781884719715, 5.5167386353996, 
+5.4650598735507, 5.32562276022907, 5.10994847528762, 4.8367403357636, 
+4.5290212736803, 4.21089402139157, 3.90457121621668, 3.62819985390263, 
+3.39473276272095, 3.21176472159953, 3.08200647099949, 3.00403636300597, 
+2.97312711434449, 2.98213939266291, 3.02254327649321, 3.0855383628711, 
+3.1630995098901, 3.24871690625825, 3.33768106160447, 3.42692907913671, 
+3.51461402193046, 3.59961227680278, 3.68113959991685, 3.75854999474245, 
+1.11490596258492, 1.21746500400875, 1.33068383281863, 1.45450530104452, 
+1.59435789685668, 1.77064528031373, 2.03102038182961, 2.44464496781032, 
+3.04615125821035, 3.74786587113109, 4.33361166215026, 4.6124521682447, 
+4.59482299030328, 4.47309368174986, 4.43226194717193, 4.51950275586099, 
+4.67239466126442, 4.80696185054038, 4.86635970273613, 4.82619117443242, 
+4.68734542981815, 4.46931732357689, 4.2020657613266, 3.91531380231444, 
+3.62918653984859, 3.35090920151279, 3.07857027120059, 2.80850865145037, 
+2.54130773842145, 2.28330441604469, 0, 0, 0, 1.49627862836685, 
+1.3687038680505, 1.26181845743125, 1.17323545602336, 1.10381984026965, 
+1.05737032628166, 1.03921924669722, 1.05439418625223, 1.10597119191249, 
+1.19403621593253, 1.31539332251495, 1.46393547665058, 1.63147790773773, 
+1.80882702315909, 1.98687704209767, 2.15756457675672, 2.31456160881382, 
+2.4536481696328, 2.57276978944406, 2.67183856559807, 2.75236943549468, 
+2.81705053303882, 2.86933128311166, 2.91308235090138, 2.95234843607927, 
+2.99118869513595, 3.03358762271483, 3.08342231653485, 3.14448183374219, 
+3.22053442124954, 3.31541223226893, 3.43302813442487, 3.57717939961188, 
+3.75097766648094, 3.9558239429871, 4.19003354662125, 4.44745280482681, 
+4.71658261542471, 4.98071670219097, 5.21936939559485, 5.41087735489576, 
+5.53566808379867, 5.57945757748482, 5.53565264610614, 5.40646021084725, 
+5.20253818515901, 4.94134473227312, 4.64458285894915, 4.33527065787538, 
+4.03498744117652, 3.76174652067782, 3.52873937263188, 3.34394498578749, 
+3.21040388575408, 3.12689774071283, 3.08884439527264, 3.08932215177195, 
+3.12017781666368, 3.17312847740902, 3.24070023644204, 3.31684010147145, 
+3.39711819912598, 3.47856486557535, 3.55929020988994, 3.63806475112512, 
+3.71399778931041, 3.78637001794014, 1.09188406585655, 1.1867702646611, 
+1.29248502285010, 1.40960799480358, 1.54351256621766, 1.71224839828413, 
+1.95665150208050, 2.33539928410403, 2.87823049050663, 3.51277441276375, 
+4.05909081491502, 4.35706205085785, 4.41262912877952, 4.38202306676106, 
+4.41506387530762, 4.54694250801797, 4.72122996233016, 4.86256092159563, 
+4.91752384880367, 4.86088023275456, 4.69216262974548, 4.43190627704159, 
+4.11454351739848, 3.77696500236929, 3.44729903186153, 3.13954011472925, 
+2.85578267679157, 2.59297731198958, 2.34920209157961, 2.12615141084551, 
+0, 0, 0, 1.49755876290754, 1.40059186639343, 1.31981750612936, 
+1.25340045363647, 1.20253355948688, 1.17095424720170, 1.16363583998975, 
+1.18518519957772, 1.23843776633043, 1.32356824330926, 1.43782813687044, 
+1.57585420666493, 1.73039404158674, 1.89325804686860, 2.05630992345363, 
+2.21233555811269, 2.35567650262400, 2.48257261001142, 2.59121848286486, 
+2.68158788063999, 2.75510984330572, 2.81428678899658, 2.86233114190169, 
+2.90287038404625, 2.93974003022505, 2.97685883170384, 3.01816680517532, 
+3.06760554537202, 3.12912569610113, 3.20670623982507, 3.30435215808875, 
+3.42599942789833, 3.5752179017429, 3.75460085695245, 3.96480234437206, 
+4.20333669498829, 4.46344220671707, 4.7334415696771, 4.99701285825899, 
+5.2345827483786, 5.42572474939115, 5.55211703978422, 5.60041989595217, 
+5.56444165565444, 5.44615335437923, 5.25539853989353, 5.00842806379239, 
+4.72560355894371, 4.42873133488814, 4.13850587877219, 3.87246163913000, 
+3.64367013681048, 3.46022305632848, 3.32538005642876, 3.23818658337317, 
+3.1943814793407, 3.18746330208466, 3.20980903123879, 3.25372439221187, 
+3.31228648502577, 3.37986222514606, 3.45226233985309, 3.52658938352087, 
+3.60091146253159, 3.67390994985792, 3.74461106900567, 3.81224493941861, 
+1.07026372592183, 1.15767372570678, 1.25596290001564, 1.36623166122068, 
+1.49354227807448, 1.65295242759273, 1.87713148341531, 2.21237822158047, 
+2.68267893268369, 3.23360660254866, 3.72772623666776, 4.04120458491798, 
+4.17510098685708, 4.24382238112272, 4.35645092704759, 4.53452146745413, 
+4.72906247793486, 4.8754793372483, 4.92534616398045, 4.85345392640295, 
+4.65837899491003, 4.36168923319156, 4.00184922242105, 3.62207651767243, 
+3.25741739369703, 2.92755470080684, 2.63777515042005, 2.38528066070761, 
+2.16578277520868, 1.97686880789185, 1.81778416012911, 0, 0, 0, 
+1.43283751776409, 1.3776574045039, 1.33294131738330, 1.30006155026154, 
+1.28266535875656, 1.28544065420169, 1.31269079214767, 1.36711047025258, 
+1.44901241761836, 1.55609417206325, 1.68370340475189, 1.82547681178858, 
+1.97418850148329, 2.12263919522315, 2.26443942996105, 2.39458202732166, 
+2.50975319985863, 2.60838672753998, 2.69051037117643, 2.75746020998052, 
+2.81154441660302, 2.85572583512572, 2.89336891448340, 2.92806894752807, 
+2.96355770285526, 3.00366475391114, 3.05230939433117, 3.11349988367112, 
+3.19131620122957, 3.28984079623043, 3.41297828528225, 3.56408388323718, 
+3.74532934735591, 3.95680116655056, 4.1954512070155, 4.45416664332298, 
+4.72132138718432, 4.98114392550232, 5.21506143432146, 5.40390405984195, 
+5.53057917658037, 5.58266121171737, 5.5543471500008, 5.44738719195837, 
+5.27084540303876, 5.03979450009628, 4.77324209110322, 4.49169477508484, 
+4.21478572154111, 3.95932616506175, 3.73800960507951, 3.55883626972672, 
+3.42518456319499, 3.33637499933483, 3.28855506352506, 3.27575104890068, 
+3.29094978738854, 3.32707814990448, 3.37775851987497, 3.43775702151722, 
+3.50311069402926, 3.57099686599909, 3.63946020349719, 3.70712029912735, 
+3.7729484145144, 3.83614744096230, 1.05059323138323, 1.13087615675246, 
+1.22197194862392, 1.32541294291459, 1.44587712931296, 1.59544710315555, 
+1.79883585635717, 2.09034255719478, 2.48834934379523, 2.95565331388578, 
+3.39571873548935, 3.71969112487733, 3.92407593324908, 4.08323790930754, 
+4.26728812773101, 4.48487708465108, 4.69454378572426, 4.84252456992379, 
+4.8857745234712, 4.79968566091026, 4.58226556324352, 4.2560094943269, 
+3.86270598960471, 3.45071520924541, 3.06063788586858, 2.71663980272575, 
+2.4264126234485, 2.18715980685862, 1.99248488111799, 1.83648697312294, 
+1.71447039876835, 1.62186020976991, 0, 0, 0, 1.43315322641093, 
+1.40930783497610, 1.39365712881330, 1.38972313711766, 1.40194330000757, 
+1.43438413650957, 1.48965793663878, 1.56824224821917, 1.66827322116090, 
+1.78577794962549, 1.91523955296635, 2.05035159590123, 2.18481135739359, 
+2.31301979123288, 2.43059396593474, 2.53464680133075, 2.62383840278582, 
+2.69824315324739, 2.75910024129735, 2.80852051411542, 2.84921190239315, 
+2.88426460526933, 2.91701241017701, 2.95096424534415, 2.98978482442097, 
+3.03729644191089, 3.09747304258166, 3.17439673711927, 3.27214015030528, 
+3.39452535726587, 3.54470236477056, 3.72450713125474, 3.93361927040213, 
+4.1686421514235, 4.42234140006735, 4.68334514347253, 4.93657611682778, 
+5.16453420500296, 5.34931661981225, 5.47503418827409, 5.53014333930387, 
+5.50921381420093, 5.41378391913419, 5.25216481698338, 5.03827513751599, 
+4.78976323370399, 4.52577784684331, 4.26477057386836, 4.02266063635552, 
+3.81158143786094, 3.63929021490754, 3.50919552224571, 3.42087317162883, 
+3.37090727092116, 3.35389377212846, 3.36345767262729, 3.39315213198819, 
+3.43713443567222, 3.49055921210406, 3.54969101241148, 3.61179884275513, 
+3.67493254270021, 3.73768256547729, 3.79899474962318, 3.85806703563638, 
+1.03325387607961, 1.10687464537406, 1.19112843878319, 1.28790968793202, 
+1.40156533395809, 1.54167127229001, 1.72626878057395, 1.97960205263942, 
+2.31529352933870, 2.71033873780678, 3.10208487827513, 3.43069359999023, 
+3.68892415037654, 3.91799136017974, 4.15580723134169, 4.40055926803801, 
+4.617364837776, 4.761921955517, 4.7962097365191, 4.69664270489517, 
+4.46107879851684, 4.11277370652571, 3.69591942877376, 3.26255888644113, 
+2.85727044937054, 2.50742086337273, 2.22236948890332, 1.99918118831456, 
+1.82970826033451, 1.70522967938628, 1.61787728654501, 1.56022685912558, 
+0, 0, 0, 1.48483415696717, 1.48075581838127, 1.48139823889911, 
+1.49012918915727, 1.51115481018967, 1.54834594319383, 1.60426802117389, 
+1.67957638294644, 1.77283249562845, 1.88070870109337, 1.99848808897871, 
+2.12073290583915, 2.24198791538204, 2.35740130019072, 2.46317971917133, 
+2.55683789874721, 2.63724696623977, 2.70452082302163, 2.75980050194440, 
+2.8050010787368, 2.84257647646803, 2.87533905124877, 2.90634876356742, 
+2.93886623280203, 2.97634880644253, 3.02246038491342, 3.08106272256651, 
+3.15615458925371, 3.25172196751327, 3.37145794096708, 3.51831301921288, 
+3.69385928252499, 3.89750659422779, 4.1256931092233, 4.3712591805505, 
+4.62325941245907, 4.86743077891069, 5.0874033445071, 5.26654582738454, 
+5.39014698227567, 5.44751581797809, 5.43358064469267, 5.34967549440945, 
+5.20338162621793, 5.00748598189253, 4.77827966838813, 4.53351859066436, 
+4.29039448893895, 4.0638215384846, 3.86524741905452, 3.70207545761200, 
+3.57766838960735, 3.4918205483228, 3.44154346827729, 3.42200260213301, 
+3.42745595229838, 3.4520698398114, 3.49052212974591, 3.53835029975639, 
+3.59205566148708, 3.64902266776875, 3.70733884248895, 3.76559905886319, 
+3.82275205697845, 3.87801077488972, 1.01846245416217, 1.08596522231222, 
+1.16381248583751, 1.25419754674637, 1.36124003210115, 1.49266035111562, 
+1.66154860969250, 1.88467476778556, 2.17203327508198, 2.51086928716400, 
+2.86321941941278, 3.19041952939142, 3.4824721337435, 3.7563694313197, 
+4.02657666236156, 4.28386604965095, 4.49858415629745, 4.63396194058052, 
+4.65639639560549, 4.54375292320476, 4.29421527669551, 3.9316014103196, 
+3.50145035698493, 3.05785732260728, 2.64768642865787, 2.30021115575356, 
+2.0257936816726, 1.82131800644783, 1.67730883421136, 1.58290445186134, 
+1.52779889669951, 1.502352376644, 1.49741853310843, 0, 0, 0, 
+1.54617351681349, 1.56201919569497, 1.58252643284234, 1.61168624875025, 
+1.65320372197589, 1.70962099791543, 1.78177549000019, 1.86863522675990, 
+1.96747919031069, 2.07433860155178, 2.18458668021080, 2.29355877779082, 
+2.39709958854758, 2.49196454494462, 2.57604114984397, 2.64839437858394, 
+2.70917084321743, 2.75941435387429, 2.80084957162299, 2.83568250710539, 
+2.86645059554793, 2.89593561591211, 2.92713409675187, 2.96326518301462, 
+3.00778663548733, 3.06438515160104, 3.13690550363198, 3.22918224913165, 
+3.34473898025788, 3.48632907306034, 3.65531802881571, 3.85095750287805, 
+4.06967021184535, 4.3045312942045, 4.54516109536225, 4.77820586802213, 
+4.98846872528999, 5.16058942093507, 5.28101092454485, 5.33987000619984, 
+5.33244332687322, 5.2598698631536, 5.12902386399512, 4.95158436521112, 
+4.74249505279488, 4.51810302132087, 4.2942938334519, 4.08490497321481, 
+3.90061472432456, 3.74839308402287, 3.63149391202176, 3.54988638616927, 
+3.50097956319621, 3.48048348697432, 3.48326383195433, 3.50407551075807, 
+3.5380993159726, 3.5812513256948, 3.63028136242496, 3.68271435522076, 
+3.73670730937121, 3.79089076093828, 3.84424155941835, 3.89600443054483, 
+1.00628450053785, 1.06825865148231, 1.14018676351800, 1.22449483517342, 
+1.32516748811905, 1.44868247823096, 1.60480818602342, 1.80528950962512, 
+2.05757388542862, 2.35542634965344, 2.67687346563795, 2.99700110650081, 
+3.30398627309056, 3.5990315277161, 3.88140372352312, 4.13730045076750, 
+4.34099988058508, 4.46147455888737, 4.4690569874273, 4.34357869198301, 
+4.08406587048391, 3.71469055258403, 3.28123798308875, 2.83818698333673, 
+2.43300278861692, 2.09563385729956, 1.83687165924124, 1.65345353278183, 
+1.53502820183057, 1.46924561667954, 1.44403316447306, 1.44809904623695, 
+1.47104611969705, 1.50381369589417, 0, 0, 0, 1.63478623209085, 
+1.66609180875735, 1.70266706244031, 1.74807695669765, 1.80485743188951, 
+1.87402634875251, 1.95493465655361, 2.04542469077374, 2.14221869209131, 
+2.24143715793677, 2.33914293089052, 2.43182083095639, 2.51672975443408, 
+2.59209801750564, 2.65716601138003, 2.71210658593476, 2.75786901082306, 
+2.79599587643666, 2.82845551482373, 2.85751872134787, 2.88569156780901, 
+2.91569939648281, 2.95050323441458, 2.99332020555260, 3.04761410124275, 
+3.11702027317715, 3.20516985569721, 3.31538332339215, 3.45021683045662, 
+3.61087265356914, 3.79653054311968, 4.00371405095934, 4.22585669459168, 
+4.45325044777678, 4.67352049583792, 4.87267077966629, 5.03660614712572, 
+5.1529013130225, 5.21250025893569, 5.21102205537556, 5.14942275344968, 
+5.03389464444246, 4.87503641814197, 4.68646290701431, 4.48311307836235, 
+4.27954539912761, 4.08848056159983, 3.91977556439039, 3.77991253393513, 
+3.67198616007347, 3.59609659303435, 3.55001102511492, 3.52994637662036, 
+3.53133973092166, 3.54950337848745, 3.58010055222968, 3.61942061876687, 
+3.6644723613827, 3.71294363399539, 3.76308887384712, 3.81360105817135, 
+3.86350604353301, 3.91209354538042, 0.996655591760163, 1.05370603367693, 
+1.12022717078657, 1.19880518452999, 1.29333869910162, 1.40951813781563, 
+1.55504160932863, 1.73852716919131, 1.96572042201598, 2.23402009374511, 
+2.53069906303622, 2.83884580552865, 3.14555961857880, 3.44282014443302, 
+3.72109729032250, 3.96420436485056, 4.14935747902563, 4.24996585389531, 
+4.24008381783721, 4.10208774651978, 3.83635042886715, 3.46719090748236, 
+3.03959109257189, 2.60684843471031, 2.21548120520981, 1.89501860542648, 
+1.65621291542219, 1.49573783798510, 1.40280427343256, 1.36416340103234, 
+1.36656089973262, 1.39753509727659, 1.44577223949901, 1.50164149353872, 
+0, 0, 0, 1.69940219038339, 1.74045076831376, 1.78367494537268, 
+1.83252342060699, 1.88953878419951, 1.95591315812570, 2.03135254734056, 
+2.11421529080554, 2.20185335078485, 2.29106648824451, 2.37857776565024, 
+2.46145209784892, 2.53740374672383, 2.60496813430901, 2.66354198166961, 
+2.7133182876486, 2.75515579481555, 2.790425581881, 2.82087166210826, 
+2.84851067773448, 2.87558108508614, 2.90453742903638, 2.93807249482535, 
+2.97914053403599, 3.03094884344276, 3.09688274474900, 3.18033076747626, 
+3.28438409974449, 3.41140031192302, 3.56244958618097, 3.73670291857426, 
+3.93086962743357, 4.13883060572379, 4.35162318277508, 4.55789605529798, 
+4.74486601706752, 4.89969012057047, 5.01105170345668, 5.07068392321108, 
+5.07454557358913, 5.02342494185975, 4.92286080789125, 4.78240454584048, 
+4.614370362514, 4.43230521222256, 4.24944082318072, 4.07736605110765, 
+3.92508959768323, 3.79857134489516, 3.70070876640221, 3.63169293953141, 
+3.58960740414762, 3.57113310107799, 3.57223732322918, 3.58875504330334, 
+3.61680901372792, 3.65305401990703, 3.69476462429895, 3.73980914588502, 
+3.78656171495677, 3.83379887443283, 3.88061150569851, 3.92634383747083, 
+0.989407728698556, 1.04213052576847, 1.10376034408225, 1.17696688075729, 
+1.26556474609777, 1.37473199680037, 1.51090990359831, 1.68084688469862, 
+1.88915561297960, 2.13496057993436, 2.41031039821192, 2.70250120504745, 
+2.99809930788061, 3.28427924783234, 3.54699840399249, 3.76914675151517, 
+3.9302376277605, 4.00732973160839, 3.97820402500549, 3.82832655604089, 
+3.55983521573081, 3.19699389919866, 2.78306891704274, 2.36884365130202, 
+1.99859309867743, 1.70053382984475, 1.48502213047514, 1.34877078337863, 
+1.28093975424263, 1.26787973984197, 1.29563923771478, 1.35098376483591, 
+1.42196159329102, 1.49853501916205, 1.57324087574687, 0, 0, 0, 
+1.80560319499509, 1.85467028327924, 1.90648308643058, 1.96359997542579, 
+2.02737717919741, 2.09784437279557, 2.17382553264225, 2.25323839000422, 
+2.33349158066208, 2.41189905363817, 2.48604413014339, 2.55404717218354, 
+2.61471636915147, 2.66758559629159, 2.71286234827063, 2.75131980770798, 
+2.78416960957234, 2.81294699353731, 2.83943003899967, 2.8656020788393, 
+2.89365342823949, 2.92600692687918, 2.96534258856354, 3.01459057483643, 
+3.07685932248257, 3.15526783463227, 3.25265952718128, 3.37119198466342, 
+3.51182450310044, 3.67376250228009, 3.85395824962838, 4.04679776858659, 
+4.24410776079991, 4.43558100081747, 4.60964294561013, 4.75468128549187, 
+4.86046177807934, 4.9194888290629, 4.92805980257479, 4.88681278320138, 
+4.8006653181217, 4.67816096010097, 4.53035180776468, 4.36942361811347, 
+4.20730035515056, 4.0544447612906, 3.91901041669511, 3.80641734175127, 
+3.71933918077137, 3.65802377540445, 3.62083087191931, 3.60486195556032, 
+3.60657199078188, 3.62228240622752, 3.6485504640882, 3.68238520641597, 
+3.72132898766727, 3.76344210428365, 3.80723415188373, 3.85158030231255, 
+3.89564753572349, 3.93884061408813, 0.98429787646103, 1.03326159955897, 
+1.09050345666027, 1.1587009728831, 1.24155260481659, 1.34385388195948, 
+1.47124219558739, 1.62932247570893, 1.82191435815329, 2.04877499839305, 
+2.3041516128958, 2.57738153752452, 2.85488098937414, 3.12166317231885, 
+3.36171658247996, 3.55787751785972, 3.69159670941005, 3.74316411276498, 
+3.69416507256708, 3.53355004138851, 3.26548786938717, 2.91399038194909, 
+2.51989680138182, 2.13047003590497, 1.78677878922676, 1.51507530275764, 
+1.32507322294075, 1.21362104225962, 1.17013513994537, 1.18095524036117, 
+1.23181212222478, 1.30901375964012, 1.40019842897687, 1.49506382632774, 
+1.58602211400506, 1.66855789820847, 0, 0, 0, 1.91593119273262, 
+1.97021830948827, 2.02729475213662, 2.08866700178163, 2.15465422702087, 
+2.22449386526868, 2.29660445356706, 2.36893267133387, 2.43931395042686, 
+2.50578848741466, 2.56683376591396, 2.62149676240963, 2.66942974094464, 
+2.71084952258249, 2.74644932077416, 2.77729428030962, 2.80472775562618, 
+2.83030694517231, 2.85577578789859, 2.88307179711184, 2.91435310066615, 
+2.95202335657251, 2.99872623432513, 3.05727868949966, 3.13051453411475, 
+3.22101848822217, 3.3307478129108, 3.46056468380693, 3.60973583212125, 
+3.77549026505748, 3.95274989430216, 4.134148404891, 4.310420962064, 
+4.47118130159226, 4.60601605699508, 4.70574181628952, 4.76361399626521, 
+4.77626702454272, 4.74420774369438, 4.67176844664525, 4.56653116140943, 
+4.4383348382603, 4.29804884102675, 4.15632499922834, 4.02252339695444, 
+3.90395250507901, 3.80548900346554, 3.72956647211429, 3.67646194807557, 
+3.64477487520872, 3.63198556538711, 3.63499473849683, 3.65057365005089, 
+3.67568729899854, 3.70768435709699, 3.74437185871179, 3.78400734350301, 
+3.82524514110234, 3.86706823592148, 3.90872614967556, 3.94968705695471, 
+0.981036071702848, 1.02676872825389, 1.08010272623824, 1.14365412906355, 
+1.22095655141006, 1.31646116195585, 1.43521582582284, 1.58205197982836, 
+1.76018281647741, 1.96945865787537, 2.20503343437007, 2.45722560941292, 
+2.71257940388393, 2.9553992238202, 3.16908661654145, 3.33690594419035, 
+3.44205843645630, 3.46782711644265, 3.39960824302985, 3.22999542184572, 
+2.96526149277495, 2.62897480103630, 2.25906921047412, 1.89865225923299, 
+1.58499175659681, 1.34197732615628, 1.17853384399147, 1.09171741080109, 
+1.07141391264593, 1.10422847657316, 1.17585349463411, 1.27238186323125, 
+1.3812269060421, 1.49194644144224, 1.59690328744549, 1.69157590400225, 
+0, 0, 0, 1.96798807420075, 2.02425101958404, 2.08113605459916, 
+2.14028257041227, 2.20226301117679, 2.26667549503418, 2.3323749489044, 
+2.39777657097369, 2.46116954781212, 2.52099113709973, 2.57602848683248, 
+2.62553457249673, 2.66926211157664, 2.70743260523844, 2.74066523282422, 
+2.76989195770565, 2.79628175417964, 2.82118981981359, 2.84613860395416, 
+2.87282784717024, 2.90316165223405, 2.93927274628812, 2.98351839911336, 
+3.03841999871947, 3.10652044778438, 3.19014197561672, 3.29104309626787, 
+3.40999753215762, 3.54634763504836, 3.69761411754045, 3.85926316037331, 
+4.02473044808846, 4.18577194633775, 4.33315374539383, 4.45761878309764, 
+4.5509957735821, 4.60726662691539, 4.62339930864516, 4.5997887043824, 
+4.54022101725935, 4.45136960544761, 4.34191925879745, 4.22148073690825, 
+4.0994842164245, 3.98422584361197, 3.88219318035069, 3.79772803230727, 
+3.73301682463156, 3.68834467431102, 3.6625185328149, 3.65335860719038, 
+3.65817100830655, 3.67414040524932, 3.69861133520263, 3.72925422973035, 
+3.76413283697369, 3.80170136213877, 3.84076216108501, 3.88040992021412, 
+3.91997907834917, 3.95900143987746, 0.979311034029364, 1.02229205775147, 
+1.0721680678856, 1.13143485886290, 1.20341076835116, 1.29219580857105, 
+1.40233175382803, 1.53804545194894, 1.70204388366240, 1.89405163606996, 
+2.10958020972056, 2.33950805204987, 2.57072578573078, 2.78759998542917, 
+2.97367000485966, 3.11289599287481, 3.19012468016824, 3.19142974571062, 
+3.10586681109293, 2.92956528473920, 2.6707781930074, 2.35244652773382, 
+2.00935304903594, 1.68017947925733, 1.39815266260958, 1.18463689477061, 
+1.04770624142637, 0.984661949470643, 0.98597820315383, 1.03869732096663, 
+1.12866570663423, 1.24194385528637, 1.36587140622321, 1.48997731017580, 
+1.60664915183881, 1.71140712328495, 1.80272077296229, 0, 0, 0, 
+2.06929903150842, 2.12583437037089, 2.18291647623716, 2.24133357567293, 
+2.30099220621183, 2.36112118327016, 2.42053748055964, 2.47791942225485, 
+2.53204449077602, 2.58196455067183, 2.62710764351679, 2.66731016601749, 
+2.7027942038143, 2.73411095327446, 2.76207242665669, 2.78769073790838, 
+2.81213840371748, 2.83673553122336, 2.86296157274309, 2.89248134216544, 
+2.92716793399159, 2.96909989925006, 3.02050763379118, 3.08364586813093, 
+3.16057698217558, 3.25286476453081, 3.36120005789846, 3.48500597472935, 
+3.62209544511033, 3.76846952381531, 3.91834233539642, 4.06445195652672, 
+4.19866669197048, 4.31283219163133, 4.39974257567581, 4.45407618486782, 
+4.47312776998936, 4.45719891115245, 4.40957132718672, 4.33606838609358, 
+4.24428875081898, 4.14265391153049, 4.03943577364762, 3.94191821561482, 
+3.85580392676124, 3.78491825368888, 3.73120117151686, 3.69493058650575, 
+3.6750930293345, 3.66981271150737, 3.67676266588647, 3.69350511816347, 
+3.71773488893094, 3.74742353704180, 3.78087934827008, 3.81674756277165, 
+3.85397673728144, 3.89177268076191, 3.9295537614436, 3.96691349968626, 
+0.978811843109271, 1.01946837906650, 1.06630223286624, 1.12164285354922, 
+1.1885505831545, 1.27075370299581, 1.37231321674407, 1.49692438927756, 
+1.64684692717403, 1.82162151526949, 2.01693897554637, 2.22413318643129, 
+2.43062455487792, 2.62126966687782, 2.78014676099454, 2.8920773804575, 
+2.94347406883842, 2.92296048642173, 2.82292454011760, 2.64268418250945, 
+2.39218161467503, 2.09355814720675, 1.77840296234867, 1.48101409742367, 
+1.23063663191078, 1.04614054584052, 0.934750456596723, 0.894015125933936, 
+0.91503421466933, 0.985373241680259, 1.09115695617991, 1.21855130716731, 
+1.35494897618424, 1.48995086990437, 1.61604138997588, 1.72883111972684, 
+1.82683959265194, 1.91091058144659, 0, 0, 2.10621418936578, 2.16223725410227, 
+2.21739593564350, 2.27265625171364, 2.32818241411175, 2.38351766946127, 
+2.43781797107382, 2.49009037723629, 2.53939968804596, 2.58502078281235, 
+2.62652818101244, 2.66382658629306, 2.69713513763487, 2.72694303654151, 
+2.75395515748654, 2.77904381137935, 2.80321797676516, 2.82761502434076, 
+2.85351305742739, 2.88235511952733, 2.9157702913391, 2.95557189481672, 
+3.00371074194998, 3.06216301976961, 3.13273945040791, 3.21681576815996, 
+3.3150039789277, 3.42680683954659, 3.55031947369334, 3.68205494739546, 
+3.81696768237766, 3.94872517779301, 4.07023552496618, 4.17438335134649, 
+4.25487343613724, 4.3070444723829, 4.32850735839572, 4.31948764853555, 
+4.28280575995636, 4.22349846125699, 4.14815388816216, 4.06408325652751, 
+3.97847426209068, 3.89766076357059, 3.82660618233877, 3.76864585513503, 
+3.72548040648186, 3.69737020207634, 3.68345726015809, 3.68213681708541, 
+3.69141231260132, 3.70918844571650, 3.73348041622297, 3.76253814718622, 
+3.79489892332317, 3.82938932733947, 3.86509819439984, 3.90133833873526, 
+3.93760845985712, 3.97356028292907, 0.979244880162183, 1.01795147529461, 
+1.06212356346342, 1.11389150802058, 1.17602722529847, 1.2518697372102, 
+1.34500694025926, 1.45863855938017, 1.59461955421556, 1.75231766960331, 
+1.92758300810687, 2.11223058217109, 2.29436658110745, 2.45960443192772, 
+2.59281621847570, 2.67980439949160, 2.70846674460336, 2.66968257027097, 
+2.55870547052601, 2.37752105626718, 2.13735494166486, 1.85939315401696, 
+1.57214381566834, 1.30579481432334, 1.08588638419100, 0.928962829448148, 
+0.841442264914652, 0.821094282804529, 0.859620791347573, 0.945135456532062, 
+1.06411881368398, 1.20295004925268, 1.34918519305629, 1.49259043743587, 
+1.62581605746341, 1.74460974968725, 1.84757140950584, 1.93555914829633, 
+0, 0, 2.13592503119266, 2.19127291609556, 2.24462843709787, 2.29709769004391, 
+2.34905418649294, 2.40030007142141, 2.4502722836937, 2.49825120252474, 
+2.54354062067395, 2.58560047246548, 2.62412583588802, 2.65907590544851, 
+2.69066390647160, 2.71932283670051, 2.74566257969313, 2.77043187975579, 
+2.7944946633991, 2.81882499487175, 2.84451918228573, 2.87281769996791, 
+2.90512416949716, 2.94300435378202, 2.98814599792895, 3.0422617162897, 
+3.10692330668493, 3.18332768137331, 3.27201162379451, 3.37255249873985, 
+3.48331039523361, 3.60127790932314, 3.72210082377877, 3.84031260540725, 
+3.94978880962711, 4.04438068691073, 4.11864169976094, 4.16852907054392, 
+4.19195520162539, 4.1890850445569, 4.16232157451352, 4.11598168746814, 
+4.05572430352232, 3.98783677107463, 3.91850484407253, 3.8531827101939, 
+3.79614743736494, 3.75027696936118, 3.71704468214806, 3.69668709894072, 
+3.68848091498736, 3.69106205181875, 3.70272975325042, 3.72169706773265, 
+3.74626945930657, 3.77495102287576, 3.80649006462926, 3.83988180699983, 
+3.87434639700080, 3.9092969332162, 3.94430697036087, 3.9790818290311
+), .Dim = c(100, 100))
diff --git a/inst/doc/WebGL.Rmd b/inst/doc/WebGL.Rmd
new file mode 100644
index 0000000..07367b2
--- /dev/null
+++ b/inst/doc/WebGL.Rmd
@@ -0,0 +1,434 @@
+---
+title: "User Interaction in WebGL"
+author: "Duncan Murdoch"
+date: "`r format(Sys.time(), '%B %d, %Y')`"
+output:
+  rmarkdown::html_vignette:
+    toc: yes
+    fig_width: 5
+    fig_height: 5
+vignette: >
+  %\VignetteIndexEntry{User Interaction in WebGL} 
+  %\VignetteEngine{knitr::rmarkdown}
+---
+
+
+```{r setup, echo=FALSE, results="asis"}
+source("setup.R")
+set.seed(123)
+```
+
+## Introduction
+
+This document describes how to embed `rgl` scenes in HTML documents
+and use embedded Javascript to 
+control a WebGL display in an HTML document.  For more 
+general information, see [rgl Overview](rgl.html).
+
+We assume that the HTML document is produced from R markdown
+source using `knitr` or `rmarkdown`.  This format mixes
+text with Markdown markup with chunks of R code.
+
+There are two ways to embed an `rgl` scene in the document.  The
+older one is to use the chunk option `webgl = TRUE`.  With that
+option, whatever `rgl` scene is active at the end of the chunk
+will be embedded.  See the `r linkfn("setupKnitr", pkg="rgl")` 
+help page for chunk options.  
+
+The second way is to use a call to `r linkfn("rglwidget",
+pkg="rglwidget")` from the `rglwidget` package.  Each call to
+this function will insert a scene into the document.  Do not set
+`webgl = TRUE`.  
+
+## Browser support
+
+Most browsers now support WebGL, but it may be disabled by
+default.  See http://get.webgl.org for help on a number of
+different browsers.  
+
+If you are using the internal browser in RStudio, support varies
+by version.  I believe it is enabled by default in Windows
+versions, but not in all Mac OSX versions.  You can run this
+command:
+ 
+    defaults write org.rstudio.RStudio WebKitWebGLEnabled -bool YES
+
+to enable it.  I do not have much experience with RStudio in
+Linux, but it does seem that WebGL is enabled there.
+
+
+Both methods make use of functions from the `rglwidget` package,
+so you will need to install it.  The second method is easier for
+me to maintain, so it is likely to receive more support in the 
+future, but for now both methods are supported, and there
+are examples of both in this document.
+
+## Examples
+
+We start with two simple examples.  The next section gives 
+reference information.
+
+Consider the simple plot of the iris data.  We
+insert a code chunk and call the `r linkfn("rglwidget",pkg="rglwidget")` 
+function with optional argument `elementId`.  This allows later
+Javascript code to refer to the image.
+```{r plot3d}
+library(rgl)
+library(rglwidget)
+with(iris, plot3d(Sepal.Length, Sepal.Width, Petal.Length, 
+                  type="s", col=as.numeric(Species)))
+subid <- currentSubscene3d()
+rglwidget(elementId="plot3drgl")
+```
+We might like a button on the web page to cause a change to the
+display, e.g. a rotation of the plot.  First we add buttons, with
+the "onclick" event set to a function described below:
+
+    <button type="button" onclick="rotate(10)">Forward</button>
+    <button type="button" onclick="rotate(-10)">Backward</button>
+
+which produces these buttons: 
+<button type="button" onclick="rotate(10)">Forward</button>
+<button type="button" onclick="rotate(-10)">Backward</button>
+
+We stored the subscene number that is currently active in
+`subid` in the code chunk above, and use it as `r rinline("subid")`
+in the script below.  `knitr` substitutes the value
+`r subid` when it processes the document.
+
+The `rotate()` function uses the Javascript function `document.getElementById` to retrieve the `<div>` component
+of the web page containing the scene.  It will have a
+component named `rglinstance` which contains information about the scene that we can modify:
+
+    <script type="text/javascript">
+    var rotate = function(angle) {
+      var rgl = document.getElementById("plot3drgl").rglinstance;
+      rgl.getObj(`r rinline("subid",
+                           script=TRUE)`).par3d.userMatrix.rotate(angle, 0,1,0);
+      rgl.drawScene();
+    };
+    </script>
+    
+<script type="text/javascript">
+var rotate = function(angle) {
+  var rgl = document.getElementById("plot3drgl").rglinstance;
+  rgl.getObj(`r subid`).par3d.userMatrix.rotate(angle, 0,1,0);
+  rgl.drawScene();
+};
+</script>
+
+If we had used `webGL=TRUE` in the chunk header,
+the `knitr` WebGL support create a global object with a name of the form `<chunkname>rgl`.  For example,  if the code chunk
+was named `plot3d`, the object
+would be called `plot3drgl`, and this code would work:
+
+    <script type="text/javascript">
+    var rotate = function(angle) {
+      plot3drgl.getObj(`r rinline("subid",
+                           script=TRUE)`).par3d.userMatrix.rotate(angle, 0,1,0);
+      plot3drgl.drawScene();
+    };
+    </script>
+    
+
+## Autogenerated controls
+
+We can also change the contents of the plot using `r indexfns("toggleButton")`.
+For example, we can redo the previous plot, but with the
+three species as separate "spheres" objects and buttons to
+toggle them:
+```{r toggle, webgl = TRUE, rgl.newwindow = TRUE}
+sphereid <- with(subset(iris, Species == "setosa"), 
+     spheres3d(Sepal.Length, Sepal.Width, Petal.Length, 
+                  col=as.numeric(Species),
+                  radius = 0.211))
+with(subset(iris, Species == "versicolor"), 
+     spheres3d(Sepal.Length, Sepal.Width, Petal.Length, 
+               col=as.numeric(Species),
+     	       radius = 0.211))
+with(subset(iris, Species == "virginica"), 
+     spheres3d(Sepal.Length, Sepal.Width, Petal.Length, 
+               col=as.numeric(Species),
+     	       radius = 0.211))
+aspect3d(1,1,1)
+axesid <- decorate3d()
+subid <- currentSubscene3d()
+```
+
+```{r results="asis"}
+toggleButton(sphereid, label = "setosa", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+1, label = "versicolor", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+2, label = "virginica", prefix = "toggle", subscene = subid)
+```
+
+Note that we need to use `results="asis"` for the button code.  
+Normally we would also use `echo=FALSE`, though I didn't do so above;
+then the buttons will end up side-by-side.  We also add another button
+to toggle the axes:
+
+```{r results="asis", echo=FALSE}
+toggleButton(sphereid, label = "setosa", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+1, label = "versicolor", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+2, label = "virginica", prefix = "toggle", subscene = subid)
+toggleButton(axesid, label="axes", prefix = "toggle", subscene = subid)
+```
+
+An alternate control to achieve the same thing is `r indexfns("subsetSlider")`.  Here we also illustrate the 
+`r indexfns("elementId2Prefix")` bridge to allow an `r indexfns("rglwidget")`
+to be controlled by the old-style slider.
+
+```{r slider}
+rglwidget(elementId = "slider")
+```
+```{r results="asis"}
+elementId2Prefix("slider")
+subsetSlider(subsets = list(setosa = sphereid, 
+                  versicolor = sphereid + 1, 
+                  virginica = sphereid + 2, 
+                  all = sphereid + 0:2),
+             prefixes = "slider", subscenes = subid,
+             init = 3)
+```
+
+There are several other functions to generate the Javascript
+code for controls.  `r indexfns("par3dinterpSetter")` generates
+a function that approximates the result of `r linkfn("par3dinterp")`.
+`r indexfns("propertySetter")` is a more general function to set
+the value of properties of the scene.  Both generate Javascript
+functions, but not the controls to use them; for that, use
+`r indexfns("propertySlider")` or your own custom code.
+
+For example, the following code (similar to the `r linkfn("play3d")`
+example) rotates the scene in a complex way.
+```{r userMatrix, webgl=TRUE}
+```
+```{r results="asis"}
+M <- r3dDefaults$userMatrix
+fn <- par3dinterp(time = (0:2)*0.75, userMatrix = list(M,
+                                     rotate3d(M, pi/2, 1, 0, 0),
+                                     rotate3d(M, pi/2, 0, 1, 0) ) )
+propertySlider(setter = par3dinterpSetter(fn, 0, 1.5, steps=15, 
+					   prefix = "userMatrix", 
+					   subscene = subid),
+	       step = 0.01)
+```
+Some things to note:  The generated Javascript slider has 150 increments,
+so that motion appears smooth.  However, storing 150 `userMatrix` values
+would take up a lot of space, so we use interpolation
+in the Javascript code.  However, the Javascript code can only do 
+linear interpolation, not the more complex spline-based SO(3)
+interpolation done by `r linkfn("par3dinterp")`.  Because of this,
+we need to output 15 steps from `r linkfn("par3dinterpSetter")`
+so that the distortions of linear interpolation are not visible.  
+
+Another function that auto-generates Javascript code is 
+`r indexfns("clipplaneSlider")`.  This function allows the user to control
+the location of a clipping plane by moving a slider.  Both it 
+and `r linkfn("par3dinterpSetter")` are implemented
+using the more general `r indexfns("propertySlider")`, which 
+allows control of multiple objects in multiple scenes, but which 
+does require knowledge of the internal representation of the scene
+in its Javascript implementation.
+
+
+Less general than `r linkfn("propertySetter")` is
+`r indexfns("vertexSetter")`.  This function sets attributes
+of individual vertices in a scene.  For example, to set the
+x-coordinate of the closest point in the setosa group, and modify
+its colour from black to white,
+
+```{r vertex, webgl=TRUE}
+```
+
+```{r results="asis"}
+setosa <- subset(iris, Species == "setosa")
+which <- which.min(setosa$Sepal.Width)
+init <- setosa$Sepal.Length[which]
+propertySlider(
+	vertexSetter(values = matrix(c(init,8,0,1,0,1,0,1), nrow=2),
+	             attributes=c("x", "r", "g", "b"), 
+		     vertices = which, objid = sphereid, 
+		     prefix = "vertex"), 
+	step=0.01)
+```
+	     
+
+A related function is `r indexfns("ageSetter")`, though it uses
+a very different specification of the attributes.
+It is used when the slider controls the "age" of the scene, 
+and attributes of vertices change with their age. 
+
+Rather than giving an example, we will illustrate
+the very similar function `r indexfns("ageControl", pkg = "rglwidget")` from the `rglwidgets` package, embedded in a 
+`r indexfns("playwidget", pkg = "rglwidget")`.  We will
+show a point moving along a curve.  In the original scene
+we need to specify multiple colours so that the
+colour is not fixed, and can be controlled by the slider.  We
+also give two `ageControl` calls in a list;
+
+```{r}
+time <- 0:500
+xyz <- cbind(cos(time/20), sin(time/10), time)
+lineid <- plot3d(xyz, type="l", col = c("black", "black"))["data"]
+sphereid <- spheres3d(xyz[1, , drop=FALSE], radius = 8, col = "red")
+rglwidget(elementId = "ageExample")
+```
+```{r}
+playwidget("ageExample", list(
+  ageControl(births = time, ages = c(0, 0, 50),
+		colors = c("gray", "red", "gray"), objids = lineid),
+	ageControl(births = 0, ages = time,
+		vertices = xyz, objids = sphereid)),
+  start = 0, stop = max(time) + 20, rate = 50,
+  components = c("Reverse", "Play", "Slower", "Faster",
+                 "Reset", "Slider", "Label"),
+  loop = TRUE)
+```
+
+The final function of this type is `r indexfns("matrixSetter")`, for setting
+up multiple controls to modify a matrix, typically `userMatrix`. This is used
+when complex manipulation of a matrix requires several controls.
+
+## User defined mouse controls
+
+`rgl` allows user defined mouse controls.  For these to work
+within WebGL, you will need to write a Javascript version as
+well as the R version.  This isn't easy:  R provides a lot
+of support functions which are not easily available in Javascript.
+
+TODO:  give an example here.
+
+## Reference for `rglClass`
+
+NB:  This section has not been updated recently, and is 
+not current.
+
+In writing the `writeWebGL()` function, I haven't tried to prevent access to 
+anything.  On the other hand, I haven't provided access to
+everything.  The parts documented here should remain relatively stable
+(unless indicated otherwise).  Users may also consult the source
+to `writeWebGL`, but should be aware that anything that isn't documented
+here is subject to change without notice.  
+
+`r indexclass("rglClass")`
+
+As documented in `r linkfn("writeWebGL")`, the call
+```{r eval=FALSE}
+writeWebGL(..., prefix = "<prefix>")
+```
+will create a global object on the output page with name 
+`<prefix>rgl` and Javascript class `rglClass`. 
+This class has a large number of properties and methods, some of which are designed
+to be available for use by other code on the web page. 
+
+Most of the properties are stored as Javascript `Array` objects, indexed
+by the `rgl` id of the subscene to which they apply.  There 
+are also Javascript methods attached to the `rglClass` class.
+
+### Methods
+
+`r indexmethods("drawScene")`
+
+After any change that will affect the display, code should
+call `<prefix>rgl.drawScene()` to redraw the scene.
+
+`r indexmethods(c("inSubscene", "addToSubscene", "delFromSubscene"))`
+
+These methods each take two arguments:  `id` and `subscene`,
+which should be the `rgl` ids of an object and a subscene.
+`inSubscene` tests whether `id` is already included in the 
+subscene, and the others 
+add it or delete it from the subscene.
+
+`r indexmethods(c("getSubsceneEntries"))`
+
+This function takes a subscene id as argument, and returns an `Array`
+containing all of the ids displayed in that subscene.
+
+`r indexmethods(c("setSubsceneEntries"))`
+
+This takes an `Array` of ids and a subscene id as arguments, and sets
+the contents of the subscene to the ids.
+
+### Properties
+
+`r indexproperties(c("FOV", "listeners", "userMatrix", "zoom"))`
+
+These correspond to the 
+`r linkfn("par3d")` properties with the same names.  
+
+- `FOV` and `zoom` are arrays of numbers. 
+- `userMatrix` is an array
+of `CanvasMatrix4` objects (documented in the file 
+`system.file("WebGL/CanvasMatrix.src.js")`.
+- Each `listeners` item is itself an array of subscene ids that "listen"
+to mouse actions, i.e. `listeners[19]` would contain all
+subscene ids that respond to mouse actions in subscene 19.
+
+`r indexproperties("viewport")`
+
+This property also corresponds to the
+`r linkfn("par3d")` property, but should be considered to be 
+read-only.
+
+`r indexproperties(c("drawFns", "clipFns"))`
+
+These two arrays contain the code to display 
+each object in the scene.  The functions in the
+`drawFns` array are called for each object
+each time it is displayed.  The `clipFns` functions
+are called when objects being clipped are drawn.
+
+`r indexproperties(c("values", "offsets"))`
+
+Most of the data about each object in a scene is contained in
+the `values` property.  This is an array, indexed by object
+id. The individual entries are numeric arrays.  Though they
+are singly-indexed, the entries are meant to be interpreted
+as matrices stored by row.  The first 3 columns are generally
+the coordinates of a vertex, and remaining columns correspond
+to other values from `r linkfn("rgl.attrib")`.  
+
+The `offsets` property gives the (0-based) offset of the first 
+column for a particular attribute in a named object.  Not all 
+columns will be present in every object; if not
+present, the corresponding `offsets` entry will be `-1`.
+The entries are
+
+Name | Meaning
+-----|--------
+vofs | Offset to 3 columns of vertex data in XYZ order
+cofs | Offset to 4 columns of colour data in RGBA order
+nofs | Offset to 3 columns of normal data
+radofs | Offset to 1 column of sphere radius data
+oofs | Offset to 2 columns of text or sprite origin data
+tofs | Offset to 2 columns of texture coordinates
+stride | Total number of columns in `values`
+
+For example, to find the blue colour entry for vertex 
+`i` in an object, one would first check if `offsets["cofs"]` was
+`-1`, indicating that no colour information was present.  If
+not, the entry could be found using
+```
+values[offsets["stride"]*(i-1) + offsets["cofs"] + 2]
+```
+This assumes `i` is specified using 1-based vertex counting
+as in R, and writes `values` and `offsets` instead of the
+fully specified `<prefix>rgl.values` and `<prefix>rgl.offsets`
+for clarity.
+
+Changes to `values` need to be pushed to the graphics system
+to be reflected in the scene; see the calls to `gl.bindBuffer` and
+`gl.bufferData` in the source to `r linkfn("propertySlider")`
+for details.
+
+
+## Index 
+
+The following functions and `rglClass` properties and methods are described in this document:<br>
+
+```{r echo=FALSE, results="asis"}
+writeIndex(cols = 5)
+```
+
+
diff --git a/inst/doc/WebGL.html b/inst/doc/WebGL.html
new file mode 100644
index 0000000..b42b9fd
--- /dev/null
+++ b/inst/doc/WebGL.html
@@ -0,0 +1,2901 @@
+<!DOCTYPE html>
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+
+<meta charset="utf-8">
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta name="generator" content="pandoc" />
+
+<meta name="author" content="Duncan Murdoch" />
+
+<meta name="date" content="2016-01-04" />
+
+<title>User Interaction in WebGL</title>
+
+<script src="data:application/x-javascript,%28function%28%29%20%7B%0A%20%20%2F%2F%20If%20window%2EHTMLWidgets%20is%20already%20defined%2C%20then%20use%20it%3B%20otherwise%20create%20a%0A%20%20%2F%2F%20new%20object%2E%20This%20allows%20preceding%20code%20to%20set%20options%20that%20affect%20the%0A%20%20%2F%2F%20initialization%20process%20%28though%20none%20currently%20exist%29%2E%0A%20%20window%2EHTMLWidgets%20%3D%20window%2EHTMLWidgets%20%7C%7C%20%7B%7D%3B%0A%0A%20%20%2F%2F%20See%20if%20 [...]
+<link href="data:text/css,%2ErglPlayer%20%7B%0A%20%20width%3A%20auto%3B%0A%20%20height%3A%20auto%3B%0A%7D%0A%0A%2ErglPlayer%20%2Ergl%2Dbutton%20%7B%0A%20%20width%3A%20auto%3B%0A%20%20display%3A%20inline%2Dblock%3B%0A%20%20font%2Dsize%3A%2075%25%3B%0A%7D%0A%0A%2ErglPlayer%20%2Ergl%2Dslider%20%7B%0A%20%20display%3A%20inline%2Dblock%3B%0A%20%20width%3A%2030%25%3B%0A%7D%0A%0A%2ErglPlayer%20%2Ergl%2Dlabel%20%7B%0A%20%20display%3A%20inline%3B%0A%20%20padding%2Dleft%3A%206px%3B%0A%20%20padding% [...]
+<script src="data:application/x-javascript,%0ArglwidgetClass%20%3D%20function%28%29%20%7B%0A%20%20%20%20this%2Ecanvas%20%3D%20null%3B%0A%20%20%20%20this%2EuserMatrix%20%3D%20new%20CanvasMatrix4%28%29%3B%0A%20%20%20%20this%2Etypes%20%3D%20%5B%5D%3B%0A%20%20%20%20this%2EprMatrix%20%3D%20new%20CanvasMatrix4%28%29%3B%0A%20%20%20%20this%2EmvMatrix%20%3D%20new%20CanvasMatrix4%28%29%3B%0A%20%20%20%20this%2Evp%20%3D%20null%3B%0A%20%20%20%20this%2EprmvMatrix%20%3D%20null%3B%0A%20%20%20%20this%2Eo [...]
+<script src="data:application/x-javascript,%2F%2A%0A%20%2A%20Copyright%20%28C%29%202009%20Apple%20Inc%2E%20All%20Rights%20Reserved%2E%0A%20%2A%0A%20%2A%20Redistribution%20and%20use%20in%20source%20and%20binary%20forms%2C%20with%20or%20without%0A%20%2A%20modification%2C%20are%20permitted%20provided%20that%20the%20following%20conditions%0A%20%2A%20are%20met%3A%0A%20%2A%201%2E%20Redistributions%20of%20source%20code%20must%20retain%20the%20above%20copyright%0A%20%2A%20%20%20%20notice%2C%20th [...]
+<script src="data:application/x-javascript,%2F%2A%20el%20is%20the%20div%2C%20holding%20the%20rgl%20object%20as%20el%2Erglinstance%2C%0A%20%20%20%20%20which%20holds%20x%20as%20el%2Erglinstance%2Escene%0A%20%20%20x%20is%20the%20JSON%20encoded%20rglwidget%2E%0A%2A%2F%0A%0A%0AHTMLWidgets%2Ewidget%28%7B%0A%0A%20%20name%3A%20%27rglWebGL%27%2C%0A%0A%20%20type%3A%20%27output%27%2C%0A%0A%20%20initialize%3A%20function%28el%2C%20width%2C%20height%29%20%7B%0A%20%20%20%20el%2Ewidth%20%3D%20width%3B%0 [...]
+<script src="data:application/x-javascript,%2F%2A%20el%20is%20the%20%3Cspan%3E%2C%20holding%20x%20as%20el%2ErglPlayer%0A%20%20%20x%20is%20the%20JSON%20encoded%20playwidget%2E%0A%20%20%20instance%20holds%20x%20as%20instance%2ErglPlayer%0A%2A%2F%0A%0AHTMLWidgets%2Ewidget%28%7B%0A%0A%20%20name%3A%20%27rglPlayer%27%2C%0A%0A%20%20type%3A%20%27output%27%2C%0A%0A%20%20initialize%3A%20function%28el%2C%20width%2C%20height%29%20%7B%0A%20%20%20%20return%20%7B%0A%20%20%20%20%7D%3B%0A%0A%20%20%7D%2C% [...]
+
+
+<style type="text/css">code{white-space: pre;}</style>
+<style type="text/css">
+table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
+  margin: 0; padding: 0; vertical-align: baseline; border: none; }
+table.sourceCode { width: 100%; line-height: 100%; }
+td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
+td.sourceCode { padding-left: 5px; }
+code > span.kw { color: #007020; font-weight: bold; }
+code > span.dt { color: #902000; }
+code > span.dv { color: #40a070; }
+code > span.bn { color: #40a070; }
+code > span.fl { color: #40a070; }
+code > span.ch { color: #4070a0; }
+code > span.st { color: #4070a0; }
+code > span.co { color: #60a0b0; font-style: italic; }
+code > span.ot { color: #007020; }
+code > span.al { color: #ff0000; font-weight: bold; }
+code > span.fu { color: #06287e; }
+code > span.er { color: #ff0000; font-weight: bold; }
+</style>
+<style type="text/css">
+  pre:not([class]) {
+    background-color: white;
+  }
+</style>
+
+
+<link href="data:text/css,body%20%7B%0A%20%20background%2Dcolor%3A%20%23fff%3B%0A%20%20margin%3A%201em%20auto%3B%0A%20%20max%2Dwidth%3A%20700px%3B%0A%20%20overflow%3A%20visible%3B%0A%20%20padding%2Dleft%3A%202em%3B%0A%20%20padding%2Dright%3A%202em%3B%0A%20%20font%2Dfamily%3A%20%22Open%20Sans%22%2C%20%22Helvetica%20Neue%22%2C%20Helvetica%2C%20Arial%2C%20sans%2Dserif%3B%0A%20%20font%2Dsize%3A%2014px%3B%0A%20%20line%2Dheight%3A%201%2E35%3B%0A%7D%0A%0A%23header%20%7B%0A%20%20text%2Dalign%3A% [...]
+
+</head>
+
+<body>
+
+
+
+<div id="header">
+<h1 class="title">User Interaction in WebGL</h1>
+<h4 class="author"><em>Duncan Murdoch</em></h4>
+<h4 class="date"><em>January 04, 2016</em></h4>
+</div>
+
+<div id="TOC">
+<ul>
+<li><a href="#introduction">Introduction</a></li>
+<li><a href="#browser-support">Browser support</a></li>
+<li><a href="#examples">Examples</a></li>
+<li><a href="#autogenerated-controls">Autogenerated controls</a></li>
+<li><a href="#user-defined-mouse-controls">User defined mouse controls</a></li>
+<li><a href="#reference-for-rglclass">Reference for <code>rglClass</code></a><ul>
+<li><a href="#methods">Methods</a></li>
+<li><a href="#properties">Properties</a></li>
+</ul></li>
+<li><a href="#index">Index</a></li>
+</ul>
+</div>
+
+<pre><code>## Warning: These vignettes assume pandoc version 1.13.1; older versions may
+## give poor formatting.</code></pre>
+<style>
+    .nostripes tr.even {background-color: white;}
+    table {border-style: none;}
+    table th {border-style: none;}
+    table td {border-style: none;}
+    a[href^=".."] {text-decoration: underline;}
+    </style>
+    
+
+<div id="introduction" class="section level2">
+<h2>Introduction</h2>
+<p>This document describes how to embed <code>rgl</code> scenes in HTML documents and use embedded Javascript to control a WebGL display in an HTML document. For more general information, see <a href="rgl.html">rgl Overview</a>.</p>
+<p>We assume that the HTML document is produced from R markdown source using <code>knitr</code> or <code>rmarkdown</code>. This format mixes text with Markdown markup with chunks of R code.</p>
+<p>There are two ways to embed an <code>rgl</code> scene in the document. The older one is to use the chunk option <code>webgl = TRUE</code>. With that option, whatever <code>rgl</code> scene is active at the end of the chunk will be embedded. See the <a href="../../rgl/help/setupKnitr"><code>setupKnitr</code></a> help page for chunk options.</p>
+<p>The second way is to use a call to <a href="../../rglwidget/help/rglwidget"><code>rglwidget</code></a> from the <code>rglwidget</code> package. Each call to this function will insert a scene into the document. Do not set <code>webgl = TRUE</code>.</p>
+</div>
+<div id="browser-support" class="section level2">
+<h2>Browser support</h2>
+<p>Most browsers now support WebGL, but it may be disabled by default. See <a href="http://get.webgl.org">http://get.webgl.org</a> for help on a number of different browsers.</p>
+<p>If you are using the internal browser in RStudio, support varies by version. I believe it is enabled by default in Windows versions, but not in all Mac OSX versions. You can run this command:</p>
+<pre><code>defaults write org.rstudio.RStudio WebKitWebGLEnabled -bool YES</code></pre>
+<p>to enable it. I do not have much experience with RStudio in Linux, but it does seem that WebGL is enabled there.</p>
+<p>Both methods make use of functions from the <code>rglwidget</code> package, so you will need to install it. The second method is easier for me to maintain, so it is likely to receive more support in the future, but for now both methods are supported, and there are examples of both in this document.</p>
+</div>
+<div id="examples" class="section level2">
+<h2>Examples</h2>
+<p>We start with two simple examples. The next section gives reference information.</p>
+<p>Consider the simple plot of the iris data. We insert a code chunk and call the <a href="../../rglwidget/help/rglwidget"><code>rglwidget</code></a> function with optional argument <code>elementId</code>. This allows later Javascript code to refer to the image.</p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(rgl)
+<span class="kw">library</span>(rglwidget)
+<span class="kw">with</span>(iris, <span class="kw">plot3d</span>(Sepal.Length, Sepal.Width, Petal.Length, 
+                  <span class="dt">type=</span><span class="st">"s"</span>, <span class="dt">col=</span><span class="kw">as.numeric</span>(Species)))
+subid <-<span class="st"> </span><span class="kw">currentSubscene3d</span>()
+<span class="kw">rglwidget</span>(<span class="dt">elementId=</span><span class="st">"plot3drgl"</span>)</code></pre>
+<p><div id="plot3drgl" style="width:480px;height:480px;" class="rglWebGL"></div>
+<script type="application/json" data-for="plot3drgl">{"x":{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":1,"objects":{ [...]
+<pre><code><button type="button" onclick="rotate(10)">Forward</button>
+<button type="button" onclick="rotate(-10)">Backward</button></code></pre>
+which produces these buttons:
+<button type="button" onclick="rotate(10)">
+Forward
+</button>
+<button type="button" onclick="rotate(-10)">
+Backward
+</button>
+
+<p>We stored the subscene number that is currently active in <code>subid</code> in the code chunk above, and use it as <code class="r"><code>`r subid`</code></code> in the script below. <code>knitr</code> substitutes the value 1 when it processes the document.</p>
+<p>The <code>rotate()</code> function uses the Javascript function <code>document.getElementById</code> to retrieve the <code><div></code> component of the web page containing the scene. It will have a component named <code>rglinstance</code> which contains information about the scene that we can modify:</p>
+<pre><code><script type="text/javascript">
+var rotate = function(angle) {
+  var rgl = document.getElementById("plot3drgl").rglinstance;
+  rgl.getObj(`r subid`).par3d.userMatrix.rotate(angle, 0,1,0);
+  rgl.drawScene();
+};
+</script></code></pre>
+<script type="text/javascript">
+var rotate = function(angle) {
+  var rgl = document.getElementById("plot3drgl").rglinstance;
+  rgl.getObj(1).par3d.userMatrix.rotate(angle, 0,1,0);
+  rgl.drawScene();
+};
+</script>
+
+<p>If we had used <code>webGL=TRUE</code> in the chunk header, the <code>knitr</code> WebGL support create a global object with a name of the form <code><chunkname>rgl</code>. For example, if the code chunk was named <code>plot3d</code>, the object would be called <code>plot3drgl</code>, and this code would work:</p>
+<pre><code><script type="text/javascript">
+var rotate = function(angle) {
+  plot3drgl.getObj(`r subid`).par3d.userMatrix.rotate(angle, 0,1,0);
+  plot3drgl.drawScene();
+};
+</script></code></pre>
+</div>
+<div id="autogenerated-controls" class="section level2">
+<h2>Autogenerated controls</h2>
+<p>We can also change the contents of the plot using <a name="toggleButton"><a href="#toggleButton"><code>toggleButton</code></a></a>. For example, we can redo the previous plot, but with the three species as separate “spheres” objects and buttons to toggle them:</p>
+<pre class="sourceCode r"><code class="sourceCode r">sphereid <-<span class="st"> </span><span class="kw">with</span>(<span class="kw">subset</span>(iris, Species ==<span class="st"> "setosa"</span>), 
+     <span class="kw">spheres3d</span>(Sepal.Length, Sepal.Width, Petal.Length, 
+                  <span class="dt">col=</span><span class="kw">as.numeric</span>(Species),
+                  <span class="dt">radius =</span> <span class="fl">0.211</span>))
+<span class="kw">with</span>(<span class="kw">subset</span>(iris, Species ==<span class="st"> "versicolor"</span>), 
+     <span class="kw">spheres3d</span>(Sepal.Length, Sepal.Width, Petal.Length, 
+               <span class="dt">col=</span><span class="kw">as.numeric</span>(Species),
+               <span class="dt">radius =</span> <span class="fl">0.211</span>))
+<span class="kw">with</span>(<span class="kw">subset</span>(iris, Species ==<span class="st"> "virginica"</span>), 
+     <span class="kw">spheres3d</span>(Sepal.Length, Sepal.Width, Petal.Length, 
+               <span class="dt">col=</span><span class="kw">as.numeric</span>(Species),
+               <span class="dt">radius =</span> <span class="fl">0.211</span>))
+<span class="kw">aspect3d</span>(<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">1</span>)
+axesid <-<span class="st"> </span><span class="kw">decorate3d</span>()
+subid <-<span class="st"> </span><span class="kw">currentSubscene3d</span>()</code></pre>
+<script>CanvasMatrix4=function(m){if(typeof m=='object'){if("length"in m&&m.length>=16){this.load(m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11],m[12],m[13],m[14],m[15]);return}else if(m instanceof CanvasMatrix4){this.load(m);return}}this.makeIdentity()};CanvasMatrix4.prototype.load=function(){if(arguments.length==1&&typeof arguments[0]=='object'){var matrix=arguments[0];if("length"in matrix&&matrix.length==16){this.m11=matrix[0];this.m12=matrix[1];this.m13=matrix[2];this. [...]
+<script>
+rglwidgetClass = function() {
+this.canvas = null;
+this.userMatrix = new CanvasMatrix4();
+this.types = [];
+this.prMatrix = new CanvasMatrix4();
+this.mvMatrix = new CanvasMatrix4();
+this.vp = null;
+this.prmvMatrix = null;
+this.origs = null;
+this.gl = null;
+this.scene = null;
+};
+(function() {
+this.multMV = function(M, v) {
+return [ M.m11 * v[0] + M.m12 * v[1] + M.m13 * v[2] + M.m14 * v[3],
+M.m21 * v[0] + M.m22 * v[1] + M.m23 * v[2] + M.m24 * v[3],
+M.m31 * v[0] + M.m32 * v[1] + M.m33 * v[2] + M.m34 * v[3],
+M.m41 * v[0] + M.m42 * v[1] + M.m43 * v[2] + M.m44 * v[3]
+];
+};
+this.vlen = function(v) {
+return Math.sqrt(this.dotprod(v, v));
+};
+this.dotprod = function(a, b) {
+return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
+}
+this.xprod = function(a, b) {
+return [a[1]*b[2] - a[2]*b[1],
+a[2]*b[0] - a[0]*b[2],
+a[0]*b[1] - a[1]*b[0]];
+};
+this.cbind = function(a, b) {
+return a.map(function(currentValue, index, array) {
+return currentValue.concat(b[index]);
+});
+};
+this.swap = function(a, i, j) {
+var temp = a[i];
+a[i] = a[j];
+a[j] = temp;
+};
+this.flatten = function(a) {
+return [].concat.apply([], a);
+};
+/* set element of 1d or 2d array as if it was flattened.  Column major, zero based! */
+this.setElement = function(a, i, value) {
+if (Array.isArray(a[0])) {
+var dim = a.length,
+col = Math.floor(i/dim),
+row = i % dim;
+a[row][col] = value;
+} else {
+a[i] = value;
+}
+};
+this.transpose = function(a) {
+var newArray = [],
+n = a.length,
+m = a[0].length,
+i;
+for(i = 0; i < m; i++){
+newArray.push([]);
+}
+for(i = 0; i < n; i++){
+for(var j = 0; j < m; j++){
+newArray[j].push(a[i][j]);
+}
+}
+return newArray;
+};
+this.sumsq = function(x) {
+var result = 0, i;
+for (i=0; i < x.length; i++)
+result += x[i]*x[i];
+return result;
+};
+this.toCanvasMatrix4 = function(mat) {
+if (mat instanceof CanvasMatrix4)
+return mat;
+var result = new CanvasMatrix4();
+mat = this.flatten(this.transpose(mat));
+result.load(mat);
+return result;
+};
+this.stringToRgb = function(s) {
+s = s.replace("#", "");
+var bigint = parseInt(s, 16);
+return [((bigint >> 16) & 255)/255,
+((bigint >> 8) & 255)/255,
+(bigint & 255)/255];
+};
+this.componentProduct = function(x, y) {
+if (typeof y === "undefined") {
+this.alertOnce("Bad arg to componentProduct");
+}
+var result = new Float32Array(3), i;
+for (i = 0; i<3; i++)
+result[i] = x[i]*y[i];
+return result;
+};
+this.getPowerOfTwo = function(value) {
+var pow = 1;
+while(pow<value) {
+pow *= 2;
+}
+return pow;
+};
+this.unique = function(arr) {
+arr = [].concat(arr);
+return arr.filter(function(value, index, self) {
+return self.indexOf(value) === index;
+});
+};
+this.repeatToLen = function(arr, len) {
+arr = [].concat(arr);
+while (arr.length < len/2)
+arr = arr.concat(arr);
+return arr.concat(arr.slice(0, len - arr.length));
+};
+this.alertOnce = function(msg) {
+if (typeof this.alerted !== "undefined")
+return;
+this.alerted = true;
+alert(msg);
+};
+this.f_is_lit = 1;
+this.f_is_smooth = 2;
+this.f_has_texture = 4;
+this.f_is_indexed = 8;
+this.f_depth_sort = 16;
+this.f_fixed_quads = 32;
+this.f_is_transparent = 64;
+this.f_is_lines = 128;
+this.f_sprites_3d = 256;
+this.f_sprite_3d = 512;
+this.f_is_subscene = 1024;
+this.f_is_clipplanes = 2048;
+this.whichList = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags;
+if (obj.type === "light")
+return "lights";
+if (flags & this.f_is_subscene)
+return "subscenes";
+if (flags & this.f_is_clipplanes)
+return "clipplanes";
+if (flags & this.f_is_transparent)
+return "transparent";
+return "opaque";
+};
+this.getObj = function(id) {
+if (typeof id !== "number") {
+this.alertOnce("getObj id is "+typeof id);
+}
+return this.scene.objects[id];
+};
+this.getIdsByType = function(type, subscene) {
+var
+result = [], i, self = this;
+if (typeof subscene === "undefined") {
+Object.keys(this.scene.objects).forEach(
+function(key) {
+key = parseInt(key, 10);
+if (self.getObj(key).type === type)
+result.push(key);
+});
+} else {
+ids = this.getObj(subscene).objects;
+for (i=0; i < ids.length; i++) {
+if (this.getObj(ids[i]).type === type) {
+result.push(ids[i]);
+}
+}
+}
+return result;
+};
+this.getMaterial = function(id, property) {
+var obj = this.getObj(id),
+mat = obj.material[property];
+if (typeof mat === "undefined")
+mat = this.scene.material[property];
+return mat;
+};
+this.inSubscene = function(id, subscene) {
+return this.getObj(subscene).objects.indexOf(id) > -1;
+};
+this.addToSubscene = function(id, subscene) {
+var thelist,
+thesub = this.getObj(subscene),
+ids = [id],
+obj = this.getObj(id), i;
+if (typeof obj.newIds !== "undefined") {
+ids = ids.concat(obj.newIds);
+}
+for (i = 0; i < ids.length; i++) {
+id = ids[i];
+if (thesub.objects.indexOf(id) == -1) {
+thelist = this.whichList(id);
+thesub.objects.push(id);
+thesub[thelist].push(id);
+}
+}
+};
+this.delFromSubscene = function(id, subscene) {
+var thelist,
+thesub = this.getObj(subscene),
+obj = this.getObj(id),
+ids = [id], i, newIds;
+if (typeof obj.newIds !== "undefined")
+ids = ids.concat(obj.newIds);
+for (j=0; j<ids.length;j++) {
+id = ids[j];
+i = thesub.objects.indexOf(id);
+if (i > -1) {
+thesub.objects.splice(i, 1);
+thelist = this.whichList(id);
+i = thesub[thelist].indexOf(id);
+thesub[thelist].splice(i, 1);
+}
+}
+};
+this.setSubsceneEntries = function(ids, subsceneid) {
+var sub = this.getObj(subsceneid);
+sub.objects = ids;
+this.initSubscene(subsceneid);
+};
+this.getSubsceneEntries = function(subscene) {
+return this.getObj(subscene).objects;
+};
+this.getChildSubscenes = function(subscene) {
+return this.getObj(subscene).subscenes;
+};
+this.getVertexShader = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags,
+type = obj.type,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+sprites_3d = flags & this.f_sprites_3d,
+sprite_3d = flags & this.f_sprite_3d,
+nclipplanes = this.countClipplanes(),
+result;
+if (type === "clipplanes" || sprites_3d) return;
+result = "  /* ****** "+type+" object "+id+" vertex shader ****** */\n"+
+"   attribute vec3 aPos;\n"+
+"   attribute vec4 aCol;\n"+
+" uniform mat4 mvMatrix;\n"+
+" uniform mat4 prMatrix;\n"+
+" varying vec4 vCol;\n"+
+" varying vec4 vPosition;\n";
+if (is_lit && !fixed_quads)
+result = result + " attribute vec3 aNorm;\n"+
+" uniform mat4 normMatrix;\n"+
+" varying vec3 vNormal;\n";
+if (has_texture || type === "text")
+result = result + " attribute vec2 aTexcoord;\n"+
+" varying vec2 vTexcoord;\n";
+if (type === "text")
+result = result + " uniform vec2 textScale;\n";
+if (fixed_quads)
+result = result + " attribute vec2 aOfs;\n";
+else if (sprite_3d)
+result = result + " uniform vec3 uOrig;\n"+
+" uniform float uSize;\n"+
+" uniform mat4 usermat;\n";
+result = result + " void main(void) {\n";
+if (nclipplanes || (!fixed_quads && !sprite_3d))
+result = result + "   vPosition = mvMatrix * vec4(aPos, 1.);\n";
+if (!fixed_quads && !sprite_3d)
+result = result + "   gl_Position = prMatrix * vPosition;\n";
+if (type == "points") {
+var size = this.getMaterial(id, "size");
+result = result + "   gl_PointSize = "+size.toFixed(1)+";\n";
+}
+result = result + "   vCol = aCol;\n";
+if (is_lit && !fixed_quads && !sprite_3d)
+result = result + "   vNormal = normalize((normMatrix * vec4(aNorm, 1.)).xyz);\n";
+if (has_texture || type === "text")
+result = result + "   vTexcoord = aTexcoord;\n";
+if (type == "text")
+result = result + "   vec4 pos = prMatrix * mvMatrix * vec4(aPos, 1.);\n"+
+"   pos = pos/pos.w;\n"+
+"   gl_Position = pos + vec4(aOfs*textScale, 0.,0.);\n";
+if (type == "sprites")
+result = result + "   vec4 pos = mvMatrix * vec4(aPos, 1.);\n"+
+"   pos = pos/pos.w + vec4(aOfs, 0., 0.);\n"+
+"   gl_Position = prMatrix*pos;\n";
+if (sprite_3d)
+result = result + "   vNormal = normalize((normMatrix * vec4(aNorm, 1.)).xyz);\n"+
+"   vec4 pos = mvMatrix * vec4(uOrig, 1.);\n"+
+"   vPosition = pos/pos.w + vec4(uSize*(vec4(aPos, 1.)*usermat).xyz,0.);\n"+
+"   gl_Position = prMatrix * vPosition;\n";
+result = result + " }\n";
+return result;
+};
+this.getFragmentShader = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags,
+type = obj.type,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+sprites_3d = flags & this.f_sprites_3d,
+nclipplanes = this.countClipplanes(), i,
+texture_format, nlights,
+result;
+if (type === "clipplanes" || sprites_3d) return;
+if (has_texture)
+texture_format = this.getMaterial(id, "textype");
+result = "/* ****** "+type+" object "+id+" fragment shader ****** */\n"+
+"#ifdef GL_ES\n"+
+"  precision highp float;\n"+
+"#endif\n"+
+"  varying vec4 vCol; // carries alpha\n"+
+"  varying vec4 vPosition;\n";
+if (has_texture || type === "text")
+result = result + " varying vec2 vTexcoord;\n"+
+" uniform sampler2D uSampler;\n";
+if (is_lit && !fixed_quads)
+result = result + " varying vec3 vNormal;\n";
+for (i = 0; i < nclipplanes; i++)
+result = result + " uniform vec4 vClipplane"+i+";\n";
+if (is_lit) {
+nlights = this.countLights();
+if (nlights)
+result = result + " uniform mat4 mvMatrix;\n";
+else
+is_lit = false;
+}
+if (is_lit) {
+result = result + "   uniform vec3 emission;\n"+
+"   uniform float shininess;\n";
+for (i=0; i < nlights; i++) {
+result = result + "   uniform vec3 ambient" + i + ";\n"+
+"   uniform vec3 specular" + i +"; // light*material\n"+
+"   uniform vec3 diffuse" + i + ";\n"+
+"   uniform vec3 lightDir" + i + ";\n"+
+"   uniform bool viewpoint" + i + ";\n"+
+"   uniform bool finite" + i + ";\n";
+}
+}
+result = result + " void main(void) {\n";
+for (i=0; i < nclipplanes;i++)
+result = result + "   if (dot(vPosition, vClipplane"+i+") < 0.0) discard;\n";
+if (is_lit) {
+result = result + "   vec3 eye = normalize(-vPosition.xyz);\n"+
+"   vec3 lightdir;\n"+
+"   vec4 colDiff;\n"+
+"   vec3 halfVec;\n"+
+"   vec4 lighteffect = vec4(emission, 0.);\n"+
+"   vec3 col;\n"+
+"   float nDotL;\n";
+if (fixed_quads) {
+result = result +   "     vec3 n = vec3(0., 0., 1.);\n";
+}
+else {
+result = result +   "     vec3 n = normalize(vNormal);\n"+
+"   n = -faceforward(n, n, eye);\n";
+}
+for (i=0; i < nlights; i++) {
+result = result + "   colDiff = vec4(vCol.rgb * diffuse" + i + ", vCol.a);\n"+
+"   lightdir = lightDir" + i + ";\n"+
+"   if (!viewpoint" + i +")\n"+
+"     lightdir = (mvMatrix * vec4(lightdir, 1.)).xyz;\n"+
+"   if (!finite" + i + ") {\n"+
+"     halfVec = normalize(lightdir + eye);\n"+
+"   } else {\n"+
+"     lightdir = normalize(lightdir - vPosition.xyz);\n"+
+"     halfVec = normalize(lightdir + eye);\n"+
+"   }\n"+
+"     col = ambient" + i + ";\n"+
+"   nDotL = dot(n, lightdir);\n"+
+"   col = col + max(nDotL, 0.) * colDiff.rgb;\n"+
+"   col = col + pow(max(dot(halfVec, n), 0.), shininess) * specular" + i + ";\n"+
+"   lighteffect = lighteffect + vec4(col, colDiff.a);\n";
+}
+} else {
+result = result +   "   vec4 colDiff = vCol;\n"+
+"     vec4 lighteffect = colDiff;\n";
+}
+if ((has_texture && texture_format === "rgba") || type === "text")
+result = result +   "     vec4 textureColor = lighteffect*texture2D(uSampler, vTexcoord);\n";
+if (has_texture) {
+result = result + {
+rgb:            "   vec4 textureColor = lighteffect*vec4(texture2D(uSampler, vTexcoord).rgb, 1.);\n",
+alpha:          "   vec4 textureColor = texture2D(uSampler, vTexcoord);\n"+
+"   float luminance = dot(vec3(1.,1.,1.), textureColor.rgb)/3.;\n"+
+"   textureColor =  vec4(lighteffect.rgb, lighteffect.a*luminance);\n",
+luminance:      "   vec4 textureColor = vec4(lighteffect.rgb*dot(texture2D(uSampler, vTexcoord).rgb, vec3(1.,1.,1.))/3., lighteffect.a);\n",
+"luminance.alpha":"   vec4 textureColor = texture2D(uSampler, vTexcoord);\n"+
+"   float luminance = dot(vec3(1.,1.,1.),textureColor.rgb)/3.;\n"+
+"   textureColor = vec4(lighteffect.rgb*luminance, lighteffect.a*textureColor.a);\n"
+}[texture_format]+
+"   gl_FragColor = textureColor;\n";
+} else if (type === "text") {
+result = result +   "     if (textureColor.a < 0.1)\n"+
+"     discard;\n"+
+"   else\n"+
+"     gl_FragColor = textureColor;\n";
+} else
+result = result +   "   gl_FragColor = lighteffect;\n";
+result = result + " }\n";
+return result;
+};
+this.getShader = function(shaderType, code) {
+var gl = this.gl, shader;
+shader = gl.createShader(shaderType);
+gl.shaderSource(shader, code);
+gl.compileShader(shader);
+if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) === 0)
+alert(gl.getShaderInfoLog(shader));
+return shader;
+};
+this.handleLoadedTexture = function(texture, textureCanvas) {
+var gl = this.gl;
+gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+gl.bindTexture(gl.TEXTURE_2D, texture);
+gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureCanvas);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+gl.generateMipmap(gl.TEXTURE_2D);
+gl.bindTexture(gl.TEXTURE_2D, null);
+};
+this.loadImageToTexture = function(uri, texture) {
+var canvas = this.textureCanvas,
+ctx = canvas.getContext("2d"),
+image = new Image(),
+self = this;
+image.onload = function() {
+var w = image.width,
+h = image.height,
+canvasX = self.getPowerOfTwo(w),
+canvasY = self.getPowerOfTwo(h),
+gl = self.gl,
+maxTexSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
+if (maxTexSize > 4096) maxTexSize = 4096;
+while (canvasX > 1 && canvasY > 1 && (canvasX > maxTexSize || canvasY > maxTexSize)) {
+canvasX /= 2;
+canvasY /= 2;
+}
+canvas.width = canvasX;
+canvas.height = canvasY;
+ctx.imageSmoothingEnabled = true;
+ctx.drawImage(image, 0, 0, canvasX, canvasY);
+self.handleLoadedTexture(texture, canvas);
+self.drawScene();
+};
+image.src = uri;
+};
+this.drawTextToCanvas = function(text, cex, family, font) {
+var canvasX, canvasY,
+textY,
+scaling = 20,
+textColour = "white",
+backgroundColour = "rgba(0,0,0,0)",
+canvas = this.textureCanvas,
+ctx = canvas.getContext("2d"),
+i, textHeights = [], widths = [], offset = 0, offsets = [],
+fontStrings = [],
+getFontString = function(i) {
+textHeights[i] = scaling*cex[i];
+var fontString = textHeights[i] + "px",
+family0 = family[i],
+font0 = font[i];
+if (family0 === "sans")
+family0 = "sans-serif";
+else if (family0 === "mono")
+family0 = "monospace";
+fontString = fontString + " " + family0;
+if (font0 === 2 || font0 === 4)
+fontString = "bold " + fontString;
+if (font0 === 3 || font0 === 4)
+fontString = "italic " + fontString;
+return fontString;
+};
+cex = this.repeatToLen(cex, text.length);
+family = this.repeatToLen(family, text.length);
+font = this.repeatToLen(font, text.length);
+canvasX = 1;
+for (i = 0; i < text.length; i++)  {
+ctx.font = fontStrings[i] = getFontString(i);
+widths[i] = ctx.measureText(text[i]).width;
+offset = offsets[i] = offset + 2*textHeights[i];
+canvasX = (widths[i] > canvasX) ? widths[i] : canvasX;
+}
+canvasX = this.getPowerOfTwo(canvasX);
+canvasY = this.getPowerOfTwo(offset);
+canvas.width = canvasX;
+canvas.height = canvasY;
+ctx.fillStyle = backgroundColour;
+ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
+ctx.textBaseline = "alphabetic";
+for(i = 0; i < text.length; i++) {
+textY = offsets[i];
+ctx.font = fontStrings[i];
+ctx.fillStyle = textColour;
+ctx.textAlign = "left";
+ctx.fillText(text[i], 0,  textY);
+}
+return {canvasX:canvasX, canvasY:canvasY,
+widths:widths, textHeights:textHeights,
+offsets:offsets};
+};
+this.setViewport = function(id) {
+var gl = this.gl,
+vp = this.getObj(id).par3d.viewport,
+x = vp.x*this.canvas.width,
+y = vp.y*this.canvas.height,
+width = vp.width*this.canvas.width,
+height = vp.height*this.canvas.height;
+this.vp = {x:x, y:y, width:width, height:height};
+gl.viewport(x, y, width, height);
+gl.scissor(x, y, width, height);
+};
+this.setprMatrix = function(id) {
+var subscene = this.getObj(id),
+embedding = subscene.embeddings.projection;
+if (embedding === "replace")
+this.prMatrix.makeIdentity();
+else
+this.setprMatrix(subscene.parent);
+if (embedding === "inherit")
+return;
+// This is based on the Frustum::enclose code from geom.cpp
+var bbox = subscene.par3d.bbox,
+scale = subscene.par3d.scale,
+ranges = [(bbox[1]-bbox[0])*scale[0]/2,
+(bbox[3]-bbox[2])*scale[1]/2,
+(bbox[5]-bbox[4])*scale[2]/2],
+radius = Math.sqrt(this.sumsq(ranges))*1.1; // A bit bigger to handle labels
+if (radius <= 0) radius = 1;
+var observer = subscene.par3d.observer,
+distance = observer[2],
+t = Math.tan(subscene.par3d.FOV*Math.PI/360),
+near = distance - radius,
+far = distance + radius,
+hlen = t*near,
+aspect = this.vp.width/this.vp.height,
+z = subscene.par3d.zoom;
+if (aspect > 1)
+this.prMatrix.frustum(-hlen*aspect*z, hlen*aspect*z,
+-hlen*z, hlen*z, near, far);
+else
+this.prMatrix.frustum(-hlen*z, hlen*z,
+-hlen*z/aspect, hlen*z/aspect,
+near, far);
+};
+this.setmvMatrix = function(id) {
+var observer = this.getObj(id).par3d.observer;
+this.mvMatrix.makeIdentity();
+this.setmodelMatrix(id);
+this.mvMatrix.translate(-observer[0], -observer[1], -observer[2]);
+};
+this.setmodelMatrix = function(id) {
+var subscene = this.getObj(id),
+embedding = subscene.embeddings.model;
+if (embedding !== "inherit") {
+var scale = subscene.par3d.scale,
+bbox = subscene.par3d.bbox,
+center = [(bbox[0]+bbox[1])/2,
+(bbox[2]+bbox[3])/2,
+(bbox[4]+bbox[5])/2];
+this.mvMatrix.translate(-center[0], -center[1], -center[2]);
+this.mvMatrix.scale(scale[0], scale[1], scale[2]);
+this.mvMatrix.multRight( subscene.par3d.userMatrix );
+}
+if (embedding !== "replace")
+this.setmodelMatrix(subscene.parent);
+};
+this.setnormMatrix = function(subsceneid) {
+var self = this,
+recurse = function(id) {
+var sub = self.getObj(id),
+embedding = sub.embeddings.model;
+if (embedding !== "inherit") {
+var scale = sub.par3d.scale;
+self.normMatrix.scale(1/scale[0], 1/scale[1], 1/scale[2]);
+self.normMatrix.multRight(sub.par3d.userMatrix);
+}
+if (embedding !== "replace")
+recurse(sub.parent);
+};
+self.normMatrix.makeIdentity();
+recurse(subsceneid);
+};
+this.setprmvMatrix = function() {
+this.prmvMatrix = new CanvasMatrix4( this.mvMatrix );
+this.prmvMatrix.multRight( this.prMatrix );
+};
+this.countClipplanes = function() {
+return this.countObjs("clipplanes");
+};
+this.countLights = function() {
+return this.countObjs("light");
+};
+this.countObjs = function(type) {
+var self = this,
+bound = 0;
+Object.keys(this.scene.objects).forEach(
+function(key) {
+if (self.getObj(parseInt(key, 10)).type === type)
+bound = bound + 1;
+});
+return bound;
+};
+this.initSubscene = function(id) {
+var sub = this.getObj(id),
+i, obj;
+if (sub.type !== "subscene")
+return;
+sub.par3d.userMatrix = this.toCanvasMatrix4(sub.par3d.userMatrix);
+sub.par3d.listeners = [].concat(sub.par3d.listeners);
+sub.backgroundId = undefined;
+sub.subscenes = [];
+sub.clipplanes = [];
+sub.transparent = [];
+sub.opaque = [];
+sub.lights = [];
+for (i=0; i < sub.objects.length; i++) {
+obj = this.getObj(sub.objects[i]);
+if (typeof obj === "undefined") {
+sub.objects.splice(i, 1);
+i--;
+} else if (obj.type === "background")
+sub.backgroundId = obj.id;
+else
+sub[this.whichList(obj.id)].push(obj.id);
+}
+};
+this.copyObj = function(id, reuse) {
+var obj = this.getObj(id),
+prev = document.getElementById(reuse).rglinstance,
+prevobj = prev.getObj(id),
+fields = ["flags", "type",
+"colors", "vertices", "centers",
+"normals", "offsets",
+"texts", "cex", "family", "font", "adj",
+"material",
+"radii",
+"texcoords",
+"userMatrix", "ids",
+"dim",
+"par3d", "userMatrix",
+"viewpoint", "finite"],
+i;
+for (i = 0; i < fields.length; i++) {
+if (typeof prevobj[fields[i]] !== "undefined")
+obj[fields[i]] = prevobj[fields[i]];
+}
+};
+this.planeUpdateTriangles = function(id, bbox) {
+var perms = [[0,0,1], [1,2,2], [2,1,0]],
+x, xrow, elem, A, d, nhits, i, j, k, u, v, w, intersect, which, v0, v2, vx, reverse,
+face1 = [], face2 = [], normals = [],
+obj = this.getObj(id),
+nPlanes = obj.normals.length;
+obj.bbox = bbox;
+obj.vertices = [];
+obj.initialized = false;
+for (elem = 0; elem < nPlanes; elem++) {
+//    Vertex Av = normal.getRecycled(elem);
+x = [];
+A = obj.normals[elem];
+d = obj.offsets[elem][0];
+nhits = 0;
+for (i=0; i<3; i++)
+for (j=0; j<2; j++)
+for (k=0; k<2; k++) {
+u = perms[0][i];
+v = perms[1][i];
+w = perms[2][i];
+if (A[w] != 0.0) {
+intersect = -(d + A[u]*bbox[j+2*u] + A[v]*bbox[k+2*v])/A[w];
+if (bbox[2*w] < intersect && intersect < bbox[1+2*w]) {
+xrow = [];
+xrow[u] = bbox[j+2*u];
+xrow[v] = bbox[k+2*v];
+xrow[w] = intersect;
+x.push(xrow);
+face1[nhits] = j + 2*u;
+face2[nhits] = k + 2*v;
+nhits++;
+}
+}
+}
+if (nhits > 3) {
+/* Re-order the intersections so the triangles work */
+for (i=0; i<nhits-2; i++) {
+which = 0; /* initialize to suppress warning */
+for (j=i+1; j<nhits; j++) {
+if (face1[i] == face1[j] || face1[i] == face2[j]
+|| face2[i] == face1[j] || face2[i] == face2[j] ) {
+which = j;
+break;
+}
+}
+if (which > i+1) {
+this.swap(x, i+1, which);
+this.swap(face1, i+1, which);
+this.swap(face2, i+1, which);
+}
+}
+}
+if (nhits >= 3) {
+/* Put in order so that the normal points out the FRONT of the faces */
+v0 = [x[0][0] - x[1][0] , x[0][1] - x[1][1], x[0][2] - x[1][2]];
+v2 = [x[2][0] - x[1][0] , x[2][1] - x[1][1], x[2][2] - x[1][2]];
+/* cross-product */
+vx = this.xprod(v0, v2);
+reverse = this.dotprod(vx, A) > 0;
+for (i=0; i<nhits-2; i++) {
+obj.vertices.push(x[0]);
+normals.push(A);
+for (j=1; j<3; j++) {
+obj.vertices.push(x[i + (reverse ? 3-j : j)]);
+normals.push(A);
+}
+}
+}
+}
+obj.pnormals = normals;
+};
+this.initObj = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags,
+type = obj.type,
+is_indexed = flags & this.f_is_indexed,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+depth_sort = flags & this.f_depth_sort,
+sprites_3d = flags & this.f_sprites_3d,
+sprite_3d = flags & this.f_sprite_3d,
+gl = this.gl,
+texinfo, drawtype, nclipplanes, f, frowsize, nrows,
+i,j,v, mat, uri, matobj;
+if (typeof id !== "number") {
+this.alertOnce("initObj id is "+typeof id);
+}
+obj.initialized = true;
+if (type === "background" || type === "bboxdeco" || type === "subscene")
+return;
+if (type === "light") {
+obj.ambient = new Float32Array(obj.colors[0].slice(0,3));
+obj.diffuse = new Float32Array(obj.colors[1].slice(0,3));
+obj.specular = new Float32Array(obj.colors[2].slice(0,3));
+obj.lightDir = new Float32Array(obj.vertices[0]);
+return;
+}
+if (type === "clipplanes") {
+obj.vClipplane = this.flatten(this.cbind(obj.normals, obj.offsets));
+return;
+}
+if (!sprites_3d) {
+obj.prog = gl.createProgram();
+gl.attachShader(obj.prog, this.getShader( gl.VERTEX_SHADER,
+this.getVertexShader(id) ));
+gl.attachShader(obj.prog, this.getShader( gl.FRAGMENT_SHADER,
+this.getFragmentShader(id) ));
+//  Force aPos to location 0, aCol to location 1
+gl.bindAttribLocation(obj.prog, 0, "aPos");
+gl.bindAttribLocation(obj.prog, 1, "aCol");
+gl.linkProgram(obj.prog);
+var linked = gl.getProgramParameter(obj.prog, gl.LINK_STATUS);
+if (!linked) {
+// An error occurred while linking
+var lastError = gl.getProgramInfoLog(program);
+console.warn("Error in program linking:" + lastError);
+gl.deleteProgram(program);
+}
+}
+if (type === "text") {
+texinfo = this.drawTextToCanvas(obj.texts,
+this.flatten(obj.cex),
+this.flatten(obj.family),
+this.flatten(obj.family));
+}
+if (fixed_quads && !sprites_3d) {
+obj.ofsLoc = gl.getAttribLocation(obj.prog, "aOfs");
+}
+if (sprite_3d) {
+obj.origLoc = gl.getUniformLocation(obj.prog, "uOrig");
+obj.sizeLoc = gl.getUniformLocation(obj.prog, "uSize");
+obj.usermatLoc = gl.getUniformLocation(obj.prog, "usermat");
+}
+if (has_texture || type == "text") {
+obj.texture = gl.createTexture();
+obj.texLoc = gl.getAttribLocation(obj.prog, "aTexcoord");
+obj.sampler = gl.getUniformLocation(obj.prog, "uSampler");
+}
+if (has_texture) {
+mat = obj.material;
+if (typeof mat.uri !== "undefined")
+uri = mat.uri;
+else if (typeof mat.uriElementId === "undefined") {
+matobj = this.getObj(mat.uriId);
+if (typeof matobj !== "undefined") {
+uri = matobj.material.uri;
+} else {
+uri = "";
+}
+} else
+uri = document.getElementById(mat.uriElementId).rglinstance.getObj(mat.uriId).material.uri;
+this.loadImageToTexture(uri, obj.texture);
+}
+if (type === "text") {
+this.handleLoadedTexture(obj.texture, this.textureCanvas);
+}
+v = obj.vertices;
+obj.vertexCount = v.length;
+if (!obj.vertexCount) return;
+var stride = 3, nc, cofs, nofs, radofs, oofs, tofs, vnew, v1;
+nc = obj.colorCount = obj.colors.length;
+if (nc > 1) {
+cofs = stride;
+stride = stride + 4;
+v = this.cbind(v, obj.colors);
+} else {
+cofs = -1;
+obj.onecolor = this.flatten(obj.colors);
+}
+if (typeof obj.normals !== "undefined") {
+nofs = stride;
+stride = stride + 3;
+v = this.cbind(v, typeof obj.pnormals !== "undefined" ? obj.pnormals : obj.normals);
+} else
+nofs = -1;
+if (typeof obj.radii !== "undefined") {
+radofs = stride;
+stride = stride + 1;
+if (obj.radii.length === v.length) {
+v = this.cbind(v, obj.radii);
+} else if (obj.radii.length === 1) {
+v = v.map(function(row, i, arr) { return row.concat(obj.radii[0]);});
+}
+} else
+radofs = -1;
+if (type == "sprites" && !sprites_3d) {
+tofs = stride;
+stride += 2;
+oofs = stride;
+stride += 2;
+vnew = new Array(4*v.length);
+var size = obj.radii, s = size[0]/2;
+for (i=0; i < v.length; i++) {
+if (size.length > 1)
+s = size[i]/2;
+vnew[4*i]  = v[i].concat([0,0,-s,-s]);
+vnew[4*i+1]= v[i].concat([1,0, s,-s]);
+vnew[4*i+2]= v[i].concat([1,1, s, s]);
+vnew[4*i+3]= v[i].concat([0,1,-s, s]);
+}
+v = vnew;
+obj.vertexCount = v.length;
+} else if (type === "text") {
+tofs = stride;
+stride += 2;
+oofs = stride;
+stride += 2;
+vnew = new Array(4*v.length);
+for (i=0; i < v.length; i++) {
+vnew[4*i]  = v[i].concat([0,-0.5]).concat(obj.adj[0]);
+vnew[4*i+1]= v[i].concat([1,-0.5]).concat(obj.adj[0]);
+vnew[4*i+2]= v[i].concat([1, 1.5]).concat(obj.adj[0]);
+vnew[4*i+3]= v[i].concat([0, 1.5]).concat(obj.adj[0]);
+for (j=0; j < 4; j++) {
+v1 = vnew[4*i+j];
+v1[tofs+2] = 2*(v1[tofs]-v1[tofs+2])*texinfo.widths[i];
+v1[tofs+3] = 2*(v1[tofs+1]-v1[tofs+3])*texinfo.textHeights[i];
+v1[tofs] *= texinfo.widths[i]/texinfo.canvasX;
+v1[tofs+1] = 1.0-(texinfo.offsets[i] -
+v1[tofs+1]*texinfo.textHeights[i])/texinfo.canvasY;
+vnew[4*i+j] = v1;
+}
+}
+v = vnew;
+obj.vertexCount = v.length;
+} else if (typeof obj.texcoords !== "undefined") {
+tofs = stride;
+stride += 2;
+oofs = -1;
+v = this.cbind(v, obj.texcoords);
+} else {
+tofs = -1;
+oofs = -1;
+}
+if (stride !== v[0].length) {
+this.alertOnce("problem in stride calculation");
+}
+obj.vOffsets = {vofs:0, cofs:cofs, nofs:nofs, radofs:radofs, oofs:oofs, tofs:tofs, stride:stride};
+obj.values = new Float32Array(this.flatten(v));
+if (sprites_3d) {
+obj.userMatrix = new CanvasMatrix4(obj.userMatrix);
+obj.objects = this.flatten([].concat(obj.ids));
+is_lit = false;
+}
+if (is_lit && !fixed_quads) {
+obj.normLoc = gl.getAttribLocation(obj.prog, "aNorm");
+}
+nclipplanes = this.countClipplanes();
+if (nclipplanes && !sprites_3d) {
+obj.clipLoc = [];
+for (i=0; i < nclipplanes; i++)
+obj.clipLoc[i] = gl.getUniformLocation(obj.prog,"vClipplane" + i);
+}
+if (is_lit) {
+obj.emissionLoc = gl.getUniformLocation(obj.prog, "emission");
+obj.emission = new Float32Array(this.stringToRgb(this.getMaterial(id, "emission")));
+obj.shininessLoc = gl.getUniformLocation(obj.prog, "shininess");
+obj.shininess = this.getMaterial(id, "shininess");
+obj.nlights = this.countLights();
+obj.ambientLoc = [];
+obj.ambient = new Float32Array(this.stringToRgb(this.getMaterial(id, "ambient")));
+obj.specularLoc = [];
+obj.specular = new Float32Array(this.stringToRgb(this.getMaterial(id, "specular")));
+obj.diffuseLoc = [];
+obj.lightDirLoc = [];
+obj.viewpointLoc = [];
+obj.finiteLoc = [];
+for (i=0; i < obj.nlights; i++) {
+obj.ambientLoc[i] = gl.getUniformLocation(obj.prog, "ambient" + i);
+obj.specularLoc[i] = gl.getUniformLocation(obj.prog, "specular" + i);
+obj.diffuseLoc[i] = gl.getUniformLocation(obj.prog, "diffuse" + i);
+obj.lightDirLoc[i] = gl.getUniformLocation(obj.prog, "lightDir" + i);
+obj.viewpointLoc[i] = gl.getUniformLocation(obj.prog, "viewpoint" + i);
+obj.finiteLoc[i] = gl.getUniformLocation(obj.prog, "finite" + i);
+}
+}
+if (is_indexed) {
+if ((type === "quads" || type === "text" ||
+type === "sprites") && !sprites_3d) {
+nrows = Math.floor(obj.vertexCount/4);
+f = Array(6*nrows);
+for (i=0; i < nrows; i++) {
+f[6*i] = 4*i;
+f[6*i+1] = 4*i + 1;
+f[6*i+2] = 4*i + 2;
+f[6*i+3] = 4*i;
+f[6*i+4] = 4*i + 2;
+f[6*i+5] = 4*i + 3;
+}
+frowsize = 6;
+} else if (type === "triangles") {
+nrows = Math.floor(obj.vertexCount/3);
+f = Array(3*nrows);
+for (i=0; i < f.length; i++) {
+f[i] = i;
+}
+frowsize = 3;
+} else if (type === "spheres") {
+nrows = obj.vertexCount;
+f = Array(nrows);
+for (i=0; i < f.length; i++) {
+f[i] = i;
+}
+frowsize = 1;
+} else if (type === "surface") {
+var dim = obj.dim[0],
+nx = dim[0],
+nz = dim[1];
+f = [];
+for (j=0; j<nx-1; j++) {
+for (i=0; i<nz-1; i++) {
+f.push(j + nx*i,
+j + nx*(i+1),
+j + 1 + nx*(i+1),
+j + nx*i,
+j + 1 + nx*(i+1),
+j + 1 + nx*i);
+}
+}
+frowsize = 6;
+}
+obj.f = new Uint16Array(f);
+if (depth_sort) {
+drawtype = "DYNAMIC_DRAW";
+} else {
+drawtype = "STATIC_DRAW";
+}
+}
+if (type !== "spheres" && !sprites_3d) {
+obj.buf = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, obj.values, gl.STATIC_DRAW); //
+}
+if (is_indexed && type !== "spheres" && !sprites_3d) {
+obj.ibuf = gl.createBuffer();
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, obj.ibuf);
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, obj.f, gl[drawtype]);
+}
+if (!sprites_3d) {
+obj.mvMatLoc = gl.getUniformLocation(obj.prog, "mvMatrix");
+obj.prMatLoc = gl.getUniformLocation(obj.prog, "prMatrix");
+}
+if (type === "text") {
+obj.textScaleLoc = gl.getUniformLocation(obj.prog, "textScale");
+}
+if (is_lit && !sprites_3d) {
+obj.normMatLoc = gl.getUniformLocation(obj.prog, "normMatrix");
+}
+};
+this.setDepthTest = function(id) {
+var gl = this.gl,
+tests = {never: gl.NEVER,
+less:  gl.LESS,
+equal: gl.EQUAL,
+lequal:gl.LEQUAL,
+greater: gl.GREATER,
+notequal: gl.NOTEQUAL,
+gequal: gl.GEQUAL,
+always: gl.ALWAYS},
+test = tests[this.getMaterial(id, "depth_test")];
+gl.depthFunc(test);
+};
+this.mode4type = {points : "POINTS",
+linestrip : "LINE_STRIP",
+abclines : "LINES",
+lines : "LINES",
+sprites : "TRIANGLES",
+planes : "TRIANGLES",
+text : "TRIANGLES",
+quads : "TRIANGLES",
+surface : "TRIANGLES",
+triangles : "TRIANGLES"};
+this.drawObj = function(id, subsceneid) {
+var obj = this.getObj(id),
+subscene = this.getObj(subsceneid),
+flags = obj.flags,
+type = obj.type,
+is_indexed = flags & this.f_is_indexed,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+depth_sort = flags & this.f_depth_sort,
+sprites_3d = flags & this.f_sprites_3d,
+sprite_3d = flags & this.f_sprite_3d,
+is_lines = flags & this.f_is_lines,
+gl = this.gl,
+sphereMV, baseofs, ofs, sscale, i, count, light,
+faces;
+if (typeof id !== "number") {
+this.alertOnce("drawObj id is "+typeof id);
+}
+if (type === "planes") {
+if (obj.bbox !== subscene.par3d.bbox || !obj.initialized) {
+this.planeUpdateTriangles(id, subscene.par3d.bbox);
+}
+}
+if (!obj.initialized)
+this.initObj(id);
+if (type === "light" || type === "bboxdeco")
+return;
+if (type === "clipplanes") {
+count = obj.offsets.length;
+var IMVClip = [];
+for (i=0; i < count; i++) {
+IMVClip[i] = this.multMV(this.invMatrix, obj.vClipplane.slice(4*i, 4*(i+1)));
+}
+obj.IMVClip = IMVClip;
+return;
+}
+this.setDepthTest(id);
+if (sprites_3d) {
+var norigs = obj.vertices.length,
+savenorm = new CanvasMatrix4(this.normMatrix);
+this.origs = obj.vertices;
+this.usermat = new Float32Array(obj.userMatrix.getAsArray());
+this.radii = obj.radii;
+this.normMatrix = subscene.spriteNormmat;
+for (this.iOrig=0; this.iOrig < norigs; this.iOrig++) {
+for (i=0; i < obj.objects.length; i++) {
+this.drawObj(obj.objects[i], subsceneid);
+}
+}
+this.normMatrix = savenorm;
+return;
+} else {
+gl.useProgram(obj.prog);
+}
+if (sprite_3d) {
+gl.uniform3fv(obj.origLoc, new Float32Array(this.origs[this.iOrig]));
+if (this.radii.length > 1) {
+gl.uniform1f(obj.sizeLoc, this.radii[this.iOrig][0]);
+} else {
+gl.uniform1f(obj.sizeLoc, this.radii[0][0]);
+}
+gl.uniformMatrix4fv(obj.usermatLoc, false, this.usermat);
+}
+if (type === "spheres") {
+gl.bindBuffer(gl.ARRAY_BUFFER, this.sphere.buf);
+} else {
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+}
+if (is_indexed && type !== "spheres") {
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, obj.ibuf);
+} else if (type === "spheres") {
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.sphere.ibuf);
+}
+gl.uniformMatrix4fv( obj.prMatLoc, false, new Float32Array(this.prMatrix.getAsArray()) );
+gl.uniformMatrix4fv( obj.mvMatLoc, false, new Float32Array(this.mvMatrix.getAsArray()) );
+var clipcheck = 0,
+clipplaneids = subscene.clipplanes,
+clip, j;
+for (i=0; i < clipplaneids.length; i++) {
+clip = this.getObj(clipplaneids[i]);
+for (j=0; j < clip.offsets.length; j++) {
+gl.uniform4fv(obj.clipLoc[clipcheck + j], clip.IMVClip[j]);
+}
+clipcheck += clip.offsets.length;
+}
+if (typeof obj.clipLoc !== "undefined")
+for (i=clipcheck; i < obj.clipLoc.length; i++)
+gl.uniform4f(obj.clipLoc[i], 0,0,0,0);
+if (is_lit) {
+gl.uniformMatrix4fv( obj.normMatLoc, false, new Float32Array(this.normMatrix.getAsArray()) );
+gl.uniform3fv( obj.emissionLoc, obj.emission);
+gl.uniform1f( obj.shininessLoc, obj.shininess);
+for (i=0; i < subscene.lights.length; i++) {
+light = this.getObj(subscene.lights[i]);
+gl.uniform3fv( obj.ambientLoc[i], this.componentProduct(light.ambient, obj.ambient));
+gl.uniform3fv( obj.specularLoc[i], this.componentProduct(light.specular, obj.specular));
+gl.uniform3fv( obj.diffuseLoc[i], light.diffuse);
+gl.uniform3fv( obj.lightDirLoc[i], light.lightDir);
+gl.uniform1i( obj.viewpointLoc[i], light.viewpoint);
+gl.uniform1i( obj.finiteLoc[i], light.finite);
+}
+for (i=subscene.lights.length; i < obj.nlights; i++) {
+gl.uniform3f( obj.ambientLoc[i], 0,0,0);
+gl.uniform3f( obj.specularLoc[i], 0,0,0);
+gl.uniform3f( obj.diffuseLoc[i], 0,0,0);
+}
+}
+if (type === "text") {
+gl.uniform2f( obj.textScaleLoc, 0.75/this.vp.width, 0.75/this.vp.height);
+}
+gl.enableVertexAttribArray( this.posLoc );
+var nc = obj.colorCount;
+count = obj.vertexCount;
+if (depth_sort) {
+var nfaces = obj.centers.length,
+frowsize, z, w;
+if (sprites_3d) frowsize = 1;
+else if (type === "triangles") frowsize = 3;
+else frowsize = 6;
+var depths = new Float32Array(nfaces);
+faces = new Array(nfaces);
+for(i=0; i<nfaces; i++) {
+z = this.prmvMatrix.m13*obj.centers[3*i] +
+this.prmvMatrix.m23*obj.centers[3*i+1] +
+this.prmvMatrix.m33*obj.centers[3*i+2] +
+this.prmvMatrix.m43;
+w = this.prmvMatrix.m14*obj.centers[3*i] +
+this.prmvMatrix.m24*obj.centers[3*i+1] +
+this.prmvMatrix.m34*obj.centers[3*i+2] +
+this.prmvMatrix.m44;
+depths[i] = z/w;
+faces[i] = i;
+}
+var depthsort = function(i,j) { return depths[j] - depths[i]; };
+faces.sort(depthsort);
+if (type !== "spheres") {
+var f = new Uint16Array(obj.f.length);
+for (i=0; i<nfaces; i++) {
+for (j=0; j<frowsize; j++) {
+f[frowsize*i + j] = obj.f[frowsize*faces[i] + j];
+}
+}
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, f, gl.DYNAMIC_DRAW);
+}
+}
+if (type === "spheres") {
+subscene = this.getObj(subsceneid);
+var scale = subscene.par3d.scale,
+scount = count;
+gl.vertexAttribPointer(this.posLoc,  3, gl.FLOAT, false, this.sphere.sphereStride,  0);
+gl.enableVertexAttribArray(obj.normLoc );
+gl.vertexAttribPointer(obj.normLoc,  3, gl.FLOAT, false, this.sphere.sphereStride,  0);
+gl.disableVertexAttribArray( this.colLoc );
+var sphereNorm = new CanvasMatrix4();
+sphereNorm.scale(scale[0], scale[1], scale[2]);
+sphereNorm.multRight(this.normMatrix);
+gl.uniformMatrix4fv( obj.normMatLoc, false, new Float32Array(sphereNorm.getAsArray()) );
+if (nc == 1) {
+gl.vertexAttrib4fv( this.colLoc, new Float32Array(obj.onecolor));
+}
+for (i = 0; i < scount; i++) {
+sphereMV = new CanvasMatrix4();
+if (depth_sort) {
+baseofs = faces[i]*obj.vOffsets.stride;
+} else {
+baseofs = i*obj.vOffsets.stride;
+}
+ofs = baseofs + obj.vOffsets.radofs;
+sscale = obj.values[ofs];
+sphereMV.scale(sscale/scale[0], sscale/scale[1], sscale/scale[2]);
+sphereMV.translate(obj.values[baseofs],
+obj.values[baseofs+1],
+obj.values[baseofs+2]);
+sphereMV.multRight(this.mvMatrix);
+gl.uniformMatrix4fv( obj.mvMatLoc, false, new Float32Array(sphereMV.getAsArray()) );
+if (nc > 1) {
+ofs = baseofs + obj.vOffsets.cofs;
+gl.vertexAttrib4f( this.colLoc, obj.values[ofs],
+obj.values[ofs+1],
+obj.values[ofs+2],
+obj.values[ofs+3] );
+}
+gl.drawElements(gl.TRIANGLES, this.sphere.sphereCount, gl.UNSIGNED_SHORT, 0);
+}
+return;
+} else {
+if (obj.colorCount === 1) {
+gl.disableVertexAttribArray( this.colLoc );
+gl.vertexAttrib4fv( this.colLoc, new Float32Array(obj.onecolor));
+} else {
+gl.enableVertexAttribArray( this.colLoc );
+gl.vertexAttribPointer(this.colLoc, 4, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.cofs);
+}
+}
+if (is_lit && obj.vOffsets.nofs > 0) {
+gl.enableVertexAttribArray( obj.normLoc );
+gl.vertexAttribPointer(obj.normLoc, 3, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.nofs);
+}
+if (has_texture || type === "text") {
+gl.enableVertexAttribArray( obj.texLoc );
+gl.vertexAttribPointer(obj.texLoc, 2, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.tofs);
+gl.activeTexture(gl.TEXTURE0);
+gl.bindTexture(gl.TEXTURE_2D, obj.texture);
+gl.uniform1i( obj.sampler, 0);
+}
+if (fixed_quads) {
+gl.enableVertexAttribArray( obj.ofsLoc );
+gl.vertexAttribPointer(obj.ofsLoc, 2, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.oofs);
+}
+var mode = this.mode4type[type];
+if (type === "sprites" || type === "text" || type === "quads") {
+count = count * 6/4;
+} else if (type === "surface") {
+count = obj.f.length;
+}
+if (is_lines) {
+gl.lineWidth( this.getMaterial(id, "lwd") );
+}
+gl.vertexAttribPointer(this.posLoc,  3, gl.FLOAT, false, 4*obj.vOffsets.stride,  4*obj.vOffsets.vofs);
+if (is_indexed) {
+gl.drawElements(gl[mode], count, gl.UNSIGNED_SHORT, 0);
+} else {
+gl.drawArrays(gl[mode], 0, count);
+}
+};
+this.drawSubscene = function(subsceneid) {
+var gl = this.gl,
+obj = this.getObj(subsceneid),
+objects = this.scene.objects,
+subids = obj.objects,
+subscene_has_faces = false,
+subscene_needs_sorting = false,
+flags, i;
+if (obj.par3d.skipRedraw)
+return;
+for (i=0; i < subids.length; i++) {
+flags = objects[subids[i]].flags;
+if (typeof flags !== "undefined") {
+subscene_has_faces |= (flags & this.f_is_lit)
+& !(flags & this.f_fixed_quads);
+subscene_needs_sorting |= (flags & this.f_depth_sort);
+}
+}
+var bgid = obj.backgroundId,
+bg;
+this.setViewport(subsceneid);
+if (typeof bgid !== "undefined" && objects[bgid].colors.length) {
+bg = objects[bgid].colors[0];
+gl.clearColor(bg[0], bg[1], bg[2], bg[3]);
+gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+}
+if (subids.length) {
+this.setprMatrix(subsceneid);
+this.setmvMatrix(subsceneid);
+if (subscene_has_faces) {
+this.setnormMatrix(subsceneid);
+if ((obj.flags & this.f_sprites_3d) &&
+typeof obj.spriteNormmat === "undefined") {
+obj.spriteNormmat = new CanvasMatrix4(this.normMatrix);
+}
+}
+if (subscene_needs_sorting)
+this.setprmvMatrix();
+var clipids = obj.clipplanes;
+if (clipids.length > 0) {
+this.invMatrix = new CanvasMatrix4(this.mvMatrix);
+this.invMatrix.invert();
+for (i = 0; i < clipids.length; i++)
+this.drawObj(clipids[i], subsceneid);
+}
+subids = obj.opaque;
+if (subids.length > 0) {
+gl.depthMask(true);
+gl.disable(gl.BLEND);
+for (i = 0; subids && i < subids.length; i++) {
+this.drawObj(subids[i], subsceneid);
+}
+}
+subids = obj.transparent;
+if (subids.length > 0) {
+gl.depthMask(false);
+gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA,
+gl.ONE, gl.ONE);
+gl.enable(gl.BLEND);
+for (i = 0; i < subids.length; i++) {
+this.drawObj(subids[i], subsceneid);
+}
+}
+subids = obj.subscenes;
+for (i = 0; i < subids.length; i++) {
+this.drawSubscene(subids[i]);
+}
+}
+};
+this.relMouseCoords = function(event) {
+var totalOffsetX = 0,
+totalOffsetY = 0,
+currentElement = this.canvas;
+do {
+totalOffsetX += currentElement.offsetLeft;
+totalOffsetY += currentElement.offsetTop;
+currentElement = currentElement.offsetParent;
+}
+while(currentElement);
+var canvasX = event.pageX - totalOffsetX,
+canvasY = event.pageY - totalOffsetY;
+return {x:canvasX, y:canvasY};
+};
+this.setMouseHandlers = function() {
+var self = this, activeSubscene, handler,
+handlers = {}, drag = 0;
+handlers.rotBase = 0;
+this.screenToVector = function(x, y) {
+var viewport = this.getObj(activeSubscene).par3d.viewport,
+width = viewport.width*this.canvas.width,
+height = viewport.height*this.canvas.height,
+radius = Math.max(width, height)/2.0,
+cx = width/2.0,
+cy = height/2.0,
+px = (x-cx)/radius,
+py = (y-cy)/radius,
+plen = Math.sqrt(px*px+py*py);
+if (plen > 1.e-6) {
+px = px/plen;
+py = py/plen;
+}
+var angle = (Math.SQRT2 - plen)/Math.SQRT2*Math.PI/2,
+z = Math.sin(angle),
+zlen = Math.sqrt(1.0 - z*z);
+px = px * zlen;
+py = py * zlen;
+return [px, py, z];
+};
+handlers.trackballdown = function(x,y) {
+var activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+i, l = activeModel.par3d.listeners;
+handlers.rotBase = this.screenToVector(x, y);
+this.saveMat = [];
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.saveMat = new CanvasMatrix4(activeSub.par3d.userMatrix);
+}
+};
+handlers.trackballmove = function(x,y) {
+var rotCurrent = this.screenToVector(x,y),
+rotBase = handlers.rotBase,
+dot = rotBase[0]*rotCurrent[0] +
+rotBase[1]*rotCurrent[1] +
+rotBase[2]*rotCurrent[2],
+angle = Math.acos( dot/this.vlen(rotBase)/this.vlen(rotCurrent) )*180.0/Math.PI,
+axis = this.xprod(rotBase, rotCurrent),
+objects = this.scene.objects,
+activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+l = activeModel.par3d.listeners,
+i;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.userMatrix.load(objects[l[i]].saveMat);
+activeSub.par3d.userMatrix.rotate(angle, axis[0], axis[1], axis[2]);
+}
+this.drawScene();
+};
+handlers.trackballend = 0;
+handlers.axisdown = function(x,y) {
+handlers.rotBase = this.screenToVector(x, this.canvas.height/2);
+var activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+i, l = activeModel.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.saveMat = new CanvasMatrix4(activeSub.par3d.userMatrix);
+}
+};
+handlers.axismove = function(x,y) {
+var rotCurrent = this.screenToVector(x, this.canvas.height/2),
+rotBase = handlers.rotBase,
+angle = (rotCurrent[0] - rotBase[0])*180/Math.PI,
+rotMat = new CanvasMatrix4();
+rotMat.rotate(angle, handlers.axis[0], handlers.axis[1], handlers.axis[2]);
+var activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+i, l = activeModel.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.userMatrix.load(activeSub.saveMat);
+activeSub.par3d.userMatrix.multLeft(rotMat);
+}
+this.drawScene();
+};
+handlers.axisend = 0;
+handlers.y0zoom = 0;
+handlers.zoom0 = 0;
+handlers.zoomdown = function(x, y) {
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+handlers.y0zoom = y;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.zoom0 = Math.log(activeSub.par3d.zoom);
+}
+};
+handlers.zoommove = function(x, y) {
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.zoom = Math.exp(activeSub.zoom0 + (y-handlers.y0zoom)/this.canvas.height);
+}
+this.drawScene();
+};
+handlers.zoomend = 0;
+handlers.y0fov = 0;
+handlers.fovdown = function(x, y) {
+handlers.y0fov = y;
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.fov0 = activeSub.par3d.FOV;
+}
+};
+handlers.fovmove = function(x, y) {
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.FOV = Math.max(1, Math.min(179, activeSub.fov0 +
+180*(y-handlers.y0fov)/this.canvas.height));
+}
+this.drawScene();
+};
+handlers.fovend = 0;
+this.canvas.onmousedown = function ( ev ){
+if (!ev.which) // Use w3c defns in preference to MS
+switch (ev.button) {
+case 0: ev.which = 1; break;
+case 1:
+case 4: ev.which = 2; break;
+case 2: ev.which = 3;
+}
+drag = ["left", "middle", "right"][ev.which-1];
+var coords = self.relMouseCoords(ev);
+coords.y = self.canvas.height-coords.y;
+activeSubscene = self.whichSubscene(coords);
+var sub = self.getObj(activeSubscene), f;
+handler = sub.par3d.mouseMode[drag];
+switch (handler) {
+case "xAxis":
+handler = "axis";
+handlers.axis = [1.0, 0.0, 0.0];
+break;
+case "yAxis":
+handler = "axis";
+handlers.axis = [0.0, 1.0, 0.0];
+break;
+case "zAxis":
+handler = "axis";
+handlers.axis = [0.0, 0.0, 1.0];
+break;
+}
+f = handlers[handler + "down"];
+if (f) {
+coords = self.translateCoords(activeSubscene, coords);
+f.call(self, coords.x, coords.y);
+ev.preventDefault();
+}
+};
+this.canvas.onmouseup = function ( ev ){
+if ( drag === 0 ) return;
+var f = handlers[handler + "up"];
+if (f)
+f();
+drag = 0;
+};
+this.canvas.onmouseout = this.canvas.onmouseup;
+this.canvas.onmousemove = function ( ev ) {
+if ( drag === 0 ) return;
+var f = handlers[handler + "move"];
+if (f) {
+var coords = self.relMouseCoords(ev);
+coords.y = self.canvas.height - coords.y;
+coords = self.translateCoords(activeSubscene, coords);
+f.call(self, coords.x, coords.y);
+}
+};
+handlers.wheelHandler = function(ev) {
+var del = 1.02, i;
+if (ev.shiftKey) del = 1.002;
+var ds = ((ev.detail || ev.wheelDelta) > 0) ? del : (1 / del);
+if (typeof activeSubscene === "undefined")
+activeSubscene = self.scene.rootSubscene;
+var activeSub = self.getObj(activeSubscene),
+activeProjection = self.getObj(self.useid(activeSub.id, "projection")),
+l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = self.getObj(l[i]);
+activeSub.par3d.zoom *= ds;
+}
+self.drawScene();
+ev.preventDefault();
+};
+this.canvas.addEventListener("DOMMouseScroll", handlers.wheelHandler, false);
+this.canvas.addEventListener("mousewheel", handlers.wheelHandler, false);
+};
+this.useid = function(subsceneid, type) {
+var sub = this.getObj(subsceneid);
+if (sub.embeddings[type] === "inherit")
+return(this.useid(sub.parent, type));
+else
+return subsceneid;
+};
+this.inViewport = function(coords, subsceneid) {
+var viewport = this.getObj(subsceneid).par3d.viewport,
+x0 = coords.x - viewport.x*this.canvas.width,
+y0 = coords.y - viewport.y*this.canvas.height;
+return 0 <= x0 && x0 <= viewport.width*this.canvas.width &&
+0 <= y0 && y0 <= viewport.height*this.canvas.height;
+};
+this.whichSubscene = function(coords) {
+var self = this,
+recurse = function(subsceneid) {
+var subscenes = self.getChildSubscenes(subsceneid), i, id;
+for (i=0; i < subscenes.length; i++) {
+id = recurse(subscenes[i]);
+if (typeof(id) !== "undefined")
+return(id);
+}
+if (self.inViewport(coords, subsceneid))
+return(subsceneid);
+else
+return undefined;
+},
+rootid = this.scene.rootSubscene,
+result = recurse(rootid);
+if (typeof(result) === "undefined")
+result = rootid;
+return result;
+};
+this.translateCoords = function(subsceneid, coords) {
+var viewport = this.getObj(subsceneid).par3d.viewport;
+return {x: coords.x - viewport.x*this.canvas.width,
+y: coords.y - viewport.y*this.canvas.height};
+};
+this.initSphere = function(verts) {
+var gl = this.gl, reuse = verts.reuse, result;
+if (typeof reuse !== "undefined") {
+var prev = document.getElementById(reuse).rglinstance.sphere;
+result = {vb: prev.vb, it: prev.it};
+} else {
+result = {vb: new Float32Array(this.flatten(this.transpose(verts.vb))),
+it: new Uint16Array(this.flatten(this.transpose(verts.it)))};
+}
+result.sphereStride = 12;
+result.sphereCount = result.it.length;
+result.buf = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, result.buf);
+gl.bufferData(gl.ARRAY_BUFFER, result.vb, gl.STATIC_DRAW);
+result.ibuf = gl.createBuffer();
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, result.ibuf);
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, result.it, gl.STATIC_DRAW);
+return result;
+};
+this.initialize = function(el, x) {
+this.textureCanvas = document.createElement("canvas");
+this.textureCanvas.style.display = "block";
+this.scene = x;
+this.normMatrix = new CanvasMatrix4();
+this.saveMat = {};
+this.distance = null;
+this.posLoc = 0;
+this.colLoc = 1;
+if (el) {
+el.rglinstance = this;
+this.initCanvas(el);
+}
+};
+this.initCanvas = function(el) {
+this.canvas = document.createElement("canvas");
+this.resize(el);
+while (el.firstChild) {
+el.removeChild(el.firstChild);
+}
+el.appendChild(this.canvas);
+this.initGL0();
+if (!this.gl)
+return;
+var objs = this.scene.objects,
+self = this;
+this.sphere = this.initSphere(this.scene.sphereVerts);
+Object.keys(objs).forEach(function(key){
+var id = parseInt(key, 10),
+obj = self.getObj(id);
+if (typeof obj.reuse !== "undefined")
+self.copyObj(id, obj.reuse);
+});
+Object.keys(objs).forEach(function(key){
+self.initSubscene(parseInt(key, 10));
+});
+Object.keys(objs).forEach(function(key){
+self.initObj(parseInt(key, 10));
+});
+this.setMouseHandlers();
+};
+/* this is only used by .writeWebGL; rglwidget has
+no debug element and does the drawing in rglwidget.js */
+this.start = function() {
+if (typeof this.prefix !== "undefined") {
+this.debugelement = document.getElementById(this.prefix + "debug");
+this.debug("");
+}
+this.drag = 0;
+this.drawScene();
+};
+this.debug = function(msg, img) {
+if (typeof this.debugelement !== "undefined") {
+this.debugelement.innerHTML = msg;
+if (typeof img !== "undefined") {
+this.debugelement.insertBefore(img, this.debugelement.firstChild);
+}
+} else
+alert(msg);
+};
+this.getSnapshot = function() {
+var img;
+if (typeof this.scene.snapshot !== "undefined") {
+img = document.createElement("img");
+img.src = this.scene.snapshot;
+img.alt = "Snapshot";
+}
+return img;
+};
+this.initGL0 = function() {
+if (!window.WebGLRenderingContext){
+this.debug("Your browser does not support WebGL. See <a href=\"http://get.webgl.org\">http://get.webgl.org</a>", this.getSnapshot());
+return;
+}
+try {
+this.initGL();
+}
+catch(e) {}
+if ( !this.gl ) {
+this.debug("Your browser appears to support WebGL, but did not create a WebGL context.  See <a href=\"http://get.webgl.org\">http://get.webgl.org</a>",
+this.getSnapshot());
+return;
+}
+};
+this.initGL = function() {
+this.gl = this.canvas.getContext("webgl") ||
+this.canvas.getContext("experimental-webgl");
+};
+this.resize = function(el) {
+this.canvas.width = el.width;
+this.canvas.height = el.height;
+};
+this.drawScene = function() {
+var gl = this.gl;
+if (!gl)
+this.alertOnce("No WebGL context.");
+gl.enable(gl.DEPTH_TEST);
+gl.depthFunc(gl.LEQUAL);
+gl.clearDepth(1.0);
+gl.clearColor(1,1,1,1);
+gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+this.drawSubscene(this.scene.rootSubscene);
+this.drawing = false;
+};
+this.subsetSetter = function(el, control) {
+if (typeof control.subscenes === "undefined" ||
+control.subscenes === null)
+control.subscenes = this.scene.rootSubscene;
+var value = Math.round(control.value),
+subscenes = [].concat(control.subscenes),
+i, j, entries, subsceneid,
+ismissing = function(x) {
+return control.fullset.indexOf(x) < 0;
+},
+tointeger = function(x) {
+return parseInt(x, 10);
+};
+for (i=0; i < subscenes.length; i++) {
+subsceneid = subscenes[i];
+if (typeof this.getObj(subsceneid) === "undefined")
+this.alertOnce("typeof object is undefined");
+entries = this.getObj(subsceneid).objects;
+entries = entries.filter(ismissing);
+if (control.accumulate) {
+for (j=0; j<=value; j++)
+entries = entries.concat(control.subsets[j]);
+} else {
+entries = entries.concat(control.subsets[value]);
+}
+entries = entries.map(tointeger);
+this.setSubsceneEntries(this.unique(entries), subsceneid);
+}
+};
+this.propertySetter = function(el, control)  {
+var value = control.value,
+values = [].concat(control.values),
+svals = [].concat(control.param),
+direct = values[0] === null,
+entries = [].concat(control.entries),
+ncol = entries.length,
+nrow = values.length/ncol,
+properties = this.repeatToLen(control.properties, ncol),
+objids = this.repeatToLen(control.objids, ncol),
+property = properties[0], objid = objids[0],
+obj = this.getObj(objid),
+propvals, i, v1, v2, p, entry, gl, needsBinding,
+newprop, newid,
+getPropvals = function() {
+if (property === "userMatrix")
+return obj.userMatrix.getAsArray();
+else
+return obj[property];
+};
+if (direct && typeof value === "undefined")
+return;
+if (control.interp) {
+values = values.slice(0, ncol).concat(values).
+concat(values.slice(ncol*(nrow-1), ncol*nrow));
+svals = [-Infinity].concat(svals).concat(Infinity);
+for (i = 1; i < svals.length; i++) {
+if (value <= svals[i]) {
+if (svals[i] === Infinity)
+p = 1;
+else
+p = (svals[i] - value)/(svals[i] - svals[i-1]);
+break;
+}
+}
+} else if (!direct) {
+value = Math.round(value);
+}
+propvals = getPropvals();
+for (j=0; j<entries.length; j++) {
+entry = entries[j];
+newprop = properties[j];
+newid = objids[j];
+if (newprop != property || newid != objid) {
+property = newprop;
+objid = newid;
+obj = this.getObj(objid);
+propvals = getPropvals();
+}
+if (control.interp) {
+v1 = values[ncol*(i-1) + j];
+v2 = values[ncol*i + j];
+this.setElement(propvals, entry, p*v1 + (1-p)*v2);
+} else if (!direct) {
+this.setElement(propvals, entry, values[ncol*value + j]);
+} else {
+this.setElement(propvals, entry, value[j]);
+}
+}
+needsBinding = [];
+for (j=0; j < entries.length; j++) {
+if (properties[j] === "values" &&
+needsBinding.indexOf(objids[j]) === -1) {
+needsBinding.push(objids[j]);
+}
+}
+for (j=0; j < needsBinding.length; j++) {
+gl = this.gl;
+obj = this.getObj(needsBinding[j]);
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, obj.values, gl.STATIC_DRAW);
+}
+};
+this.vertexSetter = function(el, control)  {
+var svals = [].concat(control.param),
+j, k, p, propvals, stride, ofs, obj,
+attrib,
+ofss    = {x:"vofs", y:"vofs", z:"vofs",
+red:"cofs", green:"cofs", blue:"cofs",
+alpha:"cofs", radii:"radofs",
+nx:"nofs", ny:"nofs", nz:"nofs",
+ox:"oofs", oy:"oofs", oz:"oofs",
+ts:"tofs", tt:"tofs"},
+pos     = {x:0, y:1, z:2,
+red:0, green:1, blue:2,
+alpha:3,radii:0,
+nx:0, ny:1, nz:2,
+ox:0, oy:1, oz:2,
+ts:0, tt:1},
+values = control.values,
+direct = values === null,
+ncol,
+interp = control.interp,
+vertices = [].concat(control.vertices),
+attributes = [].concat(control.attributes),
+value = control.value;
+ncol = Math.max(vertices.length, attributes.length);
+if (!ncol)
+return;
+vertices = this.repeatToLen(vertices, ncol);
+attributes = this.repeatToLen(attributes, ncol);
+if (direct)
+interp = false;
+/* JSON doesn't pass Infinity */
+svals[0] = -Infinity;
+svals[svals.length - 1] = Infinity;
+for (j = 1; j < svals.length; j++) {
+if (value <= svals[j]) {
+if (interp) {
+if (svals[j] === Infinity)
+p = 1;
+else
+p = (svals[j] - value)/(svals[j] - svals[j-1]);
+} else {
+if (svals[j] - value > value - svals[j-1])
+j = j - 1;
+}
+break;
+}
+}
+obj = this.getObj(control.objid);
+propvals = obj.values;
+for (k=0; k<ncol; k++) {
+attrib = attributes[k];
+vertex = vertices[k];
+ofs = obj.vOffsets[ofss[attrib]];
+if (ofs < 0)
+this.alertOnce("Attribute '"+attrib+"' not found in object "+control.objid);
+else {
+stride = obj.vOffsets.stride;
+ofs = vertex*stride + ofs + pos[attrib];
+if (direct) {
+propvals[ofs] = value;
+} else if (interp) {
+propvals[ofs] = p*values[j-1][k] + (1-p)*values[j][k];
+} else {
+propvals[ofs] = values[j][k];
+}
+}
+}
+if (typeof obj.buf !== "undefined") {
+var gl = this.gl;
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, propvals, gl.STATIC_DRAW);
+}
+};
+this.ageSetter = function(el, control) {
+var objids = [].concat(control.objids),
+nobjs = objids.length,
+time = control.value,
+births = [].concat(control.births),
+ages = [].concat(control.ages),
+steps = births.length,
+j = Array(steps),
+p = Array(steps),
+i, k, age, j0, propvals, stride, ofs, objid, obj,
+attrib, dim,
+attribs = ["colors", "alpha", "radii", "vertices",
+"normals", "origins", "texcoords",
+"x", "y", "z",
+"red", "green", "blue"],
+ofss    = ["cofs", "cofs", "radofs", "vofs",
+"nofs", "oofs", "tofs",
+"vofs", "vofs", "vofs",
+"cofs", "cofs", "cofs"],
+dims    = [3,1,1,3,
+3,2,2,
+1,1,1,
+1,1,1],
+pos     = [0,3,0,0,
+0,0,0,
+0,1,2,
+0,1,2];
+/* Infinity doesn't make it through JSON */
+ages[0] = -Infinity;
+ages[ages.length-1] = Infinity;
+for (i = 0; i < steps; i++) {
+if (births[i] !== null) {  // NA in R becomes null
+age = time - births[i];
+for (j0 = 1; age > ages[j0]; j0++);
+if (ages[j0] == Infinity)
+p[i] = 1;
+else if (ages[j0] > ages[j0-1])
+p[i] = (ages[j0] - age)/(ages[j0] - ages[j0-1]);
+else
+p[i] = 0;
+j[i] = j0;
+}
+}
+for (l = 0; l < nobjs; l++) {
+objid = objids[l];
+obj = this.getObj(objid);
+propvals = obj.values;
+stride = obj.vOffsets.stride;
+for (k = 0; k < attribs.length; k++) {
+attrib = control[attribs[k]];
+if (typeof attrib !== "undefined") {
+ofs = obj.vOffsets[ofss[k]];
+if (ofs >= 0) {
+dim = dims[k];
+ofs = ofs + pos[k];
+for (i = 0; i < steps; i++) {
+if (births[i] !== null) {
+for (d=0; d < dim; d++) {
+propvals[i*stride + ofs + d] = p[i]*attrib[dim*(j[i]-1) + d] + (1-p[i])*attrib[dim*j[i] + d];
+}
+}
+}
+} else
+this.alertOnce("\'"+attribs[k]+"\' property not found in object "+objid);
+}
+}
+obj.values = propvals;
+if (typeof obj.buf !== "undefined") {
+gl = this.gl;
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, obj.values, gl.STATIC_DRAW);
+}
+}
+};
+this.oldBridge = function(el, control) {
+var attrname, global = window[control.prefix + "rgl"];
+if (typeof global !== "undefined")
+for (attrname in global)
+this[attrname] = global[attrname];
+window[control.prefix + "rgl"] = this;
+};
+this.Player = function(el, control) {
+var
+self = this,
+components = [].concat(control.components),
+Tick = function() { /* "this" will be a timer */
+var i,
+nominal = this.value,
+slider = this.Slider,
+labels = this.outputLabels,
+output = this.Output,
+step;
+if (typeof slider !== "undefined" && nominal != slider.value)
+slider.value = nominal;
+if (typeof output !== "undefined") {
+step = Math.round((nominal - output.sliderMin)/output.sliderStep);
+if (labels !== null) {
+output.innerHTML = labels[step];
+} else {
+step = step*output.sliderStep + output.sliderMin;
+output.innerHTML = step.toPrecision(output.outputPrecision);
+}
+}
+for (i=0; i < this.actions.length; i++) {
+this.actions[i].value = nominal;
+}
+self.applyControls(el, this.actions, false);
+self.drawScene();
+},
+OnSliderInput = function() { /* "this" will be the slider */
+this.rgltimer.value = Number(this.value);
+this.rgltimer.Tick();
+},
+addSlider = function(min, max, step, value) {
+var slider = document.createElement("input");
+slider.type = "range";
+slider.min = min;
+slider.max = max;
+slider.step = step;
+slider.value = value;
+slider.oninput = OnSliderInput;
+slider.sliderActions = control.actions;
+slider.sliderScene = this;
+slider.className = "rgl-slider";
+slider.id = el.id + "-slider";
+el.rgltimer.Slider = slider;
+slider.rgltimer = el.rgltimer;
+el.appendChild(slider);
+},
+addLabel = function(labels, min, step, precision) {
+var output = document.createElement("output");
+output.sliderMin = min;
+output.sliderStep = step;
+output.outputPrecision = precision;
+output.className = "rgl-label";
+output.id = el.id + "-label";
+el.rgltimer.Output = output;
+el.rgltimer.outputLabels = labels;
+el.appendChild(output);
+},
+addButton = function(label) {
+var button = document.createElement("input"),
+onclicks = {Reverse: function() { this.rgltimer.reverse();},
+Play: function() { this.rgltimer.play();
+this.value = this.rgltimer.enabled ? "Pause" : "Play"; },
+Slower: function() { this.rgltimer.slower(); },
+Faster: function() { this.rgltimer.faster(); },
+Reset: function() { this.rgltimer.reset(); }};
+button.rgltimer = el.rgltimer;
+button.type = "button";
+button.value = label;
+if (label === "Play")
+button.rgltimer.PlayButton = button;
+button.onclick = onclicks[label];
+button.className = "rgl-button";
+button.id = el.id + "-" + label;
+el.appendChild(button);
+};
+if (typeof control.reinit !== "null") {
+control.actions.reinit = control.reinit;
+}
+el.rgltimer = new rgltimerClass(Tick, control.start, control.interval, control.stop, control.value, control.rate, control.loop, control.actions);
+for (var i=0; i < components.length; i++) {
+switch(components[i]) {
+case "Slider": addSlider(control.start, control.stop,
+control.step, control.value);
+break;
+case "Label": addLabel(control.labels, control.start,
+control.step, control.precision);
+break;
+default:
+addButton(components[i]);
+}
+}
+el.rgltimer.Tick();
+};
+this.applyControls = function(el, x, draw) {
+var self = this, reinit = x.reinit, i, obj, control, type;
+for (i = 0; i < x.length; i++) {
+control = x[i];
+type = control.type;
+self[type](el, control);
+};
+if (typeof reinit !== "undefined" && reinit !== null) {
+reinit = [].concat(reinit);
+for (i = 0; i < reinit.length; i++)
+self.getObj(reinit[i]).initialized = false;
+}
+if (typeof draw === "undefined" || draw)
+self.drawScene();
+};
+this.sceneChangeHandler = function(message) {
+var self = document.getElementById(message.elementId).rglinstance,
+objs = message.objects, mat = message.material,
+root = message.rootSubscene,
+initSubs = message.initSubscenes,
+redraw = message.redrawScene,
+skipRedraw = message.skipRedraw,
+deletes, subs, allsubs = [], obj, i,j;
+if (typeof message.delete !== "undefined") {
+deletes = [].concat(message.delete);
+if (typeof message.delfromSubscenes !== "undefined")
+subs = [].concat(message.delfromSubscenes);
+else
+subs = [];
+for (i = 0; i < deletes.length; i++) {
+for (j = 0; j < subs.length; j++) {
+self.delFromSubscene(deletes[i], subs[j]);
+}
+delete self.scene.objects[deletes[i]];
+}
+}
+if (typeof objs !== "undefined") {
+Object.keys(objs).forEach(function(key){
+key = parseInt(key, 10);
+self.scene.objects[key] = objs[key];
+self.initObj(key);
+var obj = self.getObj(key),
+subs = [].concat(obj.inSubscenes), k;
+allsubs = allsubs.concat(subs);
+for (k = 0; k < subs.length; k++)
+self.addToSubscene(key, subs[k]);
+});
+}
+if (typeof mat !== "undefined") {
+self.scene.material = mat;
+}
+if (typeof root !== "undefined") {
+self.scene.rootSubscene = root;
+}
+if (typeof initSubs !== "undefined")
+allsubs = allsubs.concat(initSubs);
+allsubs = self.unique(allsubs);
+for (i = 0; i < allsubs.length; i++) {
+self.initSubscene(allsubs[i]);
+}
+if (typeof skipRedraw !== "undefined") {
+root = self.getObj(self.scene.rootSubscene);
+root.par3d.skipRedraw = skipRedraw;
+}
+if (redraw)
+self.drawScene();
+};
+}).call(rglwidgetClass.prototype);
+rgltimerClass = function(Tick, startTime, interval, stopTime, value, rate, loop, actions) {
+this.enabled = false;
+this.timerId = 0;
+this.startTime = startTime;         /* nominal start time in seconds */
+this.value = value;                 /* current nominal time */
+this.interval = interval;           /* seconds between updates */
+this.stopTime = stopTime;           /* nominal stop time */
+this.rate = rate;                   /* nominal units per second */
+this.loop = loop;                   /* "none", "cycle", or "oscillate" */
+this.realStart = undefined;         /* real world start time */
+this.multiplier = 1;                /* multiplier for fast-forward
+or reverse */
+this.actions = actions;
+this.Tick = Tick;
+};
+(function() {
+this.play = function() {
+if (this.enabled) {
+this.enabled = false;
+window.clearInterval(this.timerId);
+this.timerId = 0;
+return;
+}
+var tick = function(self) {
+var now = new Date();
+self.value = self.multiplier*self.rate*(now - self.realStart)/1000 + self.startTime;
+if (self.value > self.stopTime || self.value < self.startTime) {
+if (!self.loop) {
+self.reset();
+} else {
+var cycle = self.stopTime - self.startTime,
+newval = (self.value - self.startTime) % cycle + self.startTime;
+if (newval < self.startTime) {
+newval += cycle;
+}
+self.realStart += (self.value - newval)*1000/self.multiplier/self.rate;
+self.value = newval;
+}
+}
+if (typeof self.Tick !== "undefined") {
+self.Tick(self.value);
+}
+};
+this.realStart = new Date() - 1000*(this.value - this.startTime)/this.rate/this.multiplier;
+this.timerId = window.setInterval(tick, 1000*this.interval, this);
+this.enabled = true;
+};
+this.reset = function() {
+this.value = this.startTime;
+this.newmultiplier(1);
+if (typeof this.Tick !== "undefined") {
+this.Tick(this.value);
+}
+if (this.enabled)
+this.play();  /* really pause... */
+if (typeof this.PlayButton !== "undefined")
+this.PlayButton.value = "Play";
+};
+this.faster = function() {
+this.newmultiplier(Math.SQRT2*this.multiplier);
+};
+this.slower = function() {
+this.newmultiplier(this.multiplier/Math.SQRT2);
+};
+this.reverse = function() {
+this.newmultiplier(-this.multiplier);
+};
+this.newmultiplier = function(newmult) {
+if (newmult != this.multiplier) {
+this.realStart += 1000*(this.value - this.startTime)/this.rate*(1/this.multiplier - 1/newmult);
+this.multiplier = newmult;
+}
+};
+}).call(rgltimerClass.prototype);</script>
+<div id="togglediv" class="rglWebGL">
+
+</div>
+<script type="text/javascript">
+var togglediv = document.getElementById("togglediv"),
+togglergl = new rglwidgetClass();
+togglediv.width = 481;
+togglediv.height = 481;
+togglergl.initialize(togglediv,
+{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":26,"objects":{"32":{"id":32,"type":"spheres","material":{},"vertices":[ [...]
+togglergl.prefix = "toggle";
+</script>
+<p id="toggledebug">
+You must enable Javascript to view this page properly.
+</p>
+<script>togglergl.start();</script>
+
+
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">toggleButton</span>(sphereid, <span class="dt">label =</span> <span class="st">"setosa"</span>, <span class="dt">prefix =</span> <span class="st">"toggle"</span>, <span class="dt">subscene =</span> subid)</code></pre>
+<button type="button" id="input5005a04efee" name="input5005a04efee" onclick="(function(){
+  var subset = [32], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+setosa
+</button>
+
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">toggleButton</span>(sphereid<span class="dv">+1</span>, <span class="dt">label =</span> <span class="st">"versicolor"</span>, <span class="dt">prefix =</span> <span class="st">"toggle"</span>, <span class="dt">subscene =</span> subid)</code></pre>
+<button type="button" id="input5006cffecc2" name="input5006cffecc2" onclick="(function(){
+  var subset = [33], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+versicolor
+</button>
+
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">toggleButton</span>(sphereid<span class="dv">+2</span>, <span class="dt">label =</span> <span class="st">"virginica"</span>, <span class="dt">prefix =</span> <span class="st">"toggle"</span>, <span class="dt">subscene =</span> subid)</code></pre>
+<button type="button" id="input5009df9525" name="input5009df9525" onclick="(function(){
+  var subset = [34], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+virginica
+</button>
+
+<p>Note that we need to use <code>results="asis"</code> for the button code.<br />Normally we would also use <code>echo=FALSE</code>, though I didn’t do so above; then the buttons will end up side-by-side. We also add another button to toggle the axes:</p>
+<button type="button" id="input5005bc6ec3e" name="input5005bc6ec3e" onclick="(function(){
+  var subset = [32], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+setosa
+</button>
+<button type="button" id="input50048b1d77e" name="input50048b1d77e" onclick="(function(){
+  var subset = [33], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+versicolor
+</button>
+<button type="button" id="input5006c7f2ed3" name="input5006c7f2ed3" onclick="(function(){
+  var subset = [34], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+virginica
+</button>
+<button type="button" id="input50045a21a7d" name="input50045a21a7d" onclick="(function(){
+  var subset = [35,36,37,38], i;
+  if (togglergl.inSubscene(subset[0], 26)) {
+    for (i=0; i<subset.length; i++)
+      togglergl.delFromSubscene(subset[i], 26);
+  } else {
+    for (i=0; i<subset.length; i++)
+      togglergl.addToSubscene(subset[i], 26);
+  }
+  togglergl.drawScene();
+})()">
+axes
+</button>
+
+<p>An alternate control to achieve the same thing is <a name="subsetSlider"><a href="#subsetSlider"><code>subsetSlider</code></a></a>. Here we also illustrate the <a name="elementId2Prefix"><a href="#elementId2Prefix"><code>elementId2Prefix</code></a></a> bridge to allow an <a name="rglwidget"><a href="#rglwidget"><code>rglwidget</code></a></a> to be controlled by the old-style slider.</p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">rglwidget</span>(<span class="dt">elementId =</span> <span class="st">"slider"</span>)</code></pre>
+<p><div id="slider" style="width:480px;height:480px;" class="rglWebGL"></div>
+<script type="application/json" data-for="slider">{"x":{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":26,"objects":{"3 [...]
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">elementId2Prefix</span>(<span class="st">"slider"</span>)</code></pre>
+<script>var sliderrgl = {};</script>
+<p><span id="rgl-play28758" class="rglPlayer"></span>
+<script type="application/json" data-for="rgl-play28758">{"x":{"actions":[{"type":"oldBridge","prefix":"slider"}],"start":0,"stop":null,"value":0,"interval":0.05,"rate":1,"components":[],"loop":true,"step":1,"labels":null,"precision":3,"reinit":null,"sceneId":"slider","respondTo":null},"evals":[]}</script></p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">subsetSlider</span>(<span class="dt">subsets =</span> <span class="kw">list</span>(<span class="dt">setosa =</span> sphereid, 
+                  <span class="dt">versicolor =</span> sphereid +<span class="st"> </span><span class="dv">1</span>, 
+                  <span class="dt">virginica =</span> sphereid +<span class="st"> </span><span class="dv">2</span>, 
+                  <span class="dt">all =</span> sphereid +<span class="st"> </span><span class="dv">0</span>:<span class="dv">2</span>),
+             <span class="dt">prefixes =</span> <span class="st">"slider"</span>, <span class="dt">subscenes =</span> subid,
+             <span class="dt">init =</span> <span class="dv">3</span>)</code></pre>
+<script>sliderrgl.input50059936211 = function(value){
+  if (typeof sliderrgl.drawScene === "undefined")
+    return;
+  var busy = (typeof sliderrgl.input50059936211.busy !== "undefined"),
+      lvalue, labels;
+  try {
+    sliderrgl.input50059936211.busy = value;
+    if (busy) return;
+    do {
+       (function(value) {
+  var i, ids = [[32],[33],[34],[32,33,34]],
+      fullset = [32,33,34], entries,
+      f = function(x) { return fullset.indexOf(x) < 0; };
+  value = Math.round(value);
+  if (typeof sliderrgl.getObj === "undefined") return;
+  entries = sliderrgl.getObj(26).objects;
+  entries = entries.filter(f);
+  entries = entries.concat(ids[value]);
+
+  sliderrgl.setSubsceneEntries(entries, 26);
+})(value);
+       sliderrgl.drawScene();
+       lvalue = Math.round((value - 0)/1);
+       labels = ['setosa','versicolor','virginica','all']; 
+  label = document.getElementById('input50059936211text');
+  if (label !== null) label.value = labels[lvalue];
+     } while (sliderrgl.input50059936211.busy !== value);
+  }
+  finally {
+    if (!busy)
+      sliderrgl.input50059936211.busy = undefined;
+  }
+};
+sliderrgl.input50059936211(3);</script>
+<input type="range" min="0" max="3" step="1" value="3" id="input50059936211" name="input50059936211" oninput="sliderrgl.input50059936211(this.valueAsNumber)">
+<output id="input50059936211text" for="input50059936211">
+all
+</output>
+
+<p>There are several other functions to generate the Javascript code for controls. <a name="par3dinterpSetter"><a href="#par3dinterpSetter"><code>par3dinterpSetter</code></a></a> generates a function that approximates the result of <a href="#par3dinterp"><code>par3dinterp</code></a>. <a name="propertySetter"><a href="#propertySetter"><code>propertySetter</code></a></a> is a more general function to set the value of properties of the scene. Both generate Javascript functions, but not the  [...]
+For example, the following code (similar to the <a href="#play3d"><code>play3d</code></a> example) rotates the scene in a complex way.
+<div id="userMatrixdiv" class="rglWebGL">
+
+</div>
+<script type="text/javascript">
+var userMatrixdiv = document.getElementById("userMatrixdiv"),
+userMatrixrgl = new rglwidgetClass();
+userMatrixdiv.width = 481;
+userMatrixdiv.height = 481;
+userMatrixrgl.initialize(userMatrixdiv,
+{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":26,"objects":{"32":{"id":32,"reuse":"togglediv"},"33":{"id":33,"reuse": [...]
+userMatrixrgl.prefix = "userMatrix";
+</script>
+<p id="userMatrixdebug">
+You must enable Javascript to view this page properly.
+</p>
+<script>userMatrixrgl.start();</script>
+
+<pre class="sourceCode r"><code class="sourceCode r">M <-<span class="st"> </span>r3dDefaults$userMatrix
+fn <-<span class="st"> </span><span class="kw">par3dinterp</span>(<span class="dt">time =</span> (<span class="dv">0</span>:<span class="dv">2</span>)*<span class="fl">0.75</span>, <span class="dt">userMatrix =</span> <span class="kw">list</span>(M,
+                                     <span class="kw">rotate3d</span>(M, pi/<span class="dv">2</span>, <span class="dv">1</span>, <span class="dv">0</span>, <span class="dv">0</span>),
+                                     <span class="kw">rotate3d</span>(M, pi/<span class="dv">2</span>, <span class="dv">0</span>, <span class="dv">1</span>, <span class="dv">0</span>) ) )
+<span class="kw">propertySlider</span>(<span class="dt">setter =</span> <span class="kw">par3dinterpSetter</span>(fn, <span class="dv">0</span>, <span class="fl">1.5</span>, <span class="dt">steps=</span><span class="dv">15</span>, 
+                       <span class="dt">prefix =</span> <span class="st">"userMatrix"</span>, 
+                       <span class="dt">subscene =</span> subid),
+           <span class="dt">step =</span> <span class="fl">0.01</span>)</code></pre>
+<script>userMatrixrgl.input50058b38422 = function(value){
+  if (typeof userMatrixrgl.drawScene === "undefined")
+    return;
+  var busy = (typeof userMatrixrgl.input50058b38422.busy !== "undefined"),
+      lvalue, labels;
+  try {
+    userMatrixrgl.input50058b38422.busy = value;
+    if (busy) return;
+    do {
+       (function(value){
+   var values = [1,0,0,0,0.3420201,-0.9396926,0,0.9396926,0.3420201,1,0,0,0,0.3420201,-0.9396926,0,0.9396926,0.3420201,0.9998637,0.01530909,0.006182005,-0.0005731673,0.4063968,-0.9136965,-0.01650021,0.9135684,0.4063502,0.998369,0.05070307,0.02623844,-0.007314602,0.5694157,-0.8220172,-0.05661938,0.8204846,0.5688579,0.994286,0.08726108,0.06148823,-0.02793499,0.7686299,-0.6390835,-0.1030288,0.6337141,0.7666756,0.9891054,0.1056615,0.1024996,-0.06017974,0.9256743,-0.3735044,-0.1343463,0.36326 [...]
+   propvals = userMatrixrgl.getObj(26).par3d.userMatrix.getAsArray();
+   var svals = [-Infinity, 0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5, Infinity],
+        v1, v2;
+   for (var i = 1; i < svals.length; i++)
+     if (value <= svals[i]) {
+       var p = (svals[i] - value)/(svals[i] - svals[i-1]);
+       v1 = values[9*(i-1)];
+       v2 = values[9*i];
+       propvals[0] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+1];
+       v2 = values[9*i+1];
+       propvals[1] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+2];
+       v2 = values[9*i+2];
+       propvals[2] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+3];
+       v2 = values[9*i+3];
+       propvals[4] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+4];
+       v2 = values[9*i+4];
+       propvals[5] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+5];
+       v2 = values[9*i+5];
+       propvals[6] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+6];
+       v2 = values[9*i+6];
+       propvals[8] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+7];
+       v2 = values[9*i+7];
+       propvals[9] = p*v1 + (1-p)*v2;
+       v1 = values[9*(i-1)+8];
+       v2 = values[9*i+8];
+       propvals[10] = p*v1 + (1-p)*v2;
+       break;
+     }
+   userMatrixrgl.getObj(26).par3d.userMatrix.load(propvals);
+})(value);
+       userMatrixrgl.drawScene();
+       lvalue = Math.round((value - 0)/0.01);
+       labels = ['0','0.01','0.02','0.03','0.04','0.05','0.0600000000000001','0.07','0.08','0.09','0.1','0.11','0.12','0.13','0.14','0.15','0.16','0.17','0.18','0.19','0.2','0.21','0.22','0.23','0.24','0.25','0.26','0.27','0.28','0.29','0.3','0.31','0.32','0.33','0.34','0.35','0.36','0.37','0.38','0.39','0.4','0.41','0.42','0.43','0.44','0.45','0.46','0.47','0.48','0.49','0.5','0.51','0.52','0.53','0.54','0.55','0.56','0.57','0.58','0.59','0.6','0.61','0.62','0.63','0.64','0.65','0.66',' [...]
+  label = document.getElementById('input50058b38422text');
+  if (label !== null) label.value = labels[lvalue];
+     } while (userMatrixrgl.input50058b38422.busy !== value);
+  }
+  finally {
+    if (!busy)
+      userMatrixrgl.input50058b38422.busy = undefined;
+  }
+};
+userMatrixrgl.input50058b38422(0);</script>
+<input type="range" min="0" max="1.5" step="0.01" value="0" id="input50058b38422" name="input50058b38422" oninput="userMatrixrgl.input50058b38422(this.valueAsNumber)">
+<output id="input50058b38422text" for="input50058b38422">
+0
+</output>
+<p>Some things to note: The generated Javascript slider has 150 increments, so that motion appears smooth. However, storing 150 <code>userMatrix</code> values would take up a lot of space, so we use interpolation in the Javascript code. However, the Javascript code can only do linear interpolation, not the more complex spline-based SO(3) interpolation done by <a href="#par3dinterp"><code>par3dinterp</code></a>. Because of this, we need to output 15 steps from <a href="#par3dinterpSetter" [...]
+<p>Another function that auto-generates Javascript code is <a name="clipplaneSlider"><a href="#clipplaneSlider"><code>clipplaneSlider</code></a></a>. This function allows the user to control the location of a clipping plane by moving a slider. Both it and <a href="#par3dinterpSetter"><code>par3dinterpSetter</code></a> are implemented using the more general <a name="propertySlider"><a href="#propertySlider"><code>propertySlider</code></a></a>, which allows control of multiple objects in m [...]
+<p>Less general than <a href="#propertySetter"><code>propertySetter</code></a> is <a name="vertexSetter"><a href="#vertexSetter"><code>vertexSetter</code></a></a>. This function sets attributes of individual vertices in a scene. For example, to set the x-coordinate of the closest point in the setosa group, and modify its colour from black to white,</p>
+<div id="vertexdiv" class="rglWebGL">
+
+</div>
+<script type="text/javascript">
+var vertexdiv = document.getElementById("vertexdiv"),
+vertexrgl = new rglwidgetClass();
+vertexdiv.width = 481;
+vertexdiv.height = 481;
+vertexrgl.initialize(vertexdiv,
+{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":26,"objects":{"32":{"id":32,"reuse":"togglediv"},"33":{"id":33,"reuse": [...]
+vertexrgl.prefix = "vertex";
+</script>
+<p id="vertexdebug">
+You must enable Javascript to view this page properly.
+</p>
+<script>vertexrgl.start();</script>
+
+
+<pre class="sourceCode r"><code class="sourceCode r">setosa <-<span class="st"> </span><span class="kw">subset</span>(iris, Species ==<span class="st"> "setosa"</span>)
+which <-<span class="st"> </span><span class="kw">which.min</span>(setosa$Sepal.Width)
+init <-<span class="st"> </span>setosa$Sepal.Length[which]
+<span class="kw">propertySlider</span>(
+    <span class="kw">vertexSetter</span>(<span class="dt">values =</span> <span class="kw">matrix</span>(<span class="kw">c</span>(init,<span class="dv">8</span>,<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">1</span>,<span class="dv">0</span>,<span class="dv">1</span>), <span class="dt">nrow=</span><span class="dv">2</span>),
+                 <span class="dt">attributes=</span><span class="kw">c</span>(<span class="st">"x"</span>, <span class="st">"r"</span>, <span class="st">"g"</span>, <span class="st">"b"</span>), 
+             <span class="dt">vertices =</span> which, <span class="dt">objid =</span> sphereid, 
+             <span class="dt">prefix =</span> <span class="st">"vertex"</span>), 
+    <span class="dt">step=</span><span class="fl">0.01</span>)</code></pre>
+<script>vertexrgl.input5005d04d19b = function(value){
+  if (typeof vertexrgl.drawScene === "undefined")
+    return;
+  var busy = (typeof vertexrgl.input5005d04d19b.busy !== "undefined"),
+      lvalue, labels;
+  try {
+    vertexrgl.input5005d04d19b.busy = value;
+    if (busy) return;
+    do {
+       (function(value){
+  var ofs, values = [4.5,0,0,0,4.5,0,0,0,8,1,1,1,8,1,1,1],
+  propvals = vertexrgl.getObj(32).values,
+  stride = vertexrgl.getObj(32).vOffsets.stride;
+  var p, v1, v2, svals = [-Infinity, 1,2, Infinity];
+  for (var i = 1; i < svals.length; i++)
+    if (value <= svals[i]) {
+      p = (svals[i] - value)/(svals[i] - svals[i-1]);
+  ofs = vertexrgl.getObj(32).vOffsets.vofs;
+  if (ofs < 0)
+    alert("Attribute x not found in object 32");
+  v1 = values[4*(i-1)];
+  v2 = values[4*i];
+  propvals[41*stride + ofs] = p*v1 + (1-p)*v2;
+  ofs = vertexrgl.getObj(32).vOffsets.cofs;
+  if (ofs < 0)
+    alert("Attribute r not found in object 32");
+  v1 = values[4*(i-1)+1];
+  v2 = values[4*i+1];
+  propvals[41*stride + ofs] = p*v1 + (1-p)*v2;
+  ofs = vertexrgl.getObj(32).vOffsets.cofs;
+  if (ofs < 0)
+    alert("Attribute g not found in object 32");
+  ofs = ofs + 1;
+  v1 = values[4*(i-1)+2];
+  v2 = values[4*i+2];
+  propvals[41*stride + ofs] = p*v1 + (1-p)*v2;
+  ofs = vertexrgl.getObj(32).vOffsets.cofs;
+  if (ofs < 0)
+    alert("Attribute b not found in object 32");
+  ofs = ofs + 2;
+  v1 = values[4*(i-1)+3];
+  v2 = values[4*i+3];
+  propvals[41*stride + ofs] = p*v1 + (1-p)*v2;
+       break;
+  }
+  vertexrgl.getObj(32).values = propvals;
+  if (typeof vertexrgl.getObj(32).buf !== "undefined") {
+    var gl = vertexrgl.gl;
+    gl.bindBuffer(gl.ARRAY_BUFFER, vertexrgl.getObj(32).buf);
+    gl.bufferData(gl.ARRAY_BUFFER, vertexrgl.getObj(32).values, gl.STATIC_DRAW);
+  }
+})(value);
+       vertexrgl.drawScene();
+       lvalue = Math.round((value - 1)/0.01);
+       labels = ['1','1.01','1.02','1.03','1.04','1.05','1.06','1.07','1.08','1.09','1.1','1.11','1.12','1.13','1.14','1.15','1.16','1.17','1.18','1.19','1.2','1.21','1.22','1.23','1.24','1.25','1.26','1.27','1.28','1.29','1.3','1.31','1.32','1.33','1.34','1.35','1.36','1.37','1.38','1.39','1.4','1.41','1.42','1.43','1.44','1.45','1.46','1.47','1.48','1.49','1.5','1.51','1.52','1.53','1.54','1.55','1.56','1.57','1.58','1.59','1.6','1.61','1.62','1.63','1.64','1.65','1.66','1.67','1.68',' [...]
+  label = document.getElementById('input5005d04d19btext');
+  if (label !== null) label.value = labels[lvalue];
+     } while (vertexrgl.input5005d04d19b.busy !== value);
+  }
+  finally {
+    if (!busy)
+      vertexrgl.input5005d04d19b.busy = undefined;
+  }
+};
+vertexrgl.input5005d04d19b(1);</script>
+<input type="range" min="1" max="2" step="0.01" value="1" id="input5005d04d19b" name="input5005d04d19b" oninput="vertexrgl.input5005d04d19b(this.valueAsNumber)">
+<output id="input5005d04d19btext" for="input5005d04d19b">
+1
+</output>
+         
+
+<p>A related function is <a name="ageSetter"><a href="#ageSetter"><code>ageSetter</code></a></a>, though it uses a very different specification of the attributes. It is used when the slider controls the “age” of the scene, and attributes of vertices change with their age.</p>
+<p>Rather than giving an example, we will illustrate the very similar function <a name="ageControl"><a href="../../rglwidget/help/ageControl"><code>ageControl</code></a></a> from the <code>rglwidgets</code> package, embedded in a <a name="playwidget"><a href="../../rglwidget/help/playwidget"><code>playwidget</code></a></a>. We will show a point moving along a curve. In the original scene we need to specify multiple colours so that the colour is not fixed, and can be controlled by the sli [...]
+<pre class="sourceCode r"><code class="sourceCode r">time <-<span class="st"> </span><span class="dv">0</span>:<span class="dv">500</span>
+xyz <-<span class="st"> </span><span class="kw">cbind</span>(<span class="kw">cos</span>(time/<span class="dv">20</span>), <span class="kw">sin</span>(time/<span class="dv">10</span>), time)
+lineid <-<span class="st"> </span><span class="kw">plot3d</span>(xyz, <span class="dt">type=</span><span class="st">"l"</span>, <span class="dt">col =</span> <span class="kw">c</span>(<span class="st">"black"</span>, <span class="st">"black"</span>))[<span class="st">"data"</span>]
+sphereid <-<span class="st"> </span><span class="kw">spheres3d</span>(xyz[<span class="dv">1</span>, , <span class="dt">drop=</span><span class="ot">FALSE</span>], <span class="dt">radius =</span> <span class="dv">8</span>, <span class="dt">col =</span> <span class="st">"red"</span>)
+<span class="kw">rglwidget</span>(<span class="dt">elementId =</span> <span class="st">"ageExample"</span>)</code></pre>
+<p><div id="ageExample" style="width:480px;height:480px;" class="rglWebGL"></div>
+<script type="application/json" data-for="ageExample">{"x":{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":26,"objects" [...]
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">playwidget</span>(<span class="st">"ageExample"</span>, <span class="kw">list</span>(
+  <span class="kw">ageControl</span>(<span class="dt">births =</span> time, <span class="dt">ages =</span> <span class="kw">c</span>(<span class="dv">0</span>, <span class="dv">0</span>, <span class="dv">50</span>),
+        <span class="dt">colors =</span> <span class="kw">c</span>(<span class="st">"gray"</span>, <span class="st">"red"</span>, <span class="st">"gray"</span>), <span class="dt">objids =</span> lineid),
+    <span class="kw">ageControl</span>(<span class="dt">births =</span> <span class="dv">0</span>, <span class="dt">ages =</span> time,
+        <span class="dt">vertices =</span> xyz, <span class="dt">objids =</span> sphereid)),
+  <span class="dt">start =</span> <span class="dv">0</span>, <span class="dt">stop =</span> <span class="kw">max</span>(time) +<span class="st"> </span><span class="dv">20</span>, <span class="dt">rate =</span> <span class="dv">50</span>,
+  <span class="dt">components =</span> <span class="kw">c</span>(<span class="st">"Reverse"</span>, <span class="st">"Play"</span>, <span class="st">"Slower"</span>, <span class="st">"Faster"</span>,
+                 <span class="st">"Reset"</span>, <span class="st">"Slider"</span>, <span class="st">"Label"</span>),
+  <span class="dt">loop =</span> <span class="ot">TRUE</span>)</code></pre>
+<p><span id="rgl-play78831" class="rglPlayer"></span>
+<script type="application/json" data-for="rgl-play78831">{"x":{"actions":[{"type":"ageSetter","objids":95,"value":0,"births":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118, [...]
+<p>The final function of this type is <a name="matrixSetter"><a href="#matrixSetter"><code>matrixSetter</code></a></a>, for setting up multiple controls to modify a matrix, typically <code>userMatrix</code>. This is used when complex manipulation of a matrix requires several controls.</p>
+</div>
+<div id="user-defined-mouse-controls" class="section level2">
+<h2>User defined mouse controls</h2>
+<p><code>rgl</code> allows user defined mouse controls. For these to work within WebGL, you will need to write a Javascript version as well as the R version. This isn’t easy: R provides a lot of support functions which are not easily available in Javascript.</p>
+<p>TODO: give an example here.</p>
+</div>
+<div id="reference-for-rglclass" class="section level2">
+<h2>Reference for <code>rglClass</code></h2>
+<p>NB: This section has not been updated recently, and is not current.</p>
+<p>In writing the <code>writeWebGL()</code> function, I haven’t tried to prevent access to anything. On the other hand, I haven’t provided access to everything. The parts documented here should remain relatively stable (unless indicated otherwise). Users may also consult the source to <code>writeWebGL</code>, but should be aware that anything that isn’t documented here is subject to change without notice.</p>
+<p><a name="rglClass"><code>rglClass</code></a></p>
+<p>As documented in <a href="#writeWebGL"><code>writeWebGL</code></a>, the call</p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">writeWebGL</span>(..., <span class="dt">prefix =</span> <span class="st">"<prefix>"</span>)</code></pre>
+<p>will create a global object on the output page with name <code><prefix>rgl</code> and Javascript class <code>rglClass</code>. This class has a large number of properties and methods, some of which are designed to be available for use by other code on the web page.</p>
+<p>Most of the properties are stored as Javascript <code>Array</code> objects, indexed by the <code>rgl</code> id of the subscene to which they apply. There are also Javascript methods attached to the <code>rglClass</code> class.</p>
+<div id="methods" class="section level3">
+<h3>Methods</h3>
+<p><a name="drawScene"><code>drawScene()</code></a></p>
+<p>After any change that will affect the display, code should call <code><prefix>rgl.drawScene()</code> to redraw the scene.</p>
+<p><a name="inSubscene"><code>inSubscene()</code></a>, <a name="addToSubscene"><code>addToSubscene()</code></a>, <a name="delFromSubscene"><code>delFromSubscene()</code></a></p>
+<p>These methods each take two arguments: <code>id</code> and <code>subscene</code>, which should be the <code>rgl</code> ids of an object and a subscene. <code>inSubscene</code> tests whether <code>id</code> is already included in the subscene, and the others add it or delete it from the subscene.</p>
+<p><a name="getSubsceneEntries"><code>getSubsceneEntries()</code></a></p>
+<p>This function takes a subscene id as argument, and returns an <code>Array</code> containing all of the ids displayed in that subscene.</p>
+<p><a name="setSubsceneEntries"><code>setSubsceneEntries()</code></a></p>
+<p>This takes an <code>Array</code> of ids and a subscene id as arguments, and sets the contents of the subscene to the ids.</p>
+</div>
+<div id="properties" class="section level3">
+<h3>Properties</h3>
+<p><a name="FOV"><code>FOV</code></a>, <a name="listeners"><code>listeners</code></a>, <a name="userMatrix"><code>userMatrix</code></a>, <a name="zoom"><code>zoom</code></a></p>
+<p>These correspond to the <a href="#par3d"><code>par3d</code></a> properties with the same names.</p>
+<ul>
+<li><code>FOV</code> and <code>zoom</code> are arrays of numbers.</li>
+<li><code>userMatrix</code> is an array of <code>CanvasMatrix4</code> objects (documented in the file <code>system.file("WebGL/CanvasMatrix.src.js")</code>.</li>
+<li>Each <code>listeners</code> item is itself an array of subscene ids that “listen” to mouse actions, i.e. <code>listeners[19]</code> would contain all subscene ids that respond to mouse actions in subscene 19.</li>
+</ul>
+<p><a name="viewport"><code>viewport</code></a></p>
+<p>This property also corresponds to the <a href="#par3d"><code>par3d</code></a> property, but should be considered to be read-only.</p>
+<p><a name="drawFns"><code>drawFns</code></a>, <a name="clipFns"><code>clipFns</code></a></p>
+<p>These two arrays contain the code to display each object in the scene. The functions in the <code>drawFns</code> array are called for each object each time it is displayed. The <code>clipFns</code> functions are called when objects being clipped are drawn.</p>
+<p><a name="values"><code>values</code></a>, <a name="offsets"><code>offsets</code></a></p>
+<p>Most of the data about each object in a scene is contained in the <code>values</code> property. This is an array, indexed by object id. The individual entries are numeric arrays. Though they are singly-indexed, the entries are meant to be interpreted as matrices stored by row. The first 3 columns are generally the coordinates of a vertex, and remaining columns correspond to other values from <a href="#rgl.attrib"><code>rgl.attrib</code></a>.</p>
+<p>The <code>offsets</code> property gives the (0-based) offset of the first column for a particular attribute in a named object. Not all columns will be present in every object; if not present, the corresponding <code>offsets</code> entry will be <code>-1</code>. The entries are</p>
+<table>
+<thead>
+<tr class="header">
+<th align="left">Name</th>
+<th align="left">Meaning</th>
+</tr>
+</thead>
+<tbody>
+<tr class="odd">
+<td align="left">vofs</td>
+<td align="left">Offset to 3 columns of vertex data in XYZ order</td>
+</tr>
+<tr class="even">
+<td align="left">cofs</td>
+<td align="left">Offset to 4 columns of colour data in RGBA order</td>
+</tr>
+<tr class="odd">
+<td align="left">nofs</td>
+<td align="left">Offset to 3 columns of normal data</td>
+</tr>
+<tr class="even">
+<td align="left">radofs</td>
+<td align="left">Offset to 1 column of sphere radius data</td>
+</tr>
+<tr class="odd">
+<td align="left">oofs</td>
+<td align="left">Offset to 2 columns of text or sprite origin data</td>
+</tr>
+<tr class="even">
+<td align="left">tofs</td>
+<td align="left">Offset to 2 columns of texture coordinates</td>
+</tr>
+<tr class="odd">
+<td align="left">stride</td>
+<td align="left">Total number of columns in <code>values</code></td>
+</tr>
+</tbody>
+</table>
+<p>For example, to find the blue colour entry for vertex <code>i</code> in an object, one would first check if <code>offsets["cofs"]</code> was <code>-1</code>, indicating that no colour information was present. If not, the entry could be found using</p>
+<pre><code>values[offsets["stride"]*(i-1) + offsets["cofs"] + 2]</code></pre>
+<p>This assumes <code>i</code> is specified using 1-based vertex counting as in R, and writes <code>values</code> and <code>offsets</code> instead of the fully specified <code><prefix>rgl.values</code> and <code><prefix>rgl.offsets</code> for clarity.</p>
+<p>Changes to <code>values</code> need to be pushed to the graphics system to be reflected in the scene; see the calls to <code>gl.bindBuffer</code> and <code>gl.bufferData</code> in the source to <a href="#propertySlider"><code>propertySlider</code></a> for details.</p>
+</div>
+</div>
+<div id="index" class="section level2">
+<h2>Index</h2>
+<p>The following functions and <code>rglClass</code> properties and methods are described in this document:<br></p>
+<div class="nostripes">
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a href="#FOV">FOV</a>  </td>
+<td align="left"><a href="#delFromSubscene">delFromSubscene</a>  </td>
+<td align="left"><a href="#listeners">listeners</a>  </td>
+<td align="left"><a href="#propertySlider">propertySlider</a>  </td>
+<td align="left"><a href="#toggleButton">toggleButton</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#addToSubscene">addToSubscene</a>  </td>
+<td align="left"><a href="#drawFns">drawFns</a>  </td>
+<td align="left"><a href="#matrixSetter">matrixSetter</a>  </td>
+<td align="left"><a href="#propertySlider">propertySlider</a>  </td>
+<td align="left"><a href="#userMatrix">userMatrix</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#ageControl">ageControl</a>  </td>
+<td align="left"><a href="#drawScene">drawScene</a>  </td>
+<td align="left"><a href="#offsets">offsets</a>  </td>
+<td align="left"><a href="#rglClass">rglClass</a>  </td>
+<td align="left"><a href="#values">values</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#ageSetter">ageSetter</a>  </td>
+<td align="left"><a href="#elementId2Prefix">elementId2Prefix</a>  </td>
+<td align="left"><a href="#par3dinterpSetter">par3dinterpSetter</a>  </td>
+<td align="left"><a href="#rglwidget">rglwidget</a>  </td>
+<td align="left"><a href="#vertexSetter">vertexSetter</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#clipFns">clipFns</a>  </td>
+<td align="left"><a href="#getSubsceneEntries">getSubsceneEntries</a>  </td>
+<td align="left"><a href="#playwidget">playwidget</a>  </td>
+<td align="left"><a href="#setSubsceneEntries">setSubsceneEntries</a>  </td>
+<td align="left"><a href="#viewport">viewport</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#clipplaneSlider">clipplaneSlider</a>  </td>
+<td align="left"><a href="#inSubscene">inSubscene</a>  </td>
+<td align="left"><a href="#propertySetter">propertySetter</a>  </td>
+<td align="left"><a href="#subsetSlider">subsetSlider</a>  </td>
+<td align="left"><a href="#zoom">zoom</a>  </td>
+</tr>
+</tbody>
+</table>
+</div>
+</div>
+
+
+
+<!-- dynamically load mathjax for compatibility with self-contained -->
+<script>
+  (function () {
+    var script = document.createElement("script");
+    script.type = "text/javascript";
+    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
+    document.getElementsByTagName("head")[0].appendChild(script);
+  })();
+</script>
+
+</body>
+</html>
diff --git a/inst/doc/rgl.Rmd b/inst/doc/rgl.Rmd
new file mode 100644
index 0000000..197d311
--- /dev/null
+++ b/inst/doc/rgl.Rmd
@@ -0,0 +1,596 @@
+---
+title: "rgl Overview"
+author: "Duncan Murdoch"
+date: "`r format(Sys.time(), '%B %d, %Y')`"
+output:
+  rmarkdown::html_vignette:
+    toc: yes
+    fig_width: 5
+    fig_height: 5
+vignette: >
+  %\VignetteIndexEntry{rgl Overview} 
+  %\VignetteEngine{knitr::rmarkdown}
+---
+
+```{r setup, echo=FALSE, results="asis"}
+source("setup.R")
+knitr::opts_chunk$set(rgl.newwindow = TRUE)
+set.seed(123)
+```
+
+
+
+## Introduction
+
+The `rgl` package is used to produce interactive 3-D plots.  It contains
+high-level graphics commands modelled loosely after classic R graphics,
+but working in three dimensions.  It also contains low level structure
+inspired by (but incompatible with) the `grid` package.
+
+This document gives an overview.  See the help pages for details.
+
+### About this document
+
+This document was written in R Markdown, using the `knitr` package
+for production.  It corresponds to rgl version 
+`r packageVersion("rgl")`.
+
+Most of the highlighted function names are HTML links.
+The internal links should work in any browser; the links to
+help topics should work if you view the vignette from
+within the R help system.
+
+The document includes WebGL figures.  To view these, you must have
+Javascript and WebGL enabled in your browser.  Some older browsers
+may not support this -- see http://get.webgl.org for tests
+and links to a discussion.
+
+The WebGL figures were produced using the `rglwidget`
+package, version `r packageVersion("rglwidget")`.
+
+
+## Basics and High Level Functions
+
+The `r indexfns("plot3d")` function
+plots points within an rgl window.  It is similar to the classic 
+`r linkfn("plot", pkg="graphics")` function,
+but works in 3 dimensions.
+
+For example
+```{r echo=1}
+with(iris, plot3d(Sepal.Length, Sepal.Width, Petal.Length, 
+                  type="s", col=as.numeric(Species)))
+rglwidget()
+```
+can be used to plot three columns of the `iris` data.  
+Allowed plot types include `"p", "l", "h", "s"`,
+meaning points, lines, segments from z=0, and spheres.  There's
+a lot of flexibility in specifying the coordinates; the 
+`r linkfn("xyz.coords", pkg = "grDevices")` function
+from the `grDevices` package is used for this.
+
+You can use your mouse to manipulate the plot.  The default is that
+if you click and hold with the left mouse button, you can rotate 
+the plot by dragging it.  The right mouse button is used to resize
+it, and the middle button changes the perspective in the point of view.
+
+If you call `r linkfn("plot3d")` again, it will overwrite the current plot.
+To open a new graphics window, use `r linkfn("open3d")`.
+ 
+The other high level function is `r indexfns("persp3d")` to draw surfaces.
+It is
+similar to the classic `r linkfn("persp", pkg = "graphics")`
+function, but with greater flexibility.
+First, any of `x`, `y` or `z`
+can be specified using matrices, not just `z`.  This allows parametric
+surfaces to be plotted. 
+An even simpler specification is possible:  `x` may be a function,
+in which case `persp3d` will work out the grid itself.  See 
+`r linkfn("persp3d.function", text="?persp3d.function", pkg="rgl")`
+for details.  For example, the `MASS` package estimates
+Gamma parameters using maximum likelihood in a 
+`r linkfn("fitdistr", text="?MASS::fitdistr", pkg="MASS")` example.
+Here we show the log likelihood surface. 
+```{r persp3d, webgl=TRUE, fig.height=3, fig.width=6}
+library(MASS)
+# from the fitdistr example
+set.seed(123)
+x <- rgamma(100, shape = 5, rate = 0.1)
+fit <- fitdistr(x, dgamma, list(shape = 1, rate = 0.1), lower = 0.001)
+loglik <- function(shape, rate) sum(dgamma(x, shape=shape, rate=rate, 
+                                           log=TRUE))
+loglik <- Vectorize(loglik)
+xlim <- fit$estimate[1]+4*fit$sd[1]*c(-1,1)
+ylim <- fit$estimate[2]+4*fit$sd[2]*c(-1,1)
+
+mfrow3d(1, 2, sharedMouse = TRUE)
+persp3d(loglik, 
+        xlim = xlim, ylim = ylim,
+        n = 30)
+zlim <- fit$loglik + c(-qchisq(0.99, 2)/2, 0)
+next3d()
+persp3d(loglik, 
+        xlim = xlim, ylim = ylim, zlim = zlim,
+        n = 30)
+```
+ On the left, the whole surface over a range of the parameters; on the right, only the 
+parts of the surface with log likelihood values near the maximum.
+
+Note:  this example used the `knitr` hook functions 
+(see `r linkfn("setupKnitr")`) to insert the
+scene into this vignette; the previous example used the `rglwidget`
+function from the package of the same name.  We generally
+recommend the newer `r linkfn("rglwidget", pkg="rglwidget")` approach.
+
+## Adding Graphical Elements
+
+### Primitive shapes
+
+Just as we have `r linkfn("points", pkg="graphics")` and 
+`r linkfn("lines", pkg="graphics")` in classic graphics, there are a number
+of low level functions in `rgl` to add graphical elements to the
+currently active plot.  The "primitive" shapes are those that are 
+native to OpenGL:
+
+----------------------------- | -----------
+`r indexfns("points3d")`:     | adds points
+`r indexfns("lines3d")`:      | adds lines
+`r indexfns("segments3d")`:   | adds line segments
+`r indexfns("triangles3d")`:  | adds triangles
+`r indexfns("quads3d")`:      | adds quadrilaterals
+
+Each of the above functions takes arguments `x`, `y` and `z`, again
+using `r linkfn("xyz.coords", pkg="grDevices")` for flexibility.
+They group successive entries
+as necessary.  For example, the `r linkfn("triangles3d")` function takes each
+successive triple of points as the vertices of a triangle.
+
+You can use these functions to annotate the current graph, or to 
+construct a figure from scratch.
+
+### Constructed shapes
+
+`rgl` also has a number of objects which it constructs
+from the primitives.
+
+----------------------------- | -----------
+`r indexfns(c("text3d", "texts3d"))`: | adds text
+`r indexfns("abclines3d")`:   | adds straight lines to plot (like `abline`)
+`r indexfns("planes3d")`:     | adds planes to plot
+`r indexfns("clipplanes3d")`: | add clipping planes to plot
+`r indexfns(c("sprites3d", "particles3d"))`: | add sprites (fixed shapes or images) to plot
+`r indexfns("spheres3d")`:    | adds spheres
+`r indexfns(c("surface3d", "terrain3d"))`:    | a surface (as used in `r linkfn("persp3d")`)
+
+### Axes and other "decorations"
+
+The following low-level functions control the look of the graph:
+
+------------------------------------ | -----------
+`r indexfns(c("axes3d", "axis3d"))`: | add axes to plot
+`r indexfns(c("box3d", "bbox3d"))`:               | add box around plot
+`r indexfns("title3d")`:             | add title to plot
+`r indexfns("mtext3d")`:             | add marginal text to plot
+`r indexfns("decorate3d")`:          | add multiple "decorations" (scales, etc.) to plot
+`r indexfns("aspect3d")`:            | set the aspect ratios for the plot
+`r indexfns(c("bg3d", "bgplot3d"))`: | set the background of the scene
+`r indexfns("show2d")`:              | show a 2D plot or image in a 3D scene
+`r indexfns("legend3d")`:            | set a legend for the scene
+`r indexfns("grid3d")`:              | add a reference grid to a graph
+
+For example, to plot three random triangles, one could use
+```{r webgl=TRUE, fig.width=3, fig.height=3}
+triangles3d(cbind(x=rnorm(9), y=rnorm(9), z=rnorm(9)), col = "green")
+decorate3d()
+bg3d("lightgray")
+aspect3d(1,1,1)
+```
+
+Besides the `*3d` functions mentioned above, there are even lower-level
+functions 
+`r indexfns(c("rgl.primitive", "rgl.points", "rgl.linestrips", "rgl.lines", "rgl.triangles",
+"rgl.quads", "rgl.texts", "rgl.abclines", "rgl.planes", "rgl.bg",
+"rgl.clipplanes", "rgl.bbox", "rgl.spheres", "rgl.sprites", "rgl.surface"))`.  
+You should avoid using these functions, which do not
+work well with the higher level `*3d` functions.  See the 
+`r linkfn("r3d", text="?r3d", pkg="rgl")` help
+topic for details.
+
+## Controlling the Look of the Scene
+
+### Lighting
+
+In most scenes, objects are "lit", meaning that their appearance
+depends on their position and orientation relative to lights
+in the scene.  The lights themselves don't normally show up,
+but their effect on the objects does.
+
+Use the `r indexfns("light3d")` function to 
+specify the position and characteristics of a light.
+Lights may be infinitely distant, or may be embedded
+within the scene.  Their characteristics include 
+`ambient`, `diffuse`, and `specular` components, all
+defaulting to white.  The `ambient` component appears
+the same from any direction.  The `diffuse` component 
+depends on the angle between the surface and the light, 
+while the `specular` component also takes the viewer's
+position into account.
+
+The `r indexfns("rgl.light")` function is a lower-level
+function with different defaults; users should normally
+use `r linkfn("light3d")`.
+
+### Materials
+
+The mental model used in `rgl` is that the objects being shown
+in scenes are physical objects in space, with material properties
+that affect how light reflects from them (or is emitted by them).
+These are mainly controlled by the `r indexfns("material3d")` function,
+or by arguments to other functions that are passed to it.
+
+The material properties that can be set by calls to `material3d` are
+described in detail in the 
+`r linkfn("material3d", text="?material3d", pkg="rgl")` help page.
+Here we give an overview.
+
+Property  | Default | Meaning 
+--------- | ------- | ------------------
+color     | white   | vector of surface colors to apply to successive vertices for diffuse light
+alpha     | 1       | transparency:  0 is invisible, 1 is opaque
+lit       | TRUE    | whether lighting calculations should be done
+ambient   | black   | color in ambient  light
+specular  | white   | color in specular light
+emission  | black   | color emitted by the surface
+shininess | 50      | controls the specular lighting:  high values look shiny
+smooth    | TRUE    | whether shading should be interpolated between vertices
+texture   | NULL    | optional path to a "texture" bitmap to be displayed on the surface
+front, back | fill  | should polygons be filled, or outlined? 
+size      | 3       | size of points in pixels
+lwd       | 1       | width of lines in pixels
+
+Other properties include 
+"texmipmap", "texmagfilter", "texminfilter", "texenvmap", "fog", 
+"point\_antialias", "line\_antialias", "depth\_mask", and "depth\_test"; 
+see the help page for details.
+
+There is also an `r indexfns("rgl.material")` function that works
+at a lower level; users should normally avoid it.
+
+### par3d:  Miscellaneous graphical parameters
+
+The `r indexfns("par3d")` function, modelled after the classic
+graphics `r linkfn("par", pkg="graphics")` function, sets or reads 
+a variety of different `rgl` internal
+parameters.  Some parameters are completely read-only; others are
+fixed at the time the window is opened, and others may be changed 
+at any time.
+
+Name        |  Changeable?     | Description
+----------- | ----- | -----------
+antialias   | fixed | Amount of hardware antialiasing 
+cex         |       | Default size for text
+family      |       | Device-independent font family name; see `r linkfn("text3d", text="?text3d", pkg="rgl")`
+font        |       | Integer font number
+useFreeType |       | Should FreeType fonts be used if available?
+fontname    | read-only | System-dependent font name set by `r indexfns("rglFonts")`
+FOV         |       | Field of view, in degrees.  Zero means isometric perspective
+ignoreExtent |      | Should `rgl` ignore the size of new objects when computing the bounding box?
+skipRedraw   |      | Should `rgl` suppress updates to the display? 
+maxClipPlanes | read-only | How many clip planes can be defined?
+modelMatrix | read-only | The OpenGL ModelView matrix; partly set by `r indexfns("view3d")` or the obsolete `r indexfns("rgl.viewpoint")`
+projMatrix  | read-only | The OpenGL Projection matrix
+bbox        | read-only | Current bounding-box of the scene
+viewport    |       | Dimensions in pixels of the scene within the window
+windowRect  |           | Dimensions in pixels of the window on the whole screen
+listeners   |           | Which subscenes respond to mouse actions in the current one
+mouseMode   |       | What the mouse buttons do.  See `r linkfn("mouseMode", '<code>"mouseMode"</code>')`
+observer    | read-only | The position of the observer; set by `r indexfns("observer3d")`
+scale       |           | Rescaling for each coordinate; see `r linkfn("aspect3d")`
+zoom        |           | Magnification of the scene
+
+### Default settings
+
+The `r indexfns("r3dDefaults")` list and the `r indexfns("getr3dDefaults")` 
+function control defaults in new windows opened by `r linkfn("open3d")`.  
+The function looks for the variable in the user's global environment,
+and if not found there, finds the one in the `rgl` namespace.  This
+allows the user to override the default settings for new windows.
+
+Once found, the `r3dDefaults` list provides initial values for `r linkfn("par3d")` parameters, as well as defaults for `r linkfn("material3d")` and `r linkfn("bg3d")` in components `"material"`
+and `"bg"` respectively.
+
+
+## Meshes:  Constructing Shapes 
+
+`rgl` includes a number of functions to construct and display 
+various solid shapes.  These generate objects of class `"shape3d"`,
+`"mesh3d"` or `"shapelist3d"`.  The details of the classes are 
+described below.  We start with functions to generate them.
+
+### Specific solids
+
+These functions generate specific shapes.  Optional arguments allow
+attributes such as colour or transformations to be specified.
+
+------------------------------------ | -----------
+`r indexfns(c("tetrahedron3d", "cube3d", "octahedron3d", "dodecahedron3d", "icosahedron3d"))`: | Platonic solids
+`r indexfns(c("cuboctahedron3d", "oh3d"))`:             | other solids
+
+```{r results="hide",webgl=TRUE}
+open3d()
+cols <- rainbow(7)
+layout3d(matrix(1:16, 4,4), heights=c(1,3,1,3))
+text3d(0,0,0,"tetrahedron3d"); next3d()
+shade3d(tetrahedron3d(col=cols[1])); next3d()
+text3d(0,0,0,"cube3d"); next3d()
+shade3d(cube3d(col=cols[2])); next3d()
+text3d(0,0,0,"octahedron3d"); next3d()
+shade3d(octahedron3d(col=cols[3])); next3d()
+text3d(0,0,0,"dodecahedron3d"); next3d()
+shade3d(dodecahedron3d(col=cols[4])); next3d()
+text3d(0,0,0,"icosahedron3d"); next3d()
+shade3d(icosahedron3d(col=cols[5])); next3d()
+text3d(0,0,0,"cuboctahedron3d"); next3d()
+shade3d(cuboctahedron3d(col=cols[6])); next3d()
+text3d(0,0,0,"oh3d"); next3d()
+shade3d(oh3d(col=cols[7]))
+```
+
+### Generating new shapes 
+
+These functions generate new shapes:
+
+------------------------------------ | -----------
+`r indexfns("cylinder3d")`: | generate a tube or cylinder
+`r indexfns("polygon3d")`:  | generate a flat polygon by triangulation
+`r indexfns("extrude3d")`:  | generate an "extrusion" of a polygon
+`r indexfns("turn3d")`:     | generate a solid of rotation
+`r indexfns("ellipse3d")`:  | generate an ellipsoid in various ways
+`r indexfns(c("tmesh3d", "qmesh3d"))`:  | generate a shape from vertices and faces
+`r indexfns("shapelist3d")`: | generate a shape by combining other shapes
+
+A related function is `r indexfns("triangulate")`, which takes a
+two dimensional polygon and divides it up into triangles using the 
+"ear-clipping" algorithm.
+
+### The underlying class structure for shapes
+
+`"shape3d"` is the basic abstract type.  Objects of this class can be
+displayed by `r indexfns("shade3d")` (which shades faces), 
+`r indexfns("wire3d")` (which draws edges), or `r indexfns("dot3d")`
+(which draws points at each vertex.)  Note that `wire3d` and `dot3d`
+only work within R; in HTML output from `r linkfn("writeWebGL")` only
+`shade3d` is supported.
+
+`"mesh3d"` is a descendant type.  Objects of this type contain the following 
+fields:
+
+Field        | Meaning
+------------ | ---------------
+vb           | A 4 by n matrix of vertices in homogeneous coordinates.  Each column is a point.
+it           | (optional) A 3 by t matrix of vertex indices.  Each column is a triangle.
+ib           | (optional) A 4 by q matrix of vertex indices.  Each column is a quadrilateral.
+material     | (optional) A list of material properties.
+normals      | (optional) A matrix of the same shape as vb, containing normal vectors at each vertex.
+texcoords    | (optional) A 2 by n matrix of texture coordinates corresponding to each vertex.
+
+### Manipulating shapes
+
+The final set of functions manipulate and modify mesh objects:
+
+------------------------------------ | -----------
+`r indexfns("addNormals")`: | add normal vectors to make a shape look smooth
+`r indexfns("subdivision3d")`: | add extra vertices to make it look even smoother
+
+## Multi-figure Layouts
+
+`rgl` has several functions to support displaying multiple different
+"subscenes" in the same window.  The high level functions are
+
+------------------------------------ | -----------
+`r indexfns("mfrow3d")`:  | Multiple figures (like `r linkfn("par", text = 'par("mfrow")', pkg="graphics")`
+`r indexfns("layout3d")`: | Multiple figures (like `r linkfn("layout", pkg="graphics")`)
+`r indexfns("next3d")`:   | Move to the next figure (like `r linkfn("plot.new", pkg="graphics")` or `r linkfn("frame", pkg="graphics")`)
+`r indexfns("subsceneList")`: | List all the subscenes in the current layout
+`r indexfns("clearSubsceneList")` | Clear the current list and revert to the previous one
+
+There are also lower level functions.
+
+------------------------------------ | -----------
+`r indexfns("newSubscene3d")`:     | Create a new subscene, with fine control over what is inherited from the parent
+`r indexfns("currentSubscene3d")`: | Report on the active subscene
+`r indexfns("subsceneInfo")`:      | Get information on current subscene
+`r indexfns("useSubscene3d")`:     | Make a different subscene active
+`r indexfns(c("addToSubscene3d", "delFromSubscene3d"))`: | Add objects to a subscene, or delete them
+`r indexfns("gc3d")`:              | Do "garbage collection":  delete objects that are not displayed in any subscene
+
+
+## Utility Functions
+
+
+### User interaction
+
+By default, `rgl` detects and handles mouse clicks within your scene,
+and uses these to control its appearance.  You can find out the current
+handlers using the following code:
+```{r}
+par3d("mouseMode")
+```
+The labels `c("left", "right", "middle")` refer to the buttons on
+a three button mouse, or simulations of them on other mice.  `"wheel"` 
+refers to the mouse wheel.
+
+The button actions generally correspond to click and drag operations.
+Possible values for `r indexfns("mouseMode", '<code>"mouseMode"</code>')` for buttons or the wheel are as follows:
+
+--------       | ---------
+`"none"`       | No action
+`"trackball"`  | The mouse acts as a virtual trackball. Clicking and dragging rotates the scene
+`"xAxis"`, `"yAxis"`, `"zAxis"`      | Like `"trackball"`, but restricted to rotation about one axis
+`"polar"`      | The mouse affects rotations by controlling polar coordinates directly
+`"selecting"`  | The mouse is being used by the `r linkfn("select3d")` function
+`"zoom"`       | The mouse zooms the display
+`"fov"`        | The mouse affects perspective by changing the field of view
+`"pull"`       | Rotating the mouse wheel towards the user "pulls the scene closer"
+`"push"`       | The same rotation "pushes the scene away"
+`"user"`       | A user action set by `r indexfns(c("rgl.setMouseCallbacks", "rgl.setWheelCallback"))`.  Use `r indexfns("rgl.getMouseCallbacks")` and `r indexfns("rgl.getWheelCallback")` to retrieve
+
+The following functions make use of the mouse for selection within a 
+scene.
+
+---------------------------- | -----------
+`r indexfns("identify3d")`   | like the classic graphics `r linkfn("identify", pkg="graphics")` function
+`r indexfns("select3d")`     | returns a function that tests whether a coordinate was selected
+`r indexfns("selectpoints3d")` | selects from specific objects
+
+The `r indexfns("rgl.select3d")` function is an obsolete version of
+`select3d`, and `r indexfns("rgl.select")` is a low-level support
+function.
+
+### Animations
+
+`rgl` has several functions that can be used to construct
+animations.  These are based on functions that update the
+scene according to the current real-world time, and repeated
+calls to those.  The functions are:
+
+---------------------- | -------------
+`r indexfns("play3d")` | Repeatedly call the update function 
+`r indexfns("spin3d")` | Update the display by rotating at a constant rate
+`r indexfns("par3dinterp")` | Compute new values of some `r linkfn("par3d")` parameters by interpolation over time
+
+See the `r linkfn("movie3d")` function for a way to output an animation
+to a file on disk.  
+Animations are not currently supported 
+in the HTML written by `r linkfn("writeWebGL")`, though the
+`rglwidget::playwidget` function provides equivalent functionality.
+
+### Exporting and importing scenes
+
+`rgl` contains several functions to write scenes to disk for use
+by other software, or to read them in.
+
+In order from highest fidelity to lowest, the functions are:
+
+----------- | -------------
+`r indexfns("scene3d")`    | Save a scene to an R variable, which can be saved and reloaded
+`r indexfns("writeWebGL")` | Write HTML and Javascript to display a scene in a web browser.  (See also [User Interaction in WebGL](WebGL.html).)
+`r indexfns("writePLY")`   | Write PLY files (commonly used in 3D printing)
+`r indexfns(c("readOBJ", "writeOBJ"))`   | Read or write OBJ files (commonly used in 3D graphics)
+`r indexfns(c("readSTL", "writeSTL"))`   | Read or write STL files (also common in 3D printing)
+`r indexfns("rgl.useNULL")`  | A helper function for setting a NULL device
+
+See the help page `r linkfn("rgl.useNULL", pkg="rgl")` for instructions on how
+to use `rgl` on a "headless" system.
+
+There are also functions to save snapshots or other recordings of a scene,
+without any 3D information being saved:
+
+------------ | -------------
+`r indexfns("snapshot3d")` | Save a PNG file bitmap of the scene
+`r indexfns("rgl.postscript")` | Save a Postscript, LaTeX, PDF, SVG or PGF vector rendering of the scene
+`r indexfns("movie3d")`    | Save a series of bitmaps to be assembled into a movie
+`r indexfns("rgl.pixels")` | Obtain pixel-level information about the scene in an R variable
+`r indexfns("rgl.Sweave")` | Driver function for inserting a snapshot into a Sweave document.
+`r indexfns(c("hook_rgl", "hook_webgl"))` | `knitr` hook functions for inserting images into a document.
+`r indexfns("setupKnitr")` | Function to set up `knitr` hooks
+
+The `r indexfns("rgl.snapshot")` function is identical to `snapshot3d`.
+The functions `r indexfns(c("rgl.Sweave.off", "Sweave.snapshot"))` are 
+involved in Sweave processing and not normally called by users.
+
+### Working with WebGL scenes
+
+There are currently two schemes for exporting a scene to a web page.
+Both require the `rglwidget` package and use the same underlying
+code.
+
+The recommended approach works with the `htmlwidgets` framework
+(see http://www.htmlwidgets.org/).  In an R Markdown document
+in `knitr`, use the chunk option `webgl=TRUE`, or the 
+`rglwidget::rglwidget()` function.  More details are given in the vignette 
+[User Interaction in WebGL](WebGL.html).
+
+The older approach uses the `writeWebGL` function to export a scene 
+to HTML and Javascript code.  
+The functions below write HTML and Javascript for working with the 
+exported scene.  
+
+------------------------------------ | -------------
+`r indexfns("propertySlider")`       | insert a slider to make changes to a scene
+`r indexfns("clipplaneSlider")`      | insert a slider to control a clipping plane
+`r indexfns("subsetSlider")`         | insert a slider to control which objects are displayed
+`r indexfns("toggleButton")`         | insert a button to toggle some items
+`r indexfns("propertySetter")`       | function to modify properties
+`r indexfns("subsetSetter")`         | function to choose subsets
+`r indexfns("ageSetter")`            | function to "age" vertices
+`r indexfns("par3dinterpSetter")`    | function like `r linkfn("par3dinterp")`
+`r indexfns("vertexSetter")`         | function to modify individual vertices
+`r indexfns("matrixSetter")`         | function to modify matrices
+
+### Working with the scene
+
+`rgl` maintains internal structures for all the scenes it displays.
+The following functions allow users to find information about them
+and manipulate them.
+
+------------------------------------ | -----------
+`r indexfns("open3d")`               | open a new window
+`r indexfns("rgl.close")`            | close the current window
+`r indexfns("rgl.bringtotop")`       | bring the current window to the top
+`r indexfns("rgl.cur")`              | id of the active device
+`r indexfns("rgl.dev.list")`         | ids of all active devices
+`r indexfns("rgl.set")`              | set a particular device to be active
+`r indexfns("rgl.ids")`              | ids and types of all current objects
+`r indexfns(c("rgl.attrib", "rgl.attrib.count"))`: | attributes of objects in the scene
+`r indexfns(c("pop3d", "rgl.pop"))`     | delete an object from the scene
+`r indexfns(c("clear3d", "rgl.clear"))`            | delete all objects of certain classes
+`r indexfns("rgl.projection")`        | return information about the current projection
+`r indexfns(c("rgl.user2window", "rgl.window2user"))` | convert between coordinates in the current projection
+
+In addition to these, there are some other related functions which
+should rarely be called by users: `r indexfns(c("rgl.init", "rgl.open", "rgl.quit"))`.  
+
+
+### Working with 3-D vectors
+
+Most `rgl` functions work internally with "homogeneous" coordinates.
+In this system, 3-D points are represented with 4 coordinates, generally
+called (x, y, z, w).  The corresponding Euclidean point is
+(x/w, y/w, z/w), if w is nonzero; zero values of w correspond to 
+"points at infinity".  The advantage of this system is that
+affine transformations including translations and perspective shifts
+become linear transformations, with multiplication by a 4 by 4 matrix.
+
+`rgl` has the following functions to work with homogeneous coordinates:
+
+------------------------------------ | -----------
+`r indexfns(c("asEuclidean", "asHomogeneous"))`: | convert between homogeneous and Euclidean coordinates
+`r indexfns(c("rotate3d", "scale3d", "translate3d"))`:  | apply a transformation
+`r indexfns("transform3d")`:  | apply a general transformation
+`r indexfns(c("rotationMatrix", "scaleMatrix", "translationMatrix"))`:  | compute the transformation matrix
+`r indexfns("identityMatrix")` | return a 4 x 4 identity matrix
+
+There is also a function `r indexfns("GramSchmidt")`, mainly for internal
+use:  it does a Gram-Schmidt orthogonalization of a 3x3 matrix,
+with some specializations for its use in `r linkfn("cylinder3d")`.
+
+## Warning:  Work in Progress!
+
+This vignette is in a preliminary form.  Many aspects of the rgl
+package are not described, or do not have examples.  There may
+even be functions that are missed completely, if the following
+list is not empty:
+```{r echo=FALSE}
+setdiff(ls("package:rgl"), documentedfns)
+```
+
+## Index of Functions
+
+The following functions and constants are described in this document:<br>
+
+```{r echo=FALSE, results="asis"}
+writeIndex(cols = 5)
+```
+
+
diff --git a/inst/doc/rgl.html b/inst/doc/rgl.html
new file mode 100644
index 0000000..1900a4b
--- /dev/null
+++ b/inst/doc/rgl.html
@@ -0,0 +1,3481 @@
+<!DOCTYPE html>
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+
+<head>
+
+<meta charset="utf-8">
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta name="generator" content="pandoc" />
+
+<meta name="author" content="Duncan Murdoch" />
+
+<meta name="date" content="2016-01-04" />
+
+<title>rgl Overview</title>
+
+<script src="data:application/x-javascript,%28function%28%29%20%7B%0A%20%20%2F%2F%20If%20window%2EHTMLWidgets%20is%20already%20defined%2C%20then%20use%20it%3B%20otherwise%20create%20a%0A%20%20%2F%2F%20new%20object%2E%20This%20allows%20preceding%20code%20to%20set%20options%20that%20affect%20the%0A%20%20%2F%2F%20initialization%20process%20%28though%20none%20currently%20exist%29%2E%0A%20%20window%2EHTMLWidgets%20%3D%20window%2EHTMLWidgets%20%7C%7C%20%7B%7D%3B%0A%0A%20%20%2F%2F%20See%20if%20 [...]
+<link href="data:text/css,%2ErglPlayer%20%7B%0A%20%20width%3A%20auto%3B%0A%20%20height%3A%20auto%3B%0A%7D%0A%0A%2ErglPlayer%20%2Ergl%2Dbutton%20%7B%0A%20%20width%3A%20auto%3B%0A%20%20display%3A%20inline%2Dblock%3B%0A%20%20font%2Dsize%3A%2075%25%3B%0A%7D%0A%0A%2ErglPlayer%20%2Ergl%2Dslider%20%7B%0A%20%20display%3A%20inline%2Dblock%3B%0A%20%20width%3A%2030%25%3B%0A%7D%0A%0A%2ErglPlayer%20%2Ergl%2Dlabel%20%7B%0A%20%20display%3A%20inline%3B%0A%20%20padding%2Dleft%3A%206px%3B%0A%20%20padding% [...]
+<script src="data:application/x-javascript,%0ArglwidgetClass%20%3D%20function%28%29%20%7B%0A%20%20%20%20this%2Ecanvas%20%3D%20null%3B%0A%20%20%20%20this%2EuserMatrix%20%3D%20new%20CanvasMatrix4%28%29%3B%0A%20%20%20%20this%2Etypes%20%3D%20%5B%5D%3B%0A%20%20%20%20this%2EprMatrix%20%3D%20new%20CanvasMatrix4%28%29%3B%0A%20%20%20%20this%2EmvMatrix%20%3D%20new%20CanvasMatrix4%28%29%3B%0A%20%20%20%20this%2Evp%20%3D%20null%3B%0A%20%20%20%20this%2EprmvMatrix%20%3D%20null%3B%0A%20%20%20%20this%2Eo [...]
+<script src="data:application/x-javascript,%2F%2A%0A%20%2A%20Copyright%20%28C%29%202009%20Apple%20Inc%2E%20All%20Rights%20Reserved%2E%0A%20%2A%0A%20%2A%20Redistribution%20and%20use%20in%20source%20and%20binary%20forms%2C%20with%20or%20without%0A%20%2A%20modification%2C%20are%20permitted%20provided%20that%20the%20following%20conditions%0A%20%2A%20are%20met%3A%0A%20%2A%201%2E%20Redistributions%20of%20source%20code%20must%20retain%20the%20above%20copyright%0A%20%2A%20%20%20%20notice%2C%20th [...]
+<script src="data:application/x-javascript,%2F%2A%20el%20is%20the%20div%2C%20holding%20the%20rgl%20object%20as%20el%2Erglinstance%2C%0A%20%20%20%20%20which%20holds%20x%20as%20el%2Erglinstance%2Escene%0A%20%20%20x%20is%20the%20JSON%20encoded%20rglwidget%2E%0A%2A%2F%0A%0A%0AHTMLWidgets%2Ewidget%28%7B%0A%0A%20%20name%3A%20%27rglWebGL%27%2C%0A%0A%20%20type%3A%20%27output%27%2C%0A%0A%20%20initialize%3A%20function%28el%2C%20width%2C%20height%29%20%7B%0A%20%20%20%20el%2Ewidth%20%3D%20width%3B%0 [...]
+
+
+<style type="text/css">code{white-space: pre;}</style>
+<style type="text/css">
+table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
+  margin: 0; padding: 0; vertical-align: baseline; border: none; }
+table.sourceCode { width: 100%; line-height: 100%; }
+td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
+td.sourceCode { padding-left: 5px; }
+code > span.kw { color: #007020; font-weight: bold; }
+code > span.dt { color: #902000; }
+code > span.dv { color: #40a070; }
+code > span.bn { color: #40a070; }
+code > span.fl { color: #40a070; }
+code > span.ch { color: #4070a0; }
+code > span.st { color: #4070a0; }
+code > span.co { color: #60a0b0; font-style: italic; }
+code > span.ot { color: #007020; }
+code > span.al { color: #ff0000; font-weight: bold; }
+code > span.fu { color: #06287e; }
+code > span.er { color: #ff0000; font-weight: bold; }
+</style>
+<style type="text/css">
+  pre:not([class]) {
+    background-color: white;
+  }
+</style>
+
+
+<link href="data:text/css,body%20%7B%0A%20%20background%2Dcolor%3A%20%23fff%3B%0A%20%20margin%3A%201em%20auto%3B%0A%20%20max%2Dwidth%3A%20700px%3B%0A%20%20overflow%3A%20visible%3B%0A%20%20padding%2Dleft%3A%202em%3B%0A%20%20padding%2Dright%3A%202em%3B%0A%20%20font%2Dfamily%3A%20%22Open%20Sans%22%2C%20%22Helvetica%20Neue%22%2C%20Helvetica%2C%20Arial%2C%20sans%2Dserif%3B%0A%20%20font%2Dsize%3A%2014px%3B%0A%20%20line%2Dheight%3A%201%2E35%3B%0A%7D%0A%0A%23header%20%7B%0A%20%20text%2Dalign%3A% [...]
+
+</head>
+
+<body>
+
+
+
+<div id="header">
+<h1 class="title">rgl Overview</h1>
+<h4 class="author"><em>Duncan Murdoch</em></h4>
+<h4 class="date"><em>January 04, 2016</em></h4>
+</div>
+
+<div id="TOC">
+<ul>
+<li><a href="#introduction">Introduction</a><ul>
+<li><a href="#about-this-document">About this document</a></li>
+</ul></li>
+<li><a href="#basics-and-high-level-functions">Basics and High Level Functions</a></li>
+<li><a href="#adding-graphical-elements">Adding Graphical Elements</a><ul>
+<li><a href="#primitive-shapes">Primitive shapes</a></li>
+<li><a href="#constructed-shapes">Constructed shapes</a></li>
+<li><a href="#axes-and-other-decorations">Axes and other “decorations”</a></li>
+</ul></li>
+<li><a href="#controlling-the-look-of-the-scene">Controlling the Look of the Scene</a><ul>
+<li><a href="#lighting">Lighting</a></li>
+<li><a href="#materials">Materials</a></li>
+<li><a href="#par3d-miscellaneous-graphical-parameters">par3d: Miscellaneous graphical parameters</a></li>
+<li><a href="#default-settings">Default settings</a></li>
+</ul></li>
+<li><a href="#meshes-constructing-shapes">Meshes: Constructing Shapes</a><ul>
+<li><a href="#specific-solids">Specific solids</a></li>
+<li><a href="#generating-new-shapes">Generating new shapes</a></li>
+<li><a href="#the-underlying-class-structure-for-shapes">The underlying class structure for shapes</a></li>
+<li><a href="#manipulating-shapes">Manipulating shapes</a></li>
+</ul></li>
+<li><a href="#multi-figure-layouts">Multi-figure Layouts</a></li>
+<li><a href="#utility-functions">Utility Functions</a><ul>
+<li><a href="#user-interaction">User interaction</a></li>
+<li><a href="#animations">Animations</a></li>
+<li><a href="#exporting-and-importing-scenes">Exporting and importing scenes</a></li>
+<li><a href="#working-with-webgl-scenes">Working with WebGL scenes</a></li>
+<li><a href="#working-with-the-scene">Working with the scene</a></li>
+<li><a href="#working-with-3-d-vectors">Working with 3-D vectors</a></li>
+</ul></li>
+<li><a href="#warning-work-in-progress">Warning: Work in Progress!</a></li>
+<li><a href="#index-of-functions">Index of Functions</a></li>
+</ul>
+</div>
+
+<pre><code>## Warning: These vignettes assume pandoc version 1.13.1; older versions may
+## give poor formatting.</code></pre>
+<style>
+    .nostripes tr.even {background-color: white;}
+    table {border-style: none;}
+    table th {border-style: none;}
+    table td {border-style: none;}
+    a[href^=".."] {text-decoration: underline;}
+    </style>
+    
+
+
+
+<div id="introduction" class="section level2">
+<h2>Introduction</h2>
+<p>The <code>rgl</code> package is used to produce interactive 3-D plots. It contains high-level graphics commands modelled loosely after classic R graphics, but working in three dimensions. It also contains low level structure inspired by (but incompatible with) the <code>grid</code> package.</p>
+<p>This document gives an overview. See the help pages for details.</p>
+<div id="about-this-document" class="section level3">
+<h3>About this document</h3>
+<p>This document was written in R Markdown, using the <code>knitr</code> package for production. It corresponds to rgl version 0.95.1441.</p>
+<p>Most of the highlighted function names are HTML links. The internal links should work in any browser; the links to help topics should work if you view the vignette from within the R help system.</p>
+<p>The document includes WebGL figures. To view these, you must have Javascript and WebGL enabled in your browser. Some older browsers may not support this – see <a href="http://get.webgl.org">http://get.webgl.org</a> for tests and links to a discussion.</p>
+<p>The WebGL figures were produced using the <code>rglwidget</code> package, version 0.1.1434.</p>
+</div>
+</div>
+<div id="basics-and-high-level-functions" class="section level2">
+<h2>Basics and High Level Functions</h2>
+<p>The <a name="plot3d"><a href="#plot3d"><code>plot3d</code></a></a> function plots points within an rgl window. It is similar to the classic <a href="../../graphics/help/plot"><code>plot</code></a> function, but works in 3 dimensions.</p>
+<p>For example</p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">with</span>(iris, <span class="kw">plot3d</span>(Sepal.Length, Sepal.Width, Petal.Length, 
+                  <span class="dt">type=</span><span class="st">"s"</span>, <span class="dt">col=</span><span class="kw">as.numeric</span>(Species)))</code></pre>
+<p><div id="rgl28758" style="width:480px;height:480px;" class="rglWebGL"></div>
+<script type="application/json" data-for="rgl28758">{"x":{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":26,"objects":{ [...]
+<p>You can use your mouse to manipulate the plot. The default is that if you click and hold with the left mouse button, you can rotate the plot by dragging it. The right mouse button is used to resize it, and the middle button changes the perspective in the point of view.</p>
+<p>If you call <a href="#plot3d"><code>plot3d</code></a> again, it will overwrite the current plot. To open a new graphics window, use <a href="#open3d"><code>open3d</code></a>.</p>
+<p>The other high level function is <a name="persp3d"><a href="#persp3d"><code>persp3d</code></a></a> to draw surfaces. It is similar to the classic <a href="../../graphics/help/persp"><code>persp</code></a> function, but with greater flexibility. First, any of <code>x</code>, <code>y</code> or <code>z</code> can be specified using matrices, not just <code>z</code>. This allows parametric surfaces to be plotted. An even simpler specification is possible: <code>x</code> may be a function, [...]
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(MASS)
+<span class="co"># from the fitdistr example</span>
+<span class="kw">set.seed</span>(<span class="dv">123</span>)
+x <-<span class="st"> </span><span class="kw">rgamma</span>(<span class="dv">100</span>, <span class="dt">shape =</span> <span class="dv">5</span>, <span class="dt">rate =</span> <span class="fl">0.1</span>)
+fit <-<span class="st"> </span><span class="kw">fitdistr</span>(x, dgamma, <span class="kw">list</span>(<span class="dt">shape =</span> <span class="dv">1</span>, <span class="dt">rate =</span> <span class="fl">0.1</span>), <span class="dt">lower =</span> <span class="fl">0.001</span>)
+loglik <-<span class="st"> </span>function(shape, rate) <span class="kw">sum</span>(<span class="kw">dgamma</span>(x, <span class="dt">shape=</span>shape, <span class="dt">rate=</span>rate, 
+                                           <span class="dt">log=</span><span class="ot">TRUE</span>))
+loglik <-<span class="st"> </span><span class="kw">Vectorize</span>(loglik)
+xlim <-<span class="st"> </span>fit$estimate[<span class="dv">1</span>]+<span class="dv">4</span>*fit$sd[<span class="dv">1</span>]*<span class="kw">c</span>(-<span class="dv">1</span>,<span class="dv">1</span>)
+ylim <-<span class="st"> </span>fit$estimate[<span class="dv">2</span>]+<span class="dv">4</span>*fit$sd[<span class="dv">2</span>]*<span class="kw">c</span>(-<span class="dv">1</span>,<span class="dv">1</span>)
+
+<span class="kw">mfrow3d</span>(<span class="dv">1</span>, <span class="dv">2</span>, <span class="dt">sharedMouse =</span> <span class="ot">TRUE</span>)
+<span class="kw">persp3d</span>(loglik, 
+        <span class="dt">xlim =</span> xlim, <span class="dt">ylim =</span> ylim,
+        <span class="dt">n =</span> <span class="dv">30</span>)
+zlim <-<span class="st"> </span>fit$loglik +<span class="st"> </span><span class="kw">c</span>(-<span class="kw">qchisq</span>(<span class="fl">0.99</span>, <span class="dv">2</span>)/<span class="dv">2</span>, <span class="dv">0</span>)
+<span class="kw">next3d</span>()
+<span class="kw">persp3d</span>(loglik, 
+        <span class="dt">xlim =</span> xlim, <span class="dt">ylim =</span> ylim, <span class="dt">zlim =</span> zlim,
+        <span class="dt">n =</span> <span class="dv">30</span>)</code></pre>
+<script>CanvasMatrix4=function(m){if(typeof m=='object'){if("length"in m&&m.length>=16){this.load(m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8],m[9],m[10],m[11],m[12],m[13],m[14],m[15]);return}else if(m instanceof CanvasMatrix4){this.load(m);return}}this.makeIdentity()};CanvasMatrix4.prototype.load=function(){if(arguments.length==1&&typeof arguments[0]=='object'){var matrix=arguments[0];if("length"in matrix&&matrix.length==16){this.m11=matrix[0];this.m12=matrix[1];this.m13=matrix[2];this. [...]
+<script>
+rglwidgetClass = function() {
+this.canvas = null;
+this.userMatrix = new CanvasMatrix4();
+this.types = [];
+this.prMatrix = new CanvasMatrix4();
+this.mvMatrix = new CanvasMatrix4();
+this.vp = null;
+this.prmvMatrix = null;
+this.origs = null;
+this.gl = null;
+this.scene = null;
+};
+(function() {
+this.multMV = function(M, v) {
+return [ M.m11 * v[0] + M.m12 * v[1] + M.m13 * v[2] + M.m14 * v[3],
+M.m21 * v[0] + M.m22 * v[1] + M.m23 * v[2] + M.m24 * v[3],
+M.m31 * v[0] + M.m32 * v[1] + M.m33 * v[2] + M.m34 * v[3],
+M.m41 * v[0] + M.m42 * v[1] + M.m43 * v[2] + M.m44 * v[3]
+];
+};
+this.vlen = function(v) {
+return Math.sqrt(this.dotprod(v, v));
+};
+this.dotprod = function(a, b) {
+return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
+}
+this.xprod = function(a, b) {
+return [a[1]*b[2] - a[2]*b[1],
+a[2]*b[0] - a[0]*b[2],
+a[0]*b[1] - a[1]*b[0]];
+};
+this.cbind = function(a, b) {
+return a.map(function(currentValue, index, array) {
+return currentValue.concat(b[index]);
+});
+};
+this.swap = function(a, i, j) {
+var temp = a[i];
+a[i] = a[j];
+a[j] = temp;
+};
+this.flatten = function(a) {
+return [].concat.apply([], a);
+};
+/* set element of 1d or 2d array as if it was flattened.  Column major, zero based! */
+this.setElement = function(a, i, value) {
+if (Array.isArray(a[0])) {
+var dim = a.length,
+col = Math.floor(i/dim),
+row = i % dim;
+a[row][col] = value;
+} else {
+a[i] = value;
+}
+};
+this.transpose = function(a) {
+var newArray = [],
+n = a.length,
+m = a[0].length,
+i;
+for(i = 0; i < m; i++){
+newArray.push([]);
+}
+for(i = 0; i < n; i++){
+for(var j = 0; j < m; j++){
+newArray[j].push(a[i][j]);
+}
+}
+return newArray;
+};
+this.sumsq = function(x) {
+var result = 0, i;
+for (i=0; i < x.length; i++)
+result += x[i]*x[i];
+return result;
+};
+this.toCanvasMatrix4 = function(mat) {
+if (mat instanceof CanvasMatrix4)
+return mat;
+var result = new CanvasMatrix4();
+mat = this.flatten(this.transpose(mat));
+result.load(mat);
+return result;
+};
+this.stringToRgb = function(s) {
+s = s.replace("#", "");
+var bigint = parseInt(s, 16);
+return [((bigint >> 16) & 255)/255,
+((bigint >> 8) & 255)/255,
+(bigint & 255)/255];
+};
+this.componentProduct = function(x, y) {
+if (typeof y === "undefined") {
+this.alertOnce("Bad arg to componentProduct");
+}
+var result = new Float32Array(3), i;
+for (i = 0; i<3; i++)
+result[i] = x[i]*y[i];
+return result;
+};
+this.getPowerOfTwo = function(value) {
+var pow = 1;
+while(pow<value) {
+pow *= 2;
+}
+return pow;
+};
+this.unique = function(arr) {
+arr = [].concat(arr);
+return arr.filter(function(value, index, self) {
+return self.indexOf(value) === index;
+});
+};
+this.repeatToLen = function(arr, len) {
+arr = [].concat(arr);
+while (arr.length < len/2)
+arr = arr.concat(arr);
+return arr.concat(arr.slice(0, len - arr.length));
+};
+this.alertOnce = function(msg) {
+if (typeof this.alerted !== "undefined")
+return;
+this.alerted = true;
+alert(msg);
+};
+this.f_is_lit = 1;
+this.f_is_smooth = 2;
+this.f_has_texture = 4;
+this.f_is_indexed = 8;
+this.f_depth_sort = 16;
+this.f_fixed_quads = 32;
+this.f_is_transparent = 64;
+this.f_is_lines = 128;
+this.f_sprites_3d = 256;
+this.f_sprite_3d = 512;
+this.f_is_subscene = 1024;
+this.f_is_clipplanes = 2048;
+this.whichList = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags;
+if (obj.type === "light")
+return "lights";
+if (flags & this.f_is_subscene)
+return "subscenes";
+if (flags & this.f_is_clipplanes)
+return "clipplanes";
+if (flags & this.f_is_transparent)
+return "transparent";
+return "opaque";
+};
+this.getObj = function(id) {
+if (typeof id !== "number") {
+this.alertOnce("getObj id is "+typeof id);
+}
+return this.scene.objects[id];
+};
+this.getIdsByType = function(type, subscene) {
+var
+result = [], i, self = this;
+if (typeof subscene === "undefined") {
+Object.keys(this.scene.objects).forEach(
+function(key) {
+key = parseInt(key, 10);
+if (self.getObj(key).type === type)
+result.push(key);
+});
+} else {
+ids = this.getObj(subscene).objects;
+for (i=0; i < ids.length; i++) {
+if (this.getObj(ids[i]).type === type) {
+result.push(ids[i]);
+}
+}
+}
+return result;
+};
+this.getMaterial = function(id, property) {
+var obj = this.getObj(id),
+mat = obj.material[property];
+if (typeof mat === "undefined")
+mat = this.scene.material[property];
+return mat;
+};
+this.inSubscene = function(id, subscene) {
+return this.getObj(subscene).objects.indexOf(id) > -1;
+};
+this.addToSubscene = function(id, subscene) {
+var thelist,
+thesub = this.getObj(subscene),
+ids = [id],
+obj = this.getObj(id), i;
+if (typeof obj.newIds !== "undefined") {
+ids = ids.concat(obj.newIds);
+}
+for (i = 0; i < ids.length; i++) {
+id = ids[i];
+if (thesub.objects.indexOf(id) == -1) {
+thelist = this.whichList(id);
+thesub.objects.push(id);
+thesub[thelist].push(id);
+}
+}
+};
+this.delFromSubscene = function(id, subscene) {
+var thelist,
+thesub = this.getObj(subscene),
+obj = this.getObj(id),
+ids = [id], i, newIds;
+if (typeof obj.newIds !== "undefined")
+ids = ids.concat(obj.newIds);
+for (j=0; j<ids.length;j++) {
+id = ids[j];
+i = thesub.objects.indexOf(id);
+if (i > -1) {
+thesub.objects.splice(i, 1);
+thelist = this.whichList(id);
+i = thesub[thelist].indexOf(id);
+thesub[thelist].splice(i, 1);
+}
+}
+};
+this.setSubsceneEntries = function(ids, subsceneid) {
+var sub = this.getObj(subsceneid);
+sub.objects = ids;
+this.initSubscene(subsceneid);
+};
+this.getSubsceneEntries = function(subscene) {
+return this.getObj(subscene).objects;
+};
+this.getChildSubscenes = function(subscene) {
+return this.getObj(subscene).subscenes;
+};
+this.getVertexShader = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags,
+type = obj.type,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+sprites_3d = flags & this.f_sprites_3d,
+sprite_3d = flags & this.f_sprite_3d,
+nclipplanes = this.countClipplanes(),
+result;
+if (type === "clipplanes" || sprites_3d) return;
+result = "  /* ****** "+type+" object "+id+" vertex shader ****** */\n"+
+"   attribute vec3 aPos;\n"+
+"   attribute vec4 aCol;\n"+
+" uniform mat4 mvMatrix;\n"+
+" uniform mat4 prMatrix;\n"+
+" varying vec4 vCol;\n"+
+" varying vec4 vPosition;\n";
+if (is_lit && !fixed_quads)
+result = result + " attribute vec3 aNorm;\n"+
+" uniform mat4 normMatrix;\n"+
+" varying vec3 vNormal;\n";
+if (has_texture || type === "text")
+result = result + " attribute vec2 aTexcoord;\n"+
+" varying vec2 vTexcoord;\n";
+if (type === "text")
+result = result + " uniform vec2 textScale;\n";
+if (fixed_quads)
+result = result + " attribute vec2 aOfs;\n";
+else if (sprite_3d)
+result = result + " uniform vec3 uOrig;\n"+
+" uniform float uSize;\n"+
+" uniform mat4 usermat;\n";
+result = result + " void main(void) {\n";
+if (nclipplanes || (!fixed_quads && !sprite_3d))
+result = result + "   vPosition = mvMatrix * vec4(aPos, 1.);\n";
+if (!fixed_quads && !sprite_3d)
+result = result + "   gl_Position = prMatrix * vPosition;\n";
+if (type == "points") {
+var size = this.getMaterial(id, "size");
+result = result + "   gl_PointSize = "+size.toFixed(1)+";\n";
+}
+result = result + "   vCol = aCol;\n";
+if (is_lit && !fixed_quads && !sprite_3d)
+result = result + "   vNormal = normalize((normMatrix * vec4(aNorm, 1.)).xyz);\n";
+if (has_texture || type === "text")
+result = result + "   vTexcoord = aTexcoord;\n";
+if (type == "text")
+result = result + "   vec4 pos = prMatrix * mvMatrix * vec4(aPos, 1.);\n"+
+"   pos = pos/pos.w;\n"+
+"   gl_Position = pos + vec4(aOfs*textScale, 0.,0.);\n";
+if (type == "sprites")
+result = result + "   vec4 pos = mvMatrix * vec4(aPos, 1.);\n"+
+"   pos = pos/pos.w + vec4(aOfs, 0., 0.);\n"+
+"   gl_Position = prMatrix*pos;\n";
+if (sprite_3d)
+result = result + "   vNormal = normalize((normMatrix * vec4(aNorm, 1.)).xyz);\n"+
+"   vec4 pos = mvMatrix * vec4(uOrig, 1.);\n"+
+"   vPosition = pos/pos.w + vec4(uSize*(vec4(aPos, 1.)*usermat).xyz,0.);\n"+
+"   gl_Position = prMatrix * vPosition;\n";
+result = result + " }\n";
+return result;
+};
+this.getFragmentShader = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags,
+type = obj.type,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+sprites_3d = flags & this.f_sprites_3d,
+nclipplanes = this.countClipplanes(), i,
+texture_format, nlights,
+result;
+if (type === "clipplanes" || sprites_3d) return;
+if (has_texture)
+texture_format = this.getMaterial(id, "textype");
+result = "/* ****** "+type+" object "+id+" fragment shader ****** */\n"+
+"#ifdef GL_ES\n"+
+"  precision highp float;\n"+
+"#endif\n"+
+"  varying vec4 vCol; // carries alpha\n"+
+"  varying vec4 vPosition;\n";
+if (has_texture || type === "text")
+result = result + " varying vec2 vTexcoord;\n"+
+" uniform sampler2D uSampler;\n";
+if (is_lit && !fixed_quads)
+result = result + " varying vec3 vNormal;\n";
+for (i = 0; i < nclipplanes; i++)
+result = result + " uniform vec4 vClipplane"+i+";\n";
+if (is_lit) {
+nlights = this.countLights();
+if (nlights)
+result = result + " uniform mat4 mvMatrix;\n";
+else
+is_lit = false;
+}
+if (is_lit) {
+result = result + "   uniform vec3 emission;\n"+
+"   uniform float shininess;\n";
+for (i=0; i < nlights; i++) {
+result = result + "   uniform vec3 ambient" + i + ";\n"+
+"   uniform vec3 specular" + i +"; // light*material\n"+
+"   uniform vec3 diffuse" + i + ";\n"+
+"   uniform vec3 lightDir" + i + ";\n"+
+"   uniform bool viewpoint" + i + ";\n"+
+"   uniform bool finite" + i + ";\n";
+}
+}
+result = result + " void main(void) {\n";
+for (i=0; i < nclipplanes;i++)
+result = result + "   if (dot(vPosition, vClipplane"+i+") < 0.0) discard;\n";
+if (is_lit) {
+result = result + "   vec3 eye = normalize(-vPosition.xyz);\n"+
+"   vec3 lightdir;\n"+
+"   vec4 colDiff;\n"+
+"   vec3 halfVec;\n"+
+"   vec4 lighteffect = vec4(emission, 0.);\n"+
+"   vec3 col;\n"+
+"   float nDotL;\n";
+if (fixed_quads) {
+result = result +   "     vec3 n = vec3(0., 0., 1.);\n";
+}
+else {
+result = result +   "     vec3 n = normalize(vNormal);\n"+
+"   n = -faceforward(n, n, eye);\n";
+}
+for (i=0; i < nlights; i++) {
+result = result + "   colDiff = vec4(vCol.rgb * diffuse" + i + ", vCol.a);\n"+
+"   lightdir = lightDir" + i + ";\n"+
+"   if (!viewpoint" + i +")\n"+
+"     lightdir = (mvMatrix * vec4(lightdir, 1.)).xyz;\n"+
+"   if (!finite" + i + ") {\n"+
+"     halfVec = normalize(lightdir + eye);\n"+
+"   } else {\n"+
+"     lightdir = normalize(lightdir - vPosition.xyz);\n"+
+"     halfVec = normalize(lightdir + eye);\n"+
+"   }\n"+
+"     col = ambient" + i + ";\n"+
+"   nDotL = dot(n, lightdir);\n"+
+"   col = col + max(nDotL, 0.) * colDiff.rgb;\n"+
+"   col = col + pow(max(dot(halfVec, n), 0.), shininess) * specular" + i + ";\n"+
+"   lighteffect = lighteffect + vec4(col, colDiff.a);\n";
+}
+} else {
+result = result +   "   vec4 colDiff = vCol;\n"+
+"     vec4 lighteffect = colDiff;\n";
+}
+if ((has_texture && texture_format === "rgba") || type === "text")
+result = result +   "     vec4 textureColor = lighteffect*texture2D(uSampler, vTexcoord);\n";
+if (has_texture) {
+result = result + {
+rgb:            "   vec4 textureColor = lighteffect*vec4(texture2D(uSampler, vTexcoord).rgb, 1.);\n",
+alpha:          "   vec4 textureColor = texture2D(uSampler, vTexcoord);\n"+
+"   float luminance = dot(vec3(1.,1.,1.), textureColor.rgb)/3.;\n"+
+"   textureColor =  vec4(lighteffect.rgb, lighteffect.a*luminance);\n",
+luminance:      "   vec4 textureColor = vec4(lighteffect.rgb*dot(texture2D(uSampler, vTexcoord).rgb, vec3(1.,1.,1.))/3., lighteffect.a);\n",
+"luminance.alpha":"   vec4 textureColor = texture2D(uSampler, vTexcoord);\n"+
+"   float luminance = dot(vec3(1.,1.,1.),textureColor.rgb)/3.;\n"+
+"   textureColor = vec4(lighteffect.rgb*luminance, lighteffect.a*textureColor.a);\n"
+}[texture_format]+
+"   gl_FragColor = textureColor;\n";
+} else if (type === "text") {
+result = result +   "     if (textureColor.a < 0.1)\n"+
+"     discard;\n"+
+"   else\n"+
+"     gl_FragColor = textureColor;\n";
+} else
+result = result +   "   gl_FragColor = lighteffect;\n";
+result = result + " }\n";
+return result;
+};
+this.getShader = function(shaderType, code) {
+var gl = this.gl, shader;
+shader = gl.createShader(shaderType);
+gl.shaderSource(shader, code);
+gl.compileShader(shader);
+if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) === 0)
+alert(gl.getShaderInfoLog(shader));
+return shader;
+};
+this.handleLoadedTexture = function(texture, textureCanvas) {
+var gl = this.gl;
+gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+gl.bindTexture(gl.TEXTURE_2D, texture);
+gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, textureCanvas);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+gl.generateMipmap(gl.TEXTURE_2D);
+gl.bindTexture(gl.TEXTURE_2D, null);
+};
+this.loadImageToTexture = function(uri, texture) {
+var canvas = this.textureCanvas,
+ctx = canvas.getContext("2d"),
+image = new Image(),
+self = this;
+image.onload = function() {
+var w = image.width,
+h = image.height,
+canvasX = self.getPowerOfTwo(w),
+canvasY = self.getPowerOfTwo(h),
+gl = self.gl,
+maxTexSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
+if (maxTexSize > 4096) maxTexSize = 4096;
+while (canvasX > 1 && canvasY > 1 && (canvasX > maxTexSize || canvasY > maxTexSize)) {
+canvasX /= 2;
+canvasY /= 2;
+}
+canvas.width = canvasX;
+canvas.height = canvasY;
+ctx.imageSmoothingEnabled = true;
+ctx.drawImage(image, 0, 0, canvasX, canvasY);
+self.handleLoadedTexture(texture, canvas);
+self.drawScene();
+};
+image.src = uri;
+};
+this.drawTextToCanvas = function(text, cex, family, font) {
+var canvasX, canvasY,
+textY,
+scaling = 20,
+textColour = "white",
+backgroundColour = "rgba(0,0,0,0)",
+canvas = this.textureCanvas,
+ctx = canvas.getContext("2d"),
+i, textHeights = [], widths = [], offset = 0, offsets = [],
+fontStrings = [],
+getFontString = function(i) {
+textHeights[i] = scaling*cex[i];
+var fontString = textHeights[i] + "px",
+family0 = family[i],
+font0 = font[i];
+if (family0 === "sans")
+family0 = "sans-serif";
+else if (family0 === "mono")
+family0 = "monospace";
+fontString = fontString + " " + family0;
+if (font0 === 2 || font0 === 4)
+fontString = "bold " + fontString;
+if (font0 === 3 || font0 === 4)
+fontString = "italic " + fontString;
+return fontString;
+};
+cex = this.repeatToLen(cex, text.length);
+family = this.repeatToLen(family, text.length);
+font = this.repeatToLen(font, text.length);
+canvasX = 1;
+for (i = 0; i < text.length; i++)  {
+ctx.font = fontStrings[i] = getFontString(i);
+widths[i] = ctx.measureText(text[i]).width;
+offset = offsets[i] = offset + 2*textHeights[i];
+canvasX = (widths[i] > canvasX) ? widths[i] : canvasX;
+}
+canvasX = this.getPowerOfTwo(canvasX);
+canvasY = this.getPowerOfTwo(offset);
+canvas.width = canvasX;
+canvas.height = canvasY;
+ctx.fillStyle = backgroundColour;
+ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
+ctx.textBaseline = "alphabetic";
+for(i = 0; i < text.length; i++) {
+textY = offsets[i];
+ctx.font = fontStrings[i];
+ctx.fillStyle = textColour;
+ctx.textAlign = "left";
+ctx.fillText(text[i], 0,  textY);
+}
+return {canvasX:canvasX, canvasY:canvasY,
+widths:widths, textHeights:textHeights,
+offsets:offsets};
+};
+this.setViewport = function(id) {
+var gl = this.gl,
+vp = this.getObj(id).par3d.viewport,
+x = vp.x*this.canvas.width,
+y = vp.y*this.canvas.height,
+width = vp.width*this.canvas.width,
+height = vp.height*this.canvas.height;
+this.vp = {x:x, y:y, width:width, height:height};
+gl.viewport(x, y, width, height);
+gl.scissor(x, y, width, height);
+};
+this.setprMatrix = function(id) {
+var subscene = this.getObj(id),
+embedding = subscene.embeddings.projection;
+if (embedding === "replace")
+this.prMatrix.makeIdentity();
+else
+this.setprMatrix(subscene.parent);
+if (embedding === "inherit")
+return;
+// This is based on the Frustum::enclose code from geom.cpp
+var bbox = subscene.par3d.bbox,
+scale = subscene.par3d.scale,
+ranges = [(bbox[1]-bbox[0])*scale[0]/2,
+(bbox[3]-bbox[2])*scale[1]/2,
+(bbox[5]-bbox[4])*scale[2]/2],
+radius = Math.sqrt(this.sumsq(ranges))*1.1; // A bit bigger to handle labels
+if (radius <= 0) radius = 1;
+var observer = subscene.par3d.observer,
+distance = observer[2],
+t = Math.tan(subscene.par3d.FOV*Math.PI/360),
+near = distance - radius,
+far = distance + radius,
+hlen = t*near,
+aspect = this.vp.width/this.vp.height,
+z = subscene.par3d.zoom;
+if (aspect > 1)
+this.prMatrix.frustum(-hlen*aspect*z, hlen*aspect*z,
+-hlen*z, hlen*z, near, far);
+else
+this.prMatrix.frustum(-hlen*z, hlen*z,
+-hlen*z/aspect, hlen*z/aspect,
+near, far);
+};
+this.setmvMatrix = function(id) {
+var observer = this.getObj(id).par3d.observer;
+this.mvMatrix.makeIdentity();
+this.setmodelMatrix(id);
+this.mvMatrix.translate(-observer[0], -observer[1], -observer[2]);
+};
+this.setmodelMatrix = function(id) {
+var subscene = this.getObj(id),
+embedding = subscene.embeddings.model;
+if (embedding !== "inherit") {
+var scale = subscene.par3d.scale,
+bbox = subscene.par3d.bbox,
+center = [(bbox[0]+bbox[1])/2,
+(bbox[2]+bbox[3])/2,
+(bbox[4]+bbox[5])/2];
+this.mvMatrix.translate(-center[0], -center[1], -center[2]);
+this.mvMatrix.scale(scale[0], scale[1], scale[2]);
+this.mvMatrix.multRight( subscene.par3d.userMatrix );
+}
+if (embedding !== "replace")
+this.setmodelMatrix(subscene.parent);
+};
+this.setnormMatrix = function(subsceneid) {
+var self = this,
+recurse = function(id) {
+var sub = self.getObj(id),
+embedding = sub.embeddings.model;
+if (embedding !== "inherit") {
+var scale = sub.par3d.scale;
+self.normMatrix.scale(1/scale[0], 1/scale[1], 1/scale[2]);
+self.normMatrix.multRight(sub.par3d.userMatrix);
+}
+if (embedding !== "replace")
+recurse(sub.parent);
+};
+self.normMatrix.makeIdentity();
+recurse(subsceneid);
+};
+this.setprmvMatrix = function() {
+this.prmvMatrix = new CanvasMatrix4( this.mvMatrix );
+this.prmvMatrix.multRight( this.prMatrix );
+};
+this.countClipplanes = function() {
+return this.countObjs("clipplanes");
+};
+this.countLights = function() {
+return this.countObjs("light");
+};
+this.countObjs = function(type) {
+var self = this,
+bound = 0;
+Object.keys(this.scene.objects).forEach(
+function(key) {
+if (self.getObj(parseInt(key, 10)).type === type)
+bound = bound + 1;
+});
+return bound;
+};
+this.initSubscene = function(id) {
+var sub = this.getObj(id),
+i, obj;
+if (sub.type !== "subscene")
+return;
+sub.par3d.userMatrix = this.toCanvasMatrix4(sub.par3d.userMatrix);
+sub.par3d.listeners = [].concat(sub.par3d.listeners);
+sub.backgroundId = undefined;
+sub.subscenes = [];
+sub.clipplanes = [];
+sub.transparent = [];
+sub.opaque = [];
+sub.lights = [];
+for (i=0; i < sub.objects.length; i++) {
+obj = this.getObj(sub.objects[i]);
+if (typeof obj === "undefined") {
+sub.objects.splice(i, 1);
+i--;
+} else if (obj.type === "background")
+sub.backgroundId = obj.id;
+else
+sub[this.whichList(obj.id)].push(obj.id);
+}
+};
+this.copyObj = function(id, reuse) {
+var obj = this.getObj(id),
+prev = document.getElementById(reuse).rglinstance,
+prevobj = prev.getObj(id),
+fields = ["flags", "type",
+"colors", "vertices", "centers",
+"normals", "offsets",
+"texts", "cex", "family", "font", "adj",
+"material",
+"radii",
+"texcoords",
+"userMatrix", "ids",
+"dim",
+"par3d", "userMatrix",
+"viewpoint", "finite"],
+i;
+for (i = 0; i < fields.length; i++) {
+if (typeof prevobj[fields[i]] !== "undefined")
+obj[fields[i]] = prevobj[fields[i]];
+}
+};
+this.planeUpdateTriangles = function(id, bbox) {
+var perms = [[0,0,1], [1,2,2], [2,1,0]],
+x, xrow, elem, A, d, nhits, i, j, k, u, v, w, intersect, which, v0, v2, vx, reverse,
+face1 = [], face2 = [], normals = [],
+obj = this.getObj(id),
+nPlanes = obj.normals.length;
+obj.bbox = bbox;
+obj.vertices = [];
+obj.initialized = false;
+for (elem = 0; elem < nPlanes; elem++) {
+//    Vertex Av = normal.getRecycled(elem);
+x = [];
+A = obj.normals[elem];
+d = obj.offsets[elem][0];
+nhits = 0;
+for (i=0; i<3; i++)
+for (j=0; j<2; j++)
+for (k=0; k<2; k++) {
+u = perms[0][i];
+v = perms[1][i];
+w = perms[2][i];
+if (A[w] != 0.0) {
+intersect = -(d + A[u]*bbox[j+2*u] + A[v]*bbox[k+2*v])/A[w];
+if (bbox[2*w] < intersect && intersect < bbox[1+2*w]) {
+xrow = [];
+xrow[u] = bbox[j+2*u];
+xrow[v] = bbox[k+2*v];
+xrow[w] = intersect;
+x.push(xrow);
+face1[nhits] = j + 2*u;
+face2[nhits] = k + 2*v;
+nhits++;
+}
+}
+}
+if (nhits > 3) {
+/* Re-order the intersections so the triangles work */
+for (i=0; i<nhits-2; i++) {
+which = 0; /* initialize to suppress warning */
+for (j=i+1; j<nhits; j++) {
+if (face1[i] == face1[j] || face1[i] == face2[j]
+|| face2[i] == face1[j] || face2[i] == face2[j] ) {
+which = j;
+break;
+}
+}
+if (which > i+1) {
+this.swap(x, i+1, which);
+this.swap(face1, i+1, which);
+this.swap(face2, i+1, which);
+}
+}
+}
+if (nhits >= 3) {
+/* Put in order so that the normal points out the FRONT of the faces */
+v0 = [x[0][0] - x[1][0] , x[0][1] - x[1][1], x[0][2] - x[1][2]];
+v2 = [x[2][0] - x[1][0] , x[2][1] - x[1][1], x[2][2] - x[1][2]];
+/* cross-product */
+vx = this.xprod(v0, v2);
+reverse = this.dotprod(vx, A) > 0;
+for (i=0; i<nhits-2; i++) {
+obj.vertices.push(x[0]);
+normals.push(A);
+for (j=1; j<3; j++) {
+obj.vertices.push(x[i + (reverse ? 3-j : j)]);
+normals.push(A);
+}
+}
+}
+}
+obj.pnormals = normals;
+};
+this.initObj = function(id) {
+var obj = this.getObj(id),
+flags = obj.flags,
+type = obj.type,
+is_indexed = flags & this.f_is_indexed,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+depth_sort = flags & this.f_depth_sort,
+sprites_3d = flags & this.f_sprites_3d,
+sprite_3d = flags & this.f_sprite_3d,
+gl = this.gl,
+texinfo, drawtype, nclipplanes, f, frowsize, nrows,
+i,j,v, mat, uri, matobj;
+if (typeof id !== "number") {
+this.alertOnce("initObj id is "+typeof id);
+}
+obj.initialized = true;
+if (type === "background" || type === "bboxdeco" || type === "subscene")
+return;
+if (type === "light") {
+obj.ambient = new Float32Array(obj.colors[0].slice(0,3));
+obj.diffuse = new Float32Array(obj.colors[1].slice(0,3));
+obj.specular = new Float32Array(obj.colors[2].slice(0,3));
+obj.lightDir = new Float32Array(obj.vertices[0]);
+return;
+}
+if (type === "clipplanes") {
+obj.vClipplane = this.flatten(this.cbind(obj.normals, obj.offsets));
+return;
+}
+if (!sprites_3d) {
+obj.prog = gl.createProgram();
+gl.attachShader(obj.prog, this.getShader( gl.VERTEX_SHADER,
+this.getVertexShader(id) ));
+gl.attachShader(obj.prog, this.getShader( gl.FRAGMENT_SHADER,
+this.getFragmentShader(id) ));
+//  Force aPos to location 0, aCol to location 1
+gl.bindAttribLocation(obj.prog, 0, "aPos");
+gl.bindAttribLocation(obj.prog, 1, "aCol");
+gl.linkProgram(obj.prog);
+var linked = gl.getProgramParameter(obj.prog, gl.LINK_STATUS);
+if (!linked) {
+// An error occurred while linking
+var lastError = gl.getProgramInfoLog(program);
+console.warn("Error in program linking:" + lastError);
+gl.deleteProgram(program);
+}
+}
+if (type === "text") {
+texinfo = this.drawTextToCanvas(obj.texts,
+this.flatten(obj.cex),
+this.flatten(obj.family),
+this.flatten(obj.family));
+}
+if (fixed_quads && !sprites_3d) {
+obj.ofsLoc = gl.getAttribLocation(obj.prog, "aOfs");
+}
+if (sprite_3d) {
+obj.origLoc = gl.getUniformLocation(obj.prog, "uOrig");
+obj.sizeLoc = gl.getUniformLocation(obj.prog, "uSize");
+obj.usermatLoc = gl.getUniformLocation(obj.prog, "usermat");
+}
+if (has_texture || type == "text") {
+obj.texture = gl.createTexture();
+obj.texLoc = gl.getAttribLocation(obj.prog, "aTexcoord");
+obj.sampler = gl.getUniformLocation(obj.prog, "uSampler");
+}
+if (has_texture) {
+mat = obj.material;
+if (typeof mat.uri !== "undefined")
+uri = mat.uri;
+else if (typeof mat.uriElementId === "undefined") {
+matobj = this.getObj(mat.uriId);
+if (typeof matobj !== "undefined") {
+uri = matobj.material.uri;
+} else {
+uri = "";
+}
+} else
+uri = document.getElementById(mat.uriElementId).rglinstance.getObj(mat.uriId).material.uri;
+this.loadImageToTexture(uri, obj.texture);
+}
+if (type === "text") {
+this.handleLoadedTexture(obj.texture, this.textureCanvas);
+}
+v = obj.vertices;
+obj.vertexCount = v.length;
+if (!obj.vertexCount) return;
+var stride = 3, nc, cofs, nofs, radofs, oofs, tofs, vnew, v1;
+nc = obj.colorCount = obj.colors.length;
+if (nc > 1) {
+cofs = stride;
+stride = stride + 4;
+v = this.cbind(v, obj.colors);
+} else {
+cofs = -1;
+obj.onecolor = this.flatten(obj.colors);
+}
+if (typeof obj.normals !== "undefined") {
+nofs = stride;
+stride = stride + 3;
+v = this.cbind(v, typeof obj.pnormals !== "undefined" ? obj.pnormals : obj.normals);
+} else
+nofs = -1;
+if (typeof obj.radii !== "undefined") {
+radofs = stride;
+stride = stride + 1;
+if (obj.radii.length === v.length) {
+v = this.cbind(v, obj.radii);
+} else if (obj.radii.length === 1) {
+v = v.map(function(row, i, arr) { return row.concat(obj.radii[0]);});
+}
+} else
+radofs = -1;
+if (type == "sprites" && !sprites_3d) {
+tofs = stride;
+stride += 2;
+oofs = stride;
+stride += 2;
+vnew = new Array(4*v.length);
+var size = obj.radii, s = size[0]/2;
+for (i=0; i < v.length; i++) {
+if (size.length > 1)
+s = size[i]/2;
+vnew[4*i]  = v[i].concat([0,0,-s,-s]);
+vnew[4*i+1]= v[i].concat([1,0, s,-s]);
+vnew[4*i+2]= v[i].concat([1,1, s, s]);
+vnew[4*i+3]= v[i].concat([0,1,-s, s]);
+}
+v = vnew;
+obj.vertexCount = v.length;
+} else if (type === "text") {
+tofs = stride;
+stride += 2;
+oofs = stride;
+stride += 2;
+vnew = new Array(4*v.length);
+for (i=0; i < v.length; i++) {
+vnew[4*i]  = v[i].concat([0,-0.5]).concat(obj.adj[0]);
+vnew[4*i+1]= v[i].concat([1,-0.5]).concat(obj.adj[0]);
+vnew[4*i+2]= v[i].concat([1, 1.5]).concat(obj.adj[0]);
+vnew[4*i+3]= v[i].concat([0, 1.5]).concat(obj.adj[0]);
+for (j=0; j < 4; j++) {
+v1 = vnew[4*i+j];
+v1[tofs+2] = 2*(v1[tofs]-v1[tofs+2])*texinfo.widths[i];
+v1[tofs+3] = 2*(v1[tofs+1]-v1[tofs+3])*texinfo.textHeights[i];
+v1[tofs] *= texinfo.widths[i]/texinfo.canvasX;
+v1[tofs+1] = 1.0-(texinfo.offsets[i] -
+v1[tofs+1]*texinfo.textHeights[i])/texinfo.canvasY;
+vnew[4*i+j] = v1;
+}
+}
+v = vnew;
+obj.vertexCount = v.length;
+} else if (typeof obj.texcoords !== "undefined") {
+tofs = stride;
+stride += 2;
+oofs = -1;
+v = this.cbind(v, obj.texcoords);
+} else {
+tofs = -1;
+oofs = -1;
+}
+if (stride !== v[0].length) {
+this.alertOnce("problem in stride calculation");
+}
+obj.vOffsets = {vofs:0, cofs:cofs, nofs:nofs, radofs:radofs, oofs:oofs, tofs:tofs, stride:stride};
+obj.values = new Float32Array(this.flatten(v));
+if (sprites_3d) {
+obj.userMatrix = new CanvasMatrix4(obj.userMatrix);
+obj.objects = this.flatten([].concat(obj.ids));
+is_lit = false;
+}
+if (is_lit && !fixed_quads) {
+obj.normLoc = gl.getAttribLocation(obj.prog, "aNorm");
+}
+nclipplanes = this.countClipplanes();
+if (nclipplanes && !sprites_3d) {
+obj.clipLoc = [];
+for (i=0; i < nclipplanes; i++)
+obj.clipLoc[i] = gl.getUniformLocation(obj.prog,"vClipplane" + i);
+}
+if (is_lit) {
+obj.emissionLoc = gl.getUniformLocation(obj.prog, "emission");
+obj.emission = new Float32Array(this.stringToRgb(this.getMaterial(id, "emission")));
+obj.shininessLoc = gl.getUniformLocation(obj.prog, "shininess");
+obj.shininess = this.getMaterial(id, "shininess");
+obj.nlights = this.countLights();
+obj.ambientLoc = [];
+obj.ambient = new Float32Array(this.stringToRgb(this.getMaterial(id, "ambient")));
+obj.specularLoc = [];
+obj.specular = new Float32Array(this.stringToRgb(this.getMaterial(id, "specular")));
+obj.diffuseLoc = [];
+obj.lightDirLoc = [];
+obj.viewpointLoc = [];
+obj.finiteLoc = [];
+for (i=0; i < obj.nlights; i++) {
+obj.ambientLoc[i] = gl.getUniformLocation(obj.prog, "ambient" + i);
+obj.specularLoc[i] = gl.getUniformLocation(obj.prog, "specular" + i);
+obj.diffuseLoc[i] = gl.getUniformLocation(obj.prog, "diffuse" + i);
+obj.lightDirLoc[i] = gl.getUniformLocation(obj.prog, "lightDir" + i);
+obj.viewpointLoc[i] = gl.getUniformLocation(obj.prog, "viewpoint" + i);
+obj.finiteLoc[i] = gl.getUniformLocation(obj.prog, "finite" + i);
+}
+}
+if (is_indexed) {
+if ((type === "quads" || type === "text" ||
+type === "sprites") && !sprites_3d) {
+nrows = Math.floor(obj.vertexCount/4);
+f = Array(6*nrows);
+for (i=0; i < nrows; i++) {
+f[6*i] = 4*i;
+f[6*i+1] = 4*i + 1;
+f[6*i+2] = 4*i + 2;
+f[6*i+3] = 4*i;
+f[6*i+4] = 4*i + 2;
+f[6*i+5] = 4*i + 3;
+}
+frowsize = 6;
+} else if (type === "triangles") {
+nrows = Math.floor(obj.vertexCount/3);
+f = Array(3*nrows);
+for (i=0; i < f.length; i++) {
+f[i] = i;
+}
+frowsize = 3;
+} else if (type === "spheres") {
+nrows = obj.vertexCount;
+f = Array(nrows);
+for (i=0; i < f.length; i++) {
+f[i] = i;
+}
+frowsize = 1;
+} else if (type === "surface") {
+var dim = obj.dim[0],
+nx = dim[0],
+nz = dim[1];
+f = [];
+for (j=0; j<nx-1; j++) {
+for (i=0; i<nz-1; i++) {
+f.push(j + nx*i,
+j + nx*(i+1),
+j + 1 + nx*(i+1),
+j + nx*i,
+j + 1 + nx*(i+1),
+j + 1 + nx*i);
+}
+}
+frowsize = 6;
+}
+obj.f = new Uint16Array(f);
+if (depth_sort) {
+drawtype = "DYNAMIC_DRAW";
+} else {
+drawtype = "STATIC_DRAW";
+}
+}
+if (type !== "spheres" && !sprites_3d) {
+obj.buf = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, obj.values, gl.STATIC_DRAW); //
+}
+if (is_indexed && type !== "spheres" && !sprites_3d) {
+obj.ibuf = gl.createBuffer();
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, obj.ibuf);
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, obj.f, gl[drawtype]);
+}
+if (!sprites_3d) {
+obj.mvMatLoc = gl.getUniformLocation(obj.prog, "mvMatrix");
+obj.prMatLoc = gl.getUniformLocation(obj.prog, "prMatrix");
+}
+if (type === "text") {
+obj.textScaleLoc = gl.getUniformLocation(obj.prog, "textScale");
+}
+if (is_lit && !sprites_3d) {
+obj.normMatLoc = gl.getUniformLocation(obj.prog, "normMatrix");
+}
+};
+this.setDepthTest = function(id) {
+var gl = this.gl,
+tests = {never: gl.NEVER,
+less:  gl.LESS,
+equal: gl.EQUAL,
+lequal:gl.LEQUAL,
+greater: gl.GREATER,
+notequal: gl.NOTEQUAL,
+gequal: gl.GEQUAL,
+always: gl.ALWAYS},
+test = tests[this.getMaterial(id, "depth_test")];
+gl.depthFunc(test);
+};
+this.mode4type = {points : "POINTS",
+linestrip : "LINE_STRIP",
+abclines : "LINES",
+lines : "LINES",
+sprites : "TRIANGLES",
+planes : "TRIANGLES",
+text : "TRIANGLES",
+quads : "TRIANGLES",
+surface : "TRIANGLES",
+triangles : "TRIANGLES"};
+this.drawObj = function(id, subsceneid) {
+var obj = this.getObj(id),
+subscene = this.getObj(subsceneid),
+flags = obj.flags,
+type = obj.type,
+is_indexed = flags & this.f_is_indexed,
+is_lit = flags & this.f_is_lit,
+has_texture = flags & this.f_has_texture,
+fixed_quads = flags & this.f_fixed_quads,
+depth_sort = flags & this.f_depth_sort,
+sprites_3d = flags & this.f_sprites_3d,
+sprite_3d = flags & this.f_sprite_3d,
+is_lines = flags & this.f_is_lines,
+gl = this.gl,
+sphereMV, baseofs, ofs, sscale, i, count, light,
+faces;
+if (typeof id !== "number") {
+this.alertOnce("drawObj id is "+typeof id);
+}
+if (type === "planes") {
+if (obj.bbox !== subscene.par3d.bbox || !obj.initialized) {
+this.planeUpdateTriangles(id, subscene.par3d.bbox);
+}
+}
+if (!obj.initialized)
+this.initObj(id);
+if (type === "light" || type === "bboxdeco")
+return;
+if (type === "clipplanes") {
+count = obj.offsets.length;
+var IMVClip = [];
+for (i=0; i < count; i++) {
+IMVClip[i] = this.multMV(this.invMatrix, obj.vClipplane.slice(4*i, 4*(i+1)));
+}
+obj.IMVClip = IMVClip;
+return;
+}
+this.setDepthTest(id);
+if (sprites_3d) {
+var norigs = obj.vertices.length,
+savenorm = new CanvasMatrix4(this.normMatrix);
+this.origs = obj.vertices;
+this.usermat = new Float32Array(obj.userMatrix.getAsArray());
+this.radii = obj.radii;
+this.normMatrix = subscene.spriteNormmat;
+for (this.iOrig=0; this.iOrig < norigs; this.iOrig++) {
+for (i=0; i < obj.objects.length; i++) {
+this.drawObj(obj.objects[i], subsceneid);
+}
+}
+this.normMatrix = savenorm;
+return;
+} else {
+gl.useProgram(obj.prog);
+}
+if (sprite_3d) {
+gl.uniform3fv(obj.origLoc, new Float32Array(this.origs[this.iOrig]));
+if (this.radii.length > 1) {
+gl.uniform1f(obj.sizeLoc, this.radii[this.iOrig][0]);
+} else {
+gl.uniform1f(obj.sizeLoc, this.radii[0][0]);
+}
+gl.uniformMatrix4fv(obj.usermatLoc, false, this.usermat);
+}
+if (type === "spheres") {
+gl.bindBuffer(gl.ARRAY_BUFFER, this.sphere.buf);
+} else {
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+}
+if (is_indexed && type !== "spheres") {
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, obj.ibuf);
+} else if (type === "spheres") {
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.sphere.ibuf);
+}
+gl.uniformMatrix4fv( obj.prMatLoc, false, new Float32Array(this.prMatrix.getAsArray()) );
+gl.uniformMatrix4fv( obj.mvMatLoc, false, new Float32Array(this.mvMatrix.getAsArray()) );
+var clipcheck = 0,
+clipplaneids = subscene.clipplanes,
+clip, j;
+for (i=0; i < clipplaneids.length; i++) {
+clip = this.getObj(clipplaneids[i]);
+for (j=0; j < clip.offsets.length; j++) {
+gl.uniform4fv(obj.clipLoc[clipcheck + j], clip.IMVClip[j]);
+}
+clipcheck += clip.offsets.length;
+}
+if (typeof obj.clipLoc !== "undefined")
+for (i=clipcheck; i < obj.clipLoc.length; i++)
+gl.uniform4f(obj.clipLoc[i], 0,0,0,0);
+if (is_lit) {
+gl.uniformMatrix4fv( obj.normMatLoc, false, new Float32Array(this.normMatrix.getAsArray()) );
+gl.uniform3fv( obj.emissionLoc, obj.emission);
+gl.uniform1f( obj.shininessLoc, obj.shininess);
+for (i=0; i < subscene.lights.length; i++) {
+light = this.getObj(subscene.lights[i]);
+gl.uniform3fv( obj.ambientLoc[i], this.componentProduct(light.ambient, obj.ambient));
+gl.uniform3fv( obj.specularLoc[i], this.componentProduct(light.specular, obj.specular));
+gl.uniform3fv( obj.diffuseLoc[i], light.diffuse);
+gl.uniform3fv( obj.lightDirLoc[i], light.lightDir);
+gl.uniform1i( obj.viewpointLoc[i], light.viewpoint);
+gl.uniform1i( obj.finiteLoc[i], light.finite);
+}
+for (i=subscene.lights.length; i < obj.nlights; i++) {
+gl.uniform3f( obj.ambientLoc[i], 0,0,0);
+gl.uniform3f( obj.specularLoc[i], 0,0,0);
+gl.uniform3f( obj.diffuseLoc[i], 0,0,0);
+}
+}
+if (type === "text") {
+gl.uniform2f( obj.textScaleLoc, 0.75/this.vp.width, 0.75/this.vp.height);
+}
+gl.enableVertexAttribArray( this.posLoc );
+var nc = obj.colorCount;
+count = obj.vertexCount;
+if (depth_sort) {
+var nfaces = obj.centers.length,
+frowsize, z, w;
+if (sprites_3d) frowsize = 1;
+else if (type === "triangles") frowsize = 3;
+else frowsize = 6;
+var depths = new Float32Array(nfaces);
+faces = new Array(nfaces);
+for(i=0; i<nfaces; i++) {
+z = this.prmvMatrix.m13*obj.centers[3*i] +
+this.prmvMatrix.m23*obj.centers[3*i+1] +
+this.prmvMatrix.m33*obj.centers[3*i+2] +
+this.prmvMatrix.m43;
+w = this.prmvMatrix.m14*obj.centers[3*i] +
+this.prmvMatrix.m24*obj.centers[3*i+1] +
+this.prmvMatrix.m34*obj.centers[3*i+2] +
+this.prmvMatrix.m44;
+depths[i] = z/w;
+faces[i] = i;
+}
+var depthsort = function(i,j) { return depths[j] - depths[i]; };
+faces.sort(depthsort);
+if (type !== "spheres") {
+var f = new Uint16Array(obj.f.length);
+for (i=0; i<nfaces; i++) {
+for (j=0; j<frowsize; j++) {
+f[frowsize*i + j] = obj.f[frowsize*faces[i] + j];
+}
+}
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, f, gl.DYNAMIC_DRAW);
+}
+}
+if (type === "spheres") {
+subscene = this.getObj(subsceneid);
+var scale = subscene.par3d.scale,
+scount = count;
+gl.vertexAttribPointer(this.posLoc,  3, gl.FLOAT, false, this.sphere.sphereStride,  0);
+gl.enableVertexAttribArray(obj.normLoc );
+gl.vertexAttribPointer(obj.normLoc,  3, gl.FLOAT, false, this.sphere.sphereStride,  0);
+gl.disableVertexAttribArray( this.colLoc );
+var sphereNorm = new CanvasMatrix4();
+sphereNorm.scale(scale[0], scale[1], scale[2]);
+sphereNorm.multRight(this.normMatrix);
+gl.uniformMatrix4fv( obj.normMatLoc, false, new Float32Array(sphereNorm.getAsArray()) );
+if (nc == 1) {
+gl.vertexAttrib4fv( this.colLoc, new Float32Array(obj.onecolor));
+}
+for (i = 0; i < scount; i++) {
+sphereMV = new CanvasMatrix4();
+if (depth_sort) {
+baseofs = faces[i]*obj.vOffsets.stride;
+} else {
+baseofs = i*obj.vOffsets.stride;
+}
+ofs = baseofs + obj.vOffsets.radofs;
+sscale = obj.values[ofs];
+sphereMV.scale(sscale/scale[0], sscale/scale[1], sscale/scale[2]);
+sphereMV.translate(obj.values[baseofs],
+obj.values[baseofs+1],
+obj.values[baseofs+2]);
+sphereMV.multRight(this.mvMatrix);
+gl.uniformMatrix4fv( obj.mvMatLoc, false, new Float32Array(sphereMV.getAsArray()) );
+if (nc > 1) {
+ofs = baseofs + obj.vOffsets.cofs;
+gl.vertexAttrib4f( this.colLoc, obj.values[ofs],
+obj.values[ofs+1],
+obj.values[ofs+2],
+obj.values[ofs+3] );
+}
+gl.drawElements(gl.TRIANGLES, this.sphere.sphereCount, gl.UNSIGNED_SHORT, 0);
+}
+return;
+} else {
+if (obj.colorCount === 1) {
+gl.disableVertexAttribArray( this.colLoc );
+gl.vertexAttrib4fv( this.colLoc, new Float32Array(obj.onecolor));
+} else {
+gl.enableVertexAttribArray( this.colLoc );
+gl.vertexAttribPointer(this.colLoc, 4, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.cofs);
+}
+}
+if (is_lit && obj.vOffsets.nofs > 0) {
+gl.enableVertexAttribArray( obj.normLoc );
+gl.vertexAttribPointer(obj.normLoc, 3, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.nofs);
+}
+if (has_texture || type === "text") {
+gl.enableVertexAttribArray( obj.texLoc );
+gl.vertexAttribPointer(obj.texLoc, 2, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.tofs);
+gl.activeTexture(gl.TEXTURE0);
+gl.bindTexture(gl.TEXTURE_2D, obj.texture);
+gl.uniform1i( obj.sampler, 0);
+}
+if (fixed_quads) {
+gl.enableVertexAttribArray( obj.ofsLoc );
+gl.vertexAttribPointer(obj.ofsLoc, 2, gl.FLOAT, false, 4*obj.vOffsets.stride, 4*obj.vOffsets.oofs);
+}
+var mode = this.mode4type[type];
+if (type === "sprites" || type === "text" || type === "quads") {
+count = count * 6/4;
+} else if (type === "surface") {
+count = obj.f.length;
+}
+if (is_lines) {
+gl.lineWidth( this.getMaterial(id, "lwd") );
+}
+gl.vertexAttribPointer(this.posLoc,  3, gl.FLOAT, false, 4*obj.vOffsets.stride,  4*obj.vOffsets.vofs);
+if (is_indexed) {
+gl.drawElements(gl[mode], count, gl.UNSIGNED_SHORT, 0);
+} else {
+gl.drawArrays(gl[mode], 0, count);
+}
+};
+this.drawSubscene = function(subsceneid) {
+var gl = this.gl,
+obj = this.getObj(subsceneid),
+objects = this.scene.objects,
+subids = obj.objects,
+subscene_has_faces = false,
+subscene_needs_sorting = false,
+flags, i;
+if (obj.par3d.skipRedraw)
+return;
+for (i=0; i < subids.length; i++) {
+flags = objects[subids[i]].flags;
+if (typeof flags !== "undefined") {
+subscene_has_faces |= (flags & this.f_is_lit)
+& !(flags & this.f_fixed_quads);
+subscene_needs_sorting |= (flags & this.f_depth_sort);
+}
+}
+var bgid = obj.backgroundId,
+bg;
+this.setViewport(subsceneid);
+if (typeof bgid !== "undefined" && objects[bgid].colors.length) {
+bg = objects[bgid].colors[0];
+gl.clearColor(bg[0], bg[1], bg[2], bg[3]);
+gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+}
+if (subids.length) {
+this.setprMatrix(subsceneid);
+this.setmvMatrix(subsceneid);
+if (subscene_has_faces) {
+this.setnormMatrix(subsceneid);
+if ((obj.flags & this.f_sprites_3d) &&
+typeof obj.spriteNormmat === "undefined") {
+obj.spriteNormmat = new CanvasMatrix4(this.normMatrix);
+}
+}
+if (subscene_needs_sorting)
+this.setprmvMatrix();
+var clipids = obj.clipplanes;
+if (clipids.length > 0) {
+this.invMatrix = new CanvasMatrix4(this.mvMatrix);
+this.invMatrix.invert();
+for (i = 0; i < clipids.length; i++)
+this.drawObj(clipids[i], subsceneid);
+}
+subids = obj.opaque;
+if (subids.length > 0) {
+gl.depthMask(true);
+gl.disable(gl.BLEND);
+for (i = 0; subids && i < subids.length; i++) {
+this.drawObj(subids[i], subsceneid);
+}
+}
+subids = obj.transparent;
+if (subids.length > 0) {
+gl.depthMask(false);
+gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA,
+gl.ONE, gl.ONE);
+gl.enable(gl.BLEND);
+for (i = 0; i < subids.length; i++) {
+this.drawObj(subids[i], subsceneid);
+}
+}
+subids = obj.subscenes;
+for (i = 0; i < subids.length; i++) {
+this.drawSubscene(subids[i]);
+}
+}
+};
+this.relMouseCoords = function(event) {
+var totalOffsetX = 0,
+totalOffsetY = 0,
+currentElement = this.canvas;
+do {
+totalOffsetX += currentElement.offsetLeft;
+totalOffsetY += currentElement.offsetTop;
+currentElement = currentElement.offsetParent;
+}
+while(currentElement);
+var canvasX = event.pageX - totalOffsetX,
+canvasY = event.pageY - totalOffsetY;
+return {x:canvasX, y:canvasY};
+};
+this.setMouseHandlers = function() {
+var self = this, activeSubscene, handler,
+handlers = {}, drag = 0;
+handlers.rotBase = 0;
+this.screenToVector = function(x, y) {
+var viewport = this.getObj(activeSubscene).par3d.viewport,
+width = viewport.width*this.canvas.width,
+height = viewport.height*this.canvas.height,
+radius = Math.max(width, height)/2.0,
+cx = width/2.0,
+cy = height/2.0,
+px = (x-cx)/radius,
+py = (y-cy)/radius,
+plen = Math.sqrt(px*px+py*py);
+if (plen > 1.e-6) {
+px = px/plen;
+py = py/plen;
+}
+var angle = (Math.SQRT2 - plen)/Math.SQRT2*Math.PI/2,
+z = Math.sin(angle),
+zlen = Math.sqrt(1.0 - z*z);
+px = px * zlen;
+py = py * zlen;
+return [px, py, z];
+};
+handlers.trackballdown = function(x,y) {
+var activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+i, l = activeModel.par3d.listeners;
+handlers.rotBase = this.screenToVector(x, y);
+this.saveMat = [];
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.saveMat = new CanvasMatrix4(activeSub.par3d.userMatrix);
+}
+};
+handlers.trackballmove = function(x,y) {
+var rotCurrent = this.screenToVector(x,y),
+rotBase = handlers.rotBase,
+dot = rotBase[0]*rotCurrent[0] +
+rotBase[1]*rotCurrent[1] +
+rotBase[2]*rotCurrent[2],
+angle = Math.acos( dot/this.vlen(rotBase)/this.vlen(rotCurrent) )*180.0/Math.PI,
+axis = this.xprod(rotBase, rotCurrent),
+objects = this.scene.objects,
+activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+l = activeModel.par3d.listeners,
+i;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.userMatrix.load(objects[l[i]].saveMat);
+activeSub.par3d.userMatrix.rotate(angle, axis[0], axis[1], axis[2]);
+}
+this.drawScene();
+};
+handlers.trackballend = 0;
+handlers.axisdown = function(x,y) {
+handlers.rotBase = this.screenToVector(x, this.canvas.height/2);
+var activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+i, l = activeModel.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.saveMat = new CanvasMatrix4(activeSub.par3d.userMatrix);
+}
+};
+handlers.axismove = function(x,y) {
+var rotCurrent = this.screenToVector(x, this.canvas.height/2),
+rotBase = handlers.rotBase,
+angle = (rotCurrent[0] - rotBase[0])*180/Math.PI,
+rotMat = new CanvasMatrix4();
+rotMat.rotate(angle, handlers.axis[0], handlers.axis[1], handlers.axis[2]);
+var activeSub = this.getObj(activeSubscene),
+activeModel = this.getObj(this.useid(activeSub.id, "model")),
+i, l = activeModel.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.userMatrix.load(activeSub.saveMat);
+activeSub.par3d.userMatrix.multLeft(rotMat);
+}
+this.drawScene();
+};
+handlers.axisend = 0;
+handlers.y0zoom = 0;
+handlers.zoom0 = 0;
+handlers.zoomdown = function(x, y) {
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+handlers.y0zoom = y;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.zoom0 = Math.log(activeSub.par3d.zoom);
+}
+};
+handlers.zoommove = function(x, y) {
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.zoom = Math.exp(activeSub.zoom0 + (y-handlers.y0zoom)/this.canvas.height);
+}
+this.drawScene();
+};
+handlers.zoomend = 0;
+handlers.y0fov = 0;
+handlers.fovdown = function(x, y) {
+handlers.y0fov = y;
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.fov0 = activeSub.par3d.FOV;
+}
+};
+handlers.fovmove = function(x, y) {
+var activeSub = this.getObj(activeSubscene),
+activeProjection = this.getObj(this.useid(activeSub.id, "projection")),
+i, l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = this.getObj(l[i]);
+activeSub.par3d.FOV = Math.max(1, Math.min(179, activeSub.fov0 +
+180*(y-handlers.y0fov)/this.canvas.height));
+}
+this.drawScene();
+};
+handlers.fovend = 0;
+this.canvas.onmousedown = function ( ev ){
+if (!ev.which) // Use w3c defns in preference to MS
+switch (ev.button) {
+case 0: ev.which = 1; break;
+case 1:
+case 4: ev.which = 2; break;
+case 2: ev.which = 3;
+}
+drag = ["left", "middle", "right"][ev.which-1];
+var coords = self.relMouseCoords(ev);
+coords.y = self.canvas.height-coords.y;
+activeSubscene = self.whichSubscene(coords);
+var sub = self.getObj(activeSubscene), f;
+handler = sub.par3d.mouseMode[drag];
+switch (handler) {
+case "xAxis":
+handler = "axis";
+handlers.axis = [1.0, 0.0, 0.0];
+break;
+case "yAxis":
+handler = "axis";
+handlers.axis = [0.0, 1.0, 0.0];
+break;
+case "zAxis":
+handler = "axis";
+handlers.axis = [0.0, 0.0, 1.0];
+break;
+}
+f = handlers[handler + "down"];
+if (f) {
+coords = self.translateCoords(activeSubscene, coords);
+f.call(self, coords.x, coords.y);
+ev.preventDefault();
+}
+};
+this.canvas.onmouseup = function ( ev ){
+if ( drag === 0 ) return;
+var f = handlers[handler + "up"];
+if (f)
+f();
+drag = 0;
+};
+this.canvas.onmouseout = this.canvas.onmouseup;
+this.canvas.onmousemove = function ( ev ) {
+if ( drag === 0 ) return;
+var f = handlers[handler + "move"];
+if (f) {
+var coords = self.relMouseCoords(ev);
+coords.y = self.canvas.height - coords.y;
+coords = self.translateCoords(activeSubscene, coords);
+f.call(self, coords.x, coords.y);
+}
+};
+handlers.wheelHandler = function(ev) {
+var del = 1.02, i;
+if (ev.shiftKey) del = 1.002;
+var ds = ((ev.detail || ev.wheelDelta) > 0) ? del : (1 / del);
+if (typeof activeSubscene === "undefined")
+activeSubscene = self.scene.rootSubscene;
+var activeSub = self.getObj(activeSubscene),
+activeProjection = self.getObj(self.useid(activeSub.id, "projection")),
+l = activeProjection.par3d.listeners;
+for (i = 0; i < l.length; i++) {
+activeSub = self.getObj(l[i]);
+activeSub.par3d.zoom *= ds;
+}
+self.drawScene();
+ev.preventDefault();
+};
+this.canvas.addEventListener("DOMMouseScroll", handlers.wheelHandler, false);
+this.canvas.addEventListener("mousewheel", handlers.wheelHandler, false);
+};
+this.useid = function(subsceneid, type) {
+var sub = this.getObj(subsceneid);
+if (sub.embeddings[type] === "inherit")
+return(this.useid(sub.parent, type));
+else
+return subsceneid;
+};
+this.inViewport = function(coords, subsceneid) {
+var viewport = this.getObj(subsceneid).par3d.viewport,
+x0 = coords.x - viewport.x*this.canvas.width,
+y0 = coords.y - viewport.y*this.canvas.height;
+return 0 <= x0 && x0 <= viewport.width*this.canvas.width &&
+0 <= y0 && y0 <= viewport.height*this.canvas.height;
+};
+this.whichSubscene = function(coords) {
+var self = this,
+recurse = function(subsceneid) {
+var subscenes = self.getChildSubscenes(subsceneid), i, id;
+for (i=0; i < subscenes.length; i++) {
+id = recurse(subscenes[i]);
+if (typeof(id) !== "undefined")
+return(id);
+}
+if (self.inViewport(coords, subsceneid))
+return(subsceneid);
+else
+return undefined;
+},
+rootid = this.scene.rootSubscene,
+result = recurse(rootid);
+if (typeof(result) === "undefined")
+result = rootid;
+return result;
+};
+this.translateCoords = function(subsceneid, coords) {
+var viewport = this.getObj(subsceneid).par3d.viewport;
+return {x: coords.x - viewport.x*this.canvas.width,
+y: coords.y - viewport.y*this.canvas.height};
+};
+this.initSphere = function(verts) {
+var gl = this.gl, reuse = verts.reuse, result;
+if (typeof reuse !== "undefined") {
+var prev = document.getElementById(reuse).rglinstance.sphere;
+result = {vb: prev.vb, it: prev.it};
+} else {
+result = {vb: new Float32Array(this.flatten(this.transpose(verts.vb))),
+it: new Uint16Array(this.flatten(this.transpose(verts.it)))};
+}
+result.sphereStride = 12;
+result.sphereCount = result.it.length;
+result.buf = gl.createBuffer();
+gl.bindBuffer(gl.ARRAY_BUFFER, result.buf);
+gl.bufferData(gl.ARRAY_BUFFER, result.vb, gl.STATIC_DRAW);
+result.ibuf = gl.createBuffer();
+gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, result.ibuf);
+gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, result.it, gl.STATIC_DRAW);
+return result;
+};
+this.initialize = function(el, x) {
+this.textureCanvas = document.createElement("canvas");
+this.textureCanvas.style.display = "block";
+this.scene = x;
+this.normMatrix = new CanvasMatrix4();
+this.saveMat = {};
+this.distance = null;
+this.posLoc = 0;
+this.colLoc = 1;
+if (el) {
+el.rglinstance = this;
+this.initCanvas(el);
+}
+};
+this.initCanvas = function(el) {
+this.canvas = document.createElement("canvas");
+this.resize(el);
+while (el.firstChild) {
+el.removeChild(el.firstChild);
+}
+el.appendChild(this.canvas);
+this.initGL0();
+if (!this.gl)
+return;
+var objs = this.scene.objects,
+self = this;
+this.sphere = this.initSphere(this.scene.sphereVerts);
+Object.keys(objs).forEach(function(key){
+var id = parseInt(key, 10),
+obj = self.getObj(id);
+if (typeof obj.reuse !== "undefined")
+self.copyObj(id, obj.reuse);
+});
+Object.keys(objs).forEach(function(key){
+self.initSubscene(parseInt(key, 10));
+});
+Object.keys(objs).forEach(function(key){
+self.initObj(parseInt(key, 10));
+});
+this.setMouseHandlers();
+};
+/* this is only used by .writeWebGL; rglwidget has
+no debug element and does the drawing in rglwidget.js */
+this.start = function() {
+if (typeof this.prefix !== "undefined") {
+this.debugelement = document.getElementById(this.prefix + "debug");
+this.debug("");
+}
+this.drag = 0;
+this.drawScene();
+};
+this.debug = function(msg, img) {
+if (typeof this.debugelement !== "undefined") {
+this.debugelement.innerHTML = msg;
+if (typeof img !== "undefined") {
+this.debugelement.insertBefore(img, this.debugelement.firstChild);
+}
+} else
+alert(msg);
+};
+this.getSnapshot = function() {
+var img;
+if (typeof this.scene.snapshot !== "undefined") {
+img = document.createElement("img");
+img.src = this.scene.snapshot;
+img.alt = "Snapshot";
+}
+return img;
+};
+this.initGL0 = function() {
+if (!window.WebGLRenderingContext){
+this.debug("Your browser does not support WebGL. See <a href=\"http://get.webgl.org\">http://get.webgl.org</a>", this.getSnapshot());
+return;
+}
+try {
+this.initGL();
+}
+catch(e) {}
+if ( !this.gl ) {
+this.debug("Your browser appears to support WebGL, but did not create a WebGL context.  See <a href=\"http://get.webgl.org\">http://get.webgl.org</a>",
+this.getSnapshot());
+return;
+}
+};
+this.initGL = function() {
+this.gl = this.canvas.getContext("webgl") ||
+this.canvas.getContext("experimental-webgl");
+};
+this.resize = function(el) {
+this.canvas.width = el.width;
+this.canvas.height = el.height;
+};
+this.drawScene = function() {
+var gl = this.gl;
+if (!gl)
+this.alertOnce("No WebGL context.");
+gl.enable(gl.DEPTH_TEST);
+gl.depthFunc(gl.LEQUAL);
+gl.clearDepth(1.0);
+gl.clearColor(1,1,1,1);
+gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+this.drawSubscene(this.scene.rootSubscene);
+this.drawing = false;
+};
+this.subsetSetter = function(el, control) {
+if (typeof control.subscenes === "undefined" ||
+control.subscenes === null)
+control.subscenes = this.scene.rootSubscene;
+var value = Math.round(control.value),
+subscenes = [].concat(control.subscenes),
+i, j, entries, subsceneid,
+ismissing = function(x) {
+return control.fullset.indexOf(x) < 0;
+},
+tointeger = function(x) {
+return parseInt(x, 10);
+};
+for (i=0; i < subscenes.length; i++) {
+subsceneid = subscenes[i];
+if (typeof this.getObj(subsceneid) === "undefined")
+this.alertOnce("typeof object is undefined");
+entries = this.getObj(subsceneid).objects;
+entries = entries.filter(ismissing);
+if (control.accumulate) {
+for (j=0; j<=value; j++)
+entries = entries.concat(control.subsets[j]);
+} else {
+entries = entries.concat(control.subsets[value]);
+}
+entries = entries.map(tointeger);
+this.setSubsceneEntries(this.unique(entries), subsceneid);
+}
+};
+this.propertySetter = function(el, control)  {
+var value = control.value,
+values = [].concat(control.values),
+svals = [].concat(control.param),
+direct = values[0] === null,
+entries = [].concat(control.entries),
+ncol = entries.length,
+nrow = values.length/ncol,
+properties = this.repeatToLen(control.properties, ncol),
+objids = this.repeatToLen(control.objids, ncol),
+property = properties[0], objid = objids[0],
+obj = this.getObj(objid),
+propvals, i, v1, v2, p, entry, gl, needsBinding,
+newprop, newid,
+getPropvals = function() {
+if (property === "userMatrix")
+return obj.userMatrix.getAsArray();
+else
+return obj[property];
+};
+if (direct && typeof value === "undefined")
+return;
+if (control.interp) {
+values = values.slice(0, ncol).concat(values).
+concat(values.slice(ncol*(nrow-1), ncol*nrow));
+svals = [-Infinity].concat(svals).concat(Infinity);
+for (i = 1; i < svals.length; i++) {
+if (value <= svals[i]) {
+if (svals[i] === Infinity)
+p = 1;
+else
+p = (svals[i] - value)/(svals[i] - svals[i-1]);
+break;
+}
+}
+} else if (!direct) {
+value = Math.round(value);
+}
+propvals = getPropvals();
+for (j=0; j<entries.length; j++) {
+entry = entries[j];
+newprop = properties[j];
+newid = objids[j];
+if (newprop != property || newid != objid) {
+property = newprop;
+objid = newid;
+obj = this.getObj(objid);
+propvals = getPropvals();
+}
+if (control.interp) {
+v1 = values[ncol*(i-1) + j];
+v2 = values[ncol*i + j];
+this.setElement(propvals, entry, p*v1 + (1-p)*v2);
+} else if (!direct) {
+this.setElement(propvals, entry, values[ncol*value + j]);
+} else {
+this.setElement(propvals, entry, value[j]);
+}
+}
+needsBinding = [];
+for (j=0; j < entries.length; j++) {
+if (properties[j] === "values" &&
+needsBinding.indexOf(objids[j]) === -1) {
+needsBinding.push(objids[j]);
+}
+}
+for (j=0; j < needsBinding.length; j++) {
+gl = this.gl;
+obj = this.getObj(needsBinding[j]);
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, obj.values, gl.STATIC_DRAW);
+}
+};
+this.vertexSetter = function(el, control)  {
+var svals = [].concat(control.param),
+j, k, p, propvals, stride, ofs, obj,
+attrib,
+ofss    = {x:"vofs", y:"vofs", z:"vofs",
+red:"cofs", green:"cofs", blue:"cofs",
+alpha:"cofs", radii:"radofs",
+nx:"nofs", ny:"nofs", nz:"nofs",
+ox:"oofs", oy:"oofs", oz:"oofs",
+ts:"tofs", tt:"tofs"},
+pos     = {x:0, y:1, z:2,
+red:0, green:1, blue:2,
+alpha:3,radii:0,
+nx:0, ny:1, nz:2,
+ox:0, oy:1, oz:2,
+ts:0, tt:1},
+values = control.values,
+direct = values === null,
+ncol,
+interp = control.interp,
+vertices = [].concat(control.vertices),
+attributes = [].concat(control.attributes),
+value = control.value;
+ncol = Math.max(vertices.length, attributes.length);
+if (!ncol)
+return;
+vertices = this.repeatToLen(vertices, ncol);
+attributes = this.repeatToLen(attributes, ncol);
+if (direct)
+interp = false;
+/* JSON doesn't pass Infinity */
+svals[0] = -Infinity;
+svals[svals.length - 1] = Infinity;
+for (j = 1; j < svals.length; j++) {
+if (value <= svals[j]) {
+if (interp) {
+if (svals[j] === Infinity)
+p = 1;
+else
+p = (svals[j] - value)/(svals[j] - svals[j-1]);
+} else {
+if (svals[j] - value > value - svals[j-1])
+j = j - 1;
+}
+break;
+}
+}
+obj = this.getObj(control.objid);
+propvals = obj.values;
+for (k=0; k<ncol; k++) {
+attrib = attributes[k];
+vertex = vertices[k];
+ofs = obj.vOffsets[ofss[attrib]];
+if (ofs < 0)
+this.alertOnce("Attribute '"+attrib+"' not found in object "+control.objid);
+else {
+stride = obj.vOffsets.stride;
+ofs = vertex*stride + ofs + pos[attrib];
+if (direct) {
+propvals[ofs] = value;
+} else if (interp) {
+propvals[ofs] = p*values[j-1][k] + (1-p)*values[j][k];
+} else {
+propvals[ofs] = values[j][k];
+}
+}
+}
+if (typeof obj.buf !== "undefined") {
+var gl = this.gl;
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, propvals, gl.STATIC_DRAW);
+}
+};
+this.ageSetter = function(el, control) {
+var objids = [].concat(control.objids),
+nobjs = objids.length,
+time = control.value,
+births = [].concat(control.births),
+ages = [].concat(control.ages),
+steps = births.length,
+j = Array(steps),
+p = Array(steps),
+i, k, age, j0, propvals, stride, ofs, objid, obj,
+attrib, dim,
+attribs = ["colors", "alpha", "radii", "vertices",
+"normals", "origins", "texcoords",
+"x", "y", "z",
+"red", "green", "blue"],
+ofss    = ["cofs", "cofs", "radofs", "vofs",
+"nofs", "oofs", "tofs",
+"vofs", "vofs", "vofs",
+"cofs", "cofs", "cofs"],
+dims    = [3,1,1,3,
+3,2,2,
+1,1,1,
+1,1,1],
+pos     = [0,3,0,0,
+0,0,0,
+0,1,2,
+0,1,2];
+/* Infinity doesn't make it through JSON */
+ages[0] = -Infinity;
+ages[ages.length-1] = Infinity;
+for (i = 0; i < steps; i++) {
+if (births[i] !== null) {  // NA in R becomes null
+age = time - births[i];
+for (j0 = 1; age > ages[j0]; j0++);
+if (ages[j0] == Infinity)
+p[i] = 1;
+else if (ages[j0] > ages[j0-1])
+p[i] = (ages[j0] - age)/(ages[j0] - ages[j0-1]);
+else
+p[i] = 0;
+j[i] = j0;
+}
+}
+for (l = 0; l < nobjs; l++) {
+objid = objids[l];
+obj = this.getObj(objid);
+propvals = obj.values;
+stride = obj.vOffsets.stride;
+for (k = 0; k < attribs.length; k++) {
+attrib = control[attribs[k]];
+if (typeof attrib !== "undefined") {
+ofs = obj.vOffsets[ofss[k]];
+if (ofs >= 0) {
+dim = dims[k];
+ofs = ofs + pos[k];
+for (i = 0; i < steps; i++) {
+if (births[i] !== null) {
+for (d=0; d < dim; d++) {
+propvals[i*stride + ofs + d] = p[i]*attrib[dim*(j[i]-1) + d] + (1-p[i])*attrib[dim*j[i] + d];
+}
+}
+}
+} else
+this.alertOnce("\'"+attribs[k]+"\' property not found in object "+objid);
+}
+}
+obj.values = propvals;
+if (typeof obj.buf !== "undefined") {
+gl = this.gl;
+gl.bindBuffer(gl.ARRAY_BUFFER, obj.buf);
+gl.bufferData(gl.ARRAY_BUFFER, obj.values, gl.STATIC_DRAW);
+}
+}
+};
+this.oldBridge = function(el, control) {
+var attrname, global = window[control.prefix + "rgl"];
+if (typeof global !== "undefined")
+for (attrname in global)
+this[attrname] = global[attrname];
+window[control.prefix + "rgl"] = this;
+};
+this.Player = function(el, control) {
+var
+self = this,
+components = [].concat(control.components),
+Tick = function() { /* "this" will be a timer */
+var i,
+nominal = this.value,
+slider = this.Slider,
+labels = this.outputLabels,
+output = this.Output,
+step;
+if (typeof slider !== "undefined" && nominal != slider.value)
+slider.value = nominal;
+if (typeof output !== "undefined") {
+step = Math.round((nominal - output.sliderMin)/output.sliderStep);
+if (labels !== null) {
+output.innerHTML = labels[step];
+} else {
+step = step*output.sliderStep + output.sliderMin;
+output.innerHTML = step.toPrecision(output.outputPrecision);
+}
+}
+for (i=0; i < this.actions.length; i++) {
+this.actions[i].value = nominal;
+}
+self.applyControls(el, this.actions, false);
+self.drawScene();
+},
+OnSliderInput = function() { /* "this" will be the slider */
+this.rgltimer.value = Number(this.value);
+this.rgltimer.Tick();
+},
+addSlider = function(min, max, step, value) {
+var slider = document.createElement("input");
+slider.type = "range";
+slider.min = min;
+slider.max = max;
+slider.step = step;
+slider.value = value;
+slider.oninput = OnSliderInput;
+slider.sliderActions = control.actions;
+slider.sliderScene = this;
+slider.className = "rgl-slider";
+slider.id = el.id + "-slider";
+el.rgltimer.Slider = slider;
+slider.rgltimer = el.rgltimer;
+el.appendChild(slider);
+},
+addLabel = function(labels, min, step, precision) {
+var output = document.createElement("output");
+output.sliderMin = min;
+output.sliderStep = step;
+output.outputPrecision = precision;
+output.className = "rgl-label";
+output.id = el.id + "-label";
+el.rgltimer.Output = output;
+el.rgltimer.outputLabels = labels;
+el.appendChild(output);
+},
+addButton = function(label) {
+var button = document.createElement("input"),
+onclicks = {Reverse: function() { this.rgltimer.reverse();},
+Play: function() { this.rgltimer.play();
+this.value = this.rgltimer.enabled ? "Pause" : "Play"; },
+Slower: function() { this.rgltimer.slower(); },
+Faster: function() { this.rgltimer.faster(); },
+Reset: function() { this.rgltimer.reset(); }};
+button.rgltimer = el.rgltimer;
+button.type = "button";
+button.value = label;
+if (label === "Play")
+button.rgltimer.PlayButton = button;
+button.onclick = onclicks[label];
+button.className = "rgl-button";
+button.id = el.id + "-" + label;
+el.appendChild(button);
+};
+if (typeof control.reinit !== "null") {
+control.actions.reinit = control.reinit;
+}
+el.rgltimer = new rgltimerClass(Tick, control.start, control.interval, control.stop, control.value, control.rate, control.loop, control.actions);
+for (var i=0; i < components.length; i++) {
+switch(components[i]) {
+case "Slider": addSlider(control.start, control.stop,
+control.step, control.value);
+break;
+case "Label": addLabel(control.labels, control.start,
+control.step, control.precision);
+break;
+default:
+addButton(components[i]);
+}
+}
+el.rgltimer.Tick();
+};
+this.applyControls = function(el, x, draw) {
+var self = this, reinit = x.reinit, i, obj, control, type;
+for (i = 0; i < x.length; i++) {
+control = x[i];
+type = control.type;
+self[type](el, control);
+};
+if (typeof reinit !== "undefined" && reinit !== null) {
+reinit = [].concat(reinit);
+for (i = 0; i < reinit.length; i++)
+self.getObj(reinit[i]).initialized = false;
+}
+if (typeof draw === "undefined" || draw)
+self.drawScene();
+};
+this.sceneChangeHandler = function(message) {
+var self = document.getElementById(message.elementId).rglinstance,
+objs = message.objects, mat = message.material,
+root = message.rootSubscene,
+initSubs = message.initSubscenes,
+redraw = message.redrawScene,
+skipRedraw = message.skipRedraw,
+deletes, subs, allsubs = [], obj, i,j;
+if (typeof message.delete !== "undefined") {
+deletes = [].concat(message.delete);
+if (typeof message.delfromSubscenes !== "undefined")
+subs = [].concat(message.delfromSubscenes);
+else
+subs = [];
+for (i = 0; i < deletes.length; i++) {
+for (j = 0; j < subs.length; j++) {
+self.delFromSubscene(deletes[i], subs[j]);
+}
+delete self.scene.objects[deletes[i]];
+}
+}
+if (typeof objs !== "undefined") {
+Object.keys(objs).forEach(function(key){
+key = parseInt(key, 10);
+self.scene.objects[key] = objs[key];
+self.initObj(key);
+var obj = self.getObj(key),
+subs = [].concat(obj.inSubscenes), k;
+allsubs = allsubs.concat(subs);
+for (k = 0; k < subs.length; k++)
+self.addToSubscene(key, subs[k]);
+});
+}
+if (typeof mat !== "undefined") {
+self.scene.material = mat;
+}
+if (typeof root !== "undefined") {
+self.scene.rootSubscene = root;
+}
+if (typeof initSubs !== "undefined")
+allsubs = allsubs.concat(initSubs);
+allsubs = self.unique(allsubs);
+for (i = 0; i < allsubs.length; i++) {
+self.initSubscene(allsubs[i]);
+}
+if (typeof skipRedraw !== "undefined") {
+root = self.getObj(self.scene.rootSubscene);
+root.par3d.skipRedraw = skipRedraw;
+}
+if (redraw)
+self.drawScene();
+};
+}).call(rglwidgetClass.prototype);
+rgltimerClass = function(Tick, startTime, interval, stopTime, value, rate, loop, actions) {
+this.enabled = false;
+this.timerId = 0;
+this.startTime = startTime;         /* nominal start time in seconds */
+this.value = value;                 /* current nominal time */
+this.interval = interval;           /* seconds between updates */
+this.stopTime = stopTime;           /* nominal stop time */
+this.rate = rate;                   /* nominal units per second */
+this.loop = loop;                   /* "none", "cycle", or "oscillate" */
+this.realStart = undefined;         /* real world start time */
+this.multiplier = 1;                /* multiplier for fast-forward
+or reverse */
+this.actions = actions;
+this.Tick = Tick;
+};
+(function() {
+this.play = function() {
+if (this.enabled) {
+this.enabled = false;
+window.clearInterval(this.timerId);
+this.timerId = 0;
+return;
+}
+var tick = function(self) {
+var now = new Date();
+self.value = self.multiplier*self.rate*(now - self.realStart)/1000 + self.startTime;
+if (self.value > self.stopTime || self.value < self.startTime) {
+if (!self.loop) {
+self.reset();
+} else {
+var cycle = self.stopTime - self.startTime,
+newval = (self.value - self.startTime) % cycle + self.startTime;
+if (newval < self.startTime) {
+newval += cycle;
+}
+self.realStart += (self.value - newval)*1000/self.multiplier/self.rate;
+self.value = newval;
+}
+}
+if (typeof self.Tick !== "undefined") {
+self.Tick(self.value);
+}
+};
+this.realStart = new Date() - 1000*(this.value - this.startTime)/this.rate/this.multiplier;
+this.timerId = window.setInterval(tick, 1000*this.interval, this);
+this.enabled = true;
+};
+this.reset = function() {
+this.value = this.startTime;
+this.newmultiplier(1);
+if (typeof this.Tick !== "undefined") {
+this.Tick(this.value);
+}
+if (this.enabled)
+this.play();  /* really pause... */
+if (typeof this.PlayButton !== "undefined")
+this.PlayButton.value = "Play";
+};
+this.faster = function() {
+this.newmultiplier(Math.SQRT2*this.multiplier);
+};
+this.slower = function() {
+this.newmultiplier(this.multiplier/Math.SQRT2);
+};
+this.reverse = function() {
+this.newmultiplier(-this.multiplier);
+};
+this.newmultiplier = function(newmult) {
+if (newmult != this.multiplier) {
+this.realStart += 1000*(this.value - this.startTime)/this.rate*(1/this.multiplier - 1/newmult);
+this.multiplier = newmult;
+}
+};
+}).call(rgltimerClass.prototype);</script>
+<div id="persp3ddiv" class="rglWebGL">
+
+</div>
+<script type="text/javascript">
+var persp3ddiv = document.getElementById("persp3ddiv"),
+persp3drgl = new rglwidgetClass();
+persp3ddiv.width = 577;
+persp3ddiv.height = 289;
+persp3drgl.initialize(persp3ddiv,
+{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":134,"objects":{"142":{"id":142,"type":"surface","material":{},"vertices [...]
+persp3drgl.prefix = "persp3d";
+</script>
+<p id="persp3ddebug">
+You must enable Javascript to view this page properly.
+</p>
+<script>persp3drgl.start();</script>
+ 
+<p>On the left, the whole surface over a range of the parameters; on the right, only the parts of the surface with log likelihood values near the maximum.</p>
+<p>Note: this example used the <code>knitr</code> hook functions (see <a href="#setupKnitr"><code>setupKnitr</code></a>) to insert the scene into this vignette; the previous example used the <code>rglwidget</code> function from the package of the same name. We generally recommend the newer <a href="../../rglwidget/help/rglwidget"><code>rglwidget</code></a> approach.</p>
+</div>
+<div id="adding-graphical-elements" class="section level2">
+<h2>Adding Graphical Elements</h2>
+<div id="primitive-shapes" class="section level3">
+<h3>Primitive shapes</h3>
+<p>Just as we have <a href="../../graphics/help/points"><code>points</code></a> and <a href="../../graphics/help/lines"><code>lines</code></a> in classic graphics, there are a number of low level functions in <code>rgl</code> to add graphical elements to the currently active plot. The “primitive” shapes are those that are native to OpenGL:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="points3d"><a href="#points3d"><code>points3d</code></a></a>:</td>
+<td align="left">adds points</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="lines3d"><a href="#lines3d"><code>lines3d</code></a></a>:</td>
+<td align="left">adds lines</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="segments3d"><a href="#segments3d"><code>segments3d</code></a></a>:</td>
+<td align="left">adds line segments</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="triangles3d"><a href="#triangles3d"><code>triangles3d</code></a></a>:</td>
+<td align="left">adds triangles</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="quads3d"><a href="#quads3d"><code>quads3d</code></a></a>:</td>
+<td align="left">adds quadrilaterals</td>
+</tr>
+</tbody>
+</table>
+<p>Each of the above functions takes arguments <code>x</code>, <code>y</code> and <code>z</code>, again using <a href="../../grDevices/help/xyz.coords"><code>xyz.coords</code></a> for flexibility. They group successive entries as necessary. For example, the <a href="#triangles3d"><code>triangles3d</code></a> function takes each successive triple of points as the vertices of a triangle.</p>
+<p>You can use these functions to annotate the current graph, or to construct a figure from scratch.</p>
+</div>
+<div id="constructed-shapes" class="section level3">
+<h3>Constructed shapes</h3>
+<p><code>rgl</code> also has a number of objects which it constructs from the primitives.</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="text3d"><a href="#text3d"><code>text3d</code></a></a>, <a name="texts3d"><a href="#texts3d"><code>texts3d</code></a></a>:</td>
+<td align="left">adds text</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="abclines3d"><a href="#abclines3d"><code>abclines3d</code></a></a>:</td>
+<td align="left">adds straight lines to plot (like <code>abline</code>)</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="planes3d"><a href="#planes3d"><code>planes3d</code></a></a>:</td>
+<td align="left">adds planes to plot</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="clipplanes3d"><a href="#clipplanes3d"><code>clipplanes3d</code></a></a>:</td>
+<td align="left">add clipping planes to plot</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="sprites3d"><a href="#sprites3d"><code>sprites3d</code></a></a>, <a name="particles3d"><a href="#particles3d"><code>particles3d</code></a></a>:</td>
+<td align="left">add sprites (fixed shapes or images) to plot</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="spheres3d"><a href="#spheres3d"><code>spheres3d</code></a></a>:</td>
+<td align="left">adds spheres</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="surface3d"><a href="#surface3d"><code>surface3d</code></a></a>, <a name="terrain3d"><a href="#terrain3d"><code>terrain3d</code></a></a>:</td>
+<td align="left">a surface (as used in <a href="#persp3d"><code>persp3d</code></a>)</td>
+</tr>
+</tbody>
+</table>
+</div>
+<div id="axes-and-other-decorations" class="section level3">
+<h3>Axes and other “decorations”</h3>
+<p>The following low-level functions control the look of the graph:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="axes3d"><a href="#axes3d"><code>axes3d</code></a></a>, <a name="axis3d"><a href="#axis3d"><code>axis3d</code></a></a>:</td>
+<td align="left">add axes to plot</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="box3d"><a href="#box3d"><code>box3d</code></a></a>, <a name="bbox3d"><a href="#bbox3d"><code>bbox3d</code></a></a>:</td>
+<td align="left">add box around plot</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="title3d"><a href="#title3d"><code>title3d</code></a></a>:</td>
+<td align="left">add title to plot</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="mtext3d"><a href="#mtext3d"><code>mtext3d</code></a></a>:</td>
+<td align="left">add marginal text to plot</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="decorate3d"><a href="#decorate3d"><code>decorate3d</code></a></a>:</td>
+<td align="left">add multiple “decorations” (scales, etc.) to plot</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="aspect3d"><a href="#aspect3d"><code>aspect3d</code></a></a>:</td>
+<td align="left">set the aspect ratios for the plot</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="bg3d"><a href="#bg3d"><code>bg3d</code></a></a>, <a name="bgplot3d"><a href="#bgplot3d"><code>bgplot3d</code></a></a>:</td>
+<td align="left">set the background of the scene</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="show2d"><a href="#show2d"><code>show2d</code></a></a>:</td>
+<td align="left">show a 2D plot or image in a 3D scene</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="legend3d"><a href="#legend3d"><code>legend3d</code></a></a>:</td>
+<td align="left">set a legend for the scene</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="grid3d"><a href="#grid3d"><code>grid3d</code></a></a>:</td>
+<td align="left">add a reference grid to a graph</td>
+</tr>
+</tbody>
+</table>
+<p>For example, to plot three random triangles, one could use</p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">triangles3d</span>(<span class="kw">cbind</span>(<span class="dt">x=</span><span class="kw">rnorm</span>(<span class="dv">9</span>), <span class="dt">y=</span><span class="kw">rnorm</span>(<span class="dv">9</span>), <span class="dt">z=</span><span class="kw">rnorm</span>(<span class="dv">9</span>)), <span class="dt">col =</span> <span class="st">"green"</span>)
+<span class="kw">decorate3d</span>()
+<span class="kw">bg3d</span>(<span class="st">"lightgray"</span>)
+<span class="kw">aspect3d</span>(<span class="dv">1</span>,<span class="dv">1</span>,<span class="dv">1</span>)</code></pre>
+<div id="unnamed_chunk_2div" class="rglWebGL">
+
+</div>
+<script type="text/javascript">
+var unnamed_chunk_2div = document.getElementById("unnamed_chunk_2div"),
+unnamed_chunk_2rgl = new rglwidgetClass();
+unnamed_chunk_2div.width = 289;
+unnamed_chunk_2div.height = 289;
+unnamed_chunk_2rgl.initialize(unnamed_chunk_2div,
+{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":178,"objects":{"184":{"id":184,"type":"triangles","material":{},"vertic [...]
+unnamed_chunk_2rgl.prefix = "unnamed_chunk_2";
+</script>
+<p id="unnamed_chunk_2debug">
+You must enable Javascript to view this page properly.
+</p>
+<script>unnamed_chunk_2rgl.start();</script>
+
+<p>Besides the <code>*3d</code> functions mentioned above, there are even lower-level functions <a name="rgl.primitive"><a href="#rgl.primitive"><code>rgl.primitive</code></a></a>, <a name="rgl.points"><a href="#rgl.points"><code>rgl.points</code></a></a>, <a name="rgl.linestrips"><a href="#rgl.linestrips"><code>rgl.linestrips</code></a></a>, <a name="rgl.lines"><a href="#rgl.lines"><code>rgl.lines</code></a></a>, <a name="rgl.triangles"><a href="#rgl.triangles"><code>rgl.triangles</code [...]
+</div>
+</div>
+<div id="controlling-the-look-of-the-scene" class="section level2">
+<h2>Controlling the Look of the Scene</h2>
+<div id="lighting" class="section level3">
+<h3>Lighting</h3>
+<p>In most scenes, objects are “lit”, meaning that their appearance depends on their position and orientation relative to lights in the scene. The lights themselves don’t normally show up, but their effect on the objects does.</p>
+<p>Use the <a name="light3d"><a href="#light3d"><code>light3d</code></a></a> function to specify the position and characteristics of a light. Lights may be infinitely distant, or may be embedded within the scene. Their characteristics include <code>ambient</code>, <code>diffuse</code>, and <code>specular</code> components, all defaulting to white. The <code>ambient</code> component appears the same from any direction. The <code>diffuse</code> component depends on the angle between the su [...]
+<p>The <a name="rgl.light"><a href="#rgl.light"><code>rgl.light</code></a></a> function is a lower-level function with different defaults; users should normally use <a href="#light3d"><code>light3d</code></a>.</p>
+</div>
+<div id="materials" class="section level3">
+<h3>Materials</h3>
+<p>The mental model used in <code>rgl</code> is that the objects being shown in scenes are physical objects in space, with material properties that affect how light reflects from them (or is emitted by them). These are mainly controlled by the <a name="material3d"><a href="#material3d"><code>material3d</code></a></a> function, or by arguments to other functions that are passed to it.</p>
+<p>The material properties that can be set by calls to <code>material3d</code> are described in detail in the <a href="../../rgl/help/material3d">?material3d</a> help page. Here we give an overview.</p>
+<table>
+<thead>
+<tr class="header">
+<th align="left">Property</th>
+<th align="left">Default</th>
+<th align="left">Meaning</th>
+</tr>
+</thead>
+<tbody>
+<tr class="odd">
+<td align="left">color</td>
+<td align="left">white</td>
+<td align="left">vector of surface colors to apply to successive vertices for diffuse light</td>
+</tr>
+<tr class="even">
+<td align="left">alpha</td>
+<td align="left">1</td>
+<td align="left">transparency: 0 is invisible, 1 is opaque</td>
+</tr>
+<tr class="odd">
+<td align="left">lit</td>
+<td align="left">TRUE</td>
+<td align="left">whether lighting calculations should be done</td>
+</tr>
+<tr class="even">
+<td align="left">ambient</td>
+<td align="left">black</td>
+<td align="left">color in ambient light</td>
+</tr>
+<tr class="odd">
+<td align="left">specular</td>
+<td align="left">white</td>
+<td align="left">color in specular light</td>
+</tr>
+<tr class="even">
+<td align="left">emission</td>
+<td align="left">black</td>
+<td align="left">color emitted by the surface</td>
+</tr>
+<tr class="odd">
+<td align="left">shininess</td>
+<td align="left">50</td>
+<td align="left">controls the specular lighting: high values look shiny</td>
+</tr>
+<tr class="even">
+<td align="left">smooth</td>
+<td align="left">TRUE</td>
+<td align="left">whether shading should be interpolated between vertices</td>
+</tr>
+<tr class="odd">
+<td align="left">texture</td>
+<td align="left">NULL</td>
+<td align="left">optional path to a “texture” bitmap to be displayed on the surface</td>
+</tr>
+<tr class="even">
+<td align="left">front, back</td>
+<td align="left">fill</td>
+<td align="left">should polygons be filled, or outlined?</td>
+</tr>
+<tr class="odd">
+<td align="left">size</td>
+<td align="left">3</td>
+<td align="left">size of points in pixels</td>
+</tr>
+<tr class="even">
+<td align="left">lwd</td>
+<td align="left">1</td>
+<td align="left">width of lines in pixels</td>
+</tr>
+</tbody>
+</table>
+<p>Other properties include “texmipmap”, “texmagfilter”, “texminfilter”, “texenvmap”, “fog”, “point_antialias”, “line_antialias”, “depth_mask”, and “depth_test”; see the help page for details.</p>
+<p>There is also an <a name="rgl.material"><a href="#rgl.material"><code>rgl.material</code></a></a> function that works at a lower level; users should normally avoid it.</p>
+</div>
+<div id="par3d-miscellaneous-graphical-parameters" class="section level3">
+<h3>par3d: Miscellaneous graphical parameters</h3>
+<p>The <a name="par3d"><a href="#par3d"><code>par3d</code></a></a> function, modelled after the classic graphics <a href="../../graphics/help/par"><code>par</code></a> function, sets or reads a variety of different <code>rgl</code> internal parameters. Some parameters are completely read-only; others are fixed at the time the window is opened, and others may be changed at any time.</p>
+<table>
+<thead>
+<tr class="header">
+<th align="left">Name</th>
+<th align="left">Changeable?</th>
+<th align="left">Description</th>
+</tr>
+</thead>
+<tbody>
+<tr class="odd">
+<td align="left">antialias</td>
+<td align="left">fixed</td>
+<td align="left">Amount of hardware antialiasing</td>
+</tr>
+<tr class="even">
+<td align="left">cex</td>
+<td align="left"></td>
+<td align="left">Default size for text</td>
+</tr>
+<tr class="odd">
+<td align="left">family</td>
+<td align="left"></td>
+<td align="left">Device-independent font family name; see <a href="../../rgl/help/text3d">?text3d</a></td>
+</tr>
+<tr class="even">
+<td align="left">font</td>
+<td align="left"></td>
+<td align="left">Integer font number</td>
+</tr>
+<tr class="odd">
+<td align="left">useFreeType</td>
+<td align="left"></td>
+<td align="left">Should FreeType fonts be used if available?</td>
+</tr>
+<tr class="even">
+<td align="left">fontname</td>
+<td align="left">read-only</td>
+<td align="left">System-dependent font name set by <a name="rglFonts"><a href="#rglFonts"><code>rglFonts</code></a></a></td>
+</tr>
+<tr class="odd">
+<td align="left">FOV</td>
+<td align="left"></td>
+<td align="left">Field of view, in degrees. Zero means isometric perspective</td>
+</tr>
+<tr class="even">
+<td align="left">ignoreExtent</td>
+<td align="left"></td>
+<td align="left">Should <code>rgl</code> ignore the size of new objects when computing the bounding box?</td>
+</tr>
+<tr class="odd">
+<td align="left">skipRedraw</td>
+<td align="left"></td>
+<td align="left">Should <code>rgl</code> suppress updates to the display?</td>
+</tr>
+<tr class="even">
+<td align="left">maxClipPlanes</td>
+<td align="left">read-only</td>
+<td align="left">How many clip planes can be defined?</td>
+</tr>
+<tr class="odd">
+<td align="left">modelMatrix</td>
+<td align="left">read-only</td>
+<td align="left">The OpenGL ModelView matrix; partly set by <a name="view3d"><a href="#view3d"><code>view3d</code></a></a> or the obsolete <a name="rgl.viewpoint"><a href="#rgl.viewpoint"><code>rgl.viewpoint</code></a></a></td>
+</tr>
+<tr class="even">
+<td align="left">projMatrix</td>
+<td align="left">read-only</td>
+<td align="left">The OpenGL Projection matrix</td>
+</tr>
+<tr class="odd">
+<td align="left">bbox</td>
+<td align="left">read-only</td>
+<td align="left">Current bounding-box of the scene</td>
+</tr>
+<tr class="even">
+<td align="left">viewport</td>
+<td align="left"></td>
+<td align="left">Dimensions in pixels of the scene within the window</td>
+</tr>
+<tr class="odd">
+<td align="left">windowRect</td>
+<td align="left"></td>
+<td align="left">Dimensions in pixels of the window on the whole screen</td>
+</tr>
+<tr class="even">
+<td align="left">listeners</td>
+<td align="left"></td>
+<td align="left">Which subscenes respond to mouse actions in the current one</td>
+</tr>
+<tr class="odd">
+<td align="left">mouseMode</td>
+<td align="left"></td>
+<td align="left">What the mouse buttons do. See <a href="#mouseMode"><code>“mouseMode”</code></a></td>
+</tr>
+<tr class="even">
+<td align="left">observer</td>
+<td align="left">read-only</td>
+<td align="left">The position of the observer; set by <a name="observer3d"><a href="#observer3d"><code>observer3d</code></a></a></td>
+</tr>
+<tr class="odd">
+<td align="left">scale</td>
+<td align="left"></td>
+<td align="left">Rescaling for each coordinate; see <a href="#aspect3d"><code>aspect3d</code></a></td>
+</tr>
+<tr class="even">
+<td align="left">zoom</td>
+<td align="left"></td>
+<td align="left">Magnification of the scene</td>
+</tr>
+</tbody>
+</table>
+</div>
+<div id="default-settings" class="section level3">
+<h3>Default settings</h3>
+<p>The <a name="r3dDefaults"><a href="#r3dDefaults"><code>r3dDefaults</code></a></a> list and the <a name="getr3dDefaults"><a href="#getr3dDefaults"><code>getr3dDefaults</code></a></a> function control defaults in new windows opened by <a href="#open3d"><code>open3d</code></a>.<br />The function looks for the variable in the user’s global environment, and if not found there, finds the one in the <code>rgl</code> namespace. This allows the user to override the default settings for new win [...]
+<p>Once found, the <code>r3dDefaults</code> list provides initial values for <a href="#par3d"><code>par3d</code></a> parameters, as well as defaults for <a href="#material3d"><code>material3d</code></a> and <a href="#bg3d"><code>bg3d</code></a> in components <code>"material"</code> and <code>"bg"</code> respectively.</p>
+</div>
+</div>
+<div id="meshes-constructing-shapes" class="section level2">
+<h2>Meshes: Constructing Shapes</h2>
+<p><code>rgl</code> includes a number of functions to construct and display various solid shapes. These generate objects of class <code>"shape3d"</code>, <code>"mesh3d"</code> or <code>"shapelist3d"</code>. The details of the classes are described below. We start with functions to generate them.</p>
+<div id="specific-solids" class="section level3">
+<h3>Specific solids</h3>
+<p>These functions generate specific shapes. Optional arguments allow attributes such as colour or transformations to be specified.</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="tetrahedron3d"><a href="#tetrahedron3d"><code>tetrahedron3d</code></a></a>, <a name="cube3d"><a href="#cube3d"><code>cube3d</code></a></a>, <a name="octahedron3d"><a href="#octahedron3d"><code>octahedron3d</code></a></a>, <a name="dodecahedron3d"><a href="#dodecahedron3d"><code>dodecahedron3d</code></a></a>, <a name="icosahedron3d"><a href="#icosahedron3d"><code>icosahedron3d</code></a></a>:</td>
+<td align="left">Platonic solids</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="cuboctahedron3d"><a href="#cuboctahedron3d"><code>cuboctahedron3d</code></a></a>, <a name="oh3d"><a href="#oh3d"><code>oh3d</code></a></a>:</td>
+<td align="left">other solids</td>
+</tr>
+</tbody>
+</table>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">open3d</span>()
+cols <-<span class="st"> </span><span class="kw">rainbow</span>(<span class="dv">7</span>)
+<span class="kw">layout3d</span>(<span class="kw">matrix</span>(<span class="dv">1</span>:<span class="dv">16</span>, <span class="dv">4</span>,<span class="dv">4</span>), <span class="dt">heights=</span><span class="kw">c</span>(<span class="dv">1</span>,<span class="dv">3</span>,<span class="dv">1</span>,<span class="dv">3</span>))
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"tetrahedron3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">tetrahedron3d</span>(<span class="dt">col=</span>cols[<span class="dv">1</span>])); <span class="kw">next3d</span>()
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"cube3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">cube3d</span>(<span class="dt">col=</span>cols[<span class="dv">2</span>])); <span class="kw">next3d</span>()
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"octahedron3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">octahedron3d</span>(<span class="dt">col=</span>cols[<span class="dv">3</span>])); <span class="kw">next3d</span>()
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"dodecahedron3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">dodecahedron3d</span>(<span class="dt">col=</span>cols[<span class="dv">4</span>])); <span class="kw">next3d</span>()
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"icosahedron3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">icosahedron3d</span>(<span class="dt">col=</span>cols[<span class="dv">5</span>])); <span class="kw">next3d</span>()
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"cuboctahedron3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">cuboctahedron3d</span>(<span class="dt">col=</span>cols[<span class="dv">6</span>])); <span class="kw">next3d</span>()
+<span class="kw">text3d</span>(<span class="dv">0</span>,<span class="dv">0</span>,<span class="dv">0</span>,<span class="st">"oh3d"</span>); <span class="kw">next3d</span>()
+<span class="kw">shade3d</span>(<span class="kw">oh3d</span>(<span class="dt">col=</span>cols[<span class="dv">7</span>]))</code></pre>
+<div id="unnamed_chunk_3div" class="rglWebGL">
+
+</div>
+<script type="text/javascript">
+var unnamed_chunk_3div = document.getElementById("unnamed_chunk_3div"),
+unnamed_chunk_3rgl = new rglwidgetClass();
+unnamed_chunk_3div.width = 481;
+unnamed_chunk_3div.height = 481;
+unnamed_chunk_3rgl.initialize(unnamed_chunk_3div,
+{"material":{"color":"#000000","alpha":1,"lit":true,"ambient":"#000000","specular":"#FFFFFF","emission":"#000000","shininess":50,"smooth":true,"front":"filled","back":"filled","size":3,"lwd":1,"fog":false,"point_antialias":false,"line_antialias":false,"texture":null,"textype":"rgb","texmipmap":false,"texminfilter":"linear","texmagfilter":"linear","texenvmap":false,"depth_mask":true,"depth_test":"less"},"rootSubscene":210,"objects":{"232":{"id":232,"type":"text","material":{"lit":false}," [...]
+unnamed_chunk_3rgl.prefix = "unnamed_chunk_3";
+</script>
+<p id="unnamed_chunk_3debug">
+You must enable Javascript to view this page properly.
+</p>
+<script>unnamed_chunk_3rgl.start();</script>
+
+</div>
+<div id="generating-new-shapes" class="section level3">
+<h3>Generating new shapes</h3>
+<p>These functions generate new shapes:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="cylinder3d"><a href="#cylinder3d"><code>cylinder3d</code></a></a>:</td>
+<td align="left">generate a tube or cylinder</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="polygon3d"><a href="#polygon3d"><code>polygon3d</code></a></a>:</td>
+<td align="left">generate a flat polygon by triangulation</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="extrude3d"><a href="#extrude3d"><code>extrude3d</code></a></a>:</td>
+<td align="left">generate an “extrusion” of a polygon</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="turn3d"><a href="#turn3d"><code>turn3d</code></a></a>:</td>
+<td align="left">generate a solid of rotation</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="ellipse3d"><a href="#ellipse3d"><code>ellipse3d</code></a></a>:</td>
+<td align="left">generate an ellipsoid in various ways</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="tmesh3d"><a href="#tmesh3d"><code>tmesh3d</code></a></a>, <a name="qmesh3d"><a href="#qmesh3d"><code>qmesh3d</code></a></a>:</td>
+<td align="left">generate a shape from vertices and faces</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="shapelist3d"><a href="#shapelist3d"><code>shapelist3d</code></a></a>:</td>
+<td align="left">generate a shape by combining other shapes</td>
+</tr>
+</tbody>
+</table>
+<p>A related function is <a name="triangulate"><a href="#triangulate"><code>triangulate</code></a></a>, which takes a two dimensional polygon and divides it up into triangles using the “ear-clipping” algorithm.</p>
+</div>
+<div id="the-underlying-class-structure-for-shapes" class="section level3">
+<h3>The underlying class structure for shapes</h3>
+<p><code>"shape3d"</code> is the basic abstract type. Objects of this class can be displayed by <a name="shade3d"><a href="#shade3d"><code>shade3d</code></a></a> (which shades faces), <a name="wire3d"><a href="#wire3d"><code>wire3d</code></a></a> (which draws edges), or <a name="dot3d"><a href="#dot3d"><code>dot3d</code></a></a> (which draws points at each vertex.) Note that <code>wire3d</code> and <code>dot3d</code> only work within R; in HTML output from <a href="#writeWebGL" [...]
+<p><code>"mesh3d"</code> is a descendant type. Objects of this type contain the following fields:</p>
+<table>
+<thead>
+<tr class="header">
+<th align="left">Field</th>
+<th align="left">Meaning</th>
+</tr>
+</thead>
+<tbody>
+<tr class="odd">
+<td align="left">vb</td>
+<td align="left">A 4 by n matrix of vertices in homogeneous coordinates. Each column is a point.</td>
+</tr>
+<tr class="even">
+<td align="left">it</td>
+<td align="left">(optional) A 3 by t matrix of vertex indices. Each column is a triangle.</td>
+</tr>
+<tr class="odd">
+<td align="left">ib</td>
+<td align="left">(optional) A 4 by q matrix of vertex indices. Each column is a quadrilateral.</td>
+</tr>
+<tr class="even">
+<td align="left">material</td>
+<td align="left">(optional) A list of material properties.</td>
+</tr>
+<tr class="odd">
+<td align="left">normals</td>
+<td align="left">(optional) A matrix of the same shape as vb, containing normal vectors at each vertex.</td>
+</tr>
+<tr class="even">
+<td align="left">texcoords</td>
+<td align="left">(optional) A 2 by n matrix of texture coordinates corresponding to each vertex.</td>
+</tr>
+</tbody>
+</table>
+</div>
+<div id="manipulating-shapes" class="section level3">
+<h3>Manipulating shapes</h3>
+<p>The final set of functions manipulate and modify mesh objects:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="addNormals"><a href="#addNormals"><code>addNormals</code></a></a>:</td>
+<td align="left">add normal vectors to make a shape look smooth</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="subdivision3d"><a href="#subdivision3d"><code>subdivision3d</code></a></a>:</td>
+<td align="left">add extra vertices to make it look even smoother</td>
+</tr>
+</tbody>
+</table>
+</div>
+</div>
+<div id="multi-figure-layouts" class="section level2">
+<h2>Multi-figure Layouts</h2>
+<p><code>rgl</code> has several functions to support displaying multiple different “subscenes” in the same window. The high level functions are</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="mfrow3d"><a href="#mfrow3d"><code>mfrow3d</code></a></a>:</td>
+<td align="left">Multiple figures (like <a href="../../graphics/help/par">par(“mfrow”)</a></td>
+</tr>
+<tr class="even">
+<td align="left"><a name="layout3d"><a href="#layout3d"><code>layout3d</code></a></a>:</td>
+<td align="left">Multiple figures (like <a href="../../graphics/help/layout"><code>layout</code></a>)</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="next3d"><a href="#next3d"><code>next3d</code></a></a>:</td>
+<td align="left">Move to the next figure (like <a href="../../graphics/help/plot.new"><code>plot.new</code></a> or <a href="../../graphics/help/frame"><code>frame</code></a>)</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="subsceneList"><a href="#subsceneList"><code>subsceneList</code></a></a>:</td>
+<td align="left">List all the subscenes in the current layout</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="clearSubsceneList"><a href="#clearSubsceneList"><code>clearSubsceneList</code></a></a></td>
+<td align="left">Clear the current list and revert to the previous one</td>
+</tr>
+</tbody>
+</table>
+<p>There are also lower level functions.</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="newSubscene3d"><a href="#newSubscene3d"><code>newSubscene3d</code></a></a>:</td>
+<td align="left">Create a new subscene, with fine control over what is inherited from the parent</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="currentSubscene3d"><a href="#currentSubscene3d"><code>currentSubscene3d</code></a></a>:</td>
+<td align="left">Report on the active subscene</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="subsceneInfo"><a href="#subsceneInfo"><code>subsceneInfo</code></a></a>:</td>
+<td align="left">Get information on current subscene</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="useSubscene3d"><a href="#useSubscene3d"><code>useSubscene3d</code></a></a>:</td>
+<td align="left">Make a different subscene active</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="addToSubscene3d"><a href="#addToSubscene3d"><code>addToSubscene3d</code></a></a>, <a name="delFromSubscene3d"><a href="#delFromSubscene3d"><code>delFromSubscene3d</code></a></a>:</td>
+<td align="left">Add objects to a subscene, or delete them</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="gc3d"><a href="#gc3d"><code>gc3d</code></a></a>:</td>
+<td align="left">Do “garbage collection”: delete objects that are not displayed in any subscene</td>
+</tr>
+</tbody>
+</table>
+</div>
+<div id="utility-functions" class="section level2">
+<h2>Utility Functions</h2>
+<div id="user-interaction" class="section level3">
+<h3>User interaction</h3>
+<p>By default, <code>rgl</code> detects and handles mouse clicks within your scene, and uses these to control its appearance. You can find out the current handlers using the following code:</p>
+<pre class="sourceCode r"><code class="sourceCode r"><span class="kw">par3d</span>(<span class="st">"mouseMode"</span>)</code></pre>
+<pre><code>##        left       right      middle       wheel 
+## "trackball"      "zoom"       "fov"      "pull"</code></pre>
+<p>The labels <code>c("left", "right", "middle")</code> refer to the buttons on a three button mouse, or simulations of them on other mice. <code>"wheel"</code> refers to the mouse wheel.</p>
+<p>The button actions generally correspond to click and drag operations. Possible values for <a name="mouseMode"><a href="#mouseMode"><code>“mouseMode”</code></a></a> for buttons or the wheel are as follows:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><code>"none"</code></td>
+<td align="left">No action</td>
+</tr>
+<tr class="even">
+<td align="left"><code>"trackball"</code></td>
+<td align="left">The mouse acts as a virtual trackball. Clicking and dragging rotates the scene</td>
+</tr>
+<tr class="odd">
+<td align="left"><code>"xAxis"</code>, <code>"yAxis"</code>, <code>"zAxis"</code></td>
+<td align="left">Like <code>"trackball"</code>, but restricted to rotation about one axis</td>
+</tr>
+<tr class="even">
+<td align="left"><code>"polar"</code></td>
+<td align="left">The mouse affects rotations by controlling polar coordinates directly</td>
+</tr>
+<tr class="odd">
+<td align="left"><code>"selecting"</code></td>
+<td align="left">The mouse is being used by the <a href="#select3d"><code>select3d</code></a> function</td>
+</tr>
+<tr class="even">
+<td align="left"><code>"zoom"</code></td>
+<td align="left">The mouse zooms the display</td>
+</tr>
+<tr class="odd">
+<td align="left"><code>"fov"</code></td>
+<td align="left">The mouse affects perspective by changing the field of view</td>
+</tr>
+<tr class="even">
+<td align="left"><code>"pull"</code></td>
+<td align="left">Rotating the mouse wheel towards the user “pulls the scene closer”</td>
+</tr>
+<tr class="odd">
+<td align="left"><code>"push"</code></td>
+<td align="left">The same rotation “pushes the scene away”</td>
+</tr>
+<tr class="even">
+<td align="left"><code>"user"</code></td>
+<td align="left">A user action set by <a name="rgl.setMouseCallbacks"><a href="#rgl.setMouseCallbacks"><code>rgl.setMouseCallbacks</code></a></a>, <a name="rgl.setWheelCallback"><a href="#rgl.setWheelCallback"><code>rgl.setWheelCallback</code></a></a>. Use <a name="rgl.getMouseCallbacks"><a href="#rgl.getMouseCallbacks"><code>rgl.getMouseCallbacks</code></a></a> and <a name="rgl.getWheelCallback"><a href="#rgl.getWheelCallback"><code>rgl.getWheelCallback</code></a></a> to retrieve</td>
+</tr>
+</tbody>
+</table>
+<p>The following functions make use of the mouse for selection within a scene.</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="identify3d"><a href="#identify3d"><code>identify3d</code></a></a></td>
+<td align="left">like the classic graphics <a href="../../graphics/help/identify"><code>identify</code></a> function</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="select3d"><a href="#select3d"><code>select3d</code></a></a></td>
+<td align="left">returns a function that tests whether a coordinate was selected</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="selectpoints3d"><a href="#selectpoints3d"><code>selectpoints3d</code></a></a></td>
+<td align="left">selects from specific objects</td>
+</tr>
+</tbody>
+</table>
+<p>The <a name="rgl.select3d"><a href="#rgl.select3d"><code>rgl.select3d</code></a></a> function is an obsolete version of <code>select3d</code>, and <a name="rgl.select"><a href="#rgl.select"><code>rgl.select</code></a></a> is a low-level support function.</p>
+</div>
+<div id="animations" class="section level3">
+<h3>Animations</h3>
+<p><code>rgl</code> has several functions that can be used to construct animations. These are based on functions that update the scene according to the current real-world time, and repeated calls to those. The functions are:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="play3d"><a href="#play3d"><code>play3d</code></a></a></td>
+<td align="left">Repeatedly call the update function</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="spin3d"><a href="#spin3d"><code>spin3d</code></a></a></td>
+<td align="left">Update the display by rotating at a constant rate</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="par3dinterp"><a href="#par3dinterp"><code>par3dinterp</code></a></a></td>
+<td align="left">Compute new values of some <a href="#par3d"><code>par3d</code></a> parameters by interpolation over time</td>
+</tr>
+</tbody>
+</table>
+<p>See the <a href="#movie3d"><code>movie3d</code></a> function for a way to output an animation to a file on disk.<br />Animations are not currently supported in the HTML written by <a href="#writeWebGL"><code>writeWebGL</code></a>, though the <code>rglwidget::playwidget</code> function provides equivalent functionality.</p>
+</div>
+<div id="exporting-and-importing-scenes" class="section level3">
+<h3>Exporting and importing scenes</h3>
+<p><code>rgl</code> contains several functions to write scenes to disk for use by other software, or to read them in.</p>
+<p>In order from highest fidelity to lowest, the functions are:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="scene3d"><a href="#scene3d"><code>scene3d</code></a></a></td>
+<td align="left">Save a scene to an R variable, which can be saved and reloaded</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="writeWebGL"><a href="#writeWebGL"><code>writeWebGL</code></a></a></td>
+<td align="left">Write HTML and Javascript to display a scene in a web browser. (See also <a href="WebGL.html">User Interaction in WebGL</a>.)</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="writePLY"><a href="#writePLY"><code>writePLY</code></a></a></td>
+<td align="left">Write PLY files (commonly used in 3D printing)</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="readOBJ"><a href="#readOBJ"><code>readOBJ</code></a></a>, <a name="writeOBJ"><a href="#writeOBJ"><code>writeOBJ</code></a></a></td>
+<td align="left">Read or write OBJ files (commonly used in 3D graphics)</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="readSTL"><a href="#readSTL"><code>readSTL</code></a></a>, <a name="writeSTL"><a href="#writeSTL"><code>writeSTL</code></a></a></td>
+<td align="left">Read or write STL files (also common in 3D printing)</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.useNULL"><a href="#rgl.useNULL"><code>rgl.useNULL</code></a></a></td>
+<td align="left">A helper function for setting a NULL device</td>
+</tr>
+</tbody>
+</table>
+<p>See the help page <a href="../../rgl/help/rgl.useNULL"><code>rgl.useNULL</code></a> for instructions on how to use <code>rgl</code> on a “headless” system.</p>
+<p>There are also functions to save snapshots or other recordings of a scene, without any 3D information being saved:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="snapshot3d"><a href="#snapshot3d"><code>snapshot3d</code></a></a></td>
+<td align="left">Save a PNG file bitmap of the scene</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.postscript"><a href="#rgl.postscript"><code>rgl.postscript</code></a></a></td>
+<td align="left">Save a Postscript, LaTeX, PDF, SVG or PGF vector rendering of the scene</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="movie3d"><a href="#movie3d"><code>movie3d</code></a></a></td>
+<td align="left">Save a series of bitmaps to be assembled into a movie</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.pixels"><a href="#rgl.pixels"><code>rgl.pixels</code></a></a></td>
+<td align="left">Obtain pixel-level information about the scene in an R variable</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="rgl.Sweave"><a href="#rgl.Sweave"><code>rgl.Sweave</code></a></a></td>
+<td align="left">Driver function for inserting a snapshot into a Sweave document.</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="hook_rgl"><a href="#hook_rgl"><code>hook_rgl</code></a></a>, <a name="hook_webgl"><a href="#hook_webgl"><code>hook_webgl</code></a></a></td>
+<td align="left"><code>knitr</code> hook functions for inserting images into a document.</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="setupKnitr"><a href="#setupKnitr"><code>setupKnitr</code></a></a></td>
+<td align="left">Function to set up <code>knitr</code> hooks</td>
+</tr>
+</tbody>
+</table>
+<p>The <a name="rgl.snapshot"><a href="#rgl.snapshot"><code>rgl.snapshot</code></a></a> function is identical to <code>snapshot3d</code>. The functions <a name="rgl.Sweave.off"><a href="#rgl.Sweave.off"><code>rgl.Sweave.off</code></a></a>, <a name="Sweave.snapshot"><a href="#Sweave.snapshot"><code>Sweave.snapshot</code></a></a> are involved in Sweave processing and not normally called by users.</p>
+</div>
+<div id="working-with-webgl-scenes" class="section level3">
+<h3>Working with WebGL scenes</h3>
+<p>There are currently two schemes for exporting a scene to a web page. Both require the <code>rglwidget</code> package and use the same underlying code.</p>
+<p>The recommended approach works with the <code>htmlwidgets</code> framework (see <a href="http://www.htmlwidgets.org/">http://www.htmlwidgets.org/</a>). In an R Markdown document in <code>knitr</code>, use the chunk option <code>webgl=TRUE</code>, or the <code>rglwidget::rglwidget()</code> function. More details are given in the vignette <a href="WebGL.html">User Interaction in WebGL</a>.</p>
+<p>The older approach uses the <code>writeWebGL</code> function to export a scene to HTML and Javascript code.<br />The functions below write HTML and Javascript for working with the exported scene.</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="propertySlider"><a href="#propertySlider"><code>propertySlider</code></a></a></td>
+<td align="left">insert a slider to make changes to a scene</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="clipplaneSlider"><a href="#clipplaneSlider"><code>clipplaneSlider</code></a></a></td>
+<td align="left">insert a slider to control a clipping plane</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="subsetSlider"><a href="#subsetSlider"><code>subsetSlider</code></a></a></td>
+<td align="left">insert a slider to control which objects are displayed</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="toggleButton"><a href="#toggleButton"><code>toggleButton</code></a></a></td>
+<td align="left">insert a button to toggle some items</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="propertySetter"><a href="#propertySetter"><code>propertySetter</code></a></a></td>
+<td align="left">function to modify properties</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="subsetSetter"><a href="#subsetSetter"><code>subsetSetter</code></a></a></td>
+<td align="left">function to choose subsets</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="ageSetter"><a href="#ageSetter"><code>ageSetter</code></a></a></td>
+<td align="left">function to “age” vertices</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="par3dinterpSetter"><a href="#par3dinterpSetter"><code>par3dinterpSetter</code></a></a></td>
+<td align="left">function like <a href="#par3dinterp"><code>par3dinterp</code></a></td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="vertexSetter"><a href="#vertexSetter"><code>vertexSetter</code></a></a></td>
+<td align="left">function to modify individual vertices</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="matrixSetter"><a href="#matrixSetter"><code>matrixSetter</code></a></a></td>
+<td align="left">function to modify matrices</td>
+</tr>
+</tbody>
+</table>
+</div>
+<div id="working-with-the-scene" class="section level3">
+<h3>Working with the scene</h3>
+<p><code>rgl</code> maintains internal structures for all the scenes it displays. The following functions allow users to find information about them and manipulate them.</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="open3d"><a href="#open3d"><code>open3d</code></a></a></td>
+<td align="left">open a new window</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.close"><a href="#rgl.close"><code>rgl.close</code></a></a></td>
+<td align="left">close the current window</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="rgl.bringtotop"><a href="#rgl.bringtotop"><code>rgl.bringtotop</code></a></a></td>
+<td align="left">bring the current window to the top</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.cur"><a href="#rgl.cur"><code>rgl.cur</code></a></a></td>
+<td align="left">id of the active device</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="rgl.dev.list"><a href="#rgl.dev.list"><code>rgl.dev.list</code></a></a></td>
+<td align="left">ids of all active devices</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.set"><a href="#rgl.set"><code>rgl.set</code></a></a></td>
+<td align="left">set a particular device to be active</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="rgl.ids"><a href="#rgl.ids"><code>rgl.ids</code></a></a></td>
+<td align="left">ids and types of all current objects</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.attrib"><a href="#rgl.attrib"><code>rgl.attrib</code></a></a>, <a name="rgl.attrib.count"><a href="#rgl.attrib.count"><code>rgl.attrib.count</code></a></a>:</td>
+<td align="left">attributes of objects in the scene</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="pop3d"><a href="#pop3d"><code>pop3d</code></a></a>, <a name="rgl.pop"><a href="#rgl.pop"><code>rgl.pop</code></a></a></td>
+<td align="left">delete an object from the scene</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="clear3d"><a href="#clear3d"><code>clear3d</code></a></a>, <a name="rgl.clear"><a href="#rgl.clear"><code>rgl.clear</code></a></a></td>
+<td align="left">delete all objects of certain classes</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="rgl.projection"><a href="#rgl.projection"><code>rgl.projection</code></a></a></td>
+<td align="left">return information about the current projection</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rgl.user2window"><a href="#rgl.user2window"><code>rgl.user2window</code></a></a>, <a name="rgl.window2user"><a href="#rgl.window2user"><code>rgl.window2user</code></a></a></td>
+<td align="left">convert between coordinates in the current projection</td>
+</tr>
+</tbody>
+</table>
+<p>In addition to these, there are some other related functions which should rarely be called by users: <a name="rgl.init"><a href="#rgl.init"><code>rgl.init</code></a></a>, <a name="rgl.open"><a href="#rgl.open"><code>rgl.open</code></a></a>, <a name="rgl.quit"><a href="#rgl.quit"><code>rgl.quit</code></a></a>.</p>
+</div>
+<div id="working-with-3-d-vectors" class="section level3">
+<h3>Working with 3-D vectors</h3>
+<p>Most <code>rgl</code> functions work internally with “homogeneous” coordinates. In this system, 3-D points are represented with 4 coordinates, generally called (x, y, z, w). The corresponding Euclidean point is (x/w, y/w, z/w), if w is nonzero; zero values of w correspond to “points at infinity”. The advantage of this system is that affine transformations including translations and perspective shifts become linear transformations, with multiplication by a 4 by 4 matrix.</p>
+<p><code>rgl</code> has the following functions to work with homogeneous coordinates:</p>
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a name="asEuclidean"><a href="#asEuclidean"><code>asEuclidean</code></a></a>, <a name="asHomogeneous"><a href="#asHomogeneous"><code>asHomogeneous</code></a></a>:</td>
+<td align="left">convert between homogeneous and Euclidean coordinates</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rotate3d"><a href="#rotate3d"><code>rotate3d</code></a></a>, <a name="scale3d"><a href="#scale3d"><code>scale3d</code></a></a>, <a name="translate3d"><a href="#translate3d"><code>translate3d</code></a></a>:</td>
+<td align="left">apply a transformation</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="transform3d"><a href="#transform3d"><code>transform3d</code></a></a>:</td>
+<td align="left">apply a general transformation</td>
+</tr>
+<tr class="even">
+<td align="left"><a name="rotationMatrix"><a href="#rotationMatrix"><code>rotationMatrix</code></a></a>, <a name="scaleMatrix"><a href="#scaleMatrix"><code>scaleMatrix</code></a></a>, <a name="translationMatrix"><a href="#translationMatrix"><code>translationMatrix</code></a></a>:</td>
+<td align="left">compute the transformation matrix</td>
+</tr>
+<tr class="odd">
+<td align="left"><a name="identityMatrix"><a href="#identityMatrix"><code>identityMatrix</code></a></a></td>
+<td align="left">return a 4 x 4 identity matrix</td>
+</tr>
+</tbody>
+</table>
+<p>There is also a function <a name="GramSchmidt"><a href="#GramSchmidt"><code>GramSchmidt</code></a></a>, mainly for internal use: it does a Gram-Schmidt orthogonalization of a 3x3 matrix, with some specializations for its use in <a href="#cylinder3d"><code>cylinder3d</code></a>.</p>
+</div>
+</div>
+<div id="warning-work-in-progress" class="section level2">
+<h2>Warning: Work in Progress!</h2>
+<p>This vignette is in a preliminary form. Many aspects of the rgl package are not described, or do not have examples. There may even be functions that are missed completely, if the following list is not empty:</p>
+<pre><code>## character(0)</code></pre>
+</div>
+<div id="index-of-functions" class="section level2">
+<h2>Index of Functions</h2>
+<p>The following functions and constants are described in this document:<br></p>
+<div class="nostripes">
+<table>
+<tbody>
+<tr class="odd">
+<td align="left"><a href="#GramSchmidt">GramSchmidt</a>  </td>
+<td align="left"><a href="#hook_webgl">hook_webgl</a>  </td>
+<td align="left"><a href="#qmesh3d">qmesh3d</a>  </td>
+<td align="left"><a href="#rgl.projection">rgl.projection</a>  </td>
+<td align="left"><a href="#spin3d">spin3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#Sweave.snapshot">Sweave.snapshot</a>  </td>
+<td align="left"><a href="#icosahedron3d">icosahedron3d</a>  </td>
+<td align="left"><a href="#quads3d">quads3d</a>  </td>
+<td align="left"><a href="#rgl.quads">rgl.quads</a>  </td>
+<td align="left"><a href="#sprites3d">sprites3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#abclines3d">abclines3d</a>  </td>
+<td align="left"><a href="#identify3d">identify3d</a>  </td>
+<td align="left"><a href="#r3dDefaults">r3dDefaults</a>  </td>
+<td align="left"><a href="#rgl.quit">rgl.quit</a>  </td>
+<td align="left"><a href="#subdivision3d">subdivision3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#addNormals">addNormals</a>  </td>
+<td align="left"><a href="#identityMatrix">identityMatrix</a>  </td>
+<td align="left"><a href="#readOBJ">readOBJ</a>  </td>
+<td align="left"><a href="#rgl.select">rgl.select</a>  </td>
+<td align="left"><a href="#subsceneInfo">subsceneInfo</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#addToSubscene3d">addToSubscene3d</a>  </td>
+<td align="left"><a href="#layout3d">layout3d</a>  </td>
+<td align="left"><a href="#readSTL">readSTL</a>  </td>
+<td align="left"><a href="#rgl.select3d">rgl.select3d</a>  </td>
+<td align="left"><a href="#subsceneList">subsceneList</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#ageSetter">ageSetter</a>  </td>
+<td align="left"><a href="#legend3d">legend3d</a>  </td>
+<td align="left"><a href="#rgl.Sweave">rgl.Sweave</a>  </td>
+<td align="left"><a href="#rgl.set">rgl.set</a>  </td>
+<td align="left"><a href="#subsetSetter">subsetSetter</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#asEuclidean">asEuclidean</a>  </td>
+<td align="left"><a href="#light3d">light3d</a>  </td>
+<td align="left"><a href="#rgl.Sweave.off">rgl.Sweave.off</a>  </td>
+<td align="left"><a href="#rgl.setMouseCallbacks">rgl.setMouseCallbacks</a>  </td>
+<td align="left"><a href="#subsetSlider">subsetSlider</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#asHomogeneous">asHomogeneous</a>  </td>
+<td align="left"><a href="#lines3d">lines3d</a>  </td>
+<td align="left"><a href="#rgl.abclines">rgl.abclines</a>  </td>
+<td align="left"><a href="#rgl.setWheelCallback">rgl.setWheelCallback</a>  </td>
+<td align="left"><a href="#surface3d">surface3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#aspect3d">aspect3d</a>  </td>
+<td align="left"><a href="#material3d">material3d</a>  </td>
+<td align="left"><a href="#rgl.attrib">rgl.attrib</a>  </td>
+<td align="left"><a href="#rgl.snapshot">rgl.snapshot</a>  </td>
+<td align="left"><a href="#terrain3d">terrain3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#axes3d">axes3d</a>  </td>
+<td align="left"><a href="#matrixSetter">matrixSetter</a>  </td>
+<td align="left"><a href="#rgl.attrib.count">rgl.attrib.count</a>  </td>
+<td align="left"><a href="#rgl.spheres">rgl.spheres</a>  </td>
+<td align="left"><a href="#tetrahedron3d">tetrahedron3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#axis3d">axis3d</a>  </td>
+<td align="left"><a href="#mfrow3d">mfrow3d</a>  </td>
+<td align="left"><a href="#rgl.bbox">rgl.bbox</a>  </td>
+<td align="left"><a href="#rgl.sprites">rgl.sprites</a>  </td>
+<td align="left"><a href="#text3d">text3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#bbox3d">bbox3d</a>  </td>
+<td align="left"><a href="#mouseMode">mouseMode</a>  </td>
+<td align="left"><a href="#rgl.bg">rgl.bg</a>  </td>
+<td align="left"><a href="#rgl.surface">rgl.surface</a>  </td>
+<td align="left"><a href="#texts3d">texts3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#bg3d">bg3d</a>  </td>
+<td align="left"><a href="#movie3d">movie3d</a>  </td>
+<td align="left"><a href="#rgl.bringtotop">rgl.bringtotop</a>  </td>
+<td align="left"><a href="#rgl.texts">rgl.texts</a>  </td>
+<td align="left"><a href="#title3d">title3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#bgplot3d">bgplot3d</a>  </td>
+<td align="left"><a href="#mtext3d">mtext3d</a>  </td>
+<td align="left"><a href="#rgl.clear">rgl.clear</a>  </td>
+<td align="left"><a href="#rgl.triangles">rgl.triangles</a>  </td>
+<td align="left"><a href="#tmesh3d">tmesh3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#box3d">box3d</a>  </td>
+<td align="left"><a href="#newSubscene3d">newSubscene3d</a>  </td>
+<td align="left"><a href="#rgl.clipplanes">rgl.clipplanes</a>  </td>
+<td align="left"><a href="#rgl.useNULL">rgl.useNULL</a>  </td>
+<td align="left"><a href="#toggleButton">toggleButton</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#clear3d">clear3d</a>  </td>
+<td align="left"><a href="#next3d">next3d</a>  </td>
+<td align="left"><a href="#rgl.close">rgl.close</a>  </td>
+<td align="left"><a href="#rgl.user2window">rgl.user2window</a>  </td>
+<td align="left"><a href="#transform3d">transform3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#clearSubsceneList">clearSubsceneList</a>  </td>
+<td align="left"><a href="#observer3d">observer3d</a>  </td>
+<td align="left"><a href="#rgl.cur">rgl.cur</a>  </td>
+<td align="left"><a href="#rgl.viewpoint">rgl.viewpoint</a>  </td>
+<td align="left"><a href="#translate3d">translate3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#clipplaneSlider">clipplaneSlider</a>  </td>
+<td align="left"><a href="#octahedron3d">octahedron3d</a>  </td>
+<td align="left"><a href="#rgl.dev.list">rgl.dev.list</a>  </td>
+<td align="left"><a href="#rgl.window2user">rgl.window2user</a>  </td>
+<td align="left"><a href="#translationMatrix">translationMatrix</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#clipplanes3d">clipplanes3d</a>  </td>
+<td align="left"><a href="#oh3d">oh3d</a>  </td>
+<td align="left"><a href="#rgl.getMouseCallbacks">rgl.getMouseCallbacks</a>  </td>
+<td align="left"><a href="#rglFonts">rglFonts</a>  </td>
+<td align="left"><a href="#triangles3d">triangles3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#cube3d">cube3d</a>  </td>
+<td align="left"><a href="#open3d">open3d</a>  </td>
+<td align="left"><a href="#rgl.getWheelCallback">rgl.getWheelCallback</a>  </td>
+<td align="left"><a href="#rotate3d">rotate3d</a>  </td>
+<td align="left"><a href="#triangulate">triangulate</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#cuboctahedron3d">cuboctahedron3d</a>  </td>
+<td align="left"><a href="#par3d">par3d</a>  </td>
+<td align="left"><a href="#rgl.ids">rgl.ids</a>  </td>
+<td align="left"><a href="#rotationMatrix">rotationMatrix</a>  </td>
+<td align="left"><a href="#turn3d">turn3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#currentSubscene3d">currentSubscene3d</a>  </td>
+<td align="left"><a href="#par3dinterp">par3dinterp</a>  </td>
+<td align="left"><a href="#rgl.init">rgl.init</a>  </td>
+<td align="left"><a href="#scale3d">scale3d</a>  </td>
+<td align="left"><a href="#useSubscene3d">useSubscene3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#cylinder3d">cylinder3d</a>  </td>
+<td align="left"><a href="#par3dinterpSetter">par3dinterpSetter</a>  </td>
+<td align="left"><a href="#rgl.light">rgl.light</a>  </td>
+<td align="left"><a href="#scaleMatrix">scaleMatrix</a>  </td>
+<td align="left"><a href="#vertexSetter">vertexSetter</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#decorate3d">decorate3d</a>  </td>
+<td align="left"><a href="#particles3d">particles3d</a>  </td>
+<td align="left"><a href="#rgl.lines">rgl.lines</a>  </td>
+<td align="left"><a href="#scene3d">scene3d</a>  </td>
+<td align="left"><a href="#view3d">view3d</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#delFromSubscene3d">delFromSubscene3d</a>  </td>
+<td align="left"><a href="#persp3d">persp3d</a>  </td>
+<td align="left"><a href="#rgl.linestrips">rgl.linestrips</a>  </td>
+<td align="left"><a href="#segments3d">segments3d</a>  </td>
+<td align="left"><a href="#wire3d">wire3d</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#dodecahedron3d">dodecahedron3d</a>  </td>
+<td align="left"><a href="#planes3d">planes3d</a>  </td>
+<td align="left"><a href="#rgl.material">rgl.material</a>  </td>
+<td align="left"><a href="#select3d">select3d</a>  </td>
+<td align="left"><a href="#writeOBJ">writeOBJ</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#dot3d">dot3d</a>  </td>
+<td align="left"><a href="#play3d">play3d</a>  </td>
+<td align="left"><a href="#rgl.open">rgl.open</a>  </td>
+<td align="left"><a href="#selectpoints3d">selectpoints3d</a>  </td>
+<td align="left"><a href="#writePLY">writePLY</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#ellipse3d">ellipse3d</a>  </td>
+<td align="left"><a href="#plot3d">plot3d</a>  </td>
+<td align="left"><a href="#rgl.pixels">rgl.pixels</a>  </td>
+<td align="left"><a href="#setupKnitr">setupKnitr</a>  </td>
+<td align="left"><a href="#writeSTL">writeSTL</a>  </td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#extrude3d">extrude3d</a>  </td>
+<td align="left"><a href="#points3d">points3d</a>  </td>
+<td align="left"><a href="#rgl.planes">rgl.planes</a>  </td>
+<td align="left"><a href="#shade3d">shade3d</a>  </td>
+<td align="left"><a href="#writeWebGL">writeWebGL</a>  </td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#gc3d">gc3d</a>  </td>
+<td align="left"><a href="#polygon3d">polygon3d</a>  </td>
+<td align="left"><a href="#rgl.points">rgl.points</a>  </td>
+<td align="left"><a href="#shapelist3d">shapelist3d</a>  </td>
+<td align="left"></td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#getr3dDefaults">getr3dDefaults</a>  </td>
+<td align="left"><a href="#pop3d">pop3d</a>  </td>
+<td align="left"><a href="#rgl.pop">rgl.pop</a>  </td>
+<td align="left"><a href="#show2d">show2d</a>  </td>
+<td align="left"></td>
+</tr>
+<tr class="even">
+<td align="left"><a href="#grid3d">grid3d</a>  </td>
+<td align="left"><a href="#propertySetter">propertySetter</a>  </td>
+<td align="left"><a href="#rgl.postscript">rgl.postscript</a>  </td>
+<td align="left"><a href="#snapshot3d">snapshot3d</a>  </td>
+<td align="left"></td>
+</tr>
+<tr class="odd">
+<td align="left"><a href="#hook_rgl">hook_rgl</a>  </td>
+<td align="left"><a href="#propertySlider">propertySlider</a>  </td>
+<td align="left"><a href="#rgl.primitive">rgl.primitive</a>  </td>
+<td align="left"><a href="#spheres3d">spheres3d</a>  </td>
+<td align="left"></td>
+</tr>
+</tbody>
+</table>
+</div>
+</div>
+
+
+
+<!-- dynamically load mathjax for compatibility with self-contained -->
+<script>
+  (function () {
+    var script = document.createElement("script");
+    script.type = "text/javascript";
+    script.src  = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
+    document.getElementsByTagName("head")[0].appendChild(script);
+  })();
+</script>
+
+</body>
+</html>
diff --git a/inst/fonts/FreeMono.ttf b/inst/fonts/FreeMono.ttf
new file mode 100644
index 0000000..c31dff2
Binary files /dev/null and b/inst/fonts/FreeMono.ttf differ
diff --git a/inst/fonts/FreeSans.ttf b/inst/fonts/FreeSans.ttf
new file mode 100644
index 0000000..0e85d7f
Binary files /dev/null and b/inst/fonts/FreeSans.ttf differ
diff --git a/inst/fonts/FreeSerif.ttf b/inst/fonts/FreeSerif.ttf
new file mode 100644
index 0000000..fd4b469
Binary files /dev/null and b/inst/fonts/FreeSerif.ttf differ
diff --git a/inst/textures/bump_dust.png b/inst/textures/bump_dust.png
new file mode 100644
index 0000000..21f1f9f
Binary files /dev/null and b/inst/textures/bump_dust.png differ
diff --git a/inst/textures/nightfire.png b/inst/textures/nightfire.png
new file mode 100644
index 0000000..c3c1728
Binary files /dev/null and b/inst/textures/nightfire.png differ
diff --git a/inst/textures/particle.png b/inst/textures/particle.png
new file mode 100644
index 0000000..56f61ac
Binary files /dev/null and b/inst/textures/particle.png differ
diff --git a/inst/textures/refmap.png b/inst/textures/refmap.png
new file mode 100644
index 0000000..40d9c90
Binary files /dev/null and b/inst/textures/refmap.png differ
diff --git a/inst/textures/rgl2.png b/inst/textures/rgl2.png
new file mode 100644
index 0000000..8663bd5
Binary files /dev/null and b/inst/textures/rgl2.png differ
diff --git a/inst/textures/sunsleep.png b/inst/textures/sunsleep.png
new file mode 100644
index 0000000..c1c8aaa
Binary files /dev/null and b/inst/textures/sunsleep.png differ
diff --git a/inst/textures/world.png b/inst/textures/world.png
new file mode 100644
index 0000000..e8b6627
Binary files /dev/null and b/inst/textures/world.png differ
diff --git a/inst/textures/worldsmall.png b/inst/textures/worldsmall.png
new file mode 100644
index 0000000..b0e90d5
Binary files /dev/null and b/inst/textures/worldsmall.png differ
diff --git a/man/3dobjects.Rd b/man/3dobjects.Rd
new file mode 100644
index 0000000..b016d96
--- /dev/null
+++ b/man/3dobjects.Rd
@@ -0,0 +1,103 @@
+\name{points3d}
+\alias{points3d}
+\alias{lines3d}
+\alias{segments3d}
+\alias{triangles3d}
+\alias{quads3d}
+\title{add primitive set shape}
+\description{
+Adds a shape node to the current scene
+}
+\usage{
+points3d(x, y = NULL, z = NULL,  ...)
+lines3d(x, y = NULL, z = NULL,  ...)
+segments3d(x, y = NULL, z = NULL, ...)
+triangles3d(x, y = NULL, z = NULL, ...)
+quads3d(x, y = NULL, z = NULL, ...)
+}
+\arguments{
+  \item{x, y, z}{coordinates. Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{ ... }{Material properties (see \code{\link{rgl.material}}).
+  For normals use \code{normals} and for
+  texture coordinates use \code{texcoords}; see \code{\link{rgl.primitive}}
+  for details.}  
+}
+\details{
+
+The functions \code{points3d}, \code{lines3d}, \code{segments3d},
+\code{triangles3d} and \code{quads3d} add points, joined lines, line segments,
+filled triangles or quadrilaterals to the plots.  They correspond to the OpenGL types
+\code{GL_POINTS, GL_LINE_STRIP, GL_LINES, GL_TRIANGLES} and \code{GL_QUADS} respectively.  
+
+Points are taken in pairs by \code{segments3d}, triplets as the vertices
+of the triangles, and quadruplets for the quadrilaterals.  Colors are applied vertex by vertex; 
+if different at each end of a line segment, or each vertex of a polygon, the colors
+are blended over the extent of the object.  Quadrilaterals must be entirely 
+in one plane and convex, or the results are undefined.
+
+These functions call the lower level functions \code{\link{rgl.points}}, \code{\link{rgl.linestrips}},
+and so on, and are provided for convenience.  
+
+The appearance of the new objects are defined by the material properties.
+See \code{\link{rgl.material}} for details.
+
+The two principal differences between the \code{rgl.*} functions and
+the \code{*3d} functions are that the former set all unspecified
+material properties to defaults, whereas the latter use current values
+as defaults; the former make persistent changes to material properties
+with each call, whereas the latter make temporary changes only for the
+duration of the call.  
+
+}
+\value{
+   Each function returns the integer object ID of the shape that
+   was added to the scene.  These can be passed to \code{\link{rgl.pop}}
+   to remove the object from the scene.
+}
+\author{
+  Ming Chen and Duncan Murdoch
+}
+
+\examples{
+# Show 12 random vertices in various ways. 
+
+M <- matrix(rnorm(36), 3, 12, dimnames = list(c('x', 'y', 'z'), 
+                                       rep(LETTERS[1:4], 3)))
+
+# Force 4-tuples to be convex in planes so that quads3d works.
+
+for (i in c(1, 5, 9)) {
+    quad <- as.data.frame(M[, i + 0:3])
+    coeffs <- runif(2, 0, 3)
+    if (mean(coeffs) < 1) coeffs <- coeffs + 1 - mean(coeffs)
+    quad$C <- with(quad, coeffs[1]*(B - A) + coeffs[2]*(D - A) + A)
+    M[, i + 0:3] <- as.matrix(quad)
+}
+
+open3d()
+
+# Rows of M are x, y, z coords; transpose to plot
+
+M <- t(M)
+shift <- matrix(c(-3, 3, 0), 12, 3, byrow = TRUE)
+
+points3d(M)
+lines3d(M + shift)
+segments3d(M + 2*shift)
+triangles3d(M + 3*shift, col = 'red')
+quads3d(M + 4*shift, col = 'green')  
+text3d(M + 5*shift, texts = 1:12)
+
+# Add labels
+
+shift <- outer(0:5, shift[1, ])
+shift[, 1] <- shift[, 1] + 3
+text3d(shift, 
+       texts = c('points3d', 'lines3d', 'segments3d',
+         'triangles3d', 'quads3d', 'text3d'),
+       adj = 0)
+ rgl.bringtotop()
+}
+\keyword{dynamic}
diff --git a/man/GramSchmidt.Rd b/man/GramSchmidt.Rd
new file mode 100644
index 0000000..a769193
--- /dev/null
+++ b/man/GramSchmidt.Rd
@@ -0,0 +1,48 @@
+\name{GramSchmidt}
+\alias{GramSchmidt}
+\title{
+The Gram-Schmidt algorithm
+}
+\description{
+Generate a 3x3 orthogonal matrix using the Gram-Schmidt algorithm.
+}
+\usage{
+GramSchmidt(v1, v2, v3, order = 1:3)
+}
+\arguments{
+  \item{v1, v2, v3}{
+Three length 3 vectors (taken as row vectors).
+}
+  \item{order}{
+The precedence order for the vectors; see Details.
+}
+}
+\details{
+This function orthogonalizes the matrix \code{rbind(v1, v2, v3)}
+using the Gram-Schmidt algorithm.  It can handle rank 2 matrices
+(returning a rank 3 matrix).  If the original is rank 1, it is likely
+to fail.
+
+The \code{order} vector determines the precedence of the original
+vectors. For example, if it is \code{c(i, j, k)}, then row \code{i} 
+will be unchanged (other than normalization); row \code{j} will
+normally be transformed within the span of rows \code{i} and \code{j}.  
+Row \code{k} will be transformed orthogonally to the span of
+the others.
+}
+\value{
+A 3x3 matrix whose rows are the orthogonalization of the original
+row vectors.
+}
+\author{
+Duncan Murdoch
+}
+\examples{
+# Proceed through the rows in order
+print(A <- matrix(rnorm(9), 3, 3))
+GramSchmidt(A[1, ], A[2, ], A[3, ])
+
+# Keep the middle row unchanged
+print(A <- matrix(c(rnorm(2), 0, 1, 0, 0, rnorm(3)), 3, 3, byrow = TRUE))
+GramSchmidt(A[1, ], A[2, ], A[3, ], order = c(2, 1, 3))
+}
diff --git a/man/abclines.Rd b/man/abclines.Rd
new file mode 100644
index 0000000..b836482
--- /dev/null
+++ b/man/abclines.Rd
@@ -0,0 +1,52 @@
+\name{abclines3d}
+\alias{rgl.abclines}
+\alias{abclines3d}
+\title{
+Lines intersecting the bounding box
+}
+\description{
+This adds mathematical lines to a scene.  Their intersection with the current
+bounding box will be drawn.
+}
+\usage{
+rgl.abclines(x, y = NULL, z = NULL, a, b = NULL, c = NULL, ...)
+abclines3d(x, y = NULL, z = NULL, a, b = NULL, c = NULL, ...)
+}
+\arguments{
+  \item{x, y, z}{
+Coordinates of points through which each line passes.  
+} 
+  \item{a, b, c}{
+Coordinates of the direction vectors for the lines.
+}
+  \item{...}{
+Material properties.
+}
+
+}
+\details{
+These functions draw the segment of a line that intersects the current
+bounding box of the scene using the parametrization
+\eqn{ (x, y, z) + (a, b, c) * s } where \eqn{s} is a real number.
+
+Any reasonable way of defining the
+coordinates \code{x, y, z} and \code{a, b, c} is acceptable.  
+See the function \code{\link[grDevices]{xyz.coords}}
+for details.
+}
+\value{
+A shape ID of the object is returned invisibly.
+}
+
+\seealso{
+\code{\link{planes3d}}, \code{\link{rgl.planes}} for mathematical planes.
+
+\code{\link{segments3d}} draws sections of lines that
+do not adapt to the bounding box.
+
+}
+\examples{
+plot3d(rnorm(100), rnorm(100), rnorm(100))
+abclines3d(0, 0, 0, a = diag(3), col = "gray")
+}
+\keyword{ dynamic }
diff --git a/man/addNormals.Rd b/man/addNormals.Rd
new file mode 100644
index 0000000..7e32a1b
--- /dev/null
+++ b/man/addNormals.Rd
@@ -0,0 +1,38 @@
+\name{addNormals}
+\alias{addNormals}
+\alias{addNormals.mesh3d}
+\alias{addNormals.shapelist3d}
+\title{
+Add normal vectors to objects so they render more smoothly.
+}
+\description{
+This generic function adds normals at each of the vertices
+of a polyhedron by averaging the normals of each incident face.  This has the
+effect of making the surface of the object appear smooth rather than faceted
+when rendered.
+}
+\usage{
+addNormals(x, ...)
+}
+\arguments{
+  \item{x}{An object to which to add normals.}
+  \item{\dots}{Additional parameters which will be passed to the methods.  Currently unused.}
+}
+\details{
+Currently methods are supplied for \code{\link[=mesh3d]{"mesh3d"}} and 
+\code{\link[=shapelist3d]{"shapelist3d"}} classes.
+}
+\value{
+A new object of the same class as \code{x}, with normals added.
+}
+\author{
+Duncan Murdoch
+}
+\examples{
+open3d()
+y <- subdivision3d(tetrahedron3d(col = "red"), depth = 3)
+shade3d(y) # No normals
+y <- addNormals(y)
+shade3d(translate3d(y, x = 1, y = 0, z = 0)) # With normals
+}
+\keyword{dynamic}
diff --git a/man/ageSetter.Rd b/man/ageSetter.Rd
new file mode 100644
index 0000000..d03677a
--- /dev/null
+++ b/man/ageSetter.Rd
@@ -0,0 +1,88 @@
+\name{ageSetter}
+\alias{ageSetter}
+\title{
+Set WebGL scene properties based on the age of components
+of objects.
+}
+\description{
+Many \pkg{rgl} shapes contain lists of vertices with various
+attributes (available via \code{\link{rgl.attrib}}).  This function
+modifies the data for those attributes in a WebGL scene.
+}
+\usage{
+ageSetter(births, ages, 
+         colors = NULL, alpha = NULL, radii = NULL, 
+         vertices = NULL, normals = NULL, origins = NULL, 
+         texcoords = NULL, 
+         objids, prefixes = "", digits = 7, 
+         param = seq(floor(min(births)), ceiling(max(births))))
+}
+\arguments{
+  \item{births}{
+Numeric vector with one value per vertex, used to determine the
+\dQuote{age} of the vertex when displaying it.
+}
+  \item{ages}{
+A non-decreasing sequence of \dQuote{ages}.  
+}
+  \item{colors, alpha, radii, vertices, normals, origins, texcoords}{
+Attributes of the vertices.  Non-\code{NULL} attributes will be 
+interpolated from these values.  See the Details section below.
+}
+  \item{objids, prefixes}{
+The object ids and scene prefixes to modify.  These are recycled to
+the same length.
+}
+  \item{digits}{
+How many digits to output in the generated Javascript code.
+}
+  \item{param}{
+Default values to be used by a slider control calling the generated
+function.
+}
+}
+\details{
+The vertex attributes
+are specified as follows:
+\describe{
+\item{colors}{A vector of colors in a format suitable for input to \code{\link{col2rgb}}}
+\item{alpha}{A numeric vector of alpha values between 0 and 1.}
+\item{radii}{A numeric vector of sphere radii.}
+\item{vertices}{A 3-column matrix of vertex coordinates.}
+\item{normals}{A 3-column matrix of vertex normals.}
+\item{origins}{A 2-column matrix of origins for text or sprites.}
+\item{texcoords}{A 2-column matrix of texture coordinates.}
+}
+
+All attributes must have the same number of entries (rows for the matrices)
+as the \code{ages} vector.  The \code{births} vector must have the
+same number of entries as the number of vertices in the object.
+
+Not all objects contain all attributes listed here; if one is
+chosen that is not a property of the corresponding object, a
+Javascript \code{alert()} will be generated.  
+}
+\value{
+A character vector of class \code{c("ageSetter", "propertySetter")} 
+containing Javascript
+code defining a function suitable for use in a \code{\link{propertySlider}}.
+
+The function takes a single argument, \code{time}, and uses it to compute the
+\dQuote{age} of vertex \code{i} as \code{time - births[i]}.  
+Those are then used with the \code{ages}
+argument to linearly interpolate settings of the specified attributes.
+Extrapolation is constant.  Repeated values in \code{ages} can be used
+to obtain discontinuities in the settings.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{propertySlider}}; more detailed control is available in
+\code{\link{vertexSetter}}.
+}
+\examples{
+if (require(rglwidget))
+  propertySlider(ageSetter(births = 1:10, ages = c(-1, 0, 1), 
+              alpha = c(0, 1, 1), objids = 123))
+}
diff --git a/man/aspect3d.Rd b/man/aspect3d.Rd
new file mode 100644
index 0000000..520cddf
--- /dev/null
+++ b/man/aspect3d.Rd
@@ -0,0 +1,42 @@
+\name{aspect3d}
+\alias{aspect3d}
+\title{Set the aspect ratios of the current plot}
+\description{
+This function sets the apparent ratios of the x, y, and z axes
+of the current bounding box.
+}
+\usage{
+aspect3d(x, y = NULL, z = NULL)
+}
+\arguments{
+  \item{x}{The ratio for the x axis, or all three ratios, or \code{"iso"} }
+  \item{y}{The ratio for the y axis }
+  \item{z}{The ratio for the z axis }
+}
+\details{
+If the ratios are all 1, the bounding box will be displayed as a cube approximately filling the display.
+Values may be set larger or smaller as desired.  Aspect \code{"iso"} signifies that the
+coordinates should all be displayed at the same scale, i.e. the bounding box should not be
+rescaled.  (This corresponds to the default display before \code{aspect3d} has been called.)
+Partial matches to \code{"iso"} are allowed.
+
+\code{aspect3d} works by modifying \code{par3d("scale")}.
+}
+\value{
+The previous value of the scale is returned invisibly.
+}
+\author{Duncan Murdoch}
+\seealso{\code{\link{plot3d}}, \code{\link{par3d}}}
+\examples{
+  x <- rnorm(100)
+  y <- rnorm(100)*2
+  z <- rnorm(100)*3
+  
+  open3d()
+  plot3d(x, y, z)
+  aspect3d(1, 1, 0.5)
+  open3d()
+  plot3d(x, y, z)
+  aspect3d("iso")
+}
+\keyword{dynamic}
diff --git a/man/attributes.Rd b/man/attributes.Rd
new file mode 100644
index 0000000..49be7ae
--- /dev/null
+++ b/man/attributes.Rd
@@ -0,0 +1,82 @@
+\name{rgl.attrib}
+\alias{rgl.attrib.count}
+\alias{rgl.attrib}
+\title{
+Get information about shapes
+}
+\description{
+Retrieves information about the shapes in a scene.
+}
+\usage{
+rgl.attrib.count(id, attrib)
+rgl.attrib(id, attrib, first = 1, 
+	last = rgl.attrib.count(id, attrib))
+}
+\arguments{
+  \item{id}{
+A shape identifier, as returned by \code{\link{rgl.ids}}.
+}
+  \item{attrib}{
+An attribute of a shape.  Currently supported: one of \cr
+\code{"vertices"}, \code{"normals"}, \code{"colors"}, \code{"texcoords"}, 
+\code{"dim"}, \code{"texts"}, \code{"cex"}, \code{"adj"}, \code{"radii"}, 
+\code{"centers"}, \code{"ids"}, \code{"usermatrix"}, \code{"types"},
+\code{"flags"}, \code{"offsets"}, \code{"family"}, \code{"font"}\cr
+or unique prefixes
+to one of those. 
+}
+  \item{first, last}{
+Specify these to retrieve only those rows of the result.
+}
+}
+\details{
+If the identifier is not found or is not a shape that has the given attribute, 
+zero will be returned by \code{rgl.attrib.count}, and an empty matrix
+will be returned by \code{rgl.attrib}.
+
+The first four \code{attrib} names correspond to the usual OpenGL
+properties; \code{"dim"} is used just for surfaces, defining the rows
+and columns in the rectangular grid; \code{"cex"}, \code{"adj"},
+\code{"family"} and \code{"font"} apply only to text objects.
+}
+\value{
+\code{rgl.attrib.count} returns the count of the requested attribute.  \code{rgl.attrib}
+returns the values of the attribute.  Attributes
+are mostly real-valued, with the following sizes:
+\tabular{lll}{
+\code{"vertices"}	\tab 3 values 	\tab x, y, z \cr
+\code{"normals"}	\tab 3 values 	\tab x, y, z \cr
+\code{"centers"}	\tab 3 values 	\tab x, y, z \cr
+\code{"colors"}	\tab 4 values 	\tab r, g, b, a \cr
+\code{"texcoords"}	\tab 2 values 	\tab s, t \cr
+\code{"dim"}	\tab 2 values 	\tab r, c \cr
+\code{"cex"}	\tab 1 value 	\tab cex \cr
+\code{"adj"}	\tab 2 values 	\tab x, y \cr
+\code{"radii"}	\tab 1 value 	\tab r \cr
+\code{"ids"}	\tab 1 value	\tab id \cr
+\code{"usermatrix"}	\tab 4 values 	\tab x, y, z, w \cr
+\code{"texts"}	\tab 1 value	\tab text \cr
+\code{"types"}	\tab 1 value	\tab type \cr
+\code{"flags"}	\tab 1 value	\tab flag \cr
+\code{"family"} \tab 1 value    \tab family \cr
+\code{"font"}   \tab 1 value    \tab font \cr
+}
+The \code{"texts"}, \code{"types"} and \code{"family"}
+attributes are character-valued; the flags
+attribute is logical valued, with named rows.
+
+These are returned as matrices with the row count equal to the count for the attribute,
+and the columns as listed above.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{rgl.ids}}
+}
+\examples{
+p <- plot3d(rnorm(100), rnorm(100), rnorm(100), type = "s", col = "red")
+rgl.attrib.count(p["data"], "vertices")
+rgl.attrib(p["data"], "vertices", last = 10)
+}
+\keyword{ graphics }
diff --git a/man/axes3d.Rd b/man/axes3d.Rd
new file mode 100644
index 0000000..8a4f508
--- /dev/null
+++ b/man/axes3d.Rd
@@ -0,0 +1,100 @@
+\name{axes3d}
+\alias{axes3d}
+\alias{axis3d}
+\alias{mtext3d}
+\alias{title3d}
+\alias{box3d}
+\title{ Draw boxes, axes and other text outside the data }
+\description{
+These functions draw axes, boxes and text outside the range of the data.
+\code{axes3d}, \code{box3d} and \code{title3d} are the higher level functions; 
+normally the others need not be called directly by users.
+}
+\usage{
+axes3d(edges = "bbox", labels = TRUE, tick = TRUE, nticks = 5, 
+	box = FALSE, expand = 1.03, ...)
+box3d(...) 
+title3d(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, 
+	zlab = NULL, line = NA, ...) 
+axis3d(edge, at = NULL, labels = TRUE, tick = TRUE, line = 0, 
+	pos = NULL, nticks = 5, ...) 
+mtext3d(text, edge, line = 0, at = NULL, pos = NA, ...) 
+}
+\arguments{
+  \item{edges}{ a code to describe which edge(s) of the box to use; see Details below }
+  \item{labels}{ whether to label the axes, or (for \code{axis3d}) the
+  labels to use}
+  \item{tick}{ whether to use tick marks }
+  \item{nticks}{ suggested number of ticks }
+  \item{box}{ draw the full box if \code{"bbox"} axes are used }
+  \item{expand}{ how much to expand the box around the data }
+  \item{main}{ the main title for the plot }
+  \item{sub}{ the subtitle for the plot }
+  \item{xlab, ylab, zlab}{ the axis labels for the plot }
+  \item{line}{ the ``line'' of the plot margin to draw the label on }
+  \item{edge, pos}{ the position at which to draw the axis or text }
+  \item{text}{ the text to draw }
+  \item{at}{ the value of a coordinate at which to draw the axis }
+  \item{\dots}{ additional parameters which are passed to \code{\link{bbox3d}} or \code{\link{material3d}} }
+}
+
+\details{
+The rectangular prism holding the 3D plot has 12 edges.  They are identified
+using 3 character strings.  The first character (`x', `y', or `z') selects 
+the direction of the axis.  The next two characters are each `-' or `+',
+selecting the lower or upper end of one of the other coordinates.  If only
+one or two characters are given, the remaining characters default to `-'.  
+For example \code{edge = 'x+'} draws an x-axis at the high level of y and the
+low level of z.
+
+By default, \code{axes3d} uses the \code{\link{bbox3d}} function to draw the axes.  
+The labels will move so that they do not obscure the data.  Alternatively,
+a vector of arguments as described above may be used, in which case
+fixed axes are drawn using \code{axis3d}.
+
+If \code{pos} is a numeric vector of length 3, \code{edge} determines
+the direction of the axis and the tick marks, and the values of the
+other two coordinates in \code{pos} determine the position.  See the
+examples.
+}
+\value{
+These functions are called for their side effects.  They return the object IDs of
+objects added to the scene.
+}
+\author{ Duncan Murdoch }
+
+\seealso{Classic graphics functions \code{\link{axis}}, \code{\link{box}},
+\code{\link{title}}, \code{\link{mtext}}, and \pkg{rgl} function \code{\link{bbox3d}}.}
+
+\examples{
+  open3d()
+  points3d(rnorm(10), rnorm(10), rnorm(10))
+
+  # First add standard axes
+  axes3d()  
+
+  # and one in the middle (the NA will be ignored, a number would 
+  # do as well)
+  axis3d('x', pos = c(NA, 0, 0))
+
+  # add titles
+  title3d('main', 'sub', 'xlab', 'ylab', 'zlab')
+
+  rgl.bringtotop()
+  
+  open3d()
+  points3d(rnorm(10), rnorm(10), rnorm(10))
+  
+  # Use fixed axes
+  
+  axes3d(c('x', 'y', 'z'))
+         
+  # Put 4 x-axes on the plot
+  axes3d(c('x--', 'x-+', 'x+-', 'x++'))         
+  
+  axis3d('x', pos = c(NA, 0, 0))     
+  title3d('main', 'sub', 'xlab', 'ylab', 'zlab')
+}
+
+
+\keyword{dynamic}%-- one or more ...
diff --git a/man/bbox.Rd b/man/bbox.Rd
new file mode 100644
index 0000000..28d5534
--- /dev/null
+++ b/man/bbox.Rd
@@ -0,0 +1,68 @@
+\name{rgl.bbox}
+\alias{rgl.bbox}
+\alias{bbox3d}
+\title{Set up Bounding Box decoration}
+\description{
+  Set up the bounding box decoration.
+}
+\usage{
+rgl.bbox( 
+	xat = NULL, xlab = NULL, xunit = 0, xlen = 5, 
+	yat = NULL, ylab = NULL, yunit = 0, ylen = 5,
+	zat = NULL, zlab = NULL, zunit = 0, zlen = 5,
+	marklen = 15.0, marklen.rel = TRUE, expand = 1, 
+	draw_front = FALSE, ...)
+bbox3d(xat = NULL, yat = NULL, zat = NULL, 
+	xunit = "pretty", yunit = "pretty", zunit = "pretty", 
+	expand = 1.03,
+	draw_front = FALSE, ...)  
+}
+\arguments{
+  \item{xat, yat, zat}{vector specifying the tickmark positions}
+  \item{xlab, ylab, zlab}{character vector specifying the tickmark labeling}
+  \item{xunit, yunit, zunit}{value specifying the tick mark base for uniform tick mark layout}
+  \item{xlen, ylen, zlen}{value specifying the number of tickmarks}
+  \item{marklen}{value specifying the length of the tickmarks}
+  \item{marklen.rel}{logical, if TRUE tick mark length is calculated using 1/\code{marklen} * axis length, otherwise tick mark length is \code{marklen} in coordinate space}
+  \item{expand}{value specifying how much to expand the bounding box around the data}
+  \item{draw_front}{draw the front faces of the bounding box}
+  \item{ ... }{Material properties (or other \code{rgl.bbox} parameters
+  in the case of \code{bbox3d}). See \code{\link{rgl.material}} for details.}
+}
+\details{
+  Four different types of tick mark layouts are possible.
+This description applies to the X axis; other axes are similar:
+  If \code{xat} is not \code{NULL}, the ticks are set up at custom positions.
+  If \code{xunit} is numeric but not zero, it defines the tick mark base.  If
+  it is \code{"pretty"} (the default in \code{bbox3d}), ticks are set at \code{\link{pretty}}
+  locations.
+  If \code{xlen} is not zero, it specifies the number of ticks
+  (a suggestion if \code{xunit} is \code{"pretty"}).
+
+  The first color specifies the bounding box, while the second one specifies the tick mark and font color.
+  
+  \code{bbox3d} defaults to \code{\link{pretty}} locations for the axis labels and a slightly larger
+  box, whereas \code{rgl.bbox} covers the exact range.
+  
+  \code{\link{axes3d}} offers more flexibility in the specification of the axes, but 
+  they are static, unlike those drawn by \code{\link{rgl.bbox}} and \code{\link{bbox3d}}.
+}
+\value{
+  This function is called for the side effect of setting the bounding box decoration.
+  A shape ID is returned to allow \code{\link{rgl.pop}} to delete it.
+}
+\examples{
+  rgl.open()
+  rgl.points(rnorm(100), rnorm(100), rnorm(100))
+  rgl.bbox(color = c("#333377", "white"), emission = "#333377", 
+           specular = "#3333FF", shininess = 5, alpha = 0.8 )
+  
+  open3d()
+  points3d(rnorm(100), rnorm(100), rnorm(100))
+  bbox3d(color = c("#333377", "black"), emission = "#333377", 
+         specular = "#3333FF", shininess = 5, alpha = 0.8)
+}
+\seealso{
+  \code{\link{rgl.material}}, \code{\link{axes3d}} 
+}
+\keyword{dynamic}
diff --git a/man/bg.Rd b/man/bg.Rd
new file mode 100644
index 0000000..0aedd11
--- /dev/null
+++ b/man/bg.Rd
@@ -0,0 +1,71 @@
+\name{bg3d}
+\alias{rgl.bg}
+\alias{bg3d}
+\title{Set up Background}
+\description{
+  Set up the background of the scene.
+}
+\usage{
+bg3d(...) 
+rgl.bg( sphere = FALSE, fogtype = "none", color = c("black", "white"), 
+	back = "lines", ...)
+
+}
+\arguments{
+  \item{fogtype}{fog type:
+    \describe{
+      \item{"none"}{no fog}
+      \item{"linear"}{linear fog function}
+      \item{"exp"}{exponential fog function}
+      \item{"exp2"}{squared exponential fog function}
+    }
+  }
+  \item{sphere}{
+  logical, if true, an environmental sphere geometry is used for the background decoration.
+  }
+  \item{color}{
+  Primary color is used for background clearing and as fog color.
+  Secondary color is used for background sphere geometry. See \code{\link{material3d}} for details.
+  }
+  \item{back}{
+  Specifies the fill style of the sphere geometry. See \code{\link{material3d}} for details.
+  }
+  \item{ ... }{Material properties. See \code{\link{material3d}} for details.}  
+}
+\details{
+If sphere is set to \code{TRUE}, an environmental sphere enclosing the whole scene is drawn.
+
+If not, but the material properties include a bitmap as a texture, the bitmap is drawn in the 
+background of the scene.  (The bitmap colors modify the general color setting.)
+
+If neither a sphere nor a bitmap background is drawn, the background is filled with a 
+solid color.
+}
+\note{
+The \code{\link{writeWebGL}} function only supports solid color backgrounds.
+}
+\examples{
+  open3d()
+  
+  # a simple white background
+  
+  bg3d("white")
+
+  # the holo-globe (inspired by star trek):
+
+  bg3d(sphere = TRUE, color = c("black", "green"), lit = FALSE, back = "lines" )
+
+  # an environmental sphere with a nice texture.
+
+  bg3d(sphere = TRUE, texture = system.file("textures/sunsleep.png", package = "rgl"), 
+         back = "filled" )
+         
+  # The same texture as a fixed background
+  
+  open3d()
+  bg3d(texture = system.file("textures/sunsleep.png", package = "rgl"), col = "white")
+}
+\seealso{
+  \code{\link{material3d}}, \code{\link{bgplot3d}} to add a 2D plot as background.
+}
+\keyword{dynamic}
diff --git a/man/bgplot3d.Rd b/man/bgplot3d.Rd
new file mode 100644
index 0000000..f81b3c0
--- /dev/null
+++ b/man/bgplot3d.Rd
@@ -0,0 +1,69 @@
+\name{bgplot3d}
+\alias{bgplot3d}
+\alias{legend3d}
+\title{Use base graphics for RGL background}
+\description{
+Add a 2D plot or a legend in the background of an RGL window.
+}
+\usage{
+bgplot3d(expression)
+legend3d(...)
+}
+\arguments{
+  \item{expression}{
+Any plotting commands to produce a plot.
+}
+  \item{...}{
+Arguments to pass to the \code{\link{legend}} function.
+}
+}
+\details{
+The \code{bgplot3d} function opens a \code{\link{png}} device and executes \code{expression},
+producing a plot there.  This plot is then used as a bitmap background for the current
+RGL subscene.
+
+The \code{legend3d} function draws a standard 2D legend to the background of the current
+subscene by calling \code{bgplot3d} to open a device, and setting up a plot region there 
+to fill the whole display.
+}
+\value{
+The \code{bgplot3d} function invisibly returns the ID of the background object that was created,
+with attribute \code{"value"} holding the value returned when the \code{expression} was
+evaluated.
+
+The \code{legend3d} function does similarly.  The \code{"value"} attribute is the result
+of the call to \code{\link{legend}}.   The scaling of the coordinates runs from 0 to 1 
+in X and Y.
+}
+\author{
+Duncan Murdoch
+}
+\note{
+Because the background plots are drawn as bitmaps, they do not resize very gracefully.
+It's best to size your window first, then draw the background at that size.
+}
+
+
+\seealso{
+\code{\link{bg3d}} for other background options.
+}
+\examples{
+x <- rnorm(100)
+y <- rnorm(100)
+z <- rnorm(100)
+open3d()
+# Needs to be a bigger window than the default
+par3d(windowRect = c(100, 100, 612, 612))
+Sys.sleep(0.1) # Allow sluggish window managers to catch up
+parent <- currentSubscene3d()
+mfrow3d(2, 2)
+plot3d(x, y, z)
+next3d(reuse = FALSE)
+bgplot3d(plot(y, z))
+next3d(reuse = FALSE)
+bgplot3d(plot(x, z))
+next3d(reuse = FALSE)
+legend3d("center", c("2D Points", "3D Points"), pch = c(1, 16))
+useSubscene3d(parent)
+}
+\keyword{ graphics }
diff --git a/man/callbacks.Rd b/man/callbacks.Rd
new file mode 100644
index 0000000..8a8e4d5
--- /dev/null
+++ b/man/callbacks.Rd
@@ -0,0 +1,75 @@
+\name{rgl.setMouseCallbacks}
+\alias{rgl.setMouseCallbacks}
+\alias{rgl.getMouseCallbacks}
+\alias{rgl.setWheelCallback}
+\alias{rgl.getWheelCallback}
+\title{ User callbacks on mouse events }
+\description{
+  Set and get user callbacks on mouse events.
+}
+\usage{
+rgl.setMouseCallbacks(button, begin = NULL, update = NULL, end = NULL)
+rgl.getMouseCallbacks(button)
+rgl.setWheelCallback(rotate)
+rgl.getWheelCallback()
+}
+\arguments{
+  \item{button}{ Which button?  }
+  \item{begin}{ Called when mouse down event occurs }
+  \item{update}{ Called when mouse moves }
+  \item{end}{ Called when mouse is released }
+  \item{rotate}{ Called when mouse wheel is rotated }
+}
+\details{
+The set functions set event handlers on mouse events that occur within the current rgl window.
+The \code{begin} and \code{update} events should be functions taking two arguments; these
+will be the mouse coordinates when the event occurs.  The \code{end} event handler
+takes no arguments.  The \code{rotate} event takes a single argument, which will be 
+equal to \code{1} if the user pushes the wheel away by one click, and \code{2} if 
+the user pulls the wheel by one click.
+
+Alternatively, the handlers may be set to \code{NULL}, the default value, in which case
+no action will occur.
+
+If a subscene has multiple listeners, the user action will still only be called for the
+subscene that received the mouse event.  It should consult \code{\link{par3d}("listeners")}
+if it makes sense to take action on the whole group of subscenes.
+
+The get function retrieves the callbacks that are currently set.
+}
+\value{
+The set functions are called for the side effect of setting the mouse event handlers.
+
+The \code{rgl.getMouseCallbacks} function returns a list containing the callback functions or \code{NULL} if no user callback is set.
+The \code{rgl.getWheelCallback} returns the callback function or \code{NULL}.
+}
+\author{ Duncan Murdoch }
+\seealso{ \code{\link{par3d}} to set built-in handlers }
+\examples{
+
+## Not quite right --- this doesn't play well with rescaling
+
+ pan3d <- function(button) {
+   start <- list()
+   
+   begin <- function(x, y) {
+       start$userMatrix <<- par3d("userMatrix")
+       start$viewport <<- par3d("viewport")
+       start$scale <<- par3d("scale")
+       start$projection <<- rgl.projection()
+       start$pos <<- rgl.window2user( x/start$viewport[3], 1 - y/start$viewport[4], 0.5, 
+                                      projection = start$projection)
+   }
+   
+   update <- function(x, y) {
+        xlat <- (rgl.window2user( x/start$viewport[3], 1 - y/start$viewport[4], 0.5,
+                                 projection = start$projection) - start$pos)*start$scale
+        mouseMatrix <- translationMatrix(xlat[1], xlat[2], xlat[3])
+        par3d(userMatrix = start$userMatrix \%*\% t(mouseMatrix) )
+   }
+   rgl.setMouseCallbacks(button, begin, update)
+   cat("Callbacks set on button", button, "of rgl device", rgl.cur(), "\n")
+ }
+ pan3d(3)
+}
+\keyword{ dynamic }
diff --git a/man/check3d.Rd b/man/check3d.Rd
new file mode 100644
index 0000000..04bf9d4
--- /dev/null
+++ b/man/check3d.Rd
@@ -0,0 +1,21 @@
+\name{.check3d}
+\alias{.check3d}
+\title{
+Check for an open rgl window.
+}
+\description{
+Mostly for internal use, this function returns the current device
+number if one exists, or opens a new device and returns that.
+}
+\usage{
+.check3d()
+}
+\value{
+The device number of an rgl device.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{open3d}}
+}
diff --git a/man/cylinder3d.Rd b/man/cylinder3d.Rd
new file mode 100644
index 0000000..f4c030b
--- /dev/null
+++ b/man/cylinder3d.Rd
@@ -0,0 +1,90 @@
+\name{cylinder3d}
+\alias{cylinder3d}
+\title{
+Create cylindrical or "tube" plots.
+}
+\description{
+This function converts a description of a space curve into a \code{\link[=mesh3d]{"mesh3d"}}
+object forming a cylindrical tube around the curve.
+}
+\usage{
+cylinder3d(center, radius = 1, twist = 0, e1 = NULL, e2 = NULL, e3 = NULL, 
+	sides = 8, section = NULL, closed = 0, debug = FALSE, keepVars = FALSE)
+}
+\arguments{
+  \item{center}{An n by 3 matrix whose columns are the x, y and z coordinates of the space curve.}
+  \item{radius}{The radius of the cross-section of the tube at each point in the center.}
+  \item{twist}{The amount by which the polygon forming the tube is twisted at each point.}
+  \item{e1, e2, e3}{The Frenet coordinates to use at each point on the space curve.}
+  \item{sides}{The number of sides in the polygon cross section.}
+  \item{section}{The polygon cross section as a two-column matrix, or \code{NULL}.}  
+  \item{closed}{Whether to treat the first and last points of the space curve as identical,
+  and close the curve, or put caps on the ends.  See the Details.}
+  \item{debug}{If \code{TRUE}, plot the local Frenet coordinates at each point.}
+  \item{keepVars}{If \code{TRUE}, return the local variables in attribute \code{"vars"}.}
+}
+\details{
+
+The number of points in the space curve is determined by the vector lengths in \code{center},
+after using \code{\link{xyz.coords}} to convert it to a list.  The other arguments
+\code{radius}, \code{twist}, \code{e1}, \code{e2}, and \code{e3} are extended to the same
+length.
+
+The \code{closed} argument controls how the ends of the cylinder are
+handled. If \code{closed > 0}, it represents the number of points of
+overlap in the coordinates.  \code{closed == TRUE} is the same as 
+\code{closed = 1}. Negative values indicate that caps should be put on the
+ends of the cylinder.  If \code{closed == -1}, a cap will be put on the
+end corresponding to \code{center[1, ]}.  If \code{closed == -2}, caps
+will be put on both ends.
+
+If \code{section} is \code{NULL} (the default), a regular
+\code{sides}-sided polygon is used, and \code{radius} measures the
+distance from the center of the cylinder to each vertex.  If not
+\code{NULL}, \code{sides} is ignored (and set internally to
+\code{nrow(section)}), and \code{radius} is used as a multiplier to
+the vertex coordinates.  \code{twist} specifies the rotation of the
+polygon.  Both \code{radius} and \code{twist} may be vectors, with
+values recycled to the number of rows in \code{center}, while
+\code{sides} and \code{section} are the same at every point along the
+curve.
+
+The three optional arguments \code{e1}, \code{e2}, and \code{e3}
+determine the local coordinate system used to create the vertices at
+each point in \code{center}.  If missing, they are computed by simple
+numerical approximations.  \code{e1} should be the tangent coordinate,
+giving the direction of the curve at the point.  The cross-section of
+the polygon will be orthogonal to \code{e1}.  \code{e2} defaults to an
+approximation to the normal or curvature vector; it is used as the
+image of the \code{y} axis of the polygon cross-section.  \code{e3}
+defaults to an approximation to the binormal vector, to which the
+\code{x} axis of the polygon maps.  The vectors are orthogonalized and
+normalized at each point.
+}
+\value{
+A \code{\link[=mesh3d]{"mesh3d"}} object holding the cylinder, possibly with
+attribute \code{"vars"} containing the local environment of the function.
+}
+\author{
+Duncan Murdoch
+}
+\examples{
+# A trefoil knot
+open3d()
+theta <- seq(0, 2*pi, len = 25)
+knot <- cylinder3d(
+      center = cbind(
+        sin(theta) + 2*sin(2*theta), 
+        2*sin(3*theta), 
+        cos(theta) - 2*cos(2*theta)),
+      e1 = cbind(
+        cos(theta) + 4*cos(2*theta), 
+        6*cos(3*theta), 
+        sin(theta) + 4*sin(2*theta)),
+      radius = 0.8, 
+      closed = TRUE)
+                     
+shade3d(addNormals(subdivision3d(knot, depth = 2)), col = "green")  
+}
+
+\keyword{ dynamic }
diff --git a/man/ellipse3d.Rd b/man/ellipse3d.Rd
new file mode 100644
index 0000000..687f382
--- /dev/null
+++ b/man/ellipse3d.Rd
@@ -0,0 +1,99 @@
+\name{ellipse3d}
+\alias{ellipse3d}
+\alias{ellipse3d.default}
+\alias{ellipse3d.lm}
+\alias{ellipse3d.glm}
+\alias{ellipse3d.nls}
+\title{
+Make an ellipsoid
+}
+\description{
+A generic function and several methods
+returning an ellipsoid or other outline of a confidence region
+for three parameters.  
+}
+\usage{
+ellipse3d(x, \dots)
+\method{ellipse3d}{default}(x, scale = c(1, 1, 1), centre = c(0, 0, 0), level = 0.95, 
+	t = sqrt(qchisq(level, 3)), which = 1:3, subdivide = 3, smooth = TRUE, ...)
+\method{ellipse3d}{lm}(x, which = 1:3, level = 0.95, t = sqrt(3 * qf(level, 
+                                                3, x$df.residual)), ...)     
+\method{ellipse3d}{glm}(x, which = 1:3, level = 0.95, t, dispersion, ...) 
+\method{ellipse3d}{nls}(x, which = 1:3, level = 0.95, t = sqrt(3 * qf(level, 
+                                                3, s$df[2])), ...) 
+}
+\arguments{
+\item{x}{
+An object. In the default method the parameter \code{x} should be a 
+square positive definite matrix at least 3x3
+in size. It will be treated as the correlation or covariance 
+of a multivariate normal distribution.
+}
+\item{\dots}{
+Additional parameters to pass to the default method or to \code{\link{qmesh3d}}.
+}
+\item{scale}{
+If \code{x} is a correlation matrix, then the standard deviations of each
+parameter can be given in the scale parameter.  This defaults to \code{c(1, 1, 1)},
+so no rescaling will be done.
+}
+\item{centre}{
+The centre of the ellipse will be at this position.
+}
+\item{level}{
+The confidence level of a simultaneous confidence region.  The default is
+0.95, for a 95\% region.  This is used to control the size of the ellipsoid.
+}
+\item{t}{
+The size of the ellipse may also be controlled by specifying the value
+of a t-statistic on its boundary.  This defaults to the appropriate
+value for the confidence region.
+}
+\item{which}{
+This parameter selects which variables from the object will be
+plotted.  The default is the first 3.
+}
+\item{subdivide}{
+This controls the number of subdivisions (see \code{\link{subdivision3d}})
+used in constructing the ellipsoid.  Higher numbers give a smoother shape.
+}
+\item{smooth}{
+If \code{TRUE}, smooth interpolation of normals is used; if \code{FALSE}, 
+a faceted ellipsoid will be displayed.
+}
+\item{dispersion}{
+The value of dispersion to use.  If specified, it is treated as fixed,
+and chi-square limits for \code{t} are used. If missing, it is 
+taken from \code{summary(x)}.
+}
+}
+\value{
+A \code{\link{mesh3d}} object representing the ellipsoid.
+}
+\examples{
+# Plot a random sample and an ellipsoid of concentration corresponding to a 95\% 
+# probability region for a
+# trivariate normal distribution with mean 0, unit variances and 
+# correlation 0.8.
+if (requireNamespace("MASS")) {
+  Sigma <- matrix(c(10, 3, 0, 3, 2, 0, 0, 0, 1), 3, 3)
+  Mean <- 1:3
+  x <- MASS::mvrnorm(1000, Mean, Sigma)
+  
+  open3d()
+  
+  plot3d(x, box = FALSE)
+  
+  plot3d( ellipse3d(Sigma, centre = Mean), col = "green", alpha = 0.5, add = TRUE)
+}  
+
+# Plot the estimate and joint 90\% confidence region for the displacement and cylinder
+# count linear coefficients in the mtcars dataset
+
+data(mtcars)
+fit <- lm(mpg ~ disp + cyl , mtcars)
+
+open3d()
+plot3d(ellipse3d(fit, level = 0.90), col = "blue", alpha = 0.5, aspect = TRUE)
+}
+\keyword{dplot}
diff --git a/man/extrude3d.Rd b/man/extrude3d.Rd
new file mode 100644
index 0000000..7eecf10
--- /dev/null
+++ b/man/extrude3d.Rd
@@ -0,0 +1,56 @@
+\name{extrude3d}
+\alias{extrude3d}
+\title{
+Generate extrusion mesh
+}
+\description{
+Given a two-dimensional polygon, this generates a three-dimensional extrusion
+of the shape by triangulating the polygon and creating a cylinder with
+that shape as the end faces.
+}
+\usage{
+extrude3d(x, y = NULL, thickness = 1, smooth = FALSE, ...)
+}
+\arguments{
+  \item{x, y}{
+A polygon description in one of the forms supported by \code{\link{triangulate}}.
+}
+  \item{thickness}{
+The extrusion will have this thickness.
+}
+  \item{smooth}{
+logical; should normals be added so that the edges of the extrusion appear
+smooth?
+}
+  \item{\dots}{
+Other parameters to pass to \code{\link{tmesh3d}} when constructing the
+mesh.
+}
+}
+\details{
+The extrusion is always constructed with the polygon in the xy plane at
+\code{z = 0} and another copy at \code{z = thickness}.  Use
+the transformation functions (e.g. \code{\link{rotate3d}}) to 
+obtain other orientations and placements.
+}
+\value{
+A mesh object containing a triangulation of the polygon
+for each face, and quadrilaterals for the sides.
+}
+\author{
+Duncan Murdoch
+}
+
+\seealso{
+\code{\link{polygon3d}} for a simple polygon, \code{\link{triangulate}} for
+the triangulation, \code{\link{turn3d}} for a solid of rotation.
+}
+\examples{
+x <- c(1:10, 10:1)
+y <- rev(c(rep(c(0, 2), 5), rep(c(1.5, -0.5), 5)))
+plot(x, y, type = "n")
+polygon(x, y)
+open3d()
+shade3d( extrude3d(x, y), col = "red" )
+}
+\keyword{ graphics }
diff --git a/man/grid3d.Rd b/man/grid3d.Rd
new file mode 100644
index 0000000..f0b36cc
--- /dev/null
+++ b/man/grid3d.Rd
@@ -0,0 +1,61 @@
+\name{grid3d}
+\alias{grid3d}
+\title{Add a grid to a 3D plot }
+\description{
+This function adds a reference grid to an RGL plot.
+}
+\usage{
+grid3d(side, at = NULL, col = "gray", lwd = 1, lty = 1, n = 5)
+}
+\arguments{
+  \item{side}{ Where to put the grid; see the Details section. }
+  \item{at}{ How to draw the grid; see the Details section. }
+  \item{col}{ The color of the grid lines. }
+  \item{lwd}{ The line width of the grid lines. (Currently only
+  \code{lty = 1} is supported.)}
+  \item{lty}{ The line type of the grid lines. }
+  \item{n}{ Suggested number of grid lines; see the Details section. }
+}
+\details{
+This function is similar to \code{\link{grid}} in classic graphics,
+except that it draws a 3D grid in the plot.
+
+The grid is drawn in a plane perpendicular to the coordinate axes. The
+first letter of the \code{side} argument specifies the direction of
+the plane: \code{"x"}, \code{"y"} or \code{"z"} (or uppercase
+versions) to specify the coordinate which is constant on the plane.
+
+If \code{at = NULL} (the default), the grid is drawn at the limit of 
+the box around the data.  If the second letter of the \code{side} argument
+is \code{"-"} or is not present, it is the lower limit; if \code{"+"}
+then at the upper limit.  The grid lines are drawn at values
+chosen by \code{\link{pretty}} with \code{n} suggested locations.
+The default locations should match those chosen by \code{\link{axis3d}}
+with \code{nticks = n}.
+
+If \code{at} is a numeric vector, the grid lines are drawn at those values.
+
+If \code{at} is a list, then the \code{"x"} component is used to
+specify the x location, the \code{"y"} component specifies the y location, and
+the \code{"z"} component specifies the z location.  Missing components
+are handled using the default as for \code{at = NULL}.
+
+Multiple grids may be drawn by specifying multiple values for \code{side}
+or for the component of \code{at} that specifies the grid location.
+}
+\note{
+If the scene is resized, the grid will not be resized; use \code{\link{abclines3d}}
+to draw grid lines that will automatically resize.
+}
+\value{ A vector or matrix of object ids is returned invisibly. }
+\author{ Ben Bolker and Duncan Murdoch }
+\seealso{ \code{\link{axis3d}} }
+\examples{
+x <- 1:10
+y <- 1:10
+z <- matrix(outer(x - 5, y - 5) + rnorm(100), 10, 10)
+open3d()
+persp3d(x, y, z, col = "red", alpha = 0.7, aspect = c(1, 1, 0.5))
+grid3d(c("x", "y+", "z"))
+}
+\keyword{ dynamic }
diff --git a/man/hook_rgl.Rd b/man/hook_rgl.Rd
new file mode 100644
index 0000000..0ff373e
--- /dev/null
+++ b/man/hook_rgl.Rd
@@ -0,0 +1,58 @@
+\name{hook_rgl}
+\alias{hook_rgl}
+\alias{hook_webgl}
+\alias{setupKnitr}
+\title{
+Hook functions to use with \pkg{knitr}
+}
+\description{
+These functions allow \pkg{rgl} graphics to be embedded in \pkg{knitr}
+documents, either as bitmaps (\code{hook_rgl} with format \code{"png"}),
+fixed vector graphics (\code{hook_rgl} with format \code{"eps"}, \code{"pdf"} or
+\code{"postscript"}), or interactive WebGL graphics (\code{hook_webgl}).
+}
+\usage{
+setupKnitr()
+hook_rgl(before, options, envir)
+hook_webgl(before, options, envir)
+}
+\arguments{
+  \item{before, options, envir}{
+Standard \pkg{knitr} hook function arguments.
+}
+}
+\details{
+The \code{setupKnitr()} function needs to be called once
+at the start of the document to install the \pkg{knitr} hooks
+and to initialize \code{hook_webgl}.
+
+The following chunk options are supported:
+\itemize{
+  \item \code{rgl.keepopen}:  no longer used.  Ignored
+  with a warning.
+  
+  \item \code{rgl.newwindow} (default \code{FALSE}):  Whether to open a new window for the display.
+  
+  \item \code{rgl.margin} (default 100):  number of pixels by which to indent the
+  WebGL window.
+  
+  \item \code{dpi}, \code{fig.retina}, \code{fig.width}, \code{fig.height}:  standard \pkg{knitr} chunk
+  options used to set the size of the output.
+  
+  \item \code{dev}:  used by \code{hook_rgl} to set 
+  the output format.  May be \code{"eps"}, \code{"postscript"},
+  \code{"pdf"} or \code{"png"} (default:  \code{"png"}).
+}
+}
+\value{
+A string to be embedded into the output, or \code{NULL} if called
+when no output is available.
+}
+\author{
+Originally by Yihui Xie in the \pkg{knitr} package; modified by
+Duncan Murdoch.
+}
+\seealso{
+\code{\link{rgl.Sweave}} embeds fixed images in Sweave documents.
+}
+\keyword{ utilities }
diff --git a/man/identify3d.Rd b/man/identify3d.Rd
new file mode 100644
index 0000000..6dd5ea5
--- /dev/null
+++ b/man/identify3d.Rd
@@ -0,0 +1,46 @@
+\name{identify3d}
+\alias{identify3d}
+\title{
+Identify points in plot.
+}
+\description{
+Identify points in a plot, similarly to the \code{\link{identify}} function
+in base graphics.
+}
+\usage{
+identify3d(x, y = NULL, z = NULL, labels = seq_along(x), n = length(x), 
+	plot = TRUE, adj = c(-0.1, 0.5), tolerance = 20, 
+	buttons = c("right", "middle"))
+}
+\arguments{
+  \item{x, y, z}{coordinates of points in a scatter plot.  Alternatively, any
+    object which defines coordinates (see \code{\link{xyz.coords}}) 
+    can be given as \code{x}, and \code{y} and \code{z} left missing.}
+  \item{labels}{an optional character vector giving labels for the
+    points.  Will be coerced using \code{\link{as.character}}, and
+    recycled if necessary to the length of \code{x}.}
+  \item{n}{the maximum number of points to be identified.}
+  \item{plot}{logical: if \code{plot} is \code{TRUE}, the labels are
+    printed near the points and if \code{FALSE} they are omitted.}
+  \item{adj}{numeric vector to use as \code{adj} parameter to 
+    \code{\link{text3d}} when plotting the labels.}
+  \item{tolerance}{the maximal distance (in pixels) 
+    for the pointer to be \sQuote{close enough} to a point.}
+  \item{buttons}{a length 1 or 2 character vector giving the buttons
+    to use for selection and quitting.}
+}
+\details{
+If \code{buttons} is length 1, the user can quit by reaching \code{n}
+selections, or by hitting the 
+escape key, but the result will be lost if escape is used.
+}
+\value{
+A vector of selected indices.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{identify}} for base graphics, \code{\link{select3d}} for selecting regions.
+}
+\keyword{ graphics }
diff --git a/man/light.Rd b/man/light.Rd
new file mode 100644
index 0000000..b6bbd8a
--- /dev/null
+++ b/man/light.Rd
@@ -0,0 +1,74 @@
+\name{light}
+\alias{rgl.light}
+\alias{light3d}
+\title{add light source}
+\description{
+  add a light source to the scene.
+}
+\usage{
+light3d(theta = 0, phi = 15, x = NULL, ...)
+rgl.light( theta = 0, phi = 0, viewpoint.rel = TRUE, ambient = "#FFFFFF", 
+           diffuse = "#FFFFFF", specular = "#FFFFFF", x = NULL, y = NULL, z = NULL)
+}
+\arguments{
+  \item{theta, phi}{polar coordinates, used by default}
+  \item{viewpoint.rel}{logical, if TRUE light is a viewpoint light that is positioned relative to the current viewpoint}
+  \item{ambient, diffuse, specular }{ light color values used for lighting calculation }
+  \item{x, y, z}{cartesian coordinates, optional}
+  \item{...}{generic arguments passed through to RGL-specific (or other) functions}
+}
+\details{
+  Up to 8 light sources are supported. They are positioned either in
+  world space or relative to the camera. By providing polar
+  coordinates to theta and phi a directional light source is used. If
+  numerical values are given to x, y and z, a point-like light source with
+  finite distance to the objects in the scene is set up.
+  
+  If \code{x} is non-null, \code{\link{xyz.coords}} will
+  be used to form the location values, so all three coordinates
+  can be specified in \code{x}.
+}
+\value{
+  This function is called for the side effect of adding a light.  A light ID is
+  returned to allow \code{\link{rgl.pop}} to remove it.
+}
+\seealso{
+  \code{\link{rgl.clear}}
+  \code{\link{rgl.pop}}
+}
+\examples{
+
+#
+# a lightsource moving through the scene
+#
+data(volcano)
+z <- 2 * volcano # Exaggerate the relief
+x <- 10 * (1:nrow(z)) # 10 meter spacing (S to N)
+y <- 10 * (1:ncol(z)) # 10 meter spacing (E to W)
+zlim <- range(z)
+zlen <- zlim[2] - zlim[1] + 1
+colorlut <- terrain.colors(zlen) # height color lookup table
+col <- colorlut[ z - zlim[1] + 1 ] # assign colors to heights for each point
+
+open3d()
+bg3d("gray50")
+surface3d(x, y, z, color = col, back = "lines")
+r <- max(y) - mean(y)
+lightid <- spheres3d(1, 1, 1, alpha = 0)
+frame <- function(time) {
+    a <- pi*(time - 1)
+    save <- par3d(skipRedraw = TRUE)
+    clear3d(type = "lights")
+    rgl.pop(id = lightid)
+    xyz <- matrix(c(r*sin(a) + mean(x), r*cos(a) + mean(y), max(z)), ncol = 3)
+    light3d(x = xyz, diffuse = "gray75", 
+            specular = "gray75", viewpoint.rel = FALSE) 
+    light3d(diffuse = "gray10", specular = "gray25")
+    lightid <<- spheres3d(xyz, emission = "white", radius = 4)
+    par3d(save)
+    Sys.sleep(0.02)
+    NULL
+}
+play3d(frame, duration = 2)
+}
+\keyword{dynamic}
diff --git a/man/material.Rd b/man/material.Rd
new file mode 100644
index 0000000..8e0f86d
--- /dev/null
+++ b/man/material.Rd
@@ -0,0 +1,174 @@
+\name{rgl.material}
+\alias{rgl.material}
+\alias{material3d}
+\title{Generic Appearance setup}
+\description{
+  Set material properties for geometry appearance.
+}
+\usage{
+rgl.material(
+  color        = c("white"),
+  alpha        = c(1.0),
+  lit          = TRUE, 
+  ambient      = "black",
+  specular     = "white", 
+  emission     = "black", 
+  shininess    = 50.0, 
+  smooth       = TRUE,
+  texture      = NULL, 
+  textype      = "rgb", 
+  texmipmap    = FALSE, 
+  texminfilter = "linear", 
+  texmagfilter = "linear",
+  texenvmap    = FALSE,
+  front        = "fill", 
+  back         = "fill",
+  size         = 3.0, 
+  lwd          = 1.0,
+  fog          = TRUE,
+  point_antialias = FALSE,
+  line_antialias = FALSE,
+  depth_mask   = TRUE,
+  depth_test   = "less",
+  ...
+)
+material3d(...)
+}
+\arguments{
+  \item{color}{
+    vector of R color characters. Represents the diffuse component in case of lighting calculation (lit = TRUE),
+    otherwise it describes the solid color characteristics.
+  }
+  \item{lit}{
+    logical, specifying if lighting calculation should take place on geometry
+  }
+  \item{ambient, specular, emission, shininess}{
+    properties for lighting calculation. ambient, specular, emission are R color character string values; shininess represents a
+    numerical.
+  }
+  \item{alpha}{ 
+    vector of alpha values between 0.0 (fully transparent) .. 1.0 (opaque).
+  }
+  \item{smooth}{
+    logical, specifying whether Gouraud shading (smooth) or flat shading should be used.
+  }
+  \item{texture}{ 
+    path to a texture image file. Supported formats: png.
+  }
+  \item{textype}{
+    specifies what is defined with the pixmap
+    \describe{
+      \item{"alpha"}{alpha values}
+      \item{"luminance"}{luminance}
+      \item{"luminance.alpha"}{luminance and alpha}
+      \item{"rgb"}{color}
+      \item{"rgba"}{color and alpha texture}
+    }
+  }
+  \item{texmipmap}{
+    Logical, specifies if the texture should be mipmapped.
+  }
+  \item{texmagfilter}{
+    specifies the magnification filtering type (sorted by ascending quality):
+    \describe{
+      \item{"nearest"}{texel nearest to the center of the pixel}
+      \item{"linear"}{weighted linear average of a 2x2 array of texels}
+    }
+  }
+  \item{texminfilter}{
+    specifies the minification filtering type (sorted by ascending quality):
+    \describe{
+      \item{"nearest"}{texel nearest to the center of the pixel}
+      \item{"linear"}{weighted linear average of a 2x2 array of texels}
+      \item{"nearest.mipmap.nearest"}{low quality mipmapping}
+      \item{"nearest.mipmap.linear"}{medium quality mipmapping}
+      \item{"linear.mipmap.nearest"}{medium quality mipmapping}
+      \item{"linear.mipmap.linear"}{high quality mipmapping}
+    }
+  }
+  \item{texenvmap}{
+    logical, specifies if auto-generated texture coordinates for environment-mapping 
+    should be performed on geometry.
+  }
+  \item{front, back}{
+    Determines the polygon mode for the specified side:
+    \describe{
+      \item{"fill"}{filled polygon}
+      \item{"line"}{wireframed polygon}
+      \item{"points"}{point polygon}
+      \item{"cull"}{culled (hidden) polygon}
+    }
+  }
+  \item{size}{ 
+    numeric, specifying the size of points in pixels
+  }
+  \item{lwd}{
+    numeric, specifying the line width in pixels
+  }
+  \item{fog}{logical, specifying if fog effect should be applied on the corresponding shape}
+  \item{point_antialias, line_antialias}{logical, specifying if points and lines 
+     should be antialiased}
+  \item{depth_mask}{logical, specifying whether the object's depth
+     should be stored.}
+  \item{depth_test}{Determines which depth test is used to see if this
+     object is visible, depending on its apparent depth in the scene
+     compared to the stored depth. Possible values are \code{"never"},
+     \code{"less"} (the default), \code{"equal"}, \code{"lequal"}
+     (less than or equal), \code{"greater"}, \code{"notequal"},
+     \code{"gequal"} (greater than or equal), \code{"always"}.}
+  \item{...}{Any of the arguments above; see Details below.}
+}
+\details{
+  Only one side at a time can be culled.
+  
+  \code{material3d} is an alternate interface to the material properties, modelled after
+\code{\link{par3d}}:  rather than setting defaults for parameters that are not specified, 
+they will be left unchanged.  \code{material3d} may also be used to query the material
+properties; see the examples below.
+
+  The current implementation does not return parameters for textures.
+  
+  If \code{point_antialias} is \code{TRUE}, points will be drawn as circles; otherwise, they
+will be drawn as squares.  Lines tend to appear heavier with \code{line_antialias == TRUE}.
+
+  The \code{material} member of the \code{\link{r3dDefaults}} list may be used to 
+set default values for material properties.
+  
+  The \code{...} parameter to \code{rgl.material} is ignored.
+}
+\value{
+\code{rgl.material()} is called for the side effect of setting the material properties.
+It returns a value invisibly which is not intended for use by the user.
+
+Users should use \code{material3d()} to query material properties.  It returns values similarly
+to \code{\link{par3d}} as follows:
+When setting properties, it returns the previous values in a named list.  A named list is also
+returned when more than one value is queried.  When a single value is queried it is returned 
+directly.
+} 
+\seealso{
+\code{\link{rgl.primitive}},
+\code{\link{rgl.bbox}},
+\code{\link{rgl.bg}},
+\code{\link{rgl.light}}
+}
+\examples{
+save <- material3d("color")
+material3d(color = "red")
+material3d("color")
+material3d(color = save)
+
+# this illustrates the effect of depth_test
+x <- c(1:3); xmid <- mean(x)
+y <- c(2, 1, 3); ymid <- mean(y)
+z <- 1
+open3d()
+tests <- c("never", "less", "equal", "lequal", "greater", 
+                  "notequal", "gequal", "always")
+for (i in 1:8) {
+  triangles3d(x, y, z + i, col = heat.colors(8)[i])
+  texts3d(xmid, ymid, z + i, paste(i, tests[i], sep = ". "), depth_test = tests[i]) 
+}
+}
+\keyword{dynamic}
+
diff --git a/man/matrices.Rd b/man/matrices.Rd
new file mode 100644
index 0000000..d94c46d
--- /dev/null
+++ b/man/matrices.Rd
@@ -0,0 +1,110 @@
+\name{matrices}
+\alias{matrices}
+\alias{identityMatrix}
+\alias{scaleMatrix}
+\alias{translationMatrix}
+\alias{rotationMatrix}
+\alias{scale3d}
+\alias{translate3d}
+\alias{rotate3d}
+\alias{transform3d}
+\alias{asHomogeneous}
+\alias{asEuclidean}
+\title{Work with homogeneous coordinates }
+\description{
+These functions construct 4x4 matrices for transformations
+in the homogeneous coordinate system used by OpenGL, and translate
+vectors between homogeneous and Euclidean coordinates.
+}
+\usage{
+identityMatrix()
+scaleMatrix(x, y, z)
+translationMatrix(x, y, z)
+rotationMatrix(angle, x, y, z, matrix)
+asHomogeneous(x)
+asEuclidean(x)
+
+scale3d(obj, x, y, z, ...)
+translate3d(obj, x, y, z, ...)
+rotate3d(obj, angle, x, y, z, matrix, ...)
+
+transform3d(obj, matrix, ...)
+
+}
+\arguments{
+  \item{x, y, z, angle, matrix}{See details} 
+  \item{obj}{An object to be transformed}
+  \item{...}{Additional parameters to be passed to methods}
+}
+\details{
+OpenGL uses homogeneous coordinates to handle perspective and affine
+transformations.  The homogeneous point \code{(x, y, z, w)} corresponds
+to the Euclidean point \code{(x/w, y/w, z/w)}.  The matrices produced by
+the functions \code{scaleMatrix}, \code{translationMatrix}, and \code{rotationMatrix}
+are to be left-multiplied by a row vector 
+of homogeneous coordinates; alternatively, the transpose of the result
+can be right-multiplied by a column vector.  The generic functions
+\code{scale3d}, \code{translate3d} and \code{rotate3d} apply these transformations
+to the \code{obj} argument.  The \code{transform3d} function is a synonym 
+for \code{rotate3d(obj, matrix = matrix)}.
+
+By default, it is assumed that \code{obj} is a row vector
+(or a matrix of row vectors) which will be multiplied on the right by
+the corresponding matrix, but users may write methods for these generics
+which operate differently.  Methods are supplied for \code{\link{mesh3d}}
+objects.
+
+To compose transformations, use matrix multiplication.  The effect is
+to apply the matrix on the left first, followed by the one on the right.
+
+\code{identityMatrix} returns an identity matrix.
+
+\code{scaleMatrix} scales each coordinate by the given factor.  In Euclidean
+coordinates, \code{(u, v, w)} is transformed to \code{(x*u, y*v, z*w)}.
+
+\code{translationMatrix} translates each coordinate by the given translation, i.e.
+\code{(u, v, w)} is transformed to \code{(u + x, v + y, w + z)}.
+
+\code{rotationMatrix} can be called in three ways.  With 
+arguments \code{angle, x, y, z} it represents a rotation 
+of \code{angle} radians about the axis 
+\code{x, y, z}.  If \code{matrix} is a 3x3 rotation matrix,
+it will be converted into the corresponding matrix in 4x4 homogeneous
+coordinates.  Finally, if a 4x4 matrix is given, it will be returned unchanged.
+(The latter behaviour is used to allow \code{transform3d} to act like a 
+generic function, even though it is not.)
+
+Use \code{asHomogeneous(x)} to convert the Euclidean vector \code{x} to
+homogeneous coordinates, and \code{asEuclidean(x)} for the reverse transformation.
+
+}
+\value{
+\code{identityMatrix},
+\code{scaleMatrix}, \code{translationMatrix}, and \code{rotationMatrix} produce
+a 4x4 matrix representing the requested transformation
+in homogeneous coordinates.  
+
+\code{scale3d}, \code{translate3d} and \code{rotate3d} transform the object
+and produce a new object of the same class.
+}
+\author{ Duncan Murdoch }
+\seealso{\code{\link{par3d}} for a description of how rgl uses matrices in
+rendering.}
+
+\examples{
+# A 90 degree rotation about the x axis:
+
+rotationMatrix(pi/2, 1, 0, 0)
+
+# Find what happens when you rotate (2, 0, 0) by 45 degrees about the y axis:
+
+x <- asHomogeneous(c(2, 0, 0))
+y <- x %*% rotationMatrix(pi/4, 0, 1, 0)
+asEuclidean(y)
+
+# or more simply...
+
+rotate3d(c(2, 0, 0), pi/4, 0, 1, 0)
+
+}
+\keyword{ dynamic }
diff --git a/man/mesh3d.Rd b/man/mesh3d.Rd
new file mode 100644
index 0000000..70e34cd
--- /dev/null
+++ b/man/mesh3d.Rd
@@ -0,0 +1,133 @@
+\name{mesh3d}
+\alias{shape3d}
+\alias{mesh3d}
+\alias{qmesh3d}
+\alias{tmesh3d}
+\alias{dot3d}
+\alias{dot3d.qmesh3d} % for back compatibility
+\alias{dot3d.mesh3d}
+\alias{wire3d}
+\alias{wire3d.qmesh3d} % for back compatibility
+\alias{wire3d.mesh3d}
+\alias{shade3d}
+\alias{shade3d.qmesh3d} % for back compatibility
+\alias{shade3d.mesh3d}
+\alias{cube3d}
+\alias{oh3d}
+\alias{tetrahedron3d}
+\alias{octahedron3d}
+\alias{icosahedron3d}
+\alias{dodecahedron3d}
+\alias{cuboctahedron3d}
+
+\title{3D Mesh objects}
+\description{
+  3D triangle and quadrangle mesh object creation and a collection of sample objects.
+}
+\usage{
+  qmesh3d(vertices, indices, homogeneous = TRUE, material = NULL, 
+         normals = NULL, texcoords = NULL)
+  tmesh3d(vertices, indices, homogeneous = TRUE, material = NULL, 
+         normals = NULL, texcoords = NULL)
+  
+  cube3d(trans = identityMatrix(), ...)  
+  tetrahedron3d(trans = identityMatrix(), ...)  
+  octahedron3d(trans = identityMatrix(), ...)  
+  icosahedron3d(trans = identityMatrix(), ...)
+  dodecahedron3d(trans = identityMatrix(), ...)
+  cuboctahedron3d(trans = identityMatrix(), ...)
+  
+  oh3d(trans = identityMatrix(), ...)    # an 'o' object
+  
+  dot3d(x, ...)   # draw dots at the vertices of an object
+  \method{dot3d}{mesh3d}(x, override = TRUE, ...)
+  wire3d(x, ...)  # draw a wireframe object
+  \method{wire3d}{mesh3d}(x, override = TRUE, ...)
+  shade3d(x, ...) # draw a shaded object
+  \method{shade3d}{mesh3d}(x, override = TRUE, ...)
+}
+\arguments{
+  \item{x}{a \code{mesh3d} object (class \code{qmesh3d} or \code{tmesh3d})}
+  \item{vertices}{3- or 4-component vector of coordinates}
+  \item{indices}{4-component vector of vertex indices}
+  \item{homogeneous}{logical indicating if homogeneous (four component) coordinates are used.}
+  \item{material}{material properties for later rendering}
+  \item{normals}{normals at each vertex}
+  \item{texcoords}{texture coordinates at each vertex}
+  \item{trans}{transformation to apply to objects; see below for defaults}
+  \item{...}{additional rendering parameters}
+  \item{override}{should the parameters specified here override those stored in the object?}
+}
+\details{
+  These functions create and work with \code{mesh3d} objects, which consist of a matrix
+  of vertex coordinates together with a matrix of indices indicating which vertex is
+  part of which face.  Such objects may have  triangular faces,
+  planar quadrilateral faces, or both.
+  
+  The sample objects optionally take a matrix transformation \code{trans} as 
+  an argument.  This transformation is applied to all vertices of the default shape.
+  The default is an identity transformation. 
+  
+  The \code{"shape3d"} class is a general class for shapes that can be plotted
+  by \code{dot3d}, \code{wire3d} or \code{shade3d}.
+  
+  The \code{"mesh3d"} class is a class of objects that form meshes: the vertices
+  are in member \code{vb}, as a 3 or 4 by \code{n} matrix.  Meshes with triangular
+  faces will contain \code{it}, a \code{3 * n} matrix giving the indices of the 
+  vertices in each face.  Quad meshes will have vertex indices in \code{ib},
+  a \code{4 * n} matrix.
+}
+\value{
+
+  \code{qmesh3d}, \code{cube3d}, \code{oh3d}, \code{tmesh3d},
+  \code{tetrahedron3d}, \code{octahedron3d}, \code{icosahedron3d} and
+  \code{dodecahedron3d} return objects of class \code{c("mesh3d",
+  "shape3d")}.  The first three of these are quad meshes, the rest are
+  triangle meshes.
+  
+  \code{dot3d}, \code{wire3d}, and \code{shade3d} are called for their side effect
+  of drawing an object into the scene; they return an object ID (or vector of IDs, for some 
+  classes) invisibly.
+  
+  See \code{\link{rgl.primitive}} for a discussion of texture coordinates.
+}
+\examples{
+
+  # generate a quad mesh object
+
+  vertices <- c( 
+     -1.0, -1.0, 0, 1.0,
+      1.0, -1.0, 0, 1.0,
+      1.0,  1.0, 0, 1.0,
+     -1.0,  1.0, 0, 1.0
+  )
+  indices <- c( 1, 2, 3, 4 )
+  
+  open3d()  
+  wire3d( qmesh3d(vertices, indices) )
+  
+  # render 4 meshes vertically in the current view
+
+  open3d()  
+  bg3d("gray")
+  l0 <- oh3d(tran = par3d("userMatrix"), color = "green" )
+  shade3d( translate3d( l0, -6, 0, 0 ))
+  l1 <- subdivision3d( l0 )
+  shade3d( translate3d( l1 , -2, 0, 0 ), color = "red", override = FALSE )
+  l2 <- subdivision3d( l1 )
+  shade3d( translate3d( l2 , 2, 0, 0 ), color = "red", override = TRUE )
+  l3 <- subdivision3d( l2 )
+  shade3d( translate3d( l3 , 6, 0, 0 ), color = "red" )
+  
+  # render all of the Platonic solids
+  open3d()
+  shade3d( translate3d( tetrahedron3d(col = "red"), 0, 0, 0) )
+  shade3d( translate3d( cube3d(col = "green"), 3, 0, 0) )
+  shade3d( translate3d( octahedron3d(col = "blue"), 6, 0, 0) )
+  shade3d( translate3d( dodecahedron3d(col = "cyan"), 9, 0, 0) )
+  shade3d( translate3d( icosahedron3d(col = "magenta"), 12, 0, 0) )
+}
+\seealso{
+  \code{\link{r3d}}, \code{\link{par3d}}, \code{\link{shapelist3d}} for multiple shapes
+}
+\keyword{dynamic}
diff --git a/man/mfrow3d.Rd b/man/mfrow3d.Rd
new file mode 100644
index 0000000..5ccd2ef
--- /dev/null
+++ b/man/mfrow3d.Rd
@@ -0,0 +1,121 @@
+\name{mfrow3d}
+\alias{mfrow3d}
+\alias{layout3d}
+\alias{next3d}
+\alias{subsceneList}
+\alias{clearSubsceneList}
+\title{
+Set up multiple figure layouts in rgl.
+}
+\description{
+The \code{mfrow3d} and \code{layout3d} functions provide functionality in \pkg{rgl}
+similar to \code{\link{par}("mfrow")} and \code{\link{layout}} in classic R graphics.
+}
+\usage{
+subsceneList(value, window = rgl.cur())
+
+mfrow3d(nr, nc, byrow = TRUE, parent = NA, sharedMouse = FALSE, ...)
+layout3d(mat, widths = rep.int(1, ncol(mat)), 
+              heights = rep.int(1, nrow(mat)),
+              parent = NA, sharedMouse = FALSE,
+              ...)
+next3d(current = NA, clear = TRUE, reuse = TRUE)
+clearSubsceneList(delete = currentSubscene3d() \%in\% subsceneList(), 
+                  window = rgl.cur())
+}
+\arguments{
+  \item{value}{
+A new subscene list to set.  If missing, return the current one (or \code{NULL}).
+}
+  \item{window}{
+Which window to operate on.
+}
+  \item{nr, nc}{
+Number of rows and columns of figures.
+}
+  \item{byrow}{
+Whether figures progress by row (as with \code{\link{par}("mfrow")}) or by column 
+(as with \code{\link{par}("mfcol")}).
+}
+  \item{mat, widths, heights}{
+Layout parameters; see \code{\link{layout}} for their interpretation.
+}
+  \item{parent}{
+The parent subscene.  \code{NA} indicates the current subscene.  See Details below.
+}
+  \item{sharedMouse}{
+Whether to make all subscenes \code{\link{par3d}("listeners")} to each other.
+}
+  \item{\dots}{
+Additional parameters to pass to \code{\link{newSubscene3d}} as each
+subscene is created.
+}
+  \item{current}{
+The subscene to move away from.  \code{NA} indicates the current subscene.
+}
+  \item{clear}{
+Whether the newly entered subscene should be cleared upon entry.
+}
+  \item{reuse}{
+Whether to skip advancing if the current subscene has no objects in it.
+}
+  \item{delete}{
+If \code{TRUE}, delete the subscenes in the current window.
+}
+}
+\details{
+rgl can maintain a list of subscenes; the \code{mfrow3d} and \code{layout3d} functions create that list.
+When the list is in place, \code{next3d} causes rgl to move to the next scene in the list, or cycle
+back to the first one.
+
+Unlike the classic R graphics versions of these functions, these functions are completely compatible with
+each other.  You can mix them within a single rgl window.
+
+In the default case where \code{parent} is missing, \code{mfrow3d} and \code{layout3d} will
+call \code{clearSubsceneList()} at the start.  
+
+By default \code{clearSubsceneList()} checks
+whether the current subscene is in the current subscene list; if so, it will delete
+all subscenes in the list, and call \code{\link{gc3d}} to delete any objects that are no
+longer shown.  The subscene list will be set to a previous value if one was recorded,
+or \code{NULL} if not.
+
+If \code{parent} is specified in \code{mfrow3d} or \code{layout3d} 
+(even as \code{NA}), the new subscenes will be created within 
+the parent.
+}
+\value{
+\code{mfrow3d} and \code{layout3d} return a vector of subscene id values that have just been
+created.  If a previous subscene list was in effect and was not automatically cleared,
+it is attached as an attribute \code{"prev"}.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{newSubscene3d}}, \code{\link{par}}, \code{\link{layout}}.
+}
+\examples{
+shapes <- list(Tetrahedron = tetrahedron3d(), Cube = cube3d(), Octahedron = octahedron3d(),
+               Icosahedron = icosahedron3d(), Dodecahedron = dodecahedron3d(),
+               Cuboctahedron = cuboctahedron3d())
+col <- rainbow(6)
+open3d()
+mfrow3d(3, 2)
+for (i in 1:6) {
+  next3d()   # won't advance the first time, since it is empty
+  shade3d(shapes[[i]], col = col[i])
+}
+
+open3d()
+mat <- matrix(1:4, 2, 2)
+mat <- rbind(mat, mat + 4, mat + 8)
+layout3d(mat, height = rep(c(3, 1), 3), sharedMouse = TRUE)
+for (i in 1:6) {
+  next3d()
+  shade3d(shapes[[i]], col = col[i])
+  next3d()
+  text3d(0, 0, 0, names(shapes)[i])
+}
+}
+\keyword{graphics }
diff --git a/man/observer3d.Rd b/man/observer3d.Rd
new file mode 100644
index 0000000..1605320
--- /dev/null
+++ b/man/observer3d.Rd
@@ -0,0 +1,53 @@
+\name{observer3d}
+\alias{observer3d}
+\title{
+Set the observer location.
+}
+\description{
+This function sets the location of the viewer.
+}
+\usage{
+observer3d(x, y = NULL, z = NULL, auto = FALSE)
+}
+\arguments{
+  \item{x, y, z}{
+The location as a 3 vector, using the usual \code{xyz.coords}
+conventions for specification.  If \code{x} is missing
+or any coordinate is \code{NA}, no change will be made to the
+location.  
+}
+  \item{auto}{ 
+If \code{TRUE}, the location will be set 
+automatically by \pkg{rgl} to make the whole bounding box visible.
+}
+}
+\details{
+This function
+sets the location of the viewer relative to the scene, after the model transformations
+(scaling, rotation) have been done, but before lighting or projection have been 
+applied.  (See \code{\link{par3d}} for details on the rendering pipeline.)
+
+The coordinate system is a slightly strange one:  the X coordinate
+moves the observer location from left to right, and the Y coordinate moves up
+and down.  The Z coordinate changes the depth from the viewer.  All are measured
+relative to the center of the bounding box (\code{par("bbox")}) of the subscene.
+The observer always looks in the positive Z direction
+after the model rotation have been done.  The coordinates are in post-scaling
+units.
+}
+\note{
+This function is likely to change in future versions of \pkg{rgl}, to allow more 
+flexibility in the specification of the observer's location and orientation.
+}
+\value{
+Invisibly returns the previous value.
+}
+\author{
+Duncan Murdoch
+}
+
+\examples{
+example(surface3d)  # The volcano data
+observer3d(0, 0, 440) # Viewed from very close up
+}
+\keyword{ graphics }
diff --git a/man/par3d.Rd b/man/par3d.Rd
new file mode 100644
index 0000000..2e782f7
--- /dev/null
+++ b/man/par3d.Rd
@@ -0,0 +1,293 @@
+\name{par3d}
+\alias{par3d}
+\alias{open3d}
+\alias{r3dDefaults}
+\alias{getr3dDefaults}
+\concept{antialias}
+\concept{bbox}
+\concept{cex}
+\concept{family}
+\concept{font}
+\concept{fontname}
+\concept{FOV}
+\concept{ignoreExtent}
+\concept{maxClipPlanes}
+\concept{modelMatrix}
+\concept{listeners}
+\concept{mouseMode}
+\concept{projMatrix}
+\concept{scale}
+\concept{skipRedraw}
+\concept{useFreeType}
+\concept{userMatrix}
+\concept{viewport}
+\concept{windowRect}
+\concept{zoom}
+
+\title{Set or Query RGL Parameters}
+
+\description{
+  \code{par3d} can be used to set or query graphical parameters in rgl.
+  Parameters can be set by specifying them as arguments to \code{par3d} in
+  \code{tag = value} form, or by passing them as a list of tagged
+  values.
+}
+\usage{
+par3d(\dots, no.readonly = FALSE, dev = rgl.cur(), 
+      subscene = currentSubscene3d(dev))
+
+open3d(\dots, params = getr3dDefaults(), 
+	    useNULL = rgl.useNULL())
+	    
+getr3dDefaults()
+
+r3dDefaults
+}
+
+\arguments{
+  \item{\dots}{arguments in \code{tag = value} form, or a list of tagged
+    values.  The tags must come from the graphical parameters described
+    below.}
+  \item{no.readonly}{logical; if \code{TRUE} and there are no other
+    arguments, only those parameters which can be set by a
+    subsequent \code{par3d()} call are returned.}
+  \item{dev}{integer; the rgl device.}
+  \item{subscene}{integer; the subscene.}
+  \item{params}{a list of graphical parameters}
+  \item{useNULL}{whether to use the null graphics device}
+}
+
+\details{
+  Parameters are queried by giving one or more character vectors to
+  \code{par3d}.
+
+  \code{par3d()} (no arguments) or \code{par3d(no.readonly = TRUE)} is used to
+  get \emph{all} the graphical parameters (as a named list).  
+
+  By default, queries and modifications apply to the current subscene
+  on the current device; specify \code{dev} and/or \code{subscene} to 
+  change this.  Some parameters apply to the device as a whole;
+  these are marked in the list below.
+
+  \code{open3d} opens a new rgl device, and sets the parameters as
+  requested.  The \code{r3dDefaults} list returned by the 
+  \code{getr3dDefaults} function will be used as default
+  values for parameters.  As installed this sets the point of view to
+  'world coordinates' (i.e. x running from left to right, y from front
+  to back, z from bottom to top), the \code{mouseMode} to
+  \code{(zAxis, zoom, fov)}, and the field of view to 30 degrees.
+  Users may create their own variable named \code{r3dDefaults} in the global
+  environment and it will override the installed one.  If there
+  is a \code{bg} element in the list or the arguments, it should be
+  a list of arguments to pass to the \code{\link{bg3d}} function to 
+  set the background.  
+  
+  The arguments to \code{open3d} may include \code{material}, a list
+  of material properties as in \code{\link{r3dDefaults}}, but note
+  that high level functions such as \code{\link{plot3d}} normally use
+  the \code{r3dDefaults} values in preference to this setting. 
+  
+  If \code{useNULL} is \code{TRUE}, \pkg{rgl} will use a \dQuote{null}
+  device.  This device records objects as they are plotted, but 
+  displays nothing. It is intended for use with \code{\link{writeWebGL}}
+  and similar functions.
+}
+
+\value{
+  When parameters are set, their former values are returned in an
+  invisible named list.  Such a list can be passed as an argument to
+  \code{par3d} to restore the parameter values.
+  Use \code{par3d(no.readonly = TRUE)} for the full list of parameters
+  that can be restored.
+
+  When just one parameter is queried, its value is returned directly.
+  When two or more parameters are queried, the result is a list of
+  values, with the list names giving the parameters.
+
+  Note the inconsistency: setting one parameter returns a list, but
+  querying one parameter returns an object.
+  
+  The \code{r3dDefaults} variable is a list containing default
+  settings.  The \code{getr3dDefaults} function searches the user's
+  global environment for \code{r3dDefaults} and returns the 
+  one in the \pkg{rgl} namespace if it was not found there.
+  The components of the list may include any settable \code{par3d}
+  parameter, or \code{"material"}, which should include a list
+  of default \code{\link{material3d}} properties, or \code{"bg"}, 
+  which is a
+  list of defaults to pass to the \code{\link{bg3d}} function.
+}
+
+\section{Parameters}{
+
+  \emph{\bold{R.O.}} indicates \emph{\bold{read-only arguments}}: These
+  may only be used in queries, i.e., they do \emph{not} set anything.
+  
+  \describe{
+    \item{\code{antialias}}{\emph{\bold{R.O.}} in \code{par3d}, may be
+    set in \code{open3d}. The (requested) number of hardware
+    antialiasing planes to use (with multisample antialiasing).  The
+    OpenGL driver may not support the requested number, in which case
+    \code{par3d("antialias")} will report what was actually set. Applies to the whole device.}    
+    \item{\code{cex}}{real.  The default size for text.}
+    \item{\code{family}}{character.  The default device independent family name; see \code{\link{text3d}}.
+    Applies to the whole device.}
+    \item{\code{font}}{integer.  The default font number (from 1 to 5; see \code{\link{text3d}}.
+    Applies to the whole device.}
+    \item{\code{useFreeType}}{logical.  Should FreeType fonts be used?
+    Applies to the whole device.}
+    \item{\code{fontname}}{\emph{\bold{R.O.}}; the system-dependent name of the current font.
+    Applies to the whole device.}
+    \item{\code{FOV}}{real.  The field of view, from 0 to 179 degrees.  This controls
+      the degree of parallax in the perspective view.
+      Isometric perspective corresponds to \code{FOV = 0}.}
+    \item{\code{ignoreExtent}}{logical.  Set to \code{TRUE} so that subsequently plotted objects
+      will be ignored in calculating the bounding box of the scene.  Applies to the
+      whole device.}
+    \item{\code{maxClipPlanes}}{\emph{\bold{R.O.}}; an integer giving the maximum
+      number of clip planes that can be defined in the current system. Applies to the whole device.}
+    \item{\code{modelMatrix}}{\emph{\bold{R.O.}}; a 4 by 4 matrix describing the position
+      of the user data.  See the Note below.}
+    \item{\code{listeners}}{integer.  A vector of subscene id values.  If a subscene receives
+      a mouse event (see \code{mouseMode} just below), the same action will be carried out
+      on all subscenes in this list.  (The subscene itself is normally listed as a listener.
+      If it is not listed, it will not respond to its own mouse events.)}
+    \item{\code{mouseMode}}{character.  A vector of 4 strings describing
+      what the 3 mouse buttons and the mouse wheel do. 
+      Partial matching is used.  Possible values for the first 3 entries of \code{mouseMode} (corresponding 
+      to the mouse buttons are 
+	\describe{
+	 \item{\code{"none"}}{No action for this button.}
+	 \item{\code{"trackball"}}{Mouse acts as a virtual trackball, rotating the scene.}
+	 \item{\code{"xAxis"}}{Similar to \code{"trackball"}, but restricted to X axis rotation.}
+	 \item{\code{"yAxis"}}{Y axis rotation.}
+	 \item{\code{"zAxis"}}{Z axis rotation.}
+	 \item{\code{"polar"}}{Mouse rotates the scene by moving in polar coordinates.}
+	 \item{\code{"selecting"}}{Mouse is used for selection.  This is not normally set by the
+	 user, but is used internally by the \code{\link{select3d}} function.}
+	 \item{\code{"zoom"}}{Mouse is used to zoom the display.}
+	 \item{\code{"fov"}}{Mouse changes the field of view of the display.}
+	 \item{\code{"user"}}{Used  when a user handler is set by 
+	 \code{\link{rgl.setMouseCallbacks}}.}
+	}
+      Possible values for the 4th entry corresponding to the mouse wheel are
+        \describe{
+	  \item{\code{"none"}}{No action.}
+	  \item{\code{"pull"}}{Pulling on the mouse wheel increases magnification, i.e. \dQuote{pulls the scene closer}.}
+	  \item{\code{"push"}}{Pulling on the mouse wheel decreases magnification, i.e. \dQuote{pushes the scene away}.}
+	  \item{\code{"user"}}{Used when a user handler is set by 
+	    \code{\link{rgl.setWheelCallback}}.}
+	}
+      A common default on Mac OSX is to convert a two finger drag on a trackpad to a mouse wheel rotation.
+      
+      Applies to the whole device.
+    }
+    \item{\code{observer}}{\emph{\bold{R.O.}}; the position of the observer relative to
+      the model.  Set by \code{\link{observer3d}}.  See the Note below.}
+    \item{\code{projMatrix}}{\emph{\bold{R.O.}}; a 4 by 4 matrix describing the current
+      projection of the scene.}
+    \item{\code{scale}}{real.  A vector of 3 values indicating the amount by which to
+      rescale each axis before display.  Set by \code{\link{aspect3d}}.}
+    \item{\code{skipRedraw}}{whether to update the display.  Set to \code{TRUE} to suspend
+      updating while making multiple changes to the scene.  See \code{demo(hist3d)} for an example.
+      Applies to the whole device.}
+    \item{\code{userMatrix}}{a 4 by 4 matrix describing user actions to
+      display the scene.}
+    \item{\code{viewport}}{real.  A vector giving the dimensions of the
+      window in pixels.  The entries are taken to be \code{c(x, y, width, height)} where
+      \code{c(x, y)} are the coordinates in pixels of the lower left corner within the window.}
+    \item{\code{zoom}}{real. A positive value indicating the current
+      magnification of the scene.}
+      \item{\code{bbox}}{\emph{\bold{R.O.}}; real. A vector of six values indicating the current values of the
+      bounding box of the scene (xmin, xmax, ymin, ymax, zmin, zmax)}
+    \item{\code{windowRect}}{integer.  A vector of four values indicating the left, top, right and 
+      bottom of the displayed window (in pixels).  Applies to the whole device.}
+  }
+}
+
+\note{
+The \code{"xAxis"}, \code{"yAxis"} and \code{"zAxis"} mouse modes rotate 
+relative to the coordinate system of the data, regardless of the current 
+orientation of the scene.
+
+When multiple parameters are set, they are set in the order given.  In some 
+cases this may lead to warnings and ignored values; for example, some font 
+families only support \code{cex = 1}, so changing both \code{cex} and 
+\code{family} needs to be done in the right order.  For example, when using the
+\code{"bitmap"} family on Windows, \code{par3d(family = "sans", cex = 2)}
+will work, but \code{par3d(cex = 2, family = "sans")} will leave \code{cex}
+at 1 (with a warning that the \code{"bitmap"} family only supports that size).
+
+Although \code{par3d("viewport")} names the entries of the reported vector,
+names are ignored when setting the viewport and entries must be specified
+in the standard order.
+
+In \pkg{rgl} versions 0.94.x the \code{modelMatrix} entry had a changed meaning; 
+before and after that it contains a copy of the OpenGL MODELVIEW matrix. 
+}
+
+\section{Rendering}{
+The parameters returned by \code{par3d} are sufficient to determine where rgl would render
+a point on the screen.  Given a column vector \code{(x, y, z)} in a subscene \code{s}, 
+it performs the equivalent of 
+the following operations:
+\enumerate{
+\item It converts the point to homogeneous coordinates by appending \code{w = 1}, giving
+the vector \code{v = (x, y, z, 1)}.
+\item It calculates the \code{M = par3d("modelMatrix")} as a product from right to left
+of the following matrices:
+  \itemize{  
+  \item A matrix to translate the centre of the bounding box to the origin.
+  \item A matrix to rescale according to \code{par3d("scale")}.
+  \item The \code{par3d("userMatrix")} as set by the user.
+  \item A matrix which may be set by mouse movements.
+  \item If \code{s} has the \code{"model"} set to \code{"modify"}, a similar collection of
+  matrices using parameters from the parent subscene.
+  }
+\item It multiplies the point by \code{M} giving \code{u = M \%*\% v}. 
+\item It multiplies that point by a matrix based on the observer position
+to translate the origin to the centre of the viewing region.
+\item Using this location and information on the
+normals (which have been similarly transformed), it performs lighting calculations. 
+\item It obtains the projection matrix \code{P = par3d("projMatrix")} and
+multiplies the point by it giving \code{P \%*\% u = (x2, y2, z2, w2)}.
+\item It converts back to Euclidean coordinates by dividing the first 3 coordinates by \code{w2}.
+\item The new value \code{z2/w2} represents the depth into the scene of the point.  Depending
+on what has already been plotted, this depth might be obscured, in which case nothing more is plotted.
+\item If the point is not culled due to depth, the \code{x2} and \code{y2} values are used
+to determine the point in the image.  The \code{par3d("viewport")} values are used to translate
+from the range \code{(-1, 1)} to pixel locations, and the point is plotted.
+\item If hardware antialiasing is enabled, then the whole process is
+repeated multiple times (at least conceptually) with different
+locations in each pixel sampled to determine what is plotted there,
+and then the images are combined into what is displayed.
+}
+See ?\link{matrices} for more information on homogeneous and Euclidean coordinates.
+
+Note that many of these calculations are done on the graphics card using single precision;
+you will likely see signs of rounding error if your scene requires more than 4 or 5 
+digit precision to distinguish values in any coordinate.  
+}
+
+\seealso{
+\code{\link{rgl.viewpoint}} to set \code{FOV} and \code{zoom}.
+
+\code{\link{rgl.useNULL}} for default usage of null device.
+}
+
+\references{
+OpenGL Architecture Review Board (1997).  OpenGL Programming Guide.  Addison-Wesley.
+}
+
+\examples{
+    r3dDefaults
+    open3d()
+    shade3d(cube3d(color = rep(rainbow(6), rep(4, 6))))
+    save <- par3d(userMatrix = rotationMatrix(90*pi/180, 1, 0, 0))
+    save
+    par3d("userMatrix")    
+    par3d(save)
+    par3d("userMatrix")
+}
+
+\keyword{dynamic}
diff --git a/man/par3dinterp.Rd b/man/par3dinterp.Rd
new file mode 100644
index 0000000..55bb0d7
--- /dev/null
+++ b/man/par3dinterp.Rd
@@ -0,0 +1,71 @@
+\name{par3dinterp}
+\alias{par3dinterp}
+\title{Interpolator for par3d parameters}
+\description{
+Returns a function which interpolates \code{par3d} parameter values,
+suitable for use in animations.
+}
+\usage{
+par3dinterp(times = NULL, userMatrix, scale, zoom, FOV, 
+            method = c("spline", "linear"), 
+            extrapolate = c("oscillate", "cycle", "constant", "natural"),
+            dev = rgl.cur(), subscene = currentSubscene3d(dev))
+}
+\arguments{
+  \item{times}{ Times at which values are recorded or a list; see below }
+  \item{userMatrix}{ Values of \code{par3d("userMatrix")} }
+  \item{scale}{ Values of \code{par3d("scale")} }
+  \item{zoom}{ Values of \code{par3d("zoom")} }
+  \item{FOV}{ Values of \code{par3d("FOV")} }
+  \item{method}{ Method of interpolation }
+  \item{extrapolate}{ How to extrapolate outside the time range }
+  \item{dev}{ Which rgl device to use }
+  \item{subscene}{ Which subscene to use }
+}
+\details{
+This function is intended to be used in constructing animations.  It produces
+a function that returns a list suitable to pass to \code{\link{par3d}}, to set 
+the viewpoint at a given point in time.
+
+All of the parameters are optional.  Only those \code{par3d} parameters that are 
+specified will be returned.
+
+The input values other than \code{times} may each be specified as
+lists, giving the parameter value settings at a fixed time, or as
+matrices or arrays.  If not lists, the following formats should be
+used: \code{userMatrix} can be a \code{4 x 4 x n} array, or a \code{4
+x 4n} matrix; \code{scale} should be an \code{n x 3} matrix;
+\code{zoom} and \code{FOV} should be length \code{n} vectors.
+
+An alternative form of input is to put all of the above arguments into
+a list (i.e. a list of lists, or a list of arrays/matrices/vectors),
+and pass it as the first argument.  This is the most convenient way to
+use this function with the \code{\link[tkrgl:tkrgl-package]{tkrgl}} function
+\code{\link[tkrgl]{par3dsave}}.
+
+Interpolation is by cubic spline or linear interpolation in an appropriate
+coordinate-wise fashion.  Extrapolation may oscillate
+(repeat the sequence forward, backward, forward, etc.), cycle (repeat
+it forward), be constant (no repetition outside the specified time
+range), or be natural (linear on an appropriate scale).   
+In the case of cycling, the first and last specified values
+should be equal, or the last one will be dropped.  Natural extrapolation
+is only supported with spline interpolation.
+
+}
+\value{
+A function is returned.  The function takes one argument, and returns a list of 
+\code{par3d} settings interpolated to that time.
+}
+\author{Duncan Murdoch }
+\seealso{ \code{\link{play3d}} to play the animation. }
+\examples{
+f <- par3dinterp( zoom = c(1, 2, 3, 1) )
+f(0)
+f(1)
+f(0.5)
+\dontrun{
+play3d(f)
+}
+}
+\keyword{ dplot }
diff --git a/man/persp3d.Rd b/man/persp3d.Rd
new file mode 100644
index 0000000..4dee58a
--- /dev/null
+++ b/man/persp3d.Rd
@@ -0,0 +1,132 @@
+\name{persp3d}
+\alias{persp3d}
+\alias{persp3d.default}
+\title{ Surface plots }
+\description{
+  This function draws plots of surfaces in 3-space. \code{persp3d} is a generic function.}
+\usage{
+persp3d(x, \dots)
+
+\method{persp3d}{default}(x = seq(0, 1, len = nrow(z)), y = seq(0, 1, len = ncol(z)), z,
+    xlim = NULL, ylim = NULL, zlim = NULL,
+    xlab = NULL, ylab = NULL, zlab = NULL, add = FALSE, aspect = !add, 
+    forceClipregion = FALSE, ...)
+}
+\arguments{
+  \item{x, y}{locations of grid lines at which the values in \code{z} are
+    measured.  These may be given as vectors or matrices.
+    If vectors, they must be in ascending order.   Either one or both may be matrices.
+    If \code{x} is a \code{list},
+    its components \code{x$x} and \code{x$y} are used for \code{x}
+    and \code{y}, respectively.}
+  \item{z}{a matrix containing the values to be plotted.  
+    Note that \code{x} can be used instead of \code{z} for
+    convenience.}
+  \item{xlim, ylim, zlim}{x-, y-  and z-limits.  If present,
+  the plot is clipped to this region.}
+  \item{xlab, ylab, zlab}{titles for the axes.  N.B. These must be
+    character strings; expressions are not accepted.  Numbers will be
+    coerced to character strings.}
+  \item{add}{whether to add the points to an existing plot.}    
+  \item{aspect}{either a logical indicating whether to adjust the aspect ratio, or a new ratio.}
+  \item{forceClipregion}{force a clipping region to be used,
+whether or not limits are given.}
+  \item{\dots}{additional material parameters to be passed to \code{\link{surface3d}}
+  and \code{\link{decorate3d}}.}
+}
+\details{
+  This is similar to \code{\link[graphics]{persp}} with user interaction.  See \code{\link{plot3d}}
+  for more general details.
+  
+  One difference from \code{\link[graphics]{persp}} is that colors are specified on each
+  vertex, rather than on each facet of the surface.  To emulate the \code{\link[graphics]{persp}}
+  color handling, you need to do the following.  First, convert the color vector to 
+  an \code{(nx - 1)} by \code{(ny - 1)} matrix; then add an extra row before row 1, 
+  and an extra column after the last column, to convert it to \code{nx} by \code{ny}.
+  (These extra colors will not be used).  For example, 
+  \code{col <- rbind(1, cbind(matrix(col, nx - 1, ny - 1), 1))}.
+  Finally, call \code{persp3d} with material property \code{smooth = FALSE}.
+  
+  If the \code{x} or \code{y} argument is a matrix, then it must be of the same
+  dimension as \code{z}, and the values in the matrix will be used for the corresponding
+  coordinates. This is used to plot shapes such as spheres or cylinders
+  where z is not a function of x and y.  See the fourth and fifth examples below.
+  
+  See the \dQuote{Clipping} section in \code{\link{plot3d}}
+for more details on \code{xlim, ylim, zlim} and \code{forceClipregion}.
+}
+\value{
+  This function is called for the side effect of drawing the plot.  A vector 
+  of shape IDs is returned invisibly.
+}
+\author{Duncan Murdoch}
+\seealso{\code{\link{plot3d}}, \code{\link{persp}}. There is
+a \code{\link{persp3d.function}} method for drawing functions.}
+\examples{
+
+# (1) The Obligatory Mathematical surface.
+#     Rotated sinc function.
+
+x <- seq(-10, 10, length = 30)
+y <- x
+f <- function(x, y) { r <- sqrt(x^2 + y^2); 10 * sin(r)/r }
+z <- outer(x, y, f)
+z[is.na(z)] <- 1
+open3d()
+bg3d("white")
+material3d(col = "black")
+persp3d(x, y, z, aspect = c(1, 1, 0.5), col = "lightblue",
+        xlab = "X", ylab = "Y", zlab = "Sinc( r )")
+
+# (2) Add to existing persp plot:
+
+xE <- c(-10, 10); xy <- expand.grid(xE, xE)
+points3d(xy[, 1], xy[, 2], 6, col = "red")
+lines3d(x, y = 10, z = 6 + sin(x), col = "green")
+
+phi <- seq(0, 2*pi, len = 201)
+r1 <- 7.725 # radius of 2nd maximum
+xr <- r1 * cos(phi)
+yr <- r1 * sin(phi)
+lines3d(xr, yr, f(xr, yr), col = "pink", lwd = 2)
+
+# (3) Visualizing a simple DEM model
+
+z <- 2 * volcano        # Exaggerate the relief
+x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
+y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
+
+open3d()
+bg3d("slategray")
+material3d(col = "black")
+persp3d(x, y, z, col = "green3", aspect = "iso",
+      axes = FALSE, box = FALSE)
+
+# (4) A globe
+
+lat <- matrix(seq(90, -90, len = 50)*pi/180, 50, 50, byrow = TRUE)
+long <- matrix(seq(-180, 180, len = 50)*pi/180, 50, 50)
+
+r <- 6378.1 # radius of Earth in km
+x <- r*cos(lat)*cos(long)
+y <- r*cos(lat)*sin(long)
+z <- r*sin(lat)
+
+open3d()
+persp3d(x, y, z, col = "white", 
+       texture = system.file("textures/worldsmall.png", package = "rgl"), 
+       specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",
+       normal_x = x, normal_y = y, normal_z = z)
+if (!rgl.useNULL())
+  play3d(spin3d(axis = c(0, 0, 1), rpm = 16), duration = 2.5)
+
+\dontrun{
+# This looks much better, but is slow because the texture is very big
+persp3d(x, y, z, col = "white", 
+       texture = system.file("textures/world.png", package = "rgl"), 
+       specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",
+       normal_x = x, normal_y = y, normal_z = z)
+}
+}
+\keyword{ dynamic }
+\keyword{ graphics }
diff --git a/man/persp3d.function.Rd b/man/persp3d.function.Rd
new file mode 100644
index 0000000..73ab1a8
--- /dev/null
+++ b/man/persp3d.function.Rd
@@ -0,0 +1,172 @@
+\name{persp3d.function}
+\alias{plot3d.function}
+\alias{persp3d.function}
+\title{
+Plot a function of two variables
+}
+\description{
+Plot a function \code{z(x, y)} or a parametric function
+\code{(x(s, t), y(s, t), z(s, t))}.
+}
+\usage{
+\method{persp3d}{function}(x, 
+  xlim = c(0, 1), ylim = c(0, 1), 
+  slim = NULL, tlim = NULL, 
+  n = 101, 
+  xvals = seq.int(min(xlim), max(xlim), length.out = n[1]), 
+  yvals = seq.int(min(ylim), max(ylim), length.out = n[2]), 
+  svals = seq.int(min(slim), max(slim), length.out = n[1]), 
+  tvals = seq.int(min(tlim), max(tlim), length.out = n[2]), 
+  xlab, ylab, zlab, 
+  col = "gray", otherargs = list(), 
+  normal = NULL, texture = NULL, \dots)
+\method{plot3d}{function}(x, \ldots)
+}
+\arguments{
+  \item{x}{
+A function of two arguments.  See the details below.
+}
+  \item{xlim, ylim}{
+By default, the range of x and y values.  For a parametric
+surface, if these are not missing, they are used as limits
+on the displayed x and y values.
+}
+  \item{slim, tlim}{
+If not \code{NULL}, these give the range of s and t in the
+parametric specification of the surface.  If
+only one is given, the other defaults to \code{c(0, 1)}.
+}
+  \item{n}{
+A one or two element vector giving the number of 
+steps in the x and y (or s and t) grid.
+}
+  \item{xvals, yvals}{
+The values at which to evaluate x and y.  Ignored for
+a parametric surface.  If used, \code{xlim} and/or \code{ylim}
+are ignored.
+}
+  \item{svals, tvals}{
+The values at which to evaluate s and t for a parametric
+surface.  Only used if
+\code{slim} or \code{tlim} is not \code{NULL}.  As with 
+\code{xvals} and \code{yvals}, these override the corresponding
+\code{slim} or \code{tlim} specification.
+}
+  \item{xlab, ylab, zlab}{
+The axis labels.  See the details below for the defaults.
+}
+  \item{col}{
+The color to use for the plot.  See the details below.
+}
+  \item{otherargs}{
+Additional arguments to pass to the function.
+}
+  \item{normal, texture}{
+Functions to set surface normals or texture coordinates.  See
+the details below.
+}
+  \item{\dots}{
+Additional arguments to pass to \code{\link{persp3d}}.
+}
+}
+\details{
+The \code{"function"} method for \code{plot3d} simply passes
+all arguments to \code{persp3d}.  Thus this description applies
+to both.
+
+The first argument \code{x} is required to be a function.  It
+is named \code{x} only because of the requirements of the S3
+system; in the remainder of this help page, we will assume
+that the assignment \code{f <- x} has been made, and will 
+refer to the function \code{f()}.
+
+\code{persp3d.function} evaluates \code{f()} on a two-dimensional
+grid of values, and displays the resulting surface.  The values
+on the grid will be passed in as vectors in the 
+first two arguments to the function, so \code{f()} needs
+to be vectorized.  Other optional arguments to \code{f()}
+can be specified in the \code{otherargs} list.
+
+In the default form where \code{slim} and \code{tlim} are both
+\code{NULL}, it is assumed that \code{f(x, y)} returns heights,
+which will be plotted in the z coordinate.  The default axis labels
+will be taken from the argument names to \code{f()} and the
+expression passed as argument \code{x} to this function.
+
+If \code{slim} or \code{tlim} is specified, a parametric
+surface is plotted.  The function
+\code{f(s, t)} must return a 3-column matrix, giving x, y and z 
+coordinates of points on the surface.  The default axis
+labels will be the column names if those are present.
+In this case \code{xlim}, \code{ylim} and \code{zlim}
+are used to define a clipping region only if specified;
+the defaults are ignored.
+
+The color of the surface may be specified as the name of a
+color, or a vector or matrix of color names. In this case
+the colors will be recycled across the points on the grid
+of values.
+
+Alternatively, a function may be given:  it should be a function
+like \code{\link{rainbow}} that takes an integer argument and
+returns a vector of colors.  In this case the colors are mapped
+to z values.
+
+The \code{normal} argument allows specification of a function
+to compute normal vectors to the surface.  This function is
+passed the same arguments as \code{f()} (incuding \code{otherargs}
+if present), and should produce a 3-column matrix containing the
+x, y and z coordinates of the normals.
+
+The \code{texture} argument is a function similar to \code{normal}, but
+it produces a 2-column matrix containing texture coordinates.
+
+Both \code{normal} and \code{texture} may also contain matrices,
+with 3 and 2 columns respectively, and rows corresponding to the
+points that were passed to \code{f()}.
+}
+\value{
+This function constructs a call to \code{\link{persp3d}}
+and returns the value from that function.
+}
+\author{
+Duncan Murdoch
+}
+
+\seealso{
+The \code{\link{curve}} function in base graphics does
+something similar for functions of one variable.  See the
+example below for space curves.
+}
+\examples{
+# (1) The Obligatory Mathematical surface.
+#     Rotated sinc function, with colors
+
+f <- function(x, y) { 
+  r <- sqrt(x^2 + y^2)
+  ifelse(r == 0, 10, 10 * sin(r)/r)
+}
+open3d()
+plot3d(f, col = colorRampPalette(c("blue", "white", "red")), 
+       xlab = "X", ylab = "Y", zlab = "Sinc( r )", 
+       xlim = c(-10, 10), ylim = c(-10, 10),
+       aspect = c(1, 1, 0.5))
+       
+# (2) A cylindrical plot
+
+f <- function(s, t) {
+  r <- 1 + exp( -pmin( (s - t)^2, 
+                       (s - t - 1)^2, 
+                       (s - t + 1)^2 )/0.01 )
+  cbind(r*cos(t*2*pi), r*sin(t*2*pi), s)
+}
+
+open3d()
+plot3d(f, slim = c(0, 1), tlim = c(0, 1), col = "red", alpha = 0.8)
+
+# Add a curve to the plot, fixing s at 0.5.
+
+plot3d(f(0.5, seq.int(0, 1, length.out = 100)), type = "l", add = TRUE, 
+       lwd = 3, depth_test = "lequal")
+}
+\keyword{ graphics }
diff --git a/man/planes.Rd b/man/planes.Rd
new file mode 100644
index 0000000..015602a
--- /dev/null
+++ b/man/planes.Rd
@@ -0,0 +1,85 @@
+\name{planes3d}
+\alias{rgl.planes}
+\alias{planes3d}
+\alias{rgl.clipplanes}
+\alias{clipplanes3d}
+\title{add planes}
+\description{
+\code{planes3d} and \code{rgl.planes} add mathematical planes 
+to a scene.  Their intersection with the current
+bounding box will be drawn.  \code{clipplanes3d} and \code{rgl.clipplanes}
+add clipping planes to a scene.
+}
+\usage{
+planes3d(a, b = NULL, c = NULL, d = 0, ...)
+rgl.planes(a, b = NULL, c = NULL, d = 0, ...)
+clipplanes3d(a, b = NULL, c = NULL, d = 0)
+rgl.clipplanes(a, b = NULL, c = NULL, d = 0)
+}
+\arguments{
+  \item{a, b, c}{
+Coordinates of the normal to the plane.  Any reasonable way of defining the
+coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+for details.
+}
+  \item{d}{
+Coordinates of the "offset".  See the details.
+}
+  \item{\dots}{
+Material properties. See \code{\link{rgl.material}} for details.  
+}
+}
+\details{
+\code{planes3d} and \code{rgl.planes} draw planes using the parametrization
+\eqn{a x + b y + c z + d = 0}.  Multiple planes may be specified
+by giving multiple values for any of \code{a, b, c, d}; the other 
+values will be recycled as necessary.
+
+\code{clipplanes3d} and \code{rgl.clipplanes} define clipping planes
+using the same equations.  Clipping planes suppress the display of
+other objects (or parts of them) in the subscene, based on their coordinates.
+Points (or parts of lines or surfaces) where the coordinates \code{x, y, z}
+satisfy \eqn{a x + b y + c z + d < 0} will be suppressed.
+
+The number of clipping planes
+supported by the OpenGL driver is implementation dependent; use
+\code{par3d("maxClipPlanes")} to find the limit.
+}
+\value{
+A shape ID of the planes or clipplanes object is returned invisibly.
+}
+\seealso{
+\code{\link{abclines3d}}, \code{\link{rgl.abclines}} for mathematical lines.
+
+\code{\link{triangles3d}}, \code{\link{rgl.triangles}} or the corresponding
+functions for quadrilaterals may be used to draw sections of planes that
+do not adapt to the bounding box.
+
+The example in \link{subscene3d} shows how to combine clipping planes
+to suppress complex shapes.
+}
+\examples{
+
+# Show regression plane with z as dependent variable
+
+open3d()
+x <- rnorm(100)
+y <- rnorm(100)
+z <- 0.2*x - 0.3*y + rnorm(100, sd = 0.3)
+fit <- lm(z ~ x + y)
+plot3d(x, y, z, type = "s", col = "red", size = 1)
+
+coefs <- coef(fit)
+a <- coefs["x"]
+b <- coefs["y"]
+c <- -1
+d <- coefs["(Intercept)"]
+planes3d(a, b, c, d, alpha = 0.5)
+
+open3d()
+ids <- plot3d(x, y, z, type = "s", col = "red", size = 1, forceClipregion = TRUE) 
+useSubscene3d(ids["clipregion"])
+clipplanes3d(a, b, c, d)
+
+}
+\keyword{dynamic}
diff --git a/man/play3d.Rd b/man/play3d.Rd
new file mode 100644
index 0000000..703bcb1
--- /dev/null
+++ b/man/play3d.Rd
@@ -0,0 +1,95 @@
+\name{play3d}
+\alias{play3d}
+\alias{movie3d}
+\title{ Play animation of rgl scene }
+\description{
+\code{play3d} calls a function repeatedly, passing it the elapsed
+time in seconds, and using the result of the function to
+reset the viewpoint.  \code{movie3d} does the same, but
+records each frame to a file to make a movie.
+}
+\usage{
+play3d(f, duration = Inf, dev = rgl.cur(), ..., startTime = 0)
+movie3d(f, duration, dev = rgl.cur(), ..., fps = 10, 
+                    movie = "movie", frames = movie, dir = tempdir(), 
+                    convert = TRUE, clean = TRUE, verbose = TRUE,
+                    top = TRUE, type = "gif", startTime = 0) 
+
+}
+\arguments{
+  \item{f}{ A function returning a list that may be passed to \code{\link{par3d}} }
+  \item{duration}{ The duration of the animation }    
+  \item{dev}{ Which rgl device to select }
+  \item{\dots}{ Additional parameters to pass to \code{f}. }
+  \item{startTime}{ Initial time at which to start the animation }
+  \item{fps}{ Number of frames per second }
+  \item{movie}{ The base of the output filename, not including .gif }
+  \item{frames}{ The base of the name for each frame }
+  \item{dir}{ A directory in which to create temporary files for each frame of the movie }  
+  \item{convert}{ Whether to try to convert the frames to a single GIF movie, or a command to do so }
+  \item{clean}{ If \code{convert} is \code{TRUE}, whether to delete the individual frames }
+  \item{verbose}{ Whether to report the \code{convert} command and the output filename }
+  \item{top}{ Whether to call \code{\link{rgl.bringtotop}} before each frame }
+  \item{type}{ What type of movie to create.  See Details. }
+}
+\details{
+The function \code{f} will be called in a loop with the first argument
+being the \code{startTime} plus the time in seconds since the start 
+(where the start is measured after all arguments have been evaluated).
+
+\code{play3d} is likely to place a high load
+on the CPU; if this is a problem, calls to \code{\link{Sys.sleep}}
+should be made within the function to release time to other processes.
+
+\code{play3d} will run for the specified \code{duration} (in seconds), but
+can be interrupted by pressing \code{ESC} while the rgl window has the focus.
+
+\code{movie3d} saves each frame to disk in a filename of the form \file{framesXXX.png}, where
+XXX is the frame number, starting from 0.  If \code{convert} is \code{TRUE}, it
+uses ImageMagick to convert them to a single file, by default an animated GIF.  
+The \code{type} argument will be passed to ImageMagick to use as a file extension
+to choose the file type.
+
+Alternatively, \code{convert} can be a template for a command to
+execute in the standard shell (wildcards are allowed). The template is
+converted to a command using \cr
+\code{\link{sprintf}(convert, fps, frames, movie, type, dir, duration)} \cr
+For example, \code{code = TRUE}
+uses the template \code{"convert -delay 1x\%d \%s*.png \%s.\%s"}. All work
+is done in the directory \code{dir}, so paths should not be needed in
+the command.  (Note that \code{\link{sprintf}} does not require all
+arguments to be used, and supports formats that use them in an
+arbitrary order.)
+
+The \code{top = TRUE} default is designed to work around an OpenGL limitation:
+in some implementations, \code{\link{rgl.snapshot}} will fail if the window
+is not topmost.
+
+As of rgl version 0.94, the \code{dev} argument is not needed:  the
+function \code{f} can specify its device, as \code{\link{spin3d}} does, 
+for example.  However, if \code{dev} is specified, it will be selected
+as the current device as each update is played.
+}
+\value{
+This function is called for the side effect of its repeated calls to \code{f}.
+It returns \code{NULL} invisibly.
+}
+\author{ Duncan Murdoch, based on code by Michael Friendly }
+\seealso{ \code{\link{spin3d}} and \code{\link{par3dinterp}} return functions suitable 
+          to use as \code{f}. See \code{demo(flag)} for an example that modifies the
+          scene in \code{f}.}
+\examples{
+open3d()
+plot3d( cube3d(col = "green") )
+M <- par3d("userMatrix")
+if (!rgl.useNULL())
+  play3d( par3dinterp(time = (0:2)*0.75, userMatrix = list(M,
+                                     rotate3d(M, pi/2, 1, 0, 0),
+                                     rotate3d(M, pi/2, 0, 1, 0) ) ), 
+        duration = 3 )
+\dontrun{
+movie3d( spin3d(), duration = 5 )
+}
+
+}
+\keyword{ dplot }
diff --git a/man/plot3d.Rd b/man/plot3d.Rd
new file mode 100644
index 0000000..d9fa8cc
--- /dev/null
+++ b/man/plot3d.Rd
@@ -0,0 +1,108 @@
+\name{plot3d}
+\alias{plot3d}
+\alias{plot3d.default}
+\alias{plot3d.mesh3d}
+\alias{decorate3d}
+\title{3D Scatterplot}
+\description{
+Draws a 3D scatterplot.
+}
+\usage{
+plot3d(x, ...)
+\method{plot3d}{default}(x, y, z,  
+	xlab, ylab, zlab, type = "p", col,  
+	size, lwd, radius,
+	add = FALSE, aspect = !add, 
+	xlim = NULL, ylim = NULL, zlim = NULL, 
+	forceClipregion = FALSE, ...)
+\method{plot3d}{mesh3d}(x, xlab = "x", ylab = "y", zlab = "z", type = c("shade", "wire", "dots"),
+	add = FALSE, ...)	
+decorate3d(xlim, ylim, zlim, 
+	xlab = "x", ylab = "y", zlab = "z", 
+	box = TRUE, axes = TRUE, main = NULL, sub = NULL,
+	top = TRUE, aspect = FALSE, expand = 1.03, 
+	...)
+}
+\arguments{
+  \item{x, y, z}{vectors of points to be plotted. Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{xlab, ylab, zlab}{labels for the coordinates.}
+  \item{type}{For the default method, a single character indicating the type of item to plot.  
+  Supported types are: 'p' for points, 's' for spheres, 
+  'l' for lines, 'h' for line segments 
+  from \code{z = 0}, and 'n' for nothing.  For the \code{mesh3d} method, one of 
+  'shade', 'wire', or 'dots'.  Partial matching is used.
+  }
+  \item{col}{the color to be used for plotted items.}
+  \item{size}{the size for plotted points.}
+  \item{lwd}{the line width for plotted items.}
+  \item{radius}{the radius of spheres:  see Details below.}
+  \item{add}{whether to add the points to an existing plot.}
+  \item{aspect}{either a logical indicating whether to adjust the aspect ratio, or a new ratio.}
+  \item{expand}{how much to expand the box around the data, if it is drawn.}
+  \item{xlim, ylim, zlim}{In \code{plot3d}, if not \code{NULL}, set clipping
+limits for the plot.  In \code{decorate3d}, these are used
+for the labels.}
+  \item{forceClipregion}{Force a clipping region to be used,
+whether or not limits are given.}
+  \item{\dots}{additional parameters which will be passed to \code{\link{par3d}}, \code{\link{material3d}}
+  or \code{decorate3d}.}
+  \item{box, axes}{whether to draw a box and axes.}
+  \item{main, sub}{main title and subtitle.}
+  \item{top}{whether to bring the window to the top when done.}
+}
+\value{
+  \code{plot3d} is called for the side effect of drawing the plot; a vector
+  of object IDs is returned.
+  
+  \code{decorate3d} adds the usual decorations to a plot:  labels, axes, etc.
+}
+\details{
+\code{plot3d} is a partial 3D analogue of plot.default.
+
+Missing values in the data are skipped, as in standard graphics.
+
+If \code{aspect} is \code{TRUE}, aspect ratios of \code{c(1, 1, 1)} are passed to
+\code{\link{aspect3d}}.  If \code{FALSE}, no aspect adjustment is done.  In other
+cases, the value is passed to \code{\link{aspect3d}}.
+
+With \code{type = "s"}, spheres are drawn centered at the specified locations.
+The radius may be controlled by \code{size} (specifying the size relative
+to the plot display, with the default \code{size = 3} giving a radius 
+about 1/20 of the plot region) or \code{radius} (specifying it on the data scale
+if an isometric aspect ratio is chosen, or on an average scale
+if not). 
+}
+\section{Clipping}{
+If any of \code{xlim}, \code{ylim} or \code{zlim} are specified,
+they should be length two vectors giving lower and upper 
+clipping limits for the corresponding coordinate.  \code{NA}
+limits will be ignored.
+
+If any clipping limits are given, then the data will be
+plotted in a newly created subscene within the current one;
+otherwise plotting will take place directly in the current
+subscene.  This subscene is named \code{"clipregion"}
+in the results. 
+
+Use \code{forceClipregion = TRUE} to force creation of this 
+subscene even without specifying limits. 
+}
+\author{
+  Duncan Murdoch
+}
+\seealso{
+  \code{\link{plot.default}},  
+  \code{\link{open3d}}, \code{\link{par3d}}.
+  There is a \code{\link{plot3d.function}} method for plotting surfaces.
+}
+\examples{
+  open3d()
+  x <- sort(rnorm(1000))
+  y <- rnorm(1000)
+  z <- rnorm(1000) + atan2(x, y)
+  plot3d(x, y, z, col = rainbow(1000))
+}
+\keyword{dynamic}
+
diff --git a/man/polygon3d.Rd b/man/polygon3d.Rd
new file mode 100644
index 0000000..183ece9
--- /dev/null
+++ b/man/polygon3d.Rd
@@ -0,0 +1,72 @@
+\name{polygon3d}
+\alias{polygon3d}
+\title{
+Triangulate and draw a polygon in three dimensions.
+}
+\description{
+This function takes a description of a flat polygon in x, y and z coordinates,
+and draws it in three dimensions.
+}
+\usage{
+polygon3d(x, y = NULL, z = NULL, fill = TRUE, plot = TRUE, 
+          coords = 1:2, random = TRUE, ...)
+}
+\arguments{
+  \item{x, y, z}{
+Vertices of the polygon in a form accepted by \code{\link{xyz.coords}}.
+}
+  \item{fill}{
+logical; should the polygon be filled?
+}
+  \item{plot}{
+logical; should the polygon be displayed?
+}
+  \item{coords}{
+Which two coordinates (\code{x = 1}, \code{y = 2}, \code{z = 3}) describe the
+polygon.  
+}
+  \item{random}{
+Should a random triangulation be used?
+}
+  \item{\dots}{
+Other parameters to pass to \code{\link{lines3d}} or \code{\link{shade3d}} if \code{plot = TRUE}.
+}
+}
+\details{
+The function triangulates the two dimensional polygon described by \code{coords}, then
+applies the triangulation to all three coordinates.  No check is made that the polygon
+is actually all in one plane, but the results may be somewhat unpredictable
+(especially if \code{random = TRUE}) if it is not.
+
+Polygons need not be simple; use \code{NA} to indicate separate closed pieces.  For
+\code{fill = FALSE} there are no other restrictions on the pieces, but for 
+\code{fill = TRUE} the resulting two-dimensional polygon needs to be one that
+\code{\link{triangulate}} can handle.
+}
+\value{
+If \code{plot = TRUE}, the id number of the lines (for \code{fill = FALSE}) or triangles
+(for \code{fill = TRUE}) that have been plotted.
+
+If \code{plot = FALSE}, then for \code{fill = FALSE}, a vector of indices into
+the XYZ matrix that could be used to draw the polygon.  For \code{fill = TRUE}, 
+a triangular mesh object representing the triangulation.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{extrude3d}} for a solid extrusion of a polygon, \code{\link{triangulate}} for
+the triangulation.
+}
+\examples{
+theta <- seq(0, 4*pi, len = 50)
+r <- theta + 1
+r <- c(r[-50], rev(theta*0.8) + 1)
+theta <- c(theta[-50], rev(theta))
+x <- r*cos(theta)
+y <- r*sin(theta)
+plot(x, y, type = "n")
+polygon(x, y)
+polygon3d(x, y, x + y, col = "blue")
+}
+\keyword{ graphics }
diff --git a/man/postscript.Rd b/man/postscript.Rd
new file mode 100644
index 0000000..32cb9ea
--- /dev/null
+++ b/man/postscript.Rd
@@ -0,0 +1,67 @@
+\name{rgl.postscript}
+\alias{rgl.postscript}
+\title{export screenshot}
+\description{
+  Saves the screenshot to a file in PostScript or other vector graphics format.
+}
+\usage{
+rgl.postscript( filename, fmt = "eps", drawText = TRUE )
+}
+\arguments{
+  \item{filename}{full path to filename.}
+  \item{fmt}{export format, currently supported: ps, eps, tex, pdf, svg, pgf }
+  \item{drawText}{logical, whether to draw text}
+}
+\details{
+Animations can be created in a loop modifying the scene and saving 
+a screenshot to a file. (See example below)
+
+This function is a wrapper for the GL2PS library by Christophe Geuzaine,
+and has the same limitations as that library:  not all OpenGL features
+are supported, and some are only supported in some formats.
+See the reference for full details.
+}
+\references{
+GL2PS: an OpenGL to PostScript printing library by Christophe Geuzaine,
+\url{http://www.geuz.org/gl2ps/}, version 1.3.8.
+}
+\author{ Christophe Geuzaine / Albrecht Gebhardt }
+\examples{
+
+x <- y <- seq(-10, 10, length = 20)
+z <- outer(x, y, function(x, y) x^2 + y^2)
+persp3d(x, y, z, col = 'lightblue')
+
+title3d("Using LaTeX text", col = 'red', line = 3)
+rgl.postscript("persp3da.ps", "ps", drawText = FALSE)
+rgl.postscript("persp3da.pdf", "pdf", drawText = FALSE)
+rgl.postscript("persp3da.tex", "tex")
+rgl.pop()
+title3d("Using ps/pdf text", col = 'red', line = 3)
+rgl.postscript("persp3db.ps", "ps")
+rgl.postscript("persp3db.pdf", "pdf")
+rgl.postscript("persp3db.tex", "tex", drawText = FALSE)
+
+\dontrun{
+
+#
+# create a series of frames for an animation
+#
+
+rgl.open()
+shade3d(oh3d(), color = "red")
+rgl.viewpoint(0, 20)
+
+for (i in 1:45) {
+  rgl.viewpoint(i, 20)
+  filename <- paste("pic", formatC(i, digits = 1, flag = "0"), ".eps", sep = "") 
+  rgl.postscript(filename, fmt = "eps")
+}
+
+}
+
+}
+\seealso{
+  \code{\link{rgl.viewpoint}}, \code{\link{rgl.snapshot}}
+}
+\keyword{dynamic}
diff --git a/man/primitive.Rd b/man/primitive.Rd
new file mode 100644
index 0000000..f510c3c
--- /dev/null
+++ b/man/primitive.Rd
@@ -0,0 +1,76 @@
+\name{rgl.primitive}
+\alias{rgl.primitive}
+\alias{rgl.points}
+\alias{rgl.lines}
+\alias{rgl.linestrips}
+\alias{rgl.triangles}
+\alias{rgl.quads}
+\title{add primitive set shape}
+\description{
+  Adds a shape node to the current scene
+}
+\usage{
+rgl.points(x, y = NULL, z = NULL, ... )
+rgl.lines(x, y = NULL, z = NULL, ... )
+rgl.linestrips(x, y = NULL, z = NULL, ...)
+rgl.triangles(x, y = NULL, z = NULL, normals = NULL, texcoords = NULL, ... )
+rgl.quads(x, y = NULL, z = NULL, normals = NULL, texcoords = NULL, ... )
+}
+\arguments{
+  \item{x, y, z}{coordinates.  Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{normals}{Normals at each point.}
+  \item{texcoords}{Texture coordinates at each point.}
+  \item{ ... }{Material properties. See \code{\link{rgl.material}} for details.}  
+}
+\details{
+  Adds a shape node to the scene. The appearance is defined by the material properties.
+  See \code{\link{rgl.material}} for details.
+  
+  The names of these functions correspond to OpenGL primitives.  They
+  all take a sequence of vertices in \code{x, y, z}.  The only non-obvious 
+  ones are \code{rgl.lines} which draws line segments based on
+  pairs of vertices, and \code{rgl.linestrips} which joins the
+  vertices.
+  
+  For triangles and quads, the normals at each vertex may be specified
+  using \code{normals}.  These may be given in any way that would be
+  acceptable as a single argument to \code{\link[grDevices]{xyz.coords}}.  
+  These need not match the actual normals to the polygon:
+  curved surfaces can be simulated by using other choices of normals.
+  
+  Texture coordinates may also be specified.  These may be given in
+  any way that would be acceptable as a single argument to 
+  \code{\link[grDevices]{xy.coords}}, and are interpreted in terms
+  of the bitmap specified as the material texture, with \code{(0, 0)} 
+  at the lower left, \code{(1, 1)} at the upper right.  The texture
+  is used to modulate the color of the polygon.
+  
+  These are the lower level functions called by
+  \code{\link{points3d}}, \code{\link{segments3d}},
+  \code{\link{lines3d}}, etc.  The two principal differences between
+  the \code{rgl.*} functions and the \code{*3d} functions are that the
+  former set all unspecified material properties to defaults, whereas
+  the latter use current values as defaults; the former make
+  persistent changes to material properties with each call, whereas
+  the latter make temporary changes only for the duration of the call.
+
+}
+\value{
+   Each primitive function returns the integer object ID of the shape that
+   was added to the scene.  These can be passed to \code{\link{rgl.pop}}
+   to remove the object from the scene.
+}
+\examples{
+rgl.open()
+rgl.points(rnorm(1000), rnorm(1000), rnorm(1000), color = heat.colors(1000))
+}
+\seealso{
+\code{\link{rgl.material}},
+\code{\link{rgl.spheres}},
+\code{\link{rgl.texts}},
+\code{\link{rgl.surface}},
+\code{\link{rgl.sprites}}
+}
+\keyword{dynamic}
diff --git a/man/propertySetter.Rd b/man/propertySetter.Rd
new file mode 100644
index 0000000..045fcf9
--- /dev/null
+++ b/man/propertySetter.Rd
@@ -0,0 +1,210 @@
+\name{propertySetter}
+\alias{propertySlider}
+\alias{propertySetter}
+\alias{par3dinterpSetter}
+\alias{matrixSetter}
+\alias{vertexSetter}
+\title{
+Write HTML/Javascript code to control a WebGL display.
+}
+\description{
+\code{propertySlider} writes out HTML code to control WebGL displays on the same page via a slider; \code{par3dinterpSetter} and
+\code{propertySetter} return Javascript code
+to be used in HTML controls.
+}
+\usage{
+propertySlider(setter = propertySetter,
+             minS, maxS, step = 1, init = minS, 
+	     labels, 
+	     id = basename(tempfile("input")), name = id,
+	     outputid = paste0(id, "text"),
+	     index = NULL,
+	     ...) 
+	     
+propertySetter(values = NULL, entries, properties, objids, prefixes = "",
+               param = seq_len(NROW(values)), interp = TRUE, digits = 7) 
+               
+par3dinterpSetter(fn, from, to, steps, subscene, omitConstant = TRUE, 
+                  rename = character(), ...)
+
+matrixSetter(fns, from, to, steps, subscene = currentSubscene3d(), 
+             matrix = "userMatrix", omitConstant = TRUE, prefix = "", ...) 
+             
+vertexSetter(values, vertices = 1, attributes, objid, prefix = "",
+	     param = seq_len(NROW(values)), interp = TRUE,
+	     digits = 7)
+}
+\arguments{
+  \item{setter}{A function to write Javascript code, or its output, or
+   a list containing several of these.}
+  \item{minS, maxS, step, init}{Slider values to be displayed. Reasonable defaults are used if missing.}
+  \item{labels}{Labels to display for each slider value.  The
+  defaults are calculated using internal variables.  If \code{NULL},
+  no labels will be shown.}
+  \item{id}{The \code{id} of the input control that will be generated.}
+  \item{name}{The name of the input control that will be generated.}
+  \item{outputid}{The \code{id} of the output control that
+will display the slider value, or \code{NULL} for none.}
+  \item{index}{The 1-based index of this slider:  it controls the
+  corresponding entry in an indexed setter such as \code{matrixSetter}.}
+  \item{...}{See Details below.}
+  \item{values}{An array of values; rows correspond to slider positions.  Alternatively, \code{NULL}; the generated function takes a
+  single value or array of values and applies them directly.}
+  \item{entries, properties, objids, prefixes}{Vectors describing
+  the columns of \code{values}.  See the details below.}
+  \item{param}{Parameter values corresponding to each row of \code{values}.}
+  \item{interp}{Whether to interpolate values.  If \code{FALSE}, 
+  the Javascript function will expect non-negative integer values.
+  Ignored if \code{values} is \code{NULL}.}
+  \item{digits}{How many significant digits to emit in the Javascript code.}
+  \item{fn}{A function returned from \code{\link{par3dinterp}}.}
+  \item{from, to, steps}{Values where \code{fn} should be evaluated.}
+  \item{subscene}{Which subscene's properties should be modified?}
+  \item{omitConstant}{If \code{TRUE}, do not set values that are
+  constant across the range.}
+  \item{rename}{A named character vector of names of Javascript properties
+  to modify.  See the details.}
+  \item{fns}{A list containing functions returned from 
+    \code{\link{par3dinterp}}.}
+  \item{matrix}{A character string giving the Javascript property
+    name of the matrix to modify.}
+  \item{prefix}{The prefix of the scene containing \code{matrix}.}
+  \item{vertices}{A vector of vertex numbers (1-based) within 
+  an object.}
+  \item{attributes}{A vector of attributes of a vertex, 
+  from \code{c("x", "y", "z", "r", "g", "b", "a", "nx", "ny", "nz",
+               "radius", "ox", "oy", "oz", "ts", "tt")}.  See
+               Details.}
+  \item{objid}{The object containing the vertices to be modified.}
+}
+\details{
+The \code{...} parameters to \code{propertySlider} will be passed to
+\code{setter} if the latter is a function, otherwise ignored. 
+
+The \code{...} parameters to \code{par3dinterpSetter}
+will be passed to \code{propertySetter}.
+
+The \code{...} parameters to \code{matrixSetter} will be passed to the
+\code{par3dinterpSetter} functions used for each of the functions
+in \code{fns}.
+
+\code{propertySetter} is a low-level general purpose function for modifying
+properties of objects in the scene.  It is mainly for internal use.
+\code{propertySlider} uses it to generate Javascript for a slider control
+to manipulate those properties.  
+
+\code{vertexSetter} modifies attributes of vertices in a single
+object.  The \code{attributes} are properties of each vertex 
+in a scene; not all are applicable to all objects. In order, 
+the are: coordinates of the vertex \code{"x", "y", "z"}, color
+of the vertex \code{"r", "g", "b", "a"}, normal at the vertex
+\code{"nx", "ny", "nz"}, radius of a sphere at the vertex
+\code{"radius"}, origin within a texture \code{"ox", "oy"} and
+perhaps \code{"oz"}, texture coordinates \code{"ts", "tt"}.
+
+\code{propertySetter} and \code{vertexSetter} allow values to be 
+specified in two ways.
+The normal way when used with a slider is to interpolate between
+specified values indexed by the slider.  If \code{values = NULL},
+the value of the slider is used directly (and only one entry can
+be set).  Multiple entries can be set directly by passing
+an array of values in custom Javascript code.
+
+\code{par3dinterpSetter} uses \code{propertySetter}
+to set parameters corresponding to values produced by the result of
+\code{par3dinterp}.  Its \code{rename} argument allows translation
+of names, e.g. \code{rename = c(userMatrix = "myMatrix")} would
+cause the \code{"userMatrix"} result from \code{\link{par3dinterp}}
+to be used to modify the Javascript \code{myMatrix} property.
+
+\code{matrixSetter} is used in the situation where multiple controls
+(e.g. sliders) are used to determine the value of a matrix, typically
+\code{"userMatrix"}.  It will generate one \code{par3dinterpSetter}
+function for each of the entries in \code{fns}; these will be called
+when a \code{propertySlider} with the corresponding (1-based) index
+is changed, and the results multiplied together from right to left
+to produce a new value for whichever property is named in \code{matrix}.
+
+The rows of the \code{values} matrix correspond to different settings
+for numeric properties.  The columns are values to insert into those properties.
+
+Argument \code{entries} gives the numeric (zero based) index into the Javascript
+property named by \code{properties}, for the object id \code{objids}, in the
+display with prefix \code{prefixes}.  All of these may be vectors, corresponding
+to the columns of \code{values}.  All but \code{entries} will be recycled 
+to the appropriate length; its length needs to match the number of 
+columns in \code{values}.
+
+There are two modes for determining the values to substitute.  In the simplest
+mode (\code{interp = FALSE} in \code{propertySetter}), 
+each row of \code{values} corresponds to a location for the slider, and
+the values are simply copied into place.  This requires that \code{param}, 
+\code{min}, \code{max} and \code{step} take on their default values.
+
+In other cases, linear interpolation is used between successive rows of \code{values},
+with extrapolation outside the range of \code{param} 
+repeating the first or last row.   \code{param} should then
+contain the values that correspond to exact rows.
+
+In both cases, \code{param} must be a strictly increasing vector.
+
+}
+\value{
+\code{propertySlider} prints the full code to generate the control, 
+and returns the \code{id} of the control that was generated.  
+
+\code{propertySetter} returns a single element character vector 
+containing the Javascript source for a function to set
+the appropriate properties.   It does not assign the function 
+to a variable or include any of the HTML wrapper text that 
+\code{propertySlider} adds.  
+
+The character vector has class
+\code{"propertySetter"}, and an attribute named \code{"env"}
+which gives access to the local environment where it was
+created, so for example \code{attr(value, "env")$prefixes} will
+give access to the \code{prefixes} argument if \code{value}
+was produced by \code{"propertySetter"}.
+
+\code{par3dinterpSetter} returns a \code{propertySetter} result.
+
+\code{matrixSetter} is similar to \code{propertySetter}, but
+the Javascript function takes arguments \code{value, index}, 
+and the class of the result is 
+\code{c("matrixSetter", "indexedSetter", "propertySetter")}.
+
+\code{vertexSetter} is similar to \code{propertySetter}, but
+the class of the result is \code{c("vertexSetter", "propertySetter")}.
+}
+\author{
+Duncan Murdoch
+}
+
+\seealso{
+\code{\link{writeWebGL}}.  \code{\link{clipplaneSlider}} makes
+use of \code{propertySlider}.
+
+\code{\link{ageSetter}} can be used as the \code{setter} argument
+to \code{propertySlider} to modify objects according to a linear (age)
+scale.
+}
+\examples{
+if (require(rglwidget)) {
+  # Just the setter function
+  cat(propertySetter(1:4, entries = 12, properties = "values", objids = 13))
+
+  # A 4-position slider
+  propertySlider(values = 1:4, entries = 12, properties = "values", objids = 13, interp = FALSE)
+
+  # A 10-position slider interpolating the 4-position slider
+  propertySlider(values = 1:4, entries = 12, properties = "values", objids = 13,
+               step = (4-1)/9)
+               
+  # The userMatrix interpolation from example(play3d)
+  M <- r3dDefaults$userMatrix
+  fn <- par3dinterp(time = (0:2)*0.75, userMatrix = list(M,
+                                     rotate3d(M, pi/2, 1, 0, 0),
+                                     rotate3d(M, pi/2, 0, 1, 0) ) )
+  cat(par3dinterpSetter(fn, 0, 3, steps=10))
+}
+}
diff --git a/man/r3d.Rd b/man/r3d.Rd
new file mode 100644
index 0000000..6a766b8
--- /dev/null
+++ b/man/r3d.Rd
@@ -0,0 +1,104 @@
+\name{r3d}
+\alias{r3d}
+\title{Generic 3D interface}
+\description{Generic 3D interface for 3D rendering and computational geometry.}
+\details{  
+  R3d is a design for an interface for 3d rendering and computation without dependency
+  on a specific rendering implementation. R3d includes a collection
+  of 3D objects and geometry algorithms.
+  All r3d interface functions are named \code{*3d}.  They represent generic functions that delegate 
+  to implementation functions.
+  
+  The interface can be grouped into 8 categories: Scene Management, Primitive Shapes,
+  High-level Shapes, Geometry Objects, Visualization, Interaction, Transformation,
+  Subdivision.  
+  
+  The rendering interface gives an abstraction to the underlying rendering model. It can
+  be grouped into four categories:    
+  \describe{
+    \item{Scene Management:}{A 3D scene consists of shapes, lights and background environment.} 
+    \item{Primitive Shapes:}{Generic primitive 3D graphics shapes such as points, lines, triangles, quadrangles and texts.} 
+    \item{High-level Shapes:}{Generic high-level 3D graphics shapes such as spheres, sprites and terrain.}
+    \item{Interaction:}{Generic interface to select points in 3D space using the pointer device.}
+  }
+  
+  In this package we include an implementation of r3d using the underlying \code{rgl.*} functions.
+  
+  3D computation is supported through the use of object structures that live entirely in R.
+  \describe{
+    \item{Geometry Objects:}{Geometry and mesh objects allow to define high-level geometry for computational purpose such as triangle or 
+                             quadrangle meshes (see \code{\link{mesh3d}}.}
+    \item{Transformation:}{Generic interface to transform 3d objects.}
+    \item{Visualization:}{Generic rendering of 3d objects such as dotted, wired or shaded.}
+    \item{Computation:}{Generic subdivision of 3d objects.}
+  }
+  
+  At present, the main practical differences between the r3d functions
+  and the \code{rgl.*} functions are as follows. 
+  
+  The r3d functions call
+  \code{\link{open3d}} if there is no device open, and the
+  \code{rgl.*} functions call \code{\link{rgl.open}}. By default
+  \code{\link{open3d}} sets the initial orientation of the coordinate
+  system in 'world coordinates', i.e. a right-handed coordinate system
+  in which the x-axis increases from left to right, the y-axis
+  increases with depth into the scene, and the z-axis increases from
+  bottom to top of the screen.  \code{rgl.*} functions, on the other
+  hand, use a right-handed coordinate system similar to that used in
+  OpenGL.  The x-axis matches that of r3d, but the y-axis increases
+  from bottom to top, and the z-axis decreases with depth into the
+  scene.  Since the user can manipulate the scene, either system can
+  be rotated into the other one.  
+  
+  The r3d functions also preserve the \code{rgl.material} setting across
+  calls (except for texture elements, in the current implementation), whereas
+  the \code{rgl.*} functions leave it as set by the last call.
+  
+  The example code below illustrates the two coordinate systems.
+}
+
+\seealso{
+\code{\link{points3d}},
+\code{\link{lines3d}},
+\code{\link{segments3d}},
+\code{\link{triangles3d}},
+\code{\link{quads3d}},
+\code{\link{text3d}},
+\code{\link{spheres3d}},
+\code{\link{sprites3d}},
+\code{\link{terrain3d}},
+\code{\link{select3d}},
+\code{\link{dot3d}},
+\code{\link{wire3d}},
+\code{\link{shade3d}},
+\code{\link{transform3d}},
+\code{\link{rotate3d}},
+\code{\link{subdivision3d}},
+\code{\link{mesh3d}},
+\code{\link{cube3d}},
+\code{\link{rgl}}
+}
+\examples{
+    
+     x <- c(0, 1, 0, 0)
+     y <- c(0, 0, 1, 0)
+     z <- c(0, 0, 0, 1)
+     labels <- c("Origin", "X", "Y", "Z")
+     i <- c(1, 2, 1, 3, 1, 4)
+
+     # rgl.* interface
+     
+     rgl.open()
+     rgl.texts(x, y, z, labels)
+     rgl.texts(1, 1, 1, "rgl.* coordinates")
+     rgl.lines(x[i], y[i], z[i])
+
+     # *3d interface
+     
+     open3d()
+     text3d(x, y, z, labels)
+     text3d(1, 1, 1, "*3d coordinates")
+     segments3d(x[i], y[i], z[i])
+}
+
+\keyword{dynamic}
diff --git a/man/readSTL.Rd b/man/readSTL.Rd
new file mode 100644
index 0000000..4eeeb0c
--- /dev/null
+++ b/man/readSTL.Rd
@@ -0,0 +1,91 @@
+\name{readSTL}
+\alias{readSTL}
+\alias{writeSTL}
+\title{
+Read and write STL (stereolithography) format files
+}
+\description{
+These functions read and write STL files.  This is a simple file format that
+is commonly used in 3D printing.  It does not represent text,
+only triangles.  The \code{writeSTL} function converts some RGL object
+types to triangles.
+}
+\usage{
+readSTL(con, ascii = FALSE, plot = TRUE, ...)
+writeSTL(con, ascii = FALSE, 
+         pointRadius = 0.005, 
+         pointShape = icosahedron3d(),
+         lineRadius = pointRadius,
+         lineSides = 20,
+         ids = NULL)
+}
+\arguments{
+  \item{con}{
+A connection or filename.
+}
+  \item{ascii}{
+Whether to use the ASCII format or the binary format.
+}
+  \item{plot}{
+On reading, should the object be plotted?
+}
+  \item{\dots}{
+If plotting, other parameters to pass to \code{\link{triangles3d}}
+}
+  \item{pointRadius, lineRadius}{
+The radius of points and lines relative to the overall scale of the figure.
+}
+  \item{pointShape}{
+A mesh shape to use for points.  It is scaled by the \code{pointRadius}.
+}
+  \item{lineSides}{
+Lines are rendered as cylinders with this many sides.
+}
+  \item{ids}{
+The identifiers (from \code{\link{rgl.ids}}) of the
+objects to write.  If \code{NULL}, try to write everything.
+}
+}
+\details{
+The current implementation is limited.  For reading, it ignores normals
+and color information.  For writing, it only outputs triangles, quads, planes, spheres,
+points, line segments, line strips and surfaces, and does not write color information.
+Lines and points are rendered in an isometric scale:  if your data scales vary, they
+will look strange.
+
+Since the STL format only allows one object per file, all RGL objects
+are combined into a single object when output.
+
+The output file is readable by Blender and Meshlab; the latter can write in
+a number of other formats, including U3D, suitable for import into a PDF document.
+
+}
+\value{
+\code{readSTL} invisibly returns the object id if \code{plot = TRUE}, or (visibly) 
+a matrix of vertices of the triangles if not.
+
+\code{writeSTL} invisibly returns the name of the connection to which the 
+data was written.
+}
+\references{
+The file format was found on Wikipedia on October 25, 2012.  I learned
+about the STL file format from David Smith's blog reporting on 
+Ian Walker's \code{r2stl} function.  
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{scene3d}} saves a copy of a scene to an R variable;
+\code{\link{writeWebGL}}, \code{\link{writePLY}}, \code{\link{writeOBJ}} and \code{\link{writeSTL}}
+write the scene to a file in various other formats.
+}
+\examples{
+filename <- tempfile(fileext = ".stl")
+open3d()
+shade3d( icosahedron3d(col = "magenta") )
+writeSTL(filename)
+open3d()
+readSTL(filename, col = "red")
+}
+\keyword{ graphics }
diff --git a/man/rgl-internal.Rd b/man/rgl-internal.Rd
new file mode 100644
index 0000000..2655de4
--- /dev/null
+++ b/man/rgl-internal.Rd
@@ -0,0 +1,65 @@
+\name{rgl-internal}
+\title{Internal rgl functions and data}
+\alias{rgl.bool}
+\alias{rgl.numeric}
+\alias{rgl.range}
+\alias{rgl.vertex}
+\alias{rgl.nvertex}
+\alias{rgl.color}
+\alias{rgl.mcolor}
+\alias{rgl.clamp}
+\alias{rgl.attr}
+\alias{rgl.enum}
+\alias{rgl.enum.gl2ps}
+\alias{rgl.enum.nodetype}
+\alias{rgl.enum.pixfmt}
+\alias{rgl.enum.polymode}
+\alias{rgl.enum.textype}
+\alias{rgl.enum.fogtype}
+\alias{rgl.enum.primtype}
+\alias{rgl.enum.halign}
+\alias{rgl.enum.texmagfilter}
+\alias{rgl.enum.texminfilter}
+\alias{rgl.selectstate}
+\alias{rgl.setselectstate}
+\alias{edgemap}
+\alias{edgeindex}
+\alias{cube3d.ib}
+\alias{cube3d.vb}
+\alias{oh3d.ib}
+\alias{oh3d.vb}
+\alias{dev3d}
+\description{
+  internal rgl functions
+}
+\usage{
+rgl.bool(x)
+rgl.numeric(x)
+rgl.range(x, low, high)
+rgl.vertex(x, y = NULL, z = NULL)
+rgl.nvertex(vertex)
+rgl.color(color)
+rgl.mcolor(colors)
+rgl.clamp(value, low, high)
+rgl.attr(vattr, nvertex) 
+rgl.enum(name, ..., multi = FALSE)
+rgl.enum.gl2ps(postscripttype) 
+rgl.enum.nodetype(type)
+rgl.enum.pixfmt(fmt)
+rgl.enum.polymode(mode)
+rgl.enum.textype(textype)
+rgl.enum.fogtype(fogtype)
+rgl.enum.primtype(primtype)
+rgl.enum.halign(halign)
+rgl.enum.texmagfilter(magfiltertype)
+rgl.enum.texminfilter(minfiltertype)
+rgl.selectstate()
+rgl.setselectstate(state)
+edgemap(size)
+edgeindex(from, to, size, row, col)
+}
+\details{
+  These are not to be called by the user.
+}
+\keyword{internal}
+
diff --git a/man/rgl-package.Rd b/man/rgl-package.Rd
new file mode 100644
index 0000000..1248d1e
--- /dev/null
+++ b/man/rgl-package.Rd
@@ -0,0 +1,43 @@
+\name{rgl-package}
+\title{3D visualization device system}
+\alias{rgl-package}
+\alias{rgl}
+\description{
+  3D real-time rendering system.
+}
+\details{
+  RGL is a 3D real-time rendering system for R.
+  Multiple windows are managed at a time. Windows
+  may be divided into \dQuote{subscenes}, where one has the current focus
+  that receives instructions from the R command-line. 
+  The device design is oriented towards the R device metaphor. If you send
+  scene management instructions, and there's no device open, it will be opened
+  automatically.
+  Opened devices automatically get the current device focus. The focus may be
+  changed by using \code{\link{rgl.set}()} or \code{\link{useSubscene3d}()}.
+  
+  \pkg{rgl} provides medium to high level functions for 3D interactive graphics, including
+  functions modelled on base graphics (\code{\link{plot3d}()}, etc.) as well as functions for 
+  constructing geometric objects (\code{\link{cube3d}()}, etc.).  Output
+  may be on screen using OpenGL, or to various standard 3D file formats including 
+  WebGL, PLY, OBJ, STL as well as 2D image formats, including PNG, Postscript, SVG, PGF.
+  
+  The \code{\link{open3d}()} function attempts to open a new RGL window,
+  using default settings specified by the user.
+  
+  \pkg{rgl} also includes a lower level interface which is described
+  in the \link{rgl.open} help topic.  We recommend that you avoid mixing
+  \code{rgl.*} and \code{*3d} calls.
+
+  See the first example below to display the ChangeLog.
+}
+\seealso{\link{r3d} for a description of the \code{*3d} interface;
+\code{\link{par3d}} for a description of scene properties and the rendering
+pipeline; \code{\link{rgl.useNULL}} for a description of how to 
+use \pkg{rgl} on a system with no graphics support.}
+\examples{
+file.show(system.file("NEWS", package = "rgl"))
+example(surface3d)
+example(plot3d)
+}
+\keyword{dynamic}
diff --git a/man/rgl.Sweave.Rd b/man/rgl.Sweave.Rd
new file mode 100644
index 0000000..113f30d
--- /dev/null
+++ b/man/rgl.Sweave.Rd
@@ -0,0 +1,89 @@
+\name{rgl.Sweave}
+\alias{rgl.Sweave}
+\alias{rgl.Sweave.off}
+\alias{Sweave.snapshot}
+\title{
+Integrating \code{rgl} with \code{Sweave}
+}
+\description{
+As of \R 2.13.0, it is possible to include \code{rgl} graphics into
+a \link{Sweave} document.  These functions support that
+integration.
+}
+\usage{
+Sweave.snapshot()
+rgl.Sweave(name, width, height, options, ...)
+rgl.Sweave.off()
+}
+\arguments{
+  \item{name, width, height, options, ...}{
+These arguments are passed by \code{\link{Sweave}} to \code{rgl.Sweave}
+when it opens the device.
+}
+}
+\details{
+The \code{rgl.Sweave} function is not normally called by the user.  The user
+specifies it as the graphics driver when opening the code chunk, e.g. by
+using
+
+\preformatted{<<fig = TRUE, pdf = FALSE, grdevice = rgl.Sweave, resolution = 100>>=}
+
+When the \code{rgl} device is closed at the end of the code chunk,
+\code{rgl.Sweave.off()} will be called automatically.  It
+will save a snapshot
+of the last image (by default in \file{.png} format) for inclusion in the 
+Sweave document and (by default) close the device.  
+Alternatively, the \code{Sweave.snapshot()} function
+can be called to save the image before the end of the chunk.  Only one
+snapshot will be taken per chunk.
+
+Several chunk options are used by the \code{rgl.Sweave} device:
+\describe{
+\item{stayopen}{(default \code{FALSE}).  If \code{TRUE} then the \code{rgl}
+device will \emph{not} be closed at the end of the chunk,
+instead a call to \code{Sweave.snapshot()}
+will be used if it has not been called explicitly.  Subsequent chunks can add
+to the scene.}
+\item{outputtype}{(default \code{png}).  The output may be specified 
+as \code{outputtype = pdf} or \code{outputtype = eps} instead, in which case
+the \code{\link{rgl.postscript}} function will be used to write output in the
+specified format.  Note that  \code{\link{rgl.postscript}} has limitations
+and does not always render scenes correctly.}
+\item{delay}{(default 0.1).  After creating the display window, \code{\link{Sys.sleep}}
+will be called to delay this many seconds, to allow the display system to 
+initialize.  This is needed in X11 systems which open the display
+asynchronously.  If the default time is too short, \code{rgl.Sweave} may
+falsely report that the window is too large to open.}
+}
+}
+
+\note{
+We recommend turning off all other graphics drivers in a chunk that uses
+\code{grdevice = rgl.Sweave}.  The \code{rgl} functions do not write to
+a standard graphics device.
+}
+
+\note{
+The \code{rgl} package relies on your graphics hardware to render OpenGL scenes,
+and the default \file{.png} output copies a bitmap from the hardware device.  All 
+such devices have limitations on the size of the bitmap, but they do not 
+always signal these limitations in a way that \code{rgl} will detect.  If you find
+that images are not being produced properly, try reducing the size using 
+the \code{resolution}, \code{width} or \code{height} chunk options.
+}
+
+\value{
+These functions are called for their side effects.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{RweaveLatex}} for a description of alternate graphics drivers
+in Sweave, and standard options that can be used in code chunks.  
+
+\code{\link{hook_rgl}}
+and \code{\link{hook_webgl}} allow fixed or interactive \pkg{rgl} scenes to be embedded in \pkg{knitr} 
+documents.
+}
+\keyword{ utilities }
diff --git a/man/rgl.bringtotop.Rd b/man/rgl.bringtotop.Rd
new file mode 100644
index 0000000..ec08ae1
--- /dev/null
+++ b/man/rgl.bringtotop.Rd
@@ -0,0 +1,30 @@
+\name{rgl.bringtotop}
+\alias{rgl.bringtotop}
+\title{Assign focus to an RGL window }
+\description{
+'rgl.bringtotop' brings the current RGL window to the
+front of the window stack (and gives it focus).}
+\usage{
+rgl.bringtotop(stay = FALSE)
+}
+\arguments{
+  \item{stay}{whether to make the window stay on top.}
+}
+\details{
+If \code{stay} is \code{TRUE}, then the window will stay on top
+of normal windows.
+}
+\author{ Ming Chen/Duncan Murdoch }
+\note{not completely implemented for X11 graphics (stay not implemented;
+window managers such as KDE may block this action
+(set "Focus stealing prevention level" to None in Control Center/Window Behavior/Advanced)).
+Not currently implemented under OS/X.}
+#ifdef windows
+\seealso{\code{\link[grDevices]{bringToTop}}}
+#endif
+\examples{
+rgl.open()
+rgl.points(rnorm(1000), rnorm(1000), rnorm(1000), color = heat.colors(1000))
+rgl.bringtotop(stay = TRUE)    
+}
+\keyword{ dynamic }
diff --git a/man/rgl.open.Rd b/man/rgl.open.Rd
new file mode 100644
index 0000000..9297e7a
--- /dev/null
+++ b/man/rgl.open.Rd
@@ -0,0 +1,94 @@
+\name{rgl.open}
+\title{3D visualization device system}
+\alias{rgl.open}
+\alias{rgl.close}
+\alias{rgl.cur}
+\alias{rgl.set}
+\alias{rgl.quit}
+\alias{rgl.init}
+\alias{rgl.antialias}
+\alias{rgl.dev.list}
+\description{
+  3D real-time rendering system.
+}
+\usage{
+# Low level rgl.* interface
+rgl.open(useNULL = rgl.useNULL())     # open new device
+rgl.close()    # close current device
+rgl.cur()      # returns active device ID
+rgl.dev.list() # returns all device IDs
+rgl.set(which, silent = FALSE) # set device as active
+rgl.quit()     # shutdown rgl device system
+rgl.init(initValue = 0, onlyNULL = FALSE)     # re-initialize rgl
+}
+\arguments{
+  \item{useNULL}{whether to open the \dQuote{null} device}
+  \item{which}{device ID}
+  \item{silent}{whether to suppress update of window titles}
+  \item{initValue}{value for internal use only}
+  \item{onlyNULL}{only initialize the null (no display) device}
+}
+\details{
+  The \pkg{rgl} device design is oriented towards the R device metaphor. If you send
+  scene management instructions, and there's no device open, it will be opened
+  automatically.
+  Opened devices automatically get the current device focus. The focus may be
+  changed by using \code{rgl.set()}.
+  \code{rgl.quit()} shuts down the rgl subsystem and all open devices, 
+  detaches the package including the shared library and additional system libraries.
+  
+  The \code{rgl.open()} function attempts to open a new RGL window.
+  If the \code{"rgl.antialias"} option is set, it will be used to
+  select the requested antialiasing.  (See \code{\link{open3d}} for
+  more description of antialiasing and an alternative way to set the
+  value.)
+  
+  If \code{useNULL} is \code{TRUE}, \pkg{rgl} will use a \dQuote{null}
+  device.  This device records objects as they are plotted, but 
+  displays nothing. It is intended for use with \code{\link{writeWebGL}}
+  and similar functions.
+  
+  If \code{rgl.open()} fails (e.g. because X windows is not running, or its
+  \code{DISPLAY} variable is not set properly), then you can retry the initialization
+  by calling \code{rgl.init()}.  Do not do this when windows have 
+  already been successfully opened:  they will be orphaned, with no way to 
+  remove them other than closing R.  In fact, it's probably a good idea not to do this
+  at all:  quitting R and restarting it is a better solution.
+
+  This package also includes a higher level interface which is described
+  in the \link{r3d} help topic.  That interface is designed to act more like
+  classic 2D R graphics.  We recommend that you avoid mixing
+  \code{rgl.*} and \code{*3d} calls.
+
+  See the first example below to display the ChangeLog.
+}
+\value{
+  \code{rgl.open}, \code{rgl.close} and \code{rgl.set} are called for their side effects
+  and return no useful value.  Similarly \code{rgl.init} and \code{rgl.quit} are not designed
+  to return useful values; in fact, users shouldn't call them at all!
+  
+  \code{rgl.cur} returns the currently active devices, or \code{0} if none is
+  active; \code{rgl.dev.list} returns a vector of all open devices.  Both functions name
+  the items according to the type of device:  \code{null} for a hidden null device, 
+  \code{wgl} for a Windows device, and \code{glX} for an X windows device.
+}
+\seealso{
+\link{r3d},
+\code{\link{rgl.clear}}, 
+\code{\link{rgl.pop}},
+\code{\link{rgl.viewpoint}},
+\code{\link{rgl.light}},
+\code{\link{rgl.bg}},
+\code{\link{rgl.bbox}},
+\code{\link{rgl.points}},
+\code{\link{rgl.lines}},
+\code{\link{rgl.triangles}},
+\code{\link{rgl.quads}},
+\code{\link{rgl.texts}},
+\code{\link{rgl.surface}},
+\code{\link{rgl.spheres}},
+\code{\link{rgl.sprites}},
+\code{\link{rgl.snapshot}},
+\code{\link{rgl.useNULL}}
+}
+\keyword{dynamic}
diff --git a/man/rgl.pixels.Rd b/man/rgl.pixels.Rd
new file mode 100644
index 0000000..ee4c267
--- /dev/null
+++ b/man/rgl.pixels.Rd
@@ -0,0 +1,41 @@
+\name{rgl.pixels}
+\alias{rgl.pixels}
+\title{ Extract pixel information from window }
+\description{
+This function extracts single components of the pixel information from the 
+topmost window.
+}
+\usage{
+rgl.pixels(component = c("red", "green", "blue"), 
+        viewport = par3d("viewport"), top = TRUE)
+}
+\arguments{  
+  \item{component}{ Which component(s)? }
+  \item{viewport}{ Lower left corner and size of desired region. }
+  \item{top}{ Whether to bring window to top before reading. }
+}
+\details{
+The possible components are \code{"red"}, \code{"green"}, \code{"blue"}, 
+\code{"alpha"}, \code{"depth"}, and \code{"luminance"} (the sum of the three
+colors).  All are scaled from 0 to 1.
+
+Note that the luminance is kept below 1 by truncating the sum; this is the 
+definition used for the \code{GL_LUMINANCE} component in OpenGL.
+}
+\value{
+A vector, matrix or array containing the desired components.  If one component
+is requested, a vector or matrix will be returned depending on the size of
+block requested (length 1 dimensions are dropped); if more, an array, whose last dimension
+is the list of components.
+}
+\author{ Duncan Murdoch }
+\seealso{ \code{\link{rgl.snapshot}} to write a copy to a file,
+\code{demo("stereo")} for functions that make use of this to draw
+a random dot stereogram and an anaglyph. }
+\examples{
+example(surface3d)
+depth <- rgl.pixels(component = "depth")
+if (length(depth) && is.matrix(depth)) # Protect against empty or single pixel windows
+    contour(depth)
+}
+\keyword{ dynamic }
diff --git a/man/rgl.select.Rd b/man/rgl.select.Rd
new file mode 100644
index 0000000..41c73a0
--- /dev/null
+++ b/man/rgl.select.Rd
@@ -0,0 +1,29 @@
+\name{rgl.select}
+\alias{rgl.select}
+\title{
+Switch to select mode, and return the mouse position selected.
+}
+\description{
+Mostly for internal use, this function temporarily
+installs a handler on a button of the mouse that will 
+return the mouse coordinates of one click and drag rectangle.
+}
+\usage{
+rgl.select(button = c("left", "middle", "right"))
+}
+\arguments{
+  \item{button}{
+Which button to use?
+}
+}
+\value{
+A vector of four coordinates:  the X and Y coordinates of the start and end of the
+dragged rectangle.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{rgl.select3d}}, a version that allows the selection region to be used to
+select points in the scene.
+}
diff --git a/man/rgl.useNULL.Rd b/man/rgl.useNULL.Rd
new file mode 100644
index 0000000..b06c1ce
--- /dev/null
+++ b/man/rgl.useNULL.Rd
@@ -0,0 +1,35 @@
+\name{rgl.useNULL}
+\alias{rgl.useNULL}
+\title{
+Report default use of null device.
+}
+\description{
+This function checks the \code{"rgl.useNULL"} option if present, or the
+\env{RGL_USE_NULL} environment variable if it is not.  If the value is
+\code{TRUE} or a string which matches \dQuote{yes} or \dQuote{true}
+in a case-insensitive test, \code{TRUE} is returned.
+}
+\usage{
+rgl.useNULL()
+}
+\note{
+This function is checked by the initialization code when \pkg{rgl}
+is loaded.  Thus if you want to run \pkg{rgl} on a system where there is no
+graphics support, you should run \code{options(rgl.useNULL = TRUE)}
+or set the environment variable \code{RGL_USE_NULL=TRUE} *before*
+calling \code{library(rgl)} (or other code that 
+loads \pkg{rgl}), and it will not fail in its attempt at initialization.
+}
+\value{
+A logical value indicating the current default for use of the null
+device.
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{open3d}} and \code{\link{rgl.open}}.
+}
+\examples{
+rgl.useNULL()
+}
diff --git a/man/rgl.user2window.Rd b/man/rgl.user2window.Rd
new file mode 100644
index 0000000..d2236ab
--- /dev/null
+++ b/man/rgl.user2window.Rd
@@ -0,0 +1,56 @@
+\name{rgl.user2window}
+\alias{rgl.user2window}
+\alias{rgl.window2user}
+\alias{rgl.projection}
+\title{ Convert between rgl user and window coordinates }
+\description{
+This function converts from 3-dimensional user coordinates
+to 3-dimensional window coordinates.
+}
+\usage{
+rgl.user2window(x, y = NULL, z = NULL, projection = rgl.projection())
+rgl.window2user(x, y = NULL, z = 0, projection = rgl.projection())
+rgl.projection()
+}
+\arguments{
+  \item{x, y, z}{Input coordinates.  Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{projection}{The rgl projection to use }
+}
+\details{
+These functions convert between user coordinates and window coordinates.
+
+Window coordinates run from 0 to 1 in X, Y, and Z.  X runs from 0 on the
+left to 1 on the right; Y runs from 0 at the bottom to 1 at the top;
+Z runs from 0 foremost to 1 in the background.  \code{rgl} does not currently
+display vertices plotted outside of this range, but in normal circumstances will automatically resize the
+display to show them.  In the example below this has been suppressed.
+
+}
+\value{
+The coordinate conversion functions produce a matrix with columns corresponding 
+to the X, Y, and Z coordinates.
+
+\code{rgl.projection()} returns a list containing the following components:
+\item{model}{the modelview matrix}
+\item{projection}{the projection matrix}
+\item{viewport}{the viewport vector}
+
+See \code{\link{par3d}} for more details.
+}
+\author{ Ming Chen / Duncan Murdoch}
+\seealso{\code{\link{select3d}} }
+\examples{
+open3d()
+points3d(rnorm(100), rnorm(100), rnorm(100))
+if (interactive() || !.Platform$OS == "unix") {
+# Calculate a square in the middle of the display and plot it
+square <- rgl.window2user(c(0.25, 0.25, 0.75, 0.75, 0.25), 
+                          c(0.25, 0.75, 0.75, 0.25, 0.25), 0.5)
+par3d(ignoreExtent = TRUE)
+lines3d(square)
+par3d(ignoreExtent = FALSE)
+}
+}
+\keyword{ dynamic }
diff --git a/man/scene.Rd b/man/scene.Rd
new file mode 100644
index 0000000..25d0727
--- /dev/null
+++ b/man/scene.Rd
@@ -0,0 +1,85 @@
+\name{scene}
+\alias{rgl.clear}
+\alias{rgl.pop}
+\alias{clear3d}
+\alias{pop3d}
+\alias{rgl.ids}
+\title{scene management}
+\description{
+Clear shapes, lights, bbox
+}
+\usage{
+clear3d( type = c("shapes", "bboxdeco", "material"), defaults, subscene = 0 ) 
+rgl.clear( type = "shapes", subscene = 0 )
+pop3d( ... )
+rgl.pop( type = "shapes", id = 0 )  
+rgl.ids( type = "shapes", subscene = NA )
+}
+\arguments{
+  \item{type}{Select subtype(s):
+    \describe{
+      \item{"shapes"}{shape stack}
+      \item{"lights"}{light stack}
+      \item{"bboxdeco"}{bounding box}
+      \item{"userviewpoint"}{user viewpoint}
+      \item{"modelviewpoint"}{model viewpoint}
+      \item{"material"}{material properties}
+      \item{"background"}{scene background}
+      \item{"subscene"}{subscene list}
+      \item{"all"}{all of the above}
+    }
+  }
+  \item{defaults}{default values to use after clearing}
+  \item{subscene}{which subscene to work with.  \code{NA} means the current one, 
+                  \code{0} means the whole scene}  
+  \item{id}{vector of ID numbers of items to remove}
+  \item{...}{generic arguments passed through to RGL-specific (or other) functions}
+
+}
+\details{
+RGL holds several lists of objects in each scene. 
+There are lists for shapes, lights, bounding box decorations, subscenes, etc.
+\code{clear3d} and \code{rgl.clear} clear the specified stack, or restore
+the defaults for the bounding box (not visible) or viewpoint. 
+With \code{id = 0} \code{rgl.pop} removes 
+the last added node on the list (except for subscenes:  there it
+removes the active subscene).  The \code{id} argument
+may be used to specify arbitrary item(s) to remove; if \code{id != 0}, 
+the \code{type} argument is ignored.
+
+\code{rgl.clear} and \code{clear3d} may also be used to clear material properties
+back to their defaults.  
+
+\code{clear3d} has an optional \code{defaults} argument, which defaults to 
+\code{\link{r3dDefaults}}.  Only the \code{materials} component of this argument
+is currently used by \code{clear3d}.
+
+\code{rgl.ids} returns a dataframe containing the IDs in the currently active subscene
+by default, or a specified subscene, or if \code{subscene = 0}, in the whole
+rgl window, along with an indicator of their type.
+
+Note that clearing the light stack leaves the scene in darkness; it should normally
+be followed by a call to \code{\link{rgl.light}} or \code{\link{light3d}}.
+}
+\seealso{
+\code{\link{rgl}},
+\code{\link{rgl.bbox}},
+\code{\link{rgl.light}},
+\code{\link{open3d}} to open a new window.
+}
+\examples{
+  x <- rnorm(100)
+  y <- rnorm(100)
+  z <- rnorm(100)
+  p <- plot3d(x, y, z, type = 's')
+  rgl.ids()
+  lines3d(x, y, z)
+  rgl.ids()
+  if (interactive()) {
+    readline("Hit enter to change spheres")
+    rgl.pop(id = p["data"])
+    spheres3d(x, y, z, col = "red", radius = 1/5)
+    box3d()
+  }
+}
+\keyword{dynamic}
diff --git a/man/scene3d.Rd b/man/scene3d.Rd
new file mode 100644
index 0000000..debe88d
--- /dev/null
+++ b/man/scene3d.Rd
@@ -0,0 +1,92 @@
+\name{scene3d}
+\alias{scene3d}
+\alias{rglscene-class}
+\alias{rglobject-class}
+\alias{plot3d.rglscene}
+\alias{plot3d.rglobject}
+\alias{print.rglscene}
+\alias{print.rglobject}
+\title{
+Saves the current scene to a variable, and displays such variables.
+}
+\description{
+This function saves a large part of the RGL state associated with the current
+window to a variable.  
+}
+\usage{
+scene3d()
+\S3method{plot3d}{rglscene}(x, add = FALSE, ...)
+\S3method{plot3d}{rglobject}(x, ...)
+\S3method{print}{rglscene}(x, ...)
+\S3method{print}{rglobject}(x, ...)
+}
+\arguments{
+\item{x}{An object of class \code{"rglscene"}}
+\item{add}{Whether to open a new window, or add to the existing one.}
+\item{...}{Additional parameters, currently ignored.}
+}
+\details{
+The components saved are:  the \code{\link{par3d}} settings, the \code{\link{material3d}}
+settings, the \code{\link{bg3d}} settings, the lights and the objects in the scene.
+
+In most cases, calling \code{\link{plot3d}} on that variable will
+duplicate the scene.  (There are likely to be small differences, mostly internal, but
+some aspects of the scene are not currently available.) If textures are used,
+the name of the texture will be saved, rather than the contents of the 
+texture file.
+
+Other than saving the code
+to recreate a scene, saving the result of \code{scene3d} to 
+a file will allow it to be reproduced later most accurately.  In roughly decreasing order of fidelity,
+\code{\link{writeWebGL}}, \code{\link{writePLY}}, \code{\link{writeOBJ}} and \code{\link{writeSTL}}
+write the scene to a file in formats readable by other software.
+}
+\value{
+The \code{scene3d} function returns an object of class
+\code{"rglscene"}.  This is a list with some or all of the components
+\item{par3d}{The results returned from a \code{\link{par3d}} call.}
+\item{material}{The results returned from a \code{\link{material3d}} call.}
+\item{bg}{A list containing some of the properties of the scene background.}
+\item{bbox}{A list containing some of the properties of the scene bounding box decoration.}
+\item{objects}{A list containing the RGL lights and objects in the scene.}  
+
+The objects in the \code{objects} component are of class
+\code{"rglobject"}.  They are lists containing some or all of the
+components
+\item{id}{The RGL identifier of the object in the original scene.}
+\item{type}{A character variable identifying the type of object.}
+\item{material}{Components of the material that differ from the scene material.}
+\item{vertices, normals, etc.}{Any of the attributes of the object retrievable by \code{\link{rgl.attrib}}.}
+\item{ignoreExtent}{A logical value indicating whether this object contributes to the bounding box.
+Currently this may differ from the object in the original scene.}
+\item{objects}{Sprites may contain other objects; they will be stored here as a list of  \code{"rglobject"}s.}
+
+Lights in the scene are stored similarly, mixed into the \code{objects} list.
+
+The \code{plot3d} methods invisibly return a vector of RGL object ids
+that were plotted.  The \code{print} methods invisibly return the
+object that was printed.
+
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{writeWebGL}}, \code{\link{writePLY}}, \code{\link{writeOBJ}} and \code{\link{writeSTL}}
+write the scene to a file in various formats.
+}
+\examples{
+open3d()
+z <- 2 * volcano        # Exaggerate the relief
+x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
+y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
+persp3d(x, y, z, col = "green3", aspect = "iso")
+
+s <- scene3d()
+# Make it bigger
+s$par3d$windowRect <- 1.5*s$par3d$windowRect
+# and draw it again
+plot3d(s)
+}
+\keyword{ graphics }
+
diff --git a/man/select3d.Rd b/man/select3d.Rd
new file mode 100644
index 0000000..3a901dd
--- /dev/null
+++ b/man/select3d.Rd
@@ -0,0 +1,56 @@
+\name{select3d}
+\alias{select3d}
+\alias{rgl.select3d}
+\title{ Select a rectangle in an RGL scene }
+\description{
+  This function allows the user to use the mouse to
+  select a region in an RGL scene.  
+}
+\usage{
+rgl.select3d(button = c("left", "middle", "right"))
+select3d(...)
+}
+\arguments{
+  \item{ button }{ Which button to use for selection.}
+  \item{ ... }{ Button argument to pass to \code{rgl.select3d}}
+}
+
+\details{
+    
+This function selects 3-dimensional regions by allowing the
+user to use a mouse to draw a rectangle showing
+the projection of the region onto the screen.  It returns
+a function which tests points for inclusion in the selected region.
+
+If the scene is later moved or rotated, the selected region will 
+remain the same, no longer corresponding to a rectangle on the screen.
+  
+}
+\value{
+Returns a function \code{f(x, y, z)} which tests whether each
+of the points \code{(x, y, z)} is in the selected region, returning
+a logical vector.  This function accepts input in a wide
+variety of formats as it uses \code{\link[grDevices]{xyz.coords}} 
+to interpret its parameters.
+}
+\author{ Ming Chen / Duncan Murdoch }
+\seealso{ \code{\link{selectpoints3d}}, \code{\link{locator}} }
+\examples{
+
+# Allow the user to select some points, and then redraw them
+# in a different color
+
+if (interactive()) {
+ x <- rnorm(1000)
+ y <- rnorm(1000)
+ z <- rnorm(1000)
+ open3d()
+ points3d(x, y, z)
+ f <- select3d()
+ keep <- f(x, y, z)
+ rgl.pop()
+ points3d(x[keep], y[keep], z[keep], color = 'red')
+ points3d(x[!keep], y[!keep], z[!keep])
+}
+}
+\keyword{dynamic}
diff --git a/man/selectpoints3d.Rd b/man/selectpoints3d.Rd
new file mode 100644
index 0000000..17233b8
--- /dev/null
+++ b/man/selectpoints3d.Rd
@@ -0,0 +1,93 @@
+\name{selectpoints3d}
+\alias{selectpoints3d}
+\title{
+Select points from a scene
+}
+\description{
+This function uses the \code{\link{select3d}} function to allow the user to choose a
+point or region in the scene, then reports on all the vertices in or near that selection.
+}
+\usage{
+selectpoints3d(objects = rgl.ids()$id, value = TRUE, closest = TRUE, % $
+               multiple = FALSE, ...)
+}
+\arguments{
+  \item{objects}{
+A vector of object id values to use for the search.
+}
+  \item{value}{
+If \code{TRUE}, return the coordinates of the points; otherwise, return
+their indices.
+}
+  \item{closest}{
+If \code{TRUE}, return the points closest to the selection of no points are
+exactly within it.
+}
+  \item{multiple}{
+If \code{TRUE} or a function, do multiple selections.  See the Details below.
+}
+  \item{\dots}{
+Other parameters to pass to \code{\link{select3d}}.
+}
+}
+\details{
+The \code{multiple} argument may be a logical value or a function.  If logical, 
+it controls whether multiple selections will be performed.  If 
+\code{multiple} is \code{FALSE}, a single selection will be performed;
+it might contain multiple points.  If \code{TRUE}, multiple selections 
+will occur and the results will be combined into a single matrix.  
+
+If \code{multiple} is a function, it should take a single argument.
+This function will be called with the argument set to a matrix
+containing newly added rows to the value, i.e. 
+it will contain coordinates of the newly selected points (if 
+\code{value = TRUE}), or the indices of the points (if \code{value =
+FALSE}).  It should return a logical value, \code{TRUE} to indicate
+that selection should continue, \code{FALSE} to indicate that it
+should stop.
+
+In either case, if multiple selections are being performed, the \code{ESC} key will 
+stop the process.
+}
+\value{
+If \code{value} is \code{TRUE}, a 3-column matrix giving the coordinates of the 
+selected points.  All rows in the matrix will be unique even if multiple vertices
+have the same coordinates.
+
+If \code{value} is \code{FALSE}, a 2-column matrix containing columns:
+\item{id}{The object id containing the point.}
+\item{index}{The index of the point within \code{\link{rgl.attrib}(id, "vertices")}.
+If multiple points have the same coordinates, all indices will be returned.}
+
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{select3d}} to return a selection function.
+}
+\examples{
+xyz <- cbind(rnorm(20), rnorm(20), rnorm(20))
+ids <- plot3d( xyz )
+
+if (interactive()) {
+  # Click near a point to select it and put a sphere there.
+  # Press ESC to quit...
+
+  # This version returns coordinates
+  selectpoints3d(ids["data"], 
+     multiple = function(x) {
+        spheres3d(x, color = "red", alpha = 0.3, radius = 0.2)
+        TRUE
+     })
+
+  # This one returns indices
+  selectpoints3d(ids["data"], value = FALSE,
+     multiple = function(ids) {
+        spheres3d(xyz[ids[, "index"], , drop = FALSE], color = "blue", 
+                  alpha = 0.3, radius = 0.2)
+        TRUE
+     })
+}
+}
+\keyword{ graphics }
diff --git a/man/shapelist3d.Rd b/man/shapelist3d.Rd
new file mode 100644
index 0000000..76a0df3
--- /dev/null
+++ b/man/shapelist3d.Rd
@@ -0,0 +1,48 @@
+\name{shapelist3d}
+\alias{shapelist3d}
+\title{ Create and plot a list of shapes }
+\description{
+ These functions create and plot a list of shapes.
+}
+\usage{
+shapelist3d(shapes, x = 0, y = NULL, z = NULL, size = 1, matrix = NULL, override = TRUE, 
+            ..., plot = TRUE)  
+}
+\arguments{
+  \item{shapes}{ A single \code{shape3d} object, or a list of them. }
+  \item{x, y, z}{ Translation(s) to apply }
+  \item{size}{ Scaling(s) to apply }
+  \item{matrix}{ A single matrix transformation, or a list of them. }
+  \item{override}{ Whether the material properties should override the ones in the shapes. }
+  \item{\dots}{ Material properties to apply. }
+  \item{plot}{ Whether to plot the result. }
+}
+\details{
+ \code{shapelist3d} is a quick way to create a complex object made up of simpler ones.
+Each of the arguments \code{shapes} through \code{override} may be a vector of 
+values (a list in the case of \code{shapes} or \code{matrix}).  All values
+will be recycled to produce a list of shapes as long as the longest of them.
+
+The \code{\link{xyz.coords}} function will be used to process the \code{x},
+\code{y} and \code{z} arguments, so a matrix may be used as \code{x} to 
+specify all three.   If a vector is used for \code{x} but \code{y} or \code{z}
+is missing, default values of \code{0} will be used.
+
+The \code{"shapelist3d"} class is simply a list of \code{"shape3d"} objects.
+
+Methods for \code{\link{dot3d}}, \code{\link{wire3d}}, \code{\link{shade3d}},
+\code{\link{translate3d}}, \code{\link{scale3d}}, and \code{\link{rotate3d}}
+are defined for these objects.
+
+}
+\value{
+An object of class \code{c("shapelist3d", "shape3d")}.
+}
+\author{ Duncan Murdoch }
+\seealso{ \code{\link{mesh3d}} }
+\examples{
+ 
+shapelist3d(icosahedron3d(), x = rnorm(10), y = rnorm(10), z = rnorm(10), col = 1:5, size = 0.3)
+
+}
+\keyword{ dynamic }
diff --git a/man/show2d.Rd b/man/show2d.Rd
new file mode 100644
index 0000000..c43248d
--- /dev/null
+++ b/man/show2d.Rd
@@ -0,0 +1,135 @@
+\name{show2d}
+\alias{show2d}
+\title{
+Draw a 2D plot on a rectangle in a 3D scene.
+}
+\description{
+This function uses a bitmap of a standard 2D graphics plot
+as a texture on a quadrilateral.  Default arguments are
+set up so that it will appear on the face of the bounding
+box of the current 3D plot, but optional arguments allow
+it to be placed anywhere in the scene.
+}
+\usage{
+show2d(expression, 
+  face = "z-", line = 0, 
+  reverse = FALSE, rotate = 0, 
+  x = NULL, y = NULL, z = NULL, 
+  width = 480, height = 480, 
+  filename = NULL, 
+  ignoreExtent = TRUE, 
+  color = "white", specular = "black", lit = FALSE, 
+  texmipmap = TRUE, texminfilter = "linear.mipmap.linear",
+  expand = 1.03,
+  texcoords = matrix(c(0, 1, 1, 0, 0, 0, 1, 1), ncol = 2),  ...)
+}
+%- maybe also 'usage' for other objects documented here.
+\arguments{
+  \item{expression}{
+Any plotting commands to produce a plot in standard graphics.
+Ignored if \code{filename} is not \code{NULL}.
+}
+  \item{face}{
+A character string defining which face of the bounding
+box to use.  See Details below.
+}
+  \item{line}{
+How far out from the bounding box should the quadrilateral
+be placed?  Uses same convention as \code{\link{mtext3d}}:
+not lines of text, but fraction of the bounding box size.
+}
+  \item{reverse, rotate}{ 
+Should the image be reversed or rotated?  See Details below.
+}
+  \item{x, y, z}{
+Specific values to use to override \code{face}.
+}
+  \item{width,height}{
+Parameters to pass to \code{\link{png}} when creating the
+bitmap.  See Details below.
+}
+  \item{filename}{
+A \file{.png} file image to use as the texture.
+}
+  \item{ignoreExtent}{
+Whether the quadrilateral should be ignored when computing
+the bounding box of the scene.
+}
+  \item{color, specular, lit, texmipmap, texminfilter, \dots}{
+Material properties to use for the quadrilateral.
+}
+  \item{expand}{Amount by which the quadrilateral is 
+expanded outside the bounding box of the data.
+}
+  \item{texcoords}{Coordinates on the image.  Lower left
+of the bitmap is \code{c(0,0)}, upper right is \code{c(1,1)}.}
+}  
+\details{
+The default arguments are chosen to make it easy to place
+a 2D image on the face of the bounding box.  If \code{x}, 
+\code{y} and \code{z} are \code{NULL} (the defaults),
+\code{face} will be used as a code for one of the
+six faces of the bounding box.  The first letter should
+be \code{"x"}, \code{"y"} or \code{"z"}; this defines 
+the axis perpendicular to the desired face.  If the
+second letter is \code{"-"} or is missing, the face
+will be chosen to be the face with the lower value 
+on that axis.  Any other letter will use the opposite 
+face.
+
+If any of  \code{x}, \code{y} or \code{z} is given, the
+specified value will be used to replace the value calculated 
+above.  Usually four values should be given, corresponding to
+the coordinates of the lower left, lower right, upper right
+and upper left of the destination for the image before
+\code{reverse} and \code{rotate} are used.  Fewer values
+can be used for one or two coordinates; \code{\link{cbind}}
+will be used to put together all 3 coordinates into
+a 4 by 3 matrix (which will be returned as an attribute
+of the result).
+
+The bitmap plot will by default be oriented so that it is
+properly oriented when viewed from the
+direction of the higher values of the perpendicular coordinate,
+and its lower left corner is at the lower value of the two
+remaining coordinates.  The argument \code{reverse} causes
+the orientation to be mirrored, and \code{rotate} causes it
+to be rotated by multiples of 90 degrees.  \code{rotate} should be an integer,
+with \code{0} for no rotation, \code{1} for a 90 degree
+counter-clockwise rotation, etc.
+
+The \code{width} and \code{height} arguments control the shape
+and resolution of the bitmap.  The defaults give a square
+bitmap, which is appropriate with the usual \code{c(1,1,1)}
+aspect ratios (see \code{aspect3d}).  Some tuning may be 
+needed to choose the resoluttion.  The plot will look best when
+displayed at its original size; shrinking it smaller tends to make
+it look faded, while expanding it bigger will make it look 
+blurry.  If \code{filename} is given, the width and height
+will be taken from the file, and \code{width} and \code{height}
+arguments will be ignored.
+}
+\value{
+Invisibly returns the id value of the quadrilateral,
+with the following attributes:
+\item{value}{The value returned by \code{expression}.}
+\item{xyz}{A 4 by 3 matrix giving the coordinates of the corners
+as used in plotting.}
+\item{texcoords}{A 4 by 2 matrix giving the texture coordinates
+of the image.}
+\item{filename}{The filename for the temporary file holding
+the bitmap image.}
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{bgplot3d}} uses a plot as the background for the window.
+}
+\examples{
+example(plot3d, ask = FALSE)
+show2d({
+  par(mar=c(0,0,0,0))
+  plot(x, y, col = rainbow(1000), axes=FALSE)
+  })
+}
\ No newline at end of file
diff --git a/man/snapshot.Rd b/man/snapshot.Rd
new file mode 100644
index 0000000..f7fa4e7
--- /dev/null
+++ b/man/snapshot.Rd
@@ -0,0 +1,58 @@
+\name{rgl.snapshot}
+\alias{rgl.snapshot}
+\alias{snapshot3d}
+\title{export screenshot}
+\description{
+  Saves the screenshot as png file.
+}
+\usage{
+rgl.snapshot( filename, fmt = "png", top = TRUE )
+snapshot3d( ... )
+}
+\arguments{
+  \item{filename}{full path to filename.}
+  \item{fmt}{image export format, currently supported: png }
+  \item{top}{whether to call \code{\link{rgl.bringtotop}}}
+  \item{...}{arguments to pass to \code{rgl.snapshot} }
+}
+\details{
+Animations can be created in a loop modifying the scene and saving 
+each screenshot to a file. Various graphics programs (e.g. ImageMagick)
+can put these together into a single animation. (See \code{\link{movie3d}} or
+the example below.)
+}
+\note{
+On some systems, the snapshot
+will include content from other windows if they cover the active rgl
+window.  Setting \code{top = TRUE} (the default) will use 
+\code{\link{rgl.bringtotop}} before the snapshot
+to avoid this.  (See \url{http://www.opengl.org/resources/faq/technical/rasterization.htm#rast0070}
+for more details.)
+}
+\seealso{\code{\link{movie3d}}, \code{\link{rgl.viewpoint}}}
+
+\examples{
+
+\dontrun{
+
+#
+# create animation
+#
+
+shade3d(oh3d(), color = "red")
+rgl.bringtotop()
+rgl.viewpoint(0, 20)
+
+setwd(tempdir())
+for (i in 1:45) {
+  rgl.viewpoint(i, 20)
+  filename <- paste("pic", formatC(i, digits = 1, flag = "0"), ".png", sep = "")
+  rgl.snapshot(filename)
+}
+## Now run ImageMagick command:
+##    convert -delay 10 *.png -loop 0 pic.gif
+}
+
+}
+
+\keyword{dynamic}
diff --git a/man/spheres.Rd b/man/spheres.Rd
new file mode 100644
index 0000000..5d26837
--- /dev/null
+++ b/man/spheres.Rd
@@ -0,0 +1,43 @@
+\name{spheres3d}
+\alias{rgl.spheres}
+\alias{spheres3d}
+\title{add sphere set shape}
+\description{
+  Adds a sphere set shape node to the scene
+}
+\usage{
+spheres3d(x, y = NULL, z = NULL, radius = 1, ...)
+rgl.spheres(x, y = NULL, z = NULL, radius, ...)
+}
+\arguments{
+  \item{x, y, z}{Numeric vector of point coordinates corresponding to
+   the center of each sphere.  Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{radius}{Vector or single value defining the sphere radius/radii}
+  \item{ ... }{Material properties. See \code{\link{rgl.material}} for details.}
+}
+\details{
+If a non-isometric aspect ratio is chosen, these functions will still draw
+objects that appear to the viewer to be spheres.  Use \code{\link{ellipse3d}} 
+to draw shapes that are spherical in the data scale.
+
+When the scale is not isometric, the radius is measured in an average scale.
+In this case the bounding box calculation is iterative, since rescaling the
+plot changes the shape of the spheres in user-coordinate, which changes
+the bounding box.  Versions of \code{rgl} prior to 0.92.802 did not do 
+this iterative adjustment.
+
+If any coordinate or radius is \code{NA}, the sphere is not plotted.
+} 
+\value{
+  A shape ID of the spheres object is returned.
+}
+\examples{
+open3d()
+spheres3d(rnorm(10), rnorm(10), rnorm(10), radius = runif(10), color = rainbow(10))
+}
+\seealso{
+  \code{\link{rgl.material}}, \code{\link{aspect3d}} for setting non-isometric scales
+}
+\keyword{dynamic}
diff --git a/man/spin3d.Rd b/man/spin3d.Rd
new file mode 100644
index 0000000..ebf4935
--- /dev/null
+++ b/man/spin3d.Rd
@@ -0,0 +1,56 @@
+\name{spin3d}
+\alias{spin3d}
+\title{ Create a function to spin a scene at a fixed rate }
+\description{
+This creates a function to use with \code{\link{play3d}} to
+spin an rgl scene at a fixed rate.
+}
+\usage{
+spin3d(axis = c(0, 0, 1), rpm = 5,
+       dev = rgl.cur(), subscene = currentSubscene3d(dev))
+}
+\arguments{
+  \item{axis}{ The desired axis of rotation }
+  \item{rpm}{ The rotation speed in rotations per minute }
+  \item{dev}{ Which rgl device to use }
+  \item{subscene}{ Which subscene to use }
+}
+\value{
+A function with header \code{function(time, base = M)}, where \code{M}
+is the result of \code{par3d("userMatrix")} at the time the function
+is created.  This function
+calculates and returns a list containing \code{userMatrix} updated by
+spinning the base matrix for \code{time} seconds at \code{rpm} revolutions per
+minute about the specified \code{axis}.
+}
+\author{ Duncan Murdoch }
+\seealso{ \code{\link{play3d}} to play the animation }
+\examples{
+# Spin one object
+open3d()
+plot3d(oh3d(col = "lightblue", alpha = 0.5))
+if (!rgl.useNULL())
+  play3d(spin3d(axis = c(1, 0, 0), rpm = 30), duration = 2)
+
+# Show spinning sprites, and rotate the whole view
+open3d()
+spriteid <- NULL
+
+spin1 <- spin3d(rpm = 4.5 ) # the scene spinner
+spin2 <- spin3d(rpm = 9 ) # the sprite spinner
+
+f <- function(time) {
+    par3d(skipRedraw = TRUE) # stops intermediate redraws
+    on.exit(par3d(skipRedraw = FALSE)) # redraw at the end
+
+    rgl.pop(id = spriteid) # delete the old sprite
+    cubeid <- shade3d(cube3d(), col = "red")
+    spriteid <<- sprites3d(0:1, 0:1, 0:1, shape = cubeid,
+                   userMatrix = spin2(time, 
+                     base = spin1(time)$userMatrix)$userMatrix)
+    spin1(time)
+}
+if (!rgl.useNULL())
+  play3d(f, duration = 2)
+}
+\keyword{ dplot }
diff --git a/man/sprites.Rd b/man/sprites.Rd
new file mode 100644
index 0000000..7ad8afd
--- /dev/null
+++ b/man/sprites.Rd
@@ -0,0 +1,66 @@
+\name{sprites}
+\alias{sprites3d}
+\alias{particles3d}
+\alias{rgl.sprites}
+\title{add sprite set shape}
+\description{
+  Adds a sprite set shape node to the scene.
+}
+\usage{
+sprites3d(x, y = NULL, z = NULL, radius = 1, shapes = NULL, userMatrix, ...)
+particles3d(x, y = NULL, z = NULL, radius = 1, ...)
+rgl.sprites(x, y = NULL, z = NULL, radius = 1, shapes = NULL, userMatrix, ...)
+}
+\arguments{
+  \item{ x, y, z }{point coordinates.  Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{ radius }{vector or single value defining the sphere radius}
+  \item{ shapes }{\code{NULL} for a simple square, or a vector of
+    identifiers of shapes in the scene}
+  \item{ userMatrix }{if \code{shape} is not \code{NULL}, the transformation matrix 
+    for the shapes}
+  \item{ ... }{material properties when \code{shape == 0}, texture mapping is supported}
+}
+\details{
+  Simple sprites (used when \code{shapes} is \code{NULL}) are 1 by 1 squares
+  that are directed towards the viewpoint. Their primary use is for
+  fast (and faked) atmospherical effects, e.g. particles and clouds
+  using alpha blended textures. Particles are Sprites using an alpha-blended 
+  particle texture giving the illusion of clouds and gasses.  
+  The centre of each square will be at the coordinates given by \code{x, y, z}.
+  
+  When \code{shapes} is not \code{NULL}, it should be a vector of
+  identifers of objects to plot in the scene (e.g. as returned by
+  plotting functions or by \code{\link{rgl.ids}}).  These objects will
+  be removed from the scene and duplicated as a sprite image in a
+  constant orientation, as specified by \code{userMatrix}.  The 
+  origin \code{0, 0, 0} will be plotted at the coordinates given by \code{x, y, z}.
+  
+  The \code{userMatrix} argument is ignored for \code{shapes = NULL}.  For
+  shapes, \code{sprites3d} defaults the matrix to \code{r3dDefaults$userMatrix}
+  while \code{rgl.sprites} defaults it to an identity transformation.
+  
+  If any coordinate is \code{NA}, the sprite is not plotted.
+  
+  The id values of the shapes are retrieved using \code{rgl.attrib(id, "ids")};
+  the user matrix is retrieved using \code{rgl.attrib(id, "usermatrix")}.
+}
+\value{
+  These functions are called for the side effect of displaying the sprites.
+  The shape ID of the displayed object is returned.
+}
+\examples{
+open3d()
+particles3d( rnorm(100), rnorm(100), rnorm(100), color = rainbow(100) )
+# is the same as
+sprites3d( rnorm(100), rnorm(100), rnorm(100), color = rainbow(100),
+  lit = FALSE, alpha = .2,
+  textype = "alpha", texture = system.file("textures/particle.png", package = "rgl") )
+sprites3d( rnorm(10) + 6, rnorm(10), rnorm(10), shape = shade3d(tetrahedron3d(), col = "red") )
+}
+\seealso{
+  \code{\link{rgl.material}}
+}
+\keyword{dynamic}
+
diff --git a/man/subdivision3d.Rd b/man/subdivision3d.Rd
new file mode 100644
index 0000000..33f1025
--- /dev/null
+++ b/man/subdivision3d.Rd
@@ -0,0 +1,46 @@
+\name{subdivision3d}
+\alias{subdivision3d}
+\alias{subdivision3d.mesh3d}
+\alias{divide.mesh3d}
+\alias{normalize.mesh3d}
+\alias{deform.mesh3d}
+\title{generic subdivision surface method}
+\description{
+The Subdivision surface algorithm divide and refine (deform) a
+given mesh recursively to certain degree (depth).
+The mesh3d algorithm consists of two stages: divide and deform.
+The divide step generates for each triangle or quad four new triangles or quads, the deform
+step drags the points (refinement step).
+}
+\usage{
+  subdivision3d( x,  ...)
+  \method{subdivision3d}{mesh3d}( x, depth = 1, normalize = FALSE, deform = TRUE, ... )
+  divide.mesh3d(mesh,  vb = mesh$vb, ib = mesh$ib, it = mesh$it )
+  normalize.mesh3d(mesh)
+  deform.mesh3d(mesh, vb = mesh$vb, ib = mesh$ib, it = mesh$it )
+}
+\arguments{
+  \item{x}{3d geometry mesh}
+  \item{mesh}{3d geometry mesh}
+  \item{depth}{recursion depth}
+  \item{normalize}{normalize mesh3d coordinates after division if \code{deform} is \code{TRUE}}
+  \item{deform}{deform mesh}
+  \item{it}{indices for triangular faces}
+  \item{ib}{indices for quad faces}
+  \item{vb}{matrix of vertices: 4xn matrix (rows x, y, z, h) or equivalent
+    vector, where h indicates scaling of each plotted quad}
+  \item{...}{other arguments (unused)}
+}
+\details{
+  Generic subdivision surface method. Currently there exists
+  an algorithm that can be applied on mesh3d objects.
+}
+\examples{
+  open3d()
+  shade3d( subdivision3d( cube3d(), depth = 3 ), color = "red", alpha = 0.5 )
+}
+\seealso{
+  \code{\link{r3d}}
+  \code{\link{mesh3d}}
+}
+\keyword{dynamic}
diff --git a/man/subscene3d.Rd b/man/subscene3d.Rd
new file mode 100644
index 0000000..f461b60
--- /dev/null
+++ b/man/subscene3d.Rd
@@ -0,0 +1,149 @@
+\name{subscene3d}
+\alias{subscene3d}
+\alias{newSubscene3d}
+\alias{currentSubscene3d}
+\alias{useSubscene3d}
+\alias{addToSubscene3d}
+\alias{delFromSubscene3d}
+\alias{gc3d}
+\title{
+Create, select or modify a subscene.
+}
+\description{
+This creates a new subscene, or selects one by \code{id} value, or adds objects to one.
+}
+\usage{
+newSubscene3d(viewport = "replace", projection = "replace", model = "replace", 
+           parent = currentSubscene3d(), 
+           copyLights = TRUE, copyShapes = FALSE, copyBBoxDeco = copyShapes, 
+           copyBackground = FALSE, newviewport,
+           ignoreExtent)
+currentSubscene3d(dev = rgl.cur())
+useSubscene3d(subscene)
+addToSubscene3d(ids, subscene = currentSubscene3d())
+delFromSubscene3d(ids, subscene = currentSubscene3d())
+gc3d(protect = NULL)
+}
+\arguments{
+  \item{viewport, projection, model}{
+How should the new subscene be embedded?  Possible values are
+\code{c("inherit", "modify", "replace")}.  See Details below.
+}
+  \item{parent}{
+The parent subscene (defaults to the current subscene).
+}
+  \item{copyLights, copyShapes, copyBBoxDeco, copyBackground}{
+Whether lights, shapes, bounding box decorations and background should be copied to the new subscene.
+}
+  \item{newviewport}{
+Optionally specify the new subscene's viewport (in pixels).
+}
+  \item{ignoreExtent}{
+Whether to ignore the subscene's bounding box when calculating the parent bounding
+box.  Defaults to \code{TRUE} if \code{model} is not \code{"inherit"}.
+}
+  \item{dev}{
+Which rgl device to query for the current subscene.
+}
+  \item{subscene}{
+Which subscene to use or modify.
+}
+  \item{ids}{
+A vector of integer object ids to add to the subscene.
+}
+  \item{protect}{
+Object ids to protect from this garbage collection.
+}
+}
+\details{
+The rgl package allows multiple windows to be open; each one corresponds to a \dQuote{scene}.
+Within each scene there are one or more \dQuote{subscenes}.  Each subscene corresponds
+to a rectangular region in the window, and may have its own projection and transformation.
+
+There is always a current subscene:  most graphic operations make changes there, e.g. by adding
+an object to it.
+
+The scene \dQuote{owns} objects; \code{addToSubscene3d} and \code{delFromSubscene3d} 
+put their ids into or remove them from the list being displayed within a particular subscene.
+The \code{gc3d} function deletes objects from the scene if they are not visible in any
+subscene, unless they are protected by having their id included in \code{protect}.
+
+The \code{viewport}, \code{projection} and \code{model} parameters each have three possible settings:
+\code{c("inherit", "modify", "replace")}.  \code{"inherit"} means that the corresponding value
+from the parent subscene will be used.  \code{"replace"} means that the new subscene will
+have its own value of the value, independent of its parent.  \code{"modify"} means that the 
+child value will be applied first, and then the parent value will be applied.  For viewport, this
+means that if the parent viewport is changed, the child will maintain its relative position.  For
+the two matrices, \code{"modify"} is unlikely to give satisfactory results, but it is available
+for possible use.
+
+The \code{viewport} parameter controls the rectangular region in which the subscene is displayed.
+It is specified using \code{newviewport} (in pixels relative to the whole window), or set to 
+match the parent viewport.
+
+The \code{projection} parameter controls settings corresponding to the observer.  These
+include the field of view and the zoom; they also include the position of the observer relative to
+the model.  The \code{par3d("projMatrix")} matrix is determined by the projection.
+
+The \code{model} parameter controls settings corresponding to the model.  Mouse rotations affect
+the model, as does scaling.  The \code{par3d("modelMatrix")} matrix is determined by these as
+well as by the position of the observer (since OpenGL assumes that the observer is at
+(0, 0, 0) after the MODELVIEW transformation).  Only those parts concerning the model are
+inherited when \code{model} specifies inheritance, the observer setting is controlled by
+\code{projection}.
+
+If \code{copyBackground} is \code{TRUE}, the background of the newly created child will
+overwrite anything displayed in the parent subscene, regardless of depth.
+}
+\value{
+If successful, each function returns the object id of the subscene, with the exception of
+\code{gc3d}, which returns the count of objects which have been deleted.
+}
+\author{
+Duncan Murdoch and Fang He.
+}
+\seealso{
+\code{\link{subsceneInfo}} for information about a subscene, 
+\code{\link{mfrow3d}} and \code{\link{layout3d}} to set up 
+multiple panes of subscenes.
+}
+\examples{
+
+# Show the Earth with a cutout by using clipplanes in subscenes
+
+lat <- matrix(seq(90, -90, len = 50)*pi/180, 50, 50, byrow = TRUE)
+long <- matrix(seq(-180, 180, len = 50)*pi/180, 50, 50)
+
+r <- 6378.1 # radius of Earth in km
+x <- r*cos(lat)*cos(long)
+y <- r*cos(lat)*sin(long)
+z <- r*sin(lat)
+
+open3d()
+obj <- surface3d(x, y, z, col = "white", 
+       texture = system.file("textures/worldsmall.png", package = "rgl"), 
+       specular = "black", axes = FALSE, box = FALSE, xlab = "", ylab = "", zlab = "",
+       normal_x = x, normal_y = y, normal_z = z)
+       
+cols <- c(rep("chocolate4", 4), rep("burlywood1", 4), "darkgoldenrod1")
+rs <- c(6350, 5639, 4928.5, 4207, 3486, 
+                         (3486 + 2351)/2, 2351, (2351 + 1216)/2, 1216)
+for (i in seq_along(rs)) 
+  obj <- c(obj, spheres3d(0, 0, col = cols[i], radius = rs[i]))
+  
+root <- currentSubscene3d()
+
+newSubscene3d("inherit", "inherit", "inherit", copyShapes = TRUE, parent = root)
+clipplanes3d(1, 0, 0, 0)
+
+newSubscene3d("inherit", "inherit", "inherit", copyShapes = TRUE, parent = root)
+clipplanes3d(0, 1, 0, 0)
+
+newSubscene3d("inherit", "inherit", "inherit", copyShapes = TRUE, parent = root)
+clipplanes3d(0, 0, 1, 0)
+
+# Now delete the objects from the root subscene, to reveal the clipping planes
+useSubscene3d(root)
+delFromSubscene3d(obj)
+}
+\keyword{ graphics }
diff --git a/man/subsceneInfo.Rd b/man/subsceneInfo.Rd
new file mode 100644
index 0000000..5ff3fe4
--- /dev/null
+++ b/man/subsceneInfo.Rd
@@ -0,0 +1,53 @@
+\name{subsceneInfo}
+\alias{subsceneInfo}
+\title{
+Get information on subscenes
+}
+\description{
+This function retrieves information about the tree of subscenes shown in the active
+window.
+}
+\usage{
+subsceneInfo(id = NA, embeddings, recursive = FALSE)
+}
+\arguments{
+  \item{id}{
+Which subscene to report on; \code{NA} is the current subscene.  Set to \code{"root"} for the root.
+}
+  \item{embeddings}{
+Optional new setting for the embeddings for this subscene.
+}
+  \item{recursive}{
+Whether to report on children recursively.
+}
+}
+\details{
+In rgl, each window contains a tree of \dQuote{subscenes}, each containing views of 
+a subset of the objects defined in the window.
+
+Rendering in each subscene depends on the viewport, the projection, and the model
+transformation.  Each of these characteristics may be inherited from the parent 
+(\code{embedding[i] = "inherit"}), may modify the parent (\code{embedding[i] = "modify"}),
+or may replace the parent (\code{embedding[i] == "replace"}).  All three must be
+specified if \code{embeddings} is used.
+}
+\value{
+\item{id}{The object id of the subscene}
+\item{parent}{The object id of the parent subscene, if any}
+\item{children}{If \code{recursive}, a list of the information for the children,
+otherwise just their object ids.}
+\item{embedding}{A vector of 3 components describing how this subscene is
+embedded in its parent.
+}
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{newSubscene3d}}
+}
+\examples{
+example(plot3d)
+subsceneInfo()
+}
+\keyword{ graphics }
diff --git a/man/surface.Rd b/man/surface.Rd
new file mode 100644
index 0000000..0fc58d8
--- /dev/null
+++ b/man/surface.Rd
@@ -0,0 +1,102 @@
+\name{rgl.surface}
+\title{add height-field surface shape}
+\alias{rgl.surface}
+\description{
+  Adds a surface to the current scene. The surface is defined by 
+  a matrix defining the height of each grid point and two vectors
+  defining the grid.
+}
+\usage{
+rgl.surface(x, z, y, coords = 1:3, ..., 
+            normal_x = NULL, normal_y = NULL, normal_z = NULL,
+            texture_s = NULL, texture_t = NULL)
+}
+\arguments{
+  \item{ x }{
+    values corresponding to rows of \code{y}, or matrix of x coordinates
+  }
+  \item{ y }{
+    matrix of height values
+  }
+  \item{ z }{
+    values corresponding to columns of \code{y}, or matrix of z coordinates
+  }
+  \item{ coords }{
+    See details
+  }
+  \item{ ... }{Material and texture properties. See \code{\link{rgl.material}} for details.} 
+  \item{normal_x, normal_y, normal_z}{
+      matrices of the same dimension as \code{y} giving the coordinates of normals at 
+      each grid point}
+  \item{texture_s, texture_t}{
+      matrices of the same dimension as \code{z} giving the coordinates within the current texture
+      of each grid point}
+
+
+}
+\details{
+  Adds a surface mesh to the current scene. The surface is defined by 
+  the matrix of height values in \code{y}, with rows corresponding 
+  to the values in \code{x} and columns corresponding to the values in 
+  \code{z}.
+  
+  The \code{coords} parameter can be used to change the geometric
+  interpretation of \code{x}, \code{y}, and \code{z}.  The first entry 
+  of \code{coords} indicates which coordinate (\code{1 = X}, 
+  \code{2 = Y}, \code{3 = Z}) corresponds to the \code{x} parameter.
+  Similarly the second entry corresponds to the \code{y} parameter,
+  and the third entry to the \code{z} parameter.  In this way 
+  surfaces may be defined over any coordinate plane.
+  
+  If the normals are not supplied, they will be calculated automatically based
+  on neighbouring points.
+  
+  Texture coordinates run from 0 to 1 over each dimension of the texture bitmap.
+  If texture coordinates are not supplied, they will be calculated to 
+  render the texture exactly once over the grid.  Values greater than 1 can be
+  used to repeat the texture over the surface.
+  
+  \code{rgl.surface} always draws the surface with the `front' upwards
+  (i.e. towards higher \code{y} values).  This can be used to render
+  the top and bottom differently; see \code{\link{rgl.material}} and
+  the example below.
+  
+  If the \code{x} or \code{z} argument is a matrix, then it must be of the same
+  dimension as \code{y}, and the values in the matrix will be used for the corresponding
+  coordinates. This is used to plot shapes such as cylinders
+  where y is not a function of x and z.
+  
+  \code{NA} values in the height matrix are not drawn.
+}
+\value{
+  The object ID of the displayed surface is returned invisibly.
+}
+\examples{
+
+#
+# volcano example taken from "persp"
+#
+
+data(volcano)
+
+y <- 2 * volcano        # Exaggerate the relief
+
+x <- 10 * (1:nrow(y))   # 10 meter spacing (S to N)
+z <- 10 * (1:ncol(y))   # 10 meter spacing (E to W)
+
+ylim <- range(y)
+ylen <- ylim[2] - ylim[1] + 1
+
+colorlut <- terrain.colors(ylen) # height color lookup table
+
+col <- colorlut[ y - ylim[1] + 1 ] # assign colors to heights for each point
+
+rgl.open()
+rgl.surface(x, z, y, color = col, back = "lines")
+
+}
+\seealso{
+  \code{\link{rgl.material}}, \code{\link{surface3d}}, \code{\link{terrain3d}}.
+  See \code{\link{persp3d}} for a higher level interface.
+}
+\keyword{dynamic}
diff --git a/man/surface3d.Rd b/man/surface3d.Rd
new file mode 100644
index 0000000..9e5dda2
--- /dev/null
+++ b/man/surface3d.Rd
@@ -0,0 +1,80 @@
+\name{surface3d}
+\title{add height-field surface shape}
+\alias{surface3d}
+\alias{terrain3d}
+\description{
+  Adds a surface to the current scene. The surface is defined by 
+  a matrix defining the height of each grid point and two vectors
+  defining the grid.
+}
+\usage{
+surface3d(x, y, z, ..., normal_x = NULL, normal_y = NULL, normal_z = NULL)
+terrain3d(x, y, z, ..., normal_x = NULL, normal_y = NULL, normal_z = NULL)
+}
+\arguments{
+  \item{ x }{
+    values corresponding to rows of \code{z}, or matrix of x coordinates
+  }
+  \item{ y }{
+    values corresponding to the columns of \code{z}, or matrix of y coordinates
+  }
+  \item{ z }{
+    matrix of heights
+  }
+  \item{ ... }{Material and texture properties. See \code{\link{rgl.material}} for details.}    
+  \item{normal_x, normal_y, normal_z}{
+    matrices of the same dimension as \code{z} giving the coordinates of normals at 
+    each grid point}
+}
+\details{
+  Adds a surface mesh to the current scene. The surface is defined by 
+  the matrix of height values in \code{z}, with rows corresponding 
+  to the values in \code{x} and columns corresponding to the values in 
+  \code{y}.  This is the same parametrization as used in \code{\link{persp}}.
+  
+  If the \code{x} or \code{y} argument is a matrix, then it must be of the same
+  dimension as \code{z}, and the values in the matrix will be used for the corresponding
+  coordinates. This is used to plot shapes such as cylinders
+  where z is not a function of x and y.
+  
+  If the normals are not supplied, they will be calculated automatically based
+  on neighbouring points.
+  
+  \code{surface3d} always draws the surface with the `front' upwards
+  (i.e. towards higher \code{z} values).  This can be used to render
+  the top and bottom differently; see \code{\link{rgl.material}} and
+  the example below.
+  
+  For more flexibility in defining the surface, use \code{\link{rgl.surface}}.
+  
+  \code{surface3d} and \code{terrain3d} are synonyms.
+}
+\examples{
+
+#
+# volcano example taken from "persp"
+#
+
+data(volcano)
+
+z <- 2 * volcano        # Exaggerate the relief
+
+x <- 10 * (1:nrow(z))   # 10 meter spacing (S to N)
+y <- 10 * (1:ncol(z))   # 10 meter spacing (E to W)
+
+zlim <- range(y)
+zlen <- zlim[2] - zlim[1] + 1
+
+colorlut <- terrain.colors(zlen) # height color lookup table
+
+col <- colorlut[ z - zlim[1] + 1 ] # assign colors to heights for each point
+
+open3d()
+surface3d(x, y, z, color = col, back = "lines")
+
+}
+\seealso{
+  \code{\link{rgl.material}}, \code{\link{rgl.surface}}.
+  See \code{\link{persp3d}} for a higher level interface.
+}
+\keyword{dynamic}
diff --git a/man/texts.Rd b/man/texts.Rd
new file mode 100644
index 0000000..34080ec
--- /dev/null
+++ b/man/texts.Rd
@@ -0,0 +1,142 @@
+\name{text3d}
+\alias{rgl.texts}
+\alias{text3d}
+\alias{texts3d}
+\alias{rglFonts}
+\title{add text}
+\description{
+  Adds text to the scene. The text is positioned in 3D space. 
+  Text is always oriented towards the camera.
+}
+\usage{
+rgl.texts(x, y = NULL, z = NULL, text, 
+            adj = 0.5, justify, family = par3d("family"), font = par3d("font"), 
+            cex = par3d("cex"), useFreeType = par3d("useFreeType"), ...)
+text3d(x, y = NULL, z = NULL, texts, adj = 0.5, justify, ...) 
+texts3d(x, y = NULL, z = NULL, texts, adj = 0.5, justify, ...) 
+rglFonts(...)
+}
+\arguments{
+  \item{x, y, z}{point coordinates.  Any reasonable way of defining the
+    coordinates is acceptable.  See the function \code{\link[grDevices]{xyz.coords}}
+    for details.}
+  \item{text}{text character vector to draw}
+  \item{texts}{text character vector to draw}
+  \item{adj}{ one value specifying the horizontal adjustment, or two, 
+              specifying horizontal and vertical adjustment respectively. }.
+  \item{justify}{(deprecated, please use adj instead) character string
+specifying the horizontal adjustment; options are \code{"left"}, \code{"right"},
+    \code{"center"}.
+  }
+  \item{ family }{A device-independent font family name, or "" }
+  \item{ font }{A numeric font number from 1 to 5 }
+  \item{ cex }{A numeric character expansion value }
+  \item{ useFreeType }{logical.  Should FreeType be used to draw text? (See details below.)}
+  \item{ ... }{In \code{rgl.texts}, material properties; see \code{\link{rgl.material}} for details.
+                 In \code{rglFonts}, device dependent font definitions for use with FreeType.
+                 In the other functions, additional parameters to pass to \code{rgl.texts}.}  
+}
+\details{
+The \code{adj} parameter determines the position of the text relative to the 
+specified coordinate.  Use \code{adj = c(0, 0)} to place the left bottom corner at
+\code{(x, y, z)}, \code{adj = c(0.5, 0.5)} to center the text there, and \code{adj = c(1, 1)}
+to put the right top corner there. The optional second coordinate for vertical 
+adjustment defaults to \code{0.5}.  Placement is done using the "advance" of
+the string and the "ascent" of the font relative to the baseline, when these metrics
+are known.
+
+\code{text3d} and \code{texts3d} draw text using the \link{r3d}
+conventions. These are synonyms; the former is singular to be
+consistent with the classic 2-D graphics functions, and the latter is
+plural to be consistent with all the other graphics primitives.  Take
+your choice!
+
+If any coordinate or text is \code{NA}, that text is not plotted.
+}
+\section{Fonts}{
+Fonts are specified using the \code{family}, \code{font}, \code{cex}, 
+and \code{useFreeType} arguments.  Defaults for the currently active
+device may be set using \code{\link{par3d}}, or for future devices
+using \code{\link{r3dDefaults}}.
+
+The \code{family} specification is the same as for standard graphics, i.e.
+families \cr
+\code{c("serif", "sans", "mono", "symbol")} \cr
+are normally
+available, but users may add additional families.  \code{font} numbers
+are restricted to the range 1 to 4 for standard, bold, italic and bold italic
+respectively; with font 5 recoded as family \code{"symbol"} font 1.  
+
+Using an unrecognized value for \code{"family"} will result in
+the system standard font as used in rgl up to version 0.76.  That font
+is not resizable and \code{font} values are ignored.
+
+If \code{useFreeType} is \code{TRUE}, then rgl will use the FreeType
+anti-aliased fonts for drawing.  This is generally desirable, and it is the
+default if rgl was built to support FreeType.  
+
+FreeType fonts are specified using the \code{rglFonts} function.  This function
+takes a vector of four filenames of TrueType font files which
+will be used for the four styles regular, bold, italic and bold italic.  The
+vector is passed with a name to be used as the family name, e.g.
+\code{rglFonts(sans = c("/path/to/FreeSans.ttf", ...}.  In order to 
+limit the file size, \code{rgl} ships with just 3 font files, for 
+regular versions of the \code{serif}, \code{sans} and \code{mono} families.  
+Additional free font files are available from the Amaya project at
+\url{http://dev.w3.org/cvsweb/Amaya/fonts/}.  See the example below for
+how to specify a full set of fonts.
+
+Full pathnames should normally be used to specify font files.  If relative
+paths are used, they are interpreted differently by platform.  Currently
+Windows fonts are looked for in the Windows fonts folder, while other
+platforms use the current working directory.
+
+If FreeType fonts are not used, then bitmapped fonts will be used instead.
+On Windows these will be based on the fonts specified using the 
+#ifdef windows
+\code{\link{windowsFonts}} 
+#endif
+#ifndef windows
+\code{windowsFonts}
+#endif
+function, and are resizable.
+Other platforms will use the default bitmapped font which is not
+resizable.  
+
+Bitmapped fonts have a limited number of characters supported; if any
+unsupported characters are used, an error will be thrown.
+}
+\value{
+  The text drawing functions return the object ID of the text object i
+invisibly.
+
+  \code{rglFonts} returns the current set of font definitions.
+}
+\examples{
+open3d()
+famnum <- rep(1:4, 8)
+family <- c("serif", "sans", "mono", "symbol")[famnum]
+font <- rep(rep(1:4, each = 4), 2)
+cex <- rep(1:2, each = 16)
+text3d(font, cex, famnum, text = paste(family, font), adj = 0.5, 
+       color = "blue", family = family, font = font, cex = cex)
+\dontrun{
+# These FreeType fonts are available from the Amaya project, and are not shipped
+# with rgl.  You would normally install them to the rgl/fonts directory
+# and use fully qualified pathnames, e.g. 
+# system.file("fonts/FreeSerif.ttf", package = "rgl")
+
+rglFonts(serif = c("FreeSerif.ttf", "FreeSerifBold.ttf", "FreeSerifItalic.ttf",
+                 "FreeSerifBoldItalic.ttf"),
+         sans  = c("FreeSans.ttf", "FreeSansBold.ttf", "FreeSansOblique.ttf",
+                 "FreeSansBoldOblique.ttf"),
+         mono  = c("FreeMono.ttf", "FreeMonoBold.ttf", "FreeMonoOblique.ttf",
+                 "FreeMonoBoldOblique.ttf"),
+         symbol= c("ESSTIX10.TTF", "ESSTIX12.TTF", "ESSTIX9_.TTF", 
+                 "ESSTIX11.TTF"))
+} 
+}
+\seealso{
+  \code{\link{r3d}}
+}
+\keyword{dynamic}
diff --git a/man/triangulate.Rd b/man/triangulate.Rd
new file mode 100644
index 0000000..f74cbcb
--- /dev/null
+++ b/man/triangulate.Rd
@@ -0,0 +1,88 @@
+\name{triangulate}
+\alias{triangulate}
+\title{
+Triangulate a two-dimensional polygon.
+}
+\description{
+This algorithm decomposes a general polygon into simple
+polygons and uses the \dQuote{ear-clipping} algorithm to triangulate it.
+Polygons with holes are supported.
+}
+\usage{
+triangulate(x, y = NULL, z = NULL, random = TRUE, plot = FALSE, partial = NA)
+}
+\arguments{
+  \item{x, y, z}{
+Coordinates of a two-dimensional polygon in a format supported by \code{\link{xyz.coords}}.  
+See Details for how \code{z} is handled.
+}
+  \item{random}{
+Whether to use a random or deterministic triangulation.
+}
+  \item{plot}{
+Whether to plot the triangulation; mainly for debugging purposes.
+}
+  \item{partial}{
+If the triangulation fails, should partial results be returned?
+}
+}
+\details{
+Normally \code{triangulate} looks only at the \code{x} and \code{y}
+coordinates.  However, if one of those is constant, it is replaced
+with the \code{z} coordinate if present.
+
+The algorithm works as follows.  First, it breaks the polygon into 
+pieces separated by \code{NA} values in \code{x} or \code{y}.
+Each of these pieces should be a simple, non-self-intersecting
+polygon, separate from the other pieces. 
+(Though some minor exceptions to this rule may work, none
+are guaranteed).  The nesting of these pieces is determined.
+
+The \dQuote{outer} polygon(s) are then merged with the
+polygons that they immediately contain, and each of these
+pieces is triangulated using the ear-clipping algorithm.  
+
+Finally, all the triangulated pieces are put together into one
+result.
+}
+\value{
+A three-by-n array giving the indices of the vertices of 
+each triangle.  (No vertices are added; only the original
+vertices are used in the triangulation.)
+
+The array has an integer vector attribute \code{"nextvert"}
+with one entry per vertex, giving the index of the next 
+vertex to proceed counter-clockwise around outer
+polygon boundaries, clockwise around inner boundaries.
+}
+\references{
+See the Wikipedia article \dQuote{polygon triangulation}
+for a description of the ear-clipping algorithm. 
+}
+\author{
+Duncan Murdoch
+}
+\note{
+Not all inputs will succeed, even when a triangulation is
+possible.  Generally using \code{random = TRUE} will find
+a successful triangulation if one exists, but it may
+occasionally take more than one try.
+}
+\seealso{
+\code{\link{extrude3d}} for a solid extrusion of a polygon, \code{\link{polygon3d}} for
+a flat display; both use \code{triangulate}.
+}
+\examples{
+theta <- seq(0, 2*pi, len = 25)[-25]
+theta <- c(theta, NA, theta, NA, theta, NA, theta, NA, theta)
+r <- c(rep(1.5, 24), NA, rep(0.5, 24), NA, rep(0.5, 24), NA, rep(0.3, 24), NA, rep(0.1, 24))
+dx <- c(rep(0, 24), NA, rep(0.6, 24), NA, rep(-0.6, 24), NA, rep(-0.6, 24), NA, rep(-0.6, 24))
+x <- r*cos(theta) + dx
+y <- r*sin(theta)
+plot(x, y, type = "n")
+polygon(x, y)
+triangulate(x, y, plot = TRUE)
+open3d()
+polygon3d(x, y, x - y, col = "red")
+}
+\keyword{ graphics }
diff --git a/man/turn3d.Rd b/man/turn3d.Rd
new file mode 100644
index 0000000..a597728
--- /dev/null
+++ b/man/turn3d.Rd
@@ -0,0 +1,42 @@
+\name{turn3d}
+\alias{turn3d}
+\title{
+Create a solid of rotation from a two-dimensional curve.
+}
+\description{
+This function \dQuote{turns} the curve (as on a lathe) to form a 
+solid of rotation along the x axis.
+}
+\usage{
+turn3d(x, y = NULL, n = 12, smooth = FALSE, ...)
+}
+\arguments{
+  \item{x, y}{
+Points on the curve, in a form suitable for \code{\link{xy.coords}}.
+The \code{y} values must be non-negative.
+}
+  \item{n}{
+How many steps in the rotation?
+}
+  \item{smooth}{
+logical; whether to add normals for a smooth appearance.
+}
+  \item{...}{
+Additional parameters to pass to \code{\link{tmesh3d}}.
+}
+}
+\value{
+A mesh object containing triangles and/or quadrilaterals.
+}
+\author{
+Fang He and Duncan Murdoch
+}
+\seealso{
+\code{\link{extrude3d}}
+}
+\examples{
+x <- 1:10
+y <- rnorm(10)^2
+shade3d(turn3d(x, y), col = "green")
+}
+\keyword{ graphics }
diff --git a/man/viewpoint.Rd b/man/viewpoint.Rd
new file mode 100644
index 0000000..cb2ac88
--- /dev/null
+++ b/man/viewpoint.Rd
@@ -0,0 +1,65 @@
+\name{viewpoint}
+\alias{rgl.viewpoint}
+\alias{view3d}
+\title{Set up viewpoint}
+\description{
+  Set the viewpoint orientation.
+}
+\usage{
+view3d( theta = 0, phi = 15, ...)
+rgl.viewpoint( theta = 0, phi = 15, fov = 60, zoom = 1, 
+        scale = par3d("scale"), interactive = TRUE, userMatrix, 
+        type = c("userviewpoint", "modelviewpoint") )
+}
+\arguments{
+  \item{theta, phi}{polar coordinates}
+  \item{...}{additional parameters to pass to \code{rgl.viewpoint}}
+  \item{fov}{field-of-view angle in degrees}
+  \item{zoom}{zoom factor}
+  \item{scale}{real length 3 vector specifying the rescaling to apply to each axis}
+  \item{interactive}{logical, specifying if interactive navigation is allowed}
+  \item{userMatrix}{4x4 matrix specifying user point of view}
+  \item{type}{which viewpoint to set?}
+}
+\details{
+The data model can be rotated using the polar coordinates \code{theta}
+and \code{phi}.  Alternatively, it can be set in a completely general way using the 4x4 matrix
+\code{userMatrix}.  If \code{userMatrix} is specified, \code{theta} and \code{phi} are ignored.
+
+The pointing device of your graphics user-interface can also be used to 
+set the viewpoint interactively. With the pointing device the buttons are by default set as follows:
+
+\describe{
+\item{left}{adjust viewpoint position}
+\item{middle}{adjust field of view angle}
+\item{right or wheel}{adjust zoom factor}
+}
+
+The user's view can be set with \code{fov} and \code{zoom}.
+
+If the \code{fov} angle is set to 0, a parallel or orthogonal
+projection is used. Small non-zero values (e.g. 0.01 or less, but not
+0.0) are likely to lead to rendering errors due to OpenGL limitations.
+
+Prior to version 0.94, all of these characteristics were stored in 
+one viewpoint object.  With that release the characteristics are split
+into those that affect the projection (the user viewpoint) and those that
+affect the model (the model viewpoint).  By default, this function
+sets both, but the \code{type} argument can be used to limit the effect.
+
+}
+\seealso{\code{\link{par3d}}}
+\examples{
+\dontrun{
+# animated round trip tour for 10 seconds
+
+rgl.open()
+shade3d(oh3d(), color = "red")
+
+start <- proc.time()[3]
+while ((i <- 36*(proc.time()[3] - start)) < 360) {
+  rgl.viewpoint(i, i/4); 
+}
+}
+}
+\keyword{dynamic}
diff --git a/man/webGLcontrols.Rd b/man/webGLcontrols.Rd
new file mode 100644
index 0000000..4f8547d
--- /dev/null
+++ b/man/webGLcontrols.Rd
@@ -0,0 +1,95 @@
+\name{webGLcontrols}
+\alias{subsetSlider}
+\alias{subsetSetter}
+\alias{clipplaneSlider}
+\alias{toggleButton}
+\title{
+Write HTML/Javascript code to control a WebGL display.
+}
+\description{
+These functions write out HTML code to control WebGL displays on the same page.
+}
+\usage{
+subsetSlider(subsets, labels = names(subsets), 
+             fullset = Reduce(union, subsets),
+             subscenes = currentSubscene3d(), prefixes = "",
+             accumulate = FALSE, ...)
+             
+subsetSetter(subsets, subscenes = currentSubscene3d(), prefixes = "", 
+			 fullset = Reduce(union, subsets),
+                         accumulate = FALSE)
+             
+clipplaneSlider(a=NULL, b=NULL, c=NULL, d=NULL, 
+                plane = 1, clipplaneids, prefixes = "", 
+                labels = signif(values[,1],3), ...)
+             
+toggleButton(subset, subscenes = currentSubscene3d(), prefixes = "", 
+             label = deparse(substitute(subset)), 
+             id = paste0(basename(tempfile("input"))), name = id) 
+}
+\arguments{
+  \item{subsets}{A list of vectors of object identifiers; the slider or setter
+  will choose among them.}
+  \item{labels}{Labels to display corresponding to each subset.  If \code{NULL},
+  numeric labels will be shown.}
+  \item{fullset}{Objects in the subscene which are not in \code{fullset}
+  will not be touched.}
+  \item{subscenes}{The subscenes to be controlled.}  
+  \item{prefixes}{The prefixes of the WebGL scenes to be controlled.}
+  \item{accumulate}{If \code{TRUE}, the subsets will accumulate (by union)
+  as the value increases.}
+  \item{id}{The \code{id} of the input control that will be generated.}
+  \item{name}{The name of the input control that will be generated.}
+  \item{...}{Arguments to pass to \code{\link{propertySlider}}.}
+  \item{a,b,c,d}{The parameter values to change.  Leave as \code{NULL}
+  to hold the parameter constant.}
+  \item{plane, clipplaneids}{The identifier of the particular clipplane
+  to modify.}
+  \item{subset}{The subset that the button should toggle.}
+  \item{label}{The button label.}
+}
+\details{
+\code{subsetSlider} and \code{clipplaneSlider} generate an HTML5 slider 
+control with a text label.  To display no text, set the labels to blanks
+in the \code{...} argument.
+
+\code{subsetSetter} is a low-level function to produce the Javascript
+code used by \code{subsetSlider}.  This code will not touch objects in the
+subscene if they
+are not in \code{fullset}.  \code{fullset} defaults to the union of 
+all the object ids mentioned in \code{subsets}, so by default if an id is 
+not mentioned in one of the subsets, it will not be controlled by the slider.
+
+\code{toggleButton} generates a button that toggles the presence
+of objects within a subscene.  If the first entry in \code{subset}
+is in the subscene, all are deleted, otherwise all are added. 
+
+\code{clipplaneSlider}  allows a clipping plane to be moved to a sequence
+of positions.  Any non-\code{NULL} entries among \code{a, b, c, d} should be
+vectors; the slider will set those parameters of the selected clipping
+plane to corresponding values as the slider is moved.
+}
+\value{
+\code{subsetSetter} returns a length-one character vector
+of class \code{"propertySetter"}.  
+
+The other functions 
+use \code{\link{cat}} to write their output and invisibly return the 
+\code{id} of the control that was generated.
+}
+\author{
+Duncan Murdoch
+}
+
+\seealso{
+\code{\link{writeWebGL}}. See \code{\link{propertySlider}} and \code{\link{propertySetter}}
+for lower level, more flexible functions.
+}
+\examples{
+if (require(rglwidget)) {
+  subsets <- list(1:3, 1:4, 1:5)
+  subsetSlider(subsets = subsets)
+  toggleButton(1:3)
+  clipplaneSlider(d = seq(0, 1, len=20), clipplaneid = 123)
+}
+}
diff --git a/man/writeOBJ.Rd b/man/writeOBJ.Rd
new file mode 100644
index 0000000..423026e
--- /dev/null
+++ b/man/writeOBJ.Rd
@@ -0,0 +1,120 @@
+\name{writeOBJ}
+\alias{writeOBJ}
+\alias{readOBJ}
+\title{
+Write Wavefront OBJ format files; read simple ones
+}
+\description{
+\code{writeOBJ} writes OBJ files.  This is a file format that
+is commonly used in 3D graphics applications.  It does not represent text,
+but does represent points, lines, polygons (and many other types that
+RGL doesn't support).  \code{readOBJ} reads only some parts
+of OBJ files.
+}
+\usage{
+writeOBJ(con, 
+         pointRadius = 0.005, pointShape = icosahedron3d(), 
+         lineRadius = pointRadius, lineSides = 20, 
+         pointsAsPoints = FALSE, linesAsLines = FALSE, 
+         withNormals = TRUE, withTextures = TRUE, 
+         separateObjects = TRUE,
+         ids = NULL)
+readOBJ(con, ...)
+}
+\arguments{
+  \item{con}{
+A connection or filename.
+}
+  \item{pointRadius, lineRadius}{
+The radius of points and lines relative to the overall scale of the figure,
+if they are converted to polyhedra.
+}
+  \item{pointShape}{
+A mesh shape to use for points if they are converted.  It is scaled by the \code{pointRadius}.
+}
+  \item{lineSides}{
+Lines are rendered as cylinders with this many sides.
+}
+  \item{pointsAsPoints, linesAsLines}{
+Whether to convert points and lines to \dQuote{point} and \dQuote{line} records in the OBJ output.
+}
+  \item{withNormals}{
+Whether to output vertex normals for smooth shading.
+}
+  \item{separateObjects}{
+Whether to mark each RGL object as a separate object in the file.
+}
+  \item{withTextures}{
+Whether to output texture coordinates.
+}
+  \item{ids}{
+The identifiers (from \code{\link{rgl.ids}}) of the
+objects to write.  If \code{NULL}, try to write everything.
+}
+
+  \item{...}{
+Additional arguments (typically just \code{material}) to pass to
+\code{\link{tmesh3d}}.
+  }
+
+}
+\details{
+
+The current \code{writeOBJ} implementation only outputs triangles, quads, planes, spheres,
+points, line segments, line strips and surfaces.  It does not output material
+properties such as colors, since the OBJ format does not support the per-vertex
+colors that RGL uses.  
+
+The \code{readOBJ} implementation can
+only read faces, and ignores 
+information about normals and textures.
+
+The defaults for \code{pointsAsPoints} and \code{linesAsLines} have been
+chosen because Blender (\url{http://www.blender.org}) does not import
+points or lines, only polygons.  If you are exporting to other software you
+may want to change them.
+
+If present, texture coordinates are output by default, but the
+textures themselves are not.
+
+Individual RGL objects are output as separate objects in the file when 
+\code{separateObjects = TRUE}, the default.
+
+The output file should be readable by Blender and Meshlab; the latter can write in
+a number of other formats, including U3D, suitable for import into a PDF document.
+}
+\value{
+\code{writeObj} invisibly returns the name of the connection to which the 
+data was written.
+
+\code{readObj} returns a mesh object constructed
+from the input file.
+}
+\references{
+The file format was found at \url{http://www.martinreddy.net/gfx/3d/OBJ.spec}
+on November 11, 2012.  
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{scene3d}} saves a copy of a scene to an R variable;
+\code{\link{writeWebGL}}, \code{\link{writePLY}} and \code{\link{writeSTL}}
+write the scene to a file in various other formats.
+}
+\examples{
+filename <- tempfile(fileext = ".obj")
+open3d()
+shade3d( icosahedron3d() )
+writeOBJ(filename)
+
+# The motivation for writing readObj() was to read this shape
+# file of Comet 67P/Churyumov-Gerasimenko, from the ESA:
+\donttest{
+open3d()
+shade3d(readOBJ(url(
+"http://sci.esa.int/science-e/www/object/doc.cfm?fobjectid=54726"
+), material = list(col = "gray")))
+}
+}
+\keyword{ graphics }
diff --git a/man/writePLY.Rd b/man/writePLY.Rd
new file mode 100644
index 0000000..3a13ec0
--- /dev/null
+++ b/man/writePLY.Rd
@@ -0,0 +1,92 @@
+\name{writePLY}
+\alias{writePLY}
+\title{
+Write Stanford PLY format files
+}
+\description{
+This function writes PLY files.  This is a simple file format that
+is commonly used in 3D printing.  It does not represent text,
+only edges and polygons.  The \code{writePLY} function 
+does the necessary conversions.
+
+}
+\usage{
+writePLY(con, format = c("little_endian", "big_endian", "ascii"), 
+         pointRadius = 0.005, pointShape = icosahedron3d(), 
+         lineRadius = pointRadius, lineSides = 20, 
+         pointsAsEdges = FALSE, linesAsEdges = pointsAsEdges, 
+         withColors = TRUE, withNormals = !(pointsAsEdges || linesAsEdges), 
+         ids = NULL)
+}
+\arguments{
+  \item{con}{
+A connection or filename.
+}
+  \item{format}{
+Which output format.  Defaults to little-endian binary.
+}
+  \item{pointRadius, lineRadius}{
+The radius of points and lines relative to the overall scale of the figure,
+if they are converted to polyhedra.
+}
+  \item{pointShape}{
+A mesh shape to use for points if they are converted.  It is scaled by the \code{pointRadius}.
+}
+  \item{lineSides}{
+Lines are rendered as cylinders with this many sides.
+}
+  \item{pointsAsEdges, linesAsEdges}{
+Whether to convert points and lines to \dQuote{Edge} records in the PLY output.
+}
+  \item{withColors}{
+Whether to output vertex color information.
+}
+  \item{withNormals}{
+Whether to output vertex normals for smooth shading.
+}
+  \item{ids}{
+The identifiers (from \code{\link{rgl.ids}}) of the
+objects to write.  If \code{NULL}, try to write everything.
+}
+
+}
+\details{
+The current implementation only outputs triangles, quads, planes, spheres,
+points, line segments, line strips and surfaces.
+
+The defaults for \code{pointsAsEdges} and \code{linesAsEdges} have been
+chosen because Blender (\url{http://www.blender.org}) does not import
+lines, only polygons.  If you are exporting to other software you
+may want to change them.
+
+Since the PLY format only allows one object per file, all RGL objects
+are combined into a single object when output.
+
+The output file is readable by Blender and Meshlab; the latter can write in
+a number of other formats, including U3D, suitable for import into a PDF document.
+
+}
+\value{
+Invisibly returns the name of the connection to which the 
+data was written.
+}
+\references{
+The file format was found at \url{http://www.mathworks.com/matlabcentral/fx_files/5459/1/content/ply.htm}
+on November 10, 2012.  
+}
+\author{
+Duncan Murdoch
+}
+\seealso{
+\code{\link{scene3d}} saves a copy of a scene to an R variable;
+\code{\link{writeWebGL}}, \code{\link{writeOBJ}} and \code{\link{writeSTL}}
+write the scene to a file in various other formats.
+}
+\examples{
+filename <- tempfile(fileext = ".ply")
+open3d()
+shade3d( icosahedron3d(col = "magenta") )
+writePLY(filename)
+}
+\keyword{ graphics }
+
diff --git a/man/writeWebGL.Rd b/man/writeWebGL.Rd
new file mode 100644
index 0000000..3a1988b
--- /dev/null
+++ b/man/writeWebGL.Rd
@@ -0,0 +1,151 @@
+\name{writeWebGL}
+\alias{writeWebGL}
+\title{
+Write scene to HTML.
+}
+\description{
+Writes the current scene to a collection of files that contain WebGL code to reproduce
+it in a browser.
+}
+\usage{
+writeWebGL(dir = "webGL", filename = file.path(dir, "index.html"), 
+           template = system.file(file.path("WebGL", "template.html"), package = "rgl"),
+           prefix = "",
+           snapshot = TRUE, commonParts = TRUE, reuse = NULL, 
+           font = "Arial", width, height)
+}
+\arguments{
+  \item{dir}{
+  Where to write the files.
+}
+  \item{filename}{
+  The filename to use for the main file.  
+}
+  \item{template}{
+The template web page to which to write the Javascript for the scene.  See Details below.
+}
+  \item{prefix}{
+An optional prefix to use on global identifiers in the scene; use different prefixes
+for different scenes displayed on the same web page.  If not blank, it should be a legal identifier
+in Javascript and HTML.
+}
+  \item{snapshot}{
+  Whether to include a snapshot of the scene, to be displayed in browsers that don't support WebGL, or
+a specification of the snapshot to use.  See
+details below.
+}
+  \item{commonParts}{
+  Whether to include parts that would be common to several
+figures on the same page.  Currently this includes
+a reference to and copy of the \file{CanvasMatrix.js}
+file in the output.
+}
+  \item{reuse}{
+  When writing several figures on the same page, set this
+to a dataframe containing values to reuse.  See the Value section below.
+  }
+  \item{font}{
+  The font to use for text.
+}
+  \item{width, height}{
+  The (optional) width and height in pixels of the image to display.  If omitted,
+the \code{par3d("windowRect")} dimensions will be used.
+}
+}
+\details{
+This function writes out a web page containing Javascript that reconstructs the scene in WebGL.
+
+Use the \code{template} argument to give the filename of a web page that is to contain the
+code for the new scene.  It should contain a single line containing \code{paste0("\%", prefix, "WebGL\%")}, e.g.
+\code{\%WebGL\%} with the default empty prefix.  That line will be replaced by the Javascript and other
+code necessary to reproduce the current scene.  The template may also contain the string \code{"\%rglVersion\%"}
+which will be replaced with the current \pkg{rgl} version number.  If
+\code{template} is \code{NULL}, the output will simply be written directly
+to the main file.
+
+To put more than one scene into a web page, use different values of \code{prefix} for each.  The prefix
+will be used in identifiers in both Javascript and HTML, so it is safest to start with a letter and
+only use alphanumeric characters.
+
+WebGL is a fairly new technology for displaying 3D scenes in browsers.  Most current browsers support it
+to some extent, though it may not be enabled by default; see \url{http://get.webgl.org} for details.  A major
+exception currently is Microsoft's Internet Explorer, though plugins are available.
+
+Currently \code{writeWebGL} has a number of known limitations, some of which will be gradually eliminated as
+development progresses:
+\itemize{
+\item The bounding box decorations are fixed; labels do not move as they do within \R.
+\item User-defined mouse controls are not supported.
+\item No automatic movement (e.g. rotation via \code{\link{spin3d}}) is supported.
+\item Missing values are not handled properly.
+\item Polygons will only be rendered as filled; there is no support in WebGL for wireframe or point rendering.
+\item WebGL browsers generally do not support more than 65535 vertices per
+object.  \code{writeWebGL} will print a warning if this limit is exceeded, but it is up to the user
+to break his scene into smaller objects.  (And 65535 vertices may not be small enough!)
+}
+
+There is some experimental support for modification of the scene by other Javascript code 
+on the same web page.  Currently this is limited to the following.  There will be a global variable
+created with name \code{<prefix>rgl}, where \code{<prefix>} will be replaced by the 
+\code{prefix} argument to \code{writeWebGL}.  Currently this variable will contain properties 
+corresponding to some of the components returned by \code{\link{par3d}}, namely \code{FOV}, \code{zoom},
+\code{userMatrix} and \code{listeners}.  Each of these components should be indexed by a subscene
+number to obtain the value for that subscene; for example, use \code{<prefix>rgl.userMatrix[3]} to obtain
+the user matrix for subscene 3 as a \code{CanvasMatrix4} object (defined in the \file{CanvasMatrix.js}
+library).  After modifying any of these values, user code should insert a call \code{<prefix>rgl.drawScene();}
+to update the display.
+The \code{snapshot} argument can be a logical value
+or a character value.  If logical and \code{FALSE},
+no snapshot will be included.  If \code{TRUE},
+a snapshot will be taken of the current scene
+using \code{\link{snapshot3d}} and included
+in the scene to use when WebGL errors occur.  If \code{snapshot}
+is a character string starting \code{"data:"}, it
+will be assumed to be the result of the \code{\link[knitr]{image_uri}} function.  Otherwise it will be assumed to
+be a filename, and \code{\link[knitr]{image_uri}} will be used
+to embed it in the output page.
+}
+\value{
+The \code{filename} is returned.  If \code{reuse} is not \code{NULL},
+it will have an attribute called \code{"reuse"} which contains a dataframe
+with columns \code{"id"} and \code{"prefix"} identifying the prefix used
+for objects drawn in this scene.  This dataframe can be used as the \code{reuse}
+argument in subsequent calls to \code{writeWebGL}.
+}
+\references{
+\url{http://www.webgl.org}
+}
+\author{
+Duncan Murdoch.
+}
+\note{
+If \code{commonParts} is \code{TRUE}, the output includes a binary copy of
+the CanvasMatrix Javascript library.  This
+file is necessary for the Javascript code written by \code{writeWebGL} to 
+function properly, but only one copy is needed if the output page
+contains multiple \code{writeWebGL} figures.  
+
+Its source (including 
+the copyright notice and license for free use) is included in the file named by
+\code{system.file("htmlwidgets/lib/CanvasMatrix.src.js", package = "rglwidget")}.  
+}
+\seealso{
+\code{\link{scene3d}} saves a copy of a scene to an R variable;
+\code{\link{writePLY}}, \code{\link{writeOBJ}} and \code{\link{writeSTL}}
+write the scene to a file in various other formats.
+}
+\examples{
+if (require(rglwidget)) {
+  plot3d(rnorm(100), rnorm(100), rnorm(100), type = "s", col = "red")
+  # This writes a copy into temporary directory 'webGL', and then displays it
+  filename <- writeWebGL(dir = file.path(tempdir(), "webGL"), 
+                       width = 500, reuse = TRUE)
+  # Display the "reuse" attribute
+  attr(filename, "reuse")
+
+  # Display the scene in a browser
+  if (interactive())
+    browseURL(paste0("file://", filename))
+}
+}
+\keyword{ graphics }
diff --git a/src/ABCLineSet.cpp b/src/ABCLineSet.cpp
new file mode 100644
index 0000000..ea03738
--- /dev/null
+++ b/src/ABCLineSet.cpp
@@ -0,0 +1,101 @@
+#include <algorithm>
+#include "ABCLineSet.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   PlaneSet
+//
+
+ABCLineSet::ABCLineSet(Material& in_material, int in_nbase, double* in_base, int in_ndir, double* in_dir)
+ : 
+   LineSet(in_material,true, false/* true */),
+   nLines(max(in_nbase, in_ndir)),
+   base(in_nbase, in_base), 
+   direction(in_ndir, in_dir)
+{
+  /* We'll set up 1 segment per line.  Each segment has 2 vertices, and each vertex
+     gets 3 color components and 1 alpha component. */
+  ARRAY<int> colors(3*nLines);
+  ARRAY<double> alphas(nLines);
+
+  if (material.colors.getLength() > 1) {
+    material.colors.recycle(nLines); 
+    for (int i=0; i<nLines; i++) {
+      Color color=material.colors.getColor(i);
+      for (int j=0; j<2; j++) {
+        colors.ptr[6*i+3*j+0] = color.getRedub();
+        colors.ptr[6*i+3*j+1] = color.getGreenub();
+        colors.ptr[6*i+3*j+2] = color.getBlueub();
+        alphas.ptr[2*i+j]     = color.getAlphaf();
+      }
+    }
+    material.colors.set(2*nLines, colors.ptr, 2*nLines, alphas.ptr);
+    material.colorPerVertex(true, 2*nLines);  
+  }
+  
+  ARRAY<double> vertices(6*nLines);
+  for (int i=0; i<vertices.size(); i++)
+    vertices.ptr[i] = NA_REAL;
+  initPrimitiveSet(2*nLines, vertices.ptr);
+}
+
+AABox& ABCLineSet::getBoundingBox(Subscene* subscene)
+{
+  updateSegments(subscene->getBoundingBox());
+  return LineSet::getBoundingBox(subscene); 
+}
+
+void ABCLineSet::renderBegin(RenderContext* renderContext)
+{
+  updateSegments(renderContext->subscene->getBoundingBox());
+  invalidateDisplaylist();
+  LineSet::renderBegin(renderContext);
+}
+
+void ABCLineSet::updateSegments(const AABox& sceneBBox)
+{
+  double bbox[2][3] = { {sceneBBox.vmin.x, sceneBBox.vmin.y, sceneBBox.vmin.z},
+                       {sceneBBox.vmax.x, sceneBBox.vmax.y, sceneBBox.vmax.z} };
+  double x[2][3];
+  for (int elem = 0; elem < nLines; elem++) {
+    Vertex bv = base.getRecycled(elem);
+    double b[3] = { bv.x, bv.y, bv.z };
+    Vertex dv = direction.getRecycled(elem);
+    double d[3] = { dv.x, dv.y, dv.z };
+    
+//    Rprintf("bbox min=%f %f %f max=%f %f %f\n", bbox[0][0], bbox[0][1], bbox[0][2],
+//                                                bbox[1][0], bbox[1][1], bbox[1][2]);
+    double smin = R_NegInf, smax = R_PosInf;
+    for (int i=0; i<3; i++)    // which coordinate
+      if (d[i] != 0) {  
+      	double s[2];
+      	for (int j=0; j<2; j++) // which limit
+          s[j] = (bbox[j][i] - b[i])/d[i];
+      	smin = max(smin, min(s[0], s[1]));
+      	smax = min(smax, max(s[0], s[1]));
+      }
+      if (smin <= smax) {
+        for (int k=0; k<3; k++) {
+          x[0][k] = b[k] + smin*d[k];
+          x[1][k] = b[k] + smax*d[k];
+        }
+        setVertex(2*elem + 0, x[0]);
+        setVertex(2*elem + 1, x[1]);
+    } else { 
+      double missing[3] = {NA_REAL, NA_REAL, NA_REAL};
+      setVertex(2*elem + 0, missing);
+      setVertex(2*elem + 1, missing);
+    }
+  }
+}
+
+void ABCLineSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  updateSegments(bbox);
+  LineSet::getAttribute(bbox, attrib, first, count, result);
+}
+
diff --git a/src/ABCLineSet.h b/src/ABCLineSet.h
new file mode 100644
index 0000000..3543065
--- /dev/null
+++ b/src/ABCLineSet.h
@@ -0,0 +1,49 @@
+#ifndef ABCLINESET_H
+#define ABCLINESET_H
+
+#include "scene.h"
+#include "geom.h"
+#include "Shape.h"
+#include "PrimitiveSet.h"
+#include <map>
+
+namespace rgl {
+
+class ABCLineSet : public LineSet {
+private:		/* Use parametrization (x,y,z) + s*(a,b,c) */
+  int		nLines;
+  ARRAY<Vertex> base; /* (x,y,z) */  
+  ARRAY<Vertex> direction; /* (a,b,c) */
+public:
+  ABCLineSet(Material& in_material, int in_nbase, double* in_base, int in_ndir, double* in_dir);
+  
+  /**
+   * tell type.
+   **/
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "abclines", buflen); };
+
+  /**
+   * overload to update segments first.
+   */
+  virtual AABox& getBoundingBox(Subscene* subscene);
+
+  /**
+   * overload to update segments first.
+   */
+  virtual void renderBegin(RenderContext* renderContext);
+
+  /**
+   * update mesh
+   */
+  void updateSegments(const AABox& sceneBBox);
+  
+  /**
+   * update then get attributes 
+   */
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+
+};
+
+} // namespace rgl
+
+#endif // PLANESET_H
diff --git a/src/BBoxDeco.cpp b/src/BBoxDeco.cpp
new file mode 100644
index 0000000..4881006
--- /dev/null
+++ b/src/BBoxDeco.cpp
@@ -0,0 +1,796 @@
+#include "BBoxDeco.h"
+
+#include "gl2ps.h"
+#include "glgui.h"
+#include "scene.h"
+#include <cstdio>
+#include <cmath>
+#include "R.h"
+#include "pretty.h"
+
+#if 0
+// This is debugging code to track down font problems.
+
+#include "R.h"
+
+static GLenum flags[] = {
+GL_ALPHA_TEST ,
+GL_AUTO_NORMAL ,
+GL_MAP2_VERTEX_4,
+GL_BLEND,
+
+GL_CLIP_PLANE0,
+GL_CLIP_PLANE1,
+GL_CLIP_PLANE2,
+GL_COLOR_LOGIC_OP,
+
+GL_COLOR_MATERIAL,
+GL_COLOR_TABLE,
+GL_CONVOLUTION_1D,
+GL_CONVOLUTION_2D,
+
+GL_CULL_FACE,
+GL_DEPTH_TEST,
+GL_DITHER,
+GL_FOG,
+
+GL_HISTOGRAM,
+GL_INDEX_LOGIC_OP,
+GL_LIGHT0,
+GL_LIGHT1,
+
+GL_LIGHT2,
+GL_LIGHTING,
+GL_LINE_SMOOTH,
+GL_LINE_STIPPLE,
+
+GL_MAP1_COLOR_4,
+GL_MAP1_INDEX,
+GL_MAP1_NORMAL,
+GL_MAP1_TEXTURE_COORD_1,
+
+GL_MAP1_TEXTURE_COORD_2,
+GL_MAP1_TEXTURE_COORD_3,
+GL_MAP1_TEXTURE_COORD_4,
+GL_MAP1_VERTEX_3,
+
+GL_MAP1_VERTEX_4,
+GL_MAP2_COLOR_4,
+GL_MAP2_INDEX,
+GL_MAP2_NORMAL,
+
+GL_MAP2_TEXTURE_COORD_1,
+GL_MAP2_TEXTURE_COORD_2,
+GL_MAP2_TEXTURE_COORD_3,
+GL_MAP2_TEXTURE_COORD_4,
+
+GL_MAP2_VERTEX_3,
+GL_MAP2_VERTEX_4,
+GL_MINMAX,
+GL_NORMALIZE,
+
+GL_POINT_SMOOTH,
+GL_POLYGON_OFFSET_FILL,
+GL_POLYGON_OFFSET_LINE,
+GL_POLYGON_OFFSET_POINT,
+
+GL_POINT,
+GL_POLYGON_SMOOTH,
+GL_POLYGON_STIPPLE,
+GL_POST_COLOR_MATRIX_COLOR_TABLE,
+
+GL_POST_CONVOLUTION_COLOR_TABLE,
+GL_RESCALE_NORMAL,
+GL_SEPARABLE_2D,
+GL_SCISSOR_TEST,
+
+GL_STENCIL_TEST,
+GL_TEXTURE_1D,
+GL_TEXTURE_2D,
+GL_TEXTURE_3D,
+
+GL_TEXTURE_GEN_Q,
+GL_TEXTURE_GEN_R,
+GL_TEXTURE_GEN_S,
+GL_TEXTURE_GEN_T};
+
+void Rpf(const char * msg)
+{
+  int flag1=0, flag2 = 0;
+  for (int i=0; i< 32; i++) {
+    GLboolean f;
+    glGetBooleanv( flags[i], &f);
+    if (f) flag1 += (1 << i);
+    glGetBooleanv( flags[i+32], &f);
+    if (f) flag2 += (1 << i);
+    }
+  
+  Rprintf("%s: Flags 0 to 31: %x 32 to 63: %x\n", msg, flag1, flag2);
+  GLint modes[2];
+  glGetIntegerv( GL_POLYGON_MODE, modes);
+  Rprintf("    Polygon modes: %X %X\n", modes[0], modes[1]);
+ }  
+#endif 
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   BBoxDeco
+//
+
+AxisInfo::AxisInfo()
+: textArray()
+{
+  mode  = AXIS_LENGTH;
+  nticks = 0;
+  ticks = NULL;
+  len   = 2;
+  unit  = 0;
+}
+
+AxisInfo::AxisInfo(int in_nticks, double* in_ticks, char** in_texts, int in_len, float in_unit)
+: textArray(in_nticks, in_texts)
+{
+ 
+  int i;
+
+  nticks = in_nticks;
+  len    = in_len;
+  unit   = in_unit;
+  ticks  = NULL;
+
+  if (nticks > 0) {
+
+    mode = AXIS_CUSTOM;
+
+    ticks = new float [nticks];
+
+    for(i=0;i<nticks;i++)
+      ticks[i] = (float) in_ticks[i];
+
+  } else {
+    
+    if (unit > 0)
+      mode = AXIS_UNIT;
+    else if (unit < 0 && len > 0)
+      mode = AXIS_PRETTY;
+    else if (len > 0)
+      mode = AXIS_LENGTH;
+    else
+      mode = AXIS_NONE;
+
+  }
+}
+
+AxisInfo::AxisInfo(AxisInfo& from) 
+: textArray(from.textArray)
+{
+  mode = from.mode;
+  nticks = from.nticks;
+  len  = from.len;
+  unit = from.unit;
+  if (nticks > 0) {
+    ticks = new float [nticks];
+    memcpy (ticks, from.ticks, sizeof(float)*nticks);
+  } else
+    ticks = NULL;
+}
+
+AxisInfo::~AxisInfo()
+{
+  if (ticks) {
+    delete [] ticks;
+  }
+}
+
+void AxisInfo::draw(RenderContext* renderContext, Vertex4& v, Vertex4& dir, Matrix4x4& modelview, 
+                    Vertex& marklen, String& string) {
+
+  Vertex4 p;
+  GLboolean valid;
+    
+  // draw mark ( 1 time ml away )
+
+  p.x = v.x + dir.x * marklen.x;
+  p.y = v.y + dir.y * marklen.y;
+  p.z = v.z + dir.z * marklen.z;  
+  
+  glBegin(GL_LINES);
+  glVertex3f(v.x,v.y,v.z);
+  glVertex3f(p.x,p.y,p.z);
+  glEnd();
+
+  // draw text ( 2 times ml away )
+
+  p.x = v.x + 2 * dir.x * marklen.x;
+  p.y = v.y + 2 * dir.y * marklen.y;
+  p.z = v.z + 2 * dir.z * marklen.z; 
+
+  glRasterPos3f( p.x, p.y, p.z );
+  
+  glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid);
+  if (valid) {  
+    // Work out the text adjustment 
+  
+    float adj = 0.5;  
+    Vertex4 eyedir = modelview * dir;
+    bool  xlarge = fabs(eyedir.x) > fabs(eyedir.y);
+  
+    if (xlarge) {
+      adj = fabs(eyedir.y)/fabs(eyedir.x)/2.0;
+      if (eyedir.x < 0) adj = 1.0 - adj;
+    }
+  
+    if (renderContext->font)
+      renderContext->font->draw(string.text, string.length, adj, 0.5, *renderContext);
+  }      
+
+}
+
+int AxisInfo::getNticks(float low, float high) {
+  switch (mode) {
+
+    case AXIS_CUSTOM: return nticks;
+
+    case AXIS_LENGTH: return len;
+
+    case AXIS_UNIT:   return (high - low)/unit;
+
+    case AXIS_PRETTY: {
+      double lo=low, up=high, shrink_sml=0.75, high_u_fact[2];
+      int ndiv=len, min_n=3, eps_correction=0;
+      int count=0;
+
+      high_u_fact[0] = 1.5;
+      high_u_fact[1] = 2.75;
+      unit = R_pretty0(&lo, &up, &ndiv, min_n, shrink_sml, high_u_fact, 
+			     eps_correction, 0);
+      
+      for (int i=(int)lo; i<=up; i++) {
+	float value = i*unit;
+	if (value >= low && value <= high) 
+	  count++;
+      }
+      return count;
+    }
+  }
+  return 0;
+}
+
+float AxisInfo::getTick(float low, float high, int index) {
+  switch (mode) {
+
+    case AXIS_CUSTOM: return ticks[index];
+
+    case AXIS_LENGTH: {
+      float delta = (len>1) ? (high-low)/(len-1) : 0;
+      return low + delta*(float)index;
+    }
+    case AXIS_UNIT: {
+      float value =  ( (float) ( (int) ( ( low+(unit-1) ) / (unit) ) ) ) * (unit);
+      return value + index*unit;
+    }
+    case AXIS_PRETTY: {
+      double lo=low, up=high, shrink_sml=0.75, high_u_fact[2];
+      int ndiv=len, min_n=3, eps_correction=0;
+      int count=0;
+
+      high_u_fact[0] = 1.5;
+      high_u_fact[1] = 2.75;
+      unit = R_pretty0(&lo, &up, &ndiv, min_n, shrink_sml, high_u_fact, 
+			     eps_correction, 0);
+      
+      for (int i=(int)lo; i<=up; i++) {
+	float value = i*unit;
+	if (value >= low && value <= high) {
+	  if (count == index) return value;
+	  count++;
+	}
+      }
+    }
+  }
+  return NA_REAL;
+}
+    
+struct Side {
+  int vidx[4];
+  Vertex4 normal;
+
+  Side( int i0, int i1, int i2, int i3, Vertex4 v )
+   : normal(v)
+  {
+    vidx[0] = i0;
+    vidx[1] = i1;
+    vidx[2] = i2;
+    vidx[3] = i3;
+  }
+
+};
+
+static Side side[6] = {
+  // BACK
+  Side(0, 2, 3, 1, Vertex4( 0.0f, 0.0f,-1.0f, 0.0f) ),
+
+  // FRONT
+  Side(4, 5, 7, 6, Vertex4( 0.0f, 0.0f, 1.0f, 0.0f) ),
+
+  // LEFT
+  Side(4, 6, 2, 0, Vertex4(-1.0f, 0.0f, 0.0f, 0.0f) ),
+
+  // RIGHT
+  Side(5, 1, 3, 7, Vertex4( 1.0f, 0.0f, 0.0f, 0.0f) ),
+
+  // BOTTOM
+  Side(0, 1, 5, 4, Vertex4( 0.0f,-1.0f, 0.0f, 0.0f) ),
+
+  // TOP
+  Side(6, 7, 3, 2, Vertex4( 0.0f, 1.0f, 0.0f, 0.0f) )
+};
+
+struct Edge{
+  Edge(int in_from, int in_to, Vertex4 in_dir) : from(in_from), to(in_to), dir(in_dir) { }
+  int from, to;
+  Vertex4 dir;
+};
+
+static Edge xaxisedge[4] = { 
+  Edge( 5,4, Vertex4( 0.0f, 0.0f, 1.0f, 0.0f) ), 
+  Edge( 0,1, Vertex4( 0.0f, 0.0f,-1.0f, 0.0f) ),
+  Edge( 6,7, Vertex4( 0.0f, 0.0f, 1.0f, 0.0f) ),
+  Edge( 3,2, Vertex4( 0.0f, 0.0f,-1.0f, 0.0f) )
+};
+static Edge yaxisedge[8] = { 
+  Edge( 5,7, Vertex4( 1.0f, 0.0f, 0.0f, 0.0f) ),
+  Edge( 7,5, Vertex4( 0.0f, 0.0f, 1.0f, 0.0f) ), 
+  Edge( 6,4, Vertex4(-1.0f, 0.0f, 0.0f, 0.0f) ), 
+  Edge( 4,6, Vertex4( 0.0f, 0.0f, 1.0f, 0.0f) ), 
+  Edge( 2,0, Vertex4( 0.0f, 0.0f,-1.0f, 0.0f) ), 
+  Edge( 0,2, Vertex4(-1.0f, 0.0f, 0.0f, 0.0f) ),
+  Edge( 3,1, Vertex4( 1.0f, 0.0f, 0.0f, 0.0f) ), 
+  Edge( 1,3, Vertex4( 0.0f, 0.0f,-1.0f, 0.0f) )
+};
+static Edge zaxisedge[4] = { 
+  Edge( 1,5, Vertex4( 1.0f, 0.0f, 0.0f, 0.0f) ), 
+  Edge( 4,0, Vertex4(-1.0f, 0.0f, 0.0f, 0.0f) ), 
+  Edge( 7,3, Vertex4( 1.0f, 0.0f, 0.0f, 0.0f) ), 
+  Edge( 2,6, Vertex4(-1.0f, 0.0f, 0.0f, 0.0f) ) 
+};
+
+
+AxisInfo BBoxDeco::defaultAxis(0,NULL,NULL,0,5);
+Material BBoxDeco::defaultMaterial( Color(0.6f,0.6f,0.6f,0.5f), Color(1.0f,1.0f,1.0f) );
+
+BBoxDeco::BBoxDeco(Material& in_material, AxisInfo& in_xaxis, AxisInfo& in_yaxis, AxisInfo& in_zaxis, float in_marklen_value, bool in_marklen_fract,
+                   float in_expand, bool in_front)
+: SceneNode(BBOXDECO), material(in_material), xaxis(in_xaxis), yaxis(in_yaxis), zaxis(in_zaxis), marklen_value(in_marklen_value), marklen_fract(in_marklen_fract),
+  expand(in_expand), draw_front(in_front)
+{
+  material.colors.recycle(2);
+}
+
+Vertex BBoxDeco::getMarkLength(const AABox& boundingBox) const
+{
+  return (marklen_fract) ? (boundingBox.vmax - boundingBox.vmin) * (1 / marklen_value) : Vertex(1,1,1) * marklen_value;
+}
+
+AABox BBoxDeco::getBoundingBox(const AABox& in_bbox) const
+{
+  AABox bbox2(in_bbox);
+
+  Vertex marklen = getMarkLength(bbox2);
+
+  Vertex v = marklen * 2;
+
+  bbox2 += bbox2.vmin - v;
+  bbox2 += bbox2.vmax + v;
+
+  return bbox2;
+}
+
+void BBoxDeco::render(RenderContext* renderContext)
+{
+  AABox bbox = renderContext->subscene->getBoundingBox();
+
+  if (bbox.isValid()) {
+  
+    Vertex center = bbox.getCenter();
+    bbox += center + (bbox.vmin - center)*expand;
+    bbox += center + (bbox.vmax - center)*expand;
+
+    // Sphere bsphere(bbox);
+
+    glPushAttrib(GL_ENABLE_BIT);
+
+    int i,j;
+
+    // vertex array:
+
+    Vertex4 boxv[8] = {
+      Vertex4( bbox.vmin.x, bbox.vmin.y, bbox.vmin.z ),
+      Vertex4( bbox.vmax.x, bbox.vmin.y, bbox.vmin.z ),
+      Vertex4( bbox.vmin.x, bbox.vmax.y, bbox.vmin.z ),
+      Vertex4( bbox.vmax.x, bbox.vmax.y, bbox.vmin.z ),
+      Vertex4( bbox.vmin.x, bbox.vmin.y, bbox.vmax.z ),
+      Vertex4( bbox.vmax.x, bbox.vmin.y, bbox.vmax.z ),
+      Vertex4( bbox.vmin.x, bbox.vmax.y, bbox.vmax.z ),
+      Vertex4( bbox.vmax.x, bbox.vmax.y, bbox.vmax.z )
+    };
+
+    Vertex4 eyev[8];
+
+    // transform vertices: used for edge distance criterion and text justification
+
+    Matrix4x4 modelview(renderContext->subscene->modelMatrix);
+
+    for(i=0;i<8;i++)
+      eyev[i] = modelview * boxv[i];
+ 
+    // setup material
+    
+    material.beginUse(renderContext);
+
+    if (material.line_antialias || material.isTransparent()) {
+      // SETUP BLENDING
+      if (renderContext->gl2psActive == GL2PS_NONE) 
+        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+      else
+	gl2psBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+      // ENABLE BLENDING
+      glEnable(GL_BLEND);
+      
+    }
+    
+    // edge adjacent matrix
+
+    int adjacent[8][8] = { { 0 } };
+
+    // draw back faces
+    // construct adjacent matrix
+
+    glBegin(GL_QUADS);
+
+    for(i=0;i<6;i++) {
+
+      const Vertex4 q = modelview * side[i].normal;
+      const Vertex4 view(0.0f,0.0f,1.0f,0.0f);
+      
+      float cos_a = view * q;
+
+      const bool front = (cos_a >= 0.0f) ? true : false;
+
+      if (draw_front || !front) {
+
+        // draw face
+
+        glNormal3f(side[i].normal.x, side[i].normal.y, side[i].normal.z);
+
+        for(j=0;j<4;j++) {
+
+	  if (!front) {
+            // modify adjacent matrix
+
+            int from = side[i].vidx[j];
+            int to   = side[i].vidx[(j+1)%4];
+
+            adjacent[from][to] = 1;
+          }          
+          
+          // feed vertex
+
+          Vertex4& v = boxv[ side[i].vidx[j] ];
+          glVertex3f(v.x, v.y, v.z);
+
+        }
+
+      }
+    }
+
+    glEnd();
+
+    // setup mark length
+
+    Vertex marklen = getMarkLength(bbox);
+
+
+    // draw axis and tickmarks
+    // find contours
+    
+    glDisable(GL_LIGHTING);
+
+    material.useColor(1);
+
+    for(i=0;i<3;i++) {
+
+      Vertex4 v;
+      AxisInfo*  axis;
+      Edge*  axisedge;
+      int    nedges;
+      float* valueptr;
+      float  low, high;
+
+      switch(i)
+      {
+        case 0:
+          axis     = &xaxis;       
+          axisedge = xaxisedge;
+          nedges   = 4;
+          valueptr = &v.x;
+          low      = bbox.vmin.x;
+          high     = bbox.vmax.x;
+          break;
+        case 1:
+          axis     = &yaxis;
+          axisedge = yaxisedge;
+          nedges   = 8;
+          valueptr = &v.y;
+          low      = bbox.vmin.y;
+          high     = bbox.vmax.y;
+          break;
+        case 2:
+	default:
+          axis     = &zaxis;
+          axisedge = zaxisedge;
+          nedges   = 4;
+          valueptr = &v.z;
+          low      = bbox.vmin.z;
+          high     = bbox.vmax.z;
+          break;
+      }
+
+      if (axis->mode == AXIS_NONE)
+        continue;
+
+      // search z-nearest contours
+      
+      float d = FLT_MAX;
+      Edge* edge = NULL;
+
+      for(j=0;j<nedges;j++) {
+  
+        int from = axisedge[j].from;
+        int to   = axisedge[j].to;
+
+        if ((adjacent[from][to] == 1) && (adjacent[to][from] == 0)) {
+
+          // found contour
+          
+          float dtmp = -(eyev[from].z + eyev[to].z)/2.0f;
+
+          if (dtmp < d) {
+  
+            // found near contour
+
+            d = dtmp;
+            edge = &axisedge[j];
+
+          }
+
+        } 
+
+      }
+
+      if (edge) {
+
+        v = boxv[edge->from];
+
+        switch (axis->mode) {
+          case AXIS_CUSTOM:
+            {
+              // draw axis and tickmarks
+
+              StringArrayIterator iter(&axis->textArray);
+
+
+              for (iter.first(), j=0; (j<axis->nticks) && (!iter.isDone());j++, iter.next()) {
+
+                float value = axis->ticks[j];
+
+                // clip marks
+
+                if ((value >= low) && (value <= high)) {
+                
+                  String string = iter.getCurrent();
+                  *valueptr = value;
+                  axis->draw(renderContext, v, edge->dir, modelview, marklen, string);
+                }
+
+              }
+            }
+            break;
+          case AXIS_LENGTH:
+            {
+              float delta = (axis->len>1) ? (high-low)/((axis->len)-1) : 0;
+
+              for(int k=0;k<axis->len;k++)
+              {
+                float value = low + delta * (float)k;
+                
+                *valueptr = value;
+
+                char text[32];
+                sprintf(text, "%.4g", value);
+
+                String string(strlen(text),text);
+
+                axis->draw(renderContext, v, edge->dir, modelview, marklen, string);
+              }
+            }
+            break;
+          case AXIS_UNIT:
+            {
+              float value =  ( (float) ( (int) ( ( low+(axis->unit-1) ) / (axis->unit) ) ) ) * (axis->unit);
+              while(value < high) {
+
+                *valueptr = value;
+
+                char text[32];
+                sprintf(text, "%.4g", value);
+
+                String s (strlen(text),text);
+
+                axis->draw(renderContext, v, edge->dir, modelview, marklen, s );
+
+                value += axis->unit;
+              }
+            }
+            break;
+          case AXIS_PRETTY:
+            {
+              /* These are the defaults from the R pretty() function, except min_n is 3 */
+              double lo=low, up=high, shrink_sml=0.75, high_u_fact[2];
+              int ndiv=axis->len, min_n=3, eps_correction=0;
+              
+              high_u_fact[0] = 1.5;
+              high_u_fact[1] = 2.75;
+              axis->unit = R_pretty0(&lo, &up, &ndiv, min_n, shrink_sml, high_u_fact, 
+                                     eps_correction, 0);
+              
+              for (int i=(int)lo; i<=up; i++) {
+                float value = i*axis->unit;
+		if (value >= low && value <= high) {
+                  *valueptr = value;
+
+                  char text[32];
+                  sprintf(text, "%.4g", value);
+
+                  String s (strlen(text),text);
+
+                  axis->draw(renderContext, v, edge->dir, modelview, marklen, s );
+		}
+              }
+            }
+            break;
+            
+        }
+      }
+    }
+    material.endUse(renderContext);
+    glPopAttrib();
+  }
+}
+
+int BBoxDeco::getAttributeCount(AABox& bbox, AttribID attrib) 
+{
+  switch (attrib) {    
+    case TEXTS: {
+      int count = ((xaxis.mode == AXIS_CUSTOM) ? xaxis.nticks : 0)
+           + ((yaxis.mode == AXIS_CUSTOM) ? yaxis.nticks : 0)
+           + ((zaxis.mode == AXIS_CUSTOM) ? zaxis.nticks : 0);
+      if (count == 0) return 0; 
+    }
+    /* if non-zero, we want labels for every vertex, so fall through. */
+    case VERTICES:
+      return xaxis.getNticks(bbox.vmin.x, bbox.vmax.x)
+           + yaxis.getNticks(bbox.vmin.y, bbox.vmax.y)
+           + zaxis.getNticks(bbox.vmin.z, bbox.vmax.z);
+    case COLORS:
+      return material.colors.getLength();
+    case FLAGS:
+      return 1;
+  }
+  return SceneNode::getAttributeCount(bbox, attrib);
+}
+
+void BBoxDeco::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch(attrib) {
+    case VERTICES:  
+    
+      float low, high;
+      int i, thisn;
+      i = 0;
+     
+      low = bbox.vmin.x;
+      high = bbox.vmax.x;
+      thisn = xaxis.getNticks(low, high);
+      for (int j=0; j<thisn; j++) {
+        if (first <= i && i < n) {
+          *result++ = xaxis.getTick(low, high, j);
+          *result++ = NA_REAL;
+          *result++ = NA_REAL;
+        }
+        i++;  
+      }
+      
+      low = bbox.vmin.y;
+      high = bbox.vmax.y;
+      thisn = yaxis.getNticks(low, high);
+      for (int j=0; j<thisn; j++) {
+        if (first <= i && i < n) {
+          *result++ = NA_REAL;
+          *result++ = yaxis.getTick(low, high, j);
+          *result++ = NA_REAL;
+        }
+        i++;  
+      }
+      
+      low = bbox.vmin.z;
+      high = bbox.vmax.z;
+      thisn = zaxis.getNticks(low, high);
+      for (int j=0; j<thisn; j++) {
+        if (first <= i && i < n) {
+          *result++ = NA_REAL;
+          *result++ = NA_REAL;
+          *result++ = zaxis.getTick(low, high, j);
+        }
+        i++;  
+      }
+      return;
+    case COLORS:
+      while (first < n) {
+	Color color = material.colors.getColor(first);
+	*result++ = color.data[0];
+	*result++ = color.data[1];
+	*result++ = color.data[2];
+	*result++ = color.data[3];
+	first++;
+      }
+      return;
+    case FLAGS:
+      *result++ = (double) draw_front;	
+    }
+    SceneNode::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
+String BBoxDeco::getTextAttribute(AABox& bbox, AttribID attrib, int index)
+{
+  int n = getAttributeCount(bbox, attrib);
+  
+  if (index < n) {
+    int count;
+    switch(attrib) {
+    case TEXTS: 
+      count = xaxis.getNticks(bbox.vmin.x, bbox.vmax.x);
+      if (index < count) {
+        if (xaxis.mode == AXIS_CUSTOM)
+          return xaxis.textArray[index];
+        else
+          return String(0, NULL);
+      }  
+      index -= count;
+      count = yaxis.getNticks(bbox.vmin.y, bbox.vmax.y);
+      if (index < count) {
+        if (yaxis.mode == AXIS_CUSTOM)
+          return yaxis.textArray[index];
+        else
+          return String(0, NULL);
+      }  
+      index -= count;
+      count = zaxis.getNticks(bbox.vmin.z, bbox.vmax.z);
+      if (index < count) {
+        if (zaxis.mode == AXIS_CUSTOM)
+          return zaxis.textArray[index];
+        else
+          return String(0, NULL);
+      }
+    }
+  }
+  return String(0, NULL);
+}
diff --git a/src/BBoxDeco.h b/src/BBoxDeco.h
new file mode 100644
index 0000000..2489722
--- /dev/null
+++ b/src/BBoxDeco.h
@@ -0,0 +1,75 @@
+#ifndef BBOX_DECO_H
+#define BBOX_DECO_H
+
+#include "SceneNode.h"
+
+//
+// CLASS
+//   BBoxDeco
+//
+
+#include "rglmath.h"
+#include "geom.h"
+
+#include "RenderContext.h"
+#include "String.h"
+#include "Material.h"
+
+namespace rgl {
+
+enum {
+  AXIS_CUSTOM,
+  AXIS_LENGTH,
+  AXIS_UNIT,
+  AXIS_PRETTY,
+  AXIS_NONE
+};
+
+struct AxisInfo {
+  AxisInfo();
+  AxisInfo(int in_nticks, double* in_values, char** in_texts, int xlen, float xunit);
+  AxisInfo(AxisInfo& from);
+  ~AxisInfo();
+  void draw(RenderContext* renderContext, Vertex4& v, Vertex4& dir, Matrix4x4& modelview, 
+            Vertex& marklen, String& string);
+            
+  int getNticks(float low, float high);
+  float getTick(float low, float high, int index);
+
+  int    mode;
+  int    nticks;
+  float* ticks;
+  StringArray textArray;
+  int    len;
+  float  unit;
+};
+
+
+class BBoxDeco : public SceneNode 
+{
+public:
+  BBoxDeco(Material& in_material=defaultMaterial, AxisInfo& xaxis=defaultAxis, AxisInfo& yaxis=defaultAxis, AxisInfo& zaxis=defaultAxis, float marklen=15.0, bool marklen_fract=true,
+           float in_expand=1.0, bool in_front=false);
+  void render(RenderContext* renderContext);
+  AABox getBoundingBox(const AABox& boundingBox) const;
+  Vertex getMarkLength(const AABox& boundingBox) const;
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  String  getTextAttribute(AABox& bbox, AttribID attrib, int index);
+  Material* getMaterial()  { return &material; }
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "bboxdeco", buflen); };
+private:
+  Material material;
+  AxisInfo xaxis, yaxis, zaxis;
+  float marklen_value;
+  bool  marklen_fract;
+  float expand;
+  bool  draw_front;
+
+  static Material defaultMaterial;
+  static AxisInfo defaultAxis;
+};
+
+} // namespace rgl
+
+#endif // BBOX_DECO_H
diff --git a/src/Background.cpp b/src/Background.cpp
new file mode 100644
index 0000000..3dd53fd
--- /dev/null
+++ b/src/Background.cpp
@@ -0,0 +1,228 @@
+#include "Background.h"
+#include "Viewpoint.h"
+#include "scene.h"
+#include "rglmath.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Background
+//
+
+Material Background::defaultMaterial( Color(0.3f,0.3f,0.3f), Color(1.0f,0.0f,0.0f) );
+
+Background::Background(Material& in_material, bool in_sphere, int in_fogtype)
+: Shape(in_material, true, BACKGROUND), sphere(in_sphere), fogtype(in_fogtype),
+  quad(NULL)
+{
+  clearColorBuffer = true;
+
+  if (sphere) {
+    material.colors.recycle(2);
+    material.front = Material::CULL_FACE;
+
+    material.colorPerVertex(false);
+
+    if (material.back == Material::FILL_FACE)
+      clearColorBuffer = false;
+
+    if ( (material.lit) || ( (material.texture) && (material.texture->is_envmap() ) ) )
+      sphereMesh.setGenNormal(true);
+    if ( (material.texture) && (!material.texture->is_envmap() ) )
+      sphereMesh.setGenTexCoord(true);
+
+    sphereMesh.setGlobe (16,16);
+
+    sphereMesh.setCenter( Vertex(0.0f,0.0f,0.0f) );
+    sphereMesh.setRadius( 1.0f );
+    sphereMesh.update();
+  }
+  else if (material.texture) {
+    double vertices[12] = { -1, -1, 1,
+                             1, -1, 1,
+                             1,  1, 1,
+                            -1,  1, 1 };
+    double texcoords[8] = { 0, 0, 
+                            1, 0,
+                            1, 1,
+                            0, 1 };
+    material.colorPerVertex(false);
+    material.colors.recycle(1);
+    quad = new QuadSet(material, 4, vertices, NULL, texcoords, true, 0, 1);
+  } else
+    material.colors.recycle(1);    
+}
+
+GLbitfield Background::getClearFlags(RenderContext* renderContext)
+{
+  if (clearColorBuffer) {
+    material.colors.getColor(0).useClearColor();
+    return GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT;
+  } else
+    return GL_DEPTH_BUFFER_BIT;
+}
+
+// FIXME:  this doesn't follow the pattern of other render methods.
+
+void Background::render(RenderContext* renderContext)
+{
+  Subscene* subscene = renderContext->subscene;
+  UserViewpoint* userviewpoint = subscene->getUserViewpoint();
+  
+  const AABox& bbox = subscene->getBoundingBox();
+
+  // setup fog
+  
+  if ((fogtype != FOG_NONE) && (bbox.isValid() )) {
+    // Sphere bsphere(bbox);
+
+    glFogfv(GL_FOG_COLOR, material.colors.getColor(0).getFloatPtr() );
+
+    switch(fogtype) {
+    case FOG_LINEAR:
+      glFogi(GL_FOG_MODE, GL_LINEAR);
+      glFogf(GL_FOG_START, userviewpoint->frustum.znear /*bsphere.radius*2*/);
+      glFogf(GL_FOG_END,   userviewpoint->frustum.zfar /*bsphere.radius*3*/ );
+      break;
+    case FOG_EXP:
+      glFogi(GL_FOG_MODE, GL_EXP);
+      glFogf(GL_FOG_DENSITY, 1.0f/userviewpoint->frustum.zfar /*(bsphere.radius*3)*/ );
+      break;
+    case FOG_EXP2:
+      glFogi(GL_FOG_MODE, GL_EXP2);
+      glFogf(GL_FOG_DENSITY, 1.0f/userviewpoint->frustum.zfar /*(bsphere.radius*3)*/ );
+      break;
+    }
+
+    glEnable(GL_FOG);
+  } else {
+    glDisable(GL_FOG);
+  }
+
+  // render bg sphere 
+  
+  if (sphere) {
+
+    float fov = userviewpoint->getFOV();
+    float hlen, znear;
+    
+    if (fov > 0.0) {
+      float rad = math::deg2rad(fov/2.0f);
+
+      hlen  = math::sin(rad) * math::cos(math::deg2rad(45.0));
+      znear = hlen / math::tan(rad);
+    } else {
+      hlen = math::cos(math::deg2rad(45.0));
+      znear = hlen;
+    }
+    
+    float zfar  = znear + 1.0f;
+    float hwidth, hheight;
+
+    float winwidth  = (float) renderContext->rect.width;
+    float winheight = (float) renderContext->rect.height;
+
+    // aspect ratio
+
+    if (winwidth >= winheight) {
+      hwidth  = hlen;
+      hheight = hlen * (winheight / winwidth);
+    } else {
+      hwidth  = hlen * (winwidth  / winheight);
+      hheight = hlen;
+    }
+
+    glMatrixMode(GL_PROJECTION);
+    glPushMatrix();
+    
+    glLoadIdentity();
+    if (fov != 0.0) {
+      glFrustum(-hwidth, hwidth, -hheight, hheight, znear, zfar );
+    } else {
+      glOrtho(-hwidth, hwidth, -hheight, hheight, znear, zfar );
+    }
+    
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    
+    glLoadIdentity();
+
+    glTranslatef(0.0f,0.0f,-znear);
+
+    ModelViewpoint* modelviewpoint = subscene->getModelViewpoint();
+    modelviewpoint->setupOrientation(renderContext);
+
+    Shape::render(renderContext);
+    glMatrixMode(GL_MODELVIEW); /* just in case... */
+    glPopMatrix();
+    glMatrixMode(GL_PROJECTION);
+    glPopMatrix();
+  } else if (quad) {
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glLoadIdentity();
+    
+    glMatrixMode(GL_PROJECTION);
+    glPushMatrix();
+    glLoadIdentity();
+    
+    quad->draw(renderContext);
+    
+    glMatrixMode(GL_PROJECTION);
+    glPopMatrix();
+    glMatrixMode(GL_MODELVIEW);
+    glPopMatrix();
+  }
+    
+}
+
+void Background::drawElement(RenderContext* renderContext, int index)
+{
+  glPushAttrib(GL_ENABLE_BIT);
+
+  material.beginUse(renderContext);
+  
+  material.useColor(1);
+ 
+  glDisable(GL_DEPTH_TEST);
+  glDepthMask(GL_FALSE);
+
+  sphereMesh.draw(renderContext);
+
+  material.endUse(renderContext);
+
+  glPopAttrib();
+}
+
+int Background::getAttributeCount(AABox& bbox, AttribID attrib) 
+{
+  switch (attrib) {    
+    case FLAGS: return 4;
+  }
+  return Shape::getAttributeCount(bbox, attrib);
+}
+
+void Background::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch(attrib) {
+    case FLAGS:
+      if (first <= 0)  
+        *result++ = (double) sphere;
+      if (first <= 1)
+	*result++ = (double) fogtype == FOG_LINEAR;
+      if (first <= 2)
+	*result++ = (double) fogtype == FOG_EXP;
+      if (first <= 3)
+	*result++ = (double) fogtype == FOG_EXP2;
+      return;
+    }
+    Shape::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
diff --git a/src/Background.h b/src/Background.h
new file mode 100644
index 0000000..2e48572
--- /dev/null
+++ b/src/Background.h
@@ -0,0 +1,47 @@
+#ifndef BACKGROUND_H
+#define BACKGROUND_H
+
+#include "Shape.h"
+#include "opengl.h"
+#include "PrimitiveSet.h"
+#include "SphereMesh.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   Background
+//
+
+class Background : public Shape
+{
+public:
+  enum {
+    FOG_NONE=1, FOG_LINEAR, FOG_EXP, FOG_EXP2
+  };
+  Background( Material& in_material = defaultMaterial, bool sphere=false, int fogtype=FOG_NONE);
+  ~Background() { if (quad) delete quad; };
+  void render(RenderContext* renderContext);
+  int getElementCount(void) { return 1; }
+  void drawElement(RenderContext* renderContext, int index);  
+  GLbitfield getClearFlags(RenderContext* renderContext);
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  void getTypeName(char* buffer, int buflen) { strncpy(buffer, "background", buflen); };
+  
+
+protected:
+  bool clearColorBuffer;
+  bool sphere;
+  int  fogtype;
+  SphereMesh sphereMesh;
+  QuadSet* quad;
+//  GLuint displayList;
+  friend class Scene;
+private:
+  static Material defaultMaterial;
+};
+
+} // namespace rgl
+
+#endif // BACKGROUND_H
diff --git a/src/COPYING.GL2PS b/src/COPYING.GL2PS
new file mode 100644
index 0000000..ff08f6d
--- /dev/null
+++ b/src/COPYING.GL2PS
@@ -0,0 +1,25 @@
+
+                           GL2PS LICENSE
+                      Version 2, November 2003
+
+              Copyright (C) 2003, Christophe Geuzaine
+
+Permission to use, copy, and distribute this software and its
+documentation for any purpose with or without fee is hereby granted,
+provided that the copyright notice appear in all copies and that both
+that copyright notice and this permission notice appear in supporting
+documentation.
+
+Permission to modify and distribute modified versions of this software
+is granted, provided that:
+
+1) the modifications are licensed under the same terms as this
+software;
+
+2) you make available the source code of any modifications that you
+distribute, either on the same media as you distribute any executable
+or other form of this software, or via a mechanism generally accepted
+in the software development community for the electronic transfer of
+data.
+
+This software is provided "as is" without express or implied warranty.
diff --git a/src/ClipPlane.cpp b/src/ClipPlane.cpp
new file mode 100644
index 0000000..4dd87aa
--- /dev/null
+++ b/src/ClipPlane.cpp
@@ -0,0 +1,122 @@
+#include "ClipPlane.h"
+#include "Viewpoint.h"
+#include "R.h"
+#include <algorithm>
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   ClipPlaneSet
+//
+
+int ClipPlaneSet::num_planes = 0;
+
+ClipPlaneSet::ClipPlaneSet(Material& in_material, int in_nnormal, double* in_normal, int in_noffset, double* in_offset)
+ : 
+   Shape(in_material,true),
+   nPlanes(max(in_nnormal, in_noffset)),
+   normal(in_nnormal, in_normal), 
+   offset(in_noffset, in_offset)
+{
+}
+
+int ClipPlaneSet::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) {
+    case NORMALS: 
+    case OFFSETS: return nPlanes;
+  }
+  return 0;
+}
+
+void ClipPlaneSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    if (attrib == NORMALS) {
+      while (first < n) {
+	*result++ = normal.getRecycled(first).x;
+	*result++ = normal.getRecycled(first).y;
+	*result++ = normal.getRecycled(first).z;
+        first++;
+      }
+    } else if (attrib == OFFSETS) {
+	while (first < n) 
+	  *result++ = offset.getRecycled(first++);
+    }
+  }
+}
+
+void ClipPlaneSet::renderBegin(RenderContext* renderContext)
+{
+  firstPlane = GL_CLIP_PLANE0 + num_planes;
+  num_planes += nPlanes;
+}
+
+void ClipPlaneSet::drawElement(RenderContext* renderContext, int index)
+{
+  GLdouble eqn[4];
+  eqn[0] = normal.getRecycled(index).x;
+  eqn[1] = normal.getRecycled(index).y;
+  eqn[2] = normal.getRecycled(index).z;
+  eqn[3] = offset.getRecycled(index);
+  glClipPlane(firstPlane + index, eqn);
+  glEnable(firstPlane + index);
+}
+
+void ClipPlaneSet::enable(bool show)
+{
+  for (int i=0; i<nPlanes; i++) {
+    if (show) glEnable(firstPlane + i);
+    else      glDisable(firstPlane + i);
+  }
+}
+
+void ClipPlaneSet::intersectBBox(AABox& bbox)
+{
+  GLdouble a, b, c, d, a1, b1, c1, d1;
+  for (int j=0; j<3; j++) /* repeat to propagate changes between coordinates */
+  for (int i=0; i<nPlanes; i++) {
+    a = normal.getRecycled(i).x;
+    b = normal.getRecycled(i).y;
+    c = normal.getRecycled(i).z;
+    d = offset.getRecycled(i);
+    b1 = -b/a;
+    c1 = -c/a;
+    d1 = -d/a;
+    if (a > 0) 
+      bbox.vmin.x = getMax(bbox.vmin.x,  b1*(b1 > 0 ? bbox.vmin.y : bbox.vmax.y)
+                                        +c1*(c1 > 0 ? bbox.vmin.z : bbox.vmax.z)
+                                        +d1);
+    else if (a < 0)
+      bbox.vmax.x = getMin(bbox.vmax.x,  b1*(b1 > 0 ? bbox.vmax.y : bbox.vmin.y)
+                                        +c1*(c1 > 0 ? bbox.vmax.z : bbox.vmin.z)
+                                        +d1);
+    a1 = -a/b;
+    c1 = -c/b;
+    d1 = -d/b;
+    if (b > 0) 
+      bbox.vmin.y = getMax(bbox.vmin.y,  a1*(a1 > 0 ? bbox.vmin.x : bbox.vmax.x)
+                                        +c1*(c1 > 0 ? bbox.vmin.z : bbox.vmax.z)
+                                        +d1);
+    else if (b < 0)
+      bbox.vmax.y = getMin(bbox.vmax.y,  a1*(a1 > 0 ? bbox.vmax.x : bbox.vmin.x)
+                                        +c1*(c1 > 0 ? bbox.vmax.z : bbox.vmin.z)
+                                        +d1);
+                                       
+    a1 = -a/c;
+    b1 = -b/c;
+    d1 = -d/c;
+    if (c > 0) 
+      bbox.vmin.z = getMax(bbox.vmin.z,  a1*(a1 > 0 ? bbox.vmin.x : bbox.vmax.x)
+                                        +b1*(b1 > 0 ? bbox.vmin.y : bbox.vmax.y)
+                                        +d1);
+    else if (c < 0)
+      bbox.vmax.z = getMin(bbox.vmax.z,  a1*(a1 > 0 ? bbox.vmax.x : bbox.vmin.x)
+                                        +b1*(b1 > 0 ? bbox.vmax.y : bbox.vmin.y)
+                                        +d1);
+  }
+}
diff --git a/src/ClipPlane.h b/src/ClipPlane.h
new file mode 100644
index 0000000..c732886
--- /dev/null
+++ b/src/ClipPlane.h
@@ -0,0 +1,51 @@
+#ifndef CLIPPLANE_H
+#define CLIPPLANE_H
+
+#include "geom.h"
+#include "Shape.h"
+#include "PrimitiveSet.h"
+#include <map>
+
+namespace rgl {
+
+class ClipPlaneSet : public Shape {
+private:		/* Use parametrization ax + by + cz + d = 0 */
+  int		nPlanes;
+  GLenum	firstPlane;
+  ARRAY<Vertex> normal; /* (a,b,c) */
+  ARRAY<float>  offset; /* d */  
+  
+    
+public:
+  ClipPlaneSet(Material& in_material, int in_nnormal, double* in_normal, int in_noffset, double* in_offset);
+  // ~PlaneSet();
+
+  static int num_planes;  // clip plane count for drawing; set to 0 initially, incremented
+			 // as each plane is added or drawn.
+  
+  /**
+   * tell type.
+   **/
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "clipplanes", buflen); };
+  
+  virtual void renderBegin(RenderContext* renderContext);
+  
+  virtual void drawElement(RenderContext* renderContext, int index);
+  
+  virtual int getElementCount(void) { return nPlanes; }
+
+  virtual int getAttributeCount(AABox& bbox, AttribID attrib);
+  
+  virtual void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+
+  void enable(bool show);  // after it has been drawn, this enables it or disables it
+  
+  bool isClipPlane(void) { return true; }
+  
+  void intersectBBox(AABox& bbox);
+
+};
+
+} // namespace rgl
+
+#endif // CLIPPLANE_H
diff --git a/src/Color.cpp b/src/Color.cpp
new file mode 100644
index 0000000..cf079da
--- /dev/null
+++ b/src/Color.cpp
@@ -0,0 +1,267 @@
+#include "Color.h"
+#include "types.h"
+
+using namespace std;
+#include <cstdlib>
+#include <cstring> // for memcpy
+
+using namespace rgl;
+
+//
+// COLOR UTILS
+//
+
+//
+// FUNCTION
+//   HexCharToNibble
+//
+
+static u8 HexCharToNibble(char c) {
+  u8 nibble = 0;
+
+  if ((c >= '0') && (c <= '9'))
+    nibble = c - '0';
+  else if (( c >= 'A') && (c <= 'F'))
+    nibble = (c - 'A') + 10;
+  else if (( c >= 'a') && (c <= 'f'))
+    nibble = (c - 'a') + 10;
+
+  return nibble;
+}
+
+//
+// FUNCTION
+//   StringToRGB8
+//
+
+static void StringToRGB8(const char* string, u8* colorptr) {
+
+  char* strptr = (char*) string;
+  int cnt = 0;
+
+  if (( *strptr++ == '#') && (cnt < 3)) {
+    char c;
+
+    while( (c = *strptr++) != '\0' ) {
+  
+      u8 component;
+
+      component = (HexCharToNibble(c) << 4);
+      
+      if ( (c = *strptr++) == '\0')
+        break;
+
+      component |= HexCharToNibble(c);
+
+      *colorptr++ = component; cnt++;
+    }
+  }
+
+  for(int i=cnt;i<3;i++)
+    *colorptr++ = 0x00;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Color
+//
+//
+
+Color::Color()
+{
+  data[0] = 1.0f;
+  data[1] = 1.0f;
+  data[2] = 1.0f;
+  data[3] = 1.0f;
+}
+
+Color::Color(float red, float green, float blue, float alpha)
+{
+  data[0] = red;
+  data[1] = green;
+  data[2] = blue;
+  data[3] = alpha;
+}
+
+Color::Color(u8 red, u8 green, u8 blue, u8 alpha)
+{
+  data[0] = ((float)red)/255.0f;
+  data[1] = ((float)green)/255.0f;
+  data[2] = ((float)blue)/255.0f;
+  data[3] = ((float)alpha)/255.0f;
+}
+
+Color::Color(const char* string)
+{
+  u8 tmp[4];
+
+  tmp[3] = 255;
+
+  StringToRGB8(string, tmp);
+  for (int i=0;i<4;i++)
+    data[i] = ((float)tmp[i])/255.0f;
+}
+
+void Color::set3iv(int* color)
+{
+  data[0] = ((float)color[0])/255.0f;
+  data[1] = ((float)color[1])/255.0f;
+  data[2] = ((float)color[2])/255.0f;
+  data[3] = 1.0f;
+}
+
+// TODO: move to rendergl.cpp
+
+#include "opengl.h"
+
+void Color::useClearColor() const
+{
+  glClearColor(data[0],data[1],data[2], data[3]);
+}
+
+void Color::useColor() const
+{
+  glColor4fv(data);
+}
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   ColorArray
+//
+
+ColorArray::ColorArray() 
+{
+  arrayptr = NULL;
+  ncolor   = 0;
+  nalpha   = 0;
+}
+
+ColorArray::ColorArray( Color& bg, Color &fg )
+{
+  ncolor   = 2;
+  nalpha   = 2;
+  arrayptr = (u8*) realloc( NULL, sizeof(u8) * 4 * ncolor);
+  arrayptr[0] = bg.getRedub();
+  arrayptr[1] = bg.getBlueub();
+  arrayptr[2] = bg.getGreenub();
+  arrayptr[3] = bg.getAlphaub();
+  arrayptr[4] = fg.getRedub();
+  arrayptr[5] = fg.getBlueub();
+  arrayptr[6] = fg.getGreenub();
+  arrayptr[7] = fg.getAlphaub();
+  hint_alphablend = ( (bg.getAlphaub() < 255) || (fg.getAlphaub() < 255) ) ? true : false;
+}
+
+ColorArray::ColorArray( ColorArray& src ) {
+  ncolor = src.ncolor;
+  nalpha = src.nalpha;
+  hint_alphablend = src.hint_alphablend;
+  if (ncolor > 0) {
+    arrayptr = (u8*) realloc( NULL, sizeof(u8) * 4 * ncolor);
+    memcpy( arrayptr, src.arrayptr, sizeof(u8) * 4 * ncolor);
+  } else {
+    arrayptr = NULL;
+  }
+}
+
+ColorArray::~ColorArray() {
+  if (arrayptr)
+    free(arrayptr);
+}
+
+void ColorArray::set( int in_ncolor, char** in_color, int in_nalpha, double* in_alpha)
+{
+  ncolor  = getMax(in_ncolor, in_nalpha);
+  nalpha  = in_nalpha;
+  u8* ptr = arrayptr = (u8*) realloc( arrayptr, sizeof(u8) * 4 * ncolor);
+
+  hint_alphablend = false;
+
+  for (unsigned int i=0;i<ncolor;i++) {
+    StringToRGB8(in_color[i%in_ncolor], ptr);
+    if (in_nalpha > 0) {
+      u8 alpha = (u8) ( clamp( (float) in_alpha[i%in_nalpha], 0.0f, 1.0f) * 255.0f );
+      if (alpha < 255)
+        hint_alphablend = true;
+      ptr[3] = alpha;
+    } else
+      ptr[3] = 0xFF;
+    ptr += 4;
+  }
+}
+
+void ColorArray::set( int in_ncolor, int* in_color, int in_nalpha, double* in_alpha)
+{
+  ncolor  = getMax(in_ncolor, in_nalpha);
+  nalpha  = in_nalpha;
+  u8* ptr = arrayptr = (u8*) realloc( arrayptr, sizeof(u8) * 4 * ncolor);
+
+  hint_alphablend = false;
+
+  for (unsigned int i=0;i<ncolor;i++) {
+    int base = (i%in_ncolor) * 3;
+    ptr[0] = (u8) in_color[base];
+    ptr[1] = (u8) in_color[base+1];
+    ptr[2] = (u8) in_color[base+2];
+    if (in_nalpha > 0) {
+      u8 alpha = (u8) ( clamp( (float) in_alpha[i%in_nalpha], 0.0f, 1.0f) * 255.0f );
+      if (alpha < 255)
+        hint_alphablend = true;
+      ptr[3] = alpha;
+    } else
+      ptr[3] = 0xFF;
+    ptr += 4;    
+  }
+}
+
+unsigned int ColorArray::getLength() const
+{
+  return ncolor;
+}
+
+bool ColorArray::hasAlpha() const
+{
+  return hint_alphablend;
+}
+
+void ColorArray::useArray() const
+{
+  glColorPointer(4, GL_UNSIGNED_BYTE, 0, (const GLvoid*) arrayptr );
+}
+
+void ColorArray::useColor(int index) const
+{
+  glColor4ubv( (const GLubyte*) &arrayptr[ index * 4] );
+}
+
+Color ColorArray::getColor(int index) const
+{
+  return Color( arrayptr[index*4], arrayptr[index*4+1], arrayptr[index*4+2], arrayptr[index*4+3] );
+}
+
+void ColorArray::recycle(unsigned int newsize)
+{
+  if (ncolor != newsize) {
+    if (ncolor > 1) {
+
+      if (newsize > 0) {
+        arrayptr = (u8*) realloc(arrayptr, sizeof(u8)*4*newsize);
+
+        for(unsigned int i=ncolor;i<newsize;i++) {
+          int m = (i % ncolor)*4;
+          arrayptr[i*4+0] = arrayptr[ m + 0];
+          arrayptr[i*4+1] = arrayptr[ m + 1];
+          arrayptr[i*4+2] = arrayptr[ m + 2];
+          arrayptr[i*4+3] = arrayptr[ m + 3];
+        }
+      } else 
+        arrayptr = NULL;
+
+      ncolor = newsize;
+    }
+  }
+}
+
diff --git a/src/Color.h b/src/Color.h
new file mode 100644
index 0000000..95c44bc
--- /dev/null
+++ b/src/Color.h
@@ -0,0 +1,75 @@
+#ifndef COLOR_H
+#define COLOR_H
+
+//
+// CLASS
+//   Color
+//
+// IMPLEMENTATION
+//   uses floats as the general format for single colors, clear colors,
+//   lighting and material color properties
+//
+
+#include "types.h"
+
+namespace rgl {
+
+class Color
+{
+public:
+  Color();
+  Color(float red, float green, float blue, float alpha=1.0f);
+  Color(u8 red, u8 green, u8 blue, u8 alpha);
+  Color(const char* string);
+  float  getRedf()   const { return data[0]; }
+  float  getGreenf() const { return data[1]; }
+  float  getBluef()  const { return data[2]; }
+  float  getAlphaf() const { return data[3]; }
+  u8     getRedub()  const { return (u8) (data[0]*255.0f); }
+  u8     getGreenub()const { return (u8) (data[1]*255.0f); }
+  u8     getBlueub() const { return (u8) (data[2]*255.0f); }
+  u8     getAlphaub()const { return (u8) (data[3]*255.0f); }
+  float* getFloatPtr() const { return (float*) data; }
+  /// set by integer ptr
+  void   set3iv(int* color);
+  void useClearColor() const;
+  void useColor() const;
+  float data[4];
+};
+
+//
+// CLASS
+//   ColorArray
+// IMPLEMENTATION
+//   uses unsigned bytes as internal format for mass color datas
+//   carries alpha values
+//
+
+class ColorArray
+{
+public:
+  ColorArray();
+  ColorArray( ColorArray& src );
+  ColorArray( Color& bg, Color& fg );
+  ~ColorArray();
+//  void set( int ncolor, RColor* rcolors, u8 alpha=255 );
+  void set( int ncolor, char** colors, int nalpha, double* alphas );
+  void set( int ncolor, int* colors, int nalpha, double* alphas );
+  void useColor( int index ) const;
+  void useArray() const;
+  unsigned int getLength() const;
+  Color getColor( int index ) const;
+  void recycle( unsigned int newsize );
+  bool hasAlpha() const;
+private:
+  bool hint_alphablend;
+  unsigned int ncolor;
+  unsigned int nalpha;
+  u8* arrayptr;
+  friend class Material;
+};
+
+} // namespace rgl
+
+#endif // COLOR_H
+
diff --git a/src/Device.h b/src/Device.h
new file mode 100644
index 0000000..a3bbc00
--- /dev/null
+++ b/src/Device.h
@@ -0,0 +1,80 @@
+#ifndef RGL_DEVICE_H
+#define RGL_DEVICE_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: Device.h 1436 2016-01-01 15:18:43Z murdoch $
+
+#include "Disposable.h"
+#include "types.h"
+#include "rglview.h"
+
+namespace rgl {
+
+//
+// class Device
+//
+// - display device title
+// - setup the view matrix container (rows and columns of views)
+// - setup the view/scene relation (scene per view -or- shared scene)
+// - manages current view
+// - dispatches scene services to current view's scene
+//
+
+
+class Device : public Disposable, protected IDisposeListener
+{
+public: // -- all methods are blocking until action completed
+
+  Device(int id, bool useNULL);
+  virtual ~Device();
+  int  getID();
+  void setName(const char* string);
+  bool open(void); // -- if failed, instance is invalid and should be deleted
+  void close(void); // -- when done, instance is invalid and should be deleted
+  bool snapshot(int format, const char* filename);
+  bool pixels(int* ll, int* size, int component, double* result);
+  bool postscript(int format, const char* filename, bool drawText);
+
+  bool clear(TypeID stackTypeID);
+  int add(SceneNode* node); // -- return a unique id if successful, or zero if not
+  bool pop(TypeID stackTypeID, int id);
+
+  // accessor method for Scene, modeled after getBoundingBox()
+  // from scene.h
+  Scene* getScene() const { return scene; }
+
+  void bringToTop(int stay);
+
+  RGLView* getRGLView(void);
+  
+  int getIgnoreExtent(void);
+  void setIgnoreExtent(int in_ignoreExtent);  
+  int getSkipRedraw(void);
+  void setSkipRedraw(int in_skipRedraw);
+  
+  void setWindowRect(int left, int top, int right, int bottom);
+  void getWindowRect(int *left, int *top, int *right, int *bottom);
+  
+  void getFonts(FontArray& outfonts, int nfonts, char** family, int* style, double* cex, 
+                bool useFreeType);
+  const char* getDevtype(void);
+
+// event handlers
+protected:
+  void notifyDisposed(Disposable* disposable);
+private:
+  void update(void);
+
+  Window* window;
+  RGLView* rglview;
+  Scene* scene;
+  const char* devtype;
+  int    id_;
+};
+
+} // namespace rgl
+
+#endif // RGL_DEVICE_H
+
diff --git a/src/DeviceManager.h b/src/DeviceManager.h
new file mode 100644
index 0000000..388079f
--- /dev/null
+++ b/src/DeviceManager.h
@@ -0,0 +1,52 @@
+#ifndef RGL_DEVICE_MANAGER_H
+#define RGL_DEVICE_MANAGER_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: DeviceManager.h 1115 2014-07-18 13:51:22Z murdoch $
+
+#include "Device.h"
+
+#include <list>
+
+namespace rgl {
+
+/**
+ * Manager component that is used as a front-end for multiple devices access
+ * using an 'id' to set the current device.
+ **/
+class DeviceManager : protected IDisposeListener {
+
+public:
+  DeviceManager(bool in_useNULLDevice);	
+  virtual ~DeviceManager();
+  bool    openDevice(bool useNULL);
+  Device* getCurrentDevice(void);
+  Device* getAnyDevice(void);
+  Device* getDevice(int id);
+  bool    setCurrent(int id, bool silent = false);
+  int     getCurrent();
+  int     getDeviceCount();
+  void   getDeviceIds(int *buffer, int bufsize);
+protected:
+  /**
+   * Dispose Listener implementation
+   **/
+  void notifyDisposed(Disposable*);
+private:
+  void    nextDevice();
+  void    previousDevice();
+  typedef std::list<Device*> Container;
+  typedef Container::iterator Iterator;
+
+  int       newID;
+  Container devices;
+  Iterator  current; 
+  bool	    useNULLDevice;
+};
+
+} // namespace rgl
+
+#endif // DEVICE_MANAGER_H
+
diff --git a/src/Disposable.cpp b/src/Disposable.cpp
new file mode 100644
index 0000000..5af143e
--- /dev/null
+++ b/src/Disposable.cpp
@@ -0,0 +1,36 @@
+#include "Disposable.h"
+
+#include <algorithm>
+#include <vector>
+#include "assert.h"
+
+using namespace rgl;
+
+void Disposable::addDisposeListener(IDisposeListener* l)
+{
+  assert( std::find( disposeListeners.begin(), disposeListeners.end(), l ) 
+          == disposeListeners.end() );
+  disposeListeners.push_back(l);  
+}
+
+void Disposable::removeDisposeListener(IDisposeListener* l)
+{
+  Container::iterator pos = std::find( disposeListeners.begin(), disposeListeners.end(), l );
+  assert( pos != disposeListeners.end() );
+  disposeListeners.erase(pos);
+}
+
+void Disposable::fireNotifyDisposed()
+{
+  // copy the listeners to a queue,
+  // so add/remove are stable during 'notifyDispose'.
+  std::vector<IDisposeListener*> queue( disposeListeners.begin(), disposeListeners.end() );
+  for ( std::vector<IDisposeListener*>::iterator i = queue.begin() ; i != queue.end() ; ++ i )
+    (*i)->notifyDisposed(this);
+}
+
+void Disposable::dispose()
+{
+  fireNotifyDisposed();  
+}
+
diff --git a/src/Disposable.h b/src/Disposable.h
new file mode 100644
index 0000000..37c590e
--- /dev/null
+++ b/src/Disposable.h
@@ -0,0 +1,60 @@
+#ifndef RGL_DISPOSABLE_H
+#define RGL_DISPOSABLE_H
+
+#include <vector>
+
+namespace rgl {
+
+// forward declaration
+class Disposable;
+
+/**
+ * Dispose Listener Interface.
+ **/
+struct IDisposeListener
+{
+  virtual ~IDisposeListener() { }
+  virtual void notifyDisposed(Disposable* disposing) = 0;
+};
+
+/**
+ * Disposable objects can be disposed autonomous while
+ * they might be managed by a different Subject.
+ * They allow for registering listeners that will be notified when
+ * the object becomes disposed.
+ **/ 
+class Disposable
+{
+public:
+  /**
+   * register listener. It is not allowed to add the listener
+   * if it is already registered.
+   * 
+   * @arg l listener to be added to list
+   **/
+  void addDisposeListener(IDisposeListener* l);
+  /**
+   * unregister listener.
+   * @arg l listener to be removed
+   **/
+  void removeDisposeListener(IDisposeListener* l);
+  /**
+   * dispose object. 
+   * Default implementatin will fire NotifyDisposed.
+   **/
+  void dispose();
+protected:
+  /**
+   * fires 'notifyDisposed' on all registered listeners.
+   * It is save to call add/remove during 'notifyDisposed'.
+   **/
+  void fireNotifyDisposed();
+private:
+  typedef std::vector<IDisposeListener*> Container;
+  Container disposeListeners;
+};
+
+} // namespace rgl
+
+#endif // RGL_DISPOSABLE_H
+
diff --git a/src/Light.cpp b/src/Light.cpp
new file mode 100644
index 0000000..6ba5480
--- /dev/null
+++ b/src/Light.cpp
@@ -0,0 +1,107 @@
+#include "Light.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Light
+//
+
+Light::Light( PolarCoord in_position, Vertex in_finposition, 
+              bool in_viewpoint, bool in_posisfinite, 
+              Color in_ambient, Color in_diffuse, Color in_specular )
+: SceneNode(LIGHT), 
+  finposition(in_finposition),  
+  ambient(in_ambient),
+  diffuse(in_diffuse),
+  specular(in_specular),
+  id(GL_FALSE),
+  viewpoint(in_viewpoint),
+  posisfinite(in_posisfinite)
+{
+  if (posisfinite) {
+    position[0] = finposition.x;
+    position[1] = finposition.y;
+    position[2] = finposition.z;
+
+    position[3] = 1.0f;
+  } else {
+      Vertex v(0.0f, 0.0f, 1.0f);
+    
+    v.rotateX( -in_position.phi );
+    v.rotateY(  in_position.theta );
+    
+    position[0] = v.x;
+    position[1] = v.y;
+    position[2] = v.z;
+    
+    position[3] = 0.0f;
+  }
+}
+
+void Light::setup(RenderContext* renderContext) 
+{
+  glLightfv(id, GL_AMBIENT,   ambient.data  );
+  glLightfv(id, GL_DIFFUSE,   diffuse.data  );
+  glLightfv(id, GL_SPECULAR,  specular.data );
+  glLightfv(id, GL_POSITION,  position );
+
+  glLightf(id, GL_SPOT_EXPONENT, 0.0f);
+  glLightf(id, GL_SPOT_CUTOFF, 180.0f);
+
+  glLightf(id, GL_CONSTANT_ATTENUATION, 1.0f);
+  glLightf(id, GL_LINEAR_ATTENUATION, 0.0f);
+  glLightf(id, GL_QUADRATIC_ATTENUATION, 0.0f);
+
+  glEnable(id);
+}
+
+int Light::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) {
+    case COLORS: return 3;
+    case VERTICES: return 1;
+    case FLAGS: return 2;
+  }  
+  
+  return 0;
+}
+
+void Light::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch (attrib) {
+      case COLORS: {
+        while (first < n) {
+          Color color;
+          switch(first) {
+          case 0: color = ambient; break;
+          case 1: color = diffuse; break;
+          case 2: color = specular;break;
+          }
+          *result++ = color.data[0];
+          *result++ = color.data[1];
+          *result++ = color.data[2];
+          *result++ = color.data[3];
+          first++;
+        }
+        return;
+      }
+      case VERTICES: {
+        *result++ = position[0];
+        *result++ = position[1];
+        *result++ = position[2];
+        return;
+      }
+      case FLAGS: {
+	if (first == 0)  
+          *result++ = (double) viewpoint;
+        *result++ = (double) posisfinite;
+        return;
+      }
+    }
+  }
+}
diff --git a/src/Light.h b/src/Light.h
new file mode 100644
index 0000000..279f250
--- /dev/null
+++ b/src/Light.h
@@ -0,0 +1,48 @@
+#ifndef LIGHT_H
+#define LIGHT_H
+
+#include "SceneNode.h"
+
+#include "rglmath.h"
+#include "Color.h"
+#include "RenderContext.h"
+
+#include "opengl.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   Light
+//
+
+class Light : public SceneNode
+{
+public:
+  Light( PolarCoord in_position = PolarCoord(0.0,0.0) , 
+  	 Vertex in_finposition=Vertex(0.0f,0.0f,0.0f), 
+  	 bool in_viewpoint=true, bool in_posisfinite=false, 
+  	 Color ambient=Color(1.0f,1.0f,1.0f), Color diffuse=Color(1.0,1.0,1.0), 
+  	 Color specular=Color(1.0,1.0,1.0) );
+  void setup(RenderContext* renderContext);
+
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "light", buflen); };
+
+private:
+  float position[4];
+  Vertex finposition;
+  Color ambient;
+  Color diffuse;
+  Color specular;
+  GLenum id;
+  bool viewpoint;
+  bool posisfinite;
+  friend class Scene;
+  friend class Subscene;
+};
+
+} // namespace rgl
+
+#endif // LIGHT_H
diff --git a/src/LineSet.cpp b/src/LineSet.cpp
new file mode 100644
index 0000000..ce5bc73
--- /dev/null
+++ b/src/LineSet.cpp
@@ -0,0 +1,24 @@
+#include "PrimitiveSet.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   LineSet
+//
+
+LineSet::LineSet(Material& in_material, int in_nvertices, double* in_vertices, bool in_ignoreExtent, bool in_bboxChange) 
+  : PrimitiveSet(in_material, in_nvertices, in_vertices, GL_LINES, 2, in_ignoreExtent, in_bboxChange)
+{
+  material.lit = false;
+  if (material.line_antialias) blended = true;
+}
+
+LineSet::LineSet(Material& in_material, bool in_ignoreExtent, bool in_bboxChange) 
+  : PrimitiveSet(in_material, GL_LINES, 2, in_ignoreExtent, in_bboxChange)
+{
+  material.lit = false;
+  if (material.line_antialias) blended = true;
+}
+
diff --git a/src/LineStripSet.cpp b/src/LineStripSet.cpp
new file mode 100644
index 0000000..83ac49c
--- /dev/null
+++ b/src/LineStripSet.cpp
@@ -0,0 +1,22 @@
+#include "PrimitiveSet.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   LineStripSet
+//
+
+LineStripSet::LineStripSet(Material& in_material, int in_nvertices, double* in_vertex, bool in_ignoreExtent, bool in_bboxChange)
+  : PrimitiveSet(in_material, in_nvertices, in_vertex, GL_LINE_STRIP, 1, in_ignoreExtent, in_bboxChange)
+{
+  material.lit = false;
+  if (material.line_antialias) blended = true;
+}
+
+void LineStripSet::drawElement(RenderContext* renderContext, int index)
+{
+  if (index < nvertices-1) 
+    glDrawArrays(type, index*nverticesperelement, 2*nverticesperelement);
+}  
diff --git a/src/Makevars.in b/src/Makevars.in
new file mode 100644
index 0000000..a4afdd9
--- /dev/null
+++ b/src/Makevars.in
@@ -0,0 +1,18 @@
+#
+# R Makevars file auto-generated using template Makevars.in 
+# AUTO-GENERATED from Makevars.in (using configure/configure.win)
+# This file is part of the RGL project.
+#
+# $Id: Makevars.in 1372 2015-10-15 19:47:06Z murdoch $
+#-DGL_VERSION_1_2 
+
+PKG_CPPFLAGS=@CPPFLAGS@ -Iext
+PKG_LIBS=@LIBS@
+AGLSHLIB=agl$(SHLIB)
+PKG_CXXFLAGS=@CXXFLAGS@ @C_VISIBILITY@
+PKG_CFLAGS=@C_VISIBILITY@
+
+BUILD=GCC3
+
+all: $(SHLIB) 
+
diff --git a/src/Material.cpp b/src/Material.cpp
new file mode 100644
index 0000000..6b0feb6
--- /dev/null
+++ b/src/Material.cpp
@@ -0,0 +1,205 @@
+#include "gl2ps.h"
+#include "Material.h"
+#include "opengl.h"
+#include "Texture.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Material
+//
+
+Material::Material(Color bg, Color fg)
+: 
+  ambient(0.0f,0.0f,0.0f,1.0f),
+  specular(1.0f,1.0f,1.0f,1.0f),
+  emission(0.0f,0.0f,0.0f,0.0f),
+  shininess(50.0f),
+  size(3.0f),
+  lwd(1.0f),
+  colors(bg,fg),
+  texture(),
+  front(FILL_FACE),
+  back(FILL_FACE),
+  smooth(true),
+  lit(true), 
+  fog(true),
+  useColorArray(false),
+  point_antialias(false),
+  line_antialias(false),
+  depth_mask(true),
+  depth_test(1),  // "less"
+  textype(Texture::RGB),    
+  mipmap(false),
+  minfilter(1),
+  magfilter(1),
+  envmap(false),
+  glVersion(-1.0)
+{
+  alphablend = ( ( bg.getAlphaf() < 1.0f ) || ( fg.getAlphaf() < 1.0f ) ) ? true : false;
+}
+
+void Material::setup()
+{
+  const char* version = (const char*)glGetString(GL_VERSION);
+  if (version) glVersion = atof(version);
+  else glVersion = 1.0;
+}
+
+void Material::beginUse(RenderContext* renderContext)
+{
+  int ncolor = colors.getLength();
+  
+  GLenum depthfunc[] = { GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER,
+                         GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS };
+  
+  SAVEGLERROR;
+  
+  glDepthFunc(depthfunc[depth_test]);
+  glDepthMask(depth_mask ? GL_TRUE : GL_FALSE);
+  
+  SAVEGLERROR;
+
+  glPushAttrib( GL_DEPTH_BUFFER_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT );
+  
+  SAVEGLERROR;
+
+  if (!alphablend) 
+    glDepthMask(GL_TRUE);
+
+  SAVEGLERROR;
+
+  if (point_antialias) glEnable(GL_POINT_SMOOTH);
+  if (line_antialias)  glEnable(GL_LINE_SMOOTH);
+  
+  SAVEGLERROR;
+
+  glDisable(GL_CULL_FACE);
+
+  for (int i=0;i<2;i++) {
+    
+    PolygonMode mode = (i==0) ? front : back;
+    
+    GLenum face = (i==0) ? GL_FRONT : GL_BACK;
+
+    SAVEGLERROR;
+
+    switch (mode) {
+      case FILL_FACE:
+        glPolygonMode( face, GL_FILL);
+        break;
+      case LINE_FACE:
+        glPolygonMode( face, GL_LINE);
+        break;
+      case POINT_FACE:
+        glPolygonMode( face, GL_POINT);
+        break;
+      case CULL_FACE:
+        glEnable(GL_CULL_FACE);
+        glCullFace(face);
+        break;
+    }
+  }
+
+  SAVEGLERROR;
+
+  glShadeModel( (smooth) ? GL_SMOOTH : GL_FLAT );
+
+  SAVEGLERROR;
+
+  if (lit) {
+    glEnable(GL_LIGHTING);
+ 
+    SAVEGLERROR;
+
+#ifdef GL_VERSION_1_2
+    if (glVersion < 0.0) setup();
+    
+    if (glVersion >= 1.2)
+      glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, (texture) ? GL_SEPARATE_SPECULAR_COLOR : GL_SINGLE_COLOR ); 
+#endif
+
+    SAVEGLERROR;
+    
+    glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
+    glEnable(GL_COLOR_MATERIAL);
+    glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT, ambient.data);
+    glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR, specular.data);
+    glMaterialf (GL_FRONT_AND_BACK,GL_SHININESS, shininess);
+    glMaterialfv(GL_FRONT_AND_BACK,GL_EMISSION, emission.data);
+  }
+
+  SAVEGLERROR;
+
+  if ( (useColorArray) && ( ncolor > 1 ) ) {
+    glEnableClientState(GL_COLOR_ARRAY);
+    colors.useArray();
+  } else
+    colors.useColor(0);
+
+  SAVEGLERROR;
+
+  if (renderContext->gl2psActive == GL2PS_NONE) {
+    glPointSize( size );
+    glLineWidth( lwd );
+  } else {
+    gl2psPointSize( size );
+    gl2psLineWidth( lwd );
+  }
+  
+  if (texture)
+    texture->beginUse(renderContext);
+
+  SAVEGLERROR;
+
+  if (!fog)
+    glDisable(GL_FOG);
+  
+  SAVEGLERROR;    
+}
+
+void Material::useColor(int index)
+{
+  if (colors.getLength() > 0)
+    colors.useColor( index % colors.getLength() );
+}
+
+void Material::endUse(RenderContext* renderContext)
+{
+  int ncolor = colors.getLength();
+
+  if ( (useColorArray) && ( ncolor > 1 ) ) {
+    glDisableClientState(GL_COLOR_ARRAY);
+    SAVEGLERROR;
+  }
+
+  if (texture) {
+    texture->endUse(renderContext);
+    SAVEGLERROR;
+  }
+  #if USE_GLGETERROR
+  saveGLerror(__FILE__, __LINE__);
+  #endif
+  glPopAttrib();
+  #if USE_GLGETERROR
+  if (SaveErrnum == GL_NO_ERROR) glGetError(); /* work around bug in some glX implementations */
+  #endif
+  SAVEGLERROR;
+  
+  glDepthFunc(GL_LESS);
+  glDepthMask(GL_TRUE);
+}
+
+void Material::colorPerVertex(bool enable, int numVertices)
+{
+  useColorArray = enable;
+  if (enable)
+    colors.recycle(numVertices);
+}
+
+
+
+
diff --git a/src/Material.h b/src/Material.h
new file mode 100644
index 0000000..4ecc90b
--- /dev/null
+++ b/src/Material.h
@@ -0,0 +1,66 @@
+#ifndef MATERIAL_H
+#define MATERIAL_H
+
+#include "Color.h"
+#include "Texture.h"
+#include "RenderContext.h"
+
+namespace rgl {
+
+//
+// STRUCT
+//   Material
+//
+
+class Material {
+public:
+
+  enum PolygonMode { 
+    FILL_FACE=1, 
+    LINE_FACE, 
+    POINT_FACE, 
+    CULL_FACE 
+  };
+
+  Material( Color bg, Color fg );
+
+  void setup();
+  // called when complete
+
+  void beginUse(RenderContext* renderContext);
+  void endUse(RenderContext* renderContext);
+  void useColor(int index);
+  void colorPerVertex(bool enable, int numVertices=0);
+  bool isTransparent() const { return alphablend; }
+
+  Color        ambient;
+  Color        specular;
+  Color        emission;
+  float        shininess;
+  float        size;          // point size
+  float        lwd;           // line width
+  ColorArray   colors;        // color or if lit, represents diffuse color
+  Ref<Texture> texture;
+  PolygonMode  front;
+  PolygonMode  back;
+  bool         alphablend;
+  bool         smooth;
+  bool         lit;
+  bool         fog;
+  bool         useColorArray;
+  bool         point_antialias;
+  bool         line_antialias;
+  bool         depth_mask;
+  int	       depth_test;  // 0=GL_NEVER, 1=GL_LESS, etc.
+  Texture::Type textype;
+  bool	       mipmap;
+  unsigned int minfilter;
+  unsigned int magfilter;
+  bool         envmap;
+  
+  float        glVersion;
+};
+
+} // namespace rgl
+
+#endif // MATERIAL_H
diff --git a/src/NULLgui.cpp b/src/NULLgui.cpp
new file mode 100644
index 0000000..4188a24
--- /dev/null
+++ b/src/NULLgui.cpp
@@ -0,0 +1,122 @@
+
+#include <ctype.h>
+#include <Rinternals.h>
+#include "config.h"
+// C++ source
+// This file is part of RGL.
+//
+// $Id: win32gui.cpp 923 2013-01-27 10:41:11Z murdoch $
+
+#include "NULLgui.h"
+
+#include "lib.h"
+#include "glgui.h"
+
+#include "assert.h"
+#include "R.h"
+
+// ---------------------------------------------------------------------------
+
+namespace rgl {
+
+class NULLWindowImpl : public WindowImpl
+{ 
+public:
+  NULLWindowImpl(Window* in_window);
+  ~NULLWindowImpl();
+  void setTitle(const char* title) {};
+  void setWindowRect(int left, int top, int right, int bottom);
+  void getWindowRect(int *left, int *top, int *right, int *bottom);
+  void show() {};
+  void hide() {};
+  void bringToTop(int stay) {};
+  void update() { if (window) window->paint(); };
+  void destroy() { if (window) window->notifyDestroy(); };
+  void captureMouse(View* pView) {};
+  void releaseMouse() {};
+  GLFont* getFont(const char* family, int style, double cex, 
+                  bool useFreeType);
+  int getAntialias() { return 1; }
+  int getMaxClipPlanes() { return INT_MAX; }
+
+private:
+  int rect[4];
+  friend class NULLGUIFactory;
+
+public:
+  bool beginGL() { return false; };
+  void endGL() {};
+  void swap() {};
+};
+
+} // namespace rgl
+
+using namespace rgl;
+// ----------------------------------------------------------------------------
+// constructor
+// ----------------------------------------------------------------------------
+NULLWindowImpl::NULLWindowImpl(Window* in_window)
+: WindowImpl(in_window)
+{
+  setWindowRect(0, 0, 256, 256);
+  fonts[0] = new NULLFont("sans", 1, 1.0);
+}
+
+NULLWindowImpl::~NULLWindowImpl()
+{
+  if (window) 
+    window->notifyDestroy(); 
+}
+
+void NULLWindowImpl::setWindowRect(int left, int top, int right, int bottom)
+{
+  rect[0] = left;
+  rect[1] = top;
+  rect[2] = right;
+  rect[3] = bottom;
+  window->resize(right-left, bottom-top);
+}
+
+void NULLWindowImpl::getWindowRect(int *left, int *top, int *right, int *bottom)
+{
+    *left = rect[0];
+    *top = rect[1];
+    *right = rect[2];
+    *bottom = rect[3];
+}
+
+GLFont* NULLWindowImpl::getFont(const char* family, int style, double cex, 
+                                 bool useFreeType)
+{
+  for (unsigned int i=0; i < fonts.size(); i++) {
+    if (fonts[i]->cex == cex && fonts[i]->style == style && !strcmp(fonts[i]->family, family)
+     && fonts[i]->useFreeType == useFreeType)
+      return fonts[i];
+  }
+  GLFont* font = new NULLFont(family, style, cex);
+  fonts.push_back(font);
+  return font;
+}
+  
+// ---------------------------------------------------------------------------
+//
+// NULLGUIFactory class
+//
+// ---------------------------------------------------------------------------
+
+
+NULLGUIFactory::NULLGUIFactory()
+{
+}
+// ---------------------------------------------------------------------------
+NULLGUIFactory::~NULLGUIFactory() {
+}
+// ---------------------------------------------------------------------------
+
+WindowImpl* NULLGUIFactory::createWindowImpl(Window* in_window)
+{
+  NULLWindowImpl* impl = new NULLWindowImpl(in_window);
+  return impl;
+}
+// ---------------------------------------------------------------------------
+
diff --git a/src/NULLgui.h b/src/NULLgui.h
new file mode 100644
index 0000000..d26912a
--- /dev/null
+++ b/src/NULLgui.h
@@ -0,0 +1,23 @@
+#ifndef RGL_NULL_GUI_H
+#define RGL_NULL_GUI_H
+// ---------------------------------------------------------------------------
+// $Id: win32gui.hpp 840 2012-01-06 16:07:37Z murdoch $
+// ---------------------------------------------------------------------------
+#include "gui.h"
+
+namespace rgl {
+
+// ---------------------------------------------------------------------------
+class NULLGUIFactory : public GUIFactory
+{
+public:
+  NULLGUIFactory();
+  virtual ~NULLGUIFactory();
+  WindowImpl* createWindowImpl(Window* window);
+};
+// ---------------------------------------------------------------------------
+
+} // namespace rgl
+
+#endif // RGL_NULL_GUI_H
+
diff --git a/src/PlaneSet.cpp b/src/PlaneSet.cpp
new file mode 100644
index 0000000..41007aa
--- /dev/null
+++ b/src/PlaneSet.cpp
@@ -0,0 +1,175 @@
+#include <algorithm>
+#include "PlaneSet.h"
+#include "Viewpoint.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   PlaneSet
+//
+
+PlaneSet::PlaneSet(Material& in_material, int in_nnormal, double* in_normal, int in_noffset, double* in_offset)
+ : 
+   TriangleSet(in_material,true, false/* true */),
+   nPlanes(max(in_nnormal, in_noffset)),
+   normal(in_nnormal, in_normal), 
+   offset(in_noffset, in_offset)
+{
+  /* We'll set up 4 triangles per plane, in case we need to render
+     a hexagon.  Each triangle has 3 vertices (so 12 for the plane), and each vertex
+     gets 3 color components and 1 alpha component. */
+  ARRAY<int> colors(36*nPlanes);
+  ARRAY<double> alphas(12*nPlanes);
+
+  if (material.colors.getLength() > 1) {
+    material.colors.recycle(nPlanes); 
+  
+    for (int i=0; i<nPlanes; i++) {
+      Color color=material.colors.getColor(i);
+      for (int j=0; j<12; j++) {
+        colors.ptr[36*i+3*j+0] = color.getRedub();
+        colors.ptr[36*i+3*j+1] = color.getGreenub();
+        colors.ptr[36*i+3*j+2] = color.getBlueub();
+        alphas.ptr[12*i+j]     = color.getAlphaf();
+      }
+    }
+    material.colors.set(12*nPlanes, colors.ptr, 12*nPlanes, alphas.ptr);
+    material.colorPerVertex(true, 12*nPlanes);
+  }
+  
+  ARRAY<double> vertices(36*nPlanes),
+                normals(36*nPlanes);
+  for (int i=0; i<vertices.size(); i++)
+    vertices.ptr[i] = NA_REAL;
+  for (int i=0; i<nPlanes; i++)
+    for (int j=0; j<12; j++) {
+      normals.ptr[36*i+3*j+0] = normal.getRecycled(i).x;
+      normals.ptr[36*i+3*j+1] = normal.getRecycled(i).y;
+      normals.ptr[36*i+3*j+2] = normal.getRecycled(i).z;
+    }  
+  initFaceSet(12*nPlanes, vertices.ptr, normals.ptr, NULL);
+}
+
+AABox& PlaneSet::getBoundingBox(Subscene* subscene)
+{
+  updateTriangles(subscene->getBoundingBox());
+  return TriangleSet::getBoundingBox(subscene); 
+}
+
+void PlaneSet::renderBegin(RenderContext* renderContext)
+{
+  updateTriangles(renderContext->subscene->getBoundingBox());
+  invalidateDisplaylist();
+  TriangleSet::renderBegin(renderContext);
+}
+
+void PlaneSet::updateTriangles(const AABox& sceneBBox)
+{
+  int perms[3][3] = { {0,0,1}, {1,2,2}, {2,1,0} };
+  double bbox[2][3] = { {sceneBBox.vmin.x, sceneBBox.vmin.y, sceneBBox.vmin.z},
+                       {sceneBBox.vmax.x, sceneBBox.vmax.y, sceneBBox.vmax.z} };
+  double x[12][3];
+  for (int elem = 0; elem < nPlanes; elem++) {
+    Vertex Av = normal.getRecycled(elem);
+    double A[3] = { Av.x, Av.y, Av.z };
+    double d = offset.getRecycled(elem);
+    int nhits = 0;
+    int face1[12], face2[12]; /* to identify which faces of the cube we're on */
+    
+    for (int i=0; i<3; i++)
+      for (int j=0; j<2; j++)
+        for (int k=0; k<2; k++) {
+          int u=perms[0][i], v=perms[1][i], w=perms[2][i];
+          if (A[w] != 0.0) {
+            double intersect = -(d + A[u]*bbox[j][u] + A[v]*bbox[k][v])/A[w];
+  	  if (bbox[0][w] < intersect && intersect < bbox[1][w]) {
+  	    x[nhits][u] = bbox[j][u];
+  	    x[nhits][v] = bbox[k][v];
+  	    x[nhits][w] = intersect;
+  	    face1[nhits] = j + 2*u;
+  	    face2[nhits] = k + 2*v;
+  	    nhits++;
+  	  }
+  	}
+      }
+    
+    if (nhits > 3) {
+      /* Re-order the intersections so the triangles work */
+      for (int i=0; i<nhits-2; i++) {
+        int which=0; /* initialize to suppress warning */
+        for (int j=i+1; j<nhits; j++) {
+          if (face1[i] == face1[j] || face1[i] == face2[j] 
+           || face2[i] == face1[j] || face2[i] == face2[j] ) {
+            which = j;
+            break;
+          }
+        }
+        if (which > i+1) {
+          for (int j=0; j<3; j++) 
+            swap(x[i+1][j], x[which][j]);
+          swap(face1[i+1], face1[which]);
+          swap(face2[i+1], face2[which]);
+        }
+      }
+    }
+    
+    if (nhits >= 3) { 
+      /* Put in order so that the normal points out the FRONT of the faces */
+      Vec3 v0(x[0][0] - x[1][0] , x[0][1] - x[1][1], x[0][2] - x[1][2]),
+           v2(x[2][0] - x[1][0] , x[2][1] - x[1][1], x[2][2] - x[1][2]),
+           vx = v0.cross(v2);
+      
+      bool reverse = vx*Av > 0;
+      
+      for (int i=0; i<nhits-2; i++) {
+        setVertex(12*elem + 3*i, x[0]); 
+        for (int j=1; j<3; j++) {
+          if (reverse)
+            setVertex(12*elem + 3*i + 3-j, x[i+j]);
+          else
+            setVertex(12*elem + 3*i + j, x[i+j]);
+        }
+      }
+    } else 
+      nhits = 2; /* all missing */
+      
+    double missing[3] = {NA_REAL, NA_REAL, NA_REAL};
+    for (int i=nhits-2; i<4; i++) 
+      for (int j=0; j<3; j++) 
+        setVertex(12*elem + 3*i + j, missing);
+  }
+}
+
+int PlaneSet::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+	switch (attrib) {
+	case NORMALS: 
+	case OFFSETS: return nPlanes;
+	}
+	return TriangleSet::getAttributeCount(bbox, attrib);
+}
+
+void PlaneSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+	int n = getAttributeCount(bbox, attrib);
+	if (first + count < n) n = first + count;
+	if (first < n) {
+		if (attrib == NORMALS) {
+			while (first < n) {
+				*result++ = normal.getRecycled(first).x;
+				*result++ = normal.getRecycled(first).y;
+				*result++ = normal.getRecycled(first).z;
+				first++;
+			}
+		} else if (attrib == OFFSETS) {
+			while (first < n) 
+				*result++ = offset.getRecycled(first++);
+		} else {
+			updateTriangles(bbox);
+			TriangleSet::getAttribute(bbox, attrib, first, count, result);
+		}
+	}
+}
diff --git a/src/PlaneSet.h b/src/PlaneSet.h
new file mode 100644
index 0000000..285a296
--- /dev/null
+++ b/src/PlaneSet.h
@@ -0,0 +1,50 @@
+#ifndef PLANESET_H
+#define PLANESET_H
+
+#include "scene.h"
+#include "geom.h"
+#include "Shape.h"
+#include "PrimitiveSet.h"
+#include <map>
+
+namespace rgl {
+
+class PlaneSet : public TriangleSet {
+private:		/* Use parametrization ax + by + cz + d = 0 */
+  int		nPlanes;
+  ARRAY<Vertex> normal; /* (a,b,c) */
+  ARRAY<float>  offset; /* d */  
+public:
+  PlaneSet(Material& in_material, int in_nnormal, double* in_normal, int in_noffset, double* in_offset);
+  // ~PlaneSet();
+  
+  /**
+   * tell type.
+   **/
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "planes", buflen); };
+
+  /**
+   * overload to update triangles first.
+   */
+  virtual AABox& getBoundingBox(Subscene* subscene);
+
+  /**
+   * overload to update triangles first.
+   */
+  virtual void renderBegin(RenderContext* renderContext);
+
+  /**
+   * update mesh
+   */
+  void updateTriangles(const AABox& sceneBBox);
+  
+  /**
+   * update then get attributes 
+   */
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);  
+};
+
+} // namespace rgl
+
+#endif // PLANESET_H
diff --git a/src/PointSet.cpp b/src/PointSet.cpp
new file mode 100644
index 0000000..b1c442d
--- /dev/null
+++ b/src/PointSet.cpp
@@ -0,0 +1,17 @@
+#include "PrimitiveSet.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   PointSet
+//
+
+PointSet::PointSet(Material& in_material, int in_nvertices, double* in_vertices, bool in_ignoreExtent, bool in_bboxChange) 
+  : PrimitiveSet(in_material, in_nvertices, in_vertices, GL_POINTS, 1, in_ignoreExtent)
+{
+  material.lit = false;
+  if (material.point_antialias) blended = true;
+} 
+
diff --git a/src/PrimitiveSet.cpp b/src/PrimitiveSet.cpp
new file mode 100644
index 0000000..4610506
--- /dev/null
+++ b/src/PrimitiveSet.cpp
@@ -0,0 +1,336 @@
+#include "PrimitiveSet.h"
+#include "R.h"
+
+using namespace rgl;
+
+// ===[ PRIMITIVE SET ]=======================================================
+
+PrimitiveSet::PrimitiveSet (
+
+    Material& in_material, 
+    int in_type,
+    int in_nverticesperelement,
+    bool in_ignoreExtent,
+    bool in_bboxChange
+    ) :
+Shape(in_material, in_ignoreExtent, SHAPE, in_bboxChange)
+{
+  type                = in_type;
+  nverticesperelement = in_nverticesperelement;
+}
+
+void PrimitiveSet::initPrimitiveSet(
+    int in_nvertices, 
+    double* in_vertices
+) {
+  nvertices           = in_nvertices;
+  nprimitives         = in_nvertices / nverticesperelement;
+  vertexArray.alloc(nvertices);
+  hasmissing = false;
+  for(int i=0;i<nvertices;i++) {
+    vertexArray[i].x = (float) in_vertices[i*3+0];
+    vertexArray[i].y = (float) in_vertices[i*3+1];
+    vertexArray[i].z = (float) in_vertices[i*3+2];
+    boundingBox += vertexArray[i];
+    hasmissing |= vertexArray[i].missing();
+  }
+}
+
+PrimitiveSet::PrimitiveSet (
+
+    Material& in_material, 
+    int in_nvertices, 
+    double* in_vertices, 
+    int in_type, 
+    int in_nverticesperelement,
+    bool in_ignoreExtent,
+    bool in_bboxChange
+
+)
+  :
+Shape(in_material, in_ignoreExtent, SHAPE, in_bboxChange)
+{
+  type                = in_type;
+  nverticesperelement = in_nverticesperelement;
+  nvertices           = in_nvertices;
+  nprimitives         = in_nvertices / nverticesperelement;
+  material.colorPerVertex(true, nvertices);
+
+  vertexArray.alloc(nvertices);
+  hasmissing = false;
+  for(int i=0;i<nvertices;i++) {
+    vertexArray[i].x = (float) in_vertices[i*3+0];
+    vertexArray[i].y = (float) in_vertices[i*3+1];
+    vertexArray[i].z = (float) in_vertices[i*3+2];
+    boundingBox += vertexArray[i];
+    hasmissing |= vertexArray[i].missing();
+  }
+}
+
+// ---------------------------------------------------------------------------
+
+void PrimitiveSet::drawBegin(RenderContext* renderContext)
+{
+  Shape::drawBegin(renderContext);
+  material.beginUse(renderContext);
+  SAVEGLERROR;
+  vertexArray.beginUse();
+  SAVEGLERROR;
+}
+
+// ---------------------------------------------------------------------------
+
+void PrimitiveSet::drawAll(RenderContext* renderContext)
+{
+  if (!hasmissing)
+    glDrawArrays(type, 0, nverticesperelement*nprimitives );
+    // FIXME: refactor to vertexArray.draw( type, 0, nverticesperelement*nprimitives );
+  else {
+    bool missing = true;
+    for (int i=0; i<nprimitives; i++) {
+      bool skip = false;
+      for (int j=0; j<nverticesperelement; j++) 
+        skip |= vertexArray[nverticesperelement*i + j].missing();
+      if (missing != skip) {
+        missing = !missing;
+        if (missing) glEnd();
+        else glBegin(type);
+      }
+      if (!missing) 
+        for (int j=0; j<nverticesperelement; j++)
+          glArrayElement( nverticesperelement*i + j );
+    }
+    if (!missing) glEnd();
+  }              
+}
+
+// ---------------------------------------------------------------------------
+
+void PrimitiveSet::drawElement(RenderContext* renderContext, int index)
+{
+  if (hasmissing) {
+    bool skip = false;
+    for (int j=0; j<nverticesperelement; j++) 
+      skip |= vertexArray[index*nverticesperelement + j].missing();
+    if (skip) return;
+  }
+  glDrawArrays(type, index*nverticesperelement, nverticesperelement);
+  // FIXME: refactor to vertexArray.draw( type, index*nverticesperelement, nverticesperelement );
+}
+
+// ---------------------------------------------------------------------------
+
+void PrimitiveSet::drawEnd(RenderContext* renderContext)
+{
+  vertexArray.endUse();
+  SAVEGLERROR;
+  material.endUse(renderContext);
+  SAVEGLERROR;
+  Shape::drawEnd(renderContext);
+}
+
+// ---------------------------------------------------------------------------
+
+void PrimitiveSet::draw(RenderContext* renderContext)
+{
+  drawBegin(renderContext);
+  SAVEGLERROR;
+
+  drawAll(renderContext);
+  SAVEGLERROR;
+  
+  drawEnd(renderContext);
+  SAVEGLERROR;
+}
+
+int PrimitiveSet::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) {
+    case VERTICES: return nvertices;
+  }
+  return Shape::getAttributeCount(bbox, attrib);
+}
+
+void PrimitiveSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    if (attrib == VERTICES) {
+      while (first < n) {
+        *result++ = vertexArray[first].x;
+        *result++ = vertexArray[first].y;
+        *result++ = vertexArray[first].z;
+        first++;
+      }
+    } else
+      Shape::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
+// ===[ FACE SET ]============================================================
+
+FaceSet::FaceSet(
+
+  Material& in_material, 
+  int in_nelements, 
+  double* in_vertex, 
+  double* in_normals,
+  double* in_texcoords,
+  int in_type, 
+  int in_nverticesperelement,
+  bool in_ignoreExtent,
+  int in_useNormals,
+  int in_useTexcoords,
+  bool in_bboxChange
+
+)
+: PrimitiveSet(in_material, in_nelements, in_vertex, in_type, in_nverticesperelement, in_ignoreExtent, in_bboxChange)
+{
+  if (material.lit) {
+    normalArray.alloc(nvertices);
+    if (in_useNormals) {
+      for(int i=0;i<nvertices;i++) {
+        normalArray[i].x = (float) in_normals[i*3+0];
+        normalArray[i].y = (float) in_normals[i*3+1];
+        normalArray[i].z = (float) in_normals[i*3+2];
+      }
+    } else {
+      for (int i=0;i<=nvertices-nverticesperelement;i+=nverticesperelement) 
+      {   
+        if (hasmissing && (vertexArray[i].missing() ||
+                           vertexArray[i+1].missing() ||
+                           vertexArray[i+2].missing()) )
+          normalArray[i] = Vertex(0.0, 0.0, 0.0);
+        else
+          normalArray[i] = vertexArray.getNormal(i,i+1,i+2);
+        for (int j=1;j<nverticesperelement;++j)    
+          normalArray[i+j] = normalArray[i];
+      }
+    }
+  }
+  if (in_useTexcoords) {
+    texCoordArray.alloc(nvertices);
+    for(int i=0;i<nvertices;i++) {
+      texCoordArray[i].s = (float) in_texcoords[i*2+0];
+      texCoordArray[i].t = (float) in_texcoords[i*2+1];      
+    }
+  }
+}
+
+FaceSet::FaceSet(Material& in_material, 
+    int in_type,
+    int in_nverticesperelement,
+    bool in_ignoreExtent,
+    bool in_bboxChange
+    ) :
+  PrimitiveSet(in_material, in_type, in_nverticesperelement, in_ignoreExtent,in_bboxChange)
+{ 
+}
+
+void FaceSet::initFaceSet(
+  int in_nelements, 
+  double* in_vertex, 
+  double* in_normals,
+  double* in_texcoords
+) {
+  initPrimitiveSet(in_nelements, in_vertex);
+  
+  bool useNormals = (in_normals) ? true : false;
+  bool useTexcoords = (in_texcoords) ? true : false;
+
+  if (material.lit) {
+    normalArray.alloc(nvertices);
+    if (useNormals) {
+      for(int i=0;i<nvertices;i++) {
+        normalArray[i].x = (float) in_normals[i*3+0];
+        normalArray[i].y = (float) in_normals[i*3+1];
+        normalArray[i].z = (float) in_normals[i*3+2];
+      }
+    } else {
+      for (int i=0;i<=nvertices-nverticesperelement;i+=nverticesperelement) 
+      {   
+        if (hasmissing && (vertexArray[i].missing() ||
+                           vertexArray[i+1].missing() ||
+                           vertexArray[i+2].missing()) )
+          normalArray[i] = Vertex(0.0, 0.0, 0.0);
+        else
+          normalArray[i] = vertexArray.getNormal(i,i+1,i+2);
+        for (int j=1;j<nverticesperelement;++j)    
+          normalArray[i+j] = normalArray[i];
+      }
+    }
+  }
+  if (useTexcoords) {
+    texCoordArray.alloc(nvertices);
+    for(int i=0;i<nvertices;i++) {
+      texCoordArray[i].s = (float) in_texcoords[i*2+0];
+      texCoordArray[i].t = (float) in_texcoords[i*2+1];      
+    }
+  }
+}
+
+// ---------------------------------------------------------------------------
+
+void FaceSet::drawBegin(RenderContext* renderContext)
+{  
+  PrimitiveSet::drawBegin(renderContext);
+
+  if (material.lit)
+    normalArray.beginUse();
+    
+  texCoordArray.beginUse();
+}
+
+// ---------------------------------------------------------------------------
+
+void FaceSet::drawEnd(RenderContext* renderContext)
+{  
+  texCoordArray.endUse();
+  
+  if (material.lit)
+    normalArray.endUse();
+
+  PrimitiveSet::drawEnd(renderContext);
+}
+
+
+int FaceSet::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) {
+    case NORMALS: if (material.lit)
+    		    return nvertices;
+    		  else
+    		    return 0;
+    case TEXCOORDS: return texCoordArray.size();
+  }
+  return PrimitiveSet::getAttributeCount(bbox, attrib);
+}
+
+void FaceSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch (attrib) {
+      case NORMALS: {
+        while (first < n) {
+          *result++ = normalArray[first].x;
+          *result++ = normalArray[first].y;
+          *result++ = normalArray[first].z;
+          first++;
+        }
+        return;
+      }
+      case TEXCOORDS: {
+        while (first < n) {
+          *result++ = texCoordArray[first].s;
+	  *result++ = texCoordArray[first].t;
+	  first++;
+	}
+	return;
+      }
+    }
+    PrimitiveSet::getAttribute(bbox, attrib, first, count, result);
+  }
+}
diff --git a/src/PrimitiveSet.h b/src/PrimitiveSet.h
new file mode 100644
index 0000000..f6d8505
--- /dev/null
+++ b/src/PrimitiveSet.h
@@ -0,0 +1,280 @@
+#ifndef PRIMITIVE_SET_H
+#define PRIMITIVE_SET_H
+
+#include "Shape.h"
+
+#include "render.h"
+
+#include <map>
+
+namespace rgl {
+
+//
+// ABSTRACT CLASS
+//   PrimitiveSet
+//
+
+class PrimitiveSet : public Shape {
+public:
+  /**
+   * overloaded
+   **/
+  virtual void draw(RenderContext* renderContext);
+  /**
+   * overloaded
+   **/
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "primitive", buflen); }
+  /**
+   * overloaded
+   **/
+  virtual int getElementCount(void) { return nprimitives; }
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  
+  /**
+   * overloaded
+   **/
+  virtual Vertex getElementCenter(int item) { return getCenter(item); }
+
+  /**
+   * begin sending primitives 
+   * interface
+   **/
+  virtual void drawBegin(RenderContext* renderContext);
+  
+  /**
+   * send primitive
+   * interface
+   **/
+  virtual void drawElement(RenderContext* renderContext, int index);
+  
+  /**
+   * end sending primitives
+   * interface
+   **/
+  virtual void drawEnd(RenderContext* renderContext);
+  
+  /**
+   * set a vertex
+   **/
+  const void setVertex(int index, double* v) { vertexArray.setVertex(index, v); }
+
+  /**
+   * setup all vertices
+   **/
+  void initPrimitiveSet(int in_nvertices, double* in_vertices);
+
+protected:
+
+  /**
+   * abstract class constructor
+   **/
+  PrimitiveSet (
+      Material& in_material, 
+      int in_nvertices, 
+      double* vertex, 
+      int in_type, 
+      int in_nverticesperelement,
+      bool in_ignoreExtent,
+      bool in_bboxChange = false
+  );
+  PrimitiveSet(
+    Material& in_material, 
+    int in_type, 
+    int in_verticesperelement,
+    bool in_ignoreExtent,
+    bool in_bboxChange 
+  );
+
+  /**
+   * get primitive center point
+   **/
+  inline Vertex getCenter(int index)
+  {
+    Vertex accu;
+    int begin = index*nverticesperelement;
+    int end   = begin+nverticesperelement;
+    for (int i = begin ; i < end ; ++i )
+      accu += vertexArray[i];
+    return accu * ( 1.0f / ( (float) nverticesperelement ) );
+  }
+
+  // ---[ PRIMITIVE DRAW INTERFACE ]------------------------------------------
+
+  
+  /**
+   * send all elements
+   * interface
+   **/
+  virtual void drawAll(RenderContext* renderContext);
+  
+  void initPrimitiveSet (
+      int in_nvertices, 
+      double* vertex, 
+      int in_type, 
+      int in_nverticesperelement,
+      bool in_ignoreExtent,
+      bool in_bboxChange 
+  );
+
+  int type;
+  int nverticesperelement;
+  int nvertices;
+  int nprimitives;
+  VertexArray vertexArray;
+  bool hasmissing; 	/* whether any vertices contain missing values */
+};
+
+
+//
+// ABSTRACT CLASS
+//   FaceSet
+//
+
+class FaceSet : public PrimitiveSet
+{
+public:
+  /**
+   * overload
+   **/
+  virtual void drawBegin(RenderContext* renderContext);
+
+  /**
+   * overload
+   **/
+  virtual void drawEnd(RenderContext* renderContext);
+  /**
+   * overloaded
+   **/  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "faces", buflen); };  
+  
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+
+protected:
+  /**
+   * Constructor
+   **/
+  FaceSet(
+    Material& in_material, 
+    int in_nelements, 
+    double* in_vertex,
+    double* in_normals,
+    double* in_texcoords,
+    int in_type, 
+    int in_nverticesperelement,
+    bool in_ignoreExtent,
+    int in_useNormals,
+    int in_useTexcoords,
+    bool in_bboxChange = false
+  );
+  
+  FaceSet(
+    Material& in_material, 
+    int in_type, 
+    int in_verticesperelement,
+    bool in_ignoreExtent,
+    bool in_bboxChange = false
+  );
+  
+  /* (re-)set mesh */
+  void initFaceSet(int in_nelements, double* in_vertex, double* in_normals, double* in_texcoords);
+ 
+private:
+  NormalArray normalArray;
+  TexCoordArray texCoordArray;
+};
+
+//
+// CLASS
+//   PointSet
+//
+
+class PointSet : public PrimitiveSet
+{ 
+public:
+  PointSet(Material& material, int nvertices, double* vertices, bool in_ignoreExtent, bool bboxChange=false);
+  /**
+   * overloaded
+   **/  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "points", buflen); };
+};
+
+//
+// CLASS
+//   LineSet
+//
+
+class LineSet : public PrimitiveSet
+{ 
+public:
+  LineSet(Material& material, int nvertices, double* vertices, bool in_ignoreExtent, bool in_bboxChange=false);
+  LineSet(Material& in_material, bool in_ignoreExtent, bool in_bboxChange);
+
+  /**
+   * overloaded
+   **/  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "lines", buflen); };
+};
+
+//
+// CLASS
+//   TriangleSet
+//
+
+class TriangleSet : public FaceSet
+{ 
+public:
+  TriangleSet(Material& in_material, int in_nvertex, double* in_vertex, double* in_normals,
+              double* in_texcoords, bool in_ignoreExtent, int in_useNormals, int in_useTexcoords, bool in_bboxChange = false)
+    : FaceSet(in_material,in_nvertex, in_vertex, in_normals, in_texcoords, 
+              GL_TRIANGLES, 3, in_ignoreExtent, in_useNormals, in_useTexcoords, in_bboxChange)
+  { }
+  TriangleSet(Material& in_material, bool in_ignoreExtent, bool in_bboxChange) : 
+    FaceSet(in_material, GL_TRIANGLES, 3, in_ignoreExtent, in_bboxChange) 
+  { }
+  /**
+   * overloaded
+   **/  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "triangles", buflen); };
+};
+
+//
+// CLASS
+//   QuadSet
+//
+
+class QuadSet : public FaceSet
+{ 
+public:
+  QuadSet(Material& in_material, int in_nvertex, double* in_vertex, double* in_normals,
+          double* in_texcoords, bool in_ignoreExtent, int in_useNormals, int in_useTexcoords)
+    : FaceSet(in_material,in_nvertex,in_vertex, in_normals, in_texcoords, 
+              GL_QUADS, 4, in_ignoreExtent, in_useNormals, in_useTexcoords)
+  { }
+  
+  /**
+   * overloaded
+   **/  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "quads", buflen); };
+};
+
+//
+// CLASS
+//   LineStripSet
+//
+
+class LineStripSet : public PrimitiveSet
+{
+public:
+  LineStripSet(Material& material, int in_nelements, double* in_vertex, bool in_ignoreExtent, bool in_bboxChange = false);
+  void drawElement(RenderContext* renderContext, int index);
+  /**
+   * overloaded
+   **/  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "linestrip", buflen); };
+};
+
+} // namespace rgl 
+
+#endif // PRIMITIVE_SET_H
diff --git a/src/R.h b/src/R.h
new file mode 100644
index 0000000..1f802fb
--- /dev/null
+++ b/src/R.h
@@ -0,0 +1,43 @@
+#ifndef RGL_R_H
+#define RGL_R_H
+
+// This define avoids a warning about ERROR redefinition in Windows
+#define STRICT_R_HEADERS
+
+#include <R.h>
+
+/* Default for antialiasing */
+#define RGL_ANTIALIAS 8
+
+/* Set this to 1 to turn on glGetError testing */
+#define USE_GLGETERROR 0
+
+
+
+#if USE_GLGETERROR
+#define SAVEGLERROR saveGLerror(__FILE__, __LINE__);
+#define CHECKGLERROR checkGLerror(__FILE__, __LINE__);
+
+/* saveGLerror is safe to call from a message handler.  It saves one error.          */
+/* checkGLerror is not safe within a message handler.  It checks for saved errors or */
+/*   other errors, then reports them through R.                                      */
+/* Neither one can be called with glBegin() ... glEnd() pairs.                       */
+/* They are defined in glErrors.cpp                                                  */
+
+namespace rgl {
+
+extern int SaveErrnum;
+
+void saveGLerror(const char *, int);  
+void checkGLerror(const char *, int);
+
+} // namespace rgl
+
+#else
+#define SAVEGLERROR
+#define CHECKGLERROR
+#endif
+
+
+
+#endif /* RGL_R_H */
diff --git a/src/RenderContext.cpp b/src/RenderContext.cpp
new file mode 100644
index 0000000..f89b9eb
--- /dev/null
+++ b/src/RenderContext.cpp
@@ -0,0 +1,12 @@
+#include "RenderContext.h"
+
+#include <map>
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   RenderContext
+//
+
diff --git a/src/RenderContext.h b/src/RenderContext.h
new file mode 100644
index 0000000..c060a24
--- /dev/null
+++ b/src/RenderContext.h
@@ -0,0 +1,39 @@
+#ifndef RENDERCONTEXT_H
+#define RENDERCONTEXT_H
+
+namespace rgl {
+class Subscene;
+class GLFont;
+} // namespace rgl
+
+#include "rglmath.h"
+#include "opengl.h"
+
+namespace rgl {
+
+class RenderContext
+{
+public:
+  RenderContext()
+  : subscene(0)
+  , rect(0,0,0,0)
+  , font(0)
+  , time(0.0)
+  , lastTime(0.0)
+  , deltaTime(0.0)
+  , gl2psActive(0)
+  { }
+  Subscene* subscene;
+  Rect2   rect;  // This is the full window rectangle in pixels
+  // RectSize size;
+  GLFont* font;
+  double time;
+  double lastTime;
+  double deltaTime;
+
+  int gl2psActive;
+};
+
+} // namespace rgl
+
+#endif // RENDERCONTEXT_H
diff --git a/src/SceneNode.h b/src/SceneNode.h
new file mode 100644
index 0000000..5005450
--- /dev/null
+++ b/src/SceneNode.h
@@ -0,0 +1,92 @@
+#ifndef SCENENODE_H
+#define SCENENODE_H
+
+//
+// ABSTRACT BASE CLASS
+//   SceneNode
+//
+
+#include "types.h"
+#include "String.h"
+#include "geom.h"
+
+namespace rgl {
+
+/*
+enum TypeID { 
+  SHAPE=1, 
+  LIGHT, 
+  BBOXDECO, 
+  USERVIEWPOINT, 
+  BACKGROUND,
+  SUBSCENE,
+  MODELVIEWPOINT
+};
+*/
+
+#define SHAPE 1
+#define LIGHT 2
+#define BBOXDECO 3
+#define USERVIEWPOINT 4
+#define BACKGROUND 6  // 5 was used for the material
+#define SUBSCENE 7
+#define MODELVIEWPOINT 8
+#define MAX_TYPE 8
+
+typedef unsigned int TypeID;
+typedef int ObjID;
+
+/* Possible attributes to request */
+
+#define VERTICES 1
+#define NORMALS 2
+#define COLORS 3
+#define TEXCOORDS 4
+#define SURFACEDIM 5
+#define TEXTS 6
+#define CEX 7
+#define ADJ 8
+#define RADII 9
+#define CENTERS 10
+#define IDS 11
+#define USERMATRIX 12
+#define TYPES 13
+#define FLAGS 14
+#define OFFSETS 15
+#define FAMILY 16
+#define FONT 17
+
+typedef unsigned int AttribID;
+
+class SceneNode
+{
+public:
+  inline const TypeID getTypeID() const { return typeID; }
+  inline const ObjID getObjID() const { return objID; }
+  virtual ~SceneNode() { };
+  static ObjID nextID;
+
+  /* Some nodes depend on the bbox, so we pass it to all */
+  virtual int getAttributeCount(AABox& bbox, AttribID attrib) { return 0; }
+  virtual void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result) { return; }
+  virtual String  getTextAttribute(AABox& bbox, AttribID attrib, int index) { return String(0, NULL); }
+  virtual void getTypeName(char* buffer, int buflen) = 0;
+
+protected:
+  SceneNode(const TypeID in_typeID) : typeID(in_typeID)
+  {  objID = nextID++; };
+private:
+  const TypeID typeID;
+  ObjID objID;
+};
+
+/**
+ * used in find_if searches, so can't be a method
+ */
+ 
+bool sameID(SceneNode* node, int id);
+
+} // namespace rgl
+
+#endif // SCENENODE_H
+ 
diff --git a/src/Shape.cpp b/src/Shape.cpp
new file mode 100644
index 0000000..5858957
--- /dev/null
+++ b/src/Shape.cpp
@@ -0,0 +1,154 @@
+
+#include <algorithm>
+#include <functional>
+
+#include "Shape.h"
+#include "SceneNode.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Shape
+//
+
+Shape::Shape(Material& in_material, bool in_ignoreExtent, TypeID in_typeID, bool in_bboxChanges)
+: SceneNode(in_typeID), bboxChanges(in_bboxChanges), ignoreExtent(in_ignoreExtent), material(in_material), 
+  displayList(0), drawLevel(0), doUpdate(true), transparent(in_material.isTransparent()),
+  blended(in_material.isTransparent())
+  
+{
+}
+
+Shape::~Shape()
+{
+  if (displayList)
+    glDeleteLists(displayList, 1);
+}
+
+void Shape::update(RenderContext* renderContext)
+{
+  doUpdate = false;
+}
+
+void Shape::draw(RenderContext* renderContext)
+{ 
+  drawBegin(renderContext);
+  SAVEGLERROR;
+  
+  for(int i=0;i<getElementCount();i++) 
+    drawElement(renderContext, i);
+    
+  SAVEGLERROR;  
+  drawEnd(renderContext);
+  SAVEGLERROR;
+}
+
+void Shape::render(RenderContext* renderContext)
+{
+  renderBegin(renderContext);
+  
+  if (displayList == 0)
+    displayList = glGenLists(1);
+    
+  SAVEGLERROR;
+  if (doUpdate) {
+    update(renderContext);
+    SAVEGLERROR;
+    glNewList(displayList, GL_COMPILE_AND_EXECUTE);
+    SAVEGLERROR;
+    draw(renderContext);
+    SAVEGLERROR;
+    glEndList();
+    SAVEGLERROR;
+  } else {
+    glCallList(displayList);
+    SAVEGLERROR;
+  }  
+}
+
+void Shape::invalidateDisplaylist()
+{
+  doUpdate = true;
+}
+
+void Shape::drawBegin(RenderContext* renderContext)
+{
+  if (drawLevel) {
+    drawLevel = 0;
+    error("Internal error:  nested Shape::drawBegin");
+  }
+  drawLevel++;
+}
+
+void Shape::drawEnd(RenderContext* renderContext)
+{
+  if (drawLevel != 1) {
+    drawLevel = 0;
+    error("Internal error: Shape::drawEnd without drawBegin");
+  }
+  drawLevel--;
+}
+
+int Shape::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) { 
+    case COLORS:  return material.colors.getLength();
+    case CENTERS: return getElementCount();
+    case FLAGS:   return 1;
+  }
+  return 0;
+}
+
+void Shape::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch (attrib) {
+      case COLORS:
+        while (first < n) {
+          Color color = material.colors.getColor(first);
+          *result++ = color.data[0];
+          *result++ = color.data[1];
+          *result++ = color.data[2];
+          *result++ = color.data[3];
+          first++;
+        }
+        return;
+      case CENTERS:
+        while (first < n) {
+          Vertex center = getElementCenter(first);
+          *result++ = center.x;
+          *result++ = center.y;
+          *result++ = center.z;
+          first++;
+        }
+        return;
+      case FLAGS:
+        if (first == 0) *result++ = (double)ignoreExtent;
+        return;
+    }
+  }
+}
+
+Shape* rgl::get_shape_from_list(std::vector<Shape*> shapes, int id, bool recursive)
+{
+  std::vector<Shape*>::iterator ishape;
+
+  if (shapes.empty()) 
+    return NULL;
+  
+  ishape = std::find_if(shapes.begin(), shapes.end(), 
+                        std::bind2nd(std::ptr_fun(&sameID), id));
+  if (ishape != shapes.end()) return *ishape;
+  
+  if (recursive) 
+    for (std::vector<Shape*>::iterator i = shapes.begin(); i != shapes.end() ; ++ i ) {
+      Shape* shape = (*i)->get_shape(id);
+      if (shape) return shape;
+    }
+  return NULL;
+}
diff --git a/src/Shape.h b/src/Shape.h
new file mode 100644
index 0000000..1cecacd
--- /dev/null
+++ b/src/Shape.h
@@ -0,0 +1,177 @@
+#ifndef SHAPE_H
+#define SHAPE_H
+
+#include <vector>
+
+#include "SceneNode.h"
+#include "Material.h"
+#include "RenderContext.h"
+
+#include "opengl.h"
+#include "geom.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   Shape
+//
+
+class Shape : public SceneNode
+{
+public:
+  Shape(Material& in_material,bool in_ignoreExtent, TypeID in_typeID=SHAPE, bool in_bboxChanges=false);
+  ~Shape();
+  
+  /**
+   * render shape.
+   * Default Implementation: uses z-buffer and a display list 
+   * that stores everything from a call to draw().  
+   **/
+  virtual void render(RenderContext* renderContext);
+
+  /**
+   * request update of node due to content change. 
+   * This will result in a new 'recording' of the display list.
+   **/
+  virtual void update(RenderContext* renderContext);
+
+  /**
+   * draw. 
+   **/
+  virtual void draw(RenderContext* renderContext);
+
+  /**
+   * obtain bounding box
+   **/
+  const AABox& getBoundingBox() const { return boundingBox; }
+  
+  /**
+   * does this shape change dimensions according to the way it is rendered?
+   * if so, the above is just a guess...
+   **/
+  const bool getBBoxChanges() const { return bboxChanges; }
+
+  /**
+   * this shows how the shape would be sized in the given context
+   **/
+  virtual AABox& getBoundingBox(Subscene* subscene) { return boundingBox; }
+  
+  /**
+   * obtain material
+   **/
+  Material* getMaterial()  { return &material; }
+  
+  const bool getIgnoreExtent() const { return ignoreExtent; }
+
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "shape", buflen); };
+  
+  /**
+   * invalidate display list
+   **/
+  void invalidateDisplaylist();
+  
+  /**
+   * access to individual items
+   **/
+   
+  virtual int getElementCount(void) = 0; 
+
+  /* overrides */
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  
+  /**
+   * location of individual items
+   **/
+  
+  virtual Vertex getElementCenter(int index) { return boundingBox.getCenter(); }
+
+  /**
+   * Starting to render the shape.  After this, the renderContext won't change until
+   * the next call.  This will only be called once per rendering.
+   **/
+  virtual void renderBegin(RenderContext* renderContext) { };
+
+  /**
+   * begin sending items.  This may be called multiple times, e.g. if the
+   * items are being intermixed with items from other shapes
+   **/
+  virtual void drawBegin(RenderContext* renderContext);
+
+  /**
+   * send one item
+   **/
+  virtual void drawElement(RenderContext* renderContext, int index) = 0;
+
+  /**
+   * end sending items
+   **/
+  virtual void drawEnd(RenderContext* renderContext);
+  
+  /**
+   * Some shapes (currently just sprites) contain others.  Do a recursive search
+   */
+  virtual Shape* get_shape(int id) { return NULL; }
+  
+  const bool isTransparent() const { return transparent; }
+  
+  const bool isBlended() const { return blended; }
+  
+  /**
+   * Does this shape need to go at the head of the shape list, rather than the tail?
+   * (e.g. clip planes need to come first 
+   **/
+  
+  virtual bool isClipPlane() { return false; }
+  
+protected:
+  /**
+   * bounding volume of overall geometry
+   **/
+  AABox    boundingBox;
+  
+  /**
+   * bounding volume changes depending on the scene?
+   **/
+  bool     bboxChanges;
+  
+  /*
+   * whether this object should be ignored in scene bounding box calculations
+   */ 
+  bool     ignoreExtent; 
+  
+  /**
+   * material
+   **/
+  Material material;
+private:
+  /**
+   * display list
+   **/
+  GLuint   displayList;
+  int	   drawLevel;     /* for debugging */
+protected:
+  /**
+   * update indicator
+   **/
+  bool     doUpdate;
+  bool     transparent, blended;
+};
+
+class ShapeItem {
+public:
+  ShapeItem(Shape* in_shape, int in_itemnum) : shape(in_shape), itemnum(in_itemnum) {};
+  Shape* shape;
+  int itemnum;
+};
+
+/**
+ * This function is used both in Scene::get_shape and in SpriteSet::get_shape
+ */
+ 
+Shape* get_shape_from_list(std::vector<Shape*> shapes, int id, bool recursive);
+
+} // namespace rgl
+
+#endif // SHAPE_H
diff --git a/src/SphereMesh.cpp b/src/SphereMesh.cpp
new file mode 100644
index 0000000..94a7c6b
--- /dev/null
+++ b/src/SphereMesh.cpp
@@ -0,0 +1,151 @@
+#include "SphereMesh.h"
+
+#include "opengl.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   SphereMesh
+//
+
+
+SphereMesh::SphereMesh()
+: center( Vertex(0.0f,0.0f,0.0f) ), 
+  radius( 1.0f ),
+  philow(-90.0f ),
+  phihigh( 90.0f ),
+  segments( 16 ),
+  sections( 16 ),
+  type( GLOBE ),
+  genNormal(false),
+  genTexCoord(false)
+{
+}
+
+void SphereMesh::setGlobe(int in_segments, int in_sections)
+{
+  type     = GLOBE;
+  segments = in_segments;
+  sections = in_sections;
+  setupMesh();
+}
+
+void SphereMesh::setTesselation(int level)
+{
+  type     = TESSELATION;
+}
+
+void SphereMesh::setupMesh()
+{
+  // setup arrays
+
+  int nvertex = (sections+1) * (segments+1);
+
+  vertexArray.alloc(nvertex);
+
+  if (genNormal)
+    normalArray.alloc(nvertex);
+
+  if (genTexCoord)
+    texCoordArray.alloc(nvertex);  
+}
+
+void SphereMesh::setCenter(const Vertex& in_center)
+{
+  center = in_center;
+}
+
+void SphereMesh::setRadius(float in_radius)
+{
+  radius = in_radius;
+}
+
+void SphereMesh::update()
+{
+  Vertex scale;
+  scale.x = scale.y = scale.z = 1.0;
+  update(scale);
+}
+
+void SphereMesh::update(const Vertex& scale)
+{
+  int i = 0;
+
+  for(int iy=0;iy<=sections;iy++) {
+
+    Vertex p(0.0f,0.0f,radius);
+
+    float fy = ((float)iy)/((float)sections);
+
+    float phi = philow + fy * (phihigh - philow);
+
+    p.rotateX( -phi );
+
+    for (int ix=0;ix<=segments;ix++,i++) {
+
+      float fx  = ((float)ix)/((float)segments);
+      float theta = fx * 360.0f;
+
+      Vertex q(p);
+
+      q.rotateY( theta );
+      
+      q.x /= scale.x;
+      q.y /= scale.y;
+      q.z /= scale.z;
+
+      vertexArray[i] = center + q;
+
+      if (genNormal) {
+	q.x *= scale.x*scale.x;
+	q.y *= scale.y*scale.y;
+	q.z *= scale.z*scale.z;
+        normalArray[i] = q;
+        normalArray[i].normalize();
+      }
+
+      if (genTexCoord) {
+        texCoordArray[i].s = fx;
+        texCoordArray[i].t = fy;
+      }
+
+    }
+  }
+}
+
+void SphereMesh::draw(RenderContext* renderContext)
+{
+  vertexArray.beginUse();
+
+  if (genNormal)
+    normalArray.beginUse();
+
+  if (genTexCoord)
+    texCoordArray.beginUse();
+
+  for(int i=0; i<sections; i++ ) {
+
+    int curr = i * (segments+1);
+    int next = curr + (segments+1);
+
+    glBegin(GL_QUAD_STRIP);
+    for(int i=0;i<=segments;i++) {
+      glArrayElement( next + i );
+      glArrayElement( curr + i );
+    }
+    glEnd();
+  }
+
+  vertexArray.endUse();
+
+  if (genNormal)
+    normalArray.endUse();
+
+  if (genTexCoord)
+    texCoordArray.endUse();
+}
+
+
+
diff --git a/src/SphereMesh.h b/src/SphereMesh.h
new file mode 100644
index 0000000..8f761f9
--- /dev/null
+++ b/src/SphereMesh.h
@@ -0,0 +1,64 @@
+#ifndef SPHERE_MESH_H
+#define SPHERE_MESH_H
+
+#include "render.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   SphereMesh
+//
+
+class SphereMesh
+{
+public:
+
+  enum Type { GLOBE, TESSELATION };
+
+  SphereMesh();
+
+  inline void setGenNormal   (bool in_genNormal)
+  { genNormal = in_genNormal; }
+  inline void setGenTexCoord (bool in_genTexCoord)
+  { genTexCoord = in_genTexCoord; }
+
+  void setGlobe       (int segments, int sections);
+  void setTesselation (int level);
+
+  void setCenter      (const Vertex& center);
+  void setRadius      (float radius);
+  void update();
+  void update	      (const Vertex& scale);
+
+/*
+  void beginDraw(RenderContext* renderContext);
+  void drawSection(int section);
+  void endDraw(RenderContext* renderContext);
+*/
+
+  void draw(RenderContext* renderContext);
+
+private:
+  
+  Vertex center;
+  float  radius;
+  float  philow;
+  float  phihigh;
+  
+  VertexArray   vertexArray;
+  NormalArray   normalArray;
+  TexCoordArray texCoordArray;
+
+  int    segments;
+  int    sections;
+  Type   type;
+  bool   genNormal;
+  bool   genTexCoord;
+
+  void   setupMesh();
+};
+
+} // namespace rgl
+
+#endif // SPHERE_MESH_H
diff --git a/src/SphereSet.cpp b/src/SphereSet.cpp
new file mode 100644
index 0000000..43ba2c0
--- /dev/null
+++ b/src/SphereSet.cpp
@@ -0,0 +1,115 @@
+#include "SphereSet.h"
+#include "Viewpoint.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   SphereSet
+//
+
+SphereSet::SphereSet(Material& in_material, int in_ncenter, double* in_center, int in_nradius, double* in_radius,
+                     int in_ignoreExtent)
+ : Shape(in_material, in_ignoreExtent, SHAPE, true), 
+   center(in_ncenter, in_center), 
+   radius(in_nradius, in_radius)
+{
+  material.colorPerVertex(false);
+
+  if (material.lit)
+    sphereMesh.setGenNormal(true);
+  if ( (material.texture) && (!material.texture->is_envmap() ) )
+    sphereMesh.setGenTexCoord(true);
+
+  sphereMesh.setGlobe(16,16);
+  
+  for (int i=0;i<center.size();i++)
+    boundingBox += Sphere( center.get(i), radius.getRecycled(i) );
+}
+
+SphereSet::~SphereSet()
+{
+}
+
+AABox& SphereSet::getBoundingBox(Subscene* subscene)
+{
+  Vertex scale = subscene->getModelViewpoint()->scale;
+  scale.x = 1.0/scale.x;
+  scale.y = 1.0/scale.y;
+  scale.z = 1.0/scale.z;
+  
+  boundingBox.invalidate();
+  for(int i=0;i<getElementCount();i++) {
+    boundingBox += center.get(i) + scale*radius.getRecycled(i);
+    boundingBox += center.get(i) - scale*radius.getRecycled(i);
+  }
+  return boundingBox;
+}
+
+void SphereSet::drawBegin(RenderContext* renderContext)
+{
+  Shape::drawBegin(renderContext);
+  material.beginUse(renderContext);
+}
+
+void SphereSet::drawElement(RenderContext* renderContext, int index) 
+{
+   if ( center.get(index).missing() || ISNAN(radius.getRecycled(index)) ) return;
+
+   material.useColor(index);
+
+   sphereMesh.setCenter( center.get(index) );
+   sphereMesh.setRadius( radius.getRecycled(index) );
+   
+   sphereMesh.update( renderContext->subscene->getModelViewpoint()->scale );
+
+   sphereMesh.draw(renderContext);
+}
+
+void SphereSet::drawEnd(RenderContext* renderContext)
+{
+  material.endUse(renderContext);
+  Shape::drawEnd(renderContext);  
+}
+
+void SphereSet::render(RenderContext* renderContext) 
+{
+  if (renderContext->subscene->getModelViewpoint()->scaleChanged) 
+    doUpdate = true;
+  Shape::render(renderContext);
+}
+
+int SphereSet::getAttributeCount(AABox& bbox, AttribID attrib) 
+{
+  switch (attrib) {
+    case RADII:    return radius.size();
+    case VERTICES: return center.size();
+  }
+  return Shape::getAttributeCount(bbox, attrib);
+}
+
+void SphereSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch (attrib) {
+      case VERTICES:
+        while (first < n) {
+          *result++ = center.get(first).x;
+          *result++ = center.get(first).y;
+          *result++ = center.get(first).z;
+          first++;
+        }
+        return;
+      case RADII:
+        while (first < n) 
+          *result++ = radius.get(first++);
+        return;
+    }  
+    Shape::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
diff --git a/src/SphereSet.h b/src/SphereSet.h
new file mode 100644
index 0000000..bb660bb
--- /dev/null
+++ b/src/SphereSet.h
@@ -0,0 +1,65 @@
+#ifndef SPHERESET_H
+#define SPHERESET_H
+
+#include "scene.h"
+#include "Shape.h"
+#include "SphereMesh.h"
+
+namespace rgl {
+
+class SphereSet : public Shape {
+private:
+  ARRAY<Vertex> center;
+  ARRAY<float>  radius;
+  SphereMesh    sphereMesh;
+public:
+  SphereSet(Material& in_material, int nsphere, double* center, int nradius, double* radius, 
+            int in_ignoreExtent);
+  ~SphereSet();
+
+  /**
+   * overload
+   **/
+  
+  /* Check whether scale has changed before rendering */
+  void render(RenderContext* renderContext);
+  
+  int getElementCount(void){ return center.size(); }
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  
+  /**
+   * location of individual items
+   **/
+  
+  Vertex getElementCenter(int index) { return center.get(index); }
+  
+  /**
+   * Spheres appear as spheres, so their bbox depends on scaling
+   **/
+   
+  virtual AABox& getBoundingBox(Subscene* subscene);
+
+
+  /**
+   * begin sending items 
+   **/
+  void drawBegin(RenderContext* renderContext);
+
+  /**
+   * send one item
+   **/
+  void drawElement(RenderContext* renderContext, int index);
+
+  /**
+   * end sending items
+   **/
+  void drawEnd(RenderContext* renderContext);
+
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "spheres", buflen); };
+
+};
+
+} // namespace rgl
+
+#endif // SPHERESET_H
diff --git a/src/SpriteSet.cpp b/src/SpriteSet.cpp
new file mode 100644
index 0000000..6adf72f
--- /dev/null
+++ b/src/SpriteSet.cpp
@@ -0,0 +1,203 @@
+
+#include "SpriteSet.h"
+#include "Shape.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   SpriteSet
+//
+
+SpriteSet::SpriteSet(Material& in_material, int in_nvertex, double* in_vertex, int in_nsize, double* in_size,
+                     int in_ignoreExtent, int count, Shape** in_shapelist, double* in_userMatrix)
+ : Shape(in_material, in_ignoreExtent), 
+  vertex(in_nvertex, in_vertex),
+   size(in_nsize, in_size)
+{ 
+  if (!count)
+    material.colorPerVertex(false);
+  else {
+    blended = false;
+    for (int i=0;i<count;i++) {
+      shapes.push_back(in_shapelist[i]);
+      blended |= in_shapelist[i]->isBlended();
+    }
+    for (int i=0;i<16;i++)
+      userMatrix[i] = *(in_userMatrix++);
+  }
+  for(int i=0;i<vertex.size();i++)
+    boundingBox += Sphere( vertex.get(i), size.getRecycled(i) );
+}
+
+SpriteSet::~SpriteSet()
+{ 
+  shapes.clear();
+}
+
+int SpriteSet::getElementCount(void) 
+{
+  return vertex.size();
+}
+  
+Vertex SpriteSet::getElementCenter(int index)
+{
+  return vertex.get(index);
+}
+
+void SpriteSet::drawBegin(RenderContext* renderContext)
+{
+  double mdata[16] = { 0 };
+  
+  Shape::drawBegin(renderContext);
+
+  glGetDoublev(GL_MODELVIEW_MATRIX, mdata);
+
+  m = Matrix4x4(mdata);
+
+  glPushMatrix();
+
+  if (!shapes.size()) {
+    doTex = (material.texture) ? true : false;
+    glNormal3f(0.0f,0.0f,1.0f);
+    material.beginUse(renderContext);
+  }
+}
+
+void SpriteSet::drawElement(RenderContext* renderContext, int index)
+{
+  Vertex& o = vertex.get(index);
+  float   s = size.getRecycled(index);
+  if (o.missing() || ISNAN(s)) return;
+
+  Vertex  v;
+  s = s * 0.5f;
+  v = m * o;
+
+  glLoadIdentity();
+  glTranslatef(v.x, v.y, v.z);
+  
+  if (shapes.size()) {
+    Shape::drawEnd(renderContext);  // The shape will call drawBegin/drawEnd
+
+    glMultMatrixd(userMatrix);
+    
+    glScalef(s,s,s);
+    for (std::vector<Shape*>::iterator i = shapes.begin(); i != shapes.end() ; ++ i ) 
+      (*i)->draw(renderContext);  
+    
+    Shape::drawBegin(renderContext);
+ }  else {
+    material.useColor(index);
+  
+    glBegin(GL_QUADS);
+  
+    if (doTex)
+      glTexCoord2f(0.0f,0.0f);
+    glVertex3f(-s, -s, 0.0f);
+ 
+    if (doTex)
+      glTexCoord2f(1.0f,0.0f);
+    glVertex3f(s, -s, 0.0f);
+
+    if (doTex)
+      glTexCoord2f(1.0f,1.0f);
+    glVertex3f(s, s, 0.0);
+
+    if (doTex)
+      glTexCoord2f(0.0f,1.0f);
+    glVertex3f(-s, s, 0.0f);  
+  
+    glEnd();
+  }
+}
+  
+void SpriteSet::drawEnd(RenderContext* renderContext)
+{
+  glPopMatrix();
+
+  if (!shapes.size())
+    material.endUse(renderContext);
+  Shape::drawEnd(renderContext);
+}
+
+void SpriteSet::render(RenderContext* renderContext)
+{ 
+    draw(renderContext);
+}
+
+int SpriteSet::getAttributeCount(AABox& bbox, AttribID attrib) 
+{
+  switch (attrib) {
+    case VERTICES: return vertex.size();
+    case RADII:    return size.size();
+    case IDS:	   
+    case TYPES:    return shapes.size();
+    case USERMATRIX: {
+      if (!shapes.size()) return 0;
+      else return 4;
+    }
+  }
+  return Shape::getAttributeCount(bbox, attrib);
+}
+
+void SpriteSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  int ind = 0;
+
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch(attrib) {
+      case VERTICES:
+        while (first < n) {
+          Vertex v = vertex.get(first);
+          *result++ = v.x;
+          *result++ = v.y;
+          *result++ = v.z;
+          first++;
+        }
+        return;     
+      case RADII:
+        while (first < n) 
+          *result++ = size.get(first++);
+        return;
+      case IDS:
+        for (std::vector<Shape*>::iterator i = shapes.begin(); i != shapes.end() ; ++ i ) {
+      	  if ( first <= ind  && ind < n )  
+            *result++ = (*i)->getObjID();
+          ind++;
+        }
+        return;
+      case USERMATRIX:
+        while (first < n) {
+          *result++ = userMatrix[first];
+          *result++ = userMatrix[4 + first];
+          *result++ = userMatrix[8 + first];
+          *result++ = userMatrix[12 + first];
+          first++;
+        }
+        return;
+    }  
+    Shape::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
+String SpriteSet::getTextAttribute(AABox& bbox, AttribID attrib, int index)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (index < n && attrib == TYPES) {
+    char* buffer = R_alloc(20, 1);    
+    shapes[index]->getTypeName(buffer, 20);
+    return String(strlen(buffer), buffer);
+  } else
+    return Shape::getTextAttribute(bbox, attrib, index);
+}
+
+
+Shape* SpriteSet::get_shape(int id)
+{
+  return get_shape_from_list(shapes, id, true);
+}
diff --git a/src/SpriteSet.h b/src/SpriteSet.h
new file mode 100644
index 0000000..e9d8043
--- /dev/null
+++ b/src/SpriteSet.h
@@ -0,0 +1,71 @@
+#ifndef SPRITE_SET_H
+#define SPRITE_SET_H
+
+#include <vector>
+#include "Shape.h"
+
+namespace rgl {
+
+//
+// SPRITESET
+//
+
+class SpriteSet : public Shape {
+private:
+  ARRAY<Vertex> vertex;
+  ARRAY<float>  size;
+
+public:
+  SpriteSet(Material& material, int nvertex, double* vertex, int nsize, double* size, 
+            int ignoreExtent, int count = 0, Shape** shapelist = NULL, double* userMatrix = NULL);
+  ~SpriteSet();
+
+  /**
+   * overload
+   **/
+  virtual void render(RenderContext* renderContext);
+  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "sprites", buflen); };
+  
+  virtual int getElementCount(void);
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  String getTextAttribute(AABox& bbox, AttribID attrib, int index);
+  
+  /**
+   * location of individual items
+   **/
+  
+  virtual Vertex getElementCenter(int index);
+  
+  /**
+   * begin sending items 
+   **/
+  virtual void drawBegin(RenderContext* renderContext);
+  
+  /**
+   * send one item
+   **/
+  virtual void drawElement(RenderContext* renderContext, int index);
+  
+  /**
+   * end sending items
+   **/
+  virtual void drawEnd(RenderContext* renderContext);
+  
+  /**
+   * extract individual shape
+   */
+  virtual Shape* get_shape(int id);
+  
+private:
+  GLdouble userMatrix[16]; /* Transformation for 3D sprites */
+  Matrix4x4 m;             /* Modelview matrix cache */
+  bool doTex;
+  std::vector<Shape*> shapes;
+
+};
+
+} // namespace rgl
+
+#endif // SPRITE_SET_H
diff --git a/src/String.cpp b/src/String.cpp
new file mode 100644
index 0000000..4c55aad
--- /dev/null
+++ b/src/String.cpp
@@ -0,0 +1,145 @@
+#include "String.h"
+#include "types.h"
+
+using namespace std;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// SECTION: Strings
+//
+
+//
+// CLASS
+//   StringArrayImpl
+//
+
+namespace rgl {
+
+class StringArrayImpl : public AutoDestroy
+{
+public:
+  StringArrayImpl(int in_ntexts, char** in_texts) 
+  {
+    int i;
+
+    ntexts = in_ntexts;
+
+    lengths = new unsigned int [ntexts];
+    starts = new unsigned int [ntexts];
+
+    int buflen = 0;
+
+    for(i=0;i<ntexts;i++) {
+      starts[i] = buflen;
+      buflen += 1 + ( lengths[i] = strlen(in_texts[i]) );
+    }
+    
+    char* tptr = textbuffer = new char [buflen];
+
+    for(i=0;i<ntexts;i++) {
+      int len = lengths[i];
+      memcpy(tptr, in_texts[i], 1 + len);
+      tptr += 1 + len;
+    }
+  }
+
+  ~StringArrayImpl()
+  {
+    delete [] lengths;
+    delete [] textbuffer;
+  }
+  int   ntexts;
+  char* textbuffer;
+  unsigned int*  lengths;
+  unsigned int*  starts;
+};
+
+}
+
+using namespace rgl;
+
+//
+// CLASS
+//   StringArray
+//
+
+StringArray::StringArray()
+{
+  impl = NULL;
+}
+
+StringArray::StringArray(int in_ntexts, char** in_texts)
+{
+  if (in_ntexts > 0) {
+    impl = new StringArrayImpl(in_ntexts, in_texts);
+    impl->ref();
+  }
+  else
+    impl = NULL;
+}
+
+StringArray::StringArray(StringArray& from)
+{
+  impl = from.impl;
+
+  if (impl)
+    impl->ref();
+}
+
+StringArray::~StringArray()
+{
+  if (impl)
+    impl->unref();
+}
+
+String StringArray::operator[](int index)
+{
+  if (impl && index < impl->ntexts)
+    return String(impl->lengths[index], impl->textbuffer + impl->starts[index]);
+  else
+    return String(0, NULL);
+}
+
+int StringArray::size()
+{
+  if (impl) return impl->ntexts;
+  else return 0;
+}
+
+//
+// CLASS
+//   StringArrayIterator
+//
+
+StringArrayIterator::StringArrayIterator(StringArray* in_array)
+{
+  array = in_array;
+}
+
+void StringArrayIterator::first()
+{
+  cnt = 0;
+  if (array->impl)
+    textptr = array->impl->textbuffer;
+  else
+    textptr = NULL;
+}
+
+void StringArrayIterator::next()
+{
+  if ( (textptr) && (cnt < array->impl->ntexts) )
+    textptr += 1 + array->impl->lengths[cnt++];
+}
+
+String StringArrayIterator::getCurrent()
+{
+  return String(array->impl->lengths[cnt], textptr );
+}
+
+bool StringArrayIterator::isDone() const 
+{
+  if (array->impl)
+    return (cnt == array->impl->ntexts) ? true : false;
+  else
+    return true;
+}
diff --git a/src/String.h b/src/String.h
new file mode 100644
index 0000000..c03f397
--- /dev/null
+++ b/src/String.h
@@ -0,0 +1,54 @@
+#ifndef STRING_H
+#define STRING_H
+
+namespace rgl {
+
+//
+// CLASS
+//   StringArray
+//
+
+struct String
+{
+  String(int in_length, char* in_text) {
+    length = in_length;
+    text   = in_text;
+  }
+  int   length;
+  char* text;
+};
+
+class StringArrayImpl;
+
+class StringArray
+{
+public:
+  StringArray();
+  StringArray(int ntexts, char** in_texts);
+  StringArray(StringArray& from);
+  ~StringArray();
+  String operator[](int index);
+  int size();
+
+private:
+  StringArrayImpl* impl;
+  friend class StringArrayIterator;
+};
+
+class StringArrayIterator
+{
+public:
+  StringArrayIterator(StringArray* array);
+  void first();
+  void next();
+  String getCurrent();
+  bool isDone() const;
+private:
+  StringArray* array;
+  int   cnt;
+  char* textptr;
+};
+
+} // namespace rgl
+
+#endif // STRING_H
diff --git a/src/Surface.cpp b/src/Surface.cpp
new file mode 100644
index 0000000..c8f22b4
--- /dev/null
+++ b/src/Surface.cpp
@@ -0,0 +1,311 @@
+#include "Surface.h"
+#include "Material.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Surface
+//
+// in_coords permutes the coordinates to allow surfaces over arbitrary planes
+// orientation is 1 to swap front and back
+
+Surface::Surface(Material& in_material, int in_nx, int in_nz, double* in_x, double* in_z, double* in_y,
+                 double* in_normal_x, double* in_normal_z, double* in_normal_y,
+                 double* in_texture_s, double* in_texture_t,
+	         int* in_coords, int in_orientation, int* in_flags, int in_ignoreExtent)
+: Shape(in_material, in_ignoreExtent)
+{
+  nx = in_nx;
+  nz = in_nz;
+  coords[0] = *(in_coords++);
+  coords[1] = *(in_coords++);
+  coords[2] = *(in_coords++);
+  orientation = in_orientation;
+
+  int nvertex = nx*nz;
+
+  material.colorPerVertex(true, nvertex);
+
+  vertexArray.alloc(nvertex);
+
+  if (material.texture)
+    texCoordArray.alloc(nvertex);
+
+  Vertex v;
+  float *x,*y,*z, *va[3];
+  
+  va[0] = &(v.x);
+  va[1] = &(v.y);
+  va[2] = &(v.z);
+  
+  x = va[coords[0]-1];
+  y = va[coords[1]-1];
+  z = va[coords[2]-1];
+  
+  int xmat = in_flags[0];
+  int zmat = in_flags[1];
+  user_normals = in_flags[2];
+  user_textures = in_flags[3];
+  
+  if (user_normals)
+    normalArray.alloc(nvertex);
+    
+  int iy  = 0;
+  for(int iz=0;iz<nz;iz++) {
+    for(int ix=0;ix<nx;ix++,iy++) {    
+      *z = (float) in_z[zmat ? iy : iz];
+      *x = (float) in_x[xmat ? iy : ix];
+      *y = (float) in_y[iy];
+
+      vertexArray[iy] = v;
+
+      boundingBox += v;
+	
+      if ( user_normals ) {
+        *x = (float) in_normal_x[iy];
+        *y = (float) in_normal_y[iy];
+        *z = (float) in_normal_z[iy];
+        
+        v.normalize();
+        normalArray[iy] = v;
+      }
+      
+      if ( (material.texture) && (! material.texture->is_envmap() ) ) {
+        if (!user_textures) {
+          texCoordArray[iy].s = ((float)ix)/((float)(nx-1));
+          texCoordArray[iy].t = 1.0f - ((float)iz)/((float)(nz-1));
+        } else {
+          texCoordArray[iy].s = in_texture_s[iy];
+          texCoordArray[iy].t = in_texture_t[iy];
+        }
+      }
+    }
+  }
+  use_normal    = user_normals || material.lit || ( material.texture && material.texture->is_envmap() );
+  if ( use_normal && !user_normals ) {
+    normalArray.alloc(nvertex);
+    iy = 0;
+    for(int iz=0;iz<nz;iz++) 
+      for(int ix=0;ix<nx;ix++,iy++) 
+        normalArray[iy] = getNormal(ix, iz);
+  }    
+  use_texcoord  = user_textures || ( material.texture && !(material.texture->is_envmap() ) ); 
+  if ((material.point_antialias && ( material.front == material.POINT_FACE 
+                                  || material.back  == material.POINT_FACE))
+   || (material.line_antialias  && ( material.front == material.LINE_FACE 
+                                  || material.back  == material.LINE_FACE))) blended = true;
+}
+
+Vertex Surface::getNormal(int ix, int iz)
+{
+  int i = iz*nx + ix;
+  Vertex total(0.0f,0.0f,0.0f);  
+  if (!vertexArray[i].missing()) {
+    // List the 8 surrounding vertices.  Repat the 1st one to make looping simpler. 
+    int ind[9];  
+    int xv[9] =  {    1,     1,      0,    -1,     -1,   -1,     0,      1,      1   };
+    int zv[9] =  {    0,     -1,     -1,   -1,     0,    1,      1,      1,      0   };    
+    int okay[9];  /* checks of surrounding vertices from right counterclockwise */
+    for (int j=0; j<8; j++) {
+      int xval = ix + xv[j], zval = iz + zv[j];
+      if (0 <= xval && xval < nx && 0 <= zval && zval < nz) {
+        ind[j] = i + xv[j] + zv[j]*nx; 
+        okay[j] = !vertexArray[ind[j]].missing();
+      } else {
+        okay[j] = 0;
+	ind[j] = 0;
+      }
+    }
+    okay[8] = okay[0];
+    ind[8] = ind[0];
+    /* Estimate normal by averaging cross-product in successive triangular sectors */
+    for (int j=0; j<8; j++) {
+      if (okay[j] && okay[j+1] ) 
+        total += vertexArray.getNormal(i, ind[j], ind[j+1] );
+    } 
+    total.normalize();
+  }
+  if (orientation) {
+    total.x = -total.x;
+    total.y = -total.y;
+    total.z = -total.z;
+  }
+  return total;
+}
+
+void Surface::draw(RenderContext* renderContext)
+{
+  bool missing;
+  drawBegin(renderContext);
+
+  for(int iz=0;iz<nz-1;iz++) {
+
+    missing = true;
+    
+    for(int ix=0;ix<nx;ix++) {
+
+      int i;
+      
+      if ( missing != (vertexArray[iz*nx+ix].missing() || vertexArray[(iz+1)*nx+ix].missing()) ) {
+        missing = !missing;
+        if (missing) glEnd();
+        else glBegin(GL_QUAD_STRIP);
+      }
+      if (!missing) {
+        // If orientation == 1, we draw iz+1 first, otherwise iz first      
+        i = (iz+  orientation)*nx+ix;
+  
+        glArrayElement( i );
+  
+        i = (iz+ !orientation)*nx+ix;
+        glArrayElement( i );
+      }
+    }
+    if (!missing) glEnd();
+  }
+
+  drawEnd(renderContext);
+}
+
+Vertex Surface::getCenter(int ix, int iz)
+{
+  Vertex accu(0.0f,0.0f,0.0f);
+  int num = 0;
+  if ( !vertexArray[iz*nx + ix].missing() ) {
+    accu = accu + vertexArray[iz*nx + ix];
+    num++;
+  }
+  if ( !vertexArray[iz*nx + ix+1].missing() ) {
+    accu = accu + vertexArray[iz*nx + ix+1];
+    num++;
+  }
+  if ( !vertexArray[(iz+1)*nx + ix].missing() ) {
+    accu = accu + vertexArray[(iz+1)*nx + ix];
+    num++;
+  }
+  if ( !vertexArray[(iz+1)*nx + ix+1].missing() ) {
+    accu = accu + vertexArray[(iz+1)*nx + ix+1];
+    num ++;
+  }
+  if (num) accu = accu * (1.0/num);
+  return accu;  
+} 
+
+Vertex Surface::getElementCenter(int index) 
+{
+  return getCenter( index % (nx-1), index / (nx-1) );
+}
+
+void Surface::drawBegin(RenderContext* renderContext)
+{
+  Shape::drawBegin(renderContext);
+  material.beginUse(renderContext);
+  vertexArray.beginUse();
+
+  if (use_texcoord)
+    texCoordArray.beginUse();
+    
+  if (use_normal)
+    normalArray.beginUse();
+
+}
+
+void Surface::drawElement(RenderContext* renderContext, int index)
+{
+  int ix = index % (nx-1), iz = index / (nx-1),
+      s = iz*nx + ix;
+  if (!vertexArray[s].missing() &&
+      !vertexArray[s+1].missing() &&
+      !vertexArray[s+nx].missing() &&
+      !vertexArray[s+nx+1].missing()) {
+    glBegin(GL_QUAD_STRIP);
+    for (int i = 0 ; i < 2; ++i ) {
+      ix = s % nx + i;
+      for (int j = 0 ; j < 2; ++j ) {
+        if (orientation)
+          iz = s / nx + !j;
+        else
+          iz = s / nx + j;
+        glArrayElement( iz*nx + ix );       
+      }
+    }
+    glEnd();
+  }
+}  
+  
+void Surface::drawEnd(RenderContext* renderContext) 
+{
+
+  if (use_normal)
+    normalArray.endUse();
+    
+  if (use_texcoord)
+    texCoordArray.endUse();
+
+  vertexArray.endUse();
+
+  material.endUse(renderContext);
+  Shape::drawEnd(renderContext);
+
+}
+
+int Surface::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) {
+    case VERTICES: return nx*nz;
+    case NORMALS: if (use_normal)
+    		    return nx*nz;
+    		  else
+    		    return 0;
+    case TEXCOORDS: if (use_texcoord) 
+    		      return nx*nz;
+    		    else
+    		      return 0;
+    case SURFACEDIM: return 1;
+  }
+  return Shape::getAttributeCount(bbox, attrib);
+}
+
+void Surface::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch (attrib) {
+      case VERTICES: {
+        while (first < n) {
+          *result++ = vertexArray[first].x;
+          *result++ = vertexArray[first].y;
+          *result++ = vertexArray[first].z;
+          first++;
+        }
+        return;
+      }        
+      case NORMALS: {
+        while (first < n) {
+          *result++ = normalArray[first].x;
+          *result++ = normalArray[first].y;
+          *result++ = normalArray[first].z;
+          first++;
+        }
+        return;
+      }
+      case TEXCOORDS: {
+        while (first < n) {
+          *result++ = texCoordArray[first].s;
+	  *result++ = texCoordArray[first].t;
+	  first++;
+	}
+	return;
+      }
+      case SURFACEDIM: {
+        *result++ = nx;
+        *result++ = nz;
+        return;
+      }
+    }
+    Shape::getAttribute(bbox, attrib, first, count, result);
+  }
+}
diff --git a/src/Surface.h b/src/Surface.h
new file mode 100644
index 0000000..ee9b8f0
--- /dev/null
+++ b/src/Surface.h
@@ -0,0 +1,70 @@
+#ifndef SURFACE_H
+#define SURFACE_H
+
+#include "Shape.h"
+
+#include "render.h"
+
+#include <map>
+
+namespace rgl {
+
+//
+// CLASS
+//   Surface
+//
+
+class Surface : public Shape {
+public:
+  Surface(Material& material, int nx, int nz, double* x, double* z, double* y,
+	         double* normal_x, double* normal_z, double* normal_y,
+	         double* texture_s, double* texture_t,
+	         int* coords, int orientation, int* flags, int ignoreExtent);
+  /**
+   * overload
+   **/
+  virtual void draw(RenderContext* renderContext);
+  
+  /* Center of square with upper left at (ix, iz) */
+  Vertex getCenter(int ix, int iz);  
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "surface", buflen); };
+  
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  
+  virtual int getElementCount(void) { return (nx-1)*(nz-1); }
+  
+  /**
+   * location of individual items
+   **/
+  
+  virtual Vertex getElementCenter(int item) ;
+
+  /**
+   * begin sending items 
+   **/
+  virtual void drawBegin(RenderContext* renderContext) ;
+
+  /**
+   * send one item
+   **/
+  virtual void drawElement(RenderContext* renderContext, int index) ;
+
+  /**
+   * end sending items
+   **/
+  virtual void drawEnd(RenderContext* renderContext) ;
+  
+private:
+  Vertex getNormal(int ix, int iz);
+
+  VertexArray vertexArray;
+  NormalArray normalArray;
+  TexCoordArray texCoordArray;
+  int nx, nz, coords[3], orientation, user_normals, user_textures;
+  bool use_normal, use_texcoord; 
+};
+
+} // namespace rgl
+
+#endif // SURFACE_H
diff --git a/src/TextSet.cpp b/src/TextSet.cpp
new file mode 100644
index 0000000..8297605
--- /dev/null
+++ b/src/TextSet.cpp
@@ -0,0 +1,156 @@
+#include "TextSet.h"
+
+#include "glgui.h"
+#include "R.h"
+#ifdef HAVE_FREETYPE
+#include <map>
+#endif
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   TextSet
+//
+// INTERNAL TEXTS STORAGE
+//   texts are copied to a buffer without null byte
+//   a separate length buffer holds string lengths in order
+//
+
+TextSet::TextSet(Material& in_material, int in_ntexts, char** in_texts, double *in_center, 
+                 double in_adjx, double in_adjy,
+                 int in_ignoreExtent, FontArray& in_fonts)
+ : Shape(in_material, in_ignoreExtent), textArray(in_ntexts, in_texts)
+{
+  int i;
+
+  material.lit = false;
+  material.colorPerVertex(false);
+
+  adjx = in_adjx;
+  adjy = in_adjy;
+
+  // init vertex array
+
+  vertexArray.alloc(in_ntexts);
+
+  fonts = in_fonts;
+#ifdef HAVE_FREETYPE  
+  blended = true;
+#endif  
+    
+  for (i=0;i<in_ntexts;i++) {
+
+    vertexArray[i].x = (float) in_center[i*3+0];
+    vertexArray[i].y = (float) in_center[i*3+1];
+    vertexArray[i].z = (float) in_center[i*3+2];
+
+    boundingBox += vertexArray[i];
+      
+    if (!fonts[i % fonts.size()])
+      error("font not available");
+    if (!fonts[i % fonts.size()]->valid(textArray[i].text))
+      error("text %d contains unsupported character", i+1);
+  }
+
+}
+
+TextSet::~TextSet()
+{
+}
+
+void TextSet::render(RenderContext* renderContext) 
+{
+  draw(renderContext);
+}
+
+void TextSet::drawBegin(RenderContext* renderContext) 
+{
+  Shape::drawBegin(renderContext);
+  material.beginUse(renderContext);
+}
+
+void TextSet::drawElement(RenderContext* renderContext, int index) 
+{
+  GLFont* font;
+
+  if (!vertexArray[index].missing()) {
+    GLboolean valid;
+    material.useColor(index);
+    glRasterPos3f( vertexArray[index].x, vertexArray[index].y, vertexArray[index].z );
+    glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid);
+    if (valid) {
+      font = fonts[index % fonts.size()];
+      if (font) {
+        String text = textArray[index];
+        font->draw( text.text, text.length, adjx, adjy, *renderContext );
+      }
+    }
+  }
+}
+
+void TextSet::drawEnd(RenderContext* renderContext)
+{
+  material.endUse(renderContext);
+  Shape::drawEnd(renderContext);
+}
+
+int TextSet::getAttributeCount(AABox& bbox, AttribID attrib) 
+{
+  switch (attrib) {
+    case FAMILY: 
+    case FONT:
+    case CEX: return fonts.size();
+    case TEXTS:
+    case VERTICES: return textArray.size();
+    case ADJ: return 1;
+  }
+  return Shape::getAttributeCount(bbox, attrib);
+}
+
+void TextSet::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch(attrib) {
+    case VERTICES:
+      while (first < n) {
+        *result++ = vertexArray[first].x;
+        *result++ = vertexArray[first].y;
+        *result++ = vertexArray[first].z;
+        first++;
+      }
+      return;
+    case CEX:
+      while (first < n) 
+        *result++ = fonts[first++]->cex;
+      return;
+    case FONT:
+      while (first < n)
+      	*result++ = fonts[first++]->style;
+      return;
+    case ADJ:
+      *result++ = adjx;
+      *result++ = adjy;
+      return;
+    }
+    Shape::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
+String TextSet::getTextAttribute(AABox& bbox, AttribID attrib, int index)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (index < n) {
+    switch (attrib) {
+    case TEXTS: 
+      return textArray[index];
+    case FAMILY:
+      char* family = fonts[index]->family;
+      return String(strlen(family), family);
+    }
+  }
+  return Shape::getTextAttribute(bbox, attrib, index);
+}
diff --git a/src/TextSet.h b/src/TextSet.h
new file mode 100644
index 0000000..0385d25
--- /dev/null
+++ b/src/TextSet.h
@@ -0,0 +1,54 @@
+#ifndef TEXTSET_H
+#define TEXTSET_H
+
+#include "Shape.h"
+
+#include "render.h"
+#include "String.h"
+#include "glgui.h"
+#ifdef HAVE_FREETYPE
+#include "FTGL/ftgl.h"
+#endif
+
+namespace rgl {
+
+//
+// TEXTSET
+//
+
+class TextSet : public Shape {
+public:
+  TextSet(Material& in_material, int in_ntexts, char** in_texts, double *in_center, 
+          double in_adjx, double in_adjy,
+          int in_ignoreExtent, FontArray& in_fonts);
+  ~TextSet();
+  /* Can't use display lists */
+  void render(RenderContext* renderContext);
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "text", buflen); };
+
+  int getElementCount(void){ return textArray.size(); }
+  int getAttributeCount(AABox& bbox, AttribID attrib);
+  void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  String getTextAttribute(AABox& bbox, AttribID attrib, int index);
+    
+  Vertex getElementCenter(int index) { return vertexArray[index]; }
+
+  void drawBegin(RenderContext* renderContext);
+  void drawElement(RenderContext* renderContext, int index);
+  void drawEnd(RenderContext* renderContext);
+
+private:
+
+  VertexArray vertexArray;
+  StringArray textArray;
+  FontArray fonts;
+
+  double adjx;
+  double adjy;
+
+};
+
+} // namespace rgl
+
+#endif // TEXTSET_H
+
diff --git a/src/Texture.cpp b/src/Texture.cpp
new file mode 100644
index 0000000..5865410
--- /dev/null
+++ b/src/Texture.cpp
@@ -0,0 +1,279 @@
+
+#include "Texture.h"
+#include "pixmap.h"
+#include "config.h"
+#include "platform.h"
+#include "RenderContext.h"
+
+using namespace std;
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Texture
+//
+
+Texture::Texture(
+  const char* in_filename
+, Type in_type
+, bool in_mipmap
+, unsigned int in_minfilter
+, unsigned int in_magfilter
+, bool in_envmap)
+{
+  texName = 0;
+  pixmap = new Pixmap();
+  type   = in_type;
+  mipmap = in_mipmap;
+  envmap = in_envmap;
+  magfilter = (in_magfilter) ? GL_LINEAR : GL_NEAREST;
+  if (mipmap) {
+    switch(in_minfilter) {
+      case 0:
+        minfilter = GL_NEAREST;
+        break;
+      case 1:
+        minfilter = GL_LINEAR;
+        break;
+      case 2:
+        minfilter = GL_NEAREST_MIPMAP_NEAREST;
+        break;
+      case 3:
+        minfilter = GL_NEAREST_MIPMAP_LINEAR;
+        break;
+      case 4:
+        minfilter = GL_LINEAR_MIPMAP_NEAREST;
+        break;
+      default:
+        minfilter = GL_LINEAR_MIPMAP_LINEAR;
+        break;
+    }
+  } else {
+    switch(in_minfilter) {
+      case 0:
+        minfilter = GL_NEAREST;
+        break;
+      default:
+        minfilter = GL_LINEAR;
+        break;
+    }
+  }
+  
+  filename = new char [1 + strlen(in_filename)];
+  memcpy(filename, in_filename, 1 + strlen(in_filename));
+  
+  if ( !pixmap->load(filename) ) {
+    delete pixmap;
+    pixmap = NULL;
+  }
+}
+
+Texture::~Texture()
+{
+  if (texName) {
+    glDeleteTextures(1, &texName);
+  }
+  if (pixmap)
+    delete pixmap;
+}
+
+
+bool Texture::isValid() const 
+{
+  return (pixmap) ? true : false;
+}
+
+void Texture::getParameters(Type *out_type, bool *out_mipmap, 
+                            unsigned int *out_minfilter, unsigned int *out_magfilter, 
+                            bool *out_envmap, int buflen, char *out_filename)
+{
+  *out_type = type;
+  *out_mipmap = mipmap;
+  switch(minfilter) {
+      case GL_NEAREST:
+        *out_minfilter = 0;
+        break;
+      case GL_LINEAR:
+        *out_minfilter = 1;      
+        break;
+      case GL_NEAREST_MIPMAP_NEAREST:
+        *out_minfilter = 2;
+        break;
+      case GL_NEAREST_MIPMAP_LINEAR:
+        *out_minfilter = 3;
+        break;
+      case GL_LINEAR_MIPMAP_NEAREST:
+        *out_minfilter = 4;
+        break;
+      case GL_LINEAR_MIPMAP_LINEAR:
+        *out_minfilter = 5;
+        break;
+      default:
+        *out_minfilter = 6;
+        break;
+  }
+  *out_magfilter = (magfilter == GL_LINEAR) ? 1 : 0;
+  *out_envmap = envmap;
+  strncpy(out_filename, filename, buflen);
+}
+
+#ifndef MODERN_OPENGL
+static unsigned int texsize(unsigned int s)
+{
+  return 1U << msb(s-1);
+}
+
+#include "lib.h"
+
+static void printGluErrorMessage(GLint error) 
+{
+  const GLubyte* gluError;
+  char buf[256];        
+  gluError = gluErrorString (error);
+  sprintf(buf, "GLU Library Error : %s", (const char*) gluError);
+  printMessage(buf);
+}
+#endif
+
+void Texture::init(RenderContext* renderContext)
+{
+  glGenTextures(1, &texName);
+  glBindTexture(GL_TEXTURE_2D, texName);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minfilter);                                                       
+  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magfilter);
+
+  GLint  internalFormat = 0;
+  GLenum format = 0;
+  GLint  ualign;
+  unsigned int bytesperpixel = 0;
+
+  switch(type)
+  {
+  case ALPHA:
+    internalFormat = GL_ALPHA;
+    break;
+  case LUMINANCE:
+    internalFormat = GL_LUMINANCE;
+    break;
+  case LUMINANCE_ALPHA:
+    internalFormat = GL_LUMINANCE_ALPHA;
+    break;
+  case RGB:
+    internalFormat = GL_RGB;
+    break;
+  case RGBA:
+    internalFormat = GL_RGBA;
+    break;
+  }
+
+  switch(pixmap->typeID)
+  {
+  case GRAY8:
+    ualign = 1;
+    bytesperpixel = 1;
+    switch(internalFormat)
+    {
+    case GL_LUMINANCE:
+      format = GL_LUMINANCE;
+      break;
+    case GL_ALPHA:
+      format = GL_ALPHA;
+      break;
+    case GL_LUMINANCE_ALPHA:
+      format = GL_LUMINANCE;
+      break;
+    }
+    break;
+  case RGB24:
+    ualign = 1;
+    format = GL_RGB;
+    bytesperpixel = 3;
+    break;
+  case RGB32:
+    ualign = 2;
+    format = GL_RGB;
+    bytesperpixel = 4;
+    break;
+  case RGBA32:
+    ualign = 2;
+    format = GL_RGBA;
+    bytesperpixel = 4;
+    break;
+  default: // INVALID
+    return;
+  }
+
+  glPixelStorei(GL_UNPACK_ALIGNMENT, ualign);
+  GLenum gl_type = GL_UNSIGNED_BYTE;
+  
+  GLint glTexSize;
+  glGetIntegerv(GL_MAX_TEXTURE_SIZE,  &glTexSize );        
+  
+  #ifdef MODERN_OPENGL
+  glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, pixmap->width, pixmap->height, 0, format, gl_type , pixmap->data);
+  if (mipmap)
+    glGenerateMipmap(GL_TEXTURE_2D);
+  #else
+  unsigned int maxSize = static_cast<unsigned int>(glTexSize);
+  if (mipmap) {                  
+    int gluError = gluBuild2DMipmaps(GL_TEXTURE_2D, internalFormat, pixmap->width, pixmap->height, format, gl_type, pixmap->data);    
+    if (gluError)
+      printGluErrorMessage(gluError);
+  } else {
+    unsigned int width  = texsize(pixmap->width);
+    unsigned int height = texsize(pixmap->height);
+    
+    if ( (width > maxSize) || (height > maxSize) ) {
+      char buf[256];
+      sprintf(buf, "GL Library : Maximum texture size of %dx%d exceeded.\n(Perhaps enabling mipmapping could help.)", maxSize,maxSize);
+      printMessage(buf);
+    } else if ( (pixmap->width != width) || ( pixmap->height != height) ) {
+      char* data = new char[width * height * bytesperpixel];
+      int gluError = gluScaleImage(format, pixmap->width, pixmap->height, gl_type, pixmap->data, width, height, gl_type, data);
+      if (gluError)
+        printGluErrorMessage(gluError);
+      glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, gl_type , data);
+      delete[] data;
+    } else {
+      glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, pixmap->width, pixmap->height, 0, format, gl_type , pixmap->data);
+    }
+  }
+  #endif /* not MODERN_OPENGL */
+  
+  if (envmap) {
+    glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+    glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
+    glEnable(GL_TEXTURE_GEN_S);
+    glEnable(GL_TEXTURE_GEN_T);
+  }
+  delete pixmap;
+  pixmap = NULL;
+}
+
+void Texture::beginUse(RenderContext* renderContext)
+{
+  if (!texName) {
+    init(renderContext);
+  }
+  glPushAttrib(GL_TEXTURE_BIT|GL_ENABLE_BIT|GL_CURRENT_BIT);
+  
+
+  glEnable(GL_TEXTURE_2D);
+  glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+  glBindTexture(GL_TEXTURE_2D, texName);
+
+  if (type == ALPHA) {
+    glEnable(GL_BLEND);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+  }
+}
+
+void Texture::endUse(RenderContext* renderContext)
+{
+  glPopAttrib();
+}
+
+
diff --git a/src/Texture.h b/src/Texture.h
new file mode 100644
index 0000000..527ad2c
--- /dev/null
+++ b/src/Texture.h
@@ -0,0 +1,54 @@
+#ifndef TEXTURE_H
+#define TEXTURE_H
+
+#include "pixmap.h"
+#include "types.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   Texture
+//
+
+class RenderContext;
+class Pixmap;
+
+#include "opengl.h"
+
+class Texture : public AutoDestroy
+{
+public:
+ 
+  enum Type { ALPHA = 1 , LUMINANCE, LUMINANCE_ALPHA, RGB, RGBA };
+
+  Texture(const char* in_filename
+   , Type type
+   , bool mipmap
+   , unsigned int minfilter
+   , unsigned int magfilter
+   , bool envmap);
+  virtual ~Texture();
+  bool isValid() const;
+  void beginUse(RenderContext* renderContext);
+  void endUse(RenderContext* renderContext);
+  bool is_envmap() const { return envmap; }
+  bool hasAlpha() const { return (type == ALPHA || type == LUMINANCE_ALPHA || type == RGBA ); }
+  void getParameters(Type *out_type, bool *out_mipmap, unsigned int *out_minfilter, 
+                     unsigned int *out_magfilter, bool *out_envmap, int bufsize, char *out_filename) ;
+  Pixmap* getPixmap() const { return pixmap; }
+private:
+  void init(RenderContext* renderContext);
+  Pixmap* pixmap;
+  GLuint  texName;
+  Type    type;
+  bool    mipmap;
+  GLenum  minfilter;
+  GLenum  magfilter;
+  bool    envmap;
+  char*   filename;
+};
+
+} // namespace rgl
+
+#endif // TEXTURE_H
diff --git a/src/Viewpoint.cpp b/src/Viewpoint.cpp
new file mode 100644
index 0000000..019de88
--- /dev/null
+++ b/src/Viewpoint.cpp
@@ -0,0 +1,244 @@
+#include "Viewpoint.h"
+
+#include "subscene.h"
+#include "opengl.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   UserViewpoint -- the viewer's portion of the viewpoint
+//   ModelViewpoint -- the model's portion
+//
+//   These were previously just one Viewpoint class, but subscenes mean they need to be split
+//
+
+UserViewpoint::UserViewpoint(float in_fov, float in_zoom) :
+    SceneNode(USERVIEWPOINT),
+    fov(in_fov),
+    zoom(in_zoom),
+    viewerInScene(false)
+{
+}
+
+ModelViewpoint::ModelViewpoint(PolarCoord in_position, Vec3 in_scale, bool in_interactive) :
+    SceneNode(MODELVIEWPOINT),
+    interactive(in_interactive)
+{
+    scale = in_scale;
+    scaleChanged = true;    
+     
+    setPosition(in_position);
+    clearMouseMatrix();
+}
+
+PolarCoord& ModelViewpoint::getPosition()
+{
+  return position;
+}
+
+ModelViewpoint::ModelViewpoint(double* in_userMatrix, Vec3 in_scale, bool in_interactive) :
+    SceneNode(MODELVIEWPOINT),
+    position( PolarCoord(0.0f, 0.0f) ),
+    interactive(in_interactive)
+{
+    for (int i=0; i<16; i++) {
+	userMatrix[i] = in_userMatrix[i];
+    }
+    scale = in_scale;
+    scaleChanged = true;
+    
+    clearMouseMatrix();
+}
+
+
+void ModelViewpoint::setPosition(const PolarCoord& in_position)
+{
+    Matrix4x4 M,N;
+    M.setRotate(0, in_position.phi);
+    N.setRotate(1, -in_position.theta);
+    M = M * N;
+    M.getData((double*)userMatrix);
+    position = in_position;
+}
+
+void ModelViewpoint::clearMouseMatrix()
+{
+    Matrix4x4 M;
+    M.setIdentity();
+    M.getData((double*)mouseMatrix);
+}
+
+float UserViewpoint::getZoom() const
+{
+  return zoom;
+}
+
+void UserViewpoint::setZoom(const float in_zoom)
+{
+  zoom = in_zoom;
+}
+
+bool ModelViewpoint::isInteractive() const
+{
+  return interactive;
+}
+
+void UserViewpoint::setFOV(const float in_fov)
+{
+  fov = clamp(in_fov, 0.0, 179.0 );
+}
+
+float UserViewpoint::getFOV() const
+{
+  return fov;
+}
+
+void UserViewpoint::setupFrustum(RenderContext* rctx, const Sphere& viewSphere)
+{
+  frustum.enclose(viewSphere.radius, fov, rctx->subscene->pviewport.width, rctx->subscene->pviewport.height);
+  if (!viewerInScene) {
+    eye.x = 0.;
+    eye.y = 0.;
+    eye.z = frustum.distance;
+  } else {
+    float oldnear = frustum.znear;
+    frustum.znear -= -eye.z + frustum.distance;
+    frustum.zfar  -= -eye.z + frustum.distance;
+    if (frustum.zfar < 0) 
+      frustum.zfar = 1;	
+    if (frustum.znear < frustum.zfar/100.)  // we lose log2(100) bits of depth resolution
+      frustum.znear = frustum.zfar/100.;
+    float ratio = frustum.znear/oldnear;
+    frustum.left   = frustum.left*ratio   + eye.x;
+    frustum.right  = frustum.right*ratio  + eye.x;
+    frustum.top    = frustum.top*ratio    + eye.y;
+    frustum.bottom = frustum.bottom*ratio + eye.y;
+  }    
+
+  // zoom
+
+  frustum.left *= zoom;
+  frustum.right *= zoom;
+  frustum.bottom *= zoom;
+  frustum.top *= zoom;
+  
+  rctx->subscene->projMatrix.loadData(rctx->subscene->projMatrix*frustum.getMatrix());
+}
+
+Vertex UserViewpoint::getObserver()
+ {
+  return this->eye;
+}
+
+void UserViewpoint::setObserver(bool automatic, Vertex eye)
+ {
+  viewerInScene = !automatic;
+  if (viewerInScene && !ISNAN(eye.x) &&!ISNAN(eye.y) && !ISNAN(eye.z))
+    this->eye = eye;
+}
+
+void UserViewpoint::setupViewer(RenderContext* rctx)
+{
+  rctx->subscene->modelMatrix = rctx->subscene->modelMatrix * Matrix4x4::translationMatrix(-eye.x, -eye.y, -eye.z);
+}
+
+void ModelViewpoint::setupOrientation(RenderContext* rctx) const
+{
+  rctx->subscene->modelMatrix = rctx->subscene->modelMatrix * mouseMatrix * userMatrix;
+}
+
+void ModelViewpoint::setupTransformation(RenderContext* rctx, Vertex center)
+{     
+  // modelview
+  setupOrientation(rctx);
+  rctx->subscene->modelMatrix = rctx->subscene->modelMatrix * Matrix4x4::scaleMatrix(scale.x, scale.y, scale.z)
+                      * Matrix4x4::translationMatrix(-center.x, -center.y, -center.z);
+}
+
+void ModelViewpoint::updateMouseMatrix(Vec3 dragStart, Vec3 dragCurrent)
+{
+	Vec3 axis = dragStart.cross(dragCurrent);
+
+	float angle = dragStart.angle(dragCurrent);
+
+	glMatrixMode(GL_MODELVIEW);
+	glPushMatrix();
+	glLoadIdentity();
+	if (axis.getLength() > 0)
+	  glRotatef((GLfloat)angle, (GLfloat)axis.x, (GLfloat)axis.y, (GLfloat)axis.z);
+	glGetDoublev(GL_MODELVIEW_MATRIX,mouseMatrix);
+	glPopMatrix();
+}
+
+void ModelViewpoint::updateMouseMatrix(PolarCoord newpos)
+{
+    Matrix4x4 M,N;
+    M.setRotate(0, newpos.phi);
+    N.setRotate(1, -newpos.theta);
+    M = M * N;
+    M.getData((double*)mouseMatrix);
+}
+
+void ModelViewpoint::mouseOneAxis(Vertex dragStart,Vertex dragCurrent,Vertex axis)
+{
+    float angle = math::rad2deg(dragCurrent.x-dragStart.x);
+    Matrix4x4 M((double *)userMatrix);
+    Vec4 v = M * Vec4(axis.x, axis.y, axis.z);
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glLoadIdentity();
+    glRotatef((GLfloat)angle, (GLfloat)v.x/v.w, (GLfloat)v.y/v.w, (GLfloat)v.z/v.w);
+    glGetDoublev(GL_MODELVIEW_MATRIX,mouseMatrix);
+    glPopMatrix();
+}
+
+void ModelViewpoint::mergeMouseMatrix()
+{
+    Matrix4x4 M((double *)userMatrix), N((double *)mouseMatrix);
+    M = N * M;
+    M.getData((double *)userMatrix);
+    N.setIdentity();
+    N.getData((double *)mouseMatrix);
+}
+
+void ModelViewpoint::getUserMatrix(double* dest)
+{
+	for(int i=0; i<16;i++)
+		dest[i] = userMatrix[i];
+}
+
+void ModelViewpoint::setUserMatrix(double* src)
+{
+	for(int i=0; i<16;i++)
+		userMatrix[i] = src[i];
+}
+
+void ModelViewpoint::getScale(double* dest)
+{
+    dest[0] = scale.x;
+    dest[1] = scale.y;
+    dest[2] = scale.z;
+}
+
+void ModelViewpoint::setScale(double* src)
+{
+    scale.x = src[0];
+    scale.y = src[1];
+    scale.z = src[2];
+    scaleChanged = true;
+}
+
+void ModelViewpoint::getPosition(double* dest)
+{
+    dest[0] = position.theta;
+    dest[1] = position.phi;
+}
+
+void ModelViewpoint::setPosition(double* src)
+{
+    position.theta = src[0];
+    position.phi = src[1];
+}
diff --git a/src/Viewpoint.h b/src/Viewpoint.h
new file mode 100644
index 0000000..72a731f
--- /dev/null
+++ b/src/Viewpoint.h
@@ -0,0 +1,75 @@
+#ifndef VIEWPOINT_H
+#define VIEWPOINT_H
+
+#include "SceneNode.h"
+
+#include "render.h"
+#include "geom.h"
+
+namespace rgl {
+
+class ModelViewpoint : public SceneNode
+{
+
+#define VIEWPOINT_MAX_ZOOM  10
+
+public:
+
+  ModelViewpoint(PolarCoord position=PolarCoord(0.0f,15.0f), Vec3 in_scale=Vec3(1.0f, 1.0f, 1.0f), bool interactive=true);
+  ModelViewpoint(double* userMatrix, Vec3 in_scale=Vec3(1.0f, 1.0f, 1.0f), bool interactive=true);
+  PolarCoord& getPosition();
+  void        setPosition(const PolarCoord& position);
+  void	      clearMouseMatrix();
+  void        setupTransformation(RenderContext* rctx, Vertex center);
+  void        setupOrientation(RenderContext* rctx) const;
+  bool        isInteractive() const;
+  void        updateMouseMatrix(Vertex dragStart,Vertex dragCurrent);
+  void	      updateMouseMatrix(PolarCoord newpos);
+  void	      mouseOneAxis(Vertex dragStart,Vertex dragCurrent,Vertex axis);
+  void 	      mergeMouseMatrix();
+  void        getUserMatrix(double* dest);
+  void	      setUserMatrix(double* src);
+  void	      getScale(double* dest);
+  void	      setScale(double* src);
+  void 	      getPosition(double* dest);
+  void        setPosition(double* src);
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "modelviewpoint", buflen); };
+
+  Vertex      scale;
+  bool        scaleChanged;
+private:
+  PolarCoord  position;
+  bool        interactive;
+public:
+  GLdouble    userMatrix[16], mouseMatrix[16];
+};
+
+class UserViewpoint : public SceneNode
+{
+
+#define VIEWPOINT_MAX_ZOOM  10
+
+public:
+
+  UserViewpoint(float fov=90.0f, float zoom=1.0f);
+  float       getZoom(void) const; 
+  void        setZoom(const float zoom);
+  float       getFOV(void) const;
+  void        setFOV(const float in_fov);
+  void        setupFrustum(RenderContext* rctx, const Sphere& viewvolumeSphere);
+  Vertex      getObserver();
+  void	      setObserver(bool automatic, Vertex eye);
+  void	      setupViewer(RenderContext* rctx);
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "userviewpoint", buflen); };
+  Frustum     frustum;
+private:
+  float       fov;
+  float       zoom;
+  bool        viewerInScene;
+  Vertex      eye;
+};
+
+
+} // namespace rgl 
+
+#endif // VIEWPOINT_H
diff --git a/src/api.cpp b/src/api.cpp
new file mode 100644
index 0000000..0ef046b
--- /dev/null
+++ b/src/api.cpp
@@ -0,0 +1,1342 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: api.cpp 1436 2016-01-01 15:18:43Z murdoch $
+
+#include "lib.h"
+#include "DeviceManager.h"
+#include "rglview.h"
+
+#include "lib.h"
+#include "R.h"
+#include "api.h"
+#include "platform.h"
+
+using namespace rgl;
+//
+// API Success is encoded as integer type:
+//
+#define RGL_FAIL     0
+#define RGL_SUCCESS  1
+inline int as_success(int b) { return (b) ; }
+
+//
+// data type conversion utilities:
+// 
+inline bool as_bool(int idata) { return (idata) ? true : false; }
+
+//
+//   rgl::rgl_init moved to init.cpp
+//
+
+namespace rgl {
+extern DeviceManager* deviceManager;
+extern void getObserver(double* ddata, Subscene* subscene);
+extern void setObserver(bool automatic, double* ddata, RGLView* rglview, Subscene* subscene);
+}
+
+//
+// FUNCTION
+//   rgl::rgl_quit
+//
+// DESCRIPTION
+//   Gets called by .onUnload ( R function )
+//
+
+
+void rgl::rgl_quit(int* successptr)
+{
+  if (deviceManager) {
+    delete deviceManager;
+    deviceManager = 0;
+  }
+
+  quit();
+
+  *successptr = RGL_SUCCESS;
+}
+
+//
+// FUNCTION
+//   rgl::rgl_dev_open
+//
+
+void rgl::rgl_dev_open(int* successptr, int* useNULL)
+{
+  *successptr = as_success( deviceManager && deviceManager->openDevice(*useNULL) );
+  CHECKGLERROR;
+}
+
+
+//
+// FUNCTION
+//   rgl::rgl_dev_close
+//
+
+void rgl::rgl_dev_close(int* successptr)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+
+    device->close();
+    success = RGL_SUCCESS;
+    CHECKGLERROR;
+
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_dev_bringtotop(int* successptr, int* stay)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+
+    device->bringToTop(*stay);
+    success = RGL_SUCCESS;
+    CHECKGLERROR;
+
+  }
+
+  *successptr = success;
+}
+
+//
+// FUNCTION
+//   rgl::rgl_dev_getcurrent
+//
+// RETURNS
+//   device id
+//
+
+SEXP rgl::rgl_dev_getcurrent(void)
+{
+  SEXP result;
+  if (deviceManager) {
+    int id = deviceManager->getCurrent();
+    PROTECT(result = ScalarInteger(id));
+    if (id) {
+      PROTECT(result = namesgets(result, ScalarString(mkChar(deviceManager->getDevice(id)->getDevtype()))));
+      CHECKGLERROR;     
+      UNPROTECT(1);
+    }
+    UNPROTECT(1);
+    return result;
+  }
+  return ScalarInteger(0);
+}
+
+//
+// FUNCTION
+//   rgl::rgl_dev_list
+//
+// RETURNS
+//   list of active device ids
+//
+
+SEXP rgl::rgl_dev_list(void)
+{
+  SEXP result, names;
+  if (deviceManager) {
+    int n = deviceManager->getDeviceCount();
+    PROTECT(result = allocVector(INTSXP, n));
+    deviceManager->getDeviceIds(INTEGER(result), n);
+    PROTECT(names = allocVector(STRSXP, n));
+    for (int i = 0; i < n; i++) {
+      Device* device = deviceManager->getDevice(INTEGER(result)[i]);
+      SET_STRING_ELT(names, i, mkChar(device->getDevtype()));
+    }
+    PROTECT(result = namesgets(result, names));
+    CHECKGLERROR;
+    UNPROTECT(3);
+    return result;
+  }
+  return allocVector(INTSXP, 0);
+}
+
+
+//
+// FUNCTION
+//   rgl::rgl_dev_setcurrent
+//
+// PARAMETERS
+//   idata
+//     [0]  device id
+//
+
+void rgl::rgl_dev_setcurrent(int* successptr, int* idata)
+{
+  int id = idata[0];
+  bool silent = (bool) idata[1];
+  *successptr = as_success ( deviceManager && deviceManager->setCurrent(id, silent) );
+  CHECKGLERROR;
+}
+
+
+//
+// SCENE MANAGEMENT
+//
+
+static Material currentMaterial(Color(1.0f,1.0f,1.0f),Color(1.0f,0.0f,0.0f));
+
+//
+// FUNCTION
+//   rgl::rgl_clear ( successPtr, idata(type) )
+//
+// PARAMETERS
+//   idata
+//     [0]  count of types
+//     [1], [2], ...  TypeID 1, 2, ...
+//
+//
+
+void rgl::rgl_clear(int* successptr, int *idata)
+{
+  int success = RGL_SUCCESS;
+  Device* device;
+  int num = idata[0];
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    for (int i=1; success && i<=num; i++) {
+      TypeID stackTypeID = (TypeID) idata[i];
+
+      success = as_success( device->clear( stackTypeID ) ); // viewpoint & material handled in R, background ignored
+    }
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+
+//
+// FUNCTION
+//   rgl::rgl_pop  ( successPtr, idata )
+//
+// PARAMETERS
+//   idata
+//     [0]  stack TypeID
+//     [1]  id SceneNode identifier
+//
+//
+
+
+void rgl::rgl_pop(int* successptr, int* idata)
+{
+  int success = RGL_FAIL;
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+
+    TypeID stackTypeID = (TypeID) idata[0];
+    int id = idata[1];
+ 
+    success = as_success( device->pop( stackTypeID, id ) );
+    CHECKGLERROR;
+
+  }
+
+  *successptr = success;
+}
+
+//
+// FUNCTION
+//   rgl::rgl_id_count
+//
+
+void rgl::rgl_id_count(int* type, int* count, int* subsceneID)
+{
+  Device* device;    
+  *count = 0;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene;
+
+    if (!*subsceneID) {
+      while (*type) {
+        *count += scene->get_id_count((TypeID) *type);
+        type++;
+      }
+    } else if ((subscene = scene->getSubscene(*subsceneID))) {
+      while (*type) {
+        *count += subscene->get_id_count((TypeID) *type, false);
+	type++;
+      }
+    }
+    CHECKGLERROR;
+  } 
+}  
+
+//
+// FUNCTION
+//   rgl::rgl_ids
+//
+
+void rgl::rgl_ids(int* type, int* ids, char** types, int* subsceneID)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene;
+    if (!*subsceneID) {  
+      while (*type) {
+        int n = scene->get_id_count((TypeID) *type);
+        if (n) {
+          scene->get_ids((TypeID) *type, ids, types);
+          ids += n;
+          types += n;
+        }
+        type++;
+      }
+    } else if ((subscene = scene->getSubscene(*subsceneID))) {
+      while (*type) {
+        int n = subscene->get_id_count((TypeID) *type, false);
+        subscene->get_ids((TypeID) *type, ids, types, false);
+        ids += n;
+        types += n;
+        type++;
+      }	
+    }
+    CHECKGLERROR;
+  }
+} 
+
+//
+// FUNCTION
+//   rgl::rgl_attrib_count
+//
+
+void rgl::rgl_attrib_count(int* id, int* attrib, int* count)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene = scene->whichSubscene(*id);
+    AABox bbox = subscene->getBoundingBox();
+    SceneNode* scenenode = scene->get_scenenode(*id);
+    if ( scenenode )
+      *count = scenenode->getAttributeCount(bbox, *attrib);
+    else
+      *count = 0;
+  }
+} 
+
+//
+// FUNCTION
+//   rgl::rgl_attrib
+//
+
+void rgl::rgl_attrib(int* id, int* attrib, int* first, int* count, double* result)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene = scene->whichSubscene(*id);
+    AABox bbox = subscene->getBoundingBox();
+    SceneNode* scenenode = scene->get_scenenode(*id);
+    if ( scenenode )
+      scenenode->getAttribute(bbox, *attrib, *first, *count, result);
+  }
+} 
+
+//
+// FUNCTION
+//   rgl::rgl_text_attrib
+//
+
+void rgl::rgl_text_attrib(int* id, int* attrib, int* first, int* count, char** result)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    AABox bbox = scene->getBoundingBox();
+    SceneNode* scenenode = scene->get_scenenode(*id);
+    
+    if (scenenode)
+      for (int i=0; i < *count; i++) {
+      	String s = scenenode->getTextAttribute(bbox, *attrib, i + *first);
+      	if (s.length) {
+      	  *result = R_alloc(s.length + 1, 1);
+	  strncpy(*result, s.text, s.length);
+	  (*result)[s.length] = '\0';
+	}
+	result++;
+      }
+  }
+} 
+
+//
+// FUNCTION
+//   rgl::rgl_bg   ( successPtr, idata )
+//
+// PARAMETERS
+//   idata
+//     [0]  bool environment sphere
+//     [1]  int  fogtype
+//
+
+
+void rgl::rgl_bg(int* successptr, int* idata)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    bool sphere    = as_bool( idata[0] );
+    int  fogtype   = idata[1];
+
+    success = as_success( device->add( new Background(currentMaterial, sphere, fogtype) ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+
+//
+// FUNCTION
+//   rgl::rgl_light   ( successPtr, idata, cdata, ddata )
+//
+
+void rgl::rgl_light ( int* successptr, int* idata, double* ddata )
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    bool  viewpoint_rel = as_bool( idata[0] );
+    bool  finite_pos = as_bool( idata[10] );
+
+    Color ambient;
+    Color diffuse;
+    Color specular;
+
+    ambient.set3iv ( &idata[1] );
+    diffuse.set3iv ( &idata[4] );
+    specular.set3iv( &idata[7] );
+
+    float theta         = (float) ddata[0];
+    float phi           = (float) ddata[1];
+    Vertex finposition   = Vertex( ddata[2], ddata[3], ddata[4] );
+
+    success = as_success( device->add( new Light( PolarCoord(theta, phi), finposition, (bool) viewpoint_rel, (bool) finite_pos, ambient, diffuse, specular ) ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+
+void rgl::rgl_viewpoint(int* successptr, int* idata, double* ddata)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    float theta	      = static_cast<float>( ddata[0] );
+    float phi	      = static_cast<float>( ddata[1] );
+    float fov         = static_cast<float>( ddata[2] );
+    float zoom        = static_cast<float>( ddata[3] );
+    Vertex scale      = Vertex( ddata[4], ddata[5], ddata[6] );
+    
+    int   interactive = idata[0];
+    int   polar       = idata[1];
+    int   user        = idata[2];
+    int   model       = idata[3];
+    
+    if (model) {
+      if (polar) success = as_success( device->add( new ModelViewpoint(PolarCoord(theta, phi), scale, interactive) ) );
+      else       success = as_success( device->add( new ModelViewpoint(ddata + 7, scale, interactive) ) );
+    } else
+      success = RGL_SUCCESS;
+      
+    if (user && success)
+      success = as_success( device->add( new UserViewpoint(fov, zoom) ) );
+
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_getObserver(int* successptr, double* ddata)
+{
+  int success = RGL_FAIL;
+  
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+  
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene = scene->getCurrentSubscene();
+    getObserver(ddata, subscene);
+    success = RGL_SUCCESS;
+  }
+  
+  *successptr = success;
+}
+
+void rgl::rgl_setObserver(int* successptr, double* ddata)
+{
+  int success = RGL_FAIL;
+  
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+  
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    bool automatic = (bool)*successptr;
+    Subscene* subscene = scene->getCurrentSubscene();
+    setObserver(automatic, ddata, rglview, subscene);
+  }
+  
+  *successptr = success;
+}
+
+void rgl::rgl_primitive(int* successptr, int* idata, double* vertex, double* normals, double* texcoords)
+{
+  int success = RGL_FAIL;
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int   type    = idata[0];
+    int   nvertex = idata[1];
+    int   ignoreExtent = device->getIgnoreExtent();
+    int   useNormals = idata[2];
+    int   useTexcoords = idata[3];
+    
+    SceneNode* node;
+
+    switch(type) {
+    case 1: // RGL_POINTS:
+      node = new PointSet( currentMaterial, nvertex, vertex, ignoreExtent);
+      break;
+    case 2: // RGL_LINES:
+      node = new LineSet( currentMaterial, nvertex, vertex, ignoreExtent);
+      break;
+    case 3: // RGL_TRIANGLES:
+      node = new TriangleSet( currentMaterial, nvertex, vertex, normals, texcoords, 
+                              ignoreExtent, useNormals, useTexcoords);
+      break;
+    case 4: // RGL_QUADS:
+      node = new QuadSet( currentMaterial, nvertex, vertex, normals, texcoords, 
+                              ignoreExtent, useNormals, useTexcoords);
+      break;
+    case 5: // RGL_LINE_STRIP:
+      node = new LineStripSet( currentMaterial, nvertex, vertex, ignoreExtent);
+      break;
+    default:
+      node = NULL;
+    }
+
+    if (node) {
+      success = as_success( device->add( node ) );
+    
+      if (!success)
+        delete node;
+    }
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_surface(int* successptr, int* idata, double* x, double* z, double* y, 
+	         double* normal_x, double* normal_z, double* normal_y,
+	         double* texture_s, double* texture_t,
+	         int* coords, int* orientation, int* flags)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int nx         = idata[0];
+    int nz         = idata[1];
+
+    success = as_success( device->add( new Surface(currentMaterial, nx, nz, x, z, y, 
+                                                   normal_x, normal_z, normal_y,
+                                                   texture_s, texture_t,
+                                                   coords, *orientation, flags,
+    						   device->getIgnoreExtent()) ) );
+
+    CHECKGLERROR;
+  }
+  *successptr = success;
+}
+
+void rgl::rgl_spheres(int* successptr, int* idata, double* vertex, double* radius)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int nvertex = idata[0];
+    int nradius = idata[1];
+
+    success = as_success( device->add( new SphereSet(currentMaterial, nvertex, vertex, nradius, radius,
+    						     device->getIgnoreExtent()) ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_planes(int* successptr, int* idata, double* normals, double* offsets)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int nnormal = idata[0];
+    int noffset = idata[1];
+
+    success = as_success( device->add( new PlaneSet(currentMaterial, nnormal, normals, noffset, offsets) ) );
+    CHECKGLERROR;
+
+  }
+  *successptr = success;
+}
+
+void rgl::rgl_clipplanes(int* successptr, int* idata, double* normals, double* offsets)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int nnormal = idata[0];
+    int noffset = idata[1];
+
+    success = as_success( device->add( new ClipPlaneSet(currentMaterial, nnormal, normals, noffset, offsets) ) );
+    CHECKGLERROR;
+
+  }
+  *successptr = success;
+}
+
+void rgl::rgl_abclines(int* successptr, int* idata, double* bases, double* directions)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int nbases = idata[0];
+    int ndirs  = idata[1];
+
+    success = as_success( device->add( new ABCLineSet(currentMaterial, nbases, bases, ndirs, directions) ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_sprites(int* successptr, int* idata, double* vertex, double* radius, int* shapes, double* userMatrix)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int nvertex = idata[0];
+    int nradius = idata[1];
+    int nshapes = idata[2];
+    int count = 0;
+    Shape** shapelist;
+    if (nshapes) {
+      shapelist = (Shape**) R_alloc(nshapes, sizeof(Shape*));
+      RGLView* rglview = device->getRGLView();
+      Scene* scene = rglview->getScene();
+      while (nshapes) {
+        int id = *(shapes++);
+        nshapes--;
+        Shape* shape = scene->get_shape(id); 
+        if (shape) {
+          scene->hide(id);
+          shapelist[count++] = shape; 
+        }
+      }
+      if (!count) {
+        *successptr = RGL_FAIL;
+        return;
+      }
+    } else 
+      shapelist = NULL;
+    success = as_success( device->add( new SpriteSet(currentMaterial, nvertex, vertex, nradius, radius,
+    						     device->getIgnoreExtent(), count, shapelist, userMatrix) ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_newsubscene(int* successptr, int* parentid, int* embedding, int* ignoreExtent)
+{
+  int success = RGL_FAIL;
+  Device* device;
+    
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();      
+    Subscene* parent = scene->getSubscene(parentid[0]);
+    if (parent) {
+      Subscene* current = scene->getCurrentSubscene();
+      scene->setCurrentSubscene(parent);	
+      Subscene* subscene = new Subscene( (Embedding)embedding[0], 
+                                         (Embedding)embedding[1], 
+                                         (Embedding)embedding[2],
+                                         *ignoreExtent != 0);
+      if (subscene && scene->add(subscene)) {
+	success = as_success( subscene->getObjID() );
+      }
+      scene->setCurrentSubscene(current);
+    }
+  }
+  *successptr = success;
+} 
+
+void rgl::rgl_setsubscene(int* id)
+{
+  Device* device;
+    
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();      
+    Subscene* subscene = scene->getSubscene(*id);
+    if (subscene) {
+      scene->setCurrentSubscene(subscene);
+    } else
+      *id = 0;
+  } else
+    *id = 0;
+}  
+
+void rgl::rgl_getsubsceneid(int* id, int* dev)
+{
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getDevice(*dev))) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    const Subscene* subscene = (*id) == 1 ? scene->getCurrentSubscene() : scene->getRootSubscene();
+    *id = subscene->getObjID();
+  } else
+    *id = 0;
+} 
+
+void rgl::rgl_getsubsceneparent(int* id)
+{
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene = scene->getSubscene(*id);
+    if (!subscene) {
+      *id = NA_INTEGER;
+    } else {
+      subscene = subscene->getParent();
+      *id = subscene ? subscene->getObjID() : 0;
+    }
+  } else
+    *id = NA_INTEGER;
+}    
+
+void rgl::rgl_getsubscenechildcount(int* id, int* n)
+{
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* subscene = scene->getSubscene(*id);
+    *n = subscene ? subscene->getChildCount() : 0;
+  } else
+    *n = 0;
+} 
+
+void rgl::rgl_getsubscenechildren(int* id, int* children)
+{
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    const Subscene* subscene = scene->getSubscene(*id);
+    if (subscene) {
+      for (int i = 0; i < subscene->getChildCount(); i++) {
+        Subscene* child = subscene->getChild(i);
+        children[i] = child ? child->getObjID() : 0;
+      }
+    }
+  }
+}
+
+void rgl::rgl_addtosubscene(int* successptr, int* count, int* ids)
+{
+  int success = RGL_FAIL;
+  Device* device;
+    
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();      
+    Subscene* subscene = scene->getSubscene(*successptr);
+    if (subscene) {
+      for (int i=0; i < count[0]; i++) {
+        SceneNode* node = scene->get_scenenode(ids[i]);
+	if (node) {
+	  subscene->add(node);
+	  success = RGL_SUCCESS;
+	} else 
+	  warning("id %d not found in scene", ids[i]);
+      }
+      rglview->update();
+    }
+  }
+  *successptr = success;
+} 
+
+void rgl::rgl_delfromsubscene(int* successptr, int* count, int* ids)
+{
+  int success = RGL_FAIL;
+  Device* device;
+    
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();      
+    Subscene* subscene = scene->getSubscene(*successptr);
+    if (subscene) {
+      for (int i=0; i < count[0]; i++) {
+        SceneNode* node = scene->get_scenenode(ids[i]);
+	if (node) 
+	  switch (node->getTypeID()) {
+	  case SHAPE: 
+	    subscene->hideShape( ids[i] );
+	    success++;
+	    break;
+	  case LIGHT:
+	    subscene->hideLight( ids[i] );
+	    success++;
+	    break;
+	  case BBOXDECO:
+	    subscene->hideBBoxDeco( ids[i] );
+	    success++;
+	    break;
+	  case SUBSCENE:
+	    scene->setCurrentSubscene( subscene->hideSubscene( ids[i], scene->getCurrentSubscene() ) );
+	    success++;
+	    break;
+	  case BACKGROUND:
+	    subscene->hideBackground( ids[i] );
+	    success++;
+	    break;
+	  case USERVIEWPOINT:
+	  case MODELVIEWPOINT:
+	    subscene->hideViewpoint( ids[i] );
+	    success++;
+	    break;
+	  default:
+	    char buffer[20];
+	    buffer[19] = 0;
+	    node->getTypeName(buffer, 20);
+	    warning("id %d is type %s; cannot hide", ids[i], buffer);
+          }
+	else 
+	  warning("id %d not found in scene", ids[i]);
+      }
+      rglview->update();
+    }
+  }
+  *successptr = success;
+}
+
+void rgl::rgl_gc(int* count, int* protect)
+{
+  Device* device;
+  int nprotect = *count;
+  *count = 0;
+    
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+    RGLView* rglview = device->getRGLView();
+    Scene* scene = rglview->getScene();
+    if (scene) {
+      Subscene* root = (Subscene *)scene->getRootSubscene(); // need to discard const
+      int rootid = root->getObjID();
+      for (TypeID i = 1; i < MAX_TYPE; i++) {
+        int n = scene->get_id_count(i);
+	if (n) {
+	  std::vector<int> ids(n);
+	  std::vector<char*> types(n);
+	  scene->get_ids(i, &ids[0], &types[0]);
+	  // First, remove the protected ones by setting them to zero.
+	  bool anyunprot = false;
+	  for (int j = 0; j < n; j++) {
+	    bool prot = (rootid == ids[j]);
+	    for (int k = 0; k < nprotect && !prot; k++) 
+	      prot = (ids[j] == protect[k]);
+	    if (prot)
+	      ids[j] = 0;
+	    else
+	      anyunprot = true;
+	  }
+	  if (!anyunprot) 
+	    continue;
+	  // Now look for the others in subscenes
+	  int m = root->get_id_count(i, true);
+	  if (m) {
+	    std::vector<int> ids2(m);
+	    std::vector<char*> types2(m);
+	    root->get_ids(i, &ids2[0], &types2[0], true);
+	    for (int j = 0; j < n; j++) {
+	      for (int k = 0; k < m && ids[j] != 0; k++) { 
+	        if (ids[j] == ids2[k])
+	          ids[j] = 0;
+	      }
+	    }
+	  }
+	  for (int j = 0; j < n; j++) {
+	    if (ids[j] != 0) {
+	      scene->pop(i, ids[j]);
+	      (*count)++;
+	    }
+	  }
+        }
+      }
+    }
+  }
+}
+
+void rgl::rgl_material(int *successptr, int* idata, char** cdata, double* ddata)
+{
+  Material& mat = currentMaterial;
+
+  int ncolor    = idata[0];
+  mat.lit       = (idata[1]) ? true : false;
+  mat.smooth    = (idata[2]) ? true : false;
+  mat.front     = (Material::PolygonMode) idata[3];
+  mat.back      = (Material::PolygonMode) idata[4];
+  mat.fog       = (idata[5]) ? true : false;
+  mat.textype   = (Texture::Type) idata[6];
+  mat.mipmap    = (idata[7]) ? true : false;
+  mat.minfilter = idata[8];
+  mat.magfilter = idata[9];
+  int    nalpha = idata[10];
+  mat.ambient.set3iv( &idata[11] );
+  mat.specular.set3iv( &idata[14] );
+  mat.emission.set3iv( &idata[17] );
+  mat.envmap    = (idata[20]) ? true : false;
+  mat.point_antialias = (idata[21]) ? true : false;
+  mat.line_antialias = (idata[22]) ? true : false;
+  mat.depth_mask = (idata[23]) ? true : false;
+  mat.depth_test = idata[24];
+  
+  int* colors   = &idata[25];
+
+  char*  pixmapfn = cdata[0];
+
+  mat.shininess   = (float) ddata[0];
+  mat.size      = (float) ddata[1];
+  mat.lwd         = (float) ddata[2];
+  double* alpha   = &ddata[3];
+
+  mat.alphablend  = false;
+  
+  if ( strlen(pixmapfn) > 0 ) {
+    mat.texture = new Texture(pixmapfn, mat.textype, mat.mipmap, mat.minfilter, mat.magfilter, mat.envmap);
+    if ( !mat.texture->isValid() ) {
+      mat.texture->unref();
+      // delete mat.texture;
+      mat.texture = NULL;
+    } else
+      mat.alphablend = mat.alphablend || mat.texture->hasAlpha();
+  } else
+    mat.texture = NULL;
+
+  mat.colors.set( ncolor, colors, nalpha, alpha);
+  mat.alphablend  = mat.alphablend || mat.colors.hasAlpha();
+
+  CHECKGLERROR;
+
+  *successptr = RGL_SUCCESS;
+}
+
+void rgl::rgl_getcolorcount(int* count)
+{
+  *count = currentMaterial.colors.getLength();
+  CHECKGLERROR;
+}
+
+void rgl::rgl_getmaterial(int *successptr, int *id, int* idata, char** cdata, double* ddata)
+{
+  Material* mat = ¤tMaterial;
+  unsigned int i,j;
+  
+  if (*id > 0) {
+    Device* device;
+    *successptr = RGL_FAIL;
+    if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+      RGLView* rglview = device->getRGLView();
+      Scene* scene = rglview->getScene();
+    
+      Shape* shape = scene->get_shape(*id);
+      if (shape) 
+        mat = shape->getMaterial(); /* success! successptr will be set below */
+      else {
+	BBoxDeco* bboxdeco = scene->get_bboxdeco(*id);
+	if (bboxdeco)
+	  mat = bboxdeco->getMaterial();
+	else {
+	  Background* background = scene->get_background(*id);
+	  if (background)
+	    mat = background->getMaterial();
+	  else
+	    return;
+        }
+      }
+    } else
+      return;
+  }
+  
+  idata[1] = mat->lit ? 1 : 0;
+  idata[2] = mat->smooth ? 1 : 0;
+  idata[3] = (int) mat->front;
+  idata[4] = (int) mat->back;
+  idata[5] = mat->fog ? 1 : 0;
+  if (mat->texture) {
+    mat->texture->getParameters( (Texture::Type*) (idata + 6),
+                               (bool*) (idata + 7),
+                               (unsigned int*) (idata + 8),
+                               (unsigned int*) (idata + 9),
+                               (bool*) (idata + 20),
+                               strlen(cdata[0]),
+                               cdata[0] );
+  } else {
+    idata[6] = (int)mat->textype;
+    idata[7] = mat->mipmap ? 1 : 0; 
+    idata[8] = mat->minfilter; 
+    idata[9] = mat->magfilter; 
+    idata[20] = mat->envmap ? 1 : 0; 
+    cdata[0][0] = '\0';
+  }
+  idata[11] = (int) mat->ambient.getRedub();
+  idata[12] = (int) mat->ambient.getGreenub();
+  idata[13] = (int) mat->ambient.getBlueub();
+  idata[14] = (int) mat->specular.getRedub();
+  idata[15] = (int) mat->specular.getGreenub();
+  idata[16] = (int) mat->specular.getBlueub();  
+  idata[17] = (int) mat->emission.getRedub();
+  idata[18] = (int) mat->emission.getGreenub();
+  idata[19] = (int) mat->emission.getBlueub();
+  idata[21] = mat->point_antialias ? 1 : 0;
+  idata[22] = mat->line_antialias ? 1 : 0;
+  idata[23] = mat->depth_mask ? 1 : 0;
+  idata[24] = mat->depth_test;
+
+  for (i=0, j=25; (i < mat->colors.getLength()) && (i < (unsigned int)idata[0]); i++) {
+    idata[j++] = (int) mat->colors.getColor(i).getRedub();
+    idata[j++] = (int) mat->colors.getColor(i).getGreenub();
+    idata[j++] = (int) mat->colors.getColor(i).getBlueub();
+  }
+  idata[0] = i;
+
+  ddata[0] = (double) mat->shininess;
+  ddata[1] = (double) mat->size;
+  ddata[2] = (double) mat->lwd;
+  
+  if (mat->colors.hasAlpha()) {
+    for (i=0, j=3; (i < mat->colors.getLength()) && (i < (unsigned int)idata[10]); i++) 
+      ddata[j++] = (double) mat->colors.getColor(i).getAlphaf();
+    idata[10] = i;
+  } else 
+    idata[10] = 0;
+  CHECKGLERROR;
+  
+  *successptr = RGL_SUCCESS;
+}
+
+void rgl::rgl_texts(int* successptr, int* idata, double* adj, char** text, double* vertex,
+               int* nfonts, char** family, int* style, double* cex, 
+               int* useFreeType)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+  
+#ifndef HAVE_FREETYPE
+  if (*useFreeType) error("FreeType not supported in this build");
+#endif
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int ntext   = idata[0];
+    
+    FontArray fonts;
+    device->getFonts(fonts, *nfonts, family, style, cex, (bool) *useFreeType);
+    success = as_success( device->add( new TextSet(currentMaterial, ntext, text, vertex, 
+                                                   adj[0], adj[1],
+    						   device->getIgnoreExtent(), fonts) ) );
+    CHECKGLERROR;
+
+  }
+  *successptr = success;
+}
+
+void rgl::rgl_bbox(int* successptr,
+              int* idata,
+              double* ddata,
+              double* xat, char** xtext,
+              double* yat, char** ytext,
+              double* zat, char** ztext)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    int   xticks     =        idata[0]; /* these are length of xat etc. */
+    int   yticks     =        idata[1];
+    int   zticks     =        idata[2];
+    int   xlen       =        idata[3]; /* these are suggested tick counts */
+    int   ylen       =        idata[4];
+    int   zlen       =        idata[5];
+    int   marklen_rel =       idata[6];
+    int   front      =        idata[7];
+
+    float xunit      = (float) ddata[0];
+    float yunit      = (float) ddata[1];
+    float zunit      = (float) ddata[2];
+    float marklen    = (float) ddata[3];
+    float expand     = (float) ddata[4];    
+
+
+    AxisInfo xaxis(xticks, xat, xtext, xlen, xunit);
+    AxisInfo yaxis(yticks, yat, ytext, ylen, yunit);
+    AxisInfo zaxis(zticks, zat, ztext, zlen, zunit);
+
+    success = as_success( device->add( new BBoxDeco(currentMaterial, xaxis, yaxis, zaxis, marklen, (bool) marklen_rel, expand, (bool)front ) ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_snapshot(int* successptr, int* idata, char** cdata)
+{
+  int success = RGL_FAIL;
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+
+    int   format   = idata[0];
+    char* filename = cdata[0];
+
+    success = as_success( device->snapshot( format, filename ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_pixels(int* successptr, int* ll, int* size, int* component, double* result)
+{
+  int success = RGL_FAIL;
+  
+  Device* device;
+  
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    
+    success = as_success( device->pixels( ll, size, *component, result) );
+    CHECKGLERROR;
+    
+  }
+  
+  *successptr = success;
+}
+
+void rgl::rgl_user2window(int* successptr, int* idata, double* point, double* pixel, double* model, double* proj, int* view)
+{
+  int success = RGL_FAIL;
+  GLdouble* vertex = pixel;
+  int columns = idata[0];
+  GLint viewport[4];
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+  
+    for (int i=0; i<4; i++) viewport[i] = view[i];
+    for (int i=0; i<columns; i++) {
+	    gluProject(point[0],point[1],point[2],model,proj,viewport,
+	    vertex,vertex+1,vertex+2);
+	    vertex[0] /= view[2];
+	    vertex[1] /= view[3];
+	    point += 3;
+	    vertex += 3;
+    }
+    success = RGL_SUCCESS;
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_window2user(int* successptr, int* idata, double* point, double* pixel, double* model, double* proj, int* view)
+{
+  int success = RGL_FAIL;
+  GLdouble* vertex = point;
+  int columns = idata[0];
+  GLint viewport[4];
+
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+  
+    for (int i=0; i<4; i++) viewport[i] = view[i];
+    for (int i=0; i<columns; i++) {
+	    pixel[0] *= view[2];
+	    pixel[1] *= view[3];
+	    gluUnProject(pixel[0],pixel[1],pixel[2],model,proj,viewport,
+	    vertex,vertex+1,vertex+2);
+	    pixel += 3;
+	    vertex += 3;
+    }
+    success = RGL_SUCCESS;
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_selectstate(int* successptr, int* selectstate, double* locations)
+{
+    int success = RGL_FAIL;
+    Device* device;
+
+    if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+	RGLView* rglview = device->getRGLView();
+
+	selectstate[0] = (int)rglview->getSelectState();
+	double* mousePosition = rglview->getMousePosition();
+
+	locations[0] = *mousePosition;
+	locations[1] = *(mousePosition+1);
+	locations[2] = *(mousePosition+2);
+	locations[3] = *(mousePosition+3);
+
+	success = RGL_SUCCESS;
+	CHECKGLERROR;
+    }
+    *successptr = success;
+
+}
+
+void rgl::rgl_setselectstate(int* successptr, int *idata)
+{
+  int success = RGL_FAIL;
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getAnyDevice())) {
+
+    MouseSelectionID selectState = (MouseSelectionID) idata[0];
+    RGLView* rglview = device->getRGLView();
+    rglview->setSelectState(selectState);
+
+    success = RGL_SUCCESS;
+    CHECKGLERROR;
+
+  }
+
+  *successptr = success;
+}
+
+void rgl::rgl_getEmbeddings(int* id, int* embeddings)
+{
+    Device* device;
+    
+    if (deviceManager && (device = deviceManager->getAnyDevice())) {
+      RGLView* rglview = device->getRGLView();
+      Scene* scene = rglview->getScene();
+      Subscene* subscene = scene->getSubscene(*id);
+      if (subscene) {
+        embeddings[0] = subscene->getEmbedding(0);
+        embeddings[1] = subscene->getEmbedding(1);
+        embeddings[2] = subscene->getEmbedding(2);
+      }
+    }
+}
+
+void rgl::rgl_setEmbeddings(int* id, int* embeddings)
+{
+    Device* device;
+    
+    if (deviceManager && (device = deviceManager->getAnyDevice())) {
+      RGLView* rglview = device->getRGLView();
+      Scene* scene = rglview->getScene();
+      Subscene* subscene = scene->getSubscene(*id);
+      *id = RGL_FAIL;
+      if (subscene) {
+        if (!subscene->getParent() &&        // can't change the root
+            (embeddings[0] != EMBED_REPLACE
+            || embeddings[1] != EMBED_REPLACE
+            || embeddings[2] != EMBED_REPLACE))
+          return;  
+        subscene->setEmbedding(0, (Embedding)embeddings[0]);
+        subscene->setEmbedding(1, (Embedding)embeddings[1]);
+        subscene->setEmbedding(2, (Embedding)embeddings[2]);
+        rglview->update();
+        *id = RGL_SUCCESS;
+      }
+    }
+}
+
+void rgl::rgl_postscript(int* successptr, int* idata, char** cdata)
+{
+  int success = RGL_FAIL;
+ 
+  Device* device;
+
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+
+    int   format   = idata[0];
+    bool  drawText = (bool)idata[1];
+    char* filename = cdata[0];
+
+    success = as_success( device->postscript( format, filename, drawText ) );
+    CHECKGLERROR;
+  }
+
+  *successptr = success;
+}
diff --git a/src/api.h b/src/api.h
new file mode 100644
index 0000000..c774482
--- /dev/null
+++ b/src/api.h
@@ -0,0 +1,121 @@
+#ifndef RGL_API_H
+#define RGL_API_H
+
+#include "R.h"
+#include <Rinternals.h>
+#include "ABCLineSet.h"
+#include "PlaneSet.h"
+#include "SphereSet.h"
+#include "SpriteSet.h"
+#include "Surface.h"
+#include "TextSet.h"
+
+
+namespace rgl {
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+// RGL API IMPLEMENTATION
+//
+//
+// C API FUNCTION DESIGN
+//  rgl_<name> ( successptr , ... )
+//
+// PARAMETERS
+//   successptr
+//     [0]  function success status
+*/
+
+/* library service */
+
+void rgl_quit          (int* successptr);
+
+/* device management */
+
+void rgl_dev_open      (int* successptr, int* useNULL);
+void rgl_dev_close      (int* successptr);
+SEXP rgl_dev_getcurrent(void);
+SEXP rgl_dev_list        (void);
+void rgl_dev_setcurrent(int* successptr, int* idata);
+void rgl_dev_bringtotop(int* successptr, int* stay);
+
+/* device services */
+
+void rgl_snapshot (int* successptr, int* idata, char** cdata);
+void rgl_pixels(int* successptr, int* ll, int* size, int* component, double* result);
+void rgl_postscript (int* successptr, int* idata, char** cdata);
+
+/* scene management */
+
+void rgl_clear    (int* successptr, int* idata);
+void rgl_pop      (int* successptr, int* idata);
+void rgl_id_count (int* type, int* count, int* subsceneID);
+void rgl_ids       (int* type, int* ids, char** types, int* subsceneID);
+void rgl_attrib_count (int* id, int* attrib, int* count);
+void rgl_attrib   (int* id, int* attrib, int* first, int* count, double* result);
+void rgl_text_attrib   (int* id, int* attrib, int* first, int* count, char** result);
+
+void rgl_material (int* successptr, int* idata, char** cdata, double* ddata);
+void rgl_getcolorcount(int* count);
+void rgl_getmaterial (int* successptr, int *id, int* idata, char** cdata, double* ddata);
+
+void rgl_light    (int* successptr, int* idata, double* ddata );
+
+void rgl_viewpoint(int* successptr, int* idata, double* ddata);
+
+void rgl_bg       (int* successptr, int* idata);
+void rgl_bbox     (int* successptr, int* idata, double* ddata, double* xat, char** xtext, double* yat, char** ytext, double* zat, char** ztext);
+
+void rgl_primitive(int* successptr, int* idata, double* vertex, double* normals, double* texcoords);
+void rgl_texts    (int* successptr, int* idata, double* adj, char** text, double* vertex,
+                                 int* nfonts, char** family, int* style, double* cex, int* useFreeType);
+void rgl_spheres  (int* successptr, int* idata, double* vertex, double* radius);
+void rgl_planes   (int* successptr, int* idata, double* normals, double* offsets);
+void rgl_clipplanes(int* successptr, int* idata, double* normals, double* offsets);
+void rgl_abclines (int* successptr, int* idata, double* bases, double* directions);
+
+void rgl_surface  (int* successptr, int* idata, double* x, double* z, double* y, 
+	                         double* normal_x, double* normal_z, double* normal_y,
+	                         double* texture_s, double* texture_t,
+	                         int* coords, int* orientation, int* flags);
+void rgl_sprites  (int* successptr, int* idata, double* vertex, double* radius, int* shapes, double* userMatrix);
+void rgl_newsubscene (int* successptr, int* parentid, int* embedding, int* ignoreExtent);
+void rgl_setsubscene (int* id);
+void rgl_getsubsceneid (int* id, int* dev); /* On input, 0 for root, 1 for current */
+void rgl_getsubsceneparent(int* id);
+void rgl_getsubscenechildcount(int* id, int* n);
+void rgl_getsubscenechildren(int* id, int* children);
+void rgl_addtosubscene (int* successptr, int* count, int* ids);
+void rgl_delfromsubscene(int* successptr, int* count, int* ids);
+void rgl_gc(int* count, int* protect);
+
+void rgl_user2window(int* successptr, int* idata, double* point, double* pixel, double* model, double* proj, int* view);
+void rgl_window2user(int* successptr, int* idata, double* point, double* pixel, double* model, double* proj, int* view);
+void rgl_locator(int* successptr, double* locations);
+
+void rgl_selectstate(int* successptr, int* selectstate, double* locations);
+void rgl_setselectstate(int* successptr, int *idata);
+void rgl_setEmbeddings(int* successptr, int* embeddings);
+void rgl_getEmbeddings(int* successptr, int* embeddings);
+
+SEXP rgl_setMouseCallbacks(SEXP button, SEXP begin, SEXP update, SEXP end);
+SEXP rgl_setWheelCallback(SEXP rotate);
+SEXP rgl_getMouseCallbacks(SEXP button);
+SEXP rgl_getWheelCallback();
+
+SEXP rgl_par3d(SEXP device, SEXP subscene, SEXP args);
+
+/* These may be removed if observer is set completely by par3d */
+void rgl_getObserver(int* successptr, double* ddata);
+void rgl_setObserver(int* successptr, double* ddata);
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace rgl
+
+#endif /* RGL_API_H */
+
diff --git a/src/assert.cpp b/src/assert.cpp
new file mode 100644
index 0000000..002f04d
--- /dev/null
+++ b/src/assert.cpp
@@ -0,0 +1,9 @@
+#include "R.h"
+#include "assert.h"
+
+void rgl_assert (const char* assertion, const char* file, int line)
+{
+    error("Assertion failure: %s\nFile: %s\nLine: %d\nPlease report to rgl maintainer.",
+           assertion, file, line);
+}
+
diff --git a/src/assert.h b/src/assert.h
new file mode 100644
index 0000000..b6ed0a5
--- /dev/null
+++ b/src/assert.h
@@ -0,0 +1,43 @@
+/* 
+ * assert.hpp
+ 
+ * Based on assert.h from MinGW, which had the following notice:
+ 
+ * This file has no copyright assigned and is placed in the Public Domain.
+ * This file is a part of the mingw-runtime package.
+ * No warranty is given; refer to the file DISCLAIMER within the package.
+ *
+ * Define the assert macro for debug output.
+ *
+ */
+ 
+/* We should be able to include this file multiple times to allow the assert
+   macro to be enabled/disabled for different parts of code.  So don't add a
+   header guard.  */ 
+
+#undef assert
+
+#ifdef	__cplusplus
+extern "C" {
+#endif
+
+#ifdef NDEBUG
+/*
+ * If not debugging, assert does nothing.
+ */
+#define assert(x)	((void)0)
+
+#else /* debugging enabled */
+
+void rgl_assert (const char*, const char*, int);
+
+/*
+ * Definition of the assert macro.
+ */
+#define assert(e)       ((e) ? (void)0 : rgl_assert(#e, __FILE__, __LINE__))
+
+#endif	/* NDEBUG */
+
+#ifdef	__cplusplus
+}
+#endif
diff --git a/src/build/autoconf/config.guess b/src/build/autoconf/config.guess
new file mode 100755
index 0000000..3c022c5
--- /dev/null
+++ b/src/build/autoconf/config.guess
@@ -0,0 +1,1444 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+#   Copyright 1992-2015 Free Software Foundation, Inc.
+
+timestamp='2015-09-14'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, see <http://www.gnu.org/licenses/>.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that
+# program.  This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+#
+# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
+#
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+#
+# Please send patches to <config-patches at gnu.org>.
+
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright 1992-2015 Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help" >&2
+       exit 1 ;;
+    * )
+       break ;;
+  esac
+done
+
+if test $# != 0; then
+  echo "$me: too many arguments$help" >&2
+  exit 1
+fi
+
+trap 'exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script. Note that the use of a
+# compiler to aid in system detection is discouraged as it requires
+# temporary files to be created and, as you can see below, it is a
+# headache to deal with in a portable fashion.
+
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+# Portable tmp directory creation inspired by the Autoconf team.
+
+set_cc_for_build='
+trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ;
+trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ;
+: ${TMPDIR=/tmp} ;
+ { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } ||
+ { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } ||
+ { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } ||
+ { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ;
+dummy=$tmp/dummy ;
+tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ;
+case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,)    echo "int x;" > $dummy.c ;
+	for c in cc gcc c89 c99 ; do
+	  if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then
+	     CC_FOR_BUILD="$c"; break ;
+	  fi ;
+	done ;
+	if test x"$CC_FOR_BUILD" = x ; then
+	  CC_FOR_BUILD=no_compiler_found ;
+	fi
+	;;
+ ,,*)   CC_FOR_BUILD=$CC ;;
+ ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
+esac ; set_cc_for_build= ;'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi at noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+	PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+case "${UNAME_SYSTEM}" in
+Linux|GNU|GNU/*)
+	# If the system lacks a compiler, then just pick glibc.
+	# We could probably try harder.
+	LIBC=gnu
+
+	eval $set_cc_for_build
+	cat <<-EOF > $dummy.c
+	#include <features.h>
+	#if defined(__UCLIBC__)
+	LIBC=uclibc
+	#elif defined(__dietlibc__)
+	LIBC=dietlibc
+	#else
+	LIBC=gnu
+	#endif
+	EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC' | sed 's, ,,g'`
+	;;
+esac
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+    *:NetBSD:*:*)
+	# NetBSD (nbsd) targets should (where applicable) match one or
+	# more of the tuples: *-*-netbsdelf*, *-*-netbsdaout*,
+	# *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
+	# switched to ELF, *-*-netbsd* would select the old
+	# object file format.  This provides both forward
+	# compatibility and a consistent mechanism for selecting the
+	# object file format.
+	#
+	# Note: NetBSD doesn't particularly care about the vendor
+	# portion of the name.  We always set it to "unknown".
+	sysctl="sysctl -n hw.machine_arch"
+	UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \
+	    /sbin/$sysctl 2>/dev/null || \
+	    /usr/sbin/$sysctl 2>/dev/null || \
+	    echo unknown)`
+	case "${UNAME_MACHINE_ARCH}" in
+	    armeb) machine=armeb-unknown ;;
+	    arm*) machine=arm-unknown ;;
+	    sh3el) machine=shl-unknown ;;
+	    sh3eb) machine=sh-unknown ;;
+	    sh5el) machine=sh5le-unknown ;;
+	    earmv*)
+		arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'`
+		endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'`
+		machine=${arch}${endian}-unknown
+		;;
+	    *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+	esac
+	# The Operating System including object format, if it has switched
+	# to ELF recently, or will in the future.
+	case "${UNAME_MACHINE_ARCH}" in
+	    arm*|earm*|i386|m68k|ns32k|sh3*|sparc|vax)
+		eval $set_cc_for_build
+		if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+			| grep -q __ELF__
+		then
+		    # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+		    # Return netbsd for either.  FIX?
+		    os=netbsd
+		else
+		    os=netbsdelf
+		fi
+		;;
+	    *)
+		os=netbsd
+		;;
+	esac
+	# Determine ABI tags.
+	case "${UNAME_MACHINE_ARCH}" in
+	    earm*)
+		expr='s/^earmv[0-9]/-eabi/;s/eb$//'
+		abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"`
+		;;
+	esac
+	# The OS release
+	# Debian GNU/NetBSD machines have a different userland, and
+	# thus, need a distinct triplet. However, they do not need
+	# kernel version information, so it can be replaced with a
+	# suitable tag, in the style of linux-gnu.
+	case "${UNAME_VERSION}" in
+	    Debian*)
+		release='-gnu'
+		;;
+	    *)
+		release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2`
+		;;
+	esac
+	# Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+	# contains redundant information, the shorter form:
+	# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+	echo "${machine}-${os}${release}${abi}"
+	exit ;;
+    *:Bitrig:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-bitrig${UNAME_RELEASE}
+	exit ;;
+    *:OpenBSD:*:*)
+	UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
+	echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
+	exit ;;
+    *:ekkoBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
+	exit ;;
+    *:SolidBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE}
+	exit ;;
+    macppc:MirBSD:*:*)
+	echo powerpc-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:MirBSD:*:*)
+	echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
+	exit ;;
+    *:Sortix:*:*)
+	echo ${UNAME_MACHINE}-unknown-sortix
+	exit ;;
+    alpha:OSF1:*:*)
+	case $UNAME_RELEASE in
+	*4.0)
+		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+		;;
+	*5.*)
+		UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'`
+		;;
+	esac
+	# According to Compaq, /usr/sbin/psrinfo has been available on
+	# OSF/1 and Tru64 systems produced since 1995.  I hope that
+	# covers most systems running today.  This code pipes the CPU
+	# types through head -n 1, so we only detect the type of CPU 0.
+	ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
+	case "$ALPHA_CPU_TYPE" in
+	    "EV4 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV4.5 (21064)")
+		UNAME_MACHINE="alpha" ;;
+	    "LCA4 (21066/21068)")
+		UNAME_MACHINE="alpha" ;;
+	    "EV5 (21164)")
+		UNAME_MACHINE="alphaev5" ;;
+	    "EV5.6 (21164A)")
+		UNAME_MACHINE="alphaev56" ;;
+	    "EV5.6 (21164PC)")
+		UNAME_MACHINE="alphapca56" ;;
+	    "EV5.7 (21164PC)")
+		UNAME_MACHINE="alphapca57" ;;
+	    "EV6 (21264)")
+		UNAME_MACHINE="alphaev6" ;;
+	    "EV6.7 (21264A)")
+		UNAME_MACHINE="alphaev67" ;;
+	    "EV6.8CB (21264C)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8AL (21264B)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.8CX (21264D)")
+		UNAME_MACHINE="alphaev68" ;;
+	    "EV6.9A (21264/EV69A)")
+		UNAME_MACHINE="alphaev69" ;;
+	    "EV7 (21364)")
+		UNAME_MACHINE="alphaev7" ;;
+	    "EV7.9 (21364A)")
+		UNAME_MACHINE="alphaev79" ;;
+	esac
+	# A Pn.n version is a patched version.
+	# A Vn.n version is a released version.
+	# A Tn.n version is a released field test version.
+	# A Xn.n version is an unreleased experimental baselevel.
+	# 1.2 uses "1.2" for uname -r.
+	echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	# Reset EXIT trap before exiting to avoid spurious non-zero exit code.
+	exitcode=$?
+	trap '' 0
+	exit $exitcode ;;
+    Alpha\ *:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# Should we change UNAME_MACHINE based on the output of uname instead
+	# of the specific Alpha model?
+	echo alpha-pc-interix
+	exit ;;
+    21064:Windows_NT:50:3)
+	echo alpha-dec-winnt3.5
+	exit ;;
+    Amiga*:UNIX_System_V:4.0:*)
+	echo m68k-unknown-sysv4
+	exit ;;
+    *:[Aa]miga[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-amigaos
+	exit ;;
+    *:[Mm]orph[Oo][Ss]:*:*)
+	echo ${UNAME_MACHINE}-unknown-morphos
+	exit ;;
+    *:OS/390:*:*)
+	echo i370-ibm-openedition
+	exit ;;
+    *:z/VM:*:*)
+	echo s390-ibm-zvmoe
+	exit ;;
+    *:OS400:*:*)
+	echo powerpc-ibm-os400
+	exit ;;
+    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+	echo arm-acorn-riscix${UNAME_RELEASE}
+	exit ;;
+    arm*:riscos:*:*|arm*:RISCOS:*:*)
+	echo arm-unknown-riscos
+	exit ;;
+    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+	echo hppa1.1-hitachi-hiuxmpp
+	exit ;;
+    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+	# akee at wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+	if test "`(/bin/universe) 2>/dev/null`" = att ; then
+		echo pyramid-pyramid-sysv3
+	else
+		echo pyramid-pyramid-bsd
+	fi
+	exit ;;
+    NILE*:*:*:dcosx)
+	echo pyramid-pyramid-svr4
+	exit ;;
+    DRS?6000:unix:4.0:6*)
+	echo sparc-icl-nx6
+	exit ;;
+    DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*)
+	case `/usr/bin/uname -p` in
+	    sparc) echo sparc-icl-nx7; exit ;;
+	esac ;;
+    s390x:SunOS:*:*)
+	echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4H:SunOS:5.*:*)
+	echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+	echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*)
+	echo i386-pc-auroraux${UNAME_RELEASE}
+	exit ;;
+    i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
+	eval $set_cc_for_build
+	SUN_ARCH="i386"
+	# If there is a compiler, see if it is configured for 64-bit objects.
+	# Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
+	# This test works for both compilers.
+	if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+	    if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
+		(CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		grep IS_64BIT_ARCH >/dev/null
+	    then
+		SUN_ARCH="x86_64"
+	    fi
+	fi
+	echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:6*:*)
+	# According to config.sub, this is the proper way to canonicalize
+	# SunOS6.  Hard to guess exactly what SunOS6 will be like, but
+	# it's likely to be more like Solaris than SunOS4.
+	echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    sun4*:SunOS:*:*)
+	case "`/usr/bin/arch -k`" in
+	    Series*|S4*)
+		UNAME_RELEASE=`uname -v`
+		;;
+	esac
+	# Japanese Language versions have a version number like `4.1.3-JL'.
+	echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+	exit ;;
+    sun3*:SunOS:*:*)
+	echo m68k-sun-sunos${UNAME_RELEASE}
+	exit ;;
+    sun*:*:4.2BSD:*)
+	UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+	test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+	case "`/bin/arch`" in
+	    sun3)
+		echo m68k-sun-sunos${UNAME_RELEASE}
+		;;
+	    sun4)
+		echo sparc-sun-sunos${UNAME_RELEASE}
+		;;
+	esac
+	exit ;;
+    aushp:SunOS:*:*)
+	echo sparc-auspex-sunos${UNAME_RELEASE}
+	exit ;;
+    # The situation for MiNT is a little confusing.  The machine name
+    # can be virtually everything (everything which is not
+    # "atarist" or "atariste" at least should have a processor
+    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
+    # to the lowercase version "mint" (or "freemint").  Finally
+    # the system name "TOS" denotes a system which is actually not
+    # MiNT.  But MiNT is downward compatible to TOS, so this should
+    # be no problem.
+    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+	echo m68k-atari-mint${UNAME_RELEASE}
+	exit ;;
+    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+	echo m68k-milan-mint${UNAME_RELEASE}
+	exit ;;
+    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+	echo m68k-hades-mint${UNAME_RELEASE}
+	exit ;;
+    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+	echo m68k-unknown-mint${UNAME_RELEASE}
+	exit ;;
+    m68k:machten:*:*)
+	echo m68k-apple-machten${UNAME_RELEASE}
+	exit ;;
+    powerpc:machten:*:*)
+	echo powerpc-apple-machten${UNAME_RELEASE}
+	exit ;;
+    RISC*:Mach:*:*)
+	echo mips-dec-mach_bsd4.3
+	exit ;;
+    RISC*:ULTRIX:*:*)
+	echo mips-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    VAX*:ULTRIX*:*:*)
+	echo vax-dec-ultrix${UNAME_RELEASE}
+	exit ;;
+    2020:CLIX:*:* | 2430:CLIX:*:*)
+	echo clipper-intergraph-clix${UNAME_RELEASE}
+	exit ;;
+    mips:*:*:UMIPS | mips:*:*:RISCos)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h>  /* for printf() prototype */
+	int main (int argc, char *argv[]) {
+#else
+	int main (argc, argv) int argc; char *argv[]; {
+#endif
+	#if defined (host_mips) && defined (MIPSEB)
+	#if defined (SYSTYPE_SYSV)
+	  printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_SVR4)
+	  printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+	#endif
+	#if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+	  printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+	#endif
+	#endif
+	  exit (-1);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c &&
+	  dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` &&
+	  SYSTEM_NAME=`$dummy $dummyarg` &&
+	    { echo "$SYSTEM_NAME"; exit; }
+	echo mips-mips-riscos${UNAME_RELEASE}
+	exit ;;
+    Motorola:PowerMAX_OS:*:*)
+	echo powerpc-motorola-powermax
+	exit ;;
+    Motorola:*:4.3:PL8-*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*)
+	echo powerpc-harris-powermax
+	exit ;;
+    Night_Hawk:Power_UNIX:*:*)
+	echo powerpc-harris-powerunix
+	exit ;;
+    m88k:CX/UX:7*:*)
+	echo m88k-harris-cxux7
+	exit ;;
+    m88k:*:4*:R4*)
+	echo m88k-motorola-sysv4
+	exit ;;
+    m88k:*:3*:R3*)
+	echo m88k-motorola-sysv3
+	exit ;;
+    AViiON:dgux:*:*)
+	# DG/UX returns AViiON for all architectures
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
+	if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+	then
+	    if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+	       [ ${TARGET_BINARY_INTERFACE}x = x ]
+	    then
+		echo m88k-dg-dgux${UNAME_RELEASE}
+	    else
+		echo m88k-dg-dguxbcs${UNAME_RELEASE}
+	    fi
+	else
+	    echo i586-dg-dgux${UNAME_RELEASE}
+	fi
+	exit ;;
+    M88*:DolphinOS:*:*)	# DolphinOS (SVR3)
+	echo m88k-dolphin-sysv3
+	exit ;;
+    M88*:*:R3*:*)
+	# Delta 88k system running SVR3
+	echo m88k-motorola-sysv3
+	exit ;;
+    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+	echo m88k-tektronix-sysv3
+	exit ;;
+    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+	echo m68k-tektronix-bsd
+	exit ;;
+    *:IRIX*:*:*)
+	echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+	exit ;;
+    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+	echo romp-ibm-aix     # uname -m gives an 8 hex-code CPU id
+	exit ;;               # Note that: echo "'`uname -s`'" gives 'AIX '
+    i*86:AIX:*:*)
+	echo i386-ibm-aix
+	exit ;;
+    ia64:AIX:*:*)
+	if [ -x /usr/bin/oslevel ] ; then
+		IBM_REV=`/usr/bin/oslevel`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:2:3)
+	if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+		eval $set_cc_for_build
+		sed 's/^		//' << EOF >$dummy.c
+		#include <sys/systemcfg.h>
+
+		main()
+			{
+			if (!__power_pc())
+				exit(1);
+			puts("powerpc-ibm-aix3.2.5");
+			exit(0);
+			}
+EOF
+		if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy`
+		then
+			echo "$SYSTEM_NAME"
+		else
+			echo rs6000-ibm-aix3.2.5
+		fi
+	elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+		echo rs6000-ibm-aix3.2.4
+	else
+		echo rs6000-ibm-aix3.2
+	fi
+	exit ;;
+    *:AIX:*:[4567])
+	IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'`
+	if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+		IBM_ARCH=rs6000
+	else
+		IBM_ARCH=powerpc
+	fi
+	if [ -x /usr/bin/lslpp ] ; then
+		IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc |
+			   awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
+	else
+		IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+	fi
+	echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+	exit ;;
+    *:AIX:*:*)
+	echo rs6000-ibm-aix
+	exit ;;
+    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+	echo romp-ibm-bsd4.4
+	exit ;;
+    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
+	echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
+	exit ;;                             # report: romp-ibm BSD 4.3
+    *:BOSX:*:*)
+	echo rs6000-bull-bosx
+	exit ;;
+    DPX/2?00:B.O.S.:*:*)
+	echo m68k-bull-sysv3
+	exit ;;
+    9000/[34]??:4.3bsd:1.*:*)
+	echo m68k-hp-bsd
+	exit ;;
+    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+	echo m68k-hp-bsd4.4
+	exit ;;
+    9000/[34678]??:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	case "${UNAME_MACHINE}" in
+	    9000/31? )            HP_ARCH=m68000 ;;
+	    9000/[34]?? )         HP_ARCH=m68k ;;
+	    9000/[678][0-9][0-9])
+		if [ -x /usr/bin/getconf ]; then
+		    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+		    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+		    case "${sc_cpu_version}" in
+		      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+		      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+		      532)                      # CPU_PA_RISC2_0
+			case "${sc_kernel_bits}" in
+			  32) HP_ARCH="hppa2.0n" ;;
+			  64) HP_ARCH="hppa2.0w" ;;
+			  '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+			esac ;;
+		    esac
+		fi
+		if [ "${HP_ARCH}" = "" ]; then
+		    eval $set_cc_for_build
+		    sed 's/^		//' << EOF >$dummy.c
+
+		#define _HPUX_SOURCE
+		#include <stdlib.h>
+		#include <unistd.h>
+
+		int main ()
+		{
+		#if defined(_SC_KERNEL_BITS)
+		    long bits = sysconf(_SC_KERNEL_BITS);
+		#endif
+		    long cpu  = sysconf (_SC_CPU_VERSION);
+
+		    switch (cpu)
+			{
+			case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+			case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+			case CPU_PA_RISC2_0:
+		#if defined(_SC_KERNEL_BITS)
+			    switch (bits)
+				{
+				case 64: puts ("hppa2.0w"); break;
+				case 32: puts ("hppa2.0n"); break;
+				default: puts ("hppa2.0"); break;
+				} break;
+		#else  /* !defined(_SC_KERNEL_BITS) */
+			    puts ("hppa2.0"); break;
+		#endif
+			default: puts ("hppa1.0"); break;
+			}
+		    exit (0);
+		}
+EOF
+		    (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+		    test -z "$HP_ARCH" && HP_ARCH=hppa
+		fi ;;
+	esac
+	if [ ${HP_ARCH} = "hppa2.0w" ]
+	then
+	    eval $set_cc_for_build
+
+	    # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating
+	    # 32-bit code.  hppa64-hp-hpux* has the same kernel and a compiler
+	    # generating 64-bit code.  GNU and HP use different nomenclature:
+	    #
+	    # $ CC_FOR_BUILD=cc ./config.guess
+	    # => hppa2.0w-hp-hpux11.23
+	    # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
+	    # => hppa64-hp-hpux11.23
+
+	    if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+		grep -q __LP64__
+	    then
+		HP_ARCH="hppa2.0w"
+	    else
+		HP_ARCH="hppa64"
+	    fi
+	fi
+	echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+	exit ;;
+    ia64:HP-UX:*:*)
+	HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+	echo ia64-hp-hpux${HPUX_REV}
+	exit ;;
+    3050*:HI-UX:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#include <unistd.h>
+	int
+	main ()
+	{
+	  long cpu = sysconf (_SC_CPU_VERSION);
+	  /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+	     true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
+	     results, however.  */
+	  if (CPU_IS_PA_RISC (cpu))
+	    {
+	      switch (cpu)
+		{
+		  case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+		  case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+		  default: puts ("hppa-hitachi-hiuxwe2"); break;
+		}
+	    }
+	  else if (CPU_IS_HP_MC68K (cpu))
+	    puts ("m68k-hitachi-hiuxwe2");
+	  else puts ("unknown-hitachi-hiuxwe2");
+	  exit (0);
+	}
+EOF
+	$CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` &&
+		{ echo "$SYSTEM_NAME"; exit; }
+	echo unknown-hitachi-hiuxwe2
+	exit ;;
+    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+	echo hppa1.1-hp-bsd
+	exit ;;
+    9000/8??:4.3bsd:*:*)
+	echo hppa1.0-hp-bsd
+	exit ;;
+    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+	echo hppa1.0-hp-mpeix
+	exit ;;
+    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+	echo hppa1.1-hp-osf
+	exit ;;
+    hp8??:OSF1:*:*)
+	echo hppa1.0-hp-osf
+	exit ;;
+    i*86:OSF1:*:*)
+	if [ -x /usr/sbin/sysversion ] ; then
+	    echo ${UNAME_MACHINE}-unknown-osf1mk
+	else
+	    echo ${UNAME_MACHINE}-unknown-osf1
+	fi
+	exit ;;
+    parisc*:Lites*:*:*)
+	echo hppa1.1-hp-lites
+	exit ;;
+    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+	echo c1-convex-bsd
+	exit ;;
+    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+	if getsysinfo -f scalar_acc
+	then echo c32-convex-bsd
+	else echo c2-convex-bsd
+	fi
+	exit ;;
+    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+	echo c34-convex-bsd
+	exit ;;
+    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+	echo c38-convex-bsd
+	exit ;;
+    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+	echo c4-convex-bsd
+	exit ;;
+    CRAY*Y-MP:*:*:*)
+	echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*[A-Z]90:*:*:*)
+	echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+	| sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+	      -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+	      -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*TS:*:*:*)
+	echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*T3E:*:*:*)
+	echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    CRAY*SV1:*:*:*)
+	echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    *:UNICOS/mp:*:*)
+	echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+	exit ;;
+    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+	FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+	echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    5000:UNIX_System_V:4.*:*)
+	FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+	FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+	echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+	exit ;;
+    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+	echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+	exit ;;
+    sparc*:BSD/OS:*:*)
+	echo sparc-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:BSD/OS:*:*)
+	echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+	exit ;;
+    *:FreeBSD:*:*)
+	UNAME_PROCESSOR=`/usr/bin/uname -p`
+	case ${UNAME_PROCESSOR} in
+	    amd64)
+		echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	    *)
+		echo ${UNAME_PROCESSOR}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;;
+	esac
+	exit ;;
+    i*:CYGWIN*:*)
+	echo ${UNAME_MACHINE}-pc-cygwin
+	exit ;;
+    *:MINGW64*:*)
+	echo ${UNAME_MACHINE}-pc-mingw64
+	exit ;;
+    *:MINGW*:*)
+	echo ${UNAME_MACHINE}-pc-mingw32
+	exit ;;
+    *:MSYS*:*)
+	echo ${UNAME_MACHINE}-pc-msys
+	exit ;;
+    i*:windows32*:*)
+	# uname -m includes "-pc" on this system.
+	echo ${UNAME_MACHINE}-mingw32
+	exit ;;
+    i*:PW*:*)
+	echo ${UNAME_MACHINE}-pc-pw32
+	exit ;;
+    *:Interix*:*)
+	case ${UNAME_MACHINE} in
+	    x86)
+		echo i586-pc-interix${UNAME_RELEASE}
+		exit ;;
+	    authenticamd | genuineintel | EM64T)
+		echo x86_64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	    IA64)
+		echo ia64-unknown-interix${UNAME_RELEASE}
+		exit ;;
+	esac ;;
+    [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*)
+	echo i${UNAME_MACHINE}-pc-mks
+	exit ;;
+    8664:Windows_NT:*)
+	echo x86_64-pc-mks
+	exit ;;
+    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+	# How do we know it's Interix rather than the generic POSIX subsystem?
+	# It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+	# UNAME_MACHINE based on the output of uname instead of i386?
+	echo i586-pc-interix
+	exit ;;
+    i*:UWIN*:*)
+	echo ${UNAME_MACHINE}-pc-uwin
+	exit ;;
+    amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*)
+	echo x86_64-unknown-cygwin
+	exit ;;
+    p*:CYGWIN*:*)
+	echo powerpcle-unknown-cygwin
+	exit ;;
+    prep*:SunOS:5.*:*)
+	echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+	exit ;;
+    *:GNU:*:*)
+	# the GNU system
+	echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-${LIBC}`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+	exit ;;
+    *:GNU/*:*:*)
+	# other systems with GNU libc and userland
+	echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
+	exit ;;
+    i*86:Minix:*:*)
+	echo ${UNAME_MACHINE}-pc-minix
+	exit ;;
+    aarch64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    aarch64_be:Linux:*:*)
+	UNAME_MACHINE=aarch64_be
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    alpha:Linux:*:*)
+	case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+	  EV5)   UNAME_MACHINE=alphaev5 ;;
+	  EV56)  UNAME_MACHINE=alphaev56 ;;
+	  PCA56) UNAME_MACHINE=alphapca56 ;;
+	  PCA57) UNAME_MACHINE=alphapca56 ;;
+	  EV6)   UNAME_MACHINE=alphaev6 ;;
+	  EV67)  UNAME_MACHINE=alphaev67 ;;
+	  EV68*) UNAME_MACHINE=alphaev68 ;;
+	esac
+	objdump --private-headers /bin/sh | grep -q ld.so.1
+	if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arc:Linux:*:* | arceb:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    arm*:Linux:*:*)
+	eval $set_cc_for_build
+	if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \
+	    | grep -q __ARM_EABI__
+	then
+	    echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	else
+	    if echo __ARM_PCS_VFP | $CC_FOR_BUILD -E - 2>/dev/null \
+		| grep -q __ARM_PCS_VFP
+	    then
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabi
+	    else
+		echo ${UNAME_MACHINE}-unknown-linux-${LIBC}eabihf
+	    fi
+	fi
+	exit ;;
+    avr32*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    cris:Linux:*:*)
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+	exit ;;
+    crisv32:Linux:*:*)
+	echo ${UNAME_MACHINE}-axis-linux-${LIBC}
+	exit ;;
+    e2k:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    frv:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    hexagon:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    i*86:Linux:*:*)
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
+	exit ;;
+    ia64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    k1om:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    m32r*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    m68*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    mips:Linux:*:* | mips64:Linux:*:*)
+	eval $set_cc_for_build
+	sed 's/^	//' << EOF >$dummy.c
+	#undef CPU
+	#undef ${UNAME_MACHINE}
+	#undef ${UNAME_MACHINE}el
+	#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL)
+	CPU=${UNAME_MACHINE}el
+	#else
+	#if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB)
+	CPU=${UNAME_MACHINE}
+	#else
+	CPU=
+	#endif
+	#endif
+EOF
+	eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
+	test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
+	;;
+    openrisc*:Linux:*:*)
+	echo or1k-unknown-linux-${LIBC}
+	exit ;;
+    or32:Linux:*:* | or1k*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    padre:Linux:*:*)
+	echo sparc-unknown-linux-${LIBC}
+	exit ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+	echo hppa64-unknown-linux-${LIBC}
+	exit ;;
+    parisc:Linux:*:* | hppa:Linux:*:*)
+	# Look for CPU level
+	case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+	  PA7*) echo hppa1.1-unknown-linux-${LIBC} ;;
+	  PA8*) echo hppa2.0-unknown-linux-${LIBC} ;;
+	  *)    echo hppa-unknown-linux-${LIBC} ;;
+	esac
+	exit ;;
+    ppc64:Linux:*:*)
+	echo powerpc64-unknown-linux-${LIBC}
+	exit ;;
+    ppc:Linux:*:*)
+	echo powerpc-unknown-linux-${LIBC}
+	exit ;;
+    ppc64le:Linux:*:*)
+	echo powerpc64le-unknown-linux-${LIBC}
+	exit ;;
+    ppcle:Linux:*:*)
+	echo powerpcle-unknown-linux-${LIBC}
+	exit ;;
+    s390:Linux:*:* | s390x:Linux:*:*)
+	echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
+	exit ;;
+    sh64*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    sh*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    sparc:Linux:*:* | sparc64:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    tile*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    vax:Linux:*:*)
+	echo ${UNAME_MACHINE}-dec-linux-${LIBC}
+	exit ;;
+    x86_64:Linux:*:*)
+	echo ${UNAME_MACHINE}-pc-linux-${LIBC}
+	exit ;;
+    xtensa*:Linux:*:*)
+	echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+	exit ;;
+    i*86:DYNIX/ptx:4*:*)
+	# ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+	# earlier versions are messed up and put the nodename in both
+	# sysname and nodename.
+	echo i386-sequent-sysv4
+	exit ;;
+    i*86:UNIX_SV:4.2MP:2.*)
+	# Unixware is an offshoot of SVR4, but it has its own version
+	# number series starting with 2...
+	# I am not positive that other SVR4 systems won't match this,
+	# I just have to hope.  -- rms.
+	# Use sysv4.2uw... so that sysv4* matches it.
+	echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+	exit ;;
+    i*86:OS/2:*:*)
+	# If we were able to find `uname', then EMX Unix compatibility
+	# is probably installed.
+	echo ${UNAME_MACHINE}-pc-os2-emx
+	exit ;;
+    i*86:XTS-300:*:STOP)
+	echo ${UNAME_MACHINE}-unknown-stop
+	exit ;;
+    i*86:atheos:*:*)
+	echo ${UNAME_MACHINE}-unknown-atheos
+	exit ;;
+    i*86:syllable:*:*)
+	echo ${UNAME_MACHINE}-pc-syllable
+	exit ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*)
+	echo i386-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    i*86:*DOS:*:*)
+	echo ${UNAME_MACHINE}-pc-msdosdjgpp
+	exit ;;
+    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+	UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+	if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+		echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+	else
+		echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+	fi
+	exit ;;
+    i*86:*:5:[678]*)
+	# UnixWare 7.x, OpenUNIX and OpenServer 6.
+	case `/bin/uname -X | grep "^Machine"` in
+	    *486*)	     UNAME_MACHINE=i486 ;;
+	    *Pentium)	     UNAME_MACHINE=i586 ;;
+	    *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+	esac
+	echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+	exit ;;
+    i*86:*:3.2:*)
+	if test -f /usr/options/cb.name; then
+		UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+		echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+	elif /bin/uname -X 2>/dev/null >/dev/null ; then
+		UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')`
+		(/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486
+		(/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \
+			&& UNAME_MACHINE=i586
+		(/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		(/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \
+			&& UNAME_MACHINE=i686
+		echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+	else
+		echo ${UNAME_MACHINE}-pc-sysv32
+	fi
+	exit ;;
+    pc:*:*:*)
+	# Left here for compatibility:
+	# uname -m prints for DJGPP always 'pc', but it prints nothing about
+	# the processor, so we play safe by assuming i586.
+	# Note: whatever this is, it MUST be the same as what config.sub
+	# prints for the "djgpp" host, or else GDB configury will decide that
+	# this is a cross-build.
+	echo i586-pc-msdosdjgpp
+	exit ;;
+    Intel:Mach:3*:*)
+	echo i386-pc-mach3
+	exit ;;
+    paragon:*:*:*)
+	echo i860-intel-osf1
+	exit ;;
+    i860:*:4.*:*) # i860-SVR4
+	if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+	  echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+	else # Add other i860-SVR4 vendors below as they are discovered.
+	  echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
+	fi
+	exit ;;
+    mini*:CTIX:SYS*5:*)
+	# "miniframe"
+	echo m68010-convergent-sysv
+	exit ;;
+    mc68k:UNIX:SYSTEM5:3.51m)
+	echo m68k-convergent-sysv
+	exit ;;
+    M680?0:D-NIX:5.3:*)
+	echo m68k-diab-dnix
+	exit ;;
+    M68*:*:R3V[5678]*:*)
+	test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;;
+    3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0)
+	OS_REL=''
+	test -r /etc/.relid \
+	&& OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	  && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	  && { echo i486-ncr-sysv4; exit; } ;;
+    NCR*:*:4.2:* | MPRAS*:*:4.2:*)
+	OS_REL='.3'
+	test -r /etc/.relid \
+	    && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+	/bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+	    && { echo i486-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; }
+	/bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \
+	    && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;;
+    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+	echo m68k-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    mc68030:UNIX_System_V:4.*:*)
+	echo m68k-atari-sysv4
+	exit ;;
+    TSUNAMI:LynxOS:2.*:*)
+	echo sparc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    rs6000:LynxOS:2.*:*)
+	echo rs6000-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*)
+	echo powerpc-unknown-lynxos${UNAME_RELEASE}
+	exit ;;
+    SM[BE]S:UNIX_SV:*:*)
+	echo mips-dde-sysv${UNAME_RELEASE}
+	exit ;;
+    RM*:ReliantUNIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    RM*:SINIX-*:*:*)
+	echo mips-sni-sysv4
+	exit ;;
+    *:SINIX-*:*:*)
+	if uname -p 2>/dev/null >/dev/null ; then
+		UNAME_MACHINE=`(uname -p) 2>/dev/null`
+		echo ${UNAME_MACHINE}-sni-sysv4
+	else
+		echo ns32k-sni-sysv
+	fi
+	exit ;;
+    PENTIUM:*:4.0*:*)	# Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+			# says <Richard.M.Bartel at ccMail.Census.GOV>
+	echo i586-unisys-sysv4
+	exit ;;
+    *:UNIX_System_V:4*:FTX*)
+	# From Gerald Hewes <hewes at openmarket.com>.
+	# How about differentiating between stratus architectures? -djm
+	echo hppa1.1-stratus-sysv4
+	exit ;;
+    *:*:*:FTX*)
+	# From seanf at swdc.stratus.com.
+	echo i860-stratus-sysv4
+	exit ;;
+    i*86:VOS:*:*)
+	# From Paul.Green at stratus.com.
+	echo ${UNAME_MACHINE}-stratus-vos
+	exit ;;
+    *:VOS:*:*)
+	# From Paul.Green at stratus.com.
+	echo hppa1.1-stratus-vos
+	exit ;;
+    mc68*:A/UX:*:*)
+	echo m68k-apple-aux${UNAME_RELEASE}
+	exit ;;
+    news*:NEWS-OS:6*:*)
+	echo mips-sony-newsos6
+	exit ;;
+    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+	if [ -d /usr/nec ]; then
+		echo mips-nec-sysv${UNAME_RELEASE}
+	else
+		echo mips-unknown-sysv${UNAME_RELEASE}
+	fi
+	exit ;;
+    BeBox:BeOS:*:*)	# BeOS running on hardware made by Be, PPC only.
+	echo powerpc-be-beos
+	exit ;;
+    BeMac:BeOS:*:*)	# BeOS running on Mac or Mac clone, PPC only.
+	echo powerpc-apple-beos
+	exit ;;
+    BePC:BeOS:*:*)	# BeOS running on Intel PC compatible.
+	echo i586-pc-beos
+	exit ;;
+    BePC:Haiku:*:*)	# Haiku running on Intel PC compatible.
+	echo i586-pc-haiku
+	exit ;;
+    x86_64:Haiku:*:*)
+	echo x86_64-unknown-haiku
+	exit ;;
+    SX-4:SUPER-UX:*:*)
+	echo sx4-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-5:SUPER-UX:*:*)
+	echo sx5-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-6:SUPER-UX:*:*)
+	echo sx6-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-7:SUPER-UX:*:*)
+	echo sx7-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8:SUPER-UX:*:*)
+	echo sx8-nec-superux${UNAME_RELEASE}
+	exit ;;
+    SX-8R:SUPER-UX:*:*)
+	echo sx8r-nec-superux${UNAME_RELEASE}
+	exit ;;
+    Power*:Rhapsody:*:*)
+	echo powerpc-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Rhapsody:*:*)
+	echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+	exit ;;
+    *:Darwin:*:*)
+	UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown
+	eval $set_cc_for_build
+	if test "$UNAME_PROCESSOR" = unknown ; then
+	    UNAME_PROCESSOR=powerpc
+	fi
+	if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
+	    if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+		if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
+		    (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+		    grep IS_64BIT_ARCH >/dev/null
+		then
+		    case $UNAME_PROCESSOR in
+			i386) UNAME_PROCESSOR=x86_64 ;;
+			powerpc) UNAME_PROCESSOR=powerpc64 ;;
+		    esac
+		fi
+	    fi
+	elif test "$UNAME_PROCESSOR" = i386 ; then
+	    # Avoid executing cc on OS X 10.9, as it ships with a stub
+	    # that puts up a graphical alert prompting to install
+	    # developer tools.  Any system running Mac OS X 10.7 or
+	    # later (Darwin 11 and later) is required to have a 64-bit
+	    # processor. This is not true of the ARM version of Darwin
+	    # that Apple uses in portable devices.
+	    UNAME_PROCESSOR=x86_64
+	fi
+	echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE}
+	exit ;;
+    *:procnto*:*:* | *:QNX:[0123456789]*:*)
+	UNAME_PROCESSOR=`uname -p`
+	if test "$UNAME_PROCESSOR" = "x86"; then
+		UNAME_PROCESSOR=i386
+		UNAME_MACHINE=pc
+	fi
+	echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE}
+	exit ;;
+    *:QNX:*:4*)
+	echo i386-pc-qnx
+	exit ;;
+    NEO-?:NONSTOP_KERNEL:*:*)
+	echo neo-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSE-*:NONSTOP_KERNEL:*:*)
+	echo nse-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    NSR-?:NONSTOP_KERNEL:*:*)
+	echo nsr-tandem-nsk${UNAME_RELEASE}
+	exit ;;
+    *:NonStop-UX:*:*)
+	echo mips-compaq-nonstopux
+	exit ;;
+    BS2000:POSIX*:*:*)
+	echo bs2000-siemens-sysv
+	exit ;;
+    DS/*:UNIX_System_V:*:*)
+	echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+	exit ;;
+    *:Plan9:*:*)
+	# "uname -m" is not consistent, so use $cputype instead. 386
+	# is converted to i386 for consistency with other x86
+	# operating systems.
+	if test "$cputype" = "386"; then
+	    UNAME_MACHINE=i386
+	else
+	    UNAME_MACHINE="$cputype"
+	fi
+	echo ${UNAME_MACHINE}-unknown-plan9
+	exit ;;
+    *:TOPS-10:*:*)
+	echo pdp10-unknown-tops10
+	exit ;;
+    *:TENEX:*:*)
+	echo pdp10-unknown-tenex
+	exit ;;
+    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+	echo pdp10-dec-tops20
+	exit ;;
+    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+	echo pdp10-xkl-tops20
+	exit ;;
+    *:TOPS-20:*:*)
+	echo pdp10-unknown-tops20
+	exit ;;
+    *:ITS:*:*)
+	echo pdp10-unknown-its
+	exit ;;
+    SEI:*:*:SEIUX)
+	echo mips-sei-seiux${UNAME_RELEASE}
+	exit ;;
+    *:DragonFly:*:*)
+	echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+	exit ;;
+    *:*VMS:*:*)
+	UNAME_MACHINE=`(uname -p) 2>/dev/null`
+	case "${UNAME_MACHINE}" in
+	    A*) echo alpha-dec-vms ; exit ;;
+	    I*) echo ia64-dec-vms ; exit ;;
+	    V*) echo vax-dec-vms ; exit ;;
+	esac ;;
+    *:XENIX:*:SysV)
+	echo i386-pc-xenix
+	exit ;;
+    i*86:skyos:*:*)
+	echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+	exit ;;
+    i*86:rdos:*:*)
+	echo ${UNAME_MACHINE}-pc-rdos
+	exit ;;
+    i*86:AROS:*:*)
+	echo ${UNAME_MACHINE}-pc-aros
+	exit ;;
+    x86_64:VMkernel:*:*)
+	echo ${UNAME_MACHINE}-unknown-esx
+	exit ;;
+esac
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+and
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches at gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo               = `(hostinfo) 2>/dev/null`
+/bin/universe          = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch              = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM  = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/src/build/autoconf/config.sub b/src/build/autoconf/config.sub
new file mode 100755
index 0000000..1acc966
--- /dev/null
+++ b/src/build/autoconf/config.sub
@@ -0,0 +1,1813 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+#   Copyright 1992-2015 Free Software Foundation, Inc.
+
+timestamp='2015-08-20'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, see <http://www.gnu.org/licenses/>.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that
+# program.  This Exception is an additional permission under section 7
+# of the GNU General Public License, version 3 ("GPLv3").
+
+
+# Please send patches to <config-patches at gnu.org>.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# You can get the latest version of this script from:
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support.  The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+#	CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+#	CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+       $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches at gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright 1992-2015 Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit ;;
+    --version | -v )
+       echo "$version" ; exit ;;
+    --help | --h* | -h )
+       echo "$usage"; exit ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )	# Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help"
+       exit 1 ;;
+
+    *local*)
+       # First pass through any local machine types.
+       echo $1
+       exit ;;
+
+    * )
+       break ;;
+  esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+    exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+    exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+  nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
+  linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \
+  kopensolaris*-gnu* | \
+  storm-chaos* | os2-emx* | rtmk-nova*)
+    os=-$maybe_os
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+    ;;
+  android-linux)
+    os=-linux-android
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`-unknown
+    ;;
+  *)
+    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+    if [ $basic_machine != $1 ]
+    then os=`echo $1 | sed 's/.*-/-/'`
+    else os=; fi
+    ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work.  We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+	-sun*os*)
+		# Prevent following clause from handling this invalid input.
+		;;
+	-dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+	-att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+	-unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+	-convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+	-c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+	-harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+	-apple | -axis | -knuth | -cray | -microblaze*)
+		os=
+		basic_machine=$1
+		;;
+	-bluegene*)
+		os=-cnk
+		;;
+	-sim | -cisco | -oki | -wec | -winbond)
+		os=
+		basic_machine=$1
+		;;
+	-scout)
+		;;
+	-wrs)
+		os=-vxworks
+		basic_machine=$1
+		;;
+	-chorusos*)
+		os=-chorusos
+		basic_machine=$1
+		;;
+	-chorusrdb)
+		os=-chorusrdb
+		basic_machine=$1
+		;;
+	-hiux*)
+		os=-hiuxwe2
+		;;
+	-sco6)
+		os=-sco5v6
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5)
+		os=-sco3.2v5
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco4)
+		os=-sco3.2v4
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2.[4-9]*)
+		os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco3.2v[4-9]*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco5v6*)
+		# Don't forget version if it is 3.2v4 or newer.
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-sco*)
+		os=-sco3.2v2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-udk*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-isc)
+		os=-isc2.2
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-clix*)
+		basic_machine=clipper-intergraph
+		;;
+	-isc*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+		;;
+	-lynx*178)
+		os=-lynxos178
+		;;
+	-lynx*5)
+		os=-lynxos5
+		;;
+	-lynx*)
+		os=-lynxos
+		;;
+	-ptx*)
+		basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+		;;
+	-windowsnt*)
+		os=`echo $os | sed -e 's/windowsnt/winnt/'`
+		;;
+	-psos*)
+		os=-psos
+		;;
+	-mint | -mint[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+	# Recognize the basic CPU types without company name.
+	# Some are omitted here because they have special meanings below.
+	1750a | 580 \
+	| a29k \
+	| aarch64 | aarch64_be \
+	| alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+	| alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+	| am33_2.0 \
+	| arc | arceb \
+	| arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
+	| avr | avr32 \
+	| ba \
+	| be32 | be64 \
+	| bfin \
+	| c4x | c8051 | clipper \
+	| d10v | d30v | dlx | dsp16xx \
+	| e2k | epiphany \
+	| fido | fr30 | frv | ft32 \
+	| h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+	| hexagon \
+	| i370 | i860 | i960 | ia64 \
+	| ip2k | iq2000 \
+	| k1om \
+	| le32 | le64 \
+	| lm32 \
+	| m32c | m32r | m32rle | m68000 | m68k | m88k \
+	| maxq | mb | microblaze | microblazeel | mcore | mep | metag \
+	| mips | mipsbe | mipseb | mipsel | mipsle \
+	| mips16 \
+	| mips64 | mips64el \
+	| mips64octeon | mips64octeonel \
+	| mips64orion | mips64orionel \
+	| mips64r5900 | mips64r5900el \
+	| mips64vr | mips64vrel \
+	| mips64vr4100 | mips64vr4100el \
+	| mips64vr4300 | mips64vr4300el \
+	| mips64vr5000 | mips64vr5000el \
+	| mips64vr5900 | mips64vr5900el \
+	| mipsisa32 | mipsisa32el \
+	| mipsisa32r2 | mipsisa32r2el \
+	| mipsisa32r6 | mipsisa32r6el \
+	| mipsisa64 | mipsisa64el \
+	| mipsisa64r2 | mipsisa64r2el \
+	| mipsisa64r6 | mipsisa64r6el \
+	| mipsisa64sb1 | mipsisa64sb1el \
+	| mipsisa64sr71k | mipsisa64sr71kel \
+	| mipsr5900 | mipsr5900el \
+	| mipstx39 | mipstx39el \
+	| mn10200 | mn10300 \
+	| moxie \
+	| mt \
+	| msp430 \
+	| nds32 | nds32le | nds32be \
+	| nios | nios2 | nios2eb | nios2el \
+	| ns16k | ns32k \
+	| open8 | or1k | or1knd | or32 \
+	| pdp10 | pdp11 | pj | pjl \
+	| powerpc | powerpc64 | powerpc64le | powerpcle \
+	| pyramid \
+	| riscv32 | riscv64 \
+	| rl78 | rx \
+	| score \
+	| sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[234]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+	| sh64 | sh64le \
+	| sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
+	| sparcv8 | sparcv9 | sparcv9b | sparcv9v \
+	| spu \
+	| tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
+	| ubicom32 \
+	| v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+	| visium \
+	| we32k \
+	| x86 | xc16x | xstormy16 | xtensa \
+	| z8k | z80)
+		basic_machine=$basic_machine-unknown
+		;;
+	c54x)
+		basic_machine=tic54x-unknown
+		;;
+	c55x)
+		basic_machine=tic55x-unknown
+		;;
+	c6x)
+		basic_machine=tic6x-unknown
+		;;
+	leon|leon[3-9])
+		basic_machine=sparc-$basic_machine
+		;;
+	m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+		;;
+	ms1)
+		basic_machine=mt-unknown
+		;;
+
+	strongarm | thumb | xscale)
+		basic_machine=arm-unknown
+		;;
+	xgate)
+		basic_machine=$basic_machine-unknown
+		os=-none
+		;;
+	xscaleeb)
+		basic_machine=armeb-unknown
+		;;
+
+	xscaleel)
+		basic_machine=armel-unknown
+		;;
+
+	# We use `pc' rather than `unknown'
+	# because (1) that's what they normally are, and
+	# (2) the word "unknown" tends to confuse beginning users.
+	i*86 | x86_64)
+	  basic_machine=$basic_machine-pc
+	  ;;
+	# Object if more than one company name word.
+	*-*-*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+	# Recognize the basic CPU types with company name.
+	580-* \
+	| a29k-* \
+	| aarch64-* | aarch64_be-* \
+	| alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+	| alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+	| alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
+	| arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
+	| avr-* | avr32-* \
+	| ba-* \
+	| be32-* | be64-* \
+	| bfin-* | bs2000-* \
+	| c[123]* | c30-* | [cjt]90-* | c4x-* \
+	| c8051-* | clipper-* | craynv-* | cydra-* \
+	| d10v-* | d30v-* | dlx-* \
+	| e2k-* | elxsi-* \
+	| f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
+	| h8300-* | h8500-* \
+	| hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+	| hexagon-* \
+	| i*86-* | i860-* | i960-* | ia64-* \
+	| ip2k-* | iq2000-* \
+	| k1om-* \
+	| le32-* | le64-* \
+	| lm32-* \
+	| m32c-* | m32r-* | m32rle-* \
+	| m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \
+	| m88110-* | m88k-* | maxq-* | mcore-* | metag-* \
+	| microblaze-* | microblazeel-* \
+	| mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \
+	| mips16-* \
+	| mips64-* | mips64el-* \
+	| mips64octeon-* | mips64octeonel-* \
+	| mips64orion-* | mips64orionel-* \
+	| mips64r5900-* | mips64r5900el-* \
+	| mips64vr-* | mips64vrel-* \
+	| mips64vr4100-* | mips64vr4100el-* \
+	| mips64vr4300-* | mips64vr4300el-* \
+	| mips64vr5000-* | mips64vr5000el-* \
+	| mips64vr5900-* | mips64vr5900el-* \
+	| mipsisa32-* | mipsisa32el-* \
+	| mipsisa32r2-* | mipsisa32r2el-* \
+	| mipsisa32r6-* | mipsisa32r6el-* \
+	| mipsisa64-* | mipsisa64el-* \
+	| mipsisa64r2-* | mipsisa64r2el-* \
+	| mipsisa64r6-* | mipsisa64r6el-* \
+	| mipsisa64sb1-* | mipsisa64sb1el-* \
+	| mipsisa64sr71k-* | mipsisa64sr71kel-* \
+	| mipsr5900-* | mipsr5900el-* \
+	| mipstx39-* | mipstx39el-* \
+	| mmix-* \
+	| mt-* \
+	| msp430-* \
+	| nds32-* | nds32le-* | nds32be-* \
+	| nios-* | nios2-* | nios2eb-* | nios2el-* \
+	| none-* | np1-* | ns16k-* | ns32k-* \
+	| open8-* \
+	| or1k*-* \
+	| orion-* \
+	| pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+	| powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+	| pyramid-* \
+	| riscv32-* | riscv64-* \
+	| rl78-* | romp-* | rs6000-* | rx-* \
+	| sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
+	| shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
+	| sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
+	| sparclite-* \
+	| sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx*-* \
+	| tahoe-* \
+	| tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
+	| tile*-* \
+	| tron-* \
+	| ubicom32-* \
+	| v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
+	| vax-* \
+	| visium-* \
+	| we32k-* \
+	| x86-* | x86_64-* | xc16x-* | xps100-* \
+	| xstormy16-* | xtensa*-* \
+	| ymp-* \
+	| z8k-* | z80-*)
+		;;
+	# Recognize the basic CPU types without company name, with glob match.
+	xtensa*)
+		basic_machine=$basic_machine-unknown
+		;;
+	# Recognize the various machine names and aliases which stand
+	# for a CPU type and a company and sometimes even an OS.
+	386bsd)
+		basic_machine=i386-unknown
+		os=-bsd
+		;;
+	3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+		basic_machine=m68000-att
+		;;
+	3b*)
+		basic_machine=we32k-att
+		;;
+	a29khif)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	abacus)
+		basic_machine=abacus-unknown
+		;;
+	adobe68k)
+		basic_machine=m68010-adobe
+		os=-scout
+		;;
+	alliant | fx80)
+		basic_machine=fx80-alliant
+		;;
+	altos | altos3068)
+		basic_machine=m68k-altos
+		;;
+	am29k)
+		basic_machine=a29k-none
+		os=-bsd
+		;;
+	amd64)
+		basic_machine=x86_64-pc
+		;;
+	amd64-*)
+		basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	amdahl)
+		basic_machine=580-amdahl
+		os=-sysv
+		;;
+	amiga | amiga-*)
+		basic_machine=m68k-unknown
+		;;
+	amigaos | amigados)
+		basic_machine=m68k-unknown
+		os=-amigaos
+		;;
+	amigaunix | amix)
+		basic_machine=m68k-unknown
+		os=-sysv4
+		;;
+	apollo68)
+		basic_machine=m68k-apollo
+		os=-sysv
+		;;
+	apollo68bsd)
+		basic_machine=m68k-apollo
+		os=-bsd
+		;;
+	aros)
+		basic_machine=i386-pc
+		os=-aros
+		;;
+        asmjs)
+		basic_machine=asmjs-unknown
+		;;
+	aux)
+		basic_machine=m68k-apple
+		os=-aux
+		;;
+	balance)
+		basic_machine=ns32k-sequent
+		os=-dynix
+		;;
+	blackfin)
+		basic_machine=bfin-unknown
+		os=-linux
+		;;
+	blackfin-*)
+		basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	bluegene*)
+		basic_machine=powerpc-ibm
+		os=-cnk
+		;;
+	c54x-*)
+		basic_machine=tic54x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c55x-*)
+		basic_machine=tic55x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c6x-*)
+		basic_machine=tic6x-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	c90)
+		basic_machine=c90-cray
+		os=-unicos
+		;;
+	cegcc)
+		basic_machine=arm-unknown
+		os=-cegcc
+		;;
+	convex-c1)
+		basic_machine=c1-convex
+		os=-bsd
+		;;
+	convex-c2)
+		basic_machine=c2-convex
+		os=-bsd
+		;;
+	convex-c32)
+		basic_machine=c32-convex
+		os=-bsd
+		;;
+	convex-c34)
+		basic_machine=c34-convex
+		os=-bsd
+		;;
+	convex-c38)
+		basic_machine=c38-convex
+		os=-bsd
+		;;
+	cray | j90)
+		basic_machine=j90-cray
+		os=-unicos
+		;;
+	craynv)
+		basic_machine=craynv-cray
+		os=-unicosmp
+		;;
+	cr16 | cr16-*)
+		basic_machine=cr16-unknown
+		os=-elf
+		;;
+	crds | unos)
+		basic_machine=m68k-crds
+		;;
+	crisv32 | crisv32-* | etraxfs*)
+		basic_machine=crisv32-axis
+		;;
+	cris | cris-* | etrax*)
+		basic_machine=cris-axis
+		;;
+	crx)
+		basic_machine=crx-unknown
+		os=-elf
+		;;
+	da30 | da30-*)
+		basic_machine=m68k-da30
+		;;
+	decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+		basic_machine=mips-dec
+		;;
+	decsystem10* | dec10*)
+		basic_machine=pdp10-dec
+		os=-tops10
+		;;
+	decsystem20* | dec20*)
+		basic_machine=pdp10-dec
+		os=-tops20
+		;;
+	delta | 3300 | motorola-3300 | motorola-delta \
+	      | 3300-motorola | delta-motorola)
+		basic_machine=m68k-motorola
+		;;
+	delta88)
+		basic_machine=m88k-motorola
+		os=-sysv3
+		;;
+	dicos)
+		basic_machine=i686-pc
+		os=-dicos
+		;;
+	djgpp)
+		basic_machine=i586-pc
+		os=-msdosdjgpp
+		;;
+	dpx20 | dpx20-*)
+		basic_machine=rs6000-bull
+		os=-bosx
+		;;
+	dpx2* | dpx2*-bull)
+		basic_machine=m68k-bull
+		os=-sysv3
+		;;
+	ebmon29k)
+		basic_machine=a29k-amd
+		os=-ebmon
+		;;
+	elxsi)
+		basic_machine=elxsi-elxsi
+		os=-bsd
+		;;
+	encore | umax | mmax)
+		basic_machine=ns32k-encore
+		;;
+	es1800 | OSE68k | ose68k | ose | OSE)
+		basic_machine=m68k-ericsson
+		os=-ose
+		;;
+	fx2800)
+		basic_machine=i860-alliant
+		;;
+	genix)
+		basic_machine=ns32k-ns
+		;;
+	gmicro)
+		basic_machine=tron-gmicro
+		os=-sysv
+		;;
+	go32)
+		basic_machine=i386-pc
+		os=-go32
+		;;
+	h3050r* | hiux*)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	h8300hms)
+		basic_machine=h8300-hitachi
+		os=-hms
+		;;
+	h8300xray)
+		basic_machine=h8300-hitachi
+		os=-xray
+		;;
+	h8500hms)
+		basic_machine=h8500-hitachi
+		os=-hms
+		;;
+	harris)
+		basic_machine=m88k-harris
+		os=-sysv3
+		;;
+	hp300-*)
+		basic_machine=m68k-hp
+		;;
+	hp300bsd)
+		basic_machine=m68k-hp
+		os=-bsd
+		;;
+	hp300hpux)
+		basic_machine=m68k-hp
+		os=-hpux
+		;;
+	hp3k9[0-9][0-9] | hp9[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k2[0-9][0-9] | hp9k31[0-9])
+		basic_machine=m68000-hp
+		;;
+	hp9k3[2-9][0-9])
+		basic_machine=m68k-hp
+		;;
+	hp9k6[0-9][0-9] | hp6[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hp9k7[0-79][0-9] | hp7[0-79][0-9])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k78[0-9] | hp78[0-9])
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+		# FIXME: really hppa2.0-hp
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][13679] | hp8[0-9][13679])
+		basic_machine=hppa1.1-hp
+		;;
+	hp9k8[0-9][0-9] | hp8[0-9][0-9])
+		basic_machine=hppa1.0-hp
+		;;
+	hppa-next)
+		os=-nextstep3
+		;;
+	hppaosf)
+		basic_machine=hppa1.1-hp
+		os=-osf
+		;;
+	hppro)
+		basic_machine=hppa1.1-hp
+		os=-proelf
+		;;
+	i370-ibm* | ibm*)
+		basic_machine=i370-ibm
+		;;
+	i*86v32)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv32
+		;;
+	i*86v4*)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv4
+		;;
+	i*86v)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-sysv
+		;;
+	i*86sol2)
+		basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+		os=-solaris2
+		;;
+	i386mach)
+		basic_machine=i386-mach
+		os=-mach
+		;;
+	i386-vsta | vsta)
+		basic_machine=i386-unknown
+		os=-vsta
+		;;
+	iris | iris4d)
+		basic_machine=mips-sgi
+		case $os in
+		    -irix*)
+			;;
+		    *)
+			os=-irix4
+			;;
+		esac
+		;;
+	isi68 | isi)
+		basic_machine=m68k-isi
+		os=-sysv
+		;;
+	leon-*|leon[3-9]-*)
+		basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'`
+		;;
+	m68knommu)
+		basic_machine=m68k-unknown
+		os=-linux
+		;;
+	m68knommu-*)
+		basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	m88k-omron*)
+		basic_machine=m88k-omron
+		;;
+	magnum | m3230)
+		basic_machine=mips-mips
+		os=-sysv
+		;;
+	merlin)
+		basic_machine=ns32k-utek
+		os=-sysv
+		;;
+	microblaze*)
+		basic_machine=microblaze-xilinx
+		;;
+	mingw64)
+		basic_machine=x86_64-pc
+		os=-mingw64
+		;;
+	mingw32)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
+	mingw32ce)
+		basic_machine=arm-unknown
+		os=-mingw32ce
+		;;
+	miniframe)
+		basic_machine=m68000-convergent
+		;;
+	*mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+		basic_machine=m68k-atari
+		os=-mint
+		;;
+	mips3*-*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+		;;
+	mips3*)
+		basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+		;;
+	monitor)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	morphos)
+		basic_machine=powerpc-unknown
+		os=-morphos
+		;;
+	moxiebox)
+		basic_machine=moxie-unknown
+		os=-moxiebox
+		;;
+	msdos)
+		basic_machine=i386-pc
+		os=-msdos
+		;;
+	ms1-*)
+		basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'`
+		;;
+	msys)
+		basic_machine=i686-pc
+		os=-msys
+		;;
+	mvs)
+		basic_machine=i370-ibm
+		os=-mvs
+		;;
+	nacl)
+		basic_machine=le32-unknown
+		os=-nacl
+		;;
+	ncr3000)
+		basic_machine=i486-ncr
+		os=-sysv4
+		;;
+	netbsd386)
+		basic_machine=i386-unknown
+		os=-netbsd
+		;;
+	netwinder)
+		basic_machine=armv4l-rebel
+		os=-linux
+		;;
+	news | news700 | news800 | news900)
+		basic_machine=m68k-sony
+		os=-newsos
+		;;
+	news1000)
+		basic_machine=m68030-sony
+		os=-newsos
+		;;
+	news-3600 | risc-news)
+		basic_machine=mips-sony
+		os=-newsos
+		;;
+	necv70)
+		basic_machine=v70-nec
+		os=-sysv
+		;;
+	next | m*-next )
+		basic_machine=m68k-next
+		case $os in
+		    -nextstep* )
+			;;
+		    -ns2*)
+		      os=-nextstep2
+			;;
+		    *)
+		      os=-nextstep3
+			;;
+		esac
+		;;
+	nh3000)
+		basic_machine=m68k-harris
+		os=-cxux
+		;;
+	nh[45]000)
+		basic_machine=m88k-harris
+		os=-cxux
+		;;
+	nindy960)
+		basic_machine=i960-intel
+		os=-nindy
+		;;
+	mon960)
+		basic_machine=i960-intel
+		os=-mon960
+		;;
+	nonstopux)
+		basic_machine=mips-compaq
+		os=-nonstopux
+		;;
+	np1)
+		basic_machine=np1-gould
+		;;
+	neo-tandem)
+		basic_machine=neo-tandem
+		;;
+	nse-tandem)
+		basic_machine=nse-tandem
+		;;
+	nsr-tandem)
+		basic_machine=nsr-tandem
+		;;
+	op50n-* | op60c-*)
+		basic_machine=hppa1.1-oki
+		os=-proelf
+		;;
+	openrisc | openrisc-*)
+		basic_machine=or32-unknown
+		;;
+	os400)
+		basic_machine=powerpc-ibm
+		os=-os400
+		;;
+	OSE68000 | ose68000)
+		basic_machine=m68000-ericsson
+		os=-ose
+		;;
+	os68k)
+		basic_machine=m68k-none
+		os=-os68k
+		;;
+	pa-hitachi)
+		basic_machine=hppa1.1-hitachi
+		os=-hiuxwe2
+		;;
+	paragon)
+		basic_machine=i860-intel
+		os=-osf
+		;;
+	parisc)
+		basic_machine=hppa-unknown
+		os=-linux
+		;;
+	parisc-*)
+		basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'`
+		os=-linux
+		;;
+	pbd)
+		basic_machine=sparc-tti
+		;;
+	pbb)
+		basic_machine=m68k-tti
+		;;
+	pc532 | pc532-*)
+		basic_machine=ns32k-pc532
+		;;
+	pc98)
+		basic_machine=i386-pc
+		;;
+	pc98-*)
+		basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium | p5 | k5 | k6 | nexgen | viac3)
+		basic_machine=i586-pc
+		;;
+	pentiumpro | p6 | 6x86 | athlon | athlon_*)
+		basic_machine=i686-pc
+		;;
+	pentiumii | pentium2 | pentiumiii | pentium3)
+		basic_machine=i686-pc
+		;;
+	pentium4)
+		basic_machine=i786-pc
+		;;
+	pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+		basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumpro-* | p6-* | 6x86-* | athlon-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*)
+		basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pentium4-*)
+		basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	pn)
+		basic_machine=pn-gould
+		;;
+	power)	basic_machine=power-ibm
+		;;
+	ppc | ppcbe)	basic_machine=powerpc-unknown
+		;;
+	ppc-* | ppcbe-*)
+		basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppcle | powerpclittle | ppc-le | powerpc-little)
+		basic_machine=powerpcle-unknown
+		;;
+	ppcle-* | powerpclittle-*)
+		basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64)	basic_machine=powerpc64-unknown
+		;;
+	ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+		basic_machine=powerpc64le-unknown
+		;;
+	ppc64le-* | powerpc64little-*)
+		basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	ps2)
+		basic_machine=i386-ibm
+		;;
+	pw32)
+		basic_machine=i586-unknown
+		os=-pw32
+		;;
+	rdos | rdos64)
+		basic_machine=x86_64-pc
+		os=-rdos
+		;;
+	rdos32)
+		basic_machine=i386-pc
+		os=-rdos
+		;;
+	rom68k)
+		basic_machine=m68k-rom68k
+		os=-coff
+		;;
+	rm[46]00)
+		basic_machine=mips-siemens
+		;;
+	rtpc | rtpc-*)
+		basic_machine=romp-ibm
+		;;
+	s390 | s390-*)
+		basic_machine=s390-ibm
+		;;
+	s390x | s390x-*)
+		basic_machine=s390x-ibm
+		;;
+	sa29200)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	sb1)
+		basic_machine=mipsisa64sb1-unknown
+		;;
+	sb1el)
+		basic_machine=mipsisa64sb1el-unknown
+		;;
+	sde)
+		basic_machine=mipsisa32-sde
+		os=-elf
+		;;
+	sei)
+		basic_machine=mips-sei
+		os=-seiux
+		;;
+	sequent)
+		basic_machine=i386-sequent
+		;;
+	sh)
+		basic_machine=sh-hitachi
+		os=-hms
+		;;
+	sh5el)
+		basic_machine=sh5le-unknown
+		;;
+	sh64)
+		basic_machine=sh64-unknown
+		;;
+	sparclite-wrs | simso-wrs)
+		basic_machine=sparclite-wrs
+		os=-vxworks
+		;;
+	sps7)
+		basic_machine=m68k-bull
+		os=-sysv2
+		;;
+	spur)
+		basic_machine=spur-unknown
+		;;
+	st2000)
+		basic_machine=m68k-tandem
+		;;
+	stratus)
+		basic_machine=i860-stratus
+		os=-sysv4
+		;;
+	strongarm-* | thumb-*)
+		basic_machine=arm-`echo $basic_machine | sed 's/^[^-]*-//'`
+		;;
+	sun2)
+		basic_machine=m68000-sun
+		;;
+	sun2os3)
+		basic_machine=m68000-sun
+		os=-sunos3
+		;;
+	sun2os4)
+		basic_machine=m68000-sun
+		os=-sunos4
+		;;
+	sun3os3)
+		basic_machine=m68k-sun
+		os=-sunos3
+		;;
+	sun3os4)
+		basic_machine=m68k-sun
+		os=-sunos4
+		;;
+	sun4os3)
+		basic_machine=sparc-sun
+		os=-sunos3
+		;;
+	sun4os4)
+		basic_machine=sparc-sun
+		os=-sunos4
+		;;
+	sun4sol2)
+		basic_machine=sparc-sun
+		os=-solaris2
+		;;
+	sun3 | sun3-*)
+		basic_machine=m68k-sun
+		;;
+	sun4)
+		basic_machine=sparc-sun
+		;;
+	sun386 | sun386i | roadrunner)
+		basic_machine=i386-sun
+		;;
+	sv1)
+		basic_machine=sv1-cray
+		os=-unicos
+		;;
+	symmetry)
+		basic_machine=i386-sequent
+		os=-dynix
+		;;
+	t3e)
+		basic_machine=alphaev5-cray
+		os=-unicos
+		;;
+	t90)
+		basic_machine=t90-cray
+		os=-unicos
+		;;
+	tile*)
+		basic_machine=$basic_machine-unknown
+		os=-linux-gnu
+		;;
+	tx39)
+		basic_machine=mipstx39-unknown
+		;;
+	tx39el)
+		basic_machine=mipstx39el-unknown
+		;;
+	toad1)
+		basic_machine=pdp10-xkl
+		os=-tops20
+		;;
+	tower | tower-32)
+		basic_machine=m68k-ncr
+		;;
+	tpf)
+		basic_machine=s390x-ibm
+		os=-tpf
+		;;
+	udi29k)
+		basic_machine=a29k-amd
+		os=-udi
+		;;
+	ultra3)
+		basic_machine=a29k-nyu
+		os=-sym1
+		;;
+	v810 | necv810)
+		basic_machine=v810-nec
+		os=-none
+		;;
+	vaxv)
+		basic_machine=vax-dec
+		os=-sysv
+		;;
+	vms)
+		basic_machine=vax-dec
+		os=-vms
+		;;
+	vpp*|vx|vx-*)
+		basic_machine=f301-fujitsu
+		;;
+	vxworks960)
+		basic_machine=i960-wrs
+		os=-vxworks
+		;;
+	vxworks68)
+		basic_machine=m68k-wrs
+		os=-vxworks
+		;;
+	vxworks29k)
+		basic_machine=a29k-wrs
+		os=-vxworks
+		;;
+	w65*)
+		basic_machine=w65-wdc
+		os=-none
+		;;
+	w89k-*)
+		basic_machine=hppa1.1-winbond
+		os=-proelf
+		;;
+	xbox)
+		basic_machine=i686-pc
+		os=-mingw32
+		;;
+	xps | xps100)
+		basic_machine=xps100-honeywell
+		;;
+	xscale-* | xscalee[bl]-*)
+		basic_machine=`echo $basic_machine | sed 's/^xscale/arm/'`
+		;;
+	ymp)
+		basic_machine=ymp-cray
+		os=-unicos
+		;;
+	z8k-*-coff)
+		basic_machine=z8k-unknown
+		os=-sim
+		;;
+	z80-*-coff)
+		basic_machine=z80-unknown
+		os=-sim
+		;;
+	none)
+		basic_machine=none-none
+		os=-none
+		;;
+
+# Here we handle the default manufacturer of certain CPU types.  It is in
+# some cases the only manufacturer, in others, it is the most popular.
+	w89k)
+		basic_machine=hppa1.1-winbond
+		;;
+	op50n)
+		basic_machine=hppa1.1-oki
+		;;
+	op60c)
+		basic_machine=hppa1.1-oki
+		;;
+	romp)
+		basic_machine=romp-ibm
+		;;
+	mmix)
+		basic_machine=mmix-knuth
+		;;
+	rs6000)
+		basic_machine=rs6000-ibm
+		;;
+	vax)
+		basic_machine=vax-dec
+		;;
+	pdp10)
+		# there are many clones, so DEC is not a safe bet
+		basic_machine=pdp10-unknown
+		;;
+	pdp11)
+		basic_machine=pdp11-dec
+		;;
+	we32k)
+		basic_machine=we32k-att
+		;;
+	sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele)
+		basic_machine=sh-unknown
+		;;
+	sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v)
+		basic_machine=sparc-sun
+		;;
+	cydra)
+		basic_machine=cydra-cydrome
+		;;
+	orion)
+		basic_machine=orion-highlevel
+		;;
+	orion105)
+		basic_machine=clipper-highlevel
+		;;
+	mac | mpw | mac-mpw)
+		basic_machine=m68k-apple
+		;;
+	pmac | pmac-mpw)
+		basic_machine=powerpc-apple
+		;;
+	*-unknown)
+		# Make sure to match an already-canonicalized machine name.
+		;;
+	*)
+		echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+		exit 1
+		;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+	*-digital*)
+		basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+		;;
+	*-commodore*)
+		basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+		;;
+	*)
+		;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+	# First match some system type aliases
+	# that might get confused with valid system types.
+	# -solaris* is a basic system type, with this one exception.
+	-auroraux)
+		os=-auroraux
+		;;
+	-solaris1 | -solaris1.*)
+		os=`echo $os | sed -e 's|solaris1|sunos4|'`
+		;;
+	-solaris)
+		os=-solaris2
+		;;
+	-svr4*)
+		os=-sysv4
+		;;
+	-unixware*)
+		os=-sysv4.2uw
+		;;
+	-gnu/linux*)
+		os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+		;;
+	# First accept the basic system types.
+	# The portable systems comes first.
+	# Each alternative MUST END IN A *, to match a version number.
+	# -sysv* is not here because it comes later, after sysvr4.
+	-gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+	      | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\
+	      | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
+	      | -sym* | -kopensolaris* | -plan9* \
+	      | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+	      | -aos* | -aros* | -cloudabi* | -sortix* \
+	      | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+	      | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+	      | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
+	      | -bitrig* | -openbsd* | -solidbsd* \
+	      | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
+	      | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+	      | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+	      | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+	      | -chorusos* | -chorusrdb* | -cegcc* \
+	      | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+	      | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+	      | -linux-newlib* | -linux-musl* | -linux-uclibc* \
+	      | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
+	      | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
+	      | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+	      | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+	      | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
+	      | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
+	      | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
+	      | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
+	# Remember, each alternative MUST END IN *, to match a version number.
+		;;
+	-qnx*)
+		case $basic_machine in
+		    x86-* | i*86-*)
+			;;
+		    *)
+			os=-nto$os
+			;;
+		esac
+		;;
+	-nto-qnx*)
+		;;
+	-nto*)
+		os=`echo $os | sed -e 's|nto|nto-qnx|'`
+		;;
+	-sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+	      | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \
+	      | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+		;;
+	-mac*)
+		os=`echo $os | sed -e 's|mac|macos|'`
+		;;
+	-linux-dietlibc)
+		os=-linux-dietlibc
+		;;
+	-linux*)
+		os=`echo $os | sed -e 's|linux|linux-gnu|'`
+		;;
+	-sunos5*)
+		os=`echo $os | sed -e 's|sunos5|solaris2|'`
+		;;
+	-sunos6*)
+		os=`echo $os | sed -e 's|sunos6|solaris3|'`
+		;;
+	-opened*)
+		os=-openedition
+		;;
+	-os400*)
+		os=-os400
+		;;
+	-wince*)
+		os=-wince
+		;;
+	-osfrose*)
+		os=-osfrose
+		;;
+	-osf*)
+		os=-osf
+		;;
+	-utek*)
+		os=-bsd
+		;;
+	-dynix*)
+		os=-bsd
+		;;
+	-acis*)
+		os=-aos
+		;;
+	-atheos*)
+		os=-atheos
+		;;
+	-syllable*)
+		os=-syllable
+		;;
+	-386bsd)
+		os=-bsd
+		;;
+	-ctix* | -uts*)
+		os=-sysv
+		;;
+	-nova*)
+		os=-rtmk-nova
+		;;
+	-ns2 )
+		os=-nextstep2
+		;;
+	-nsk*)
+		os=-nsk
+		;;
+	# Preserve the version number of sinix5.
+	-sinix5.*)
+		os=`echo $os | sed -e 's|sinix|sysv|'`
+		;;
+	-sinix*)
+		os=-sysv4
+		;;
+	-tpf*)
+		os=-tpf
+		;;
+	-triton*)
+		os=-sysv3
+		;;
+	-oss*)
+		os=-sysv3
+		;;
+	-svr4)
+		os=-sysv4
+		;;
+	-svr3)
+		os=-sysv3
+		;;
+	-sysvr4)
+		os=-sysv4
+		;;
+	# This must come after -sysvr4.
+	-sysv*)
+		;;
+	-ose*)
+		os=-ose
+		;;
+	-es1800*)
+		os=-ose
+		;;
+	-xenix)
+		os=-xenix
+		;;
+	-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+		os=-mint
+		;;
+	-aros*)
+		os=-aros
+		;;
+	-zvmoe)
+		os=-zvmoe
+		;;
+	-dicos*)
+		os=-dicos
+		;;
+	-nacl*)
+		;;
+	-none)
+		;;
+	*)
+		# Get rid of the `-' at the beginning of $os.
+		os=`echo $os | sed 's/[^-]*-//'`
+		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+		exit 1
+		;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system.  Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+	score-*)
+		os=-elf
+		;;
+	spu-*)
+		os=-elf
+		;;
+	*-acorn)
+		os=-riscix1.2
+		;;
+	arm*-rebel)
+		os=-linux
+		;;
+	arm*-semi)
+		os=-aout
+		;;
+	c4x-* | tic4x-*)
+		os=-coff
+		;;
+	c8051-*)
+		os=-elf
+		;;
+	hexagon-*)
+		os=-elf
+		;;
+	tic54x-*)
+		os=-coff
+		;;
+	tic55x-*)
+		os=-coff
+		;;
+	tic6x-*)
+		os=-coff
+		;;
+	# This must come before the *-dec entry.
+	pdp10-*)
+		os=-tops20
+		;;
+	pdp11-*)
+		os=-none
+		;;
+	*-dec | vax-*)
+		os=-ultrix4.2
+		;;
+	m68*-apollo)
+		os=-domain
+		;;
+	i386-sun)
+		os=-sunos4.0.2
+		;;
+	m68000-sun)
+		os=-sunos3
+		;;
+	m68*-cisco)
+		os=-aout
+		;;
+	mep-*)
+		os=-elf
+		;;
+	mips*-cisco)
+		os=-elf
+		;;
+	mips*-*)
+		os=-elf
+		;;
+	or32-*)
+		os=-coff
+		;;
+	*-tti)	# must be before sparc entry or we get the wrong os.
+		os=-sysv3
+		;;
+	sparc-* | *-sun)
+		os=-sunos4.1.1
+		;;
+	*-be)
+		os=-beos
+		;;
+	*-haiku)
+		os=-haiku
+		;;
+	*-ibm)
+		os=-aix
+		;;
+	*-knuth)
+		os=-mmixware
+		;;
+	*-wec)
+		os=-proelf
+		;;
+	*-winbond)
+		os=-proelf
+		;;
+	*-oki)
+		os=-proelf
+		;;
+	*-hp)
+		os=-hpux
+		;;
+	*-hitachi)
+		os=-hiux
+		;;
+	i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+		os=-sysv
+		;;
+	*-cbm)
+		os=-amigaos
+		;;
+	*-dg)
+		os=-dgux
+		;;
+	*-dolphin)
+		os=-sysv3
+		;;
+	m68k-ccur)
+		os=-rtu
+		;;
+	m88k-omron*)
+		os=-luna
+		;;
+	*-next )
+		os=-nextstep
+		;;
+	*-sequent)
+		os=-ptx
+		;;
+	*-crds)
+		os=-unos
+		;;
+	*-ns)
+		os=-genix
+		;;
+	i370-*)
+		os=-mvs
+		;;
+	*-next)
+		os=-nextstep3
+		;;
+	*-gould)
+		os=-sysv
+		;;
+	*-highlevel)
+		os=-bsd
+		;;
+	*-encore)
+		os=-bsd
+		;;
+	*-sgi)
+		os=-irix
+		;;
+	*-siemens)
+		os=-sysv4
+		;;
+	*-masscomp)
+		os=-rtu
+		;;
+	f30[01]-fujitsu | f700-fujitsu)
+		os=-uxpv
+		;;
+	*-rom68k)
+		os=-coff
+		;;
+	*-*bug)
+		os=-coff
+		;;
+	*-apple)
+		os=-macos
+		;;
+	*-atari*)
+		os=-mint
+		;;
+	*)
+		os=-none
+		;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer.  We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+	*-unknown)
+		case $os in
+			-riscix*)
+				vendor=acorn
+				;;
+			-sunos*)
+				vendor=sun
+				;;
+			-cnk*|-aix*)
+				vendor=ibm
+				;;
+			-beos*)
+				vendor=be
+				;;
+			-hpux*)
+				vendor=hp
+				;;
+			-mpeix*)
+				vendor=hp
+				;;
+			-hiux*)
+				vendor=hitachi
+				;;
+			-unos*)
+				vendor=crds
+				;;
+			-dgux*)
+				vendor=dg
+				;;
+			-luna*)
+				vendor=omron
+				;;
+			-genix*)
+				vendor=ns
+				;;
+			-mvs* | -opened*)
+				vendor=ibm
+				;;
+			-os400*)
+				vendor=ibm
+				;;
+			-ptx*)
+				vendor=sequent
+				;;
+			-tpf*)
+				vendor=ibm
+				;;
+			-vxsim* | -vxworks* | -windiss*)
+				vendor=wrs
+				;;
+			-aux*)
+				vendor=apple
+				;;
+			-hms*)
+				vendor=hitachi
+				;;
+			-mpw* | -macos*)
+				vendor=apple
+				;;
+			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+				vendor=atari
+				;;
+			-vos*)
+				vendor=stratus
+				;;
+		esac
+		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+		;;
+esac
+
+echo $basic_machine$os
+exit
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/src/build/autoconf/install-sh b/src/build/autoconf/install-sh
new file mode 100755
index 0000000..377bb86
--- /dev/null
+++ b/src/build/autoconf/install-sh
@@ -0,0 +1,527 @@
+#!/bin/sh
+# install - install a program, script, or datafile
+
+scriptversion=2011-11-20.07; # UTC
+
+# This originates from X11R5 (mit/util/scripts/install.sh), which was
+# later released in X11R6 (xc/config/util/install.sh) with the
+# following copyright and license.
+#
+# Copyright (C) 1994 X Consortium
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to
+# deal in the Software without restriction, including without limitation the
+# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+# sell copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
+# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
+# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+# Except as contained in this notice, the name of the X Consortium shall not
+# be used in advertising or otherwise to promote the sale, use or other deal-
+# ings in this Software without prior written authorization from the X Consor-
+# tium.
+#
+#
+# FSF changes to this file are in the public domain.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# 'make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.
+
+nl='
+'
+IFS=" ""	$nl"
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit=${DOITPROG-}
+if test -z "$doit"; then
+  doit_exec=exec
+else
+  doit_exec=$doit
+fi
+
+# Put in absolute file names if you don't have them in your path;
+# or use environment vars.
+
+chgrpprog=${CHGRPPROG-chgrp}
+chmodprog=${CHMODPROG-chmod}
+chownprog=${CHOWNPROG-chown}
+cmpprog=${CMPPROG-cmp}
+cpprog=${CPPROG-cp}
+mkdirprog=${MKDIRPROG-mkdir}
+mvprog=${MVPROG-mv}
+rmprog=${RMPROG-rm}
+stripprog=${STRIPPROG-strip}
+
+posix_glob='?'
+initialize_posix_glob='
+  test "$posix_glob" != "?" || {
+    if (set -f) 2>/dev/null; then
+      posix_glob=
+    else
+      posix_glob=:
+    fi
+  }
+'
+
+posix_mkdir=
+
+# Desired mode of installed file.
+mode=0755
+
+chgrpcmd=
+chmodcmd=$chmodprog
+chowncmd=
+mvcmd=$mvprog
+rmcmd="$rmprog -f"
+stripcmd=
+
+src=
+dst=
+dir_arg=
+dst_arg=
+
+copy_on_change=false
+no_target_directory=
+
+usage="\
+Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
+   or: $0 [OPTION]... SRCFILES... DIRECTORY
+   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
+   or: $0 [OPTION]... -d DIRECTORIES...
+
+In the 1st form, copy SRCFILE to DSTFILE.
+In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
+In the 4th, create DIRECTORIES.
+
+Options:
+     --help     display this help and exit.
+     --version  display version info and exit.
+
+  -c            (ignored)
+  -C            install only if different (preserve the last data modification time)
+  -d            create directories instead of installing files.
+  -g GROUP      $chgrpprog installed files to GROUP.
+  -m MODE       $chmodprog installed files to MODE.
+  -o USER       $chownprog installed files to USER.
+  -s            $stripprog installed files.
+  -t DIRECTORY  install into DIRECTORY.
+  -T            report an error if DSTFILE is a directory.
+
+Environment variables override the default commands:
+  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
+  RMPROG STRIPPROG
+"
+
+while test $# -ne 0; do
+  case $1 in
+    -c) ;;
+
+    -C) copy_on_change=true;;
+
+    -d) dir_arg=true;;
+
+    -g) chgrpcmd="$chgrpprog $2"
+	shift;;
+
+    --help) echo "$usage"; exit $?;;
+
+    -m) mode=$2
+	case $mode in
+	  *' '* | *'	'* | *'
+'*	  | *'*'* | *'?'* | *'['*)
+	    echo "$0: invalid mode: $mode" >&2
+	    exit 1;;
+	esac
+	shift;;
+
+    -o) chowncmd="$chownprog $2"
+	shift;;
+
+    -s) stripcmd=$stripprog;;
+
+    -t) dst_arg=$2
+	# Protect names problematic for 'test' and other utilities.
+	case $dst_arg in
+	  -* | [=\(\)!]) dst_arg=./$dst_arg;;
+	esac
+	shift;;
+
+    -T) no_target_directory=true;;
+
+    --version) echo "$0 $scriptversion"; exit $?;;
+
+    --)	shift
+	break;;
+
+    -*)	echo "$0: invalid option: $1" >&2
+	exit 1;;
+
+    *)  break;;
+  esac
+  shift
+done
+
+if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
+  # When -d is used, all remaining arguments are directories to create.
+  # When -t is used, the destination is already specified.
+  # Otherwise, the last argument is the destination.  Remove it from $@.
+  for arg
+  do
+    if test -n "$dst_arg"; then
+      # $@ is not empty: it contains at least $arg.
+      set fnord "$@" "$dst_arg"
+      shift # fnord
+    fi
+    shift # arg
+    dst_arg=$arg
+    # Protect names problematic for 'test' and other utilities.
+    case $dst_arg in
+      -* | [=\(\)!]) dst_arg=./$dst_arg;;
+    esac
+  done
+fi
+
+if test $# -eq 0; then
+  if test -z "$dir_arg"; then
+    echo "$0: no input file specified." >&2
+    exit 1
+  fi
+  # It's OK to call 'install-sh -d' without argument.
+  # This can happen when creating conditional directories.
+  exit 0
+fi
+
+if test -z "$dir_arg"; then
+  do_exit='(exit $ret); exit $ret'
+  trap "ret=129; $do_exit" 1
+  trap "ret=130; $do_exit" 2
+  trap "ret=141; $do_exit" 13
+  trap "ret=143; $do_exit" 15
+
+  # Set umask so as not to create temps with too-generous modes.
+  # However, 'strip' requires both read and write access to temps.
+  case $mode in
+    # Optimize common cases.
+    *644) cp_umask=133;;
+    *755) cp_umask=22;;
+
+    *[0-7])
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw='% 200'
+      fi
+      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
+    *)
+      if test -z "$stripcmd"; then
+	u_plus_rw=
+      else
+	u_plus_rw=,u+rw
+      fi
+      cp_umask=$mode$u_plus_rw;;
+  esac
+fi
+
+for src
+do
+  # Protect names problematic for 'test' and other utilities.
+  case $src in
+    -* | [=\(\)!]) src=./$src;;
+  esac
+
+  if test -n "$dir_arg"; then
+    dst=$src
+    dstdir=$dst
+    test -d "$dstdir"
+    dstdir_status=$?
+  else
+
+    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
+    # might cause directories to be created, which would be especially bad
+    # if $src (and thus $dsttmp) contains '*'.
+    if test ! -f "$src" && test ! -d "$src"; then
+      echo "$0: $src does not exist." >&2
+      exit 1
+    fi
+
+    if test -z "$dst_arg"; then
+      echo "$0: no destination specified." >&2
+      exit 1
+    fi
+    dst=$dst_arg
+
+    # If destination is a directory, append the input filename; won't work
+    # if double slashes aren't ignored.
+    if test -d "$dst"; then
+      if test -n "$no_target_directory"; then
+	echo "$0: $dst_arg: Is a directory" >&2
+	exit 1
+      fi
+      dstdir=$dst
+      dst=$dstdir/`basename "$src"`
+      dstdir_status=0
+    else
+      # Prefer dirname, but fall back on a substitute if dirname fails.
+      dstdir=`
+	(dirname "$dst") 2>/dev/null ||
+	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+	     X"$dst" : 'X\(//\)[^/]' \| \
+	     X"$dst" : 'X\(//\)$' \| \
+	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
+	echo X"$dst" |
+	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)[^/].*/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\/\)$/{
+		   s//\1/
+		   q
+		 }
+		 /^X\(\/\).*/{
+		   s//\1/
+		   q
+		 }
+		 s/.*/./; q'
+      `
+
+      test -d "$dstdir"
+      dstdir_status=$?
+    fi
+  fi
+
+  obsolete_mkdir_used=false
+
+  if test $dstdir_status != 0; then
+    case $posix_mkdir in
+      '')
+	# Create intermediate dirs using mode 755 as modified by the umask.
+	# This is like FreeBSD 'install' as of 1997-10-28.
+	umask=`umask`
+	case $stripcmd.$umask in
+	  # Optimize common cases.
+	  *[2367][2367]) mkdir_umask=$umask;;
+	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
+
+	  *[0-7])
+	    mkdir_umask=`expr $umask + 22 \
+	      - $umask % 100 % 40 + $umask % 20 \
+	      - $umask % 10 % 4 + $umask % 2
+	    `;;
+	  *) mkdir_umask=$umask,go-w;;
+	esac
+
+	# With -d, create the new directory with the user-specified mode.
+	# Otherwise, rely on $mkdir_umask.
+	if test -n "$dir_arg"; then
+	  mkdir_mode=-m$mode
+	else
+	  mkdir_mode=
+	fi
+
+	posix_mkdir=false
+	case $umask in
+	  *[123567][0-7][0-7])
+	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
+	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
+	    ;;
+	  *)
+	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
+	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
+
+	    if (umask $mkdir_umask &&
+		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
+	    then
+	      if test -z "$dir_arg" || {
+		   # Check for POSIX incompatibilities with -m.
+		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
+		   # other-writable bit of parent directory when it shouldn't.
+		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
+		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
+		   case $ls_ld_tmpdir in
+		     d????-?r-*) different_mode=700;;
+		     d????-?--*) different_mode=755;;
+		     *) false;;
+		   esac &&
+		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
+		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
+		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
+		   }
+		 }
+	      then posix_mkdir=:
+	      fi
+	      rmdir "$tmpdir/d" "$tmpdir"
+	    else
+	      # Remove any dirs left behind by ancient mkdir implementations.
+	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
+	    fi
+	    trap '' 0;;
+	esac;;
+    esac
+
+    if
+      $posix_mkdir && (
+	umask $mkdir_umask &&
+	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
+      )
+    then :
+    else
+
+      # The umask is ridiculous, or mkdir does not conform to POSIX,
+      # or it failed possibly due to a race condition.  Create the
+      # directory the slow way, step by step, checking for races as we go.
+
+      case $dstdir in
+	/*) prefix='/';;
+	[-=\(\)!]*) prefix='./';;
+	*)  prefix='';;
+      esac
+
+      eval "$initialize_posix_glob"
+
+      oIFS=$IFS
+      IFS=/
+      $posix_glob set -f
+      set fnord $dstdir
+      shift
+      $posix_glob set +f
+      IFS=$oIFS
+
+      prefixes=
+
+      for d
+      do
+	test X"$d" = X && continue
+
+	prefix=$prefix$d
+	if test -d "$prefix"; then
+	  prefixes=
+	else
+	  if $posix_mkdir; then
+	    (umask=$mkdir_umask &&
+	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
+	    # Don't fail if two instances are running concurrently.
+	    test -d "$prefix" || exit 1
+	  else
+	    case $prefix in
+	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
+	      *) qprefix=$prefix;;
+	    esac
+	    prefixes="$prefixes '$qprefix'"
+	  fi
+	fi
+	prefix=$prefix/
+      done
+
+      if test -n "$prefixes"; then
+	# Don't fail if two instances are running concurrently.
+	(umask $mkdir_umask &&
+	 eval "\$doit_exec \$mkdirprog $prefixes") ||
+	  test -d "$dstdir" || exit 1
+	obsolete_mkdir_used=true
+      fi
+    fi
+  fi
+
+  if test -n "$dir_arg"; then
+    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
+    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
+      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
+  else
+
+    # Make a couple of temp file names in the proper directory.
+    dsttmp=$dstdir/_inst.$$_
+    rmtmp=$dstdir/_rm.$$_
+
+    # Trap to clean up those temp files at exit.
+    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
+
+    # Copy the file name to the temp name.
+    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
+
+    # and set any options; do chmod last to preserve setuid bits.
+    #
+    # If any of these fail, we abort the whole thing.  If we want to
+    # ignore errors from any of these, just make sure not to ignore
+    # errors from the above "$doit $cpprog $src $dsttmp" command.
+    #
+    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
+    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
+    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
+    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
+
+    # If -C, don't bother to copy if it wouldn't change the file.
+    if $copy_on_change &&
+       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
+       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
+
+       eval "$initialize_posix_glob" &&
+       $posix_glob set -f &&
+       set X $old && old=:$2:$4:$5:$6 &&
+       set X $new && new=:$2:$4:$5:$6 &&
+       $posix_glob set +f &&
+
+       test "$old" = "$new" &&
+       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
+    then
+      rm -f "$dsttmp"
+    else
+      # Rename the file to the real destination.
+      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
+
+      # The rename failed, perhaps because mv can't rename something else
+      # to itself, or perhaps because mv is so ancient that it does not
+      # support -f.
+      {
+	# Now remove or move aside any old file at destination location.
+	# We try this two ways since rm can't unlink itself on some
+	# systems and the destination file might be busy for other
+	# reasons.  In this case, the final cleanup might fail but the new
+	# file should still install successfully.
+	{
+	  test ! -f "$dst" ||
+	  $doit $rmcmd -f "$dst" 2>/dev/null ||
+	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
+	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
+	  } ||
+	  { echo "$0: cannot unlink or rename $dst" >&2
+	    (exit 1); exit 1
+	  }
+	} &&
+
+	# Now rename the file to the real destination.
+	$doit $mvcmd "$dsttmp" "$dst"
+      }
+    fi || exit 1
+
+    trap '' 0
+  fi
+done
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "scriptversion="
+# time-stamp-format: "%:y-%02m-%02d.%02H"
+# time-stamp-time-zone: "UTC"
+# time-stamp-end: "; # UTC"
+# End:
diff --git a/src/callbacks.cpp b/src/callbacks.cpp
new file mode 100644
index 0000000..0cdecfe
--- /dev/null
+++ b/src/callbacks.cpp
@@ -0,0 +1,154 @@
+#include "api.h"
+#include "rglview.h"
+
+#include "DeviceManager.h"
+
+using namespace rgl;
+
+namespace rgl {
+extern DeviceManager* deviceManager;
+}
+
+/* These defines are not in the installed version of R */
+#include "R.h"
+
+#include <Rdefines.h>
+#include <Rinternals.h>
+
+static void userControl(void *userData, int mouseX, int mouseY)
+{
+  SEXP fn = (SEXP)userData;
+  eval(lang3(fn, ScalarInteger(mouseX), ScalarInteger(mouseY)), R_GlobalEnv);
+}
+
+static void userControlEnd(void *userData)
+{
+  SEXP fn = (SEXP)userData;
+  eval(lang1(fn), R_GlobalEnv);
+}
+
+static void userCleanup(void **userData)
+{
+  for (int i=0; i<3; i++) {
+    if (userData[i]) {
+      R_ReleaseObject((SEXP)userData[i]);
+      userData[i] = 0;
+    }
+  }
+}
+
+static void userWheel(void *wheelData, int dir)
+{
+  SEXP fn = (SEXP)wheelData;
+  eval(lang2(fn, ScalarInteger(dir)), R_GlobalEnv);
+}
+
+SEXP rgl::rgl_setMouseCallbacks(SEXP button, SEXP begin, SEXP update, SEXP end)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    void* userData[3] = {0, 0, 0};
+    userControlPtr beginCallback, updateCallback;
+    userControlEndPtr endCallback;
+    userCleanupPtr cleanupCallback;
+    
+    int b = asInteger(button);
+    if (b < 1 || b > 3) error("button must be 1, 2 or 3");
+    
+    rglview->getMouseCallbacks(b, &beginCallback, &updateCallback, &endCallback, 
+                               &cleanupCallback, (void**)&userData);
+    if (isFunction(begin)) {
+      beginCallback = &userControl;
+      userData[0] = (void*)begin;
+      R_PreserveObject(begin);
+    } else if (begin == R_NilValue) beginCallback = 0;
+    else error("callback must be a function");
+    
+    if (isFunction(update)) {
+      updateCallback = &userControl;
+      userData[1] = (void*)update;
+      R_PreserveObject(update);
+    } else if (update == R_NilValue) updateCallback = 0;
+    else error("callback must be a function");
+    
+    if (isFunction(end)) {
+      endCallback = &userControlEnd;
+      userData[2] = (void*)end;
+      R_PreserveObject(end);
+    } else if (end == R_NilValue) endCallback = 0;
+    else error("callback must be a function");
+    
+    rglview->setMouseCallbacks(b, beginCallback, updateCallback, endCallback, 
+                               &userCleanup, userData);
+  } else error("no rgl device is open");
+  return R_NilValue;
+}      
+
+SEXP rgl::rgl_getMouseCallbacks(SEXP button)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    void* userData[3] = {0, 0, 0};
+    userControlPtr beginCallback, updateCallback;
+    userControlEndPtr endCallback;
+    userCleanupPtr cleanupCallback;
+    
+    int b = asInteger(button);
+    if (b < 1 || b > 3) error("button must be 1, 2 or 3");
+    
+    rglview->getMouseCallbacks(b, &beginCallback, &updateCallback, &endCallback, 
+                               &cleanupCallback, (void**)&userData);
+    SEXP result;
+    PROTECT(result = allocVector(VECSXP, 3));
+    
+    if (beginCallback == &userControl) 
+      SET_VECTOR_ELT(result, 0, (SEXP)userData[0]);
+    
+    if (updateCallback == &userControl) 
+      SET_VECTOR_ELT(result, 1, (SEXP)userData[1]);
+    
+    if (endCallback == &userControlEnd)
+      SET_VECTOR_ELT(result, 2, (SEXP)userData[2]);
+
+    UNPROTECT(1);
+    return result;
+  } else error("no rgl device is open");
+  return R_NilValue;
+}      
+ 
+SEXP rgl::rgl_setWheelCallback(SEXP rotate)
+{
+  Device* device;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    void* wheelData = 0;
+    userWheelPtr wheelCallback;
+      
+    if (isFunction(rotate)) {
+      wheelCallback = &userWheel;
+      wheelData = (void*)rotate;
+      R_PreserveObject(rotate);
+    } else if (rotate == R_NilValue) wheelCallback = 0;
+    else error("callback must be a function");
+    
+    rglview->setWheelCallback(wheelCallback, wheelData);
+  } else error("no rgl device is open");
+  return R_NilValue;
+}
+
+SEXP rgl::rgl_getWheelCallback()
+{
+  Device* device;
+  SEXP result = R_NilValue;
+  if (deviceManager && (device = deviceManager->getCurrentDevice())) {
+    RGLView* rglview = device->getRGLView();
+    void* wheelData = 0;
+    userWheelPtr wheelCallback;
+    rglview->getWheelCallback(&wheelCallback, (void**)&wheelData);
+    if (wheelCallback == &userWheel)
+      result = (SEXP)wheelData;
+  } else error("no rgl device is open");
+  return result;
+}      
diff --git a/src/config.h b/src/config.h
new file mode 100644
index 0000000..6577612
--- /dev/null
+++ b/src/config.h
@@ -0,0 +1,18 @@
+#ifndef RGL_CONFIG_H
+#define RGL_CONFIG_H
+// ---------------------------------------------------------------------------
+// Platform detection
+// ---------------------------------------------------------------------------
+#if defined(__APPLE__)
+# define RGL_OSX 1
+# define RGL_X11 1
+#else
+# if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
+#  define RGL_W32 1
+# else
+#  define RGL_X11 1
+# endif
+#endif
+// ---------------------------------------------------------------------------
+#endif //RGL_CONFIG_H
+
diff --git a/src/device.cpp b/src/device.cpp
new file mode 100644
index 0000000..b0428e9
--- /dev/null
+++ b/src/device.cpp
@@ -0,0 +1,154 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: device.cpp 1436 2016-01-01 15:18:43Z murdoch $
+// ---------------------------------------------------------------------------
+#include <cstring>
+#include "Device.h"
+#include "lib.h"
+
+using namespace rgl;
+
+// ---------------------------------------------------------------------------
+Device::Device(int id, bool useNULL) : id_(id)
+{
+  scene   = new Scene();
+  rglview = new RGLView(scene);
+  window  = new Window( rglview, getGUIFactory(useNULL) );
+  devtype = GUIFactoryName(useNULL);
+  window->addDisposeListener(this);
+}
+// ---------------------------------------------------------------------------
+Device::~Device()
+{
+  delete scene;
+}
+// ---------------------------------------------------------------------------
+int  Device::getID() 
+{
+  return id_;
+}
+// ---------------------------------------------------------------------------
+void Device::notifyDisposed(Disposable* disposable)
+{
+  dispose();
+}
+// ---------------------------------------------------------------------------
+void Device::setName(const char* string)
+{
+  window->setTitle(string);
+}
+// ---------------------------------------------------------------------------
+void Device::update()
+{
+//  window->update();
+}
+// ---------------------------------------------------------------------------
+bool Device::open(void)
+{
+  window->setVisibility(true);
+  return true;
+}
+// ---------------------------------------------------------------------------
+void Device::close(void)
+{
+  window->on_close(); 
+}
+// ---------------------------------------------------------------------------
+
+void Device::bringToTop(int stay)
+{
+  window->bringToTop(stay);
+}
+
+void Device::setWindowRect(int left, int top, int right, int bottom)
+{
+  window->setWindowRect(left, top, right, bottom);
+}
+
+void Device::getWindowRect(int *left, int *top, int *right, int *bottom)
+{
+  window->getWindowRect(left, top, right, bottom);
+}
+
+// ---------------------------------------------------------------------------
+int Device::getIgnoreExtent(void)
+{
+  return scene->getIgnoreExtent();
+}
+// ---------------------------------------------------------------------------
+void Device::setIgnoreExtent(int in_ignoreExtent)
+{
+  scene->setIgnoreExtent(in_ignoreExtent);
+}
+// ---------------------------------------------------------------------------
+int Device::getSkipRedraw(void)
+{
+  return window->getSkipRedraw();
+}
+// ---------------------------------------------------------------------------
+void Device::setSkipRedraw(int in_skipRedraw)
+{
+  window->setSkipRedraw(in_skipRedraw);
+}
+// ---------------------------------------------------------------------------
+bool Device::clear(TypeID stackTypeID)
+{
+  bool success;
+  success = scene->clear(stackTypeID);
+  rglview->update();
+  return success;
+}
+// ---------------------------------------------------------------------------
+int Device::add(SceneNode* node)
+{
+  bool success;
+  success = scene->add(node);
+  rglview->update();
+  if (success) return node->getObjID();
+  else return 0;
+}
+// ---------------------------------------------------------------------------
+
+bool Device::pop(TypeID stackTypeID, int id)
+{
+  bool success;
+  bool inGL = rglview->windowImpl->beginGL(); // May need to set context for display lists.
+  success = scene->pop(stackTypeID, id);
+  if (inGL) {
+    rglview->windowImpl->endGL();
+  }
+  rglview->update();
+  return success;
+}
+// ---------------------------------------------------------------------------
+bool Device::snapshot(int format, const char* filename)
+{
+  return rglview->snapshot( (PixmapFileFormatID) format, filename);
+}
+// ---------------------------------------------------------------------------
+bool Device::pixels(int* ll, int* size, int component, double* result)
+{
+  return rglview->pixels( ll, size, component, result);
+}
+// ---------------------------------------------------------------------------
+RGLView* Device::getRGLView(void)
+{
+  return rglview;
+}
+// ---------------------------------------------------------------------------
+bool Device::postscript(int format, const char* filename, bool drawText)
+{
+  return rglview->postscript( format, filename, drawText);
+}
+// ---------------------------------------------------------------------------
+void Device::getFonts(FontArray& outfonts, int nfonts, char** family, int* style, double* cex, 
+                      bool useFreeType)
+{
+  window->getFonts(outfonts, nfonts, family, style, cex, useFreeType);
+}
+// ---------------------------------------------------------------------------
+const char * Device::getDevtype()
+{
+  return devtype;
+}
diff --git a/src/devicemanager.cpp b/src/devicemanager.cpp
new file mode 100644
index 0000000..8d4eec5
--- /dev/null
+++ b/src/devicemanager.cpp
@@ -0,0 +1,165 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: devicemanager.cpp 1115 2014-07-18 13:51:22Z murdoch $
+
+#include <algorithm>
+#include <cstdio>
+#include "DeviceManager.h"
+#include "types.h"
+#include "assert.h"
+#include "lib.h"
+
+using namespace rgl;
+
+DeviceManager::DeviceManager(bool in_useNULLDevice) 
+ : newID(1), devices(), current( devices.end() ), useNULLDevice(in_useNULLDevice)
+{ }
+
+DeviceManager::~DeviceManager()
+{
+  std::vector<Device*> disposeList;
+  {
+    for( Container::const_iterator i = devices.begin(), end = devices.end() ;  i!=end ; ++i ) {
+      disposeList.push_back(*i);
+    }
+  }
+  // disploseList. devices.begin(), devices.end() );
+  for (std::vector<Device*>::iterator i = disposeList.begin(); i != disposeList.end() ; ++ i ) {
+    // remove manager from listeners    
+    (*i)->removeDisposeListener(this);
+    // close device
+    (*i)->close();
+  }
+}
+
+bool DeviceManager::openDevice(bool useNULL) 
+{
+  Device* pDevice = new Device(newID, useNULL);  
+  if ( pDevice->open() ) {
+    ++newID;
+    pDevice->addDisposeListener(this);
+    devices.insert( devices.end(), pDevice );
+    setCurrent( pDevice->getID() );
+    return true;
+  } else {
+    delete pDevice;
+    return false;
+  }
+}
+
+Device* DeviceManager::getCurrentDevice()
+{
+  if ( current != devices.end() )
+    return *current;
+  else
+    return NULL;
+}
+
+Device* DeviceManager::getAnyDevice()
+{
+  Device* pDevice = getCurrentDevice();
+  if (pDevice == NULL) {
+    openDevice(useNULLDevice);
+    pDevice = getCurrentDevice();
+  }
+  return pDevice;
+}
+
+Device* DeviceManager::getDevice(int id)
+{
+  for (Container::iterator i = devices.begin() ; i != devices.end() ; ++i ) {
+    if ( (*i)->getID() == id )
+      return *i;
+  }
+  return NULL;
+}
+
+bool DeviceManager::setCurrent(int id, bool silent)
+{
+  char buffer[64];
+  
+  Container::iterator i;
+  for (i = devices.begin() ; i != devices.end() ; ++ i ) {
+    if ( (*i)->getID() == id )
+      break; 
+  }
+  if ( i != devices.end() ) {
+    if ( !silent && current != devices.end() ) {
+      sprintf(buffer, "RGL device %d", (*current)->getID() );    
+      (*current)->setName(buffer);
+    }
+    current = i;
+    if ( !silent ) {
+      sprintf(buffer, "RGL device %d [Focus]", (*current)->getID() );    
+      (*current)->setName(buffer);
+    }
+    return true;
+  } else
+    return false;
+}
+
+int DeviceManager::getCurrent() {
+  if ( current != devices.end() )
+    return (*current)->getID();
+  else
+    return 0;
+}
+
+int DeviceManager::getDeviceCount() {
+  int result = 0;
+  for (Container::iterator i = devices.begin(); i != devices.end() ; ++i, ++result);
+  return result;
+}
+
+void DeviceManager::getDeviceIds(int *buffer, int bufsize) {
+  int count = 0;
+  for (Container::iterator i = devices.begin(); i != devices.end() && count < bufsize; ++i, ++count) {
+    *(buffer++) = (*i)->getID();
+  }
+}
+
+/**
+ * Device disposed handler
+ **/
+void DeviceManager::notifyDisposed(Disposable* disposed)
+{
+  Container::iterator pos = std::find( devices.begin(), devices.end(), static_cast<Device*>( disposed ) );
+  assert( pos != devices.end() );  
+  if ( pos == current ) {
+    if ( devices.size() == 1 )
+      current = devices.end();
+    else
+      nextDevice();
+  }  
+  devices.erase(pos);  
+}
+
+void DeviceManager::nextDevice()
+{
+  if ( current != devices.end() ) {
+    // cycle to next
+    Iterator next = ++current;
+    if ( next == devices.end() )
+      next = devices.begin();
+    setCurrent( (*next)->getID() );
+  } else {
+    // ignore: no devices    
+  }
+}
+
+void DeviceManager::previousDevice()
+{
+  if ( current != devices.end() ) {
+    // cycle to previous
+    Iterator prev = current;
+    if (prev == devices.begin() )
+      prev = devices.end();
+    --prev;
+    setCurrent( (*prev)->getID() );
+  } else {
+    // ignore: no devices
+  }
+}
+
+
diff --git a/src/ext/GLsdk/GL/gl.h b/src/ext/GLsdk/GL/gl.h
new file mode 100644
index 0000000..54049bd
--- /dev/null
+++ b/src/ext/GLsdk/GL/gl.h
@@ -0,0 +1,1914 @@
+#ifndef __gl_h_
+#define __gl_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** The contents of this file are subject to the GLX Public License Version 1.0
+** (the "License"). You may not use this file except in compliance with the
+** License. You may obtain a copy of the License at Silicon Graphics, Inc.,
+** attn: Legal Services, 2011 N. Shoreline Blvd., Mountain View, CA 94043
+** or at http://www.sgi.com/software/opensource/glx/license.html.
+** 
+** Software distributed under the License is distributed on an "AS IS"
+** basis. ALL WARRANTIES ARE DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY
+** IMPLIED WARRANTIES OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR
+** PURPOSE OR OF NON- INFRINGEMENT. See the License for the specific
+** language governing rights and limitations under the License.
+** 
+** The Original Software is GLX version 1.2 source code, released February,
+** 1999. The developer of the Original Software is Silicon Graphics, Inc.
+** Those portions of the Subject Software created by Silicon Graphics, Inc.
+** are Copyright (c) 1991-9 Silicon Graphics, Inc. All Rights Reserved.
+*/
+
+#ifndef _WIN32
+#define WINGDIAPI
+#define APIENTRY
+#endif
+
+typedef unsigned int GLenum;
+typedef unsigned char GLboolean;
+typedef unsigned int GLbitfield;
+typedef signed char GLbyte;
+typedef short GLshort;
+typedef int GLint;
+typedef int GLsizei;
+typedef unsigned char GLubyte;
+typedef unsigned short GLushort;
+typedef unsigned int GLuint;
+typedef float GLfloat;
+typedef float GLclampf;
+typedef double GLdouble;
+typedef double GLclampd;
+typedef void GLvoid;
+
+/*************************************************************/
+
+/* Version */
+#define GL_VERSION_1_1                    1
+#define GL_VERSION_1_2                    1
+
+/* Extensions */
+#define GL_ARB_imaging                    1
+#define GL_ARB_multitexture               1
+
+/* AccumOp */
+#define GL_ACCUM                          0x0100
+#define GL_LOAD                           0x0101
+#define GL_RETURN                         0x0102
+#define GL_MULT                           0x0103
+#define GL_ADD                            0x0104
+
+/* AlphaFunction */
+#define GL_NEVER                          0x0200
+#define GL_LESS                           0x0201
+#define GL_EQUAL                          0x0202
+#define GL_LEQUAL                         0x0203
+#define GL_GREATER                        0x0204
+#define GL_NOTEQUAL                       0x0205
+#define GL_GEQUAL                         0x0206
+#define GL_ALWAYS                         0x0207
+
+/* AttribMask */
+#define GL_CURRENT_BIT                    0x00000001
+#define GL_POINT_BIT                      0x00000002
+#define GL_LINE_BIT                       0x00000004
+#define GL_POLYGON_BIT                    0x00000008
+#define GL_POLYGON_STIPPLE_BIT            0x00000010
+#define GL_PIXEL_MODE_BIT                 0x00000020
+#define GL_LIGHTING_BIT                   0x00000040
+#define GL_FOG_BIT                        0x00000080
+#define GL_DEPTH_BUFFER_BIT               0x00000100
+#define GL_ACCUM_BUFFER_BIT               0x00000200
+#define GL_STENCIL_BUFFER_BIT             0x00000400
+#define GL_VIEWPORT_BIT                   0x00000800
+#define GL_TRANSFORM_BIT                  0x00001000
+#define GL_ENABLE_BIT                     0x00002000
+#define GL_COLOR_BUFFER_BIT               0x00004000
+#define GL_HINT_BIT                       0x00008000
+#define GL_EVAL_BIT                       0x00010000
+#define GL_LIST_BIT                       0x00020000
+#define GL_TEXTURE_BIT                    0x00040000
+#define GL_SCISSOR_BIT                    0x00080000
+#define GL_ALL_ATTRIB_BITS                0x000fffff
+
+/* BeginMode */
+#define GL_POINTS                         0x0000
+#define GL_LINES                          0x0001
+#define GL_LINE_LOOP                      0x0002
+#define GL_LINE_STRIP                     0x0003
+#define GL_TRIANGLES                      0x0004
+#define GL_TRIANGLE_STRIP                 0x0005
+#define GL_TRIANGLE_FAN                   0x0006
+#define GL_QUADS                          0x0007
+#define GL_QUAD_STRIP                     0x0008
+#define GL_POLYGON                        0x0009
+
+/* BlendEquationMode */
+/*      GL_LOGIC_OP */
+/*      GL_FUNC_ADD */
+/*      GL_MIN */
+/*      GL_MAX */
+/*      GL_FUNC_SUBTRACT */
+/*      GL_FUNC_REVERSE_SUBTRACT */
+
+/* BlendingFactorDest */
+#define GL_ZERO                           0
+#define GL_ONE                            1
+#define GL_SRC_COLOR                      0x0300
+#define GL_ONE_MINUS_SRC_COLOR            0x0301
+#define GL_SRC_ALPHA                      0x0302
+#define GL_ONE_MINUS_SRC_ALPHA            0x0303
+#define GL_DST_ALPHA                      0x0304
+#define GL_ONE_MINUS_DST_ALPHA            0x0305
+/*      GL_CONSTANT_COLOR */
+/*      GL_ONE_MINUS_CONSTANT_COLOR */
+/*      GL_CONSTANT_ALPHA */
+/*      GL_ONE_MINUS_CONSTANT_ALPHA */
+
+/* BlendingFactorSrc */
+/*      GL_ZERO */
+/*      GL_ONE */
+#define GL_DST_COLOR                      0x0306
+#define GL_ONE_MINUS_DST_COLOR            0x0307
+#define GL_SRC_ALPHA_SATURATE             0x0308
+/*      GL_SRC_ALPHA */
+/*      GL_ONE_MINUS_SRC_ALPHA */
+/*      GL_DST_ALPHA */
+/*      GL_ONE_MINUS_DST_ALPHA */
+/*      GL_CONSTANT_COLOR */
+/*      GL_ONE_MINUS_CONSTANT_COLOR */
+/*      GL_CONSTANT_ALPHA */
+/*      GL_ONE_MINUS_CONSTANT_ALPHA */
+
+/* Boolean */
+#define GL_TRUE                           1
+#define GL_FALSE                          0
+
+/* ClearBufferMask */
+/*      GL_COLOR_BUFFER_BIT */
+/*      GL_ACCUM_BUFFER_BIT */
+/*      GL_STENCIL_BUFFER_BIT */
+/*      GL_DEPTH_BUFFER_BIT */
+
+/* ClientArrayType */
+/*      GL_VERTEX_ARRAY */
+/*      GL_NORMAL_ARRAY */
+/*      GL_COLOR_ARRAY */
+/*      GL_INDEX_ARRAY */
+/*      GL_TEXTURE_COORD_ARRAY */
+/*      GL_EDGE_FLAG_ARRAY */
+
+/* ClipPlaneName */
+#define GL_CLIP_PLANE0                    0x3000
+#define GL_CLIP_PLANE1                    0x3001
+#define GL_CLIP_PLANE2                    0x3002
+#define GL_CLIP_PLANE3                    0x3003
+#define GL_CLIP_PLANE4                    0x3004
+#define GL_CLIP_PLANE5                    0x3005
+
+/* ColorMaterialFace */
+/*      GL_FRONT */
+/*      GL_BACK */
+/*      GL_FRONT_AND_BACK */
+
+/* ColorMaterialParameter */
+/*      GL_AMBIENT */
+/*      GL_DIFFUSE */
+/*      GL_SPECULAR */
+/*      GL_EMISSION */
+/*      GL_AMBIENT_AND_DIFFUSE */
+
+/* ColorPointerType */
+/*      GL_BYTE */
+/*      GL_UNSIGNED_BYTE */
+/*      GL_SHORT */
+/*      GL_UNSIGNED_SHORT */
+/*      GL_INT */
+/*      GL_UNSIGNED_INT */
+/*      GL_FLOAT */
+/*      GL_DOUBLE */
+
+/* ColorTableParameterPName */
+/*      GL_COLOR_TABLE_SCALE */
+/*      GL_COLOR_TABLE_BIAS */
+
+/* ColorTableTarget */
+/*      GL_COLOR_TABLE */
+/*      GL_POST_CONVOLUTION_COLOR_TABLE */
+/*      GL_POST_COLOR_MATRIX_COLOR_TABLE */
+/*      GL_PROXY_COLOR_TABLE */
+/*      GL_PROXY_POST_CONVOLUTION_COLOR_TABLE */
+/*      GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE */
+
+/* ConvolutionBorderMode */
+/*      GL_REDUCE */
+/*      GL_IGNORE_BORDER */
+/*      GL_CONSTANT_BORDER */
+
+/* ConvolutionParameter */
+/*      GL_CONVOLUTION_BORDER_MODE */
+/*      GL_CONVOLUTION_FILTER_SCALE */
+/*      GL_CONVOLUTION_FILTER_BIAS */
+
+/* ConvolutionTarget */
+/*      GL_CONVOLUTION_1D */
+/*      GL_CONVOLUTION_2D */
+
+/* CullFaceMode */
+/*      GL_FRONT */
+/*      GL_BACK */
+/*      GL_FRONT_AND_BACK */
+
+/* DataType */
+#define GL_BYTE                           0x1400
+#define GL_UNSIGNED_BYTE                  0x1401
+#define GL_SHORT                          0x1402
+#define GL_UNSIGNED_SHORT                 0x1403
+#define GL_INT                            0x1404
+#define GL_UNSIGNED_INT                   0x1405
+#define GL_FLOAT                          0x1406
+#define GL_2_BYTES                        0x1407
+#define GL_3_BYTES                        0x1408
+#define GL_4_BYTES                        0x1409
+#define GL_DOUBLE                         0x140A
+
+/* DepthFunction */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* DrawBufferMode */
+#define GL_NONE                           0
+#define GL_FRONT_LEFT                     0x0400
+#define GL_FRONT_RIGHT                    0x0401
+#define GL_BACK_LEFT                      0x0402
+#define GL_BACK_RIGHT                     0x0403
+#define GL_FRONT                          0x0404
+#define GL_BACK                           0x0405
+#define GL_LEFT                           0x0406
+#define GL_RIGHT                          0x0407
+#define GL_FRONT_AND_BACK                 0x0408
+#define GL_AUX0                           0x0409
+#define GL_AUX1                           0x040A
+#define GL_AUX2                           0x040B
+#define GL_AUX3                           0x040C
+
+/* Enable */
+/*      GL_FOG */
+/*      GL_LIGHTING */
+/*      GL_TEXTURE_1D */
+/*      GL_TEXTURE_2D */
+/*      GL_LINE_STIPPLE */
+/*      GL_POLYGON_STIPPLE */
+/*      GL_CULL_FACE */
+/*      GL_ALPHA_TEST */
+/*      GL_BLEND */
+/*      GL_INDEX_LOGIC_OP */
+/*      GL_COLOR_LOGIC_OP */
+/*      GL_DITHER */
+/*      GL_STENCIL_TEST */
+/*      GL_DEPTH_TEST */
+/*      GL_CLIP_PLANE0 */
+/*      GL_CLIP_PLANE1 */
+/*      GL_CLIP_PLANE2 */
+/*      GL_CLIP_PLANE3 */
+/*      GL_CLIP_PLANE4 */
+/*      GL_CLIP_PLANE5 */
+/*      GL_LIGHT0 */
+/*      GL_LIGHT1 */
+/*      GL_LIGHT2 */
+/*      GL_LIGHT3 */
+/*      GL_LIGHT4 */
+/*      GL_LIGHT5 */
+/*      GL_LIGHT6 */
+/*      GL_LIGHT7 */
+/*      GL_TEXTURE_GEN_S */
+/*      GL_TEXTURE_GEN_T */
+/*      GL_TEXTURE_GEN_R */
+/*      GL_TEXTURE_GEN_Q */
+/*      GL_MAP1_VERTEX_3 */
+/*      GL_MAP1_VERTEX_4 */
+/*      GL_MAP1_COLOR_4 */
+/*      GL_MAP1_INDEX */
+/*      GL_MAP1_NORMAL */
+/*      GL_MAP1_TEXTURE_COORD_1 */
+/*      GL_MAP1_TEXTURE_COORD_2 */
+/*      GL_MAP1_TEXTURE_COORD_3 */
+/*      GL_MAP1_TEXTURE_COORD_4 */
+/*      GL_MAP2_VERTEX_3 */
+/*      GL_MAP2_VERTEX_4 */
+/*      GL_MAP2_COLOR_4 */
+/*      GL_MAP2_INDEX */
+/*      GL_MAP2_NORMAL */
+/*      GL_MAP2_TEXTURE_COORD_1 */
+/*      GL_MAP2_TEXTURE_COORD_2 */
+/*      GL_MAP2_TEXTURE_COORD_3 */
+/*      GL_MAP2_TEXTURE_COORD_4 */
+/*      GL_POINT_SMOOTH */
+/*      GL_LINE_SMOOTH */
+/*      GL_POLYGON_SMOOTH */
+/*      GL_SCISSOR_TEST */
+/*      GL_COLOR_MATERIAL */
+/*      GL_NORMALIZE */
+/*      GL_AUTO_NORMAL */
+/*      GL_VERTEX_ARRAY */
+/*      GL_NORMAL_ARRAY */
+/*      GL_COLOR_ARRAY */
+/*      GL_INDEX_ARRAY */
+/*      GL_TEXTURE_COORD_ARRAY */
+/*      GL_EDGE_FLAG_ARRAY */
+/*      GL_POLYGON_OFFSET_POINT */
+/*      GL_POLYGON_OFFSET_LINE */
+/*      GL_POLYGON_OFFSET_FILL */
+/*      GL_COLOR_TABLE */
+/*      GL_POST_CONVOLUTION_COLOR_TABLE */
+/*      GL_POST_COLOR_MATRIX_COLOR_TABLE */
+/*      GL_CONVOLUTION_1D */
+/*      GL_CONVOLUTION_2D */
+/*      GL_SEPARABLE_2D */
+/*      GL_HISTOGRAM */
+/*      GL_MINMAX */
+/*      GL_RESCALE_NORMAL */
+/*      GL_TEXTURE_3D */
+
+/* ErrorCode */
+#define GL_NO_ERROR                       0
+#define GL_INVALID_ENUM                   0x0500
+#define GL_INVALID_VALUE                  0x0501
+#define GL_INVALID_OPERATION              0x0502
+#define GL_STACK_OVERFLOW                 0x0503
+#define GL_STACK_UNDERFLOW                0x0504
+#define GL_OUT_OF_MEMORY                  0x0505
+/*      GL_TABLE_TOO_LARGE */
+
+/* FeedBackMode */
+#define GL_2D                             0x0600
+#define GL_3D                             0x0601
+#define GL_3D_COLOR                       0x0602
+#define GL_3D_COLOR_TEXTURE               0x0603
+#define GL_4D_COLOR_TEXTURE               0x0604
+
+/* FeedBackToken */
+#define GL_PASS_THROUGH_TOKEN             0x0700
+#define GL_POINT_TOKEN                    0x0701
+#define GL_LINE_TOKEN                     0x0702
+#define GL_POLYGON_TOKEN                  0x0703
+#define GL_BITMAP_TOKEN                   0x0704
+#define GL_DRAW_PIXEL_TOKEN               0x0705
+#define GL_COPY_PIXEL_TOKEN               0x0706
+#define GL_LINE_RESET_TOKEN               0x0707
+
+/* FogMode */
+/*      GL_LINEAR */
+#define GL_EXP                            0x0800
+#define GL_EXP2                           0x0801
+
+/* FogParameter */
+/*      GL_FOG_COLOR */
+/*      GL_FOG_DENSITY */
+/*      GL_FOG_END */
+/*      GL_FOG_INDEX */
+/*      GL_FOG_MODE */
+/*      GL_FOG_START */
+
+/* FrontFaceDirection */
+#define GL_CW                             0x0900
+#define GL_CCW                            0x0901
+
+/* GetColorTableParameterPName */
+/*      GL_COLOR_TABLE_SCALE */
+/*      GL_COLOR_TABLE_BIAS */
+/*      GL_COLOR_TABLE_FORMAT */
+/*      GL_COLOR_TABLE_WIDTH */
+/*      GL_COLOR_TABLE_RED_SIZE */
+/*      GL_COLOR_TABLE_GREEN_SIZE */
+/*      GL_COLOR_TABLE_BLUE_SIZE */
+/*      GL_COLOR_TABLE_ALPHA_SIZE */
+/*      GL_COLOR_TABLE_LUMINANCE_SIZE */
+/*      GL_COLOR_TABLE_INTENSITY_SIZE */
+
+/* GetConvolutionParameterPName */
+/*      GL_CONVOLUTION_BORDER_COLOR */
+/*      GL_CONVOLUTION_BORDER_MODE */
+/*      GL_CONVOLUTION_FILTER_SCALE */
+/*      GL_CONVOLUTION_FILTER_BIAS */
+/*      GL_CONVOLUTION_FORMAT */
+/*      GL_CONVOLUTION_WIDTH */
+/*      GL_CONVOLUTION_HEIGHT */
+/*      GL_MAX_CONVOLUTION_WIDTH */
+/*      GL_MAX_CONVOLUTION_HEIGHT */
+
+/* GetHistogramParameterPName */
+/*      GL_HISTOGRAM_WIDTH */
+/*      GL_HISTOGRAM_FORMAT */
+/*      GL_HISTOGRAM_RED_SIZE */
+/*      GL_HISTOGRAM_GREEN_SIZE */
+/*      GL_HISTOGRAM_BLUE_SIZE */
+/*      GL_HISTOGRAM_ALPHA_SIZE */
+/*      GL_HISTOGRAM_LUMINANCE_SIZE */
+/*      GL_HISTOGRAM_SINK */
+
+/* GetMapTarget */
+#define GL_COEFF                          0x0A00
+#define GL_ORDER                          0x0A01
+#define GL_DOMAIN                         0x0A02
+
+/* GetMinmaxParameterPName */
+/*      GL_MINMAX_FORMAT */
+/*      GL_MINMAX_SINK */
+
+/* GetPixelMap */
+/*      GL_PIXEL_MAP_I_TO_I */
+/*      GL_PIXEL_MAP_S_TO_S */
+/*      GL_PIXEL_MAP_I_TO_R */
+/*      GL_PIXEL_MAP_I_TO_G */
+/*      GL_PIXEL_MAP_I_TO_B */
+/*      GL_PIXEL_MAP_I_TO_A */
+/*      GL_PIXEL_MAP_R_TO_R */
+/*      GL_PIXEL_MAP_G_TO_G */
+/*      GL_PIXEL_MAP_B_TO_B */
+/*      GL_PIXEL_MAP_A_TO_A */
+
+/* GetPointerTarget */
+/*      GL_VERTEX_ARRAY_POINTER */
+/*      GL_NORMAL_ARRAY_POINTER */
+/*      GL_COLOR_ARRAY_POINTER */
+/*      GL_INDEX_ARRAY_POINTER */
+/*      GL_TEXTURE_COORD_ARRAY_POINTER */
+/*      GL_EDGE_FLAG_ARRAY_POINTER */
+
+/* GetTarget */
+#define GL_CURRENT_COLOR                  0x0B00
+#define GL_CURRENT_INDEX                  0x0B01
+#define GL_CURRENT_NORMAL                 0x0B02
+#define GL_CURRENT_TEXTURE_COORDS         0x0B03
+#define GL_CURRENT_RASTER_COLOR           0x0B04
+#define GL_CURRENT_RASTER_INDEX           0x0B05
+#define GL_CURRENT_RASTER_TEXTURE_COORDS  0x0B06
+#define GL_CURRENT_RASTER_POSITION        0x0B07
+#define GL_CURRENT_RASTER_POSITION_VALID  0x0B08
+#define GL_CURRENT_RASTER_DISTANCE        0x0B09
+#define GL_POINT_SMOOTH                   0x0B10
+#define GL_POINT_SIZE                     0x0B11
+#define GL_POINT_SIZE_RANGE               0x0B12
+#define GL_POINT_SIZE_GRANULARITY         0x0B13
+#define GL_LINE_SMOOTH                    0x0B20
+#define GL_LINE_WIDTH                     0x0B21
+#define GL_LINE_WIDTH_RANGE               0x0B22
+#define GL_LINE_WIDTH_GRANULARITY         0x0B23
+#define GL_LINE_STIPPLE                   0x0B24
+#define GL_LINE_STIPPLE_PATTERN           0x0B25
+#define GL_LINE_STIPPLE_REPEAT            0x0B26
+/*      GL_SMOOTH_POINT_SIZE_RANGE */
+/*      GL_SMOOTH_POINT_SIZE_GRANULARITY */
+/*      GL_SMOOTH_LINE_WIDTH_RANGE */
+/*      GL_SMOOTH_LINE_WIDTH_GRANULARITY */
+/*      GL_ALIASED_POINT_SIZE_RANGE */
+/*      GL_ALIASED_LINE_WIDTH_RANGE */
+#define GL_LIST_MODE                      0x0B30
+#define GL_MAX_LIST_NESTING               0x0B31
+#define GL_LIST_BASE                      0x0B32
+#define GL_LIST_INDEX                     0x0B33
+#define GL_POLYGON_MODE                   0x0B40
+#define GL_POLYGON_SMOOTH                 0x0B41
+#define GL_POLYGON_STIPPLE                0x0B42
+#define GL_EDGE_FLAG                      0x0B43
+#define GL_CULL_FACE                      0x0B44
+#define GL_CULL_FACE_MODE                 0x0B45
+#define GL_FRONT_FACE                     0x0B46
+#define GL_LIGHTING                       0x0B50
+#define GL_LIGHT_MODEL_LOCAL_VIEWER       0x0B51
+#define GL_LIGHT_MODEL_TWO_SIDE           0x0B52
+#define GL_LIGHT_MODEL_AMBIENT            0x0B53
+#define GL_SHADE_MODEL                    0x0B54
+#define GL_COLOR_MATERIAL_FACE            0x0B55
+#define GL_COLOR_MATERIAL_PARAMETER       0x0B56
+#define GL_COLOR_MATERIAL                 0x0B57
+#define GL_FOG                            0x0B60
+#define GL_FOG_INDEX                      0x0B61
+#define GL_FOG_DENSITY                    0x0B62
+#define GL_FOG_START                      0x0B63
+#define GL_FOG_END                        0x0B64
+#define GL_FOG_MODE                       0x0B65
+#define GL_FOG_COLOR                      0x0B66
+#define GL_DEPTH_RANGE                    0x0B70
+#define GL_DEPTH_TEST                     0x0B71
+#define GL_DEPTH_WRITEMASK                0x0B72
+#define GL_DEPTH_CLEAR_VALUE              0x0B73
+#define GL_DEPTH_FUNC                     0x0B74
+#define GL_ACCUM_CLEAR_VALUE              0x0B80
+#define GL_STENCIL_TEST                   0x0B90
+#define GL_STENCIL_CLEAR_VALUE            0x0B91
+#define GL_STENCIL_FUNC                   0x0B92
+#define GL_STENCIL_VALUE_MASK             0x0B93
+#define GL_STENCIL_FAIL                   0x0B94
+#define GL_STENCIL_PASS_DEPTH_FAIL        0x0B95
+#define GL_STENCIL_PASS_DEPTH_PASS        0x0B96
+#define GL_STENCIL_REF                    0x0B97
+#define GL_STENCIL_WRITEMASK              0x0B98
+#define GL_MATRIX_MODE                    0x0BA0
+#define GL_NORMALIZE                      0x0BA1
+#define GL_VIEWPORT                       0x0BA2
+#define GL_MODELVIEW_STACK_DEPTH          0x0BA3
+#define GL_PROJECTION_STACK_DEPTH         0x0BA4
+#define GL_TEXTURE_STACK_DEPTH            0x0BA5
+#define GL_MODELVIEW_MATRIX               0x0BA6
+#define GL_PROJECTION_MATRIX              0x0BA7
+#define GL_TEXTURE_MATRIX                 0x0BA8
+#define GL_ATTRIB_STACK_DEPTH             0x0BB0
+#define GL_CLIENT_ATTRIB_STACK_DEPTH      0x0BB1
+#define GL_ALPHA_TEST                     0x0BC0
+#define GL_ALPHA_TEST_FUNC                0x0BC1
+#define GL_ALPHA_TEST_REF                 0x0BC2
+#define GL_DITHER                         0x0BD0
+#define GL_BLEND_DST                      0x0BE0
+#define GL_BLEND_SRC                      0x0BE1
+#define GL_BLEND                          0x0BE2
+#define GL_LOGIC_OP_MODE                  0x0BF0
+#define GL_INDEX_LOGIC_OP                 0x0BF1
+#define GL_COLOR_LOGIC_OP                 0x0BF2
+#define GL_AUX_BUFFERS                    0x0C00
+#define GL_DRAW_BUFFER                    0x0C01
+#define GL_READ_BUFFER                    0x0C02
+#define GL_SCISSOR_BOX                    0x0C10
+#define GL_SCISSOR_TEST                   0x0C11
+#define GL_INDEX_CLEAR_VALUE              0x0C20
+#define GL_INDEX_WRITEMASK                0x0C21
+#define GL_COLOR_CLEAR_VALUE              0x0C22
+#define GL_COLOR_WRITEMASK                0x0C23
+#define GL_INDEX_MODE                     0x0C30
+#define GL_RGBA_MODE                      0x0C31
+#define GL_DOUBLEBUFFER                   0x0C32
+#define GL_STEREO                         0x0C33
+#define GL_RENDER_MODE                    0x0C40
+#define GL_PERSPECTIVE_CORRECTION_HINT    0x0C50
+#define GL_POINT_SMOOTH_HINT              0x0C51
+#define GL_LINE_SMOOTH_HINT               0x0C52
+#define GL_POLYGON_SMOOTH_HINT            0x0C53
+#define GL_FOG_HINT                       0x0C54
+#define GL_TEXTURE_GEN_S                  0x0C60
+#define GL_TEXTURE_GEN_T                  0x0C61
+#define GL_TEXTURE_GEN_R                  0x0C62
+#define GL_TEXTURE_GEN_Q                  0x0C63
+#define GL_PIXEL_MAP_I_TO_I               0x0C70
+#define GL_PIXEL_MAP_S_TO_S               0x0C71
+#define GL_PIXEL_MAP_I_TO_R               0x0C72
+#define GL_PIXEL_MAP_I_TO_G               0x0C73
+#define GL_PIXEL_MAP_I_TO_B               0x0C74
+#define GL_PIXEL_MAP_I_TO_A               0x0C75
+#define GL_PIXEL_MAP_R_TO_R               0x0C76
+#define GL_PIXEL_MAP_G_TO_G               0x0C77
+#define GL_PIXEL_MAP_B_TO_B               0x0C78
+#define GL_PIXEL_MAP_A_TO_A               0x0C79
+#define GL_PIXEL_MAP_I_TO_I_SIZE          0x0CB0
+#define GL_PIXEL_MAP_S_TO_S_SIZE          0x0CB1
+#define GL_PIXEL_MAP_I_TO_R_SIZE          0x0CB2
+#define GL_PIXEL_MAP_I_TO_G_SIZE          0x0CB3
+#define GL_PIXEL_MAP_I_TO_B_SIZE          0x0CB4
+#define GL_PIXEL_MAP_I_TO_A_SIZE          0x0CB5
+#define GL_PIXEL_MAP_R_TO_R_SIZE          0x0CB6
+#define GL_PIXEL_MAP_G_TO_G_SIZE          0x0CB7
+#define GL_PIXEL_MAP_B_TO_B_SIZE          0x0CB8
+#define GL_PIXEL_MAP_A_TO_A_SIZE          0x0CB9
+#define GL_UNPACK_SWAP_BYTES              0x0CF0
+#define GL_UNPACK_LSB_FIRST               0x0CF1
+#define GL_UNPACK_ROW_LENGTH              0x0CF2
+#define GL_UNPACK_SKIP_ROWS               0x0CF3
+#define GL_UNPACK_SKIP_PIXELS             0x0CF4
+#define GL_UNPACK_ALIGNMENT               0x0CF5
+#define GL_PACK_SWAP_BYTES                0x0D00
+#define GL_PACK_LSB_FIRST                 0x0D01
+#define GL_PACK_ROW_LENGTH                0x0D02
+#define GL_PACK_SKIP_ROWS                 0x0D03
+#define GL_PACK_SKIP_PIXELS               0x0D04
+#define GL_PACK_ALIGNMENT                 0x0D05
+#define GL_MAP_COLOR                      0x0D10
+#define GL_MAP_STENCIL                    0x0D11
+#define GL_INDEX_SHIFT                    0x0D12
+#define GL_INDEX_OFFSET                   0x0D13
+#define GL_RED_SCALE                      0x0D14
+#define GL_RED_BIAS                       0x0D15
+#define GL_ZOOM_X                         0x0D16
+#define GL_ZOOM_Y                         0x0D17
+#define GL_GREEN_SCALE                    0x0D18
+#define GL_GREEN_BIAS                     0x0D19
+#define GL_BLUE_SCALE                     0x0D1A
+#define GL_BLUE_BIAS                      0x0D1B
+#define GL_ALPHA_SCALE                    0x0D1C
+#define GL_ALPHA_BIAS                     0x0D1D
+#define GL_DEPTH_SCALE                    0x0D1E
+#define GL_DEPTH_BIAS                     0x0D1F
+#define GL_MAX_EVAL_ORDER                 0x0D30
+#define GL_MAX_LIGHTS                     0x0D31
+#define GL_MAX_CLIP_PLANES                0x0D32
+#define GL_MAX_TEXTURE_SIZE               0x0D33
+#define GL_MAX_PIXEL_MAP_TABLE            0x0D34
+#define GL_MAX_ATTRIB_STACK_DEPTH         0x0D35
+#define GL_MAX_MODELVIEW_STACK_DEPTH      0x0D36
+#define GL_MAX_NAME_STACK_DEPTH           0x0D37
+#define GL_MAX_PROJECTION_STACK_DEPTH     0x0D38
+#define GL_MAX_TEXTURE_STACK_DEPTH        0x0D39
+#define GL_MAX_VIEWPORT_DIMS              0x0D3A
+#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH  0x0D3B
+#define GL_SUBPIXEL_BITS                  0x0D50
+#define GL_INDEX_BITS                     0x0D51
+#define GL_RED_BITS                       0x0D52
+#define GL_GREEN_BITS                     0x0D53
+#define GL_BLUE_BITS                      0x0D54
+#define GL_ALPHA_BITS                     0x0D55
+#define GL_DEPTH_BITS                     0x0D56
+#define GL_STENCIL_BITS                   0x0D57
+#define GL_ACCUM_RED_BITS                 0x0D58
+#define GL_ACCUM_GREEN_BITS               0x0D59
+#define GL_ACCUM_BLUE_BITS                0x0D5A
+#define GL_ACCUM_ALPHA_BITS               0x0D5B
+#define GL_NAME_STACK_DEPTH               0x0D70
+#define GL_AUTO_NORMAL                    0x0D80
+#define GL_MAP1_COLOR_4                   0x0D90
+#define GL_MAP1_INDEX                     0x0D91
+#define GL_MAP1_NORMAL                    0x0D92
+#define GL_MAP1_TEXTURE_COORD_1           0x0D93
+#define GL_MAP1_TEXTURE_COORD_2           0x0D94
+#define GL_MAP1_TEXTURE_COORD_3           0x0D95
+#define GL_MAP1_TEXTURE_COORD_4           0x0D96
+#define GL_MAP1_VERTEX_3                  0x0D97
+#define GL_MAP1_VERTEX_4                  0x0D98
+#define GL_MAP2_COLOR_4                   0x0DB0
+#define GL_MAP2_INDEX                     0x0DB1
+#define GL_MAP2_NORMAL                    0x0DB2
+#define GL_MAP2_TEXTURE_COORD_1           0x0DB3
+#define GL_MAP2_TEXTURE_COORD_2           0x0DB4
+#define GL_MAP2_TEXTURE_COORD_3           0x0DB5
+#define GL_MAP2_TEXTURE_COORD_4           0x0DB6
+#define GL_MAP2_VERTEX_3                  0x0DB7
+#define GL_MAP2_VERTEX_4                  0x0DB8
+#define GL_MAP1_GRID_DOMAIN               0x0DD0
+#define GL_MAP1_GRID_SEGMENTS             0x0DD1
+#define GL_MAP2_GRID_DOMAIN               0x0DD2
+#define GL_MAP2_GRID_SEGMENTS             0x0DD3
+#define GL_TEXTURE_1D                     0x0DE0
+#define GL_TEXTURE_2D                     0x0DE1
+#define GL_FEEDBACK_BUFFER_POINTER        0x0DF0
+#define GL_FEEDBACK_BUFFER_SIZE           0x0DF1
+#define GL_FEEDBACK_BUFFER_TYPE           0x0DF2
+#define GL_SELECTION_BUFFER_POINTER       0x0DF3
+#define GL_SELECTION_BUFFER_SIZE          0x0DF4
+/*      GL_TEXTURE_BINDING_1D */
+/*      GL_TEXTURE_BINDING_2D */
+/*      GL_TEXTURE_BINDING_3D */
+/*      GL_VERTEX_ARRAY */
+/*      GL_NORMAL_ARRAY */
+/*      GL_COLOR_ARRAY */
+/*      GL_INDEX_ARRAY */
+/*      GL_TEXTURE_COORD_ARRAY */
+/*      GL_EDGE_FLAG_ARRAY */
+/*      GL_VERTEX_ARRAY_SIZE */
+/*      GL_VERTEX_ARRAY_TYPE */
+/*      GL_VERTEX_ARRAY_STRIDE */
+/*      GL_NORMAL_ARRAY_TYPE */
+/*      GL_NORMAL_ARRAY_STRIDE */
+/*      GL_COLOR_ARRAY_SIZE */
+/*      GL_COLOR_ARRAY_TYPE */
+/*      GL_COLOR_ARRAY_STRIDE */
+/*      GL_INDEX_ARRAY_TYPE */
+/*      GL_INDEX_ARRAY_STRIDE */
+/*      GL_TEXTURE_COORD_ARRAY_SIZE */
+/*      GL_TEXTURE_COORD_ARRAY_TYPE */
+/*      GL_TEXTURE_COORD_ARRAY_STRIDE */
+/*      GL_EDGE_FLAG_ARRAY_STRIDE */
+/*      GL_POLYGON_OFFSET_FACTOR */
+/*      GL_POLYGON_OFFSET_UNITS */
+/*      GL_COLOR_TABLE */
+/*      GL_POST_CONVOLUTION_COLOR_TABLE */
+/*      GL_POST_COLOR_MATRIX_COLOR_TABLE */
+/*      GL_CONVOLUTION_1D */
+/*      GL_CONVOLUTION_2D */
+/*      GL_SEPARABLE_2D */
+/*      GL_POST_CONVOLUTION_RED_SCALE */
+/*      GL_POST_CONVOLUTION_GREEN_SCALE */
+/*      GL_POST_CONVOLUTION_BLUE_SCALE */
+/*      GL_POST_CONVOLUTION_ALPHA_SCALE */
+/*      GL_POST_CONVOLUTION_RED_BIAS */
+/*      GL_POST_CONVOLUTION_GREEN_BIAS */
+/*      GL_POST_CONVOLUTION_BLUE_BIAS */
+/*      GL_POST_CONVOLUTION_ALPHA_BIAS */
+/*      GL_COLOR_MATRIX */
+/*      GL_COLOR_MATRIX_STACK_DEPTH */
+/*      GL_MAX_COLOR_MATRIX_STACK_DEPTH */
+/*      GL_POST_COLOR_MATRIX_RED_SCALE */
+/*      GL_POST_COLOR_MATRIX_GREEN_SCALE */
+/*      GL_POST_COLOR_MATRIX_BLUE_SCALE */
+/*      GL_POST_COLOR_MATRIX_ALPHA_SCALE */
+/*      GL_POST_COLOR_MATRIX_RED_BIAS */
+/*      GL_POST_COLOR_MATRIX_GREEN_BIAS */
+/*      GL_POST_COLOR_MATRIX_BLUE_BIAS */
+/*      GL_POST_COLOR_MATRIX_ALPHA_BIAS */
+/*      GL_HISTOGRAM */
+/*      GL_MINMAX */
+/*      GL_MAX_ELEMENTS_VERTICES */
+/*      GL_MAX_ELEMENTS_INDICES */
+/*      GL_RESCALE_NORMAL */
+/*      GL_LIGHT_MODEL_COLOR_CONTROL */
+/*      GL_PACK_SKIP_IMAGES */
+/*      GL_PACK_IMAGE_HEIGHT */
+/*      GL_UNPACK_SKIP_IMAGES */
+/*      GL_UNPACK_IMAGE_HEIGHT */
+/*      GL_TEXTURE_3D */
+/*      GL_MAX_3D_TEXTURE_SIZE */
+/*      GL_BLEND_COLOR */
+/*      GL_BLEND_EQUATION */
+/*      GL_ACTIVE_TEXTURE_ARB */
+/*      GL_CLIENT_ACTIVE_TEXTURE_ARB */
+/*      GL_MAX_TEXTURE_UNITS_ARB */
+
+/* GetTextureParameter */
+/*      GL_TEXTURE_MAG_FILTER */
+/*      GL_TEXTURE_MIN_FILTER */
+/*      GL_TEXTURE_WRAP_S */
+/*      GL_TEXTURE_WRAP_T */
+#define GL_TEXTURE_WIDTH                  0x1000
+#define GL_TEXTURE_HEIGHT                 0x1001
+#define GL_TEXTURE_INTERNAL_FORMAT        0x1003
+#define GL_TEXTURE_BORDER_COLOR           0x1004
+#define GL_TEXTURE_BORDER                 0x1005
+/*      GL_TEXTURE_RED_SIZE */
+/*      GL_TEXTURE_GREEN_SIZE */
+/*      GL_TEXTURE_BLUE_SIZE */
+/*      GL_TEXTURE_ALPHA_SIZE */
+/*      GL_TEXTURE_LUMINANCE_SIZE */
+/*      GL_TEXTURE_INTENSITY_SIZE */
+/*      GL_TEXTURE_PRIORITY */
+/*      GL_TEXTURE_RESIDENT */
+/*      GL_TEXTURE_DEPTH */
+/*      GL_TEXTURE_WRAP_R */
+/*      GL_TEXTURE_MIN_LOD */
+/*      GL_TEXTURE_MAX_LOD */
+/*      GL_TEXTURE_BASE_LEVEL */
+/*      GL_TEXTURE_MAX_LEVEL */
+
+/* HintMode */
+#define GL_DONT_CARE                      0x1100
+#define GL_FASTEST                        0x1101
+#define GL_NICEST                         0x1102
+
+/* HintTarget */
+/*      GL_PERSPECTIVE_CORRECTION_HINT */
+/*      GL_POINT_SMOOTH_HINT */
+/*      GL_LINE_SMOOTH_HINT */
+/*      GL_POLYGON_SMOOTH_HINT */
+/*      GL_FOG_HINT */
+
+/* HistogramTarget */
+/*      GL_HISTOGRAM */
+/*      GL_PROXY_HISTOGRAM */
+
+/* IndexPointerType */
+/*      GL_SHORT */
+/*      GL_INT */
+/*      GL_FLOAT */
+/*      GL_DOUBLE */
+
+/* LightModelColorControl */
+/*      GL_SINGLE_COLOR */
+/*      GL_SEPARATE_SPECULAR_COLOR */
+
+/* LightModelParameter */
+/*      GL_LIGHT_MODEL_AMBIENT */
+/*      GL_LIGHT_MODEL_LOCAL_VIEWER */
+/*      GL_LIGHT_MODEL_TWO_SIDE */
+/*      GL_LIGHT_MODEL_COLOR_CONTROL */
+
+/* LightName */
+#define GL_LIGHT0                         0x4000
+#define GL_LIGHT1                         0x4001
+#define GL_LIGHT2                         0x4002
+#define GL_LIGHT3                         0x4003
+#define GL_LIGHT4                         0x4004
+#define GL_LIGHT5                         0x4005
+#define GL_LIGHT6                         0x4006
+#define GL_LIGHT7                         0x4007
+
+/* LightParameter */
+#define GL_AMBIENT                        0x1200
+#define GL_DIFFUSE                        0x1201
+#define GL_SPECULAR                       0x1202
+#define GL_POSITION                       0x1203
+#define GL_SPOT_DIRECTION                 0x1204
+#define GL_SPOT_EXPONENT                  0x1205
+#define GL_SPOT_CUTOFF                    0x1206
+#define GL_CONSTANT_ATTENUATION           0x1207
+#define GL_LINEAR_ATTENUATION             0x1208
+#define GL_QUADRATIC_ATTENUATION          0x1209
+
+/* InterleavedArrays */
+/*      GL_V2F */
+/*      GL_V3F */
+/*      GL_C4UB_V2F */
+/*      GL_C4UB_V3F */
+/*      GL_C3F_V3F */
+/*      GL_N3F_V3F */
+/*      GL_C4F_N3F_V3F */
+/*      GL_T2F_V3F */
+/*      GL_T4F_V4F */
+/*      GL_T2F_C4UB_V3F */
+/*      GL_T2F_C3F_V3F */
+/*      GL_T2F_N3F_V3F */
+/*      GL_T2F_C4F_N3F_V3F */
+/*      GL_T4F_C4F_N3F_V4F */
+
+/* ListMode */
+#define GL_COMPILE                        0x1300
+#define GL_COMPILE_AND_EXECUTE            0x1301
+
+/* ListNameType */
+/*      GL_BYTE */
+/*      GL_UNSIGNED_BYTE */
+/*      GL_SHORT */
+/*      GL_UNSIGNED_SHORT */
+/*      GL_INT */
+/*      GL_UNSIGNED_INT */
+/*      GL_FLOAT */
+/*      GL_2_BYTES */
+/*      GL_3_BYTES */
+/*      GL_4_BYTES */
+
+/* LogicOp */
+#define GL_CLEAR                          0x1500
+#define GL_AND                            0x1501
+#define GL_AND_REVERSE                    0x1502
+#define GL_COPY                           0x1503
+#define GL_AND_INVERTED                   0x1504
+#define GL_NOOP                           0x1505
+#define GL_XOR                            0x1506
+#define GL_OR                             0x1507
+#define GL_NOR                            0x1508
+#define GL_EQUIV                          0x1509
+#define GL_INVERT                         0x150A
+#define GL_OR_REVERSE                     0x150B
+#define GL_COPY_INVERTED                  0x150C
+#define GL_OR_INVERTED                    0x150D
+#define GL_NAND                           0x150E
+#define GL_SET                            0x150F
+
+/* MapTarget */
+/*      GL_MAP1_COLOR_4 */
+/*      GL_MAP1_INDEX */
+/*      GL_MAP1_NORMAL */
+/*      GL_MAP1_TEXTURE_COORD_1 */
+/*      GL_MAP1_TEXTURE_COORD_2 */
+/*      GL_MAP1_TEXTURE_COORD_3 */
+/*      GL_MAP1_TEXTURE_COORD_4 */
+/*      GL_MAP1_VERTEX_3 */
+/*      GL_MAP1_VERTEX_4 */
+/*      GL_MAP2_COLOR_4 */
+/*      GL_MAP2_INDEX */
+/*      GL_MAP2_NORMAL */
+/*      GL_MAP2_TEXTURE_COORD_1 */
+/*      GL_MAP2_TEXTURE_COORD_2 */
+/*      GL_MAP2_TEXTURE_COORD_3 */
+/*      GL_MAP2_TEXTURE_COORD_4 */
+/*      GL_MAP2_VERTEX_3 */
+/*      GL_MAP2_VERTEX_4 */
+
+/* MaterialFace */
+/*      GL_FRONT */
+/*      GL_BACK */
+/*      GL_FRONT_AND_BACK */
+
+/* MaterialParameter */
+#define GL_EMISSION                       0x1600
+#define GL_SHININESS                      0x1601
+#define GL_AMBIENT_AND_DIFFUSE            0x1602
+#define GL_COLOR_INDEXES                  0x1603
+/*      GL_AMBIENT */
+/*      GL_DIFFUSE */
+/*      GL_SPECULAR */
+
+/* MatrixMode */
+#define GL_MODELVIEW                      0x1700
+#define GL_PROJECTION                     0x1701
+#define GL_TEXTURE                        0x1702
+
+/* MeshMode1 */
+/*      GL_POINT */
+/*      GL_LINE */
+
+/* MeshMode2 */
+/*      GL_POINT */
+/*      GL_LINE */
+/*      GL_FILL */
+
+/* MinmaxTarget */
+/*      GL_MINMAX */
+
+/* NormalPointerType */
+/*      GL_BYTE */
+/*      GL_SHORT */
+/*      GL_INT */
+/*      GL_FLOAT */
+/*      GL_DOUBLE */
+
+/* PixelCopyType */
+#define GL_COLOR                          0x1800
+#define GL_DEPTH                          0x1801
+#define GL_STENCIL                        0x1802
+
+/* PixelFormat */
+#define GL_COLOR_INDEX                    0x1900
+#define GL_STENCIL_INDEX                  0x1901
+#define GL_DEPTH_COMPONENT                0x1902
+#define GL_RED                            0x1903
+#define GL_GREEN                          0x1904
+#define GL_BLUE                           0x1905
+#define GL_ALPHA                          0x1906
+#define GL_RGB                            0x1907
+#define GL_RGBA                           0x1908
+#define GL_LUMINANCE                      0x1909
+#define GL_LUMINANCE_ALPHA                0x190A
+/*      GL_ABGR */
+
+/* PixelInternalFormat */
+/*      GL_ALPHA4 */
+/*      GL_ALPHA8 */
+/*      GL_ALPHA12 */
+/*      GL_ALPHA16 */
+/*      GL_LUMINANCE4 */
+/*      GL_LUMINANCE8 */
+/*      GL_LUMINANCE12 */
+/*      GL_LUMINANCE16 */
+/*      GL_LUMINANCE4_ALPHA4 */
+/*      GL_LUMINANCE6_ALPHA2 */
+/*      GL_LUMINANCE8_ALPHA8 */
+/*      GL_LUMINANCE12_ALPHA4 */
+/*      GL_LUMINANCE12_ALPHA12 */
+/*      GL_LUMINANCE16_ALPHA16 */
+/*      GL_INTENSITY */
+/*      GL_INTENSITY4 */
+/*      GL_INTENSITY8 */
+/*      GL_INTENSITY12 */
+/*      GL_INTENSITY16 */
+/*      GL_R3_G3_B2 */
+/*      GL_RGB4 */
+/*      GL_RGB5 */
+/*      GL_RGB8 */
+/*      GL_RGB10 */
+/*      GL_RGB12 */
+/*      GL_RGB16 */
+/*      GL_RGBA2 */
+/*      GL_RGBA4 */
+/*      GL_RGB5_A1 */
+/*      GL_RGBA8 */
+/*      GL_RGB10_A2 */
+/*      GL_RGBA12 */
+/*      GL_RGBA16 */
+
+/* PixelMap */
+/*      GL_PIXEL_MAP_I_TO_I */
+/*      GL_PIXEL_MAP_S_TO_S */
+/*      GL_PIXEL_MAP_I_TO_R */
+/*      GL_PIXEL_MAP_I_TO_G */
+/*      GL_PIXEL_MAP_I_TO_B */
+/*      GL_PIXEL_MAP_I_TO_A */
+/*      GL_PIXEL_MAP_R_TO_R */
+/*      GL_PIXEL_MAP_G_TO_G */
+/*      GL_PIXEL_MAP_B_TO_B */
+/*      GL_PIXEL_MAP_A_TO_A */
+
+/* PixelStore */
+/*      GL_UNPACK_SWAP_BYTES */
+/*      GL_UNPACK_LSB_FIRST */
+/*      GL_UNPACK_ROW_LENGTH */
+/*      GL_UNPACK_SKIP_ROWS */
+/*      GL_UNPACK_SKIP_PIXELS */
+/*      GL_UNPACK_ALIGNMENT */
+/*      GL_PACK_SWAP_BYTES */
+/*      GL_PACK_LSB_FIRST */
+/*      GL_PACK_ROW_LENGTH */
+/*      GL_PACK_SKIP_ROWS */
+/*      GL_PACK_SKIP_PIXELS */
+/*      GL_PACK_ALIGNMENT */
+/*      GL_PACK_SKIP_IMAGES */
+/*      GL_PACK_IMAGE_HEIGHT */
+/*      GL_UNPACK_SKIP_IMAGES */
+/*      GL_UNPACK_IMAGE_HEIGHT */
+
+/* PixelTransfer */
+/*      GL_MAP_COLOR */
+/*      GL_MAP_STENCIL */
+/*      GL_INDEX_SHIFT */
+/*      GL_INDEX_OFFSET */
+/*      GL_RED_SCALE */
+/*      GL_RED_BIAS */
+/*      GL_GREEN_SCALE */
+/*      GL_GREEN_BIAS */
+/*      GL_BLUE_SCALE */
+/*      GL_BLUE_BIAS */
+/*      GL_ALPHA_SCALE */
+/*      GL_ALPHA_BIAS */
+/*      GL_DEPTH_SCALE */
+/*      GL_DEPTH_BIAS */
+/*      GL_POST_CONVOLUTION_RED_SCALE */
+/*      GL_POST_CONVOLUTION_GREEN_SCALE */
+/*      GL_POST_CONVOLUTION_BLUE_SCALE */
+/*      GL_POST_CONVOLUTION_ALPHA_SCALE */
+/*      GL_POST_CONVOLUTION_RED_BIAS */
+/*      GL_POST_CONVOLUTION_GREEN_BIAS */
+/*      GL_POST_CONVOLUTION_BLUE_BIAS */
+/*      GL_POST_CONVOLUTION_ALPHA_BIAS */
+/*      GL_POST_COLOR_MATRIX_RED_SCALE */
+/*      GL_POST_COLOR_MATRIX_GREEN_SCALE */
+/*      GL_POST_COLOR_MATRIX_BLUE_SCALE */
+/*      GL_POST_COLOR_MATRIX_ALPHA_SCALE */
+/*      GL_POST_COLOR_MATRIX_RED_BIAS */
+/*      GL_POST_COLOR_MATRIX_GREEN_BIAS */
+/*      GL_POST_COLOR_MATRIX_BLUE_BIAS */
+/*      GL_POST_COLOR_MATRIX_ALPHA_BIAS */
+
+/* PixelType */
+#define GL_BITMAP                         0x1A00
+/*      GL_BYTE */
+/*      GL_UNSIGNED_BYTE */
+/*      GL_SHORT */
+/*      GL_UNSIGNED_SHORT */
+/*      GL_INT */
+/*      GL_UNSIGNED_INT */
+/*      GL_FLOAT */
+/*      GL_BGR */
+/*      GL_BGRA */
+/*      GL_UNSIGNED_BYTE_3_3_2 */
+/*      GL_UNSIGNED_SHORT_4_4_4_4 */
+/*      GL_UNSIGNED_SHORT_5_5_5_1 */
+/*      GL_UNSIGNED_INT_8_8_8_8 */
+/*      GL_UNSIGNED_INT_10_10_10_2 */
+/*      GL_UNSIGNED_SHORT_5_6_5 */
+/*      GL_UNSIGNED_BYTE_2_3_3_REV */
+/*      GL_UNSIGNED_SHORT_5_6_5_REV */
+/*      GL_UNSIGNED_SHORT_4_4_4_4_REV */
+/*      GL_UNSIGNED_SHORT_1_5_5_5_REV */
+/*      GL_UNSIGNED_INT_8_8_8_8_REV */
+/*      GL_UNSIGNED_INT_2_10_10_10_REV */
+
+/* PolygonMode */
+#define GL_POINT                          0x1B00
+#define GL_LINE                           0x1B01
+#define GL_FILL                           0x1B02
+
+/* ReadBufferMode */
+/*      GL_FRONT_LEFT */
+/*      GL_FRONT_RIGHT */
+/*      GL_BACK_LEFT */
+/*      GL_BACK_RIGHT */
+/*      GL_FRONT */
+/*      GL_BACK */
+/*      GL_LEFT */
+/*      GL_RIGHT */
+/*      GL_AUX0 */
+/*      GL_AUX1 */
+/*      GL_AUX2 */
+/*      GL_AUX3 */
+
+/* RenderingMode */
+#define GL_RENDER                         0x1C00
+#define GL_FEEDBACK                       0x1C01
+#define GL_SELECT                         0x1C02
+
+/* SeparableTarget */
+/*      GL_SEPARABLE_2D */
+
+/* ShadingModel */
+#define GL_FLAT                           0x1D00
+#define GL_SMOOTH                         0x1D01
+
+/* StencilFunction */
+/*      GL_NEVER */
+/*      GL_LESS */
+/*      GL_EQUAL */
+/*      GL_LEQUAL */
+/*      GL_GREATER */
+/*      GL_NOTEQUAL */
+/*      GL_GEQUAL */
+/*      GL_ALWAYS */
+
+/* StencilOp */
+/*      GL_ZERO */
+#define GL_KEEP                           0x1E00
+#define GL_REPLACE                        0x1E01
+#define GL_INCR                           0x1E02
+#define GL_DECR                           0x1E03
+/*      GL_INVERT */
+
+/* StringName */
+#define GL_VENDOR                         0x1F00
+#define GL_RENDERER                       0x1F01
+#define GL_VERSION                        0x1F02
+#define GL_EXTENSIONS                     0x1F03
+
+/* TextureCoordName */
+#define GL_S                              0x2000
+#define GL_T                              0x2001
+#define GL_R                              0x2002
+#define GL_Q                              0x2003
+
+/* TexCoordPointerType */
+/*      GL_SHORT */
+/*      GL_INT */
+/*      GL_FLOAT */
+/*      GL_DOUBLE */
+
+/* TextureEnvMode */
+#define GL_MODULATE                       0x2100
+#define GL_DECAL                          0x2101
+/*      GL_BLEND */
+/*      GL_REPLACE */
+
+/* TextureEnvParameter */
+#define GL_TEXTURE_ENV_MODE               0x2200
+#define GL_TEXTURE_ENV_COLOR              0x2201
+
+/* TextureEnvTarget */
+#define GL_TEXTURE_ENV                    0x2300
+
+/* TextureGenMode */
+#define GL_EYE_LINEAR                     0x2400
+#define GL_OBJECT_LINEAR                  0x2401
+#define GL_SPHERE_MAP                     0x2402
+
+/* TextureGenParameter */
+#define GL_TEXTURE_GEN_MODE               0x2500
+#define GL_OBJECT_PLANE                   0x2501
+#define GL_EYE_PLANE                      0x2502
+
+/* TextureMagFilter */
+#define GL_NEAREST                        0x2600
+#define GL_LINEAR                         0x2601
+
+/* TextureMinFilter */
+/*      GL_NEAREST */
+/*      GL_LINEAR */
+#define GL_NEAREST_MIPMAP_NEAREST         0x2700
+#define GL_LINEAR_MIPMAP_NEAREST          0x2701
+#define GL_NEAREST_MIPMAP_LINEAR          0x2702
+#define GL_LINEAR_MIPMAP_LINEAR           0x2703
+
+/* TextureParameterName */
+#define GL_TEXTURE_MAG_FILTER             0x2800
+#define GL_TEXTURE_MIN_FILTER             0x2801
+#define GL_TEXTURE_WRAP_S                 0x2802
+#define GL_TEXTURE_WRAP_T                 0x2803
+/*      GL_TEXTURE_BORDER_COLOR */
+/*      GL_TEXTURE_PRIORITY */
+/*      GL_TEXTURE_WRAP_R */
+/*      GL_TEXTURE_MIN_LOD */
+/*      GL_TEXTURE_MAX_LOD */
+/*      GL_TEXTURE_BASE_LEVEL */
+/*      GL_TEXTURE_MAX_LEVEL */
+
+/* TextureTarget */
+/*      GL_TEXTURE_1D */
+/*      GL_TEXTURE_2D */
+/*      GL_PROXY_TEXTURE_1D */
+/*      GL_PROXY_TEXTURE_2D */
+/*      GL_TEXTURE_3D */
+/*      GL_PROXY_TEXTURE_3D */
+
+/* TextureUnit */
+/*      GL_TEXTURE0_ARB */
+/*      GL_TEXTURE1_ARB */
+/*      GL_TEXTURE2_ARB */
+/*      GL_TEXTURE3_ARB */
+/*      GL_TEXTURE4_ARB */
+/*      GL_TEXTURE5_ARB */
+/*      GL_TEXTURE6_ARB */
+/*      GL_TEXTURE7_ARB */
+/*      GL_TEXTURE8_ARB */
+/*      GL_TEXTURE9_ARB */
+/*      GL_TEXTURE10_ARB */
+/*      GL_TEXTURE11_ARB */
+/*      GL_TEXTURE12_ARB */
+/*      GL_TEXTURE13_ARB */
+/*      GL_TEXTURE14_ARB */
+/*      GL_TEXTURE15_ARB */
+/*      GL_TEXTURE16_ARB */
+/*      GL_TEXTURE17_ARB */
+/*      GL_TEXTURE18_ARB */
+/*      GL_TEXTURE19_ARB */
+/*      GL_TEXTURE20_ARB */
+/*      GL_TEXTURE21_ARB */
+/*      GL_TEXTURE22_ARB */
+/*      GL_TEXTURE23_ARB */
+/*      GL_TEXTURE24_ARB */
+/*      GL_TEXTURE25_ARB */
+/*      GL_TEXTURE26_ARB */
+/*      GL_TEXTURE27_ARB */
+/*      GL_TEXTURE28_ARB */
+/*      GL_TEXTURE29_ARB */
+/*      GL_TEXTURE30_ARB */
+/*      GL_TEXTURE31_ARB */
+
+/* TextureWrapMode */
+#define GL_CLAMP                          0x2900
+#define GL_REPEAT                         0x2901
+/*      GL_CLAMP_TO_EDGE */
+
+/* VertexPointerType */
+/*      GL_SHORT */
+/*      GL_INT */
+/*      GL_FLOAT */
+/*      GL_DOUBLE */
+
+/* ClientAttribMask */
+#define GL_CLIENT_PIXEL_STORE_BIT         0x00000001
+#define GL_CLIENT_VERTEX_ARRAY_BIT        0x00000002
+#define GL_CLIENT_ALL_ATTRIB_BITS         0xffffffff
+
+/* polygon_offset */
+#define GL_POLYGON_OFFSET_FACTOR          0x8038
+#define GL_POLYGON_OFFSET_UNITS           0x2A00
+#define GL_POLYGON_OFFSET_POINT           0x2A01
+#define GL_POLYGON_OFFSET_LINE            0x2A02
+#define GL_POLYGON_OFFSET_FILL            0x8037
+
+/* texture */
+#define GL_ALPHA4                         0x803B
+#define GL_ALPHA8                         0x803C
+#define GL_ALPHA12                        0x803D
+#define GL_ALPHA16                        0x803E
+#define GL_LUMINANCE4                     0x803F
+#define GL_LUMINANCE8                     0x8040
+#define GL_LUMINANCE12                    0x8041
+#define GL_LUMINANCE16                    0x8042
+#define GL_LUMINANCE4_ALPHA4              0x8043
+#define GL_LUMINANCE6_ALPHA2              0x8044
+#define GL_LUMINANCE8_ALPHA8              0x8045
+#define GL_LUMINANCE12_ALPHA4             0x8046
+#define GL_LUMINANCE12_ALPHA12            0x8047
+#define GL_LUMINANCE16_ALPHA16            0x8048
+#define GL_INTENSITY                      0x8049
+#define GL_INTENSITY4                     0x804A
+#define GL_INTENSITY8                     0x804B
+#define GL_INTENSITY12                    0x804C
+#define GL_INTENSITY16                    0x804D
+#define GL_R3_G3_B2                       0x2A10
+#define GL_RGB4                           0x804F
+#define GL_RGB5                           0x8050
+#define GL_RGB8                           0x8051
+#define GL_RGB10                          0x8052
+#define GL_RGB12                          0x8053
+#define GL_RGB16                          0x8054
+#define GL_RGBA2                          0x8055
+#define GL_RGBA4                          0x8056
+#define GL_RGB5_A1                        0x8057
+#define GL_RGBA8                          0x8058
+#define GL_RGB10_A2                       0x8059
+#define GL_RGBA12                         0x805A
+#define GL_RGBA16                         0x805B
+#define GL_TEXTURE_RED_SIZE               0x805C
+#define GL_TEXTURE_GREEN_SIZE             0x805D
+#define GL_TEXTURE_BLUE_SIZE              0x805E
+#define GL_TEXTURE_ALPHA_SIZE             0x805F
+#define GL_TEXTURE_LUMINANCE_SIZE         0x8060
+#define GL_TEXTURE_INTENSITY_SIZE         0x8061
+#define GL_PROXY_TEXTURE_1D               0x8063
+#define GL_PROXY_TEXTURE_2D               0x8064
+
+/* texture_object */
+#define GL_TEXTURE_PRIORITY               0x8066
+#define GL_TEXTURE_RESIDENT               0x8067
+#define GL_TEXTURE_BINDING_1D             0x8068
+#define GL_TEXTURE_BINDING_2D             0x8069
+#define GL_TEXTURE_BINDING_3D             0x806A
+
+/* vertex_array */
+#define GL_VERTEX_ARRAY                   0x8074
+#define GL_NORMAL_ARRAY                   0x8075
+#define GL_COLOR_ARRAY                    0x8076
+#define GL_INDEX_ARRAY                    0x8077
+#define GL_TEXTURE_COORD_ARRAY            0x8078
+#define GL_EDGE_FLAG_ARRAY                0x8079
+#define GL_VERTEX_ARRAY_SIZE              0x807A
+#define GL_VERTEX_ARRAY_TYPE              0x807B
+#define GL_VERTEX_ARRAY_STRIDE            0x807C
+#define GL_NORMAL_ARRAY_TYPE              0x807E
+#define GL_NORMAL_ARRAY_STRIDE            0x807F
+#define GL_COLOR_ARRAY_SIZE               0x8081
+#define GL_COLOR_ARRAY_TYPE               0x8082
+#define GL_COLOR_ARRAY_STRIDE             0x8083
+#define GL_INDEX_ARRAY_TYPE               0x8085
+#define GL_INDEX_ARRAY_STRIDE             0x8086
+#define GL_TEXTURE_COORD_ARRAY_SIZE       0x8088
+#define GL_TEXTURE_COORD_ARRAY_TYPE       0x8089
+#define GL_TEXTURE_COORD_ARRAY_STRIDE     0x808A
+#define GL_EDGE_FLAG_ARRAY_STRIDE         0x808C
+#define GL_VERTEX_ARRAY_POINTER           0x808E
+#define GL_NORMAL_ARRAY_POINTER           0x808F
+#define GL_COLOR_ARRAY_POINTER            0x8090
+#define GL_INDEX_ARRAY_POINTER            0x8091
+#define GL_TEXTURE_COORD_ARRAY_POINTER    0x8092
+#define GL_EDGE_FLAG_ARRAY_POINTER        0x8093
+#define GL_V2F                            0x2A20
+#define GL_V3F                            0x2A21
+#define GL_C4UB_V2F                       0x2A22
+#define GL_C4UB_V3F                       0x2A23
+#define GL_C3F_V3F                        0x2A24
+#define GL_N3F_V3F                        0x2A25
+#define GL_C4F_N3F_V3F                    0x2A26
+#define GL_T2F_V3F                        0x2A27
+#define GL_T4F_V4F                        0x2A28
+#define GL_T2F_C4UB_V3F                   0x2A29
+#define GL_T2F_C3F_V3F                    0x2A2A
+#define GL_T2F_N3F_V3F                    0x2A2B
+#define GL_T2F_C4F_N3F_V3F                0x2A2C
+#define GL_T4F_C4F_N3F_V4F                0x2A2D
+
+/* bgra */
+#define GL_BGR                            0x80E0
+#define GL_BGRA                           0x80E1
+
+/* blend_color */
+#define GL_CONSTANT_COLOR                 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002
+#define GL_CONSTANT_ALPHA                 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
+#define GL_BLEND_COLOR                    0x8005
+
+/* blend_minmax */
+#define GL_FUNC_ADD                       0x8006
+#define GL_MIN                            0x8007
+#define GL_MAX                            0x8008
+#define GL_BLEND_EQUATION                 0x8009
+
+/* blend_subtract */
+#define GL_FUNC_SUBTRACT                  0x800A
+#define GL_FUNC_REVERSE_SUBTRACT          0x800B
+
+/* color_matrix */
+#define GL_COLOR_MATRIX                   0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH       0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH   0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE    0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE  0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE   0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE  0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS     0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS   0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS    0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS   0x80BB
+
+/* color_table */
+#define GL_COLOR_TABLE                    0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE   0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE  0x80D2
+#define GL_PROXY_COLOR_TABLE              0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
+#define GL_COLOR_TABLE_SCALE              0x80D6
+#define GL_COLOR_TABLE_BIAS               0x80D7
+#define GL_COLOR_TABLE_FORMAT             0x80D8
+#define GL_COLOR_TABLE_WIDTH              0x80D9
+#define GL_COLOR_TABLE_RED_SIZE           0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE         0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE          0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE         0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE     0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE     0x80DF
+
+/* convolution */
+#define GL_CONVOLUTION_1D                 0x8010
+#define GL_CONVOLUTION_2D                 0x8011
+#define GL_SEPARABLE_2D                   0x8012
+#define GL_CONVOLUTION_BORDER_MODE        0x8013
+#define GL_CONVOLUTION_FILTER_SCALE       0x8014
+#define GL_CONVOLUTION_FILTER_BIAS        0x8015
+#define GL_REDUCE                         0x8016
+#define GL_CONVOLUTION_FORMAT             0x8017
+#define GL_CONVOLUTION_WIDTH              0x8018
+#define GL_CONVOLUTION_HEIGHT             0x8019
+#define GL_MAX_CONVOLUTION_WIDTH          0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT         0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE     0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE   0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE    0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE   0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS      0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS    0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS     0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS    0x8023
+#define GL_CONSTANT_BORDER                0x8151
+#define GL_REPLICATE_BORDER               0x8153
+#define GL_CONVOLUTION_BORDER_COLOR       0x8154
+
+/* draw_range_elements */
+#define GL_MAX_ELEMENTS_VERTICES          0x80E8
+#define GL_MAX_ELEMENTS_INDICES           0x80E9
+
+/* histogram */
+#define GL_HISTOGRAM                      0x8024
+#define GL_PROXY_HISTOGRAM                0x8025
+#define GL_HISTOGRAM_WIDTH                0x8026
+#define GL_HISTOGRAM_FORMAT               0x8027
+#define GL_HISTOGRAM_RED_SIZE             0x8028
+#define GL_HISTOGRAM_GREEN_SIZE           0x8029
+#define GL_HISTOGRAM_BLUE_SIZE            0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE           0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE       0x802C
+#define GL_HISTOGRAM_SINK                 0x802D
+#define GL_MINMAX                         0x802E
+#define GL_MINMAX_FORMAT                  0x802F
+#define GL_MINMAX_SINK                    0x8030
+#define GL_TABLE_TOO_LARGE                0x8031
+
+/* packed_pixels */
+#define GL_UNSIGNED_BYTE_3_3_2            0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_INT_8_8_8_8           0x8035
+#define GL_UNSIGNED_INT_10_10_10_2        0x8036
+#define GL_UNSIGNED_BYTE_2_3_3_REV        0x8362
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+#define GL_UNSIGNED_SHORT_5_6_5_REV       0x8364
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV     0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV     0x8366
+#define GL_UNSIGNED_INT_8_8_8_8_REV       0x8367
+#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368
+
+/* rescale_normal */
+#define GL_RESCALE_NORMAL                 0x803A
+
+/* separate_specular_color */
+#define GL_LIGHT_MODEL_COLOR_CONTROL      0x81F8
+#define GL_SINGLE_COLOR                   0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR        0x81FA
+
+/* texture3D */
+#define GL_PACK_SKIP_IMAGES               0x806B
+#define GL_PACK_IMAGE_HEIGHT              0x806C
+#define GL_UNPACK_SKIP_IMAGES             0x806D
+#define GL_UNPACK_IMAGE_HEIGHT            0x806E
+#define GL_TEXTURE_3D                     0x806F
+#define GL_PROXY_TEXTURE_3D               0x8070
+#define GL_TEXTURE_DEPTH                  0x8071
+#define GL_TEXTURE_WRAP_R                 0x8072
+#define GL_MAX_3D_TEXTURE_SIZE            0x8073
+
+/* texture_edge_clamp */
+#define GL_CLAMP_TO_EDGE                  0x812F
+
+/* texture_lod */
+#define GL_TEXTURE_MIN_LOD                0x813A
+#define GL_TEXTURE_MAX_LOD                0x813B
+#define GL_TEXTURE_BASE_LEVEL             0x813C
+#define GL_TEXTURE_MAX_LEVEL              0x813D
+
+/* GetTarget1_2 */
+#define GL_SMOOTH_POINT_SIZE_RANGE        0x0B12
+#define GL_SMOOTH_POINT_SIZE_GRANULARITY  0x0B13
+#define GL_SMOOTH_LINE_WIDTH_RANGE        0x0B22
+#define GL_SMOOTH_LINE_WIDTH_GRANULARITY  0x0B23
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+
+/* multitexture */
+#define GL_TEXTURE0_ARB                   0x84C0
+#define GL_TEXTURE1_ARB                   0x84C1
+#define GL_TEXTURE2_ARB                   0x84C2
+#define GL_TEXTURE3_ARB                   0x84C3
+#define GL_TEXTURE4_ARB                   0x84C4
+#define GL_TEXTURE5_ARB                   0x84C5
+#define GL_TEXTURE6_ARB                   0x84C6
+#define GL_TEXTURE7_ARB                   0x84C7
+#define GL_TEXTURE8_ARB                   0x84C8
+#define GL_TEXTURE9_ARB                   0x84C9
+#define GL_TEXTURE10_ARB                  0x84CA
+#define GL_TEXTURE11_ARB                  0x84CB
+#define GL_TEXTURE12_ARB                  0x84CC
+#define GL_TEXTURE13_ARB                  0x84CD
+#define GL_TEXTURE14_ARB                  0x84CE
+#define GL_TEXTURE15_ARB                  0x84CF
+#define GL_TEXTURE16_ARB                  0x84D0
+#define GL_TEXTURE17_ARB                  0x84D1
+#define GL_TEXTURE18_ARB                  0x84D2
+#define GL_TEXTURE19_ARB                  0x84D3
+#define GL_TEXTURE20_ARB                  0x84D4
+#define GL_TEXTURE21_ARB                  0x84D5
+#define GL_TEXTURE22_ARB                  0x84D6
+#define GL_TEXTURE23_ARB                  0x84D7
+#define GL_TEXTURE24_ARB                  0x84D8
+#define GL_TEXTURE25_ARB                  0x84D9
+#define GL_TEXTURE26_ARB                  0x84DA
+#define GL_TEXTURE27_ARB                  0x84DB
+#define GL_TEXTURE28_ARB                  0x84DC
+#define GL_TEXTURE29_ARB                  0x84DD
+#define GL_TEXTURE30_ARB                  0x84DE
+#define GL_TEXTURE31_ARB                  0x84DF
+#define GL_ACTIVE_TEXTURE_ARB             0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE_ARB      0x84E1
+#define GL_MAX_TEXTURE_UNITS_ARB          0x84E2
+
+/* Extensions */
+#define GL_EXT_abgr                       1
+#define GL_EXT_blend_color                1
+#define GL_EXT_blend_minmax               1
+#define GL_EXT_blend_subtract             1
+#define GL_EXT_texture_env_combine        1
+#define GL_EXT_texture_env_add            1
+
+/* EXT_abgr */
+#define GL_ABGR_EXT                       0x8000
+
+/* EXT_blend_color */
+#define GL_CONSTANT_COLOR_EXT             0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR_EXT   0x8002
+#define GL_CONSTANT_ALPHA_EXT             0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT   0x8004
+#define GL_BLEND_COLOR_EXT                0x8005
+
+/* EXT_blend_minmax */
+#define GL_FUNC_ADD_EXT                   0x8006
+#define GL_MIN_EXT                        0x8007
+#define GL_MAX_EXT                        0x8008
+#define GL_BLEND_EQUATION_EXT             0x8009
+
+/* EXT_blend_subtract */
+#define GL_FUNC_SUBTRACT_EXT              0x800A
+#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B
+
+/* EXT_texture_env_combine */
+#define GL_COMBINE_EXT                    0x8570
+#define GL_COMBINE_RGB_EXT                0x8571
+#define GL_COMBINE_ALPHA_EXT              0x8572
+#define GL_RGB_SCALE_EXT                  0x8573
+#define GL_ADD_SIGNED_EXT                 0x8574
+#define GL_INTERPOLATE_EXT                0x8575
+#define GL_CONSTANT_EXT                   0x8576
+#define GL_PRIMARY_COLOR_EXT              0x8577
+#define GL_PREVIOUS_EXT                   0x8578
+#define GL_SOURCE0_RGB_EXT                0x8580
+#define GL_SOURCE1_RGB_EXT                0x8581
+#define GL_SOURCE2_RGB_EXT                0x8582
+#define GL_SOURCE0_ALPHA_EXT              0x8588
+#define GL_SOURCE1_ALPHA_EXT              0x8589
+#define GL_SOURCE2_ALPHA_EXT              0x858A
+#define GL_OPERAND0_RGB_EXT               0x8590
+#define GL_OPERAND1_RGB_EXT               0x8591
+#define GL_OPERAND2_RGB_EXT               0x8592
+#define GL_OPERAND0_ALPHA_EXT             0x8598
+#define GL_OPERAND1_ALPHA_EXT             0x8599
+#define GL_OPERAND2_ALPHA_EXT             0x859A
+
+/* For compatibility with OpenGL v1.0 */
+#define GL_LOGIC_OP GL_INDEX_LOGIC_OP
+#define GL_TEXTURE_COMPONENTS GL_TEXTURE_INTERNAL_FORMAT
+
+/*************************************************************/
+
+WINGDIAPI void APIENTRY glAccum (GLenum op, GLfloat value);
+WINGDIAPI void APIENTRY glAlphaFunc (GLenum func, GLclampf ref);
+WINGDIAPI GLboolean APIENTRY glAreTexturesResident (GLsizei n, const GLuint *textures, GLboolean *residences);
+WINGDIAPI void APIENTRY glArrayElement (GLint i);
+WINGDIAPI void APIENTRY glBegin (GLenum mode);
+WINGDIAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
+WINGDIAPI void APIENTRY glBitmap (GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap);
+WINGDIAPI void APIENTRY glBlendFunc (GLenum sfactor, GLenum dfactor);
+WINGDIAPI void APIENTRY glCallList (GLuint list);
+WINGDIAPI void APIENTRY glCallLists (GLsizei n, GLenum type, const GLvoid *lists);
+WINGDIAPI void APIENTRY glClear (GLbitfield mask);
+WINGDIAPI void APIENTRY glClearAccum (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+WINGDIAPI void APIENTRY glClearColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+WINGDIAPI void APIENTRY glClearDepth (GLclampd depth);
+WINGDIAPI void APIENTRY glClearIndex (GLfloat c);
+WINGDIAPI void APIENTRY glClearStencil (GLint s);
+WINGDIAPI void APIENTRY glClipPlane (GLenum plane, const GLdouble *equation);
+WINGDIAPI void APIENTRY glColor3b (GLbyte red, GLbyte green, GLbyte blue);
+WINGDIAPI void APIENTRY glColor3bv (const GLbyte *v);
+WINGDIAPI void APIENTRY glColor3d (GLdouble red, GLdouble green, GLdouble blue);
+WINGDIAPI void APIENTRY glColor3dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glColor3f (GLfloat red, GLfloat green, GLfloat blue);
+WINGDIAPI void APIENTRY glColor3fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glColor3i (GLint red, GLint green, GLint blue);
+WINGDIAPI void APIENTRY glColor3iv (const GLint *v);
+WINGDIAPI void APIENTRY glColor3s (GLshort red, GLshort green, GLshort blue);
+WINGDIAPI void APIENTRY glColor3sv (const GLshort *v);
+WINGDIAPI void APIENTRY glColor3ub (GLubyte red, GLubyte green, GLubyte blue);
+WINGDIAPI void APIENTRY glColor3ubv (const GLubyte *v);
+WINGDIAPI void APIENTRY glColor3ui (GLuint red, GLuint green, GLuint blue);
+WINGDIAPI void APIENTRY glColor3uiv (const GLuint *v);
+WINGDIAPI void APIENTRY glColor3us (GLushort red, GLushort green, GLushort blue);
+WINGDIAPI void APIENTRY glColor3usv (const GLushort *v);
+WINGDIAPI void APIENTRY glColor4b (GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha);
+WINGDIAPI void APIENTRY glColor4bv (const GLbyte *v);
+WINGDIAPI void APIENTRY glColor4d (GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha);
+WINGDIAPI void APIENTRY glColor4dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glColor4f (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
+WINGDIAPI void APIENTRY glColor4fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glColor4i (GLint red, GLint green, GLint blue, GLint alpha);
+WINGDIAPI void APIENTRY glColor4iv (const GLint *v);
+WINGDIAPI void APIENTRY glColor4s (GLshort red, GLshort green, GLshort blue, GLshort alpha);
+WINGDIAPI void APIENTRY glColor4sv (const GLshort *v);
+WINGDIAPI void APIENTRY glColor4ub (GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha);
+WINGDIAPI void APIENTRY glColor4ubv (const GLubyte *v);
+WINGDIAPI void APIENTRY glColor4ui (GLuint red, GLuint green, GLuint blue, GLuint alpha);
+WINGDIAPI void APIENTRY glColor4uiv (const GLuint *v);
+WINGDIAPI void APIENTRY glColor4us (GLushort red, GLushort green, GLushort blue, GLushort alpha);
+WINGDIAPI void APIENTRY glColor4usv (const GLushort *v);
+WINGDIAPI void APIENTRY glColorMask (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+WINGDIAPI void APIENTRY glColorMaterial (GLenum face, GLenum mode);
+WINGDIAPI void APIENTRY glColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+WINGDIAPI void APIENTRY glCopyPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum type);
+WINGDIAPI void APIENTRY glCopyTexImage1D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+WINGDIAPI void APIENTRY glCopyTexImage2D (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+WINGDIAPI void APIENTRY glCopyTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+WINGDIAPI void APIENTRY glCopyTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+WINGDIAPI void APIENTRY glCullFace (GLenum mode);
+WINGDIAPI void APIENTRY glDeleteLists (GLuint list, GLsizei range);
+WINGDIAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
+WINGDIAPI void APIENTRY glDepthFunc (GLenum func);
+WINGDIAPI void APIENTRY glDepthMask (GLboolean flag);
+WINGDIAPI void APIENTRY glDepthRange (GLclampd zNear, GLclampd zFar);
+WINGDIAPI void APIENTRY glDisable (GLenum cap);
+WINGDIAPI void APIENTRY glDisableClientState (GLenum array);
+WINGDIAPI void APIENTRY glDrawArrays (GLenum mode, GLint first, GLsizei count);
+WINGDIAPI void APIENTRY glDrawBuffer (GLenum mode);
+WINGDIAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const GLvoid *indices);
+WINGDIAPI void APIENTRY glDrawPixels (GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+WINGDIAPI void APIENTRY glEdgeFlag (GLboolean flag);
+WINGDIAPI void APIENTRY glEdgeFlagPointer (GLsizei stride, const GLboolean *pointer);
+WINGDIAPI void APIENTRY glEdgeFlagv (const GLboolean *flag);
+WINGDIAPI void APIENTRY glEnable (GLenum cap);
+WINGDIAPI void APIENTRY glEnableClientState (GLenum array);
+WINGDIAPI void APIENTRY glEnd (void);
+WINGDIAPI void APIENTRY glEndList (void);
+WINGDIAPI void APIENTRY glEvalCoord1d (GLdouble u);
+WINGDIAPI void APIENTRY glEvalCoord1dv (const GLdouble *u);
+WINGDIAPI void APIENTRY glEvalCoord1f (GLfloat u);
+WINGDIAPI void APIENTRY glEvalCoord1fv (const GLfloat *u);
+WINGDIAPI void APIENTRY glEvalCoord2d (GLdouble u, GLdouble v);
+WINGDIAPI void APIENTRY glEvalCoord2dv (const GLdouble *u);
+WINGDIAPI void APIENTRY glEvalCoord2f (GLfloat u, GLfloat v);
+WINGDIAPI void APIENTRY glEvalCoord2fv (const GLfloat *u);
+WINGDIAPI void APIENTRY glEvalMesh1 (GLenum mode, GLint i1, GLint i2);
+WINGDIAPI void APIENTRY glEvalMesh2 (GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2);
+WINGDIAPI void APIENTRY glEvalPoint1 (GLint i);
+WINGDIAPI void APIENTRY glEvalPoint2 (GLint i, GLint j);
+WINGDIAPI void APIENTRY glFeedbackBuffer (GLsizei size, GLenum type, GLfloat *buffer);
+WINGDIAPI void APIENTRY glFinish (void);
+WINGDIAPI void APIENTRY glFlush (void);
+WINGDIAPI void APIENTRY glFogf (GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glFogfv (GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glFogi (GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glFogiv (GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glFrontFace (GLenum mode);
+WINGDIAPI void APIENTRY glFrustum (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+WINGDIAPI GLuint APIENTRY glGenLists (GLsizei range);
+WINGDIAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
+WINGDIAPI void APIENTRY glGetBooleanv (GLenum pname, GLboolean *params);
+WINGDIAPI void APIENTRY glGetClipPlane (GLenum plane, GLdouble *equation);
+WINGDIAPI void APIENTRY glGetDoublev (GLenum pname, GLdouble *params);
+WINGDIAPI GLenum APIENTRY glGetError (void);
+WINGDIAPI void APIENTRY glGetFloatv (GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glGetLightfv (GLenum light, GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetLightiv (GLenum light, GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glGetMapdv (GLenum target, GLenum query, GLdouble *v);
+WINGDIAPI void APIENTRY glGetMapfv (GLenum target, GLenum query, GLfloat *v);
+WINGDIAPI void APIENTRY glGetMapiv (GLenum target, GLenum query, GLint *v);
+WINGDIAPI void APIENTRY glGetMaterialfv (GLenum face, GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetMaterialiv (GLenum face, GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glGetPixelMapfv (GLenum map, GLfloat *values);
+WINGDIAPI void APIENTRY glGetPixelMapuiv (GLenum map, GLuint *values);
+WINGDIAPI void APIENTRY glGetPixelMapusv (GLenum map, GLushort *values);
+WINGDIAPI void APIENTRY glGetPointerv (GLenum pname, GLvoid* *params);
+WINGDIAPI void APIENTRY glGetPolygonStipple (GLubyte *mask);
+WINGDIAPI const GLubyte * APIENTRY glGetString (GLenum name);
+WINGDIAPI void APIENTRY glGetTexEnvfv (GLenum target, GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetTexEnviv (GLenum target, GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glGetTexGendv (GLenum coord, GLenum pname, GLdouble *params);
+WINGDIAPI void APIENTRY glGetTexGenfv (GLenum coord, GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetTexGeniv (GLenum coord, GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glGetTexImage (GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels);
+WINGDIAPI void APIENTRY glGetTexLevelParameterfv (GLenum target, GLint level, GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetTexLevelParameteriv (GLenum target, GLint level, GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glGetTexParameterfv (GLenum target, GLenum pname, GLfloat *params);
+WINGDIAPI void APIENTRY glGetTexParameteriv (GLenum target, GLenum pname, GLint *params);
+WINGDIAPI void APIENTRY glHint (GLenum target, GLenum mode);
+WINGDIAPI void APIENTRY glIndexMask (GLuint mask);
+WINGDIAPI void APIENTRY glIndexPointer (GLenum type, GLsizei stride, const GLvoid *pointer);
+WINGDIAPI void APIENTRY glIndexd (GLdouble c);
+WINGDIAPI void APIENTRY glIndexdv (const GLdouble *c);
+WINGDIAPI void APIENTRY glIndexf (GLfloat c);
+WINGDIAPI void APIENTRY glIndexfv (const GLfloat *c);
+WINGDIAPI void APIENTRY glIndexi (GLint c);
+WINGDIAPI void APIENTRY glIndexiv (const GLint *c);
+WINGDIAPI void APIENTRY glIndexs (GLshort c);
+WINGDIAPI void APIENTRY glIndexsv (const GLshort *c);
+WINGDIAPI void APIENTRY glIndexub (GLubyte c);
+WINGDIAPI void APIENTRY glIndexubv (const GLubyte *c);
+WINGDIAPI void APIENTRY glInitNames (void);
+WINGDIAPI void APIENTRY glInterleavedArrays (GLenum format, GLsizei stride, const GLvoid *pointer);
+WINGDIAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
+WINGDIAPI GLboolean APIENTRY glIsList (GLuint list);
+WINGDIAPI GLboolean APIENTRY glIsTexture (GLuint texture);
+WINGDIAPI void APIENTRY glLightModelf (GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glLightModelfv (GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glLightModeli (GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glLightModeliv (GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glLightf (GLenum light, GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glLightfv (GLenum light, GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glLighti (GLenum light, GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glLightiv (GLenum light, GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glLineStipple (GLint factor, GLushort pattern);
+WINGDIAPI void APIENTRY glLineWidth (GLfloat width);
+WINGDIAPI void APIENTRY glListBase (GLuint base);
+WINGDIAPI void APIENTRY glLoadIdentity (void);
+WINGDIAPI void APIENTRY glLoadMatrixd (const GLdouble *m);
+WINGDIAPI void APIENTRY glLoadMatrixf (const GLfloat *m);
+WINGDIAPI void APIENTRY glLoadName (GLuint name);
+WINGDIAPI void APIENTRY glLogicOp (GLenum opcode);
+WINGDIAPI void APIENTRY glMap1d (GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points);
+WINGDIAPI void APIENTRY glMap1f (GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points);
+WINGDIAPI void APIENTRY glMap2d (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points);
+WINGDIAPI void APIENTRY glMap2f (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points);
+WINGDIAPI void APIENTRY glMapGrid1d (GLint un, GLdouble u1, GLdouble u2);
+WINGDIAPI void APIENTRY glMapGrid1f (GLint un, GLfloat u1, GLfloat u2);
+WINGDIAPI void APIENTRY glMapGrid2d (GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2);
+WINGDIAPI void APIENTRY glMapGrid2f (GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2);
+WINGDIAPI void APIENTRY glMaterialf (GLenum face, GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glMaterialfv (GLenum face, GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glMateriali (GLenum face, GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glMaterialiv (GLenum face, GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glMatrixMode (GLenum mode);
+WINGDIAPI void APIENTRY glMultMatrixd (const GLdouble *m);
+WINGDIAPI void APIENTRY glMultMatrixf (const GLfloat *m);
+WINGDIAPI void APIENTRY glNewList (GLuint list, GLenum mode);
+WINGDIAPI void APIENTRY glNormal3b (GLbyte nx, GLbyte ny, GLbyte nz);
+WINGDIAPI void APIENTRY glNormal3bv (const GLbyte *v);
+WINGDIAPI void APIENTRY glNormal3d (GLdouble nx, GLdouble ny, GLdouble nz);
+WINGDIAPI void APIENTRY glNormal3dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glNormal3f (GLfloat nx, GLfloat ny, GLfloat nz);
+WINGDIAPI void APIENTRY glNormal3fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glNormal3i (GLint nx, GLint ny, GLint nz);
+WINGDIAPI void APIENTRY glNormal3iv (const GLint *v);
+WINGDIAPI void APIENTRY glNormal3s (GLshort nx, GLshort ny, GLshort nz);
+WINGDIAPI void APIENTRY glNormal3sv (const GLshort *v);
+WINGDIAPI void APIENTRY glNormalPointer (GLenum type, GLsizei stride, const GLvoid *pointer);
+WINGDIAPI void APIENTRY glOrtho (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar);
+WINGDIAPI void APIENTRY glPassThrough (GLfloat token);
+WINGDIAPI void APIENTRY glPixelMapfv (GLenum map, GLint mapsize, const GLfloat *values);
+WINGDIAPI void APIENTRY glPixelMapuiv (GLenum map, GLint mapsize, const GLuint *values);
+WINGDIAPI void APIENTRY glPixelMapusv (GLenum map, GLint mapsize, const GLushort *values);
+WINGDIAPI void APIENTRY glPixelStoref (GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glPixelTransferf (GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glPixelTransferi (GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glPixelZoom (GLfloat xfactor, GLfloat yfactor);
+WINGDIAPI void APIENTRY glPointSize (GLfloat size);
+WINGDIAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
+WINGDIAPI void APIENTRY glPolygonOffset (GLfloat factor, GLfloat units);
+WINGDIAPI void APIENTRY glPolygonStipple (const GLubyte *mask);
+WINGDIAPI void APIENTRY glPopAttrib (void);
+WINGDIAPI void APIENTRY glPopClientAttrib (void);
+WINGDIAPI void APIENTRY glPopMatrix (void);
+WINGDIAPI void APIENTRY glPopName (void);
+WINGDIAPI void APIENTRY glPrioritizeTextures (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+WINGDIAPI void APIENTRY glPushAttrib (GLbitfield mask);
+WINGDIAPI void APIENTRY glPushClientAttrib (GLbitfield mask);
+WINGDIAPI void APIENTRY glPushMatrix (void);
+WINGDIAPI void APIENTRY glPushName (GLuint name);
+WINGDIAPI void APIENTRY glRasterPos2d (GLdouble x, GLdouble y);
+WINGDIAPI void APIENTRY glRasterPos2dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glRasterPos2f (GLfloat x, GLfloat y);
+WINGDIAPI void APIENTRY glRasterPos2fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glRasterPos2i (GLint x, GLint y);
+WINGDIAPI void APIENTRY glRasterPos2iv (const GLint *v);
+WINGDIAPI void APIENTRY glRasterPos2s (GLshort x, GLshort y);
+WINGDIAPI void APIENTRY glRasterPos2sv (const GLshort *v);
+WINGDIAPI void APIENTRY glRasterPos3d (GLdouble x, GLdouble y, GLdouble z);
+WINGDIAPI void APIENTRY glRasterPos3dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glRasterPos3f (GLfloat x, GLfloat y, GLfloat z);
+WINGDIAPI void APIENTRY glRasterPos3fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glRasterPos3i (GLint x, GLint y, GLint z);
+WINGDIAPI void APIENTRY glRasterPos3iv (const GLint *v);
+WINGDIAPI void APIENTRY glRasterPos3s (GLshort x, GLshort y, GLshort z);
+WINGDIAPI void APIENTRY glRasterPos3sv (const GLshort *v);
+WINGDIAPI void APIENTRY glRasterPos4d (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+WINGDIAPI void APIENTRY glRasterPos4dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glRasterPos4f (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+WINGDIAPI void APIENTRY glRasterPos4fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glRasterPos4i (GLint x, GLint y, GLint z, GLint w);
+WINGDIAPI void APIENTRY glRasterPos4iv (const GLint *v);
+WINGDIAPI void APIENTRY glRasterPos4s (GLshort x, GLshort y, GLshort z, GLshort w);
+WINGDIAPI void APIENTRY glRasterPos4sv (const GLshort *v);
+WINGDIAPI void APIENTRY glReadBuffer (GLenum mode);
+WINGDIAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels);
+WINGDIAPI void APIENTRY glRectd (GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2);
+WINGDIAPI void APIENTRY glRectdv (const GLdouble *v1, const GLdouble *v2);
+WINGDIAPI void APIENTRY glRectf (GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2);
+WINGDIAPI void APIENTRY glRectfv (const GLfloat *v1, const GLfloat *v2);
+WINGDIAPI void APIENTRY glRecti (GLint x1, GLint y1, GLint x2, GLint y2);
+WINGDIAPI void APIENTRY glRectiv (const GLint *v1, const GLint *v2);
+WINGDIAPI void APIENTRY glRects (GLshort x1, GLshort y1, GLshort x2, GLshort y2);
+WINGDIAPI void APIENTRY glRectsv (const GLshort *v1, const GLshort *v2);
+WINGDIAPI GLint APIENTRY glRenderMode (GLenum mode);
+WINGDIAPI void APIENTRY glRotated (GLdouble angle, GLdouble x, GLdouble y, GLdouble z);
+WINGDIAPI void APIENTRY glRotatef (GLfloat angle, GLfloat x, GLfloat y, GLfloat z);
+WINGDIAPI void APIENTRY glScaled (GLdouble x, GLdouble y, GLdouble z);
+WINGDIAPI void APIENTRY glScalef (GLfloat x, GLfloat y, GLfloat z);
+WINGDIAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
+WINGDIAPI void APIENTRY glSelectBuffer (GLsizei size, GLuint *buffer);
+WINGDIAPI void APIENTRY glShadeModel (GLenum mode);
+WINGDIAPI void APIENTRY glStencilFunc (GLenum func, GLint ref, GLuint mask);
+WINGDIAPI void APIENTRY glStencilMask (GLuint mask);
+WINGDIAPI void APIENTRY glStencilOp (GLenum fail, GLenum zfail, GLenum zpass);
+WINGDIAPI void APIENTRY glTexCoord1d (GLdouble s);
+WINGDIAPI void APIENTRY glTexCoord1dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glTexCoord1f (GLfloat s);
+WINGDIAPI void APIENTRY glTexCoord1fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glTexCoord1i (GLint s);
+WINGDIAPI void APIENTRY glTexCoord1iv (const GLint *v);
+WINGDIAPI void APIENTRY glTexCoord1s (GLshort s);
+WINGDIAPI void APIENTRY glTexCoord1sv (const GLshort *v);
+WINGDIAPI void APIENTRY glTexCoord2d (GLdouble s, GLdouble t);
+WINGDIAPI void APIENTRY glTexCoord2dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glTexCoord2f (GLfloat s, GLfloat t);
+WINGDIAPI void APIENTRY glTexCoord2fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glTexCoord2i (GLint s, GLint t);
+WINGDIAPI void APIENTRY glTexCoord2iv (const GLint *v);
+WINGDIAPI void APIENTRY glTexCoord2s (GLshort s, GLshort t);
+WINGDIAPI void APIENTRY glTexCoord2sv (const GLshort *v);
+WINGDIAPI void APIENTRY glTexCoord3d (GLdouble s, GLdouble t, GLdouble r);
+WINGDIAPI void APIENTRY glTexCoord3dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glTexCoord3f (GLfloat s, GLfloat t, GLfloat r);
+WINGDIAPI void APIENTRY glTexCoord3fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glTexCoord3i (GLint s, GLint t, GLint r);
+WINGDIAPI void APIENTRY glTexCoord3iv (const GLint *v);
+WINGDIAPI void APIENTRY glTexCoord3s (GLshort s, GLshort t, GLshort r);
+WINGDIAPI void APIENTRY glTexCoord3sv (const GLshort *v);
+WINGDIAPI void APIENTRY glTexCoord4d (GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+WINGDIAPI void APIENTRY glTexCoord4dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glTexCoord4f (GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+WINGDIAPI void APIENTRY glTexCoord4fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glTexCoord4i (GLint s, GLint t, GLint r, GLint q);
+WINGDIAPI void APIENTRY glTexCoord4iv (const GLint *v);
+WINGDIAPI void APIENTRY glTexCoord4s (GLshort s, GLshort t, GLshort r, GLshort q);
+WINGDIAPI void APIENTRY glTexCoord4sv (const GLshort *v);
+WINGDIAPI void APIENTRY glTexCoordPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+WINGDIAPI void APIENTRY glTexEnvf (GLenum target, GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glTexEnvfv (GLenum target, GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glTexEnvi (GLenum target, GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glTexEnviv (GLenum target, GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glTexGend (GLenum coord, GLenum pname, GLdouble param);
+WINGDIAPI void APIENTRY glTexGendv (GLenum coord, GLenum pname, const GLdouble *params);
+WINGDIAPI void APIENTRY glTexGenf (GLenum coord, GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glTexGenfv (GLenum coord, GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glTexGeni (GLenum coord, GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glTexGeniv (GLenum coord, GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glTexImage1D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+WINGDIAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+WINGDIAPI void APIENTRY glTexParameterf (GLenum target, GLenum pname, GLfloat param);
+WINGDIAPI void APIENTRY glTexParameterfv (GLenum target, GLenum pname, const GLfloat *params);
+WINGDIAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
+WINGDIAPI void APIENTRY glTexParameteriv (GLenum target, GLenum pname, const GLint *params);
+WINGDIAPI void APIENTRY glTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+WINGDIAPI void APIENTRY glTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+WINGDIAPI void APIENTRY glTranslated (GLdouble x, GLdouble y, GLdouble z);
+WINGDIAPI void APIENTRY glTranslatef (GLfloat x, GLfloat y, GLfloat z);
+WINGDIAPI void APIENTRY glVertex2d (GLdouble x, GLdouble y);
+WINGDIAPI void APIENTRY glVertex2dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glVertex2f (GLfloat x, GLfloat y);
+WINGDIAPI void APIENTRY glVertex2fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glVertex2i (GLint x, GLint y);
+WINGDIAPI void APIENTRY glVertex2iv (const GLint *v);
+WINGDIAPI void APIENTRY glVertex2s (GLshort x, GLshort y);
+WINGDIAPI void APIENTRY glVertex2sv (const GLshort *v);
+WINGDIAPI void APIENTRY glVertex3d (GLdouble x, GLdouble y, GLdouble z);
+WINGDIAPI void APIENTRY glVertex3dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glVertex3f (GLfloat x, GLfloat y, GLfloat z);
+WINGDIAPI void APIENTRY glVertex3fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glVertex3i (GLint x, GLint y, GLint z);
+WINGDIAPI void APIENTRY glVertex3iv (const GLint *v);
+WINGDIAPI void APIENTRY glVertex3s (GLshort x, GLshort y, GLshort z);
+WINGDIAPI void APIENTRY glVertex3sv (const GLshort *v);
+WINGDIAPI void APIENTRY glVertex4d (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+WINGDIAPI void APIENTRY glVertex4dv (const GLdouble *v);
+WINGDIAPI void APIENTRY glVertex4f (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+WINGDIAPI void APIENTRY glVertex4fv (const GLfloat *v);
+WINGDIAPI void APIENTRY glVertex4i (GLint x, GLint y, GLint z, GLint w);
+WINGDIAPI void APIENTRY glVertex4iv (const GLint *v);
+WINGDIAPI void APIENTRY glVertex4s (GLshort x, GLshort y, GLshort z, GLshort w);
+WINGDIAPI void APIENTRY glVertex4sv (const GLshort *v);
+WINGDIAPI void APIENTRY glVertexPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+WINGDIAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __gl_h_ */
diff --git a/src/ext/GLsdk/GL/glext.h b/src/ext/GLsdk/GL/glext.h
new file mode 100644
index 0000000..1507194
--- /dev/null
+++ b/src/ext/GLsdk/GL/glext.h
@@ -0,0 +1,5924 @@
+#ifndef __glext_h_
+#define __glext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2002 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+/*************************************************************/
+
+/* Header file version number, required by OpenGL ABI for Linux */
+/* glext.h last updated 2004/2/23 */
+/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
+#define GL_GLEXT_VERSION 22
+
+#ifndef GL_VERSION_1_2
+#define GL_UNSIGNED_BYTE_3_3_2            0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4         0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1         0x8034
+#define GL_UNSIGNED_INT_8_8_8_8           0x8035
+#define GL_UNSIGNED_INT_10_10_10_2        0x8036
+#define GL_RESCALE_NORMAL                 0x803A
+#define GL_TEXTURE_BINDING_3D             0x806A
+#define GL_PACK_SKIP_IMAGES               0x806B
+#define GL_PACK_IMAGE_HEIGHT              0x806C
+#define GL_UNPACK_SKIP_IMAGES             0x806D
+#define GL_UNPACK_IMAGE_HEIGHT            0x806E
+#define GL_TEXTURE_3D                     0x806F
+#define GL_PROXY_TEXTURE_3D               0x8070
+#define GL_TEXTURE_DEPTH                  0x8071
+#define GL_TEXTURE_WRAP_R                 0x8072
+#define GL_MAX_3D_TEXTURE_SIZE            0x8073
+#define GL_UNSIGNED_BYTE_2_3_3_REV        0x8362
+#define GL_UNSIGNED_SHORT_5_6_5           0x8363
+#define GL_UNSIGNED_SHORT_5_6_5_REV       0x8364
+#define GL_UNSIGNED_SHORT_4_4_4_4_REV     0x8365
+#define GL_UNSIGNED_SHORT_1_5_5_5_REV     0x8366
+#define GL_UNSIGNED_INT_8_8_8_8_REV       0x8367
+#define GL_UNSIGNED_INT_2_10_10_10_REV    0x8368
+#define GL_BGR                            0x80E0
+#define GL_BGRA                           0x80E1
+#define GL_MAX_ELEMENTS_VERTICES          0x80E8
+#define GL_MAX_ELEMENTS_INDICES           0x80E9
+#define GL_CLAMP_TO_EDGE                  0x812F
+#define GL_TEXTURE_MIN_LOD                0x813A
+#define GL_TEXTURE_MAX_LOD                0x813B
+#define GL_TEXTURE_BASE_LEVEL             0x813C
+#define GL_TEXTURE_MAX_LEVEL              0x813D
+#define GL_LIGHT_MODEL_COLOR_CONTROL      0x81F8
+#define GL_SINGLE_COLOR                   0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR        0x81FA
+#define GL_SMOOTH_POINT_SIZE_RANGE        0x0B12
+#define GL_SMOOTH_POINT_SIZE_GRANULARITY  0x0B13
+#define GL_SMOOTH_LINE_WIDTH_RANGE        0x0B22
+#define GL_SMOOTH_LINE_WIDTH_GRANULARITY  0x0B23
+#define GL_ALIASED_POINT_SIZE_RANGE       0x846D
+#define GL_ALIASED_LINE_WIDTH_RANGE       0x846E
+#endif
+
+#ifndef GL_ARB_imaging
+#define GL_CONSTANT_COLOR                 0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR       0x8002
+#define GL_CONSTANT_ALPHA                 0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA       0x8004
+#define GL_BLEND_COLOR                    0x8005
+#define GL_FUNC_ADD                       0x8006
+#define GL_MIN                            0x8007
+#define GL_MAX                            0x8008
+#define GL_BLEND_EQUATION                 0x8009
+#define GL_FUNC_SUBTRACT                  0x800A
+#define GL_FUNC_REVERSE_SUBTRACT          0x800B
+#define GL_CONVOLUTION_1D                 0x8010
+#define GL_CONVOLUTION_2D                 0x8011
+#define GL_SEPARABLE_2D                   0x8012
+#define GL_CONVOLUTION_BORDER_MODE        0x8013
+#define GL_CONVOLUTION_FILTER_SCALE       0x8014
+#define GL_CONVOLUTION_FILTER_BIAS        0x8015
+#define GL_REDUCE                         0x8016
+#define GL_CONVOLUTION_FORMAT             0x8017
+#define GL_CONVOLUTION_WIDTH              0x8018
+#define GL_CONVOLUTION_HEIGHT             0x8019
+#define GL_MAX_CONVOLUTION_WIDTH          0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT         0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE     0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE   0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE    0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE   0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS      0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS    0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS     0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS    0x8023
+#define GL_HISTOGRAM                      0x8024
+#define GL_PROXY_HISTOGRAM                0x8025
+#define GL_HISTOGRAM_WIDTH                0x8026
+#define GL_HISTOGRAM_FORMAT               0x8027
+#define GL_HISTOGRAM_RED_SIZE             0x8028
+#define GL_HISTOGRAM_GREEN_SIZE           0x8029
+#define GL_HISTOGRAM_BLUE_SIZE            0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE           0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE       0x802C
+#define GL_HISTOGRAM_SINK                 0x802D
+#define GL_MINMAX                         0x802E
+#define GL_MINMAX_FORMAT                  0x802F
+#define GL_MINMAX_SINK                    0x8030
+#define GL_TABLE_TOO_LARGE                0x8031
+#define GL_COLOR_MATRIX                   0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH       0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH   0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE    0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE  0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE   0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE  0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS     0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS   0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS    0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS   0x80BB
+#define GL_COLOR_TABLE                    0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE   0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE  0x80D2
+#define GL_PROXY_COLOR_TABLE              0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE 0x80D5
+#define GL_COLOR_TABLE_SCALE              0x80D6
+#define GL_COLOR_TABLE_BIAS               0x80D7
+#define GL_COLOR_TABLE_FORMAT             0x80D8
+#define GL_COLOR_TABLE_WIDTH              0x80D9
+#define GL_COLOR_TABLE_RED_SIZE           0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE         0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE          0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE         0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE     0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE     0x80DF
+#define GL_CONSTANT_BORDER                0x8151
+#define GL_REPLICATE_BORDER               0x8153
+#define GL_CONVOLUTION_BORDER_COLOR       0x8154
+#endif
+
+#ifndef GL_VERSION_1_3
+#define GL_TEXTURE0                       0x84C0
+#define GL_TEXTURE1                       0x84C1
+#define GL_TEXTURE2                       0x84C2
+#define GL_TEXTURE3                       0x84C3
+#define GL_TEXTURE4                       0x84C4
+#define GL_TEXTURE5                       0x84C5
+#define GL_TEXTURE6                       0x84C6
+#define GL_TEXTURE7                       0x84C7
+#define GL_TEXTURE8                       0x84C8
+#define GL_TEXTURE9                       0x84C9
+#define GL_TEXTURE10                      0x84CA
+#define GL_TEXTURE11                      0x84CB
+#define GL_TEXTURE12                      0x84CC
+#define GL_TEXTURE13                      0x84CD
+#define GL_TEXTURE14                      0x84CE
+#define GL_TEXTURE15                      0x84CF
+#define GL_TEXTURE16                      0x84D0
+#define GL_TEXTURE17                      0x84D1
+#define GL_TEXTURE18                      0x84D2
+#define GL_TEXTURE19                      0x84D3
+#define GL_TEXTURE20                      0x84D4
+#define GL_TEXTURE21                      0x84D5
+#define GL_TEXTURE22                      0x84D6
+#define GL_TEXTURE23                      0x84D7
+#define GL_TEXTURE24                      0x84D8
+#define GL_TEXTURE25                      0x84D9
+#define GL_TEXTURE26                      0x84DA
+#define GL_TEXTURE27                      0x84DB
+#define GL_TEXTURE28                      0x84DC
+#define GL_TEXTURE29                      0x84DD
+#define GL_TEXTURE30                      0x84DE
+#define GL_TEXTURE31                      0x84DF
+#define GL_ACTIVE_TEXTURE                 0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE          0x84E1
+#define GL_MAX_TEXTURE_UNITS              0x84E2
+#define GL_TRANSPOSE_MODELVIEW_MATRIX     0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX    0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX       0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX         0x84E6
+#define GL_MULTISAMPLE                    0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE       0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE            0x809F
+#define GL_SAMPLE_COVERAGE                0x80A0
+#define GL_SAMPLE_BUFFERS                 0x80A8
+#define GL_SAMPLES                        0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE          0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT         0x80AB
+#define GL_MULTISAMPLE_BIT                0x20000000
+#define GL_NORMAL_MAP                     0x8511
+#define GL_REFLECTION_MAP                 0x8512
+#define GL_TEXTURE_CUBE_MAP               0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP       0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X    0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X    0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y    0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y    0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z    0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z    0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP         0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE      0x851C
+#define GL_COMPRESSED_ALPHA               0x84E9
+#define GL_COMPRESSED_LUMINANCE           0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA     0x84EB
+#define GL_COMPRESSED_INTENSITY           0x84EC
+#define GL_COMPRESSED_RGB                 0x84ED
+#define GL_COMPRESSED_RGBA                0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT       0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE  0x86A0
+#define GL_TEXTURE_COMPRESSED             0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS     0x86A3
+#define GL_CLAMP_TO_BORDER                0x812D
+#define GL_CLAMP_TO_BORDER_SGIS           0x812D
+#define GL_COMBINE                        0x8570
+#define GL_COMBINE_RGB                    0x8571
+#define GL_COMBINE_ALPHA                  0x8572
+#define GL_SOURCE0_RGB                    0x8580
+#define GL_SOURCE1_RGB                    0x8581
+#define GL_SOURCE2_RGB                    0x8582
+#define GL_SOURCE0_ALPHA                  0x8588
+#define GL_SOURCE1_ALPHA                  0x8589
+#define GL_SOURCE2_ALPHA                  0x858A
+#define GL_OPERAND0_RGB                   0x8590
+#define GL_OPERAND1_RGB                   0x8591
+#define GL_OPERAND2_RGB                   0x8592
+#define GL_OPERAND0_ALPHA                 0x8598
+#define GL_OPERAND1_ALPHA                 0x8599
+#define GL_OPERAND2_ALPHA                 0x859A
+#define GL_RGB_SCALE                      0x8573
+#define GL_ADD_SIGNED                     0x8574
+#define GL_INTERPOLATE                    0x8575
+#define GL_SUBTRACT                       0x84E7
+#define GL_CONSTANT                       0x8576
+#define GL_PRIMARY_COLOR                  0x8577
+#define GL_PREVIOUS                       0x8578
+#define GL_DOT3_RGB                       0x86AE
+#define GL_DOT3_RGBA                      0x86AF
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_BLEND_DST_RGB                  0x80C8
+#define GL_BLEND_SRC_RGB                  0x80C9
+#define GL_BLEND_DST_ALPHA                0x80CA
+#define GL_BLEND_SRC_ALPHA                0x80CB
+#define GL_POINT_SIZE_MIN                 0x8126
+#define GL_POINT_SIZE_MAX                 0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE      0x8128
+#define GL_POINT_DISTANCE_ATTENUATION     0x8129
+#define GL_GENERATE_MIPMAP                0x8191
+#define GL_GENERATE_MIPMAP_HINT           0x8192
+#define GL_DEPTH_COMPONENT16              0x81A5
+#define GL_DEPTH_COMPONENT24              0x81A6
+#define GL_DEPTH_COMPONENT32              0x81A7
+#define GL_MIRRORED_REPEAT                0x8370
+#define GL_FOG_COORDINATE_SOURCE          0x8450
+#define GL_FOG_COORDINATE                 0x8451
+#define GL_FRAGMENT_DEPTH                 0x8452
+#define GL_CURRENT_FOG_COORDINATE         0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE      0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE    0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER   0x8456
+#define GL_FOG_COORDINATE_ARRAY           0x8457
+#define GL_COLOR_SUM                      0x8458
+#define GL_CURRENT_SECONDARY_COLOR        0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE     0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE     0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE   0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER  0x845D
+#define GL_SECONDARY_COLOR_ARRAY          0x845E
+#define GL_MAX_TEXTURE_LOD_BIAS           0x84FD
+#define GL_TEXTURE_FILTER_CONTROL         0x8500
+#define GL_TEXTURE_LOD_BIAS               0x8501
+#define GL_INCR_WRAP                      0x8507
+#define GL_DECR_WRAP                      0x8508
+#define GL_TEXTURE_DEPTH_SIZE             0x884A
+#define GL_DEPTH_TEXTURE_MODE             0x884B
+#define GL_TEXTURE_COMPARE_MODE           0x884C
+#define GL_TEXTURE_COMPARE_FUNC           0x884D
+#define GL_COMPARE_R_TO_TEXTURE           0x884E
+#endif
+
+#ifndef GL_VERSION_1_5
+#define GL_BUFFER_SIZE                    0x8764
+#define GL_BUFFER_USAGE                   0x8765
+#define GL_QUERY_COUNTER_BITS             0x8864
+#define GL_CURRENT_QUERY                  0x8865
+#define GL_QUERY_RESULT                   0x8866
+#define GL_QUERY_RESULT_AVAILABLE         0x8867
+#define GL_ARRAY_BUFFER                   0x8892
+#define GL_ELEMENT_ARRAY_BUFFER           0x8893
+#define GL_ARRAY_BUFFER_BINDING           0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING   0x8895
+#define GL_VERTEX_ARRAY_BUFFER_BINDING    0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING    0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING     0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING     0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING    0x889E
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F
+#define GL_READ_ONLY                      0x88B8
+#define GL_WRITE_ONLY                     0x88B9
+#define GL_READ_WRITE                     0x88BA
+#define GL_BUFFER_ACCESS                  0x88BB
+#define GL_BUFFER_MAPPED                  0x88BC
+#define GL_BUFFER_MAP_POINTER             0x88BD
+#define GL_STREAM_DRAW                    0x88E0
+#define GL_STREAM_READ                    0x88E1
+#define GL_STREAM_COPY                    0x88E2
+#define GL_STATIC_DRAW                    0x88E4
+#define GL_STATIC_READ                    0x88E5
+#define GL_STATIC_COPY                    0x88E6
+#define GL_DYNAMIC_DRAW                   0x88E8
+#define GL_DYNAMIC_READ                   0x88E9
+#define GL_DYNAMIC_COPY                   0x88EA
+#define GL_SAMPLES_PASSED                 0x8914
+#define GL_FOG_COORD_SOURCE               GL_FOG_COORDINATE_SOURCE
+#define GL_FOG_COORD                      GL_FOG_COORDINATE
+#define GL_CURRENT_FOG_COORD              GL_CURRENT_FOG_COORDINATE
+#define GL_FOG_COORD_ARRAY_TYPE           GL_FOG_COORDINATE_ARRAY_TYPE
+#define GL_FOG_COORD_ARRAY_STRIDE         GL_FOG_COORDINATE_ARRAY_STRIDE
+#define GL_FOG_COORD_ARRAY_POINTER        GL_FOG_COORDINATE_ARRAY_POINTER
+#define GL_FOG_COORD_ARRAY                GL_FOG_COORDINATE_ARRAY
+#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING
+#define GL_SRC0_RGB                       GL_SOURCE0_RGB
+#define GL_SRC1_RGB                       GL_SOURCE1_RGB
+#define GL_SRC2_RGB                       GL_SOURCE2_RGB
+#define GL_SRC0_ALPHA                     GL_SOURCE0_ALPHA
+#define GL_SRC1_ALPHA                     GL_SOURCE1_ALPHA
+#define GL_SRC2_ALPHA                     GL_SOURCE2_ALPHA
+#endif
+
+#ifndef GL_ARB_multitexture
+#define GL_TEXTURE0_ARB                   0x84C0
+#define GL_TEXTURE1_ARB                   0x84C1
+#define GL_TEXTURE2_ARB                   0x84C2
+#define GL_TEXTURE3_ARB                   0x84C3
+#define GL_TEXTURE4_ARB                   0x84C4
+#define GL_TEXTURE5_ARB                   0x84C5
+#define GL_TEXTURE6_ARB                   0x84C6
+#define GL_TEXTURE7_ARB                   0x84C7
+#define GL_TEXTURE8_ARB                   0x84C8
+#define GL_TEXTURE9_ARB                   0x84C9
+#define GL_TEXTURE10_ARB                  0x84CA
+#define GL_TEXTURE11_ARB                  0x84CB
+#define GL_TEXTURE12_ARB                  0x84CC
+#define GL_TEXTURE13_ARB                  0x84CD
+#define GL_TEXTURE14_ARB                  0x84CE
+#define GL_TEXTURE15_ARB                  0x84CF
+#define GL_TEXTURE16_ARB                  0x84D0
+#define GL_TEXTURE17_ARB                  0x84D1
+#define GL_TEXTURE18_ARB                  0x84D2
+#define GL_TEXTURE19_ARB                  0x84D3
+#define GL_TEXTURE20_ARB                  0x84D4
+#define GL_TEXTURE21_ARB                  0x84D5
+#define GL_TEXTURE22_ARB                  0x84D6
+#define GL_TEXTURE23_ARB                  0x84D7
+#define GL_TEXTURE24_ARB                  0x84D8
+#define GL_TEXTURE25_ARB                  0x84D9
+#define GL_TEXTURE26_ARB                  0x84DA
+#define GL_TEXTURE27_ARB                  0x84DB
+#define GL_TEXTURE28_ARB                  0x84DC
+#define GL_TEXTURE29_ARB                  0x84DD
+#define GL_TEXTURE30_ARB                  0x84DE
+#define GL_TEXTURE31_ARB                  0x84DF
+#define GL_ACTIVE_TEXTURE_ARB             0x84E0
+#define GL_CLIENT_ACTIVE_TEXTURE_ARB      0x84E1
+#define GL_MAX_TEXTURE_UNITS_ARB          0x84E2
+#endif
+
+#ifndef GL_ARB_transpose_matrix
+#define GL_TRANSPOSE_MODELVIEW_MATRIX_ARB 0x84E3
+#define GL_TRANSPOSE_PROJECTION_MATRIX_ARB 0x84E4
+#define GL_TRANSPOSE_TEXTURE_MATRIX_ARB   0x84E5
+#define GL_TRANSPOSE_COLOR_MATRIX_ARB     0x84E6
+#endif
+
+#ifndef GL_ARB_multisample
+#define GL_MULTISAMPLE_ARB                0x809D
+#define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB   0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_ARB        0x809F
+#define GL_SAMPLE_COVERAGE_ARB            0x80A0
+#define GL_SAMPLE_BUFFERS_ARB             0x80A8
+#define GL_SAMPLES_ARB                    0x80A9
+#define GL_SAMPLE_COVERAGE_VALUE_ARB      0x80AA
+#define GL_SAMPLE_COVERAGE_INVERT_ARB     0x80AB
+#define GL_MULTISAMPLE_BIT_ARB            0x20000000
+#endif
+
+#ifndef GL_ARB_texture_env_add
+#endif
+
+#ifndef GL_ARB_texture_cube_map
+#define GL_NORMAL_MAP_ARB                 0x8511
+#define GL_REFLECTION_MAP_ARB             0x8512
+#define GL_TEXTURE_CUBE_MAP_ARB           0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_ARB   0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP_ARB     0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB  0x851C
+#endif
+
+#ifndef GL_ARB_texture_compression
+#define GL_COMPRESSED_ALPHA_ARB           0x84E9
+#define GL_COMPRESSED_LUMINANCE_ARB       0x84EA
+#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB
+#define GL_COMPRESSED_INTENSITY_ARB       0x84EC
+#define GL_COMPRESSED_RGB_ARB             0x84ED
+#define GL_COMPRESSED_RGBA_ARB            0x84EE
+#define GL_TEXTURE_COMPRESSION_HINT_ARB   0x84EF
+#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0
+#define GL_TEXTURE_COMPRESSED_ARB         0x86A1
+#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2
+#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3
+#endif
+
+#ifndef GL_ARB_texture_border_clamp
+#define GL_CLAMP_TO_BORDER_ARB            0x812D
+#endif
+
+#ifndef GL_ARB_point_parameters
+#define GL_POINT_SIZE_MIN_ARB             0x8126
+#define GL_POINT_SIZE_MAX_ARB             0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_ARB  0x8128
+#define GL_POINT_DISTANCE_ATTENUATION_ARB 0x8129
+#endif
+
+#ifndef GL_ARB_vertex_blend
+#define GL_MAX_VERTEX_UNITS_ARB           0x86A4
+#define GL_ACTIVE_VERTEX_UNITS_ARB        0x86A5
+#define GL_WEIGHT_SUM_UNITY_ARB           0x86A6
+#define GL_VERTEX_BLEND_ARB               0x86A7
+#define GL_CURRENT_WEIGHT_ARB             0x86A8
+#define GL_WEIGHT_ARRAY_TYPE_ARB          0x86A9
+#define GL_WEIGHT_ARRAY_STRIDE_ARB        0x86AA
+#define GL_WEIGHT_ARRAY_SIZE_ARB          0x86AB
+#define GL_WEIGHT_ARRAY_POINTER_ARB       0x86AC
+#define GL_WEIGHT_ARRAY_ARB               0x86AD
+#define GL_MODELVIEW0_ARB                 0x1700
+#define GL_MODELVIEW1_ARB                 0x850A
+#define GL_MODELVIEW2_ARB                 0x8722
+#define GL_MODELVIEW3_ARB                 0x8723
+#define GL_MODELVIEW4_ARB                 0x8724
+#define GL_MODELVIEW5_ARB                 0x8725
+#define GL_MODELVIEW6_ARB                 0x8726
+#define GL_MODELVIEW7_ARB                 0x8727
+#define GL_MODELVIEW8_ARB                 0x8728
+#define GL_MODELVIEW9_ARB                 0x8729
+#define GL_MODELVIEW10_ARB                0x872A
+#define GL_MODELVIEW11_ARB                0x872B
+#define GL_MODELVIEW12_ARB                0x872C
+#define GL_MODELVIEW13_ARB                0x872D
+#define GL_MODELVIEW14_ARB                0x872E
+#define GL_MODELVIEW15_ARB                0x872F
+#define GL_MODELVIEW16_ARB                0x8730
+#define GL_MODELVIEW17_ARB                0x8731
+#define GL_MODELVIEW18_ARB                0x8732
+#define GL_MODELVIEW19_ARB                0x8733
+#define GL_MODELVIEW20_ARB                0x8734
+#define GL_MODELVIEW21_ARB                0x8735
+#define GL_MODELVIEW22_ARB                0x8736
+#define GL_MODELVIEW23_ARB                0x8737
+#define GL_MODELVIEW24_ARB                0x8738
+#define GL_MODELVIEW25_ARB                0x8739
+#define GL_MODELVIEW26_ARB                0x873A
+#define GL_MODELVIEW27_ARB                0x873B
+#define GL_MODELVIEW28_ARB                0x873C
+#define GL_MODELVIEW29_ARB                0x873D
+#define GL_MODELVIEW30_ARB                0x873E
+#define GL_MODELVIEW31_ARB                0x873F
+#endif
+
+#ifndef GL_ARB_matrix_palette
+#define GL_MATRIX_PALETTE_ARB             0x8840
+#define GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB 0x8841
+#define GL_MAX_PALETTE_MATRICES_ARB       0x8842
+#define GL_CURRENT_PALETTE_MATRIX_ARB     0x8843
+#define GL_MATRIX_INDEX_ARRAY_ARB         0x8844
+#define GL_CURRENT_MATRIX_INDEX_ARB       0x8845
+#define GL_MATRIX_INDEX_ARRAY_SIZE_ARB    0x8846
+#define GL_MATRIX_INDEX_ARRAY_TYPE_ARB    0x8847
+#define GL_MATRIX_INDEX_ARRAY_STRIDE_ARB  0x8848
+#define GL_MATRIX_INDEX_ARRAY_POINTER_ARB 0x8849
+#endif
+
+#ifndef GL_ARB_texture_env_combine
+#define GL_COMBINE_ARB                    0x8570
+#define GL_COMBINE_RGB_ARB                0x8571
+#define GL_COMBINE_ALPHA_ARB              0x8572
+#define GL_SOURCE0_RGB_ARB                0x8580
+#define GL_SOURCE1_RGB_ARB                0x8581
+#define GL_SOURCE2_RGB_ARB                0x8582
+#define GL_SOURCE0_ALPHA_ARB              0x8588
+#define GL_SOURCE1_ALPHA_ARB              0x8589
+#define GL_SOURCE2_ALPHA_ARB              0x858A
+#define GL_OPERAND0_RGB_ARB               0x8590
+#define GL_OPERAND1_RGB_ARB               0x8591
+#define GL_OPERAND2_RGB_ARB               0x8592
+#define GL_OPERAND0_ALPHA_ARB             0x8598
+#define GL_OPERAND1_ALPHA_ARB             0x8599
+#define GL_OPERAND2_ALPHA_ARB             0x859A
+#define GL_RGB_SCALE_ARB                  0x8573
+#define GL_ADD_SIGNED_ARB                 0x8574
+#define GL_INTERPOLATE_ARB                0x8575
+#define GL_SUBTRACT_ARB                   0x84E7
+#define GL_CONSTANT_ARB                   0x8576
+#define GL_PRIMARY_COLOR_ARB              0x8577
+#define GL_PREVIOUS_ARB                   0x8578
+#endif
+
+#ifndef GL_ARB_texture_env_crossbar
+#endif
+
+#ifndef GL_ARB_texture_env_dot3
+#define GL_DOT3_RGB_ARB                   0x86AE
+#define GL_DOT3_RGBA_ARB                  0x86AF
+#endif
+
+#ifndef GL_ARB_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_ARB            0x8370
+#endif
+
+#ifndef GL_ARB_depth_texture
+#define GL_DEPTH_COMPONENT16_ARB          0x81A5
+#define GL_DEPTH_COMPONENT24_ARB          0x81A6
+#define GL_DEPTH_COMPONENT32_ARB          0x81A7
+#define GL_TEXTURE_DEPTH_SIZE_ARB         0x884A
+#define GL_DEPTH_TEXTURE_MODE_ARB         0x884B
+#endif
+
+#ifndef GL_ARB_shadow
+#define GL_TEXTURE_COMPARE_MODE_ARB       0x884C
+#define GL_TEXTURE_COMPARE_FUNC_ARB       0x884D
+#define GL_COMPARE_R_TO_TEXTURE_ARB       0x884E
+#endif
+
+#ifndef GL_ARB_shadow_ambient
+#define GL_TEXTURE_COMPARE_FAIL_VALUE_ARB 0x80BF
+#endif
+
+#ifndef GL_ARB_window_pos
+#endif
+
+#ifndef GL_ARB_vertex_program
+#define GL_COLOR_SUM_ARB                  0x8458
+#define GL_VERTEX_PROGRAM_ARB             0x8620
+#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622
+#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB   0x8623
+#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624
+#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB   0x8625
+#define GL_CURRENT_VERTEX_ATTRIB_ARB      0x8626
+#define GL_PROGRAM_LENGTH_ARB             0x8627
+#define GL_PROGRAM_STRING_ARB             0x8628
+#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E
+#define GL_MAX_PROGRAM_MATRICES_ARB       0x862F
+#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640
+#define GL_CURRENT_MATRIX_ARB             0x8641
+#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB  0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB    0x8643
+#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645
+#define GL_PROGRAM_ERROR_POSITION_ARB     0x864B
+#define GL_PROGRAM_BINDING_ARB            0x8677
+#define GL_MAX_VERTEX_ATTRIBS_ARB         0x8869
+#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A
+#define GL_PROGRAM_ERROR_STRING_ARB       0x8874
+#define GL_PROGRAM_FORMAT_ASCII_ARB       0x8875
+#define GL_PROGRAM_FORMAT_ARB             0x8876
+#define GL_PROGRAM_INSTRUCTIONS_ARB       0x88A0
+#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB   0x88A1
+#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2
+#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3
+#define GL_PROGRAM_TEMPORARIES_ARB        0x88A4
+#define GL_MAX_PROGRAM_TEMPORARIES_ARB    0x88A5
+#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6
+#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7
+#define GL_PROGRAM_PARAMETERS_ARB         0x88A8
+#define GL_MAX_PROGRAM_PARAMETERS_ARB     0x88A9
+#define GL_PROGRAM_NATIVE_PARAMETERS_ARB  0x88AA
+#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB
+#define GL_PROGRAM_ATTRIBS_ARB            0x88AC
+#define GL_MAX_PROGRAM_ATTRIBS_ARB        0x88AD
+#define GL_PROGRAM_NATIVE_ATTRIBS_ARB     0x88AE
+#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF
+#define GL_PROGRAM_ADDRESS_REGISTERS_ARB  0x88B0
+#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1
+#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2
+#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3
+#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4
+#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5
+#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6
+#define GL_TRANSPOSE_CURRENT_MATRIX_ARB   0x88B7
+#define GL_MATRIX0_ARB                    0x88C0
+#define GL_MATRIX1_ARB                    0x88C1
+#define GL_MATRIX2_ARB                    0x88C2
+#define GL_MATRIX3_ARB                    0x88C3
+#define GL_MATRIX4_ARB                    0x88C4
+#define GL_MATRIX5_ARB                    0x88C5
+#define GL_MATRIX6_ARB                    0x88C6
+#define GL_MATRIX7_ARB                    0x88C7
+#define GL_MATRIX8_ARB                    0x88C8
+#define GL_MATRIX9_ARB                    0x88C9
+#define GL_MATRIX10_ARB                   0x88CA
+#define GL_MATRIX11_ARB                   0x88CB
+#define GL_MATRIX12_ARB                   0x88CC
+#define GL_MATRIX13_ARB                   0x88CD
+#define GL_MATRIX14_ARB                   0x88CE
+#define GL_MATRIX15_ARB                   0x88CF
+#define GL_MATRIX16_ARB                   0x88D0
+#define GL_MATRIX17_ARB                   0x88D1
+#define GL_MATRIX18_ARB                   0x88D2
+#define GL_MATRIX19_ARB                   0x88D3
+#define GL_MATRIX20_ARB                   0x88D4
+#define GL_MATRIX21_ARB                   0x88D5
+#define GL_MATRIX22_ARB                   0x88D6
+#define GL_MATRIX23_ARB                   0x88D7
+#define GL_MATRIX24_ARB                   0x88D8
+#define GL_MATRIX25_ARB                   0x88D9
+#define GL_MATRIX26_ARB                   0x88DA
+#define GL_MATRIX27_ARB                   0x88DB
+#define GL_MATRIX28_ARB                   0x88DC
+#define GL_MATRIX29_ARB                   0x88DD
+#define GL_MATRIX30_ARB                   0x88DE
+#define GL_MATRIX31_ARB                   0x88DF
+#endif
+
+#ifndef GL_ARB_fragment_program
+#define GL_FRAGMENT_PROGRAM_ARB           0x8804
+#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB   0x8805
+#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB   0x8806
+#define GL_PROGRAM_TEX_INDIRECTIONS_ARB   0x8807
+#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808
+#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809
+#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A
+#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B
+#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C
+#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D
+#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E
+#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F
+#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810
+#define GL_MAX_TEXTURE_COORDS_ARB         0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB    0x8872
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+#define GL_BUFFER_SIZE_ARB                0x8764
+#define GL_BUFFER_USAGE_ARB               0x8765
+#define GL_ARRAY_BUFFER_ARB               0x8892
+#define GL_ELEMENT_ARRAY_BUFFER_ARB       0x8893
+#define GL_ARRAY_BUFFER_BINDING_ARB       0x8894
+#define GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
+#define GL_VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
+#define GL_NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
+#define GL_COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
+#define GL_INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
+#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
+#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
+#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
+#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
+#define GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
+#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
+#define GL_READ_ONLY_ARB                  0x88B8
+#define GL_WRITE_ONLY_ARB                 0x88B9
+#define GL_READ_WRITE_ARB                 0x88BA
+#define GL_BUFFER_ACCESS_ARB              0x88BB
+#define GL_BUFFER_MAPPED_ARB              0x88BC
+#define GL_BUFFER_MAP_POINTER_ARB         0x88BD
+#define GL_STREAM_DRAW_ARB                0x88E0
+#define GL_STREAM_READ_ARB                0x88E1
+#define GL_STREAM_COPY_ARB                0x88E2
+#define GL_STATIC_DRAW_ARB                0x88E4
+#define GL_STATIC_READ_ARB                0x88E5
+#define GL_STATIC_COPY_ARB                0x88E6
+#define GL_DYNAMIC_DRAW_ARB               0x88E8
+#define GL_DYNAMIC_READ_ARB               0x88E9
+#define GL_DYNAMIC_COPY_ARB               0x88EA
+#endif
+
+#ifndef GL_ARB_occlusion_query
+#define GL_QUERY_COUNTER_BITS_ARB         0x8864
+#define GL_CURRENT_QUERY_ARB              0x8865
+#define GL_QUERY_RESULT_ARB               0x8866
+#define GL_QUERY_RESULT_AVAILABLE_ARB     0x8867
+#define GL_SAMPLES_PASSED_ARB             0x8914
+#endif
+
+#ifndef GL_ARB_shader_objects
+#define GL_PROGRAM_OBJECT_ARB             0x8B40
+#define GL_SHADER_OBJECT_ARB              0x8B48
+#define GL_OBJECT_TYPE_ARB                0x8B4E
+#define GL_OBJECT_SUBTYPE_ARB             0x8B4F
+#define GL_FLOAT_VEC2_ARB                 0x8B50
+#define GL_FLOAT_VEC3_ARB                 0x8B51
+#define GL_FLOAT_VEC4_ARB                 0x8B52
+#define GL_INT_VEC2_ARB                   0x8B53
+#define GL_INT_VEC3_ARB                   0x8B54
+#define GL_INT_VEC4_ARB                   0x8B55
+#define GL_BOOL_ARB                       0x8B56
+#define GL_BOOL_VEC2_ARB                  0x8B57
+#define GL_BOOL_VEC3_ARB                  0x8B58
+#define GL_BOOL_VEC4_ARB                  0x8B59
+#define GL_FLOAT_MAT2_ARB                 0x8B5A
+#define GL_FLOAT_MAT3_ARB                 0x8B5B
+#define GL_FLOAT_MAT4_ARB                 0x8B5C
+#define GL_OBJECT_DELETE_STATUS_ARB       0x8B80
+#define GL_OBJECT_COMPILE_STATUS_ARB      0x8B81
+#define GL_OBJECT_LINK_STATUS_ARB         0x8B82
+#define GL_OBJECT_VALIDATE_STATUS_ARB     0x8B83
+#define GL_OBJECT_INFO_LOG_LENGTH_ARB     0x8B84
+#define GL_OBJECT_ATTACHED_OBJECTS_ARB    0x8B85
+#define GL_OBJECT_ACTIVE_UNIFORMS_ARB     0x8B86
+#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87
+#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88
+#endif
+
+#ifndef GL_ARB_vertex_shader
+#define GL_VERTEX_SHADER_ARB              0x8B31
+#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A
+#define GL_MAX_VARYING_FLOATS_ARB         0x8B4B
+#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C
+#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D
+#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB   0x8B89
+#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A
+#endif
+
+#ifndef GL_ARB_fragment_shader
+#define GL_FRAGMENT_SHADER_ARB            0x8B30
+#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49
+#endif
+
+#ifndef GL_ARB_shading_language_100
+#endif
+
+#ifndef GL_ARB_texture_non_power_of_two
+#endif
+
+#ifndef GL_ARB_point_sprite
+#define GL_POINT_SPRITE_ARB               0x8861
+#define GL_COORD_REPLACE_ARB              0x8862
+#endif
+
+#ifndef GL_ARB_fragment_program_shadow
+#endif
+
+#ifndef GL_EXT_abgr
+#define GL_ABGR_EXT                       0x8000
+#endif
+
+#ifndef GL_EXT_blend_color
+#define GL_CONSTANT_COLOR_EXT             0x8001
+#define GL_ONE_MINUS_CONSTANT_COLOR_EXT   0x8002
+#define GL_CONSTANT_ALPHA_EXT             0x8003
+#define GL_ONE_MINUS_CONSTANT_ALPHA_EXT   0x8004
+#define GL_BLEND_COLOR_EXT                0x8005
+#endif
+
+#ifndef GL_EXT_polygon_offset
+#define GL_POLYGON_OFFSET_EXT             0x8037
+#define GL_POLYGON_OFFSET_FACTOR_EXT      0x8038
+#define GL_POLYGON_OFFSET_BIAS_EXT        0x8039
+#endif
+
+#ifndef GL_EXT_texture
+#define GL_ALPHA4_EXT                     0x803B
+#define GL_ALPHA8_EXT                     0x803C
+#define GL_ALPHA12_EXT                    0x803D
+#define GL_ALPHA16_EXT                    0x803E
+#define GL_LUMINANCE4_EXT                 0x803F
+#define GL_LUMINANCE8_EXT                 0x8040
+#define GL_LUMINANCE12_EXT                0x8041
+#define GL_LUMINANCE16_EXT                0x8042
+#define GL_LUMINANCE4_ALPHA4_EXT          0x8043
+#define GL_LUMINANCE6_ALPHA2_EXT          0x8044
+#define GL_LUMINANCE8_ALPHA8_EXT          0x8045
+#define GL_LUMINANCE12_ALPHA4_EXT         0x8046
+#define GL_LUMINANCE12_ALPHA12_EXT        0x8047
+#define GL_LUMINANCE16_ALPHA16_EXT        0x8048
+#define GL_INTENSITY_EXT                  0x8049
+#define GL_INTENSITY4_EXT                 0x804A
+#define GL_INTENSITY8_EXT                 0x804B
+#define GL_INTENSITY12_EXT                0x804C
+#define GL_INTENSITY16_EXT                0x804D
+#define GL_RGB2_EXT                       0x804E
+#define GL_RGB4_EXT                       0x804F
+#define GL_RGB5_EXT                       0x8050
+#define GL_RGB8_EXT                       0x8051
+#define GL_RGB10_EXT                      0x8052
+#define GL_RGB12_EXT                      0x8053
+#define GL_RGB16_EXT                      0x8054
+#define GL_RGBA2_EXT                      0x8055
+#define GL_RGBA4_EXT                      0x8056
+#define GL_RGB5_A1_EXT                    0x8057
+#define GL_RGBA8_EXT                      0x8058
+#define GL_RGB10_A2_EXT                   0x8059
+#define GL_RGBA12_EXT                     0x805A
+#define GL_RGBA16_EXT                     0x805B
+#define GL_TEXTURE_RED_SIZE_EXT           0x805C
+#define GL_TEXTURE_GREEN_SIZE_EXT         0x805D
+#define GL_TEXTURE_BLUE_SIZE_EXT          0x805E
+#define GL_TEXTURE_ALPHA_SIZE_EXT         0x805F
+#define GL_TEXTURE_LUMINANCE_SIZE_EXT     0x8060
+#define GL_TEXTURE_INTENSITY_SIZE_EXT     0x8061
+#define GL_REPLACE_EXT                    0x8062
+#define GL_PROXY_TEXTURE_1D_EXT           0x8063
+#define GL_PROXY_TEXTURE_2D_EXT           0x8064
+#define GL_TEXTURE_TOO_LARGE_EXT          0x8065
+#endif
+
+#ifndef GL_EXT_texture3D
+#define GL_PACK_SKIP_IMAGES_EXT           0x806B
+#define GL_PACK_IMAGE_HEIGHT_EXT          0x806C
+#define GL_UNPACK_SKIP_IMAGES_EXT         0x806D
+#define GL_UNPACK_IMAGE_HEIGHT_EXT        0x806E
+#define GL_TEXTURE_3D_EXT                 0x806F
+#define GL_PROXY_TEXTURE_3D_EXT           0x8070
+#define GL_TEXTURE_DEPTH_EXT              0x8071
+#define GL_TEXTURE_WRAP_R_EXT             0x8072
+#define GL_MAX_3D_TEXTURE_SIZE_EXT        0x8073
+#endif
+
+#ifndef GL_SGIS_texture_filter4
+#define GL_FILTER4_SGIS                   0x8146
+#define GL_TEXTURE_FILTER4_SIZE_SGIS      0x8147
+#endif
+
+#ifndef GL_EXT_subtexture
+#endif
+
+#ifndef GL_EXT_copy_texture
+#endif
+
+#ifndef GL_EXT_histogram
+#define GL_HISTOGRAM_EXT                  0x8024
+#define GL_PROXY_HISTOGRAM_EXT            0x8025
+#define GL_HISTOGRAM_WIDTH_EXT            0x8026
+#define GL_HISTOGRAM_FORMAT_EXT           0x8027
+#define GL_HISTOGRAM_RED_SIZE_EXT         0x8028
+#define GL_HISTOGRAM_GREEN_SIZE_EXT       0x8029
+#define GL_HISTOGRAM_BLUE_SIZE_EXT        0x802A
+#define GL_HISTOGRAM_ALPHA_SIZE_EXT       0x802B
+#define GL_HISTOGRAM_LUMINANCE_SIZE_EXT   0x802C
+#define GL_HISTOGRAM_SINK_EXT             0x802D
+#define GL_MINMAX_EXT                     0x802E
+#define GL_MINMAX_FORMAT_EXT              0x802F
+#define GL_MINMAX_SINK_EXT                0x8030
+#define GL_TABLE_TOO_LARGE_EXT            0x8031
+#endif
+
+#ifndef GL_EXT_convolution
+#define GL_CONVOLUTION_1D_EXT             0x8010
+#define GL_CONVOLUTION_2D_EXT             0x8011
+#define GL_SEPARABLE_2D_EXT               0x8012
+#define GL_CONVOLUTION_BORDER_MODE_EXT    0x8013
+#define GL_CONVOLUTION_FILTER_SCALE_EXT   0x8014
+#define GL_CONVOLUTION_FILTER_BIAS_EXT    0x8015
+#define GL_REDUCE_EXT                     0x8016
+#define GL_CONVOLUTION_FORMAT_EXT         0x8017
+#define GL_CONVOLUTION_WIDTH_EXT          0x8018
+#define GL_CONVOLUTION_HEIGHT_EXT         0x8019
+#define GL_MAX_CONVOLUTION_WIDTH_EXT      0x801A
+#define GL_MAX_CONVOLUTION_HEIGHT_EXT     0x801B
+#define GL_POST_CONVOLUTION_RED_SCALE_EXT 0x801C
+#define GL_POST_CONVOLUTION_GREEN_SCALE_EXT 0x801D
+#define GL_POST_CONVOLUTION_BLUE_SCALE_EXT 0x801E
+#define GL_POST_CONVOLUTION_ALPHA_SCALE_EXT 0x801F
+#define GL_POST_CONVOLUTION_RED_BIAS_EXT  0x8020
+#define GL_POST_CONVOLUTION_GREEN_BIAS_EXT 0x8021
+#define GL_POST_CONVOLUTION_BLUE_BIAS_EXT 0x8022
+#define GL_POST_CONVOLUTION_ALPHA_BIAS_EXT 0x8023
+#endif
+
+#ifndef GL_SGI_color_matrix
+#define GL_COLOR_MATRIX_SGI               0x80B1
+#define GL_COLOR_MATRIX_STACK_DEPTH_SGI   0x80B2
+#define GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI 0x80B3
+#define GL_POST_COLOR_MATRIX_RED_SCALE_SGI 0x80B4
+#define GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI 0x80B5
+#define GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI 0x80B6
+#define GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI 0x80B7
+#define GL_POST_COLOR_MATRIX_RED_BIAS_SGI 0x80B8
+#define GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI 0x80B9
+#define GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI 0x80BA
+#define GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI 0x80BB
+#endif
+
+#ifndef GL_SGI_color_table
+#define GL_COLOR_TABLE_SGI                0x80D0
+#define GL_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D1
+#define GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D2
+#define GL_PROXY_COLOR_TABLE_SGI          0x80D3
+#define GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI 0x80D4
+#define GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI 0x80D5
+#define GL_COLOR_TABLE_SCALE_SGI          0x80D6
+#define GL_COLOR_TABLE_BIAS_SGI           0x80D7
+#define GL_COLOR_TABLE_FORMAT_SGI         0x80D8
+#define GL_COLOR_TABLE_WIDTH_SGI          0x80D9
+#define GL_COLOR_TABLE_RED_SIZE_SGI       0x80DA
+#define GL_COLOR_TABLE_GREEN_SIZE_SGI     0x80DB
+#define GL_COLOR_TABLE_BLUE_SIZE_SGI      0x80DC
+#define GL_COLOR_TABLE_ALPHA_SIZE_SGI     0x80DD
+#define GL_COLOR_TABLE_LUMINANCE_SIZE_SGI 0x80DE
+#define GL_COLOR_TABLE_INTENSITY_SIZE_SGI 0x80DF
+#endif
+
+#ifndef GL_SGIS_pixel_texture
+#define GL_PIXEL_TEXTURE_SGIS             0x8353
+#define GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS 0x8354
+#define GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS 0x8355
+#define GL_PIXEL_GROUP_COLOR_SGIS         0x8356
+#endif
+
+#ifndef GL_SGIX_pixel_texture
+#define GL_PIXEL_TEX_GEN_SGIX             0x8139
+#define GL_PIXEL_TEX_GEN_MODE_SGIX        0x832B
+#endif
+
+#ifndef GL_SGIS_texture4D
+#define GL_PACK_SKIP_VOLUMES_SGIS         0x8130
+#define GL_PACK_IMAGE_DEPTH_SGIS          0x8131
+#define GL_UNPACK_SKIP_VOLUMES_SGIS       0x8132
+#define GL_UNPACK_IMAGE_DEPTH_SGIS        0x8133
+#define GL_TEXTURE_4D_SGIS                0x8134
+#define GL_PROXY_TEXTURE_4D_SGIS          0x8135
+#define GL_TEXTURE_4DSIZE_SGIS            0x8136
+#define GL_TEXTURE_WRAP_Q_SGIS            0x8137
+#define GL_MAX_4D_TEXTURE_SIZE_SGIS       0x8138
+#define GL_TEXTURE_4D_BINDING_SGIS        0x814F
+#endif
+
+#ifndef GL_SGI_texture_color_table
+#define GL_TEXTURE_COLOR_TABLE_SGI        0x80BC
+#define GL_PROXY_TEXTURE_COLOR_TABLE_SGI  0x80BD
+#endif
+
+#ifndef GL_EXT_cmyka
+#define GL_CMYK_EXT                       0x800C
+#define GL_CMYKA_EXT                      0x800D
+#define GL_PACK_CMYK_HINT_EXT             0x800E
+#define GL_UNPACK_CMYK_HINT_EXT           0x800F
+#endif
+
+#ifndef GL_EXT_texture_object
+#define GL_TEXTURE_PRIORITY_EXT           0x8066
+#define GL_TEXTURE_RESIDENT_EXT           0x8067
+#define GL_TEXTURE_1D_BINDING_EXT         0x8068
+#define GL_TEXTURE_2D_BINDING_EXT         0x8069
+#define GL_TEXTURE_3D_BINDING_EXT         0x806A
+#endif
+
+#ifndef GL_SGIS_detail_texture
+#define GL_DETAIL_TEXTURE_2D_SGIS         0x8095
+#define GL_DETAIL_TEXTURE_2D_BINDING_SGIS 0x8096
+#define GL_LINEAR_DETAIL_SGIS             0x8097
+#define GL_LINEAR_DETAIL_ALPHA_SGIS       0x8098
+#define GL_LINEAR_DETAIL_COLOR_SGIS       0x8099
+#define GL_DETAIL_TEXTURE_LEVEL_SGIS      0x809A
+#define GL_DETAIL_TEXTURE_MODE_SGIS       0x809B
+#define GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS 0x809C
+#endif
+
+#ifndef GL_SGIS_sharpen_texture
+#define GL_LINEAR_SHARPEN_SGIS            0x80AD
+#define GL_LINEAR_SHARPEN_ALPHA_SGIS      0x80AE
+#define GL_LINEAR_SHARPEN_COLOR_SGIS      0x80AF
+#define GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS 0x80B0
+#endif
+
+#ifndef GL_EXT_packed_pixels
+#define GL_UNSIGNED_BYTE_3_3_2_EXT        0x8032
+#define GL_UNSIGNED_SHORT_4_4_4_4_EXT     0x8033
+#define GL_UNSIGNED_SHORT_5_5_5_1_EXT     0x8034
+#define GL_UNSIGNED_INT_8_8_8_8_EXT       0x8035
+#define GL_UNSIGNED_INT_10_10_10_2_EXT    0x8036
+#endif
+
+#ifndef GL_SGIS_texture_lod
+#define GL_TEXTURE_MIN_LOD_SGIS           0x813A
+#define GL_TEXTURE_MAX_LOD_SGIS           0x813B
+#define GL_TEXTURE_BASE_LEVEL_SGIS        0x813C
+#define GL_TEXTURE_MAX_LEVEL_SGIS         0x813D
+#endif
+
+#ifndef GL_SGIS_multisample
+#define GL_MULTISAMPLE_SGIS               0x809D
+#define GL_SAMPLE_ALPHA_TO_MASK_SGIS      0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_SGIS       0x809F
+#define GL_SAMPLE_MASK_SGIS               0x80A0
+#define GL_1PASS_SGIS                     0x80A1
+#define GL_2PASS_0_SGIS                   0x80A2
+#define GL_2PASS_1_SGIS                   0x80A3
+#define GL_4PASS_0_SGIS                   0x80A4
+#define GL_4PASS_1_SGIS                   0x80A5
+#define GL_4PASS_2_SGIS                   0x80A6
+#define GL_4PASS_3_SGIS                   0x80A7
+#define GL_SAMPLE_BUFFERS_SGIS            0x80A8
+#define GL_SAMPLES_SGIS                   0x80A9
+#define GL_SAMPLE_MASK_VALUE_SGIS         0x80AA
+#define GL_SAMPLE_MASK_INVERT_SGIS        0x80AB
+#define GL_SAMPLE_PATTERN_SGIS            0x80AC
+#endif
+
+#ifndef GL_EXT_rescale_normal
+#define GL_RESCALE_NORMAL_EXT             0x803A
+#endif
+
+#ifndef GL_EXT_vertex_array
+#define GL_VERTEX_ARRAY_EXT               0x8074
+#define GL_NORMAL_ARRAY_EXT               0x8075
+#define GL_COLOR_ARRAY_EXT                0x8076
+#define GL_INDEX_ARRAY_EXT                0x8077
+#define GL_TEXTURE_COORD_ARRAY_EXT        0x8078
+#define GL_EDGE_FLAG_ARRAY_EXT            0x8079
+#define GL_VERTEX_ARRAY_SIZE_EXT          0x807A
+#define GL_VERTEX_ARRAY_TYPE_EXT          0x807B
+#define GL_VERTEX_ARRAY_STRIDE_EXT        0x807C
+#define GL_VERTEX_ARRAY_COUNT_EXT         0x807D
+#define GL_NORMAL_ARRAY_TYPE_EXT          0x807E
+#define GL_NORMAL_ARRAY_STRIDE_EXT        0x807F
+#define GL_NORMAL_ARRAY_COUNT_EXT         0x8080
+#define GL_COLOR_ARRAY_SIZE_EXT           0x8081
+#define GL_COLOR_ARRAY_TYPE_EXT           0x8082
+#define GL_COLOR_ARRAY_STRIDE_EXT         0x8083
+#define GL_COLOR_ARRAY_COUNT_EXT          0x8084
+#define GL_INDEX_ARRAY_TYPE_EXT           0x8085
+#define GL_INDEX_ARRAY_STRIDE_EXT         0x8086
+#define GL_INDEX_ARRAY_COUNT_EXT          0x8087
+#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT   0x8088
+#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT   0x8089
+#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A
+#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT  0x808B
+#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT     0x808C
+#define GL_EDGE_FLAG_ARRAY_COUNT_EXT      0x808D
+#define GL_VERTEX_ARRAY_POINTER_EXT       0x808E
+#define GL_NORMAL_ARRAY_POINTER_EXT       0x808F
+#define GL_COLOR_ARRAY_POINTER_EXT        0x8090
+#define GL_INDEX_ARRAY_POINTER_EXT        0x8091
+#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092
+#define GL_EDGE_FLAG_ARRAY_POINTER_EXT    0x8093
+#endif
+
+#ifndef GL_EXT_misc_attribute
+#endif
+
+#ifndef GL_SGIS_generate_mipmap
+#define GL_GENERATE_MIPMAP_SGIS           0x8191
+#define GL_GENERATE_MIPMAP_HINT_SGIS      0x8192
+#endif
+
+#ifndef GL_SGIX_clipmap
+#define GL_LINEAR_CLIPMAP_LINEAR_SGIX     0x8170
+#define GL_TEXTURE_CLIPMAP_CENTER_SGIX    0x8171
+#define GL_TEXTURE_CLIPMAP_FRAME_SGIX     0x8172
+#define GL_TEXTURE_CLIPMAP_OFFSET_SGIX    0x8173
+#define GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8174
+#define GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX 0x8175
+#define GL_TEXTURE_CLIPMAP_DEPTH_SGIX     0x8176
+#define GL_MAX_CLIPMAP_DEPTH_SGIX         0x8177
+#define GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX 0x8178
+#define GL_NEAREST_CLIPMAP_NEAREST_SGIX   0x844D
+#define GL_NEAREST_CLIPMAP_LINEAR_SGIX    0x844E
+#define GL_LINEAR_CLIPMAP_NEAREST_SGIX    0x844F
+#endif
+
+#ifndef GL_SGIX_shadow
+#define GL_TEXTURE_COMPARE_SGIX           0x819A
+#define GL_TEXTURE_COMPARE_OPERATOR_SGIX  0x819B
+#define GL_TEXTURE_LEQUAL_R_SGIX          0x819C
+#define GL_TEXTURE_GEQUAL_R_SGIX          0x819D
+#endif
+
+#ifndef GL_SGIS_texture_edge_clamp
+#define GL_CLAMP_TO_EDGE_SGIS             0x812F
+#endif
+
+#ifndef GL_EXT_blend_minmax
+#define GL_FUNC_ADD_EXT                   0x8006
+#define GL_MIN_EXT                        0x8007
+#define GL_MAX_EXT                        0x8008
+#define GL_BLEND_EQUATION_EXT             0x8009
+#endif
+
+#ifndef GL_EXT_blend_subtract
+#define GL_FUNC_SUBTRACT_EXT              0x800A
+#define GL_FUNC_REVERSE_SUBTRACT_EXT      0x800B
+#endif
+
+#ifndef GL_EXT_blend_logic_op
+#endif
+
+#ifndef GL_SGIX_interlace
+#define GL_INTERLACE_SGIX                 0x8094
+#endif
+
+#ifndef GL_SGIX_pixel_tiles
+#define GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX 0x813E
+#define GL_PIXEL_TILE_CACHE_INCREMENT_SGIX 0x813F
+#define GL_PIXEL_TILE_WIDTH_SGIX          0x8140
+#define GL_PIXEL_TILE_HEIGHT_SGIX         0x8141
+#define GL_PIXEL_TILE_GRID_WIDTH_SGIX     0x8142
+#define GL_PIXEL_TILE_GRID_HEIGHT_SGIX    0x8143
+#define GL_PIXEL_TILE_GRID_DEPTH_SGIX     0x8144
+#define GL_PIXEL_TILE_CACHE_SIZE_SGIX     0x8145
+#endif
+
+#ifndef GL_SGIS_texture_select
+#define GL_DUAL_ALPHA4_SGIS               0x8110
+#define GL_DUAL_ALPHA8_SGIS               0x8111
+#define GL_DUAL_ALPHA12_SGIS              0x8112
+#define GL_DUAL_ALPHA16_SGIS              0x8113
+#define GL_DUAL_LUMINANCE4_SGIS           0x8114
+#define GL_DUAL_LUMINANCE8_SGIS           0x8115
+#define GL_DUAL_LUMINANCE12_SGIS          0x8116
+#define GL_DUAL_LUMINANCE16_SGIS          0x8117
+#define GL_DUAL_INTENSITY4_SGIS           0x8118
+#define GL_DUAL_INTENSITY8_SGIS           0x8119
+#define GL_DUAL_INTENSITY12_SGIS          0x811A
+#define GL_DUAL_INTENSITY16_SGIS          0x811B
+#define GL_DUAL_LUMINANCE_ALPHA4_SGIS     0x811C
+#define GL_DUAL_LUMINANCE_ALPHA8_SGIS     0x811D
+#define GL_QUAD_ALPHA4_SGIS               0x811E
+#define GL_QUAD_ALPHA8_SGIS               0x811F
+#define GL_QUAD_LUMINANCE4_SGIS           0x8120
+#define GL_QUAD_LUMINANCE8_SGIS           0x8121
+#define GL_QUAD_INTENSITY4_SGIS           0x8122
+#define GL_QUAD_INTENSITY8_SGIS           0x8123
+#define GL_DUAL_TEXTURE_SELECT_SGIS       0x8124
+#define GL_QUAD_TEXTURE_SELECT_SGIS       0x8125
+#endif
+
+#ifndef GL_SGIX_sprite
+#define GL_SPRITE_SGIX                    0x8148
+#define GL_SPRITE_MODE_SGIX               0x8149
+#define GL_SPRITE_AXIS_SGIX               0x814A
+#define GL_SPRITE_TRANSLATION_SGIX        0x814B
+#define GL_SPRITE_AXIAL_SGIX              0x814C
+#define GL_SPRITE_OBJECT_ALIGNED_SGIX     0x814D
+#define GL_SPRITE_EYE_ALIGNED_SGIX        0x814E
+#endif
+
+#ifndef GL_SGIX_texture_multi_buffer
+#define GL_TEXTURE_MULTI_BUFFER_HINT_SGIX 0x812E
+#endif
+
+#ifndef GL_EXT_point_parameters
+#define GL_POINT_SIZE_MIN_EXT             0x8126
+#define GL_POINT_SIZE_MAX_EXT             0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_EXT  0x8128
+#define GL_DISTANCE_ATTENUATION_EXT       0x8129
+#endif
+
+#ifndef GL_SGIS_point_parameters
+#define GL_POINT_SIZE_MIN_SGIS            0x8126
+#define GL_POINT_SIZE_MAX_SGIS            0x8127
+#define GL_POINT_FADE_THRESHOLD_SIZE_SGIS 0x8128
+#define GL_DISTANCE_ATTENUATION_SGIS      0x8129
+#endif
+
+#ifndef GL_SGIX_instruments
+#define GL_INSTRUMENT_BUFFER_POINTER_SGIX 0x8180
+#define GL_INSTRUMENT_MEASUREMENTS_SGIX   0x8181
+#endif
+
+#ifndef GL_SGIX_texture_scale_bias
+#define GL_POST_TEXTURE_FILTER_BIAS_SGIX  0x8179
+#define GL_POST_TEXTURE_FILTER_SCALE_SGIX 0x817A
+#define GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX 0x817B
+#define GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX 0x817C
+#endif
+
+#ifndef GL_SGIX_framezoom
+#define GL_FRAMEZOOM_SGIX                 0x818B
+#define GL_FRAMEZOOM_FACTOR_SGIX          0x818C
+#define GL_MAX_FRAMEZOOM_FACTOR_SGIX      0x818D
+#endif
+
+#ifndef GL_SGIX_tag_sample_buffer
+#endif
+
+#ifndef GL_FfdMaskSGIX
+#define GL_TEXTURE_DEFORMATION_BIT_SGIX   0x00000001
+#define GL_GEOMETRY_DEFORMATION_BIT_SGIX  0x00000002
+#endif
+
+#ifndef GL_SGIX_polynomial_ffd
+#define GL_GEOMETRY_DEFORMATION_SGIX      0x8194
+#define GL_TEXTURE_DEFORMATION_SGIX       0x8195
+#define GL_DEFORMATIONS_MASK_SGIX         0x8196
+#define GL_MAX_DEFORMATION_ORDER_SGIX     0x8197
+#endif
+
+#ifndef GL_SGIX_reference_plane
+#define GL_REFERENCE_PLANE_SGIX           0x817D
+#define GL_REFERENCE_PLANE_EQUATION_SGIX  0x817E
+#endif
+
+#ifndef GL_SGIX_flush_raster
+#endif
+
+#ifndef GL_SGIX_depth_texture
+#define GL_DEPTH_COMPONENT16_SGIX         0x81A5
+#define GL_DEPTH_COMPONENT24_SGIX         0x81A6
+#define GL_DEPTH_COMPONENT32_SGIX         0x81A7
+#endif
+
+#ifndef GL_SGIS_fog_function
+#define GL_FOG_FUNC_SGIS                  0x812A
+#define GL_FOG_FUNC_POINTS_SGIS           0x812B
+#define GL_MAX_FOG_FUNC_POINTS_SGIS       0x812C
+#endif
+
+#ifndef GL_SGIX_fog_offset
+#define GL_FOG_OFFSET_SGIX                0x8198
+#define GL_FOG_OFFSET_VALUE_SGIX          0x8199
+#endif
+
+#ifndef GL_HP_image_transform
+#define GL_IMAGE_SCALE_X_HP               0x8155
+#define GL_IMAGE_SCALE_Y_HP               0x8156
+#define GL_IMAGE_TRANSLATE_X_HP           0x8157
+#define GL_IMAGE_TRANSLATE_Y_HP           0x8158
+#define GL_IMAGE_ROTATE_ANGLE_HP          0x8159
+#define GL_IMAGE_ROTATE_ORIGIN_X_HP       0x815A
+#define GL_IMAGE_ROTATE_ORIGIN_Y_HP       0x815B
+#define GL_IMAGE_MAG_FILTER_HP            0x815C
+#define GL_IMAGE_MIN_FILTER_HP            0x815D
+#define GL_IMAGE_CUBIC_WEIGHT_HP          0x815E
+#define GL_CUBIC_HP                       0x815F
+#define GL_AVERAGE_HP                     0x8160
+#define GL_IMAGE_TRANSFORM_2D_HP          0x8161
+#define GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8162
+#define GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP 0x8163
+#endif
+
+#ifndef GL_HP_convolution_border_modes
+#define GL_IGNORE_BORDER_HP               0x8150
+#define GL_CONSTANT_BORDER_HP             0x8151
+#define GL_REPLICATE_BORDER_HP            0x8153
+#define GL_CONVOLUTION_BORDER_COLOR_HP    0x8154
+#endif
+
+#ifndef GL_INGR_palette_buffer
+#endif
+
+#ifndef GL_SGIX_texture_add_env
+#define GL_TEXTURE_ENV_BIAS_SGIX          0x80BE
+#endif
+
+#ifndef GL_EXT_color_subtable
+#endif
+
+#ifndef GL_PGI_vertex_hints
+#define GL_VERTEX_DATA_HINT_PGI           0x1A22A
+#define GL_VERTEX_CONSISTENT_HINT_PGI     0x1A22B
+#define GL_MATERIAL_SIDE_HINT_PGI         0x1A22C
+#define GL_MAX_VERTEX_HINT_PGI            0x1A22D
+#define GL_COLOR3_BIT_PGI                 0x00010000
+#define GL_COLOR4_BIT_PGI                 0x00020000
+#define GL_EDGEFLAG_BIT_PGI               0x00040000
+#define GL_INDEX_BIT_PGI                  0x00080000
+#define GL_MAT_AMBIENT_BIT_PGI            0x00100000
+#define GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI 0x00200000
+#define GL_MAT_DIFFUSE_BIT_PGI            0x00400000
+#define GL_MAT_EMISSION_BIT_PGI           0x00800000
+#define GL_MAT_COLOR_INDEXES_BIT_PGI      0x01000000
+#define GL_MAT_SHININESS_BIT_PGI          0x02000000
+#define GL_MAT_SPECULAR_BIT_PGI           0x04000000
+#define GL_NORMAL_BIT_PGI                 0x08000000
+#define GL_TEXCOORD1_BIT_PGI              0x10000000
+#define GL_TEXCOORD2_BIT_PGI              0x20000000
+#define GL_TEXCOORD3_BIT_PGI              0x40000000
+#define GL_TEXCOORD4_BIT_PGI              0x80000000
+#define GL_VERTEX23_BIT_PGI               0x00000004
+#define GL_VERTEX4_BIT_PGI                0x00000008
+#endif
+
+#ifndef GL_PGI_misc_hints
+#define GL_PREFER_DOUBLEBUFFER_HINT_PGI   0x1A1F8
+#define GL_CONSERVE_MEMORY_HINT_PGI       0x1A1FD
+#define GL_RECLAIM_MEMORY_HINT_PGI        0x1A1FE
+#define GL_NATIVE_GRAPHICS_HANDLE_PGI     0x1A202
+#define GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI 0x1A203
+#define GL_NATIVE_GRAPHICS_END_HINT_PGI   0x1A204
+#define GL_ALWAYS_FAST_HINT_PGI           0x1A20C
+#define GL_ALWAYS_SOFT_HINT_PGI           0x1A20D
+#define GL_ALLOW_DRAW_OBJ_HINT_PGI        0x1A20E
+#define GL_ALLOW_DRAW_WIN_HINT_PGI        0x1A20F
+#define GL_ALLOW_DRAW_FRG_HINT_PGI        0x1A210
+#define GL_ALLOW_DRAW_MEM_HINT_PGI        0x1A211
+#define GL_STRICT_DEPTHFUNC_HINT_PGI      0x1A216
+#define GL_STRICT_LIGHTING_HINT_PGI       0x1A217
+#define GL_STRICT_SCISSOR_HINT_PGI        0x1A218
+#define GL_FULL_STIPPLE_HINT_PGI          0x1A219
+#define GL_CLIP_NEAR_HINT_PGI             0x1A220
+#define GL_CLIP_FAR_HINT_PGI              0x1A221
+#define GL_WIDE_LINE_HINT_PGI             0x1A222
+#define GL_BACK_NORMALS_HINT_PGI          0x1A223
+#endif
+
+#ifndef GL_EXT_paletted_texture
+#define GL_COLOR_INDEX1_EXT               0x80E2
+#define GL_COLOR_INDEX2_EXT               0x80E3
+#define GL_COLOR_INDEX4_EXT               0x80E4
+#define GL_COLOR_INDEX8_EXT               0x80E5
+#define GL_COLOR_INDEX12_EXT              0x80E6
+#define GL_COLOR_INDEX16_EXT              0x80E7
+#define GL_TEXTURE_INDEX_SIZE_EXT         0x80ED
+#endif
+
+#ifndef GL_EXT_clip_volume_hint
+#define GL_CLIP_VOLUME_CLIPPING_HINT_EXT  0x80F0
+#endif
+
+#ifndef GL_SGIX_list_priority
+#define GL_LIST_PRIORITY_SGIX             0x8182
+#endif
+
+#ifndef GL_SGIX_ir_instrument1
+#define GL_IR_INSTRUMENT1_SGIX            0x817F
+#endif
+
+#ifndef GL_SGIX_calligraphic_fragment
+#define GL_CALLIGRAPHIC_FRAGMENT_SGIX     0x8183
+#endif
+
+#ifndef GL_SGIX_texture_lod_bias
+#define GL_TEXTURE_LOD_BIAS_S_SGIX        0x818E
+#define GL_TEXTURE_LOD_BIAS_T_SGIX        0x818F
+#define GL_TEXTURE_LOD_BIAS_R_SGIX        0x8190
+#endif
+
+#ifndef GL_SGIX_shadow_ambient
+#define GL_SHADOW_AMBIENT_SGIX            0x80BF
+#endif
+
+#ifndef GL_EXT_index_texture
+#endif
+
+#ifndef GL_EXT_index_material
+#define GL_INDEX_MATERIAL_EXT             0x81B8
+#define GL_INDEX_MATERIAL_PARAMETER_EXT   0x81B9
+#define GL_INDEX_MATERIAL_FACE_EXT        0x81BA
+#endif
+
+#ifndef GL_EXT_index_func
+#define GL_INDEX_TEST_EXT                 0x81B5
+#define GL_INDEX_TEST_FUNC_EXT            0x81B6
+#define GL_INDEX_TEST_REF_EXT             0x81B7
+#endif
+
+#ifndef GL_EXT_index_array_formats
+#define GL_IUI_V2F_EXT                    0x81AD
+#define GL_IUI_V3F_EXT                    0x81AE
+#define GL_IUI_N3F_V2F_EXT                0x81AF
+#define GL_IUI_N3F_V3F_EXT                0x81B0
+#define GL_T2F_IUI_V2F_EXT                0x81B1
+#define GL_T2F_IUI_V3F_EXT                0x81B2
+#define GL_T2F_IUI_N3F_V2F_EXT            0x81B3
+#define GL_T2F_IUI_N3F_V3F_EXT            0x81B4
+#endif
+
+#ifndef GL_EXT_compiled_vertex_array
+#define GL_ARRAY_ELEMENT_LOCK_FIRST_EXT   0x81A8
+#define GL_ARRAY_ELEMENT_LOCK_COUNT_EXT   0x81A9
+#endif
+
+#ifndef GL_EXT_cull_vertex
+#define GL_CULL_VERTEX_EXT                0x81AA
+#define GL_CULL_VERTEX_EYE_POSITION_EXT   0x81AB
+#define GL_CULL_VERTEX_OBJECT_POSITION_EXT 0x81AC
+#endif
+
+#ifndef GL_SGIX_ycrcb
+#define GL_YCRCB_422_SGIX                 0x81BB
+#define GL_YCRCB_444_SGIX                 0x81BC
+#endif
+
+#ifndef GL_SGIX_fragment_lighting
+#define GL_FRAGMENT_LIGHTING_SGIX         0x8400
+#define GL_FRAGMENT_COLOR_MATERIAL_SGIX   0x8401
+#define GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX 0x8402
+#define GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX 0x8403
+#define GL_MAX_FRAGMENT_LIGHTS_SGIX       0x8404
+#define GL_MAX_ACTIVE_LIGHTS_SGIX         0x8405
+#define GL_CURRENT_RASTER_NORMAL_SGIX     0x8406
+#define GL_LIGHT_ENV_MODE_SGIX            0x8407
+#define GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX 0x8408
+#define GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX 0x8409
+#define GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX 0x840A
+#define GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX 0x840B
+#define GL_FRAGMENT_LIGHT0_SGIX           0x840C
+#define GL_FRAGMENT_LIGHT1_SGIX           0x840D
+#define GL_FRAGMENT_LIGHT2_SGIX           0x840E
+#define GL_FRAGMENT_LIGHT3_SGIX           0x840F
+#define GL_FRAGMENT_LIGHT4_SGIX           0x8410
+#define GL_FRAGMENT_LIGHT5_SGIX           0x8411
+#define GL_FRAGMENT_LIGHT6_SGIX           0x8412
+#define GL_FRAGMENT_LIGHT7_SGIX           0x8413
+#endif
+
+#ifndef GL_IBM_rasterpos_clip
+#define GL_RASTER_POSITION_UNCLIPPED_IBM  0x19262
+#endif
+
+#ifndef GL_HP_texture_lighting
+#define GL_TEXTURE_LIGHTING_MODE_HP       0x8167
+#define GL_TEXTURE_POST_SPECULAR_HP       0x8168
+#define GL_TEXTURE_PRE_SPECULAR_HP        0x8169
+#endif
+
+#ifndef GL_EXT_draw_range_elements
+#define GL_MAX_ELEMENTS_VERTICES_EXT      0x80E8
+#define GL_MAX_ELEMENTS_INDICES_EXT       0x80E9
+#endif
+
+#ifndef GL_WIN_phong_shading
+#define GL_PHONG_WIN                      0x80EA
+#define GL_PHONG_HINT_WIN                 0x80EB
+#endif
+
+#ifndef GL_WIN_specular_fog
+#define GL_FOG_SPECULAR_TEXTURE_WIN       0x80EC
+#endif
+
+#ifndef GL_EXT_light_texture
+#define GL_FRAGMENT_MATERIAL_EXT          0x8349
+#define GL_FRAGMENT_NORMAL_EXT            0x834A
+#define GL_FRAGMENT_COLOR_EXT             0x834C
+#define GL_ATTENUATION_EXT                0x834D
+#define GL_SHADOW_ATTENUATION_EXT         0x834E
+#define GL_TEXTURE_APPLICATION_MODE_EXT   0x834F
+#define GL_TEXTURE_LIGHT_EXT              0x8350
+#define GL_TEXTURE_MATERIAL_FACE_EXT      0x8351
+#define GL_TEXTURE_MATERIAL_PARAMETER_EXT 0x8352
+/* reuse GL_FRAGMENT_DEPTH_EXT */
+#endif
+
+#ifndef GL_SGIX_blend_alpha_minmax
+#define GL_ALPHA_MIN_SGIX                 0x8320
+#define GL_ALPHA_MAX_SGIX                 0x8321
+#endif
+
+#ifndef GL_SGIX_impact_pixel_texture
+#define GL_PIXEL_TEX_GEN_Q_CEILING_SGIX   0x8184
+#define GL_PIXEL_TEX_GEN_Q_ROUND_SGIX     0x8185
+#define GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX     0x8186
+#define GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX 0x8187
+#define GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX 0x8188
+#define GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX    0x8189
+#define GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX    0x818A
+#endif
+
+#ifndef GL_EXT_bgra
+#define GL_BGR_EXT                        0x80E0
+#define GL_BGRA_EXT                       0x80E1
+#endif
+
+#ifndef GL_SGIX_async
+#define GL_ASYNC_MARKER_SGIX              0x8329
+#endif
+
+#ifndef GL_SGIX_async_pixel
+#define GL_ASYNC_TEX_IMAGE_SGIX           0x835C
+#define GL_ASYNC_DRAW_PIXELS_SGIX         0x835D
+#define GL_ASYNC_READ_PIXELS_SGIX         0x835E
+#define GL_MAX_ASYNC_TEX_IMAGE_SGIX       0x835F
+#define GL_MAX_ASYNC_DRAW_PIXELS_SGIX     0x8360
+#define GL_MAX_ASYNC_READ_PIXELS_SGIX     0x8361
+#endif
+
+#ifndef GL_SGIX_async_histogram
+#define GL_ASYNC_HISTOGRAM_SGIX           0x832C
+#define GL_MAX_ASYNC_HISTOGRAM_SGIX       0x832D
+#endif
+
+#ifndef GL_INTEL_texture_scissor
+#endif
+
+#ifndef GL_INTEL_parallel_arrays
+#define GL_PARALLEL_ARRAYS_INTEL          0x83F4
+#define GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL 0x83F5
+#define GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL 0x83F6
+#define GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL 0x83F7
+#define GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL 0x83F8
+#endif
+
+#ifndef GL_HP_occlusion_test
+#define GL_OCCLUSION_TEST_HP              0x8165
+#define GL_OCCLUSION_TEST_RESULT_HP       0x8166
+#endif
+
+#ifndef GL_EXT_pixel_transform
+#define GL_PIXEL_TRANSFORM_2D_EXT         0x8330
+#define GL_PIXEL_MAG_FILTER_EXT           0x8331
+#define GL_PIXEL_MIN_FILTER_EXT           0x8332
+#define GL_PIXEL_CUBIC_WEIGHT_EXT         0x8333
+#define GL_CUBIC_EXT                      0x8334
+#define GL_AVERAGE_EXT                    0x8335
+#define GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8336
+#define GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT 0x8337
+#define GL_PIXEL_TRANSFORM_2D_MATRIX_EXT  0x8338
+#endif
+
+#ifndef GL_EXT_pixel_transform_color_table
+#endif
+
+#ifndef GL_EXT_shared_texture_palette
+#define GL_SHARED_TEXTURE_PALETTE_EXT     0x81FB
+#endif
+
+#ifndef GL_EXT_separate_specular_color
+#define GL_LIGHT_MODEL_COLOR_CONTROL_EXT  0x81F8
+#define GL_SINGLE_COLOR_EXT               0x81F9
+#define GL_SEPARATE_SPECULAR_COLOR_EXT    0x81FA
+#endif
+
+#ifndef GL_EXT_secondary_color
+#define GL_COLOR_SUM_EXT                  0x8458
+#define GL_CURRENT_SECONDARY_COLOR_EXT    0x8459
+#define GL_SECONDARY_COLOR_ARRAY_SIZE_EXT 0x845A
+#define GL_SECONDARY_COLOR_ARRAY_TYPE_EXT 0x845B
+#define GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT 0x845C
+#define GL_SECONDARY_COLOR_ARRAY_POINTER_EXT 0x845D
+#define GL_SECONDARY_COLOR_ARRAY_EXT      0x845E
+#endif
+
+#ifndef GL_EXT_texture_perturb_normal
+#define GL_PERTURB_EXT                    0x85AE
+#define GL_TEXTURE_NORMAL_EXT             0x85AF
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#endif
+
+#ifndef GL_EXT_fog_coord
+#define GL_FOG_COORDINATE_SOURCE_EXT      0x8450
+#define GL_FOG_COORDINATE_EXT             0x8451
+#define GL_FRAGMENT_DEPTH_EXT             0x8452
+#define GL_CURRENT_FOG_COORDINATE_EXT     0x8453
+#define GL_FOG_COORDINATE_ARRAY_TYPE_EXT  0x8454
+#define GL_FOG_COORDINATE_ARRAY_STRIDE_EXT 0x8455
+#define GL_FOG_COORDINATE_ARRAY_POINTER_EXT 0x8456
+#define GL_FOG_COORDINATE_ARRAY_EXT       0x8457
+#endif
+
+#ifndef GL_REND_screen_coordinates
+#define GL_SCREEN_COORDINATES_REND        0x8490
+#define GL_INVERTED_SCREEN_W_REND         0x8491
+#endif
+
+#ifndef GL_EXT_coordinate_frame
+#define GL_TANGENT_ARRAY_EXT              0x8439
+#define GL_BINORMAL_ARRAY_EXT             0x843A
+#define GL_CURRENT_TANGENT_EXT            0x843B
+#define GL_CURRENT_BINORMAL_EXT           0x843C
+#define GL_TANGENT_ARRAY_TYPE_EXT         0x843E
+#define GL_TANGENT_ARRAY_STRIDE_EXT       0x843F
+#define GL_BINORMAL_ARRAY_TYPE_EXT        0x8440
+#define GL_BINORMAL_ARRAY_STRIDE_EXT      0x8441
+#define GL_TANGENT_ARRAY_POINTER_EXT      0x8442
+#define GL_BINORMAL_ARRAY_POINTER_EXT     0x8443
+#define GL_MAP1_TANGENT_EXT               0x8444
+#define GL_MAP2_TANGENT_EXT               0x8445
+#define GL_MAP1_BINORMAL_EXT              0x8446
+#define GL_MAP2_BINORMAL_EXT              0x8447
+#endif
+
+#ifndef GL_EXT_texture_env_combine
+#define GL_COMBINE_EXT                    0x8570
+#define GL_COMBINE_RGB_EXT                0x8571
+#define GL_COMBINE_ALPHA_EXT              0x8572
+#define GL_RGB_SCALE_EXT                  0x8573
+#define GL_ADD_SIGNED_EXT                 0x8574
+#define GL_INTERPOLATE_EXT                0x8575
+#define GL_CONSTANT_EXT                   0x8576
+#define GL_PRIMARY_COLOR_EXT              0x8577
+#define GL_PREVIOUS_EXT                   0x8578
+#define GL_SOURCE0_RGB_EXT                0x8580
+#define GL_SOURCE1_RGB_EXT                0x8581
+#define GL_SOURCE2_RGB_EXT                0x8582
+#define GL_SOURCE0_ALPHA_EXT              0x8588
+#define GL_SOURCE1_ALPHA_EXT              0x8589
+#define GL_SOURCE2_ALPHA_EXT              0x858A
+#define GL_OPERAND0_RGB_EXT               0x8590
+#define GL_OPERAND1_RGB_EXT               0x8591
+#define GL_OPERAND2_RGB_EXT               0x8592
+#define GL_OPERAND0_ALPHA_EXT             0x8598
+#define GL_OPERAND1_ALPHA_EXT             0x8599
+#define GL_OPERAND2_ALPHA_EXT             0x859A
+#endif
+
+#ifndef GL_APPLE_specular_vector
+#define GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE 0x85B0
+#endif
+
+#ifndef GL_APPLE_transform_hint
+#define GL_TRANSFORM_HINT_APPLE           0x85B1
+#endif
+
+#ifndef GL_SGIX_fog_scale
+#define GL_FOG_SCALE_SGIX                 0x81FC
+#define GL_FOG_SCALE_VALUE_SGIX           0x81FD
+#endif
+
+#ifndef GL_SUNX_constant_data
+#define GL_UNPACK_CONSTANT_DATA_SUNX      0x81D5
+#define GL_TEXTURE_CONSTANT_DATA_SUNX     0x81D6
+#endif
+
+#ifndef GL_SUN_global_alpha
+#define GL_GLOBAL_ALPHA_SUN               0x81D9
+#define GL_GLOBAL_ALPHA_FACTOR_SUN        0x81DA
+#endif
+
+#ifndef GL_SUN_triangle_list
+#define GL_RESTART_SUN                    0x0001
+#define GL_REPLACE_MIDDLE_SUN             0x0002
+#define GL_REPLACE_OLDEST_SUN             0x0003
+#define GL_TRIANGLE_LIST_SUN              0x81D7
+#define GL_REPLACEMENT_CODE_SUN           0x81D8
+#define GL_REPLACEMENT_CODE_ARRAY_SUN     0x85C0
+#define GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN 0x85C1
+#define GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN 0x85C2
+#define GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN 0x85C3
+#define GL_R1UI_V3F_SUN                   0x85C4
+#define GL_R1UI_C4UB_V3F_SUN              0x85C5
+#define GL_R1UI_C3F_V3F_SUN               0x85C6
+#define GL_R1UI_N3F_V3F_SUN               0x85C7
+#define GL_R1UI_C4F_N3F_V3F_SUN           0x85C8
+#define GL_R1UI_T2F_V3F_SUN               0x85C9
+#define GL_R1UI_T2F_N3F_V3F_SUN           0x85CA
+#define GL_R1UI_T2F_C4F_N3F_V3F_SUN       0x85CB
+#endif
+
+#ifndef GL_SUN_vertex
+#endif
+
+#ifndef GL_EXT_blend_func_separate
+#define GL_BLEND_DST_RGB_EXT              0x80C8
+#define GL_BLEND_SRC_RGB_EXT              0x80C9
+#define GL_BLEND_DST_ALPHA_EXT            0x80CA
+#define GL_BLEND_SRC_ALPHA_EXT            0x80CB
+#endif
+
+#ifndef GL_INGR_color_clamp
+#define GL_RED_MIN_CLAMP_INGR             0x8560
+#define GL_GREEN_MIN_CLAMP_INGR           0x8561
+#define GL_BLUE_MIN_CLAMP_INGR            0x8562
+#define GL_ALPHA_MIN_CLAMP_INGR           0x8563
+#define GL_RED_MAX_CLAMP_INGR             0x8564
+#define GL_GREEN_MAX_CLAMP_INGR           0x8565
+#define GL_BLUE_MAX_CLAMP_INGR            0x8566
+#define GL_ALPHA_MAX_CLAMP_INGR           0x8567
+#endif
+
+#ifndef GL_INGR_interlace_read
+#define GL_INTERLACE_READ_INGR            0x8568
+#endif
+
+#ifndef GL_EXT_stencil_wrap
+#define GL_INCR_WRAP_EXT                  0x8507
+#define GL_DECR_WRAP_EXT                  0x8508
+#endif
+
+#ifndef GL_EXT_422_pixels
+#define GL_422_EXT                        0x80CC
+#define GL_422_REV_EXT                    0x80CD
+#define GL_422_AVERAGE_EXT                0x80CE
+#define GL_422_REV_AVERAGE_EXT            0x80CF
+#endif
+
+#ifndef GL_NV_texgen_reflection
+#define GL_NORMAL_MAP_NV                  0x8511
+#define GL_REFLECTION_MAP_NV              0x8512
+#endif
+
+#ifndef GL_EXT_texture_cube_map
+#define GL_NORMAL_MAP_EXT                 0x8511
+#define GL_REFLECTION_MAP_EXT             0x8512
+#define GL_TEXTURE_CUBE_MAP_EXT           0x8513
+#define GL_TEXTURE_BINDING_CUBE_MAP_EXT   0x8514
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT 0x8515
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT 0x8516
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT 0x8517
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT 0x8518
+#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT 0x8519
+#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT 0x851A
+#define GL_PROXY_TEXTURE_CUBE_MAP_EXT     0x851B
+#define GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT  0x851C
+#endif
+
+#ifndef GL_SUN_convolution_border_modes
+#define GL_WRAP_BORDER_SUN                0x81D4
+#endif
+
+#ifndef GL_EXT_texture_env_add
+#endif
+
+#ifndef GL_EXT_texture_lod_bias
+#define GL_MAX_TEXTURE_LOD_BIAS_EXT       0x84FD
+#define GL_TEXTURE_FILTER_CONTROL_EXT     0x8500
+#define GL_TEXTURE_LOD_BIAS_EXT           0x8501
+#endif
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE
+#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF
+#endif
+
+#ifndef GL_EXT_vertex_weighting
+#define GL_MODELVIEW0_STACK_DEPTH_EXT     GL_MODELVIEW_STACK_DEPTH
+#define GL_MODELVIEW1_STACK_DEPTH_EXT     0x8502
+#define GL_MODELVIEW0_MATRIX_EXT          GL_MODELVIEW_MATRIX
+#define GL_MODELVIEW1_MATRIX_EXT          0x8506
+#define GL_VERTEX_WEIGHTING_EXT           0x8509
+#define GL_MODELVIEW0_EXT                 GL_MODELVIEW
+#define GL_MODELVIEW1_EXT                 0x850A
+#define GL_CURRENT_VERTEX_WEIGHT_EXT      0x850B
+#define GL_VERTEX_WEIGHT_ARRAY_EXT        0x850C
+#define GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT   0x850D
+#define GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT   0x850E
+#define GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT 0x850F
+#define GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT 0x8510
+#endif
+
+#ifndef GL_NV_light_max_exponent
+#define GL_MAX_SHININESS_NV               0x8504
+#define GL_MAX_SPOT_EXPONENT_NV           0x8505
+#endif
+
+#ifndef GL_NV_vertex_array_range
+#define GL_VERTEX_ARRAY_RANGE_NV          0x851D
+#define GL_VERTEX_ARRAY_RANGE_LENGTH_NV   0x851E
+#define GL_VERTEX_ARRAY_RANGE_VALID_NV    0x851F
+#define GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV 0x8520
+#define GL_VERTEX_ARRAY_RANGE_POINTER_NV  0x8521
+#endif
+
+#ifndef GL_NV_register_combiners
+#define GL_REGISTER_COMBINERS_NV          0x8522
+#define GL_VARIABLE_A_NV                  0x8523
+#define GL_VARIABLE_B_NV                  0x8524
+#define GL_VARIABLE_C_NV                  0x8525
+#define GL_VARIABLE_D_NV                  0x8526
+#define GL_VARIABLE_E_NV                  0x8527
+#define GL_VARIABLE_F_NV                  0x8528
+#define GL_VARIABLE_G_NV                  0x8529
+#define GL_CONSTANT_COLOR0_NV             0x852A
+#define GL_CONSTANT_COLOR1_NV             0x852B
+#define GL_PRIMARY_COLOR_NV               0x852C
+#define GL_SECONDARY_COLOR_NV             0x852D
+#define GL_SPARE0_NV                      0x852E
+#define GL_SPARE1_NV                      0x852F
+#define GL_DISCARD_NV                     0x8530
+#define GL_E_TIMES_F_NV                   0x8531
+#define GL_SPARE0_PLUS_SECONDARY_COLOR_NV 0x8532
+#define GL_UNSIGNED_IDENTITY_NV           0x8536
+#define GL_UNSIGNED_INVERT_NV             0x8537
+#define GL_EXPAND_NORMAL_NV               0x8538
+#define GL_EXPAND_NEGATE_NV               0x8539
+#define GL_HALF_BIAS_NORMAL_NV            0x853A
+#define GL_HALF_BIAS_NEGATE_NV            0x853B
+#define GL_SIGNED_IDENTITY_NV             0x853C
+#define GL_SIGNED_NEGATE_NV               0x853D
+#define GL_SCALE_BY_TWO_NV                0x853E
+#define GL_SCALE_BY_FOUR_NV               0x853F
+#define GL_SCALE_BY_ONE_HALF_NV           0x8540
+#define GL_BIAS_BY_NEGATIVE_ONE_HALF_NV   0x8541
+#define GL_COMBINER_INPUT_NV              0x8542
+#define GL_COMBINER_MAPPING_NV            0x8543
+#define GL_COMBINER_COMPONENT_USAGE_NV    0x8544
+#define GL_COMBINER_AB_DOT_PRODUCT_NV     0x8545
+#define GL_COMBINER_CD_DOT_PRODUCT_NV     0x8546
+#define GL_COMBINER_MUX_SUM_NV            0x8547
+#define GL_COMBINER_SCALE_NV              0x8548
+#define GL_COMBINER_BIAS_NV               0x8549
+#define GL_COMBINER_AB_OUTPUT_NV          0x854A
+#define GL_COMBINER_CD_OUTPUT_NV          0x854B
+#define GL_COMBINER_SUM_OUTPUT_NV         0x854C
+#define GL_MAX_GENERAL_COMBINERS_NV       0x854D
+#define GL_NUM_GENERAL_COMBINERS_NV       0x854E
+#define GL_COLOR_SUM_CLAMP_NV             0x854F
+#define GL_COMBINER0_NV                   0x8550
+#define GL_COMBINER1_NV                   0x8551
+#define GL_COMBINER2_NV                   0x8552
+#define GL_COMBINER3_NV                   0x8553
+#define GL_COMBINER4_NV                   0x8554
+#define GL_COMBINER5_NV                   0x8555
+#define GL_COMBINER6_NV                   0x8556
+#define GL_COMBINER7_NV                   0x8557
+/* reuse GL_TEXTURE0_ARB */
+/* reuse GL_TEXTURE1_ARB */
+/* reuse GL_ZERO */
+/* reuse GL_NONE */
+/* reuse GL_FOG */
+#endif
+
+#ifndef GL_NV_fog_distance
+#define GL_FOG_DISTANCE_MODE_NV           0x855A
+#define GL_EYE_RADIAL_NV                  0x855B
+#define GL_EYE_PLANE_ABSOLUTE_NV          0x855C
+/* reuse GL_EYE_PLANE */
+#endif
+
+#ifndef GL_NV_texgen_emboss
+#define GL_EMBOSS_LIGHT_NV                0x855D
+#define GL_EMBOSS_CONSTANT_NV             0x855E
+#define GL_EMBOSS_MAP_NV                  0x855F
+#endif
+
+#ifndef GL_NV_blend_square
+#endif
+
+#ifndef GL_NV_texture_env_combine4
+#define GL_COMBINE4_NV                    0x8503
+#define GL_SOURCE3_RGB_NV                 0x8583
+#define GL_SOURCE3_ALPHA_NV               0x858B
+#define GL_OPERAND3_RGB_NV                0x8593
+#define GL_OPERAND3_ALPHA_NV              0x859B
+#endif
+
+#ifndef GL_MESA_resize_buffers
+#endif
+
+#ifndef GL_MESA_window_pos
+#endif
+
+#ifndef GL_EXT_texture_compression_s3tc
+#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT   0x83F0
+#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT  0x83F1
+#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT  0x83F2
+#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT  0x83F3
+#endif
+
+#ifndef GL_IBM_cull_vertex
+#define GL_CULL_VERTEX_IBM                103050
+#endif
+
+#ifndef GL_IBM_multimode_draw_arrays
+#endif
+
+#ifndef GL_IBM_vertex_array_lists
+#define GL_VERTEX_ARRAY_LIST_IBM          103070
+#define GL_NORMAL_ARRAY_LIST_IBM          103071
+#define GL_COLOR_ARRAY_LIST_IBM           103072
+#define GL_INDEX_ARRAY_LIST_IBM           103073
+#define GL_TEXTURE_COORD_ARRAY_LIST_IBM   103074
+#define GL_EDGE_FLAG_ARRAY_LIST_IBM       103075
+#define GL_FOG_COORDINATE_ARRAY_LIST_IBM  103076
+#define GL_SECONDARY_COLOR_ARRAY_LIST_IBM 103077
+#define GL_VERTEX_ARRAY_LIST_STRIDE_IBM   103080
+#define GL_NORMAL_ARRAY_LIST_STRIDE_IBM   103081
+#define GL_COLOR_ARRAY_LIST_STRIDE_IBM    103082
+#define GL_INDEX_ARRAY_LIST_STRIDE_IBM    103083
+#define GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM 103084
+#define GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM 103085
+#define GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM 103086
+#define GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM 103087
+#endif
+
+#ifndef GL_SGIX_subsample
+#define GL_PACK_SUBSAMPLE_RATE_SGIX       0x85A0
+#define GL_UNPACK_SUBSAMPLE_RATE_SGIX     0x85A1
+#define GL_PIXEL_SUBSAMPLE_4444_SGIX      0x85A2
+#define GL_PIXEL_SUBSAMPLE_2424_SGIX      0x85A3
+#define GL_PIXEL_SUBSAMPLE_4242_SGIX      0x85A4
+#endif
+
+#ifndef GL_SGIX_ycrcb_subsample
+#endif
+
+#ifndef GL_SGIX_ycrcba
+#define GL_YCRCB_SGIX                     0x8318
+#define GL_YCRCBA_SGIX                    0x8319
+#endif
+
+#ifndef GL_SGI_depth_pass_instrument
+#define GL_DEPTH_PASS_INSTRUMENT_SGIX     0x8310
+#define GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX 0x8311
+#define GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX 0x8312
+#endif
+
+#ifndef GL_3DFX_texture_compression_FXT1
+#define GL_COMPRESSED_RGB_FXT1_3DFX       0x86B0
+#define GL_COMPRESSED_RGBA_FXT1_3DFX      0x86B1
+#endif
+
+#ifndef GL_3DFX_multisample
+#define GL_MULTISAMPLE_3DFX               0x86B2
+#define GL_SAMPLE_BUFFERS_3DFX            0x86B3
+#define GL_SAMPLES_3DFX                   0x86B4
+#define GL_MULTISAMPLE_BIT_3DFX           0x20000000
+#endif
+
+#ifndef GL_3DFX_tbuffer
+#endif
+
+#ifndef GL_EXT_multisample
+#define GL_MULTISAMPLE_EXT                0x809D
+#define GL_SAMPLE_ALPHA_TO_MASK_EXT       0x809E
+#define GL_SAMPLE_ALPHA_TO_ONE_EXT        0x809F
+#define GL_SAMPLE_MASK_EXT                0x80A0
+#define GL_1PASS_EXT                      0x80A1
+#define GL_2PASS_0_EXT                    0x80A2
+#define GL_2PASS_1_EXT                    0x80A3
+#define GL_4PASS_0_EXT                    0x80A4
+#define GL_4PASS_1_EXT                    0x80A5
+#define GL_4PASS_2_EXT                    0x80A6
+#define GL_4PASS_3_EXT                    0x80A7
+#define GL_SAMPLE_BUFFERS_EXT             0x80A8
+#define GL_SAMPLES_EXT                    0x80A9
+#define GL_SAMPLE_MASK_VALUE_EXT          0x80AA
+#define GL_SAMPLE_MASK_INVERT_EXT         0x80AB
+#define GL_SAMPLE_PATTERN_EXT             0x80AC
+#define GL_MULTISAMPLE_BIT_EXT            0x20000000
+#endif
+
+#ifndef GL_SGIX_vertex_preclip
+#define GL_VERTEX_PRECLIP_SGIX            0x83EE
+#define GL_VERTEX_PRECLIP_HINT_SGIX       0x83EF
+#endif
+
+#ifndef GL_SGIX_convolution_accuracy
+#define GL_CONVOLUTION_HINT_SGIX          0x8316
+#endif
+
+#ifndef GL_SGIX_resample
+#define GL_PACK_RESAMPLE_SGIX             0x842C
+#define GL_UNPACK_RESAMPLE_SGIX           0x842D
+#define GL_RESAMPLE_REPLICATE_SGIX        0x842E
+#define GL_RESAMPLE_ZERO_FILL_SGIX        0x842F
+#define GL_RESAMPLE_DECIMATE_SGIX         0x8430
+#endif
+
+#ifndef GL_SGIS_point_line_texgen
+#define GL_EYE_DISTANCE_TO_POINT_SGIS     0x81F0
+#define GL_OBJECT_DISTANCE_TO_POINT_SGIS  0x81F1
+#define GL_EYE_DISTANCE_TO_LINE_SGIS      0x81F2
+#define GL_OBJECT_DISTANCE_TO_LINE_SGIS   0x81F3
+#define GL_EYE_POINT_SGIS                 0x81F4
+#define GL_OBJECT_POINT_SGIS              0x81F5
+#define GL_EYE_LINE_SGIS                  0x81F6
+#define GL_OBJECT_LINE_SGIS               0x81F7
+#endif
+
+#ifndef GL_SGIS_texture_color_mask
+#define GL_TEXTURE_COLOR_WRITEMASK_SGIS   0x81EF
+#endif
+
+#ifndef GL_EXT_texture_env_dot3
+#define GL_DOT3_RGB_EXT                   0x8740
+#define GL_DOT3_RGBA_EXT                  0x8741
+#endif
+
+#ifndef GL_ATI_texture_mirror_once
+#define GL_MIRROR_CLAMP_ATI               0x8742
+#define GL_MIRROR_CLAMP_TO_EDGE_ATI       0x8743
+#endif
+
+#ifndef GL_NV_fence
+#define GL_ALL_COMPLETED_NV               0x84F2
+#define GL_FENCE_STATUS_NV                0x84F3
+#define GL_FENCE_CONDITION_NV             0x84F4
+#endif
+
+#ifndef GL_IBM_texture_mirrored_repeat
+#define GL_MIRRORED_REPEAT_IBM            0x8370
+#endif
+
+#ifndef GL_NV_evaluators
+#define GL_EVAL_2D_NV                     0x86C0
+#define GL_EVAL_TRIANGULAR_2D_NV          0x86C1
+#define GL_MAP_TESSELLATION_NV            0x86C2
+#define GL_MAP_ATTRIB_U_ORDER_NV          0x86C3
+#define GL_MAP_ATTRIB_V_ORDER_NV          0x86C4
+#define GL_EVAL_FRACTIONAL_TESSELLATION_NV 0x86C5
+#define GL_EVAL_VERTEX_ATTRIB0_NV         0x86C6
+#define GL_EVAL_VERTEX_ATTRIB1_NV         0x86C7
+#define GL_EVAL_VERTEX_ATTRIB2_NV         0x86C8
+#define GL_EVAL_VERTEX_ATTRIB3_NV         0x86C9
+#define GL_EVAL_VERTEX_ATTRIB4_NV         0x86CA
+#define GL_EVAL_VERTEX_ATTRIB5_NV         0x86CB
+#define GL_EVAL_VERTEX_ATTRIB6_NV         0x86CC
+#define GL_EVAL_VERTEX_ATTRIB7_NV         0x86CD
+#define GL_EVAL_VERTEX_ATTRIB8_NV         0x86CE
+#define GL_EVAL_VERTEX_ATTRIB9_NV         0x86CF
+#define GL_EVAL_VERTEX_ATTRIB10_NV        0x86D0
+#define GL_EVAL_VERTEX_ATTRIB11_NV        0x86D1
+#define GL_EVAL_VERTEX_ATTRIB12_NV        0x86D2
+#define GL_EVAL_VERTEX_ATTRIB13_NV        0x86D3
+#define GL_EVAL_VERTEX_ATTRIB14_NV        0x86D4
+#define GL_EVAL_VERTEX_ATTRIB15_NV        0x86D5
+#define GL_MAX_MAP_TESSELLATION_NV        0x86D6
+#define GL_MAX_RATIONAL_EVAL_ORDER_NV     0x86D7
+#endif
+
+#ifndef GL_NV_packed_depth_stencil
+#define GL_DEPTH_STENCIL_NV               0x84F9
+#define GL_UNSIGNED_INT_24_8_NV           0x84FA
+#endif
+
+#ifndef GL_NV_register_combiners2
+#define GL_PER_STAGE_CONSTANTS_NV         0x8535
+#endif
+
+#ifndef GL_NV_texture_compression_vtc
+#endif
+
+#ifndef GL_NV_texture_rectangle
+#define GL_TEXTURE_RECTANGLE_NV           0x84F5
+#define GL_TEXTURE_BINDING_RECTANGLE_NV   0x84F6
+#define GL_PROXY_TEXTURE_RECTANGLE_NV     0x84F7
+#define GL_MAX_RECTANGLE_TEXTURE_SIZE_NV  0x84F8
+#endif
+
+#ifndef GL_NV_texture_shader
+#define GL_OFFSET_TEXTURE_RECTANGLE_NV    0x864C
+#define GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV 0x864D
+#define GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV 0x864E
+#define GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV 0x86D9
+#define GL_UNSIGNED_INT_S8_S8_8_8_NV      0x86DA
+#define GL_UNSIGNED_INT_8_8_S8_S8_REV_NV  0x86DB
+#define GL_DSDT_MAG_INTENSITY_NV          0x86DC
+#define GL_SHADER_CONSISTENT_NV           0x86DD
+#define GL_TEXTURE_SHADER_NV              0x86DE
+#define GL_SHADER_OPERATION_NV            0x86DF
+#define GL_CULL_MODES_NV                  0x86E0
+#define GL_OFFSET_TEXTURE_MATRIX_NV       0x86E1
+#define GL_OFFSET_TEXTURE_SCALE_NV        0x86E2
+#define GL_OFFSET_TEXTURE_BIAS_NV         0x86E3
+#define GL_OFFSET_TEXTURE_2D_MATRIX_NV    GL_OFFSET_TEXTURE_MATRIX_NV
+#define GL_OFFSET_TEXTURE_2D_SCALE_NV     GL_OFFSET_TEXTURE_SCALE_NV
+#define GL_OFFSET_TEXTURE_2D_BIAS_NV      GL_OFFSET_TEXTURE_BIAS_NV
+#define GL_PREVIOUS_TEXTURE_INPUT_NV      0x86E4
+#define GL_CONST_EYE_NV                   0x86E5
+#define GL_PASS_THROUGH_NV                0x86E6
+#define GL_CULL_FRAGMENT_NV               0x86E7
+#define GL_OFFSET_TEXTURE_2D_NV           0x86E8
+#define GL_DEPENDENT_AR_TEXTURE_2D_NV     0x86E9
+#define GL_DEPENDENT_GB_TEXTURE_2D_NV     0x86EA
+#define GL_DOT_PRODUCT_NV                 0x86EC
+#define GL_DOT_PRODUCT_DEPTH_REPLACE_NV   0x86ED
+#define GL_DOT_PRODUCT_TEXTURE_2D_NV      0x86EE
+#define GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV 0x86F0
+#define GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV 0x86F1
+#define GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV 0x86F2
+#define GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV 0x86F3
+#define GL_HILO_NV                        0x86F4
+#define GL_DSDT_NV                        0x86F5
+#define GL_DSDT_MAG_NV                    0x86F6
+#define GL_DSDT_MAG_VIB_NV                0x86F7
+#define GL_HILO16_NV                      0x86F8
+#define GL_SIGNED_HILO_NV                 0x86F9
+#define GL_SIGNED_HILO16_NV               0x86FA
+#define GL_SIGNED_RGBA_NV                 0x86FB
+#define GL_SIGNED_RGBA8_NV                0x86FC
+#define GL_SIGNED_RGB_NV                  0x86FE
+#define GL_SIGNED_RGB8_NV                 0x86FF
+#define GL_SIGNED_LUMINANCE_NV            0x8701
+#define GL_SIGNED_LUMINANCE8_NV           0x8702
+#define GL_SIGNED_LUMINANCE_ALPHA_NV      0x8703
+#define GL_SIGNED_LUMINANCE8_ALPHA8_NV    0x8704
+#define GL_SIGNED_ALPHA_NV                0x8705
+#define GL_SIGNED_ALPHA8_NV               0x8706
+#define GL_SIGNED_INTENSITY_NV            0x8707
+#define GL_SIGNED_INTENSITY8_NV           0x8708
+#define GL_DSDT8_NV                       0x8709
+#define GL_DSDT8_MAG8_NV                  0x870A
+#define GL_DSDT8_MAG8_INTENSITY8_NV       0x870B
+#define GL_SIGNED_RGB_UNSIGNED_ALPHA_NV   0x870C
+#define GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV 0x870D
+#define GL_HI_SCALE_NV                    0x870E
+#define GL_LO_SCALE_NV                    0x870F
+#define GL_DS_SCALE_NV                    0x8710
+#define GL_DT_SCALE_NV                    0x8711
+#define GL_MAGNITUDE_SCALE_NV             0x8712
+#define GL_VIBRANCE_SCALE_NV              0x8713
+#define GL_HI_BIAS_NV                     0x8714
+#define GL_LO_BIAS_NV                     0x8715
+#define GL_DS_BIAS_NV                     0x8716
+#define GL_DT_BIAS_NV                     0x8717
+#define GL_MAGNITUDE_BIAS_NV              0x8718
+#define GL_VIBRANCE_BIAS_NV               0x8719
+#define GL_TEXTURE_BORDER_VALUES_NV       0x871A
+#define GL_TEXTURE_HI_SIZE_NV             0x871B
+#define GL_TEXTURE_LO_SIZE_NV             0x871C
+#define GL_TEXTURE_DS_SIZE_NV             0x871D
+#define GL_TEXTURE_DT_SIZE_NV             0x871E
+#define GL_TEXTURE_MAG_SIZE_NV            0x871F
+#endif
+
+#ifndef GL_NV_texture_shader2
+#define GL_DOT_PRODUCT_TEXTURE_3D_NV      0x86EF
+#endif
+
+#ifndef GL_NV_vertex_array_range2
+#define GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV 0x8533
+#endif
+
+#ifndef GL_NV_vertex_program
+#define GL_VERTEX_PROGRAM_NV              0x8620
+#define GL_VERTEX_STATE_PROGRAM_NV        0x8621
+#define GL_ATTRIB_ARRAY_SIZE_NV           0x8623
+#define GL_ATTRIB_ARRAY_STRIDE_NV         0x8624
+#define GL_ATTRIB_ARRAY_TYPE_NV           0x8625
+#define GL_CURRENT_ATTRIB_NV              0x8626
+#define GL_PROGRAM_LENGTH_NV              0x8627
+#define GL_PROGRAM_STRING_NV              0x8628
+#define GL_MODELVIEW_PROJECTION_NV        0x8629
+#define GL_IDENTITY_NV                    0x862A
+#define GL_INVERSE_NV                     0x862B
+#define GL_TRANSPOSE_NV                   0x862C
+#define GL_INVERSE_TRANSPOSE_NV           0x862D
+#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E
+#define GL_MAX_TRACK_MATRICES_NV          0x862F
+#define GL_MATRIX0_NV                     0x8630
+#define GL_MATRIX1_NV                     0x8631
+#define GL_MATRIX2_NV                     0x8632
+#define GL_MATRIX3_NV                     0x8633
+#define GL_MATRIX4_NV                     0x8634
+#define GL_MATRIX5_NV                     0x8635
+#define GL_MATRIX6_NV                     0x8636
+#define GL_MATRIX7_NV                     0x8637
+#define GL_CURRENT_MATRIX_STACK_DEPTH_NV  0x8640
+#define GL_CURRENT_MATRIX_NV              0x8641
+#define GL_VERTEX_PROGRAM_POINT_SIZE_NV   0x8642
+#define GL_VERTEX_PROGRAM_TWO_SIDE_NV     0x8643
+#define GL_PROGRAM_PARAMETER_NV           0x8644
+#define GL_ATTRIB_ARRAY_POINTER_NV        0x8645
+#define GL_PROGRAM_TARGET_NV              0x8646
+#define GL_PROGRAM_RESIDENT_NV            0x8647
+#define GL_TRACK_MATRIX_NV                0x8648
+#define GL_TRACK_MATRIX_TRANSFORM_NV      0x8649
+#define GL_VERTEX_PROGRAM_BINDING_NV      0x864A
+#define GL_PROGRAM_ERROR_POSITION_NV      0x864B
+#define GL_VERTEX_ATTRIB_ARRAY0_NV        0x8650
+#define GL_VERTEX_ATTRIB_ARRAY1_NV        0x8651
+#define GL_VERTEX_ATTRIB_ARRAY2_NV        0x8652
+#define GL_VERTEX_ATTRIB_ARRAY3_NV        0x8653
+#define GL_VERTEX_ATTRIB_ARRAY4_NV        0x8654
+#define GL_VERTEX_ATTRIB_ARRAY5_NV        0x8655
+#define GL_VERTEX_ATTRIB_ARRAY6_NV        0x8656
+#define GL_VERTEX_ATTRIB_ARRAY7_NV        0x8657
+#define GL_VERTEX_ATTRIB_ARRAY8_NV        0x8658
+#define GL_VERTEX_ATTRIB_ARRAY9_NV        0x8659
+#define GL_VERTEX_ATTRIB_ARRAY10_NV       0x865A
+#define GL_VERTEX_ATTRIB_ARRAY11_NV       0x865B
+#define GL_VERTEX_ATTRIB_ARRAY12_NV       0x865C
+#define GL_VERTEX_ATTRIB_ARRAY13_NV       0x865D
+#define GL_VERTEX_ATTRIB_ARRAY14_NV       0x865E
+#define GL_VERTEX_ATTRIB_ARRAY15_NV       0x865F
+#define GL_MAP1_VERTEX_ATTRIB0_4_NV       0x8660
+#define GL_MAP1_VERTEX_ATTRIB1_4_NV       0x8661
+#define GL_MAP1_VERTEX_ATTRIB2_4_NV       0x8662
+#define GL_MAP1_VERTEX_ATTRIB3_4_NV       0x8663
+#define GL_MAP1_VERTEX_ATTRIB4_4_NV       0x8664
+#define GL_MAP1_VERTEX_ATTRIB5_4_NV       0x8665
+#define GL_MAP1_VERTEX_ATTRIB6_4_NV       0x8666
+#define GL_MAP1_VERTEX_ATTRIB7_4_NV       0x8667
+#define GL_MAP1_VERTEX_ATTRIB8_4_NV       0x8668
+#define GL_MAP1_VERTEX_ATTRIB9_4_NV       0x8669
+#define GL_MAP1_VERTEX_ATTRIB10_4_NV      0x866A
+#define GL_MAP1_VERTEX_ATTRIB11_4_NV      0x866B
+#define GL_MAP1_VERTEX_ATTRIB12_4_NV      0x866C
+#define GL_MAP1_VERTEX_ATTRIB13_4_NV      0x866D
+#define GL_MAP1_VERTEX_ATTRIB14_4_NV      0x866E
+#define GL_MAP1_VERTEX_ATTRIB15_4_NV      0x866F
+#define GL_MAP2_VERTEX_ATTRIB0_4_NV       0x8670
+#define GL_MAP2_VERTEX_ATTRIB1_4_NV       0x8671
+#define GL_MAP2_VERTEX_ATTRIB2_4_NV       0x8672
+#define GL_MAP2_VERTEX_ATTRIB3_4_NV       0x8673
+#define GL_MAP2_VERTEX_ATTRIB4_4_NV       0x8674
+#define GL_MAP2_VERTEX_ATTRIB5_4_NV       0x8675
+#define GL_MAP2_VERTEX_ATTRIB6_4_NV       0x8676
+#define GL_MAP2_VERTEX_ATTRIB7_4_NV       0x8677
+#define GL_MAP2_VERTEX_ATTRIB8_4_NV       0x8678
+#define GL_MAP2_VERTEX_ATTRIB9_4_NV       0x8679
+#define GL_MAP2_VERTEX_ATTRIB10_4_NV      0x867A
+#define GL_MAP2_VERTEX_ATTRIB11_4_NV      0x867B
+#define GL_MAP2_VERTEX_ATTRIB12_4_NV      0x867C
+#define GL_MAP2_VERTEX_ATTRIB13_4_NV      0x867D
+#define GL_MAP2_VERTEX_ATTRIB14_4_NV      0x867E
+#define GL_MAP2_VERTEX_ATTRIB15_4_NV      0x867F
+#endif
+
+#ifndef GL_SGIX_texture_coordinate_clamp
+#define GL_TEXTURE_MAX_CLAMP_S_SGIX       0x8369
+#define GL_TEXTURE_MAX_CLAMP_T_SGIX       0x836A
+#define GL_TEXTURE_MAX_CLAMP_R_SGIX       0x836B
+#endif
+
+#ifndef GL_SGIX_scalebias_hint
+#define GL_SCALEBIAS_HINT_SGIX            0x8322
+#endif
+
+#ifndef GL_OML_interlace
+#define GL_INTERLACE_OML                  0x8980
+#define GL_INTERLACE_READ_OML             0x8981
+#endif
+
+#ifndef GL_OML_subsample
+#define GL_FORMAT_SUBSAMPLE_24_24_OML     0x8982
+#define GL_FORMAT_SUBSAMPLE_244_244_OML   0x8983
+#endif
+
+#ifndef GL_OML_resample
+#define GL_PACK_RESAMPLE_OML              0x8984
+#define GL_UNPACK_RESAMPLE_OML            0x8985
+#define GL_RESAMPLE_REPLICATE_OML         0x8986
+#define GL_RESAMPLE_ZERO_FILL_OML         0x8987
+#define GL_RESAMPLE_AVERAGE_OML           0x8988
+#define GL_RESAMPLE_DECIMATE_OML          0x8989
+#endif
+
+#ifndef GL_NV_copy_depth_to_color
+#define GL_DEPTH_STENCIL_TO_RGBA_NV       0x886E
+#define GL_DEPTH_STENCIL_TO_BGRA_NV       0x886F
+#endif
+
+#ifndef GL_ATI_envmap_bumpmap
+#define GL_BUMP_ROT_MATRIX_ATI            0x8775
+#define GL_BUMP_ROT_MATRIX_SIZE_ATI       0x8776
+#define GL_BUMP_NUM_TEX_UNITS_ATI         0x8777
+#define GL_BUMP_TEX_UNITS_ATI             0x8778
+#define GL_DUDV_ATI                       0x8779
+#define GL_DU8DV8_ATI                     0x877A
+#define GL_BUMP_ENVMAP_ATI                0x877B
+#define GL_BUMP_TARGET_ATI                0x877C
+#endif
+
+#ifndef GL_ATI_fragment_shader
+#define GL_FRAGMENT_SHADER_ATI            0x8920
+#define GL_REG_0_ATI                      0x8921
+#define GL_REG_1_ATI                      0x8922
+#define GL_REG_2_ATI                      0x8923
+#define GL_REG_3_ATI                      0x8924
+#define GL_REG_4_ATI                      0x8925
+#define GL_REG_5_ATI                      0x8926
+#define GL_REG_6_ATI                      0x8927
+#define GL_REG_7_ATI                      0x8928
+#define GL_REG_8_ATI                      0x8929
+#define GL_REG_9_ATI                      0x892A
+#define GL_REG_10_ATI                     0x892B
+#define GL_REG_11_ATI                     0x892C
+#define GL_REG_12_ATI                     0x892D
+#define GL_REG_13_ATI                     0x892E
+#define GL_REG_14_ATI                     0x892F
+#define GL_REG_15_ATI                     0x8930
+#define GL_REG_16_ATI                     0x8931
+#define GL_REG_17_ATI                     0x8932
+#define GL_REG_18_ATI                     0x8933
+#define GL_REG_19_ATI                     0x8934
+#define GL_REG_20_ATI                     0x8935
+#define GL_REG_21_ATI                     0x8936
+#define GL_REG_22_ATI                     0x8937
+#define GL_REG_23_ATI                     0x8938
+#define GL_REG_24_ATI                     0x8939
+#define GL_REG_25_ATI                     0x893A
+#define GL_REG_26_ATI                     0x893B
+#define GL_REG_27_ATI                     0x893C
+#define GL_REG_28_ATI                     0x893D
+#define GL_REG_29_ATI                     0x893E
+#define GL_REG_30_ATI                     0x893F
+#define GL_REG_31_ATI                     0x8940
+#define GL_CON_0_ATI                      0x8941
+#define GL_CON_1_ATI                      0x8942
+#define GL_CON_2_ATI                      0x8943
+#define GL_CON_3_ATI                      0x8944
+#define GL_CON_4_ATI                      0x8945
+#define GL_CON_5_ATI                      0x8946
+#define GL_CON_6_ATI                      0x8947
+#define GL_CON_7_ATI                      0x8948
+#define GL_CON_8_ATI                      0x8949
+#define GL_CON_9_ATI                      0x894A
+#define GL_CON_10_ATI                     0x894B
+#define GL_CON_11_ATI                     0x894C
+#define GL_CON_12_ATI                     0x894D
+#define GL_CON_13_ATI                     0x894E
+#define GL_CON_14_ATI                     0x894F
+#define GL_CON_15_ATI                     0x8950
+#define GL_CON_16_ATI                     0x8951
+#define GL_CON_17_ATI                     0x8952
+#define GL_CON_18_ATI                     0x8953
+#define GL_CON_19_ATI                     0x8954
+#define GL_CON_20_ATI                     0x8955
+#define GL_CON_21_ATI                     0x8956
+#define GL_CON_22_ATI                     0x8957
+#define GL_CON_23_ATI                     0x8958
+#define GL_CON_24_ATI                     0x8959
+#define GL_CON_25_ATI                     0x895A
+#define GL_CON_26_ATI                     0x895B
+#define GL_CON_27_ATI                     0x895C
+#define GL_CON_28_ATI                     0x895D
+#define GL_CON_29_ATI                     0x895E
+#define GL_CON_30_ATI                     0x895F
+#define GL_CON_31_ATI                     0x8960
+#define GL_MOV_ATI                        0x8961
+#define GL_ADD_ATI                        0x8963
+#define GL_MUL_ATI                        0x8964
+#define GL_SUB_ATI                        0x8965
+#define GL_DOT3_ATI                       0x8966
+#define GL_DOT4_ATI                       0x8967
+#define GL_MAD_ATI                        0x8968
+#define GL_LERP_ATI                       0x8969
+#define GL_CND_ATI                        0x896A
+#define GL_CND0_ATI                       0x896B
+#define GL_DOT2_ADD_ATI                   0x896C
+#define GL_SECONDARY_INTERPOLATOR_ATI     0x896D
+#define GL_NUM_FRAGMENT_REGISTERS_ATI     0x896E
+#define GL_NUM_FRAGMENT_CONSTANTS_ATI     0x896F
+#define GL_NUM_PASSES_ATI                 0x8970
+#define GL_NUM_INSTRUCTIONS_PER_PASS_ATI  0x8971
+#define GL_NUM_INSTRUCTIONS_TOTAL_ATI     0x8972
+#define GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI 0x8973
+#define GL_NUM_LOOPBACK_COMPONENTS_ATI    0x8974
+#define GL_COLOR_ALPHA_PAIRING_ATI        0x8975
+#define GL_SWIZZLE_STR_ATI                0x8976
+#define GL_SWIZZLE_STQ_ATI                0x8977
+#define GL_SWIZZLE_STR_DR_ATI             0x8978
+#define GL_SWIZZLE_STQ_DQ_ATI             0x8979
+#define GL_SWIZZLE_STRQ_ATI               0x897A
+#define GL_SWIZZLE_STRQ_DQ_ATI            0x897B
+#define GL_RED_BIT_ATI                    0x00000001
+#define GL_GREEN_BIT_ATI                  0x00000002
+#define GL_BLUE_BIT_ATI                   0x00000004
+#define GL_2X_BIT_ATI                     0x00000001
+#define GL_4X_BIT_ATI                     0x00000002
+#define GL_8X_BIT_ATI                     0x00000004
+#define GL_HALF_BIT_ATI                   0x00000008
+#define GL_QUARTER_BIT_ATI                0x00000010
+#define GL_EIGHTH_BIT_ATI                 0x00000020
+#define GL_SATURATE_BIT_ATI               0x00000040
+#define GL_COMP_BIT_ATI                   0x00000002
+#define GL_NEGATE_BIT_ATI                 0x00000004
+#define GL_BIAS_BIT_ATI                   0x00000008
+#endif
+
+#ifndef GL_ATI_pn_triangles
+#define GL_PN_TRIANGLES_ATI               0x87F0
+#define GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F1
+#define GL_PN_TRIANGLES_POINT_MODE_ATI    0x87F2
+#define GL_PN_TRIANGLES_NORMAL_MODE_ATI   0x87F3
+#define GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI 0x87F4
+#define GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI 0x87F5
+#define GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI 0x87F6
+#define GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI 0x87F7
+#define GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI 0x87F8
+#endif
+
+#ifndef GL_ATI_vertex_array_object
+#define GL_STATIC_ATI                     0x8760
+#define GL_DYNAMIC_ATI                    0x8761
+#define GL_PRESERVE_ATI                   0x8762
+#define GL_DISCARD_ATI                    0x8763
+#define GL_OBJECT_BUFFER_SIZE_ATI         0x8764
+#define GL_OBJECT_BUFFER_USAGE_ATI        0x8765
+#define GL_ARRAY_OBJECT_BUFFER_ATI        0x8766
+#define GL_ARRAY_OBJECT_OFFSET_ATI        0x8767
+#endif
+
+#ifndef GL_EXT_vertex_shader
+#define GL_VERTEX_SHADER_EXT              0x8780
+#define GL_VERTEX_SHADER_BINDING_EXT      0x8781
+#define GL_OP_INDEX_EXT                   0x8782
+#define GL_OP_NEGATE_EXT                  0x8783
+#define GL_OP_DOT3_EXT                    0x8784
+#define GL_OP_DOT4_EXT                    0x8785
+#define GL_OP_MUL_EXT                     0x8786
+#define GL_OP_ADD_EXT                     0x8787
+#define GL_OP_MADD_EXT                    0x8788
+#define GL_OP_FRAC_EXT                    0x8789
+#define GL_OP_MAX_EXT                     0x878A
+#define GL_OP_MIN_EXT                     0x878B
+#define GL_OP_SET_GE_EXT                  0x878C
+#define GL_OP_SET_LT_EXT                  0x878D
+#define GL_OP_CLAMP_EXT                   0x878E
+#define GL_OP_FLOOR_EXT                   0x878F
+#define GL_OP_ROUND_EXT                   0x8790
+#define GL_OP_EXP_BASE_2_EXT              0x8791
+#define GL_OP_LOG_BASE_2_EXT              0x8792
+#define GL_OP_POWER_EXT                   0x8793
+#define GL_OP_RECIP_EXT                   0x8794
+#define GL_OP_RECIP_SQRT_EXT              0x8795
+#define GL_OP_SUB_EXT                     0x8796
+#define GL_OP_CROSS_PRODUCT_EXT           0x8797
+#define GL_OP_MULTIPLY_MATRIX_EXT         0x8798
+#define GL_OP_MOV_EXT                     0x8799
+#define GL_OUTPUT_VERTEX_EXT              0x879A
+#define GL_OUTPUT_COLOR0_EXT              0x879B
+#define GL_OUTPUT_COLOR1_EXT              0x879C
+#define GL_OUTPUT_TEXTURE_COORD0_EXT      0x879D
+#define GL_OUTPUT_TEXTURE_COORD1_EXT      0x879E
+#define GL_OUTPUT_TEXTURE_COORD2_EXT      0x879F
+#define GL_OUTPUT_TEXTURE_COORD3_EXT      0x87A0
+#define GL_OUTPUT_TEXTURE_COORD4_EXT      0x87A1
+#define GL_OUTPUT_TEXTURE_COORD5_EXT      0x87A2
+#define GL_OUTPUT_TEXTURE_COORD6_EXT      0x87A3
+#define GL_OUTPUT_TEXTURE_COORD7_EXT      0x87A4
+#define GL_OUTPUT_TEXTURE_COORD8_EXT      0x87A5
+#define GL_OUTPUT_TEXTURE_COORD9_EXT      0x87A6
+#define GL_OUTPUT_TEXTURE_COORD10_EXT     0x87A7
+#define GL_OUTPUT_TEXTURE_COORD11_EXT     0x87A8
+#define GL_OUTPUT_TEXTURE_COORD12_EXT     0x87A9
+#define GL_OUTPUT_TEXTURE_COORD13_EXT     0x87AA
+#define GL_OUTPUT_TEXTURE_COORD14_EXT     0x87AB
+#define GL_OUTPUT_TEXTURE_COORD15_EXT     0x87AC
+#define GL_OUTPUT_TEXTURE_COORD16_EXT     0x87AD
+#define GL_OUTPUT_TEXTURE_COORD17_EXT     0x87AE
+#define GL_OUTPUT_TEXTURE_COORD18_EXT     0x87AF
+#define GL_OUTPUT_TEXTURE_COORD19_EXT     0x87B0
+#define GL_OUTPUT_TEXTURE_COORD20_EXT     0x87B1
+#define GL_OUTPUT_TEXTURE_COORD21_EXT     0x87B2
+#define GL_OUTPUT_TEXTURE_COORD22_EXT     0x87B3
+#define GL_OUTPUT_TEXTURE_COORD23_EXT     0x87B4
+#define GL_OUTPUT_TEXTURE_COORD24_EXT     0x87B5
+#define GL_OUTPUT_TEXTURE_COORD25_EXT     0x87B6
+#define GL_OUTPUT_TEXTURE_COORD26_EXT     0x87B7
+#define GL_OUTPUT_TEXTURE_COORD27_EXT     0x87B8
+#define GL_OUTPUT_TEXTURE_COORD28_EXT     0x87B9
+#define GL_OUTPUT_TEXTURE_COORD29_EXT     0x87BA
+#define GL_OUTPUT_TEXTURE_COORD30_EXT     0x87BB
+#define GL_OUTPUT_TEXTURE_COORD31_EXT     0x87BC
+#define GL_OUTPUT_FOG_EXT                 0x87BD
+#define GL_SCALAR_EXT                     0x87BE
+#define GL_VECTOR_EXT                     0x87BF
+#define GL_MATRIX_EXT                     0x87C0
+#define GL_VARIANT_EXT                    0x87C1
+#define GL_INVARIANT_EXT                  0x87C2
+#define GL_LOCAL_CONSTANT_EXT             0x87C3
+#define GL_LOCAL_EXT                      0x87C4
+#define GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87C5
+#define GL_MAX_VERTEX_SHADER_VARIANTS_EXT 0x87C6
+#define GL_MAX_VERTEX_SHADER_INVARIANTS_EXT 0x87C7
+#define GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87C8
+#define GL_MAX_VERTEX_SHADER_LOCALS_EXT   0x87C9
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CA
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT 0x87CB
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87CC
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT 0x87CD
+#define GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT 0x87CE
+#define GL_VERTEX_SHADER_INSTRUCTIONS_EXT 0x87CF
+#define GL_VERTEX_SHADER_VARIANTS_EXT     0x87D0
+#define GL_VERTEX_SHADER_INVARIANTS_EXT   0x87D1
+#define GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT 0x87D2
+#define GL_VERTEX_SHADER_LOCALS_EXT       0x87D3
+#define GL_VERTEX_SHADER_OPTIMIZED_EXT    0x87D4
+#define GL_X_EXT                          0x87D5
+#define GL_Y_EXT                          0x87D6
+#define GL_Z_EXT                          0x87D7
+#define GL_W_EXT                          0x87D8
+#define GL_NEGATIVE_X_EXT                 0x87D9
+#define GL_NEGATIVE_Y_EXT                 0x87DA
+#define GL_NEGATIVE_Z_EXT                 0x87DB
+#define GL_NEGATIVE_W_EXT                 0x87DC
+#define GL_ZERO_EXT                       0x87DD
+#define GL_ONE_EXT                        0x87DE
+#define GL_NEGATIVE_ONE_EXT               0x87DF
+#define GL_NORMALIZED_RANGE_EXT           0x87E0
+#define GL_FULL_RANGE_EXT                 0x87E1
+#define GL_CURRENT_VERTEX_EXT             0x87E2
+#define GL_MVP_MATRIX_EXT                 0x87E3
+#define GL_VARIANT_VALUE_EXT              0x87E4
+#define GL_VARIANT_DATATYPE_EXT           0x87E5
+#define GL_VARIANT_ARRAY_STRIDE_EXT       0x87E6
+#define GL_VARIANT_ARRAY_TYPE_EXT         0x87E7
+#define GL_VARIANT_ARRAY_EXT              0x87E8
+#define GL_VARIANT_ARRAY_POINTER_EXT      0x87E9
+#define GL_INVARIANT_VALUE_EXT            0x87EA
+#define GL_INVARIANT_DATATYPE_EXT         0x87EB
+#define GL_LOCAL_CONSTANT_VALUE_EXT       0x87EC
+#define GL_LOCAL_CONSTANT_DATATYPE_EXT    0x87ED
+#endif
+
+#ifndef GL_ATI_vertex_streams
+#define GL_MAX_VERTEX_STREAMS_ATI         0x876B
+#define GL_VERTEX_STREAM0_ATI             0x876C
+#define GL_VERTEX_STREAM1_ATI             0x876D
+#define GL_VERTEX_STREAM2_ATI             0x876E
+#define GL_VERTEX_STREAM3_ATI             0x876F
+#define GL_VERTEX_STREAM4_ATI             0x8770
+#define GL_VERTEX_STREAM5_ATI             0x8771
+#define GL_VERTEX_STREAM6_ATI             0x8772
+#define GL_VERTEX_STREAM7_ATI             0x8773
+#define GL_VERTEX_SOURCE_ATI              0x8774
+#endif
+
+#ifndef GL_ATI_element_array
+#define GL_ELEMENT_ARRAY_ATI              0x8768
+#define GL_ELEMENT_ARRAY_TYPE_ATI         0x8769
+#define GL_ELEMENT_ARRAY_POINTER_ATI      0x876A
+#endif
+
+#ifndef GL_SUN_mesh_array
+#define GL_QUAD_MESH_SUN                  0x8614
+#define GL_TRIANGLE_MESH_SUN              0x8615
+#endif
+
+#ifndef GL_SUN_slice_accum
+#define GL_SLICE_ACCUM_SUN                0x85CC
+#endif
+
+#ifndef GL_NV_multisample_filter_hint
+#define GL_MULTISAMPLE_FILTER_HINT_NV     0x8534
+#endif
+
+#ifndef GL_NV_depth_clamp
+#define GL_DEPTH_CLAMP_NV                 0x864F
+#endif
+
+#ifndef GL_NV_occlusion_query
+#define GL_PIXEL_COUNTER_BITS_NV          0x8864
+#define GL_CURRENT_OCCLUSION_QUERY_ID_NV  0x8865
+#define GL_PIXEL_COUNT_NV                 0x8866
+#define GL_PIXEL_COUNT_AVAILABLE_NV       0x8867
+#endif
+
+#ifndef GL_NV_point_sprite
+#define GL_POINT_SPRITE_NV                0x8861
+#define GL_COORD_REPLACE_NV               0x8862
+#define GL_POINT_SPRITE_R_MODE_NV         0x8863
+#endif
+
+#ifndef GL_NV_texture_shader3
+#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV 0x8850
+#define GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV 0x8851
+#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8852
+#define GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV 0x8853
+#define GL_OFFSET_HILO_TEXTURE_2D_NV      0x8854
+#define GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV 0x8855
+#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV 0x8856
+#define GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV 0x8857
+#define GL_DEPENDENT_HILO_TEXTURE_2D_NV   0x8858
+#define GL_DEPENDENT_RGB_TEXTURE_3D_NV    0x8859
+#define GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV 0x885A
+#define GL_DOT_PRODUCT_PASS_THROUGH_NV    0x885B
+#define GL_DOT_PRODUCT_TEXTURE_1D_NV      0x885C
+#define GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV 0x885D
+#define GL_HILO8_NV                       0x885E
+#define GL_SIGNED_HILO8_NV                0x885F
+#define GL_FORCE_BLUE_TO_ONE_NV           0x8860
+#endif
+
+#ifndef GL_NV_vertex_program1_1
+#endif
+
+#ifndef GL_EXT_shadow_funcs
+#endif
+
+#ifndef GL_EXT_stencil_two_side
+#define GL_STENCIL_TEST_TWO_SIDE_EXT      0x8910
+#define GL_ACTIVE_STENCIL_FACE_EXT        0x8911
+#endif
+
+#ifndef GL_ATI_text_fragment_shader
+#define GL_TEXT_FRAGMENT_SHADER_ATI       0x8200
+#endif
+
+#ifndef GL_APPLE_client_storage
+#define GL_UNPACK_CLIENT_STORAGE_APPLE    0x85B2
+#endif
+
+#ifndef GL_APPLE_element_array
+#define GL_ELEMENT_ARRAY_APPLE            0x8768
+#define GL_ELEMENT_ARRAY_TYPE_APPLE       0x8769
+#define GL_ELEMENT_ARRAY_POINTER_APPLE    0x876A
+#endif
+
+#ifndef GL_APPLE_fence
+#define GL_DRAW_PIXELS_APPLE              0x8A0A
+#define GL_FENCE_APPLE                    0x8A0B
+#endif
+
+#ifndef GL_APPLE_vertex_array_object
+#define GL_VERTEX_ARRAY_BINDING_APPLE     0x85B5
+#endif
+
+#ifndef GL_APPLE_vertex_array_range
+#define GL_VERTEX_ARRAY_RANGE_APPLE       0x851D
+#define GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE 0x851E
+#define GL_VERTEX_ARRAY_STORAGE_HINT_APPLE 0x851F
+#define GL_VERTEX_ARRAY_RANGE_POINTER_APPLE 0x8521
+#define GL_STORAGE_CACHED_APPLE           0x85BE
+#define GL_STORAGE_SHARED_APPLE           0x85BF
+#endif
+
+#ifndef GL_APPLE_ycbcr_422
+#define GL_YCBCR_422_APPLE                0x85B9
+#define GL_UNSIGNED_SHORT_8_8_APPLE       0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_APPLE   0x85BB
+#endif
+
+#ifndef GL_S3_s3tc
+#define GL_RGB_S3TC                       0x83A0
+#define GL_RGB4_S3TC                      0x83A1
+#define GL_RGBA_S3TC                      0x83A2
+#define GL_RGBA4_S3TC                     0x83A3
+#endif
+
+#ifndef GL_ATI_draw_buffers
+#define GL_MAX_DRAW_BUFFERS_ATI           0x8824
+#define GL_DRAW_BUFFER0_ATI               0x8825
+#define GL_DRAW_BUFFER1_ATI               0x8826
+#define GL_DRAW_BUFFER2_ATI               0x8827
+#define GL_DRAW_BUFFER3_ATI               0x8828
+#define GL_DRAW_BUFFER4_ATI               0x8829
+#define GL_DRAW_BUFFER5_ATI               0x882A
+#define GL_DRAW_BUFFER6_ATI               0x882B
+#define GL_DRAW_BUFFER7_ATI               0x882C
+#define GL_DRAW_BUFFER8_ATI               0x882D
+#define GL_DRAW_BUFFER9_ATI               0x882E
+#define GL_DRAW_BUFFER10_ATI              0x882F
+#define GL_DRAW_BUFFER11_ATI              0x8830
+#define GL_DRAW_BUFFER12_ATI              0x8831
+#define GL_DRAW_BUFFER13_ATI              0x8832
+#define GL_DRAW_BUFFER14_ATI              0x8833
+#define GL_DRAW_BUFFER15_ATI              0x8834
+#endif
+
+#ifndef GL_ATI_texture_env_combine3
+#define GL_MODULATE_ADD_ATI               0x8744
+#define GL_MODULATE_SIGNED_ADD_ATI        0x8745
+#define GL_MODULATE_SUBTRACT_ATI          0x8746
+#endif
+
+#ifndef GL_ATI_texture_float
+#define GL_RGBA_FLOAT32_ATI               0x8814
+#define GL_RGB_FLOAT32_ATI                0x8815
+#define GL_ALPHA_FLOAT32_ATI              0x8816
+#define GL_INTENSITY_FLOAT32_ATI          0x8817
+#define GL_LUMINANCE_FLOAT32_ATI          0x8818
+#define GL_LUMINANCE_ALPHA_FLOAT32_ATI    0x8819
+#define GL_RGBA_FLOAT16_ATI               0x881A
+#define GL_RGB_FLOAT16_ATI                0x881B
+#define GL_ALPHA_FLOAT16_ATI              0x881C
+#define GL_INTENSITY_FLOAT16_ATI          0x881D
+#define GL_LUMINANCE_FLOAT16_ATI          0x881E
+#define GL_LUMINANCE_ALPHA_FLOAT16_ATI    0x881F
+#endif
+
+#ifndef GL_NV_float_buffer
+#define GL_FLOAT_R_NV                     0x8880
+#define GL_FLOAT_RG_NV                    0x8881
+#define GL_FLOAT_RGB_NV                   0x8882
+#define GL_FLOAT_RGBA_NV                  0x8883
+#define GL_FLOAT_R16_NV                   0x8884
+#define GL_FLOAT_R32_NV                   0x8885
+#define GL_FLOAT_RG16_NV                  0x8886
+#define GL_FLOAT_RG32_NV                  0x8887
+#define GL_FLOAT_RGB16_NV                 0x8888
+#define GL_FLOAT_RGB32_NV                 0x8889
+#define GL_FLOAT_RGBA16_NV                0x888A
+#define GL_FLOAT_RGBA32_NV                0x888B
+#define GL_TEXTURE_FLOAT_COMPONENTS_NV    0x888C
+#define GL_FLOAT_CLEAR_COLOR_VALUE_NV     0x888D
+#define GL_FLOAT_RGBA_MODE_NV             0x888E
+#endif
+
+#ifndef GL_NV_fragment_program
+#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868
+#define GL_FRAGMENT_PROGRAM_NV            0x8870
+#define GL_MAX_TEXTURE_COORDS_NV          0x8871
+#define GL_MAX_TEXTURE_IMAGE_UNITS_NV     0x8872
+#define GL_FRAGMENT_PROGRAM_BINDING_NV    0x8873
+#define GL_PROGRAM_ERROR_STRING_NV        0x8874
+#endif
+
+#ifndef GL_NV_half_float
+#define GL_HALF_FLOAT_NV                  0x140B
+#endif
+
+#ifndef GL_NV_pixel_data_range
+#define GL_WRITE_PIXEL_DATA_RANGE_NV      0x8878
+#define GL_READ_PIXEL_DATA_RANGE_NV       0x8879
+#define GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV 0x887A
+#define GL_READ_PIXEL_DATA_RANGE_LENGTH_NV 0x887B
+#define GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV 0x887C
+#define GL_READ_PIXEL_DATA_RANGE_POINTER_NV 0x887D
+#endif
+
+#ifndef GL_NV_primitive_restart
+#define GL_PRIMITIVE_RESTART_NV           0x8558
+#define GL_PRIMITIVE_RESTART_INDEX_NV     0x8559
+#endif
+
+#ifndef GL_NV_texture_expand_normal
+#define GL_TEXTURE_UNSIGNED_REMAP_MODE_NV 0x888F
+#endif
+
+#ifndef GL_NV_vertex_program2
+#endif
+
+#ifndef GL_ATI_map_object_buffer
+#endif
+
+#ifndef GL_ATI_separate_stencil
+#define GL_STENCIL_BACK_FUNC_ATI          0x8800
+#define GL_STENCIL_BACK_FAIL_ATI          0x8801
+#define GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI 0x8802
+#define GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI 0x8803
+#endif
+
+#ifndef GL_ATI_vertex_attrib_array_object
+#endif
+
+#ifndef GL_EXT_depth_bounds_test
+#define GL_DEPTH_BOUNDS_TEST_EXT          0x8890
+#define GL_DEPTH_BOUNDS_EXT               0x8891
+#endif
+
+#ifndef GL_EXT_texture_mirror_clamp
+#define GL_MIRROR_CLAMP_EXT               0x8742
+#define GL_MIRROR_CLAMP_TO_EDGE_EXT       0x8743
+#define GL_MIRROR_CLAMP_TO_BORDER_EXT     0x8912
+#endif
+
+#ifndef GL_EXT_blend_equation_separate
+#define GL_BLEND_EQUATION_RGB_EXT         GL_BLEND_EQUATION
+#define GL_BLEND_EQUATION_ALPHA_EXT       0x883D
+#endif
+
+#ifndef GL_MESA_pack_invert
+#define GL_PACK_INVERT_MESA               0x8758
+#endif
+
+#ifndef GL_MESA_ycbcr_texture
+#define GL_UNSIGNED_SHORT_8_8_MESA        0x85BA
+#define GL_UNSIGNED_SHORT_8_8_REV_MESA    0x85BB
+#define GL_YCBCR_MESA                     0x8757
+#endif
+
+
+/*************************************************************/
+
+#include <stddef.h>
+#ifndef GL_VERSION_1_5
+/* GL types for handling large vertex buffer objects */
+typedef ptrdiff_t GLintptr;
+typedef ptrdiff_t GLsizeiptr;
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+/* GL types for handling large vertex buffer objects */
+typedef ptrdiff_t GLintptrARB;
+typedef ptrdiff_t GLsizeiptrARB;
+#endif
+
+#ifndef GL_ARB_shader_objects
+/* GL types for handling shader object handles and characters */
+typedef char GLcharARB;		/* native character */
+typedef unsigned int GLhandleARB;	/* shader object handle */
+#endif
+
+#ifndef GL_NV_half_float
+/* GL type for representing NVIDIA "half" floating point type in host memory */
+typedef unsigned short GLhalfNV;
+#endif
+
+#ifndef GL_VERSION_1_2
+#define GL_VERSION_1_2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendColor (GLclampf, GLclampf, GLclampf, GLclampf);
+GLAPI void APIENTRY glBlendEquation (GLenum);
+GLAPI void APIENTRY glDrawRangeElements (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
+GLAPI void APIENTRY glColorTable (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glColorTableParameterfv (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glColorTableParameteriv (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glCopyColorTable (GLenum, GLenum, GLint, GLint, GLsizei);
+GLAPI void APIENTRY glGetColorTable (GLenum, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetColorTableParameterfv (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetColorTableParameteriv (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glColorSubTable (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glCopyColorSubTable (GLenum, GLsizei, GLint, GLint, GLsizei);
+GLAPI void APIENTRY glConvolutionFilter1D (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glConvolutionFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glConvolutionParameterf (GLenum, GLenum, GLfloat);
+GLAPI void APIENTRY glConvolutionParameterfv (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glConvolutionParameteri (GLenum, GLenum, GLint);
+GLAPI void APIENTRY glConvolutionParameteriv (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glCopyConvolutionFilter1D (GLenum, GLenum, GLint, GLint, GLsizei);
+GLAPI void APIENTRY glCopyConvolutionFilter2D (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
+GLAPI void APIENTRY glGetConvolutionFilter (GLenum, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetConvolutionParameterfv (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetConvolutionParameteriv (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetSeparableFilter (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
+GLAPI void APIENTRY glSeparableFilter2D (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
+GLAPI void APIENTRY glGetHistogram (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetHistogramParameterfv (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetHistogramParameteriv (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetMinmax (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetMinmaxParameterfv (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetMinmaxParameteriv (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glHistogram (GLenum, GLsizei, GLenum, GLboolean);
+GLAPI void APIENTRY glMinmax (GLenum, GLenum, GLboolean);
+GLAPI void APIENTRY glResetHistogram (GLenum);
+GLAPI void APIENTRY glResetMinmax (GLenum);
+GLAPI void APIENTRY glTexImage3D (GLenum, GLint, GLint, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glCopyTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDCOLORPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+typedef void (APIENTRYP PFNGLCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCOLORTABLEPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIPROC) (GLenum target, GLenum pname, GLint params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSEPARABLEFILTERPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMINMAXPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLHISTOGRAMPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLMINMAXPROC) (GLenum target, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLRESETHISTOGRAMPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLRESETMINMAXPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLTEXIMAGE3DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_VERSION_1_3
+#define GL_VERSION_1_3 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glActiveTexture (GLenum);
+GLAPI void APIENTRY glClientActiveTexture (GLenum);
+GLAPI void APIENTRY glMultiTexCoord1d (GLenum, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord1dv (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord1f (GLenum, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord1fv (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord1i (GLenum, GLint);
+GLAPI void APIENTRY glMultiTexCoord1iv (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord1s (GLenum, GLshort);
+GLAPI void APIENTRY glMultiTexCoord1sv (GLenum, const GLshort *);
+GLAPI void APIENTRY glMultiTexCoord2d (GLenum, GLdouble, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord2dv (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord2f (GLenum, GLfloat, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord2fv (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord2i (GLenum, GLint, GLint);
+GLAPI void APIENTRY glMultiTexCoord2iv (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord2s (GLenum, GLshort, GLshort);
+GLAPI void APIENTRY glMultiTexCoord2sv (GLenum, const GLshort *);
+GLAPI void APIENTRY glMultiTexCoord3d (GLenum, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord3dv (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord3f (GLenum, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord3fv (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord3i (GLenum, GLint, GLint, GLint);
+GLAPI void APIENTRY glMultiTexCoord3iv (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord3s (GLenum, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glMultiTexCoord3sv (GLenum, const GLshort *);
+GLAPI void APIENTRY glMultiTexCoord4d (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord4dv (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord4f (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord4fv (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord4i (GLenum, GLint, GLint, GLint, GLint);
+GLAPI void APIENTRY glMultiTexCoord4iv (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord4s (GLenum, GLshort, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glMultiTexCoord4sv (GLenum, const GLshort *);
+GLAPI void APIENTRY glLoadTransposeMatrixf (const GLfloat *);
+GLAPI void APIENTRY glLoadTransposeMatrixd (const GLdouble *);
+GLAPI void APIENTRY glMultTransposeMatrixf (const GLfloat *);
+GLAPI void APIENTRY glMultTransposeMatrixd (const GLdouble *);
+GLAPI void APIENTRY glSampleCoverage (GLclampf, GLboolean);
+GLAPI void APIENTRY glCompressedTexImage3D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexImage2D (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexImage1D (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexSubImage3D (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexSubImage2D (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexSubImage1D (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glGetCompressedTexImage (GLenum, GLint, GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DPROC) (GLenum target, GLdouble s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FPROC) (GLenum target, GLfloat s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IPROC) (GLenum target, GLint s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SPROC) (GLenum target, GLshort s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DPROC) (GLenum target, GLdouble s, GLdouble t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FPROC) (GLenum target, GLfloat s, GLfloat t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IPROC) (GLenum target, GLint s, GLint t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SPROC) (GLenum target, GLshort s, GLshort t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IPROC) (GLenum target, GLint s, GLint t, GLint r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDPROC) (const GLdouble *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDPROC) (const GLdouble *m);
+typedef void (APIENTRYP PFNGLSAMPLECOVERAGEPROC) (GLclampf value, GLboolean invert);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEPROC) (GLenum target, GLint level, GLvoid *img);
+#endif
+
+#ifndef GL_VERSION_1_4
+#define GL_VERSION_1_4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncSeparate (GLenum, GLenum, GLenum, GLenum);
+GLAPI void APIENTRY glFogCoordf (GLfloat);
+GLAPI void APIENTRY glFogCoordfv (const GLfloat *);
+GLAPI void APIENTRY glFogCoordd (GLdouble);
+GLAPI void APIENTRY glFogCoorddv (const GLdouble *);
+GLAPI void APIENTRY glFogCoordPointer (GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glMultiDrawArrays (GLenum, GLint *, GLsizei *, GLsizei);
+GLAPI void APIENTRY glMultiDrawElements (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
+GLAPI void APIENTRY glPointParameterf (GLenum, GLfloat);
+GLAPI void APIENTRY glPointParameterfv (GLenum, const GLfloat *);
+GLAPI void APIENTRY glPointParameteri (GLenum, GLint);
+GLAPI void APIENTRY glPointParameteriv (GLenum, const GLint *);
+GLAPI void APIENTRY glSecondaryColor3b (GLbyte, GLbyte, GLbyte);
+GLAPI void APIENTRY glSecondaryColor3bv (const GLbyte *);
+GLAPI void APIENTRY glSecondaryColor3d (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glSecondaryColor3dv (const GLdouble *);
+GLAPI void APIENTRY glSecondaryColor3f (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glSecondaryColor3fv (const GLfloat *);
+GLAPI void APIENTRY glSecondaryColor3i (GLint, GLint, GLint);
+GLAPI void APIENTRY glSecondaryColor3iv (const GLint *);
+GLAPI void APIENTRY glSecondaryColor3s (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glSecondaryColor3sv (const GLshort *);
+GLAPI void APIENTRY glSecondaryColor3ub (GLubyte, GLubyte, GLubyte);
+GLAPI void APIENTRY glSecondaryColor3ubv (const GLubyte *);
+GLAPI void APIENTRY glSecondaryColor3ui (GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glSecondaryColor3uiv (const GLuint *);
+GLAPI void APIENTRY glSecondaryColor3us (GLushort, GLushort, GLushort);
+GLAPI void APIENTRY glSecondaryColor3usv (const GLushort *);
+GLAPI void APIENTRY glSecondaryColorPointer (GLint, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glWindowPos2d (GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos2dv (const GLdouble *);
+GLAPI void APIENTRY glWindowPos2f (GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos2fv (const GLfloat *);
+GLAPI void APIENTRY glWindowPos2i (GLint, GLint);
+GLAPI void APIENTRY glWindowPos2iv (const GLint *);
+GLAPI void APIENTRY glWindowPos2s (GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos2sv (const GLshort *);
+GLAPI void APIENTRY glWindowPos3d (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos3dv (const GLdouble *);
+GLAPI void APIENTRY glWindowPos3f (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos3fv (const GLfloat *);
+GLAPI void APIENTRY glWindowPos3i (GLint, GLint, GLint);
+GLAPI void APIENTRY glWindowPos3iv (const GLint *);
+GLAPI void APIENTRY glWindowPos3s (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos3sv (const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+typedef void (APIENTRYP PFNGLFOGCOORDFPROC) (GLfloat coord);
+typedef void (APIENTRYP PFNGLFOGCOORDFVPROC) (const GLfloat *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDPROC) (GLdouble coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDVPROC) (const GLdouble *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTERPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERIPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERIVPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BPROC) (GLbyte red, GLbyte green, GLbyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DPROC) (GLdouble red, GLdouble green, GLdouble blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FPROC) (GLfloat red, GLfloat green, GLfloat blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IPROC) (GLint red, GLint green, GLint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SPROC) (GLshort red, GLshort green, GLshort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBPROC) (GLubyte red, GLubyte green, GLubyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVPROC) (const GLubyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIPROC) (GLuint red, GLuint green, GLuint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVPROC) (const GLuint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USPROC) (GLushort red, GLushort green, GLushort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVPROC) (const GLushort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DPROC) (GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FPROC) (GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IPROC) (GLint x, GLint y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SPROC) (GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DPROC) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FPROC) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IPROC) (GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SPROC) (GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_VERSION_1_5
+#define GL_VERSION_1_5 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenQueries (GLsizei, GLuint *);
+GLAPI void APIENTRY glDeleteQueries (GLsizei, const GLuint *);
+GLAPI GLboolean APIENTRY glIsQuery (GLuint);
+GLAPI void APIENTRY glBeginQuery (GLenum, GLuint);
+GLAPI void APIENTRY glEndQuery (GLenum);
+GLAPI void APIENTRY glGetQueryiv (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetQueryObjectiv (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetQueryObjectuiv (GLuint, GLenum, GLuint *);
+GLAPI void APIENTRY glBindBuffer (GLenum, GLuint);
+GLAPI void APIENTRY glDeleteBuffers (GLsizei, const GLuint *);
+GLAPI void APIENTRY glGenBuffers (GLsizei, GLuint *);
+GLAPI GLboolean APIENTRY glIsBuffer (GLuint);
+GLAPI void APIENTRY glBufferData (GLenum, GLsizeiptr, const GLvoid *, GLenum);
+GLAPI void APIENTRY glBufferSubData (GLenum, GLintptr, GLsizeiptr, const GLvoid *);
+GLAPI void APIENTRY glGetBufferSubData (GLenum, GLintptr, GLsizeiptr, GLvoid *);
+GLAPI GLvoid* APIENTRY glMapBuffer (GLenum, GLenum);
+GLAPI GLboolean APIENTRY glUnmapBuffer (GLenum);
+GLAPI void APIENTRY glGetBufferParameteriv (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetBufferPointerv (GLenum, GLenum, GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids);
+typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params);
+typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
+typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
+typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
+typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
+typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
+typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_ARB_multitexture
+#define GL_ARB_multitexture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glActiveTextureARB (GLenum);
+GLAPI void APIENTRY glClientActiveTextureARB (GLenum);
+GLAPI void APIENTRY glMultiTexCoord1dARB (GLenum, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord1dvARB (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord1fARB (GLenum, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord1fvARB (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord1iARB (GLenum, GLint);
+GLAPI void APIENTRY glMultiTexCoord1ivARB (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord1sARB (GLenum, GLshort);
+GLAPI void APIENTRY glMultiTexCoord1svARB (GLenum, const GLshort *);
+GLAPI void APIENTRY glMultiTexCoord2dARB (GLenum, GLdouble, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord2dvARB (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord2fARB (GLenum, GLfloat, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord2fvARB (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord2iARB (GLenum, GLint, GLint);
+GLAPI void APIENTRY glMultiTexCoord2ivARB (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord2sARB (GLenum, GLshort, GLshort);
+GLAPI void APIENTRY glMultiTexCoord2svARB (GLenum, const GLshort *);
+GLAPI void APIENTRY glMultiTexCoord3dARB (GLenum, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord3dvARB (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord3fARB (GLenum, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord3fvARB (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord3iARB (GLenum, GLint, GLint, GLint);
+GLAPI void APIENTRY glMultiTexCoord3ivARB (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord3sARB (GLenum, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glMultiTexCoord3svARB (GLenum, const GLshort *);
+GLAPI void APIENTRY glMultiTexCoord4dARB (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glMultiTexCoord4dvARB (GLenum, const GLdouble *);
+GLAPI void APIENTRY glMultiTexCoord4fARB (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glMultiTexCoord4fvARB (GLenum, const GLfloat *);
+GLAPI void APIENTRY glMultiTexCoord4iARB (GLenum, GLint, GLint, GLint, GLint);
+GLAPI void APIENTRY glMultiTexCoord4ivARB (GLenum, const GLint *);
+GLAPI void APIENTRY glMultiTexCoord4sARB (GLenum, GLshort, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glMultiTexCoord4svARB (GLenum, const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLACTIVETEXTUREARBPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLCLIENTACTIVETEXTUREARBPROC) (GLenum texture);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DARBPROC) (GLenum target, GLdouble s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FARBPROC) (GLenum target, GLfloat s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IARBPROC) (GLenum target, GLint s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SARBPROC) (GLenum target, GLshort s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DARBPROC) (GLenum target, GLdouble s, GLdouble t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FARBPROC) (GLenum target, GLfloat s, GLfloat t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IARBPROC) (GLenum target, GLint s, GLint t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SARBPROC) (GLenum target, GLshort s, GLshort t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IARBPROC) (GLenum target, GLint s, GLint t, GLint r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3SVARBPROC) (GLenum target, const GLshort *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DARBPROC) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4DVARBPROC) (GLenum target, const GLdouble *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FARBPROC) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4FVARBPROC) (GLenum target, const GLfloat *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IARBPROC) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4IVARBPROC) (GLenum target, const GLint *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SARBPROC) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4SVARBPROC) (GLenum target, const GLshort *v);
+#endif
+
+#ifndef GL_ARB_transpose_matrix
+#define GL_ARB_transpose_matrix 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glLoadTransposeMatrixfARB (const GLfloat *);
+GLAPI void APIENTRY glLoadTransposeMatrixdARB (const GLdouble *);
+GLAPI void APIENTRY glMultTransposeMatrixfARB (const GLfloat *);
+GLAPI void APIENTRY glMultTransposeMatrixdARB (const GLdouble *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLLOADTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXFARBPROC) (const GLfloat *m);
+typedef void (APIENTRYP PFNGLMULTTRANSPOSEMATRIXDARBPROC) (const GLdouble *m);
+#endif
+
+#ifndef GL_ARB_multisample
+#define GL_ARB_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSampleCoverageARB (GLclampf, GLboolean);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSAMPLECOVERAGEARBPROC) (GLclampf value, GLboolean invert);
+#endif
+
+#ifndef GL_ARB_texture_env_add
+#define GL_ARB_texture_env_add 1
+#endif
+
+#ifndef GL_ARB_texture_cube_map
+#define GL_ARB_texture_cube_map 1
+#endif
+
+#ifndef GL_ARB_texture_compression
+#define GL_ARB_texture_compression 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCompressedTexImage3DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexImage2DARB (GLenum, GLint, GLenum, GLsizei, GLsizei, GLint, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexImage1DARB (GLenum, GLint, GLenum, GLsizei, GLint, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexSubImage3DARB (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexSubImage2DARB (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glCompressedTexSubImage1DARB (GLenum, GLint, GLint, GLsizei, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glGetCompressedTexImageARB (GLenum, GLint, GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE3DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE2DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXIMAGE1DARBPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE3DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE2DARBPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOMPRESSEDTEXSUBIMAGE1DARBPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETCOMPRESSEDTEXIMAGEARBPROC) (GLenum target, GLint level, GLvoid *img);
+#endif
+
+#ifndef GL_ARB_texture_border_clamp
+#define GL_ARB_texture_border_clamp 1
+#endif
+
+#ifndef GL_ARB_point_parameters
+#define GL_ARB_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameterfARB (GLenum, GLfloat);
+GLAPI void APIENTRY glPointParameterfvARB (GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFARBPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVARBPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_ARB_vertex_blend
+#define GL_ARB_vertex_blend 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glWeightbvARB (GLint, const GLbyte *);
+GLAPI void APIENTRY glWeightsvARB (GLint, const GLshort *);
+GLAPI void APIENTRY glWeightivARB (GLint, const GLint *);
+GLAPI void APIENTRY glWeightfvARB (GLint, const GLfloat *);
+GLAPI void APIENTRY glWeightdvARB (GLint, const GLdouble *);
+GLAPI void APIENTRY glWeightubvARB (GLint, const GLubyte *);
+GLAPI void APIENTRY glWeightusvARB (GLint, const GLushort *);
+GLAPI void APIENTRY glWeightuivARB (GLint, const GLuint *);
+GLAPI void APIENTRY glWeightPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glVertexBlendARB (GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLWEIGHTBVARBPROC) (GLint size, const GLbyte *weights);
+typedef void (APIENTRYP PFNGLWEIGHTSVARBPROC) (GLint size, const GLshort *weights);
+typedef void (APIENTRYP PFNGLWEIGHTIVARBPROC) (GLint size, const GLint *weights);
+typedef void (APIENTRYP PFNGLWEIGHTFVARBPROC) (GLint size, const GLfloat *weights);
+typedef void (APIENTRYP PFNGLWEIGHTDVARBPROC) (GLint size, const GLdouble *weights);
+typedef void (APIENTRYP PFNGLWEIGHTUBVARBPROC) (GLint size, const GLubyte *weights);
+typedef void (APIENTRYP PFNGLWEIGHTUSVARBPROC) (GLint size, const GLushort *weights);
+typedef void (APIENTRYP PFNGLWEIGHTUIVARBPROC) (GLint size, const GLuint *weights);
+typedef void (APIENTRYP PFNGLWEIGHTPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXBLENDARBPROC) (GLint count);
+#endif
+
+#ifndef GL_ARB_matrix_palette
+#define GL_ARB_matrix_palette 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCurrentPaletteMatrixARB (GLint);
+GLAPI void APIENTRY glMatrixIndexubvARB (GLint, const GLubyte *);
+GLAPI void APIENTRY glMatrixIndexusvARB (GLint, const GLushort *);
+GLAPI void APIENTRY glMatrixIndexuivARB (GLint, const GLuint *);
+GLAPI void APIENTRY glMatrixIndexPointerARB (GLint, GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCURRENTPALETTEMATRIXARBPROC) (GLint index);
+typedef void (APIENTRYP PFNGLMATRIXINDEXUBVARBPROC) (GLint size, const GLubyte *indices);
+typedef void (APIENTRYP PFNGLMATRIXINDEXUSVARBPROC) (GLint size, const GLushort *indices);
+typedef void (APIENTRYP PFNGLMATRIXINDEXUIVARBPROC) (GLint size, const GLuint *indices);
+typedef void (APIENTRYP PFNGLMATRIXINDEXPOINTERARBPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_ARB_texture_env_combine
+#define GL_ARB_texture_env_combine 1
+#endif
+
+#ifndef GL_ARB_texture_env_crossbar
+#define GL_ARB_texture_env_crossbar 1
+#endif
+
+#ifndef GL_ARB_texture_env_dot3
+#define GL_ARB_texture_env_dot3 1
+#endif
+
+#ifndef GL_ARB_texture_mirrored_repeat
+#define GL_ARB_texture_mirrored_repeat 1
+#endif
+
+#ifndef GL_ARB_depth_texture
+#define GL_ARB_depth_texture 1
+#endif
+
+#ifndef GL_ARB_shadow
+#define GL_ARB_shadow 1
+#endif
+
+#ifndef GL_ARB_shadow_ambient
+#define GL_ARB_shadow_ambient 1
+#endif
+
+#ifndef GL_ARB_window_pos
+#define GL_ARB_window_pos 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glWindowPos2dARB (GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos2dvARB (const GLdouble *);
+GLAPI void APIENTRY glWindowPos2fARB (GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos2fvARB (const GLfloat *);
+GLAPI void APIENTRY glWindowPos2iARB (GLint, GLint);
+GLAPI void APIENTRY glWindowPos2ivARB (const GLint *);
+GLAPI void APIENTRY glWindowPos2sARB (GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos2svARB (const GLshort *);
+GLAPI void APIENTRY glWindowPos3dARB (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos3dvARB (const GLdouble *);
+GLAPI void APIENTRY glWindowPos3fARB (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos3fvARB (const GLfloat *);
+GLAPI void APIENTRY glWindowPos3iARB (GLint, GLint, GLint);
+GLAPI void APIENTRY glWindowPos3ivARB (const GLint *);
+GLAPI void APIENTRY glWindowPos3sARB (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos3svARB (const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLWINDOWPOS2DARBPROC) (GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVARBPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FARBPROC) (GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVARBPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IARBPROC) (GLint x, GLint y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVARBPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SARBPROC) (GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVARBPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DARBPROC) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVARBPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FARBPROC) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVARBPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IARBPROC) (GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVARBPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SARBPROC) (GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVARBPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_ARB_vertex_program
+#define GL_ARB_vertex_program 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttrib1dARB (GLuint, GLdouble);
+GLAPI void APIENTRY glVertexAttrib1dvARB (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib1fARB (GLuint, GLfloat);
+GLAPI void APIENTRY glVertexAttrib1fvARB (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib1sARB (GLuint, GLshort);
+GLAPI void APIENTRY glVertexAttrib1svARB (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib2dARB (GLuint, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexAttrib2dvARB (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib2fARB (GLuint, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexAttrib2fvARB (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib2sARB (GLuint, GLshort, GLshort);
+GLAPI void APIENTRY glVertexAttrib2svARB (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib3dARB (GLuint, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexAttrib3dvARB (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib3fARB (GLuint, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexAttrib3fvARB (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib3sARB (GLuint, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glVertexAttrib3svARB (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib4NbvARB (GLuint, const GLbyte *);
+GLAPI void APIENTRY glVertexAttrib4NivARB (GLuint, const GLint *);
+GLAPI void APIENTRY glVertexAttrib4NsvARB (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib4NubARB (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
+GLAPI void APIENTRY glVertexAttrib4NubvARB (GLuint, const GLubyte *);
+GLAPI void APIENTRY glVertexAttrib4NuivARB (GLuint, const GLuint *);
+GLAPI void APIENTRY glVertexAttrib4NusvARB (GLuint, const GLushort *);
+GLAPI void APIENTRY glVertexAttrib4bvARB (GLuint, const GLbyte *);
+GLAPI void APIENTRY glVertexAttrib4dARB (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexAttrib4dvARB (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib4fARB (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexAttrib4fvARB (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib4ivARB (GLuint, const GLint *);
+GLAPI void APIENTRY glVertexAttrib4sARB (GLuint, GLshort, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glVertexAttrib4svARB (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib4ubvARB (GLuint, const GLubyte *);
+GLAPI void APIENTRY glVertexAttrib4uivARB (GLuint, const GLuint *);
+GLAPI void APIENTRY glVertexAttrib4usvARB (GLuint, const GLushort *);
+GLAPI void APIENTRY glVertexAttribPointerARB (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glEnableVertexAttribArrayARB (GLuint);
+GLAPI void APIENTRY glDisableVertexAttribArrayARB (GLuint);
+GLAPI void APIENTRY glProgramStringARB (GLenum, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glBindProgramARB (GLenum, GLuint);
+GLAPI void APIENTRY glDeleteProgramsARB (GLsizei, const GLuint *);
+GLAPI void APIENTRY glGenProgramsARB (GLsizei, GLuint *);
+GLAPI void APIENTRY glProgramEnvParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glProgramEnvParameter4dvARB (GLenum, GLuint, const GLdouble *);
+GLAPI void APIENTRY glProgramEnvParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glProgramEnvParameter4fvARB (GLenum, GLuint, const GLfloat *);
+GLAPI void APIENTRY glProgramLocalParameter4dARB (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glProgramLocalParameter4dvARB (GLenum, GLuint, const GLdouble *);
+GLAPI void APIENTRY glProgramLocalParameter4fARB (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glProgramLocalParameter4fvARB (GLenum, GLuint, const GLfloat *);
+GLAPI void APIENTRY glGetProgramEnvParameterdvARB (GLenum, GLuint, GLdouble *);
+GLAPI void APIENTRY glGetProgramEnvParameterfvARB (GLenum, GLuint, GLfloat *);
+GLAPI void APIENTRY glGetProgramLocalParameterdvARB (GLenum, GLuint, GLdouble *);
+GLAPI void APIENTRY glGetProgramLocalParameterfvARB (GLenum, GLuint, GLfloat *);
+GLAPI void APIENTRY glGetProgramivARB (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetProgramStringARB (GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetVertexAttribdvARB (GLuint, GLenum, GLdouble *);
+GLAPI void APIENTRY glGetVertexAttribfvARB (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetVertexAttribivARB (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetVertexAttribPointervARB (GLuint, GLenum, GLvoid* *);
+GLAPI GLboolean APIENTRY glIsProgramARB (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DARBPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FARBPROC) (GLuint index, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SARBPROC) (GLuint index, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DARBPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FARBPROC) (GLuint index, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SARBPROC) (GLuint index, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVARBPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVARBPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBARBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVARBPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVARBPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVARBPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVARBPROC) (GLuint index, const GLbyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DARBPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVARBPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FARBPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVARBPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVARBPROC) (GLuint index, const GLint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SARBPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVARBPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVARBPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVARBPROC) (GLuint index, const GLuint *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVARBPROC) (GLuint index, const GLushort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERARBPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
+typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYARBPROC) (GLuint index);
+typedef void (APIENTRYP PFNGLPROGRAMSTRINGARBPROC) (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+typedef void (APIENTRYP PFNGLBINDPROGRAMARBPROC) (GLenum target, GLuint program);
+typedef void (APIENTRYP PFNGLDELETEPROGRAMSARBPROC) (GLsizei n, const GLuint *programs);
+typedef void (APIENTRYP PFNGLGENPROGRAMSARBPROC) (GLsizei n, GLuint *programs);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMENVPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DARBPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4DVARBPROC) (GLenum target, GLuint index, const GLdouble *params);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FARBPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMLOCALPARAMETER4FVARBPROC) (GLenum target, GLuint index, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMENVPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERDVARBPROC) (GLenum target, GLuint index, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMLOCALPARAMETERFVARBPROC) (GLenum target, GLuint index, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGARBPROC) (GLenum target, GLenum pname, GLvoid *string);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVARBPROC) (GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVARBPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVARBPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVARBPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+typedef GLboolean (APIENTRYP PFNGLISPROGRAMARBPROC) (GLuint program);
+#endif
+
+#ifndef GL_ARB_fragment_program
+#define GL_ARB_fragment_program 1
+/* All ARB_fragment_program entry points are shared with ARB_vertex_program. */
+#endif
+
+#ifndef GL_ARB_vertex_buffer_object
+#define GL_ARB_vertex_buffer_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindBufferARB (GLenum, GLuint);
+GLAPI void APIENTRY glDeleteBuffersARB (GLsizei, const GLuint *);
+GLAPI void APIENTRY glGenBuffersARB (GLsizei, GLuint *);
+GLAPI GLboolean APIENTRY glIsBufferARB (GLuint);
+GLAPI void APIENTRY glBufferDataARB (GLenum, GLsizeiptrARB, const GLvoid *, GLenum);
+GLAPI void APIENTRY glBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, const GLvoid *);
+GLAPI void APIENTRY glGetBufferSubDataARB (GLenum, GLintptrARB, GLsizeiptrARB, GLvoid *);
+GLAPI GLvoid* APIENTRY glMapBufferARB (GLenum, GLenum);
+GLAPI GLboolean APIENTRY glUnmapBufferARB (GLenum);
+GLAPI void APIENTRY glGetBufferParameterivARB (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetBufferPointervARB (GLenum, GLenum, GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDBUFFERARBPROC) (GLenum target, GLuint buffer);
+typedef void (APIENTRYP PFNGLDELETEBUFFERSARBPROC) (GLsizei n, const GLuint *buffers);
+typedef void (APIENTRYP PFNGLGENBUFFERSARBPROC) (GLsizei n, GLuint *buffers);
+typedef GLboolean (APIENTRYP PFNGLISBUFFERARBPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLBUFFERDATAARBPROC) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
+typedef void (APIENTRYP PFNGLBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
+typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAARBPROC) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
+typedef GLvoid* (APIENTRYP PFNGLMAPBUFFERARBPROC) (GLenum target, GLenum access);
+typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERARBPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVARBPROC) (GLenum target, GLenum pname, GLvoid* *params);
+#endif
+
+#ifndef GL_ARB_occlusion_query
+#define GL_ARB_occlusion_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenQueriesARB (GLsizei, GLuint *);
+GLAPI void APIENTRY glDeleteQueriesARB (GLsizei, const GLuint *);
+GLAPI GLboolean APIENTRY glIsQueryARB (GLuint);
+GLAPI void APIENTRY glBeginQueryARB (GLenum, GLuint);
+GLAPI void APIENTRY glEndQueryARB (GLenum);
+GLAPI void APIENTRY glGetQueryivARB (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetQueryObjectivARB (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetQueryObjectuivARB (GLuint, GLenum, GLuint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENQUERIESARBPROC) (GLsizei n, GLuint *ids);
+typedef void (APIENTRYP PFNGLDELETEQUERIESARBPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISQUERYARBPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINQUERYARBPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLENDQUERYARBPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLGETQUERYIVARBPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVARBPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVARBPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_ARB_shader_objects
+#define GL_ARB_shader_objects 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDeleteObjectARB (GLhandleARB);
+GLAPI GLhandleARB APIENTRY glGetHandleARB (GLenum);
+GLAPI void APIENTRY glDetachObjectARB (GLhandleARB, GLhandleARB);
+GLAPI GLhandleARB APIENTRY glCreateShaderObjectARB (GLenum);
+GLAPI void APIENTRY glShaderSourceARB (GLhandleARB, GLsizei, const GLcharARB* *, const GLint *);
+GLAPI void APIENTRY glCompileShaderARB (GLhandleARB);
+GLAPI GLhandleARB APIENTRY glCreateProgramObjectARB (void);
+GLAPI void APIENTRY glAttachObjectARB (GLhandleARB, GLhandleARB);
+GLAPI void APIENTRY glLinkProgramARB (GLhandleARB);
+GLAPI void APIENTRY glUseProgramObjectARB (GLhandleARB);
+GLAPI void APIENTRY glValidateProgramARB (GLhandleARB);
+GLAPI void APIENTRY glUniform1fARB (GLint, GLfloat);
+GLAPI void APIENTRY glUniform2fARB (GLint, GLfloat, GLfloat);
+GLAPI void APIENTRY glUniform3fARB (GLint, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glUniform4fARB (GLint, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glUniform1iARB (GLint, GLint);
+GLAPI void APIENTRY glUniform2iARB (GLint, GLint, GLint);
+GLAPI void APIENTRY glUniform3iARB (GLint, GLint, GLint, GLint);
+GLAPI void APIENTRY glUniform4iARB (GLint, GLint, GLint, GLint, GLint);
+GLAPI void APIENTRY glUniform1fvARB (GLint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glUniform2fvARB (GLint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glUniform3fvARB (GLint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glUniform4fvARB (GLint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glUniform1ivARB (GLint, GLsizei, const GLint *);
+GLAPI void APIENTRY glUniform2ivARB (GLint, GLsizei, const GLint *);
+GLAPI void APIENTRY glUniform3ivARB (GLint, GLsizei, const GLint *);
+GLAPI void APIENTRY glUniform4ivARB (GLint, GLsizei, const GLint *);
+GLAPI void APIENTRY glUniformMatrix2fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
+GLAPI void APIENTRY glUniformMatrix3fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
+GLAPI void APIENTRY glUniformMatrix4fvARB (GLint, GLsizei, GLboolean, const GLfloat *);
+GLAPI void APIENTRY glGetObjectParameterfvARB (GLhandleARB, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetObjectParameterivARB (GLhandleARB, GLenum, GLint *);
+GLAPI void APIENTRY glGetInfoLogARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
+GLAPI void APIENTRY glGetAttachedObjectsARB (GLhandleARB, GLsizei, GLsizei *, GLhandleARB *);
+GLAPI GLint APIENTRY glGetUniformLocationARB (GLhandleARB, const GLcharARB *);
+GLAPI void APIENTRY glGetActiveUniformARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
+GLAPI void APIENTRY glGetUniformfvARB (GLhandleARB, GLint, GLfloat *);
+GLAPI void APIENTRY glGetUniformivARB (GLhandleARB, GLint, GLint *);
+GLAPI void APIENTRY glGetShaderSourceARB (GLhandleARB, GLsizei, GLsizei *, GLcharARB *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDELETEOBJECTARBPROC) (GLhandleARB obj);
+typedef GLhandleARB (APIENTRYP PFNGLGETHANDLEARBPROC) (GLenum pname);
+typedef void (APIENTRYP PFNGLDETACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB attachedObj);
+typedef GLhandleARB (APIENTRYP PFNGLCREATESHADEROBJECTARBPROC) (GLenum shaderType);
+typedef void (APIENTRYP PFNGLSHADERSOURCEARBPROC) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
+typedef void (APIENTRYP PFNGLCOMPILESHADERARBPROC) (GLhandleARB shaderObj);
+typedef GLhandleARB (APIENTRYP PFNGLCREATEPROGRAMOBJECTARBPROC) (void);
+typedef void (APIENTRYP PFNGLATTACHOBJECTARBPROC) (GLhandleARB containerObj, GLhandleARB obj);
+typedef void (APIENTRYP PFNGLLINKPROGRAMARBPROC) (GLhandleARB programObj);
+typedef void (APIENTRYP PFNGLUSEPROGRAMOBJECTARBPROC) (GLhandleARB programObj);
+typedef void (APIENTRYP PFNGLVALIDATEPROGRAMARBPROC) (GLhandleARB programObj);
+typedef void (APIENTRYP PFNGLUNIFORM1FARBPROC) (GLint location, GLfloat v0);
+typedef void (APIENTRYP PFNGLUNIFORM2FARBPROC) (GLint location, GLfloat v0, GLfloat v1);
+typedef void (APIENTRYP PFNGLUNIFORM3FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+typedef void (APIENTRYP PFNGLUNIFORM4FARBPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+typedef void (APIENTRYP PFNGLUNIFORM1IARBPROC) (GLint location, GLint v0);
+typedef void (APIENTRYP PFNGLUNIFORM2IARBPROC) (GLint location, GLint v0, GLint v1);
+typedef void (APIENTRYP PFNGLUNIFORM3IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2);
+typedef void (APIENTRYP PFNGLUNIFORM4IARBPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+typedef void (APIENTRYP PFNGLUNIFORM1FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM2FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM3FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM4FVARBPROC) (GLint location, GLsizei count, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORM1IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM2IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM3IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORM4IVARBPROC) (GLint location, GLsizei count, const GLint *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVARBPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERFVARBPROC) (GLhandleARB obj, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETOBJECTPARAMETERIVARBPROC) (GLhandleARB obj, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETINFOLOGARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
+typedef void (APIENTRYP PFNGLGETATTACHEDOBJECTSARBPROC) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
+typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
+typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+typedef void (APIENTRYP PFNGLGETUNIFORMFVARBPROC) (GLhandleARB programObj, GLint location, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETUNIFORMIVARBPROC) (GLhandleARB programObj, GLint location, GLint *params);
+typedef void (APIENTRYP PFNGLGETSHADERSOURCEARBPROC) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
+#endif
+
+#ifndef GL_ARB_vertex_shader
+#define GL_ARB_vertex_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindAttribLocationARB (GLhandleARB, GLuint, const GLcharARB *);
+GLAPI void APIENTRY glGetActiveAttribARB (GLhandleARB, GLuint, GLsizei, GLsizei *, GLint *, GLenum *, GLcharARB *);
+GLAPI GLint APIENTRY glGetAttribLocationARB (GLhandleARB, const GLcharARB *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONARBPROC) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
+typedef void (APIENTRYP PFNGLGETACTIVEATTRIBARBPROC) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONARBPROC) (GLhandleARB programObj, const GLcharARB *name);
+#endif
+
+#ifndef GL_ARB_fragment_shader
+#define GL_ARB_fragment_shader 1
+#endif
+
+#ifndef GL_ARB_shading_language_100
+#define GL_ARB_shading_language_100 1
+#endif
+
+#ifndef GL_ARB_texture_non_power_of_two
+#define GL_ARB_texture_non_power_of_two 1
+#endif
+
+#ifndef GL_ARB_point_sprite
+#define GL_ARB_point_sprite 1
+#endif
+
+#ifndef GL_ARB_fragment_program_shadow
+#define GL_ARB_fragment_program_shadow 1
+#endif
+
+#ifndef GL_EXT_abgr
+#define GL_EXT_abgr 1
+#endif
+
+#ifndef GL_EXT_blend_color
+#define GL_EXT_blend_color 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendColorEXT (GLclampf, GLclampf, GLclampf, GLclampf);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDCOLOREXTPROC) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+#endif
+
+#ifndef GL_EXT_polygon_offset
+#define GL_EXT_polygon_offset 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPolygonOffsetEXT (GLfloat, GLfloat);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOLYGONOFFSETEXTPROC) (GLfloat factor, GLfloat bias);
+#endif
+
+#ifndef GL_EXT_texture
+#define GL_EXT_texture 1
+#endif
+
+#ifndef GL_EXT_texture3D
+#define GL_EXT_texture3D 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage3DEXT (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXIMAGE3DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_SGIS_texture_filter4
+#define GL_SGIS_texture_filter4 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetTexFilterFuncSGIS (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glTexFilterFuncSGIS (GLenum, GLenum, GLsizei, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLfloat *weights);
+typedef void (APIENTRYP PFNGLTEXFILTERFUNCSGISPROC) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
+#endif
+
+#ifndef GL_EXT_subtexture
+#define GL_EXT_subtexture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexSubImage1DEXT (GLenum, GLint, GLint, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_EXT_copy_texture
+#define GL_EXT_copy_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCopyTexImage1DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLint);
+GLAPI void APIENTRY glCopyTexImage2DEXT (GLenum, GLint, GLenum, GLint, GLint, GLsizei, GLsizei, GLint);
+GLAPI void APIENTRY glCopyTexSubImage1DEXT (GLenum, GLint, GLint, GLint, GLint, GLsizei);
+GLAPI void APIENTRY glCopyTexSubImage2DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
+GLAPI void APIENTRY glCopyTexSubImage3DEXT (GLenum, GLint, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DEXTPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE3DEXTPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifndef GL_EXT_histogram
+#define GL_EXT_histogram 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetHistogramEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetHistogramParameterfvEXT (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetHistogramParameterivEXT (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetMinmaxEXT (GLenum, GLboolean, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetMinmaxParameterfvEXT (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetMinmaxParameterivEXT (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glHistogramEXT (GLenum, GLsizei, GLenum, GLboolean);
+GLAPI void APIENTRY glMinmaxEXT (GLenum, GLenum, GLboolean);
+GLAPI void APIENTRY glResetHistogramEXT (GLenum);
+GLAPI void APIENTRY glResetMinmaxEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETHISTOGRAMEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETHISTOGRAMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMINMAXEXTPROC) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMINMAXPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLHISTOGRAMEXTPROC) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLMINMAXEXTPROC) (GLenum target, GLenum internalformat, GLboolean sink);
+typedef void (APIENTRYP PFNGLRESETHISTOGRAMEXTPROC) (GLenum target);
+typedef void (APIENTRYP PFNGLRESETMINMAXEXTPROC) (GLenum target);
+#endif
+
+#ifndef GL_EXT_convolution
+#define GL_EXT_convolution 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glConvolutionFilter1DEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glConvolutionFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glConvolutionParameterfEXT (GLenum, GLenum, GLfloat);
+GLAPI void APIENTRY glConvolutionParameterfvEXT (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glConvolutionParameteriEXT (GLenum, GLenum, GLint);
+GLAPI void APIENTRY glConvolutionParameterivEXT (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glCopyConvolutionFilter1DEXT (GLenum, GLenum, GLint, GLint, GLsizei);
+GLAPI void APIENTRY glCopyConvolutionFilter2DEXT (GLenum, GLenum, GLint, GLint, GLsizei, GLsizei);
+GLAPI void APIENTRY glGetConvolutionFilterEXT (GLenum, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetConvolutionParameterfvEXT (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetConvolutionParameterivEXT (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetSeparableFilterEXT (GLenum, GLenum, GLenum, GLvoid *, GLvoid *, GLvoid *);
+GLAPI void APIENTRY glSeparableFilter2DEXT (GLenum, GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint params);
+typedef void (APIENTRYP PFNGLCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER1DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLCOPYCONVOLUTIONFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCONVOLUTIONPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETSEPARABLEFILTEREXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+typedef void (APIENTRYP PFNGLSEPARABLEFILTER2DEXTPROC) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+#endif
+
+#ifndef GL_EXT_color_matrix
+#define GL_EXT_color_matrix 1
+#endif
+
+#ifndef GL_SGI_color_table
+#define GL_SGI_color_table 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorTableSGI (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glColorTableParameterfvSGI (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glColorTableParameterivSGI (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glCopyColorTableSGI (GLenum, GLenum, GLint, GLint, GLsizei);
+GLAPI void APIENTRY glGetColorTableSGI (GLenum, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetColorTableParameterfvSGI (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetColorTableParameterivSGI (GLenum, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOPYCOLORTABLESGIPROC) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+typedef void (APIENTRYP PFNGLGETCOLORTABLESGIPROC) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVSGIPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVSGIPROC) (GLenum target, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_SGIX_pixel_texture
+#define GL_SGIX_pixel_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelTexGenSGIX (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELTEXGENSGIXPROC) (GLenum mode);
+#endif
+
+#ifndef GL_SGIS_pixel_texture
+#define GL_SGIS_pixel_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelTexGenParameteriSGIS (GLenum, GLint);
+GLAPI void APIENTRY glPixelTexGenParameterivSGIS (GLenum, const GLint *);
+GLAPI void APIENTRY glPixelTexGenParameterfSGIS (GLenum, GLfloat);
+GLAPI void APIENTRY glPixelTexGenParameterfvSGIS (GLenum, const GLfloat *);
+GLAPI void APIENTRY glGetPixelTexGenParameterivSGIS (GLenum, GLint *);
+GLAPI void APIENTRY glGetPixelTexGenParameterfvSGIS (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERISGISPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERIVSGISPROC) (GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPIXELTEXGENPARAMETERFVSGISPROC) (GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_SGIS_texture4D
+#define GL_SGIS_texture4D 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexImage4DSGIS (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glTexSubImage4DSGIS (GLenum, GLint, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXIMAGE4DSGISPROC) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+typedef void (APIENTRYP PFNGLTEXSUBIMAGE4DSGISPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
+#endif
+
+#ifndef GL_SGI_texture_color_table
+#define GL_SGI_texture_color_table 1
+#endif
+
+#ifndef GL_EXT_cmyka
+#define GL_EXT_cmyka 1
+#endif
+
+#ifndef GL_EXT_texture_object
+#define GL_EXT_texture_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLboolean APIENTRY glAreTexturesResidentEXT (GLsizei, const GLuint *, GLboolean *);
+GLAPI void APIENTRY glBindTextureEXT (GLenum, GLuint);
+GLAPI void APIENTRY glDeleteTexturesEXT (GLsizei, const GLuint *);
+GLAPI void APIENTRY glGenTexturesEXT (GLsizei, GLuint *);
+GLAPI GLboolean APIENTRY glIsTextureEXT (GLuint);
+GLAPI void APIENTRY glPrioritizeTexturesEXT (GLsizei, const GLuint *, const GLclampf *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLboolean (APIENTRYP PFNGLARETEXTURESRESIDENTEXTPROC) (GLsizei n, const GLuint *textures, GLboolean *residences);
+typedef void (APIENTRYP PFNGLBINDTEXTUREEXTPROC) (GLenum target, GLuint texture);
+typedef void (APIENTRYP PFNGLDELETETEXTURESEXTPROC) (GLsizei n, const GLuint *textures);
+typedef void (APIENTRYP PFNGLGENTEXTURESEXTPROC) (GLsizei n, GLuint *textures);
+typedef GLboolean (APIENTRYP PFNGLISTEXTUREEXTPROC) (GLuint texture);
+typedef void (APIENTRYP PFNGLPRIORITIZETEXTURESEXTPROC) (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+#endif
+
+#ifndef GL_SGIS_detail_texture
+#define GL_SGIS_detail_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDetailTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glGetDetailTexFuncSGIS (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDETAILTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
+typedef void (APIENTRYP PFNGLGETDETAILTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
+#endif
+
+#ifndef GL_SGIS_sharpen_texture
+#define GL_SGIS_sharpen_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSharpenTexFuncSGIS (GLenum, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glGetSharpenTexFuncSGIS (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSHARPENTEXFUNCSGISPROC) (GLenum target, GLsizei n, const GLfloat *points);
+typedef void (APIENTRYP PFNGLGETSHARPENTEXFUNCSGISPROC) (GLenum target, GLfloat *points);
+#endif
+
+#ifndef GL_EXT_packed_pixels
+#define GL_EXT_packed_pixels 1
+#endif
+
+#ifndef GL_SGIS_texture_lod
+#define GL_SGIS_texture_lod 1
+#endif
+
+#ifndef GL_SGIS_multisample
+#define GL_SGIS_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSampleMaskSGIS (GLclampf, GLboolean);
+GLAPI void APIENTRY glSamplePatternSGIS (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSAMPLEMASKSGISPROC) (GLclampf value, GLboolean invert);
+typedef void (APIENTRYP PFNGLSAMPLEPATTERNSGISPROC) (GLenum pattern);
+#endif
+
+#ifndef GL_EXT_rescale_normal
+#define GL_EXT_rescale_normal 1
+#endif
+
+#ifndef GL_EXT_vertex_array
+#define GL_EXT_vertex_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glArrayElementEXT (GLint);
+GLAPI void APIENTRY glColorPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glDrawArraysEXT (GLenum, GLint, GLsizei);
+GLAPI void APIENTRY glEdgeFlagPointerEXT (GLsizei, GLsizei, const GLboolean *);
+GLAPI void APIENTRY glGetPointervEXT (GLenum, GLvoid* *);
+GLAPI void APIENTRY glIndexPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glNormalPointerEXT (GLenum, GLsizei, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glTexCoordPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glVertexPointerEXT (GLint, GLenum, GLsizei, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLARRAYELEMENTEXTPROC) (GLint i);
+typedef void (APIENTRYP PFNGLCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLDRAWARRAYSEXTPROC) (GLenum mode, GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLEDGEFLAGPOINTEREXTPROC) (GLsizei stride, GLsizei count, const GLboolean *pointer);
+typedef void (APIENTRYP PFNGLGETPOINTERVEXTPROC) (GLenum pname, GLvoid* *params);
+typedef void (APIENTRYP PFNGLINDEXPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLNORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_misc_attribute
+#define GL_EXT_misc_attribute 1
+#endif
+
+#ifndef GL_SGIS_generate_mipmap
+#define GL_SGIS_generate_mipmap 1
+#endif
+
+#ifndef GL_SGIX_clipmap
+#define GL_SGIX_clipmap 1
+#endif
+
+#ifndef GL_SGIX_shadow
+#define GL_SGIX_shadow 1
+#endif
+
+#ifndef GL_SGIS_texture_edge_clamp
+#define GL_SGIS_texture_edge_clamp 1
+#endif
+
+#ifndef GL_SGIS_texture_border_clamp
+#define GL_SGIS_texture_border_clamp 1
+#endif
+
+#ifndef GL_EXT_blend_minmax
+#define GL_EXT_blend_minmax 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendEquationEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDEQUATIONEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_blend_subtract
+#define GL_EXT_blend_subtract 1
+#endif
+
+#ifndef GL_EXT_blend_logic_op
+#define GL_EXT_blend_logic_op 1
+#endif
+
+#ifndef GL_SGIX_interlace
+#define GL_SGIX_interlace 1
+#endif
+
+#ifndef GL_SGIX_pixel_tiles
+#define GL_SGIX_pixel_tiles 1
+#endif
+
+#ifndef GL_SGIX_texture_select
+#define GL_SGIX_texture_select 1
+#endif
+
+#ifndef GL_SGIX_sprite
+#define GL_SGIX_sprite 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSpriteParameterfSGIX (GLenum, GLfloat);
+GLAPI void APIENTRY glSpriteParameterfvSGIX (GLenum, const GLfloat *);
+GLAPI void APIENTRY glSpriteParameteriSGIX (GLenum, GLint);
+GLAPI void APIENTRY glSpriteParameterivSGIX (GLenum, const GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERFSGIXPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERFVSGIXPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERISGIXPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLSPRITEPARAMETERIVSGIXPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_SGIX_texture_multi_buffer
+#define GL_SGIX_texture_multi_buffer 1
+#endif
+
+#ifndef GL_EXT_point_parameters
+#define GL_EXT_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameterfEXT (GLenum, GLfloat);
+GLAPI void APIENTRY glPointParameterfvEXT (GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFEXTPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVEXTPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_SGIS_point_parameters
+#define GL_SGIS_point_parameters 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameterfSGIS (GLenum, GLfloat);
+GLAPI void APIENTRY glPointParameterfvSGIS (GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFSGISPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERFVSGISPROC) (GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_SGIX_instruments
+#define GL_SGIX_instruments 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLint APIENTRY glGetInstrumentsSGIX (void);
+GLAPI void APIENTRY glInstrumentsBufferSGIX (GLsizei, GLint *);
+GLAPI GLint APIENTRY glPollInstrumentsSGIX (GLint *);
+GLAPI void APIENTRY glReadInstrumentsSGIX (GLint);
+GLAPI void APIENTRY glStartInstrumentsSGIX (void);
+GLAPI void APIENTRY glStopInstrumentsSGIX (GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLint (APIENTRYP PFNGLGETINSTRUMENTSSGIXPROC) (void);
+typedef void (APIENTRYP PFNGLINSTRUMENTSBUFFERSGIXPROC) (GLsizei size, GLint *buffer);
+typedef GLint (APIENTRYP PFNGLPOLLINSTRUMENTSSGIXPROC) (GLint *marker_p);
+typedef void (APIENTRYP PFNGLREADINSTRUMENTSSGIXPROC) (GLint marker);
+typedef void (APIENTRYP PFNGLSTARTINSTRUMENTSSGIXPROC) (void);
+typedef void (APIENTRYP PFNGLSTOPINSTRUMENTSSGIXPROC) (GLint marker);
+#endif
+
+#ifndef GL_SGIX_texture_scale_bias
+#define GL_SGIX_texture_scale_bias 1
+#endif
+
+#ifndef GL_SGIX_framezoom
+#define GL_SGIX_framezoom 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFrameZoomSGIX (GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFRAMEZOOMSGIXPROC) (GLint factor);
+#endif
+
+#ifndef GL_SGIX_tag_sample_buffer
+#define GL_SGIX_tag_sample_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTagSampleBufferSGIX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTAGSAMPLEBUFFERSGIXPROC) (void);
+#endif
+
+#ifndef GL_SGIX_polynomial_ffd
+#define GL_SGIX_polynomial_ffd 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDeformationMap3dSGIX (GLenum, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, GLdouble, GLdouble, GLint, GLint, const GLdouble *);
+GLAPI void APIENTRY glDeformationMap3fSGIX (GLenum, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, GLfloat, GLfloat, GLint, GLint, const GLfloat *);
+GLAPI void APIENTRY glDeformSGIX (GLbitfield);
+GLAPI void APIENTRY glLoadIdentityDeformationMapSGIX (GLbitfield);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEFORMATIONMAP3DSGIXPROC) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
+typedef void (APIENTRYP PFNGLDEFORMATIONMAP3FSGIXPROC) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
+typedef void (APIENTRYP PFNGLDEFORMSGIXPROC) (GLbitfield mask);
+typedef void (APIENTRYP PFNGLLOADIDENTITYDEFORMATIONMAPSGIXPROC) (GLbitfield mask);
+#endif
+
+#ifndef GL_SGIX_reference_plane
+#define GL_SGIX_reference_plane 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glReferencePlaneSGIX (const GLdouble *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLREFERENCEPLANESGIXPROC) (const GLdouble *equation);
+#endif
+
+#ifndef GL_SGIX_flush_raster
+#define GL_SGIX_flush_raster 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFlushRasterSGIX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFLUSHRASTERSGIXPROC) (void);
+#endif
+
+#ifndef GL_SGIX_depth_texture
+#define GL_SGIX_depth_texture 1
+#endif
+
+#ifndef GL_SGIS_fog_function
+#define GL_SGIS_fog_function 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFogFuncSGIS (GLsizei, const GLfloat *);
+GLAPI void APIENTRY glGetFogFuncSGIS (GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFOGFUNCSGISPROC) (GLsizei n, const GLfloat *points);
+typedef void (APIENTRYP PFNGLGETFOGFUNCSGISPROC) (GLfloat *points);
+#endif
+
+#ifndef GL_SGIX_fog_offset
+#define GL_SGIX_fog_offset 1
+#endif
+
+#ifndef GL_HP_image_transform
+#define GL_HP_image_transform 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glImageTransformParameteriHP (GLenum, GLenum, GLint);
+GLAPI void APIENTRY glImageTransformParameterfHP (GLenum, GLenum, GLfloat);
+GLAPI void APIENTRY glImageTransformParameterivHP (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glImageTransformParameterfvHP (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glGetImageTransformParameterivHP (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetImageTransformParameterfvHP (GLenum, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIHPPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFHPPROC) (GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERIVHPPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETIMAGETRANSFORMPARAMETERFVHPPROC) (GLenum target, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_HP_convolution_border_modes
+#define GL_HP_convolution_border_modes 1
+#endif
+
+#ifndef GL_SGIX_texture_add_env
+#define GL_SGIX_texture_add_env 1
+#endif
+
+#ifndef GL_EXT_color_subtable
+#define GL_EXT_color_subtable 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorSubTableEXT (GLenum, GLsizei, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glCopyColorSubTableEXT (GLenum, GLsizei, GLint, GLint, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+typedef void (APIENTRYP PFNGLCOPYCOLORSUBTABLEEXTPROC) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+#endif
+
+#ifndef GL_PGI_vertex_hints
+#define GL_PGI_vertex_hints 1
+#endif
+
+#ifndef GL_PGI_misc_hints
+#define GL_PGI_misc_hints 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glHintPGI (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLHINTPGIPROC) (GLenum target, GLint mode);
+#endif
+
+#ifndef GL_EXT_paletted_texture
+#define GL_EXT_paletted_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorTableEXT (GLenum, GLenum, GLsizei, GLenum, GLenum, const GLvoid *);
+GLAPI void APIENTRY glGetColorTableEXT (GLenum, GLenum, GLenum, GLvoid *);
+GLAPI void APIENTRY glGetColorTableParameterivEXT (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetColorTableParameterfvEXT (GLenum, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORTABLEEXTPROC) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEEXTPROC) (GLenum target, GLenum format, GLenum type, GLvoid *data);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERIVEXTPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETCOLORTABLEPARAMETERFVEXTPROC) (GLenum target, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_EXT_clip_volume_hint
+#define GL_EXT_clip_volume_hint 1
+#endif
+
+#ifndef GL_SGIX_list_priority
+#define GL_SGIX_list_priority 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGetListParameterfvSGIX (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetListParameterivSGIX (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glListParameterfSGIX (GLuint, GLenum, GLfloat);
+GLAPI void APIENTRY glListParameterfvSGIX (GLuint, GLenum, const GLfloat *);
+GLAPI void APIENTRY glListParameteriSGIX (GLuint, GLenum, GLint);
+GLAPI void APIENTRY glListParameterivSGIX (GLuint, GLenum, const GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGETLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLLISTPARAMETERFSGIXPROC) (GLuint list, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLLISTPARAMETERFVSGIXPROC) (GLuint list, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLLISTPARAMETERISGIXPROC) (GLuint list, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLLISTPARAMETERIVSGIXPROC) (GLuint list, GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_SGIX_ir_instrument1
+#define GL_SGIX_ir_instrument1 1
+#endif
+
+#ifndef GL_SGIX_calligraphic_fragment
+#define GL_SGIX_calligraphic_fragment 1
+#endif
+
+#ifndef GL_SGIX_texture_lod_bias
+#define GL_SGIX_texture_lod_bias 1
+#endif
+
+#ifndef GL_SGIX_shadow_ambient
+#define GL_SGIX_shadow_ambient 1
+#endif
+
+#ifndef GL_EXT_index_texture
+#define GL_EXT_index_texture 1
+#endif
+
+#ifndef GL_EXT_index_material
+#define GL_EXT_index_material 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glIndexMaterialEXT (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLINDEXMATERIALEXTPROC) (GLenum face, GLenum mode);
+#endif
+
+#ifndef GL_EXT_index_func
+#define GL_EXT_index_func 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glIndexFuncEXT (GLenum, GLclampf);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLINDEXFUNCEXTPROC) (GLenum func, GLclampf ref);
+#endif
+
+#ifndef GL_EXT_index_array_formats
+#define GL_EXT_index_array_formats 1
+#endif
+
+#ifndef GL_EXT_compiled_vertex_array
+#define GL_EXT_compiled_vertex_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glLockArraysEXT (GLint, GLsizei);
+GLAPI void APIENTRY glUnlockArraysEXT (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLLOCKARRAYSEXTPROC) (GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLUNLOCKARRAYSEXTPROC) (void);
+#endif
+
+#ifndef GL_EXT_cull_vertex
+#define GL_EXT_cull_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCullParameterdvEXT (GLenum, GLdouble *);
+GLAPI void APIENTRY glCullParameterfvEXT (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCULLPARAMETERDVEXTPROC) (GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLCULLPARAMETERFVEXTPROC) (GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_SGIX_ycrcb
+#define GL_SGIX_ycrcb 1
+#endif
+
+#ifndef GL_SGIX_fragment_lighting
+#define GL_SGIX_fragment_lighting 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFragmentColorMaterialSGIX (GLenum, GLenum);
+GLAPI void APIENTRY glFragmentLightfSGIX (GLenum, GLenum, GLfloat);
+GLAPI void APIENTRY glFragmentLightfvSGIX (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glFragmentLightiSGIX (GLenum, GLenum, GLint);
+GLAPI void APIENTRY glFragmentLightivSGIX (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glFragmentLightModelfSGIX (GLenum, GLfloat);
+GLAPI void APIENTRY glFragmentLightModelfvSGIX (GLenum, const GLfloat *);
+GLAPI void APIENTRY glFragmentLightModeliSGIX (GLenum, GLint);
+GLAPI void APIENTRY glFragmentLightModelivSGIX (GLenum, const GLint *);
+GLAPI void APIENTRY glFragmentMaterialfSGIX (GLenum, GLenum, GLfloat);
+GLAPI void APIENTRY glFragmentMaterialfvSGIX (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glFragmentMaterialiSGIX (GLenum, GLenum, GLint);
+GLAPI void APIENTRY glFragmentMaterialivSGIX (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glGetFragmentLightfvSGIX (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetFragmentLightivSGIX (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetFragmentMaterialfvSGIX (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetFragmentMaterialivSGIX (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glLightEnviSGIX (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFRAGMENTCOLORMATERIALSGIXPROC) (GLenum face, GLenum mode);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFSGIXPROC) (GLenum light, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTISGIXPROC) (GLenum light, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFSGIXPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELFVSGIXPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELISGIXPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFRAGMENTLIGHTMODELIVSGIXPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFSGIXPROC) (GLenum face, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALISGIXPROC) (GLenum face, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTFVSGIXPROC) (GLenum light, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTLIGHTIVSGIXPROC) (GLenum light, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALFVSGIXPROC) (GLenum face, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETFRAGMENTMATERIALIVSGIXPROC) (GLenum face, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLLIGHTENVISGIXPROC) (GLenum pname, GLint param);
+#endif
+
+#ifndef GL_IBM_rasterpos_clip
+#define GL_IBM_rasterpos_clip 1
+#endif
+
+#ifndef GL_HP_texture_lighting
+#define GL_HP_texture_lighting 1
+#endif
+
+#ifndef GL_EXT_draw_range_elements
+#define GL_EXT_draw_range_elements 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawRangeElementsEXT (GLenum, GLuint, GLuint, GLsizei, GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTSEXTPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+#endif
+
+#ifndef GL_WIN_phong_shading
+#define GL_WIN_phong_shading 1
+#endif
+
+#ifndef GL_WIN_specular_fog
+#define GL_WIN_specular_fog 1
+#endif
+
+#ifndef GL_EXT_light_texture
+#define GL_EXT_light_texture 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glApplyTextureEXT (GLenum);
+GLAPI void APIENTRY glTextureLightEXT (GLenum);
+GLAPI void APIENTRY glTextureMaterialEXT (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLAPPLYTEXTUREEXTPROC) (GLenum mode);
+typedef void (APIENTRYP PFNGLTEXTURELIGHTEXTPROC) (GLenum pname);
+typedef void (APIENTRYP PFNGLTEXTUREMATERIALEXTPROC) (GLenum face, GLenum mode);
+#endif
+
+#ifndef GL_SGIX_blend_alpha_minmax
+#define GL_SGIX_blend_alpha_minmax 1
+#endif
+
+#ifndef GL_EXT_bgra
+#define GL_EXT_bgra 1
+#endif
+
+#ifndef GL_SGIX_async
+#define GL_SGIX_async 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glAsyncMarkerSGIX (GLuint);
+GLAPI GLint APIENTRY glFinishAsyncSGIX (GLuint *);
+GLAPI GLint APIENTRY glPollAsyncSGIX (GLuint *);
+GLAPI GLuint APIENTRY glGenAsyncMarkersSGIX (GLsizei);
+GLAPI void APIENTRY glDeleteAsyncMarkersSGIX (GLuint, GLsizei);
+GLAPI GLboolean APIENTRY glIsAsyncMarkerSGIX (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLASYNCMARKERSGIXPROC) (GLuint marker);
+typedef GLint (APIENTRYP PFNGLFINISHASYNCSGIXPROC) (GLuint *markerp);
+typedef GLint (APIENTRYP PFNGLPOLLASYNCSGIXPROC) (GLuint *markerp);
+typedef GLuint (APIENTRYP PFNGLGENASYNCMARKERSSGIXPROC) (GLsizei range);
+typedef void (APIENTRYP PFNGLDELETEASYNCMARKERSSGIXPROC) (GLuint marker, GLsizei range);
+typedef GLboolean (APIENTRYP PFNGLISASYNCMARKERSGIXPROC) (GLuint marker);
+#endif
+
+#ifndef GL_SGIX_async_pixel
+#define GL_SGIX_async_pixel 1
+#endif
+
+#ifndef GL_SGIX_async_histogram
+#define GL_SGIX_async_histogram 1
+#endif
+
+#ifndef GL_INTEL_parallel_arrays
+#define GL_INTEL_parallel_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexPointervINTEL (GLint, GLenum, const GLvoid* *);
+GLAPI void APIENTRY glNormalPointervINTEL (GLenum, const GLvoid* *);
+GLAPI void APIENTRY glColorPointervINTEL (GLint, GLenum, const GLvoid* *);
+GLAPI void APIENTRY glTexCoordPointervINTEL (GLint, GLenum, const GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+typedef void (APIENTRYP PFNGLNORMALPOINTERVINTELPROC) (GLenum type, const GLvoid* *pointer);
+typedef void (APIENTRYP PFNGLCOLORPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTERVINTELPROC) (GLint size, GLenum type, const GLvoid* *pointer);
+#endif
+
+#ifndef GL_HP_occlusion_test
+#define GL_HP_occlusion_test 1
+#endif
+
+#ifndef GL_EXT_pixel_transform
+#define GL_EXT_pixel_transform 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelTransformParameteriEXT (GLenum, GLenum, GLint);
+GLAPI void APIENTRY glPixelTransformParameterfEXT (GLenum, GLenum, GLfloat);
+GLAPI void APIENTRY glPixelTransformParameterivEXT (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glPixelTransformParameterfvEXT (GLenum, GLenum, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIEXTPROC) (GLenum target, GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFEXTPROC) (GLenum target, GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERIVEXTPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLPIXELTRANSFORMPARAMETERFVEXTPROC) (GLenum target, GLenum pname, const GLfloat *params);
+#endif
+
+#ifndef GL_EXT_pixel_transform_color_table
+#define GL_EXT_pixel_transform_color_table 1
+#endif
+
+#ifndef GL_EXT_shared_texture_palette
+#define GL_EXT_shared_texture_palette 1
+#endif
+
+#ifndef GL_EXT_separate_specular_color
+#define GL_EXT_separate_specular_color 1
+#endif
+
+#ifndef GL_EXT_secondary_color
+#define GL_EXT_secondary_color 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSecondaryColor3bEXT (GLbyte, GLbyte, GLbyte);
+GLAPI void APIENTRY glSecondaryColor3bvEXT (const GLbyte *);
+GLAPI void APIENTRY glSecondaryColor3dEXT (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glSecondaryColor3dvEXT (const GLdouble *);
+GLAPI void APIENTRY glSecondaryColor3fEXT (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glSecondaryColor3fvEXT (const GLfloat *);
+GLAPI void APIENTRY glSecondaryColor3iEXT (GLint, GLint, GLint);
+GLAPI void APIENTRY glSecondaryColor3ivEXT (const GLint *);
+GLAPI void APIENTRY glSecondaryColor3sEXT (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glSecondaryColor3svEXT (const GLshort *);
+GLAPI void APIENTRY glSecondaryColor3ubEXT (GLubyte, GLubyte, GLubyte);
+GLAPI void APIENTRY glSecondaryColor3ubvEXT (const GLubyte *);
+GLAPI void APIENTRY glSecondaryColor3uiEXT (GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glSecondaryColor3uivEXT (const GLuint *);
+GLAPI void APIENTRY glSecondaryColor3usEXT (GLushort, GLushort, GLushort);
+GLAPI void APIENTRY glSecondaryColor3usvEXT (const GLushort *);
+GLAPI void APIENTRY glSecondaryColorPointerEXT (GLint, GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BEXTPROC) (GLbyte red, GLbyte green, GLbyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3BVEXTPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DEXTPROC) (GLdouble red, GLdouble green, GLdouble blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3DVEXTPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FEXTPROC) (GLfloat red, GLfloat green, GLfloat blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3FVEXTPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IEXTPROC) (GLint red, GLint green, GLint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3IVEXTPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SEXTPROC) (GLshort red, GLshort green, GLshort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3SVEXTPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBEXTPROC) (GLubyte red, GLubyte green, GLubyte blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UBVEXTPROC) (const GLubyte *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIEXTPROC) (GLuint red, GLuint green, GLuint blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3UIVEXTPROC) (const GLuint *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USEXTPROC) (GLushort red, GLushort green, GLushort blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3USVEXTPROC) (const GLushort *v);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTEREXTPROC) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_texture_perturb_normal
+#define GL_EXT_texture_perturb_normal 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTextureNormalEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXTURENORMALEXTPROC) (GLenum mode);
+#endif
+
+#ifndef GL_EXT_multi_draw_arrays
+#define GL_EXT_multi_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMultiDrawArraysEXT (GLenum, GLint *, GLsizei *, GLsizei);
+GLAPI void APIENTRY glMultiDrawElementsEXT (GLenum, const GLsizei *, GLenum, const GLvoid* *, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMULTIDRAWARRAYSEXTPROC) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTSEXTPROC) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+#endif
+
+#ifndef GL_EXT_fog_coord
+#define GL_EXT_fog_coord 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFogCoordfEXT (GLfloat);
+GLAPI void APIENTRY glFogCoordfvEXT (const GLfloat *);
+GLAPI void APIENTRY glFogCoorddEXT (GLdouble);
+GLAPI void APIENTRY glFogCoorddvEXT (const GLdouble *);
+GLAPI void APIENTRY glFogCoordPointerEXT (GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFOGCOORDFEXTPROC) (GLfloat coord);
+typedef void (APIENTRYP PFNGLFOGCOORDFVEXTPROC) (const GLfloat *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDEXTPROC) (GLdouble coord);
+typedef void (APIENTRYP PFNGLFOGCOORDDVEXTPROC) (const GLdouble *coord);
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_REND_screen_coordinates
+#define GL_REND_screen_coordinates 1
+#endif
+
+#ifndef GL_EXT_coordinate_frame
+#define GL_EXT_coordinate_frame 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTangent3bEXT (GLbyte, GLbyte, GLbyte);
+GLAPI void APIENTRY glTangent3bvEXT (const GLbyte *);
+GLAPI void APIENTRY glTangent3dEXT (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glTangent3dvEXT (const GLdouble *);
+GLAPI void APIENTRY glTangent3fEXT (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTangent3fvEXT (const GLfloat *);
+GLAPI void APIENTRY glTangent3iEXT (GLint, GLint, GLint);
+GLAPI void APIENTRY glTangent3ivEXT (const GLint *);
+GLAPI void APIENTRY glTangent3sEXT (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glTangent3svEXT (const GLshort *);
+GLAPI void APIENTRY glBinormal3bEXT (GLbyte, GLbyte, GLbyte);
+GLAPI void APIENTRY glBinormal3bvEXT (const GLbyte *);
+GLAPI void APIENTRY glBinormal3dEXT (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glBinormal3dvEXT (const GLdouble *);
+GLAPI void APIENTRY glBinormal3fEXT (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glBinormal3fvEXT (const GLfloat *);
+GLAPI void APIENTRY glBinormal3iEXT (GLint, GLint, GLint);
+GLAPI void APIENTRY glBinormal3ivEXT (const GLint *);
+GLAPI void APIENTRY glBinormal3sEXT (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glBinormal3svEXT (const GLshort *);
+GLAPI void APIENTRY glTangentPointerEXT (GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glBinormalPointerEXT (GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTANGENT3BEXTPROC) (GLbyte tx, GLbyte ty, GLbyte tz);
+typedef void (APIENTRYP PFNGLTANGENT3BVEXTPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLTANGENT3DEXTPROC) (GLdouble tx, GLdouble ty, GLdouble tz);
+typedef void (APIENTRYP PFNGLTANGENT3DVEXTPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLTANGENT3FEXTPROC) (GLfloat tx, GLfloat ty, GLfloat tz);
+typedef void (APIENTRYP PFNGLTANGENT3FVEXTPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLTANGENT3IEXTPROC) (GLint tx, GLint ty, GLint tz);
+typedef void (APIENTRYP PFNGLTANGENT3IVEXTPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLTANGENT3SEXTPROC) (GLshort tx, GLshort ty, GLshort tz);
+typedef void (APIENTRYP PFNGLTANGENT3SVEXTPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLBINORMAL3BEXTPROC) (GLbyte bx, GLbyte by, GLbyte bz);
+typedef void (APIENTRYP PFNGLBINORMAL3BVEXTPROC) (const GLbyte *v);
+typedef void (APIENTRYP PFNGLBINORMAL3DEXTPROC) (GLdouble bx, GLdouble by, GLdouble bz);
+typedef void (APIENTRYP PFNGLBINORMAL3DVEXTPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLBINORMAL3FEXTPROC) (GLfloat bx, GLfloat by, GLfloat bz);
+typedef void (APIENTRYP PFNGLBINORMAL3FVEXTPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLBINORMAL3IEXTPROC) (GLint bx, GLint by, GLint bz);
+typedef void (APIENTRYP PFNGLBINORMAL3IVEXTPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLBINORMAL3SEXTPROC) (GLshort bx, GLshort by, GLshort bz);
+typedef void (APIENTRYP PFNGLBINORMAL3SVEXTPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLTANGENTPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLBINORMALPOINTEREXTPROC) (GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_EXT_texture_env_combine
+#define GL_EXT_texture_env_combine 1
+#endif
+
+#ifndef GL_APPLE_specular_vector
+#define GL_APPLE_specular_vector 1
+#endif
+
+#ifndef GL_APPLE_transform_hint
+#define GL_APPLE_transform_hint 1
+#endif
+
+#ifndef GL_SGIX_fog_scale
+#define GL_SGIX_fog_scale 1
+#endif
+
+#ifndef GL_SUNX_constant_data
+#define GL_SUNX_constant_data 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFinishTextureSUNX (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFINISHTEXTURESUNXPROC) (void);
+#endif
+
+#ifndef GL_SUN_global_alpha
+#define GL_SUN_global_alpha 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGlobalAlphaFactorbSUN (GLbyte);
+GLAPI void APIENTRY glGlobalAlphaFactorsSUN (GLshort);
+GLAPI void APIENTRY glGlobalAlphaFactoriSUN (GLint);
+GLAPI void APIENTRY glGlobalAlphaFactorfSUN (GLfloat);
+GLAPI void APIENTRY glGlobalAlphaFactordSUN (GLdouble);
+GLAPI void APIENTRY glGlobalAlphaFactorubSUN (GLubyte);
+GLAPI void APIENTRY glGlobalAlphaFactorusSUN (GLushort);
+GLAPI void APIENTRY glGlobalAlphaFactoruiSUN (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORBSUNPROC) (GLbyte factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORSSUNPROC) (GLshort factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORISUNPROC) (GLint factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORFSUNPROC) (GLfloat factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORDSUNPROC) (GLdouble factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUBSUNPROC) (GLubyte factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUSSUNPROC) (GLushort factor);
+typedef void (APIENTRYP PFNGLGLOBALALPHAFACTORUISUNPROC) (GLuint factor);
+#endif
+
+#ifndef GL_SUN_triangle_list
+#define GL_SUN_triangle_list 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glReplacementCodeuiSUN (GLuint);
+GLAPI void APIENTRY glReplacementCodeusSUN (GLushort);
+GLAPI void APIENTRY glReplacementCodeubSUN (GLubyte);
+GLAPI void APIENTRY glReplacementCodeuivSUN (const GLuint *);
+GLAPI void APIENTRY glReplacementCodeusvSUN (const GLushort *);
+GLAPI void APIENTRY glReplacementCodeubvSUN (const GLubyte *);
+GLAPI void APIENTRY glReplacementCodePointerSUN (GLenum, GLsizei, const GLvoid* *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUISUNPROC) (GLuint code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSSUNPROC) (GLushort code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBSUNPROC) (GLubyte code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVSUNPROC) (const GLuint *code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUSVSUNPROC) (const GLushort *code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUBVSUNPROC) (const GLubyte *code);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEPOINTERSUNPROC) (GLenum type, GLsizei stride, const GLvoid* *pointer);
+#endif
+
+#ifndef GL_SUN_vertex
+#define GL_SUN_vertex 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColor4ubVertex2fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat);
+GLAPI void APIENTRY glColor4ubVertex2fvSUN (const GLubyte *, const GLfloat *);
+GLAPI void APIENTRY glColor4ubVertex3fSUN (GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glColor4ubVertex3fvSUN (const GLubyte *, const GLfloat *);
+GLAPI void APIENTRY glColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glColor3fVertex3fvSUN (const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord2fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord2fVertex3fvSUN (const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord4fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord4fVertex4fvSUN (const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fSUN (GLfloat, GLfloat, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord2fColor4ubVertex3fvSUN (const GLfloat *, const GLubyte *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord2fColor3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord2fColor3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord2fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiVertex3fvSUN (const GLuint *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fSUN (GLuint, GLubyte, GLubyte, GLubyte, GLubyte, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *, const GLubyte *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiColor3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *, const GLfloat *, const GLfloat *, const GLfloat *, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX2FVSUNPROC) (const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FSUNPROC) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLCOLOR4UBVERTEX3FVSUNPROC) (const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FSUNPROC) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLTEXCOORD4FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4UBVERTEX3FVSUNPROC) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLTEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FSUNPROC) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLTEXCOORD4FCOLOR4FNORMAL3FVERTEX4FVSUNPROC) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FSUNPROC) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUIVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FSUNPROC) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4UBVERTEX3FVSUNPROC) (const GLuint *rc, const GLubyte *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUINORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUICOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FSUNPROC) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLREPLACEMENTCODEUITEXCOORD2FCOLOR4FNORMAL3FVERTEX3FVSUNPROC) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+#endif
+
+#ifndef GL_EXT_blend_func_separate
+#define GL_EXT_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncSeparateEXT (GLenum, GLenum, GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEEXTPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif
+
+#ifndef GL_INGR_blend_func_separate
+#define GL_INGR_blend_func_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendFuncSeparateINGR (GLenum, GLenum, GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEINGRPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+#endif
+
+#ifndef GL_INGR_color_clamp
+#define GL_INGR_color_clamp 1
+#endif
+
+#ifndef GL_INGR_interlace_read
+#define GL_INGR_interlace_read 1
+#endif
+
+#ifndef GL_EXT_stencil_wrap
+#define GL_EXT_stencil_wrap 1
+#endif
+
+#ifndef GL_EXT_422_pixels
+#define GL_EXT_422_pixels 1
+#endif
+
+#ifndef GL_NV_texgen_reflection
+#define GL_NV_texgen_reflection 1
+#endif
+
+#ifndef GL_SUN_convolution_border_modes
+#define GL_SUN_convolution_border_modes 1
+#endif
+
+#ifndef GL_EXT_texture_env_add
+#define GL_EXT_texture_env_add 1
+#endif
+
+#ifndef GL_EXT_texture_lod_bias
+#define GL_EXT_texture_lod_bias 1
+#endif
+
+#ifndef GL_EXT_texture_filter_anisotropic
+#define GL_EXT_texture_filter_anisotropic 1
+#endif
+
+#ifndef GL_EXT_vertex_weighting
+#define GL_EXT_vertex_weighting 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexWeightfEXT (GLfloat);
+GLAPI void APIENTRY glVertexWeightfvEXT (const GLfloat *);
+GLAPI void APIENTRY glVertexWeightPointerEXT (GLsizei, GLenum, GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTFEXTPROC) (GLfloat weight);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTFVEXTPROC) (const GLfloat *weight);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTPOINTEREXTPROC) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
+#endif
+
+#ifndef GL_NV_light_max_exponent
+#define GL_NV_light_max_exponent 1
+#endif
+
+#ifndef GL_NV_vertex_array_range
+#define GL_NV_vertex_array_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glFlushVertexArrayRangeNV (void);
+GLAPI void APIENTRY glVertexArrayRangeNV (GLsizei, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGENVPROC) (void);
+typedef void (APIENTRYP PFNGLVERTEXARRAYRANGENVPROC) (GLsizei length, const GLvoid *pointer);
+#endif
+
+#ifndef GL_NV_register_combiners
+#define GL_NV_register_combiners 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCombinerParameterfvNV (GLenum, const GLfloat *);
+GLAPI void APIENTRY glCombinerParameterfNV (GLenum, GLfloat);
+GLAPI void APIENTRY glCombinerParameterivNV (GLenum, const GLint *);
+GLAPI void APIENTRY glCombinerParameteriNV (GLenum, GLint);
+GLAPI void APIENTRY glCombinerInputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum);
+GLAPI void APIENTRY glCombinerOutputNV (GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLenum, GLboolean, GLboolean, GLboolean);
+GLAPI void APIENTRY glFinalCombinerInputNV (GLenum, GLenum, GLenum, GLenum);
+GLAPI void APIENTRY glGetCombinerInputParameterfvNV (GLenum, GLenum, GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetCombinerInputParameterivNV (GLenum, GLenum, GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetCombinerOutputParameterfvNV (GLenum, GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetCombinerOutputParameterivNV (GLenum, GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetFinalCombinerInputParameterfvNV (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetFinalCombinerInputParameterivNV (GLenum, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFVNVPROC) (GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERFNVPROC) (GLenum pname, GLfloat param);
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLCOMBINERPARAMETERINVPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLCOMBINERINPUTNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+typedef void (APIENTRYP PFNGLCOMBINEROUTPUTNVPROC) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
+typedef void (APIENTRYP PFNGLFINALCOMBINERINPUTNVPROC) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOMBINERINPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERFVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOMBINEROUTPUTPARAMETERIVNVPROC) (GLenum stage, GLenum portion, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERFVNVPROC) (GLenum variable, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETFINALCOMBINERINPUTPARAMETERIVNVPROC) (GLenum variable, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_NV_fog_distance
+#define GL_NV_fog_distance 1
+#endif
+
+#ifndef GL_NV_texgen_emboss
+#define GL_NV_texgen_emboss 1
+#endif
+
+#ifndef GL_NV_blend_square
+#define GL_NV_blend_square 1
+#endif
+
+#ifndef GL_NV_texture_env_combine4
+#define GL_NV_texture_env_combine4 1
+#endif
+
+#ifndef GL_MESA_resize_buffers
+#define GL_MESA_resize_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glResizeBuffersMESA (void);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLRESIZEBUFFERSMESAPROC) (void);
+#endif
+
+#ifndef GL_MESA_window_pos
+#define GL_MESA_window_pos 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glWindowPos2dMESA (GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos2dvMESA (const GLdouble *);
+GLAPI void APIENTRY glWindowPos2fMESA (GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos2fvMESA (const GLfloat *);
+GLAPI void APIENTRY glWindowPos2iMESA (GLint, GLint);
+GLAPI void APIENTRY glWindowPos2ivMESA (const GLint *);
+GLAPI void APIENTRY glWindowPos2sMESA (GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos2svMESA (const GLshort *);
+GLAPI void APIENTRY glWindowPos3dMESA (GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos3dvMESA (const GLdouble *);
+GLAPI void APIENTRY glWindowPos3fMESA (GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos3fvMESA (const GLfloat *);
+GLAPI void APIENTRY glWindowPos3iMESA (GLint, GLint, GLint);
+GLAPI void APIENTRY glWindowPos3ivMESA (const GLint *);
+GLAPI void APIENTRY glWindowPos3sMESA (GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos3svMESA (const GLshort *);
+GLAPI void APIENTRY glWindowPos4dMESA (GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glWindowPos4dvMESA (const GLdouble *);
+GLAPI void APIENTRY glWindowPos4fMESA (GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glWindowPos4fvMESA (const GLfloat *);
+GLAPI void APIENTRY glWindowPos4iMESA (GLint, GLint, GLint, GLint);
+GLAPI void APIENTRY glWindowPos4ivMESA (const GLint *);
+GLAPI void APIENTRY glWindowPos4sMESA (GLshort, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glWindowPos4svMESA (const GLshort *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLWINDOWPOS2DMESAPROC) (GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2DVMESAPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FMESAPROC) (GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2FVMESAPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IMESAPROC) (GLint x, GLint y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2IVMESAPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SMESAPROC) (GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLWINDOWPOS2SVMESAPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DMESAPROC) (GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3DVMESAPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FMESAPROC) (GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3FVMESAPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IMESAPROC) (GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3IVMESAPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SMESAPROC) (GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLWINDOWPOS3SVMESAPROC) (const GLshort *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4DMESAPROC) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4DVMESAPROC) (const GLdouble *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4FMESAPROC) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4FVMESAPROC) (const GLfloat *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4IMESAPROC) (GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4IVMESAPROC) (const GLint *v);
+typedef void (APIENTRYP PFNGLWINDOWPOS4SMESAPROC) (GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLWINDOWPOS4SVMESAPROC) (const GLshort *v);
+#endif
+
+#ifndef GL_IBM_cull_vertex
+#define GL_IBM_cull_vertex 1
+#endif
+
+#ifndef GL_IBM_multimode_draw_arrays
+#define GL_IBM_multimode_draw_arrays 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMultiModeDrawArraysIBM (const GLenum *, const GLint *, const GLsizei *, GLsizei, GLint);
+GLAPI void APIENTRY glMultiModeDrawElementsIBM (const GLenum *, const GLsizei *, GLenum, const GLvoid* const *, GLsizei, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMULTIMODEDRAWARRAYSIBMPROC) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
+typedef void (APIENTRYP PFNGLMULTIMODEDRAWELEMENTSIBMPROC) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
+#endif
+
+#ifndef GL_IBM_vertex_array_lists
+#define GL_IBM_vertex_array_lists 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+GLAPI void APIENTRY glSecondaryColorPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+GLAPI void APIENTRY glEdgeFlagPointerListIBM (GLint, const GLboolean* *, GLint);
+GLAPI void APIENTRY glFogCoordPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
+GLAPI void APIENTRY glIndexPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
+GLAPI void APIENTRY glNormalPointerListIBM (GLenum, GLint, const GLvoid* *, GLint);
+GLAPI void APIENTRY glTexCoordPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+GLAPI void APIENTRY glVertexPointerListIBM (GLint, GLenum, GLint, const GLvoid* *, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLSECONDARYCOLORPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLEDGEFLAGPOINTERLISTIBMPROC) (GLint stride, const GLboolean* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLFOGCOORDPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLINDEXPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLNORMALPOINTERLISTIBMPROC) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLTEXCOORDPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+typedef void (APIENTRYP PFNGLVERTEXPOINTERLISTIBMPROC) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+#endif
+
+#ifndef GL_SGIX_subsample
+#define GL_SGIX_subsample 1
+#endif
+
+#ifndef GL_SGIX_ycrcba
+#define GL_SGIX_ycrcba 1
+#endif
+
+#ifndef GL_SGIX_ycrcb_subsample
+#define GL_SGIX_ycrcb_subsample 1
+#endif
+
+#ifndef GL_SGIX_depth_pass_instrument
+#define GL_SGIX_depth_pass_instrument 1
+#endif
+
+#ifndef GL_3DFX_texture_compression_FXT1
+#define GL_3DFX_texture_compression_FXT1 1
+#endif
+
+#ifndef GL_3DFX_multisample
+#define GL_3DFX_multisample 1
+#endif
+
+#ifndef GL_3DFX_tbuffer
+#define GL_3DFX_tbuffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTbufferMask3DFX (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTBUFFERMASK3DFXPROC) (GLuint mask);
+#endif
+
+#ifndef GL_EXT_multisample
+#define GL_EXT_multisample 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glSampleMaskEXT (GLclampf, GLboolean);
+GLAPI void APIENTRY glSamplePatternEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSAMPLEMASKEXTPROC) (GLclampf value, GLboolean invert);
+typedef void (APIENTRYP PFNGLSAMPLEPATTERNEXTPROC) (GLenum pattern);
+#endif
+
+#ifndef GL_SGIX_vertex_preclip
+#define GL_SGIX_vertex_preclip 1
+#endif
+
+#ifndef GL_SGIX_convolution_accuracy
+#define GL_SGIX_convolution_accuracy 1
+#endif
+
+#ifndef GL_SGIX_resample
+#define GL_SGIX_resample 1
+#endif
+
+#ifndef GL_SGIS_point_line_texgen
+#define GL_SGIS_point_line_texgen 1
+#endif
+
+#ifndef GL_SGIS_texture_color_mask
+#define GL_SGIS_texture_color_mask 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTextureColorMaskSGIS (GLboolean, GLboolean, GLboolean, GLboolean);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXTURECOLORMASKSGISPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+#endif
+
+#ifndef GL_SGIX_igloo_interface
+#define GL_SGIX_igloo_interface 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glIglooInterfaceSGIX (GLenum, const GLvoid *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLIGLOOINTERFACESGIXPROC) (GLenum pname, const GLvoid *params);
+#endif
+
+#ifndef GL_EXT_texture_env_dot3
+#define GL_EXT_texture_env_dot3 1
+#endif
+
+#ifndef GL_ATI_texture_mirror_once
+#define GL_ATI_texture_mirror_once 1
+#endif
+
+#ifndef GL_NV_fence
+#define GL_NV_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDeleteFencesNV (GLsizei, const GLuint *);
+GLAPI void APIENTRY glGenFencesNV (GLsizei, GLuint *);
+GLAPI GLboolean APIENTRY glIsFenceNV (GLuint);
+GLAPI GLboolean APIENTRY glTestFenceNV (GLuint);
+GLAPI void APIENTRY glGetFenceivNV (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glFinishFenceNV (GLuint);
+GLAPI void APIENTRY glSetFenceNV (GLuint, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDELETEFENCESNVPROC) (GLsizei n, const GLuint *fences);
+typedef void (APIENTRYP PFNGLGENFENCESNVPROC) (GLsizei n, GLuint *fences);
+typedef GLboolean (APIENTRYP PFNGLISFENCENVPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLTESTFENCENVPROC) (GLuint fence);
+typedef void (APIENTRYP PFNGLGETFENCEIVNVPROC) (GLuint fence, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLFINISHFENCENVPROC) (GLuint fence);
+typedef void (APIENTRYP PFNGLSETFENCENVPROC) (GLuint fence, GLenum condition);
+#endif
+
+#ifndef GL_NV_evaluators
+#define GL_NV_evaluators 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLint, GLint, GLboolean, const GLvoid *);
+GLAPI void APIENTRY glMapParameterivNV (GLenum, GLenum, const GLint *);
+GLAPI void APIENTRY glMapParameterfvNV (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glGetMapControlPointsNV (GLenum, GLuint, GLenum, GLsizei, GLsizei, GLboolean, GLvoid *);
+GLAPI void APIENTRY glGetMapParameterivNV (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glGetMapParameterfvNV (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetMapAttribParameterivNV (GLenum, GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetMapAttribParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glEvalMapsNV (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
+typedef void (APIENTRYP PFNGLMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, const GLint *params);
+typedef void (APIENTRYP PFNGLMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMAPCONTROLPOINTSNVPROC) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
+typedef void (APIENTRYP PFNGLGETMAPPARAMETERIVNVPROC) (GLenum target, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMAPPARAMETERFVNVPROC) (GLenum target, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERIVNVPROC) (GLenum target, GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETMAPATTRIBPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLEVALMAPSNVPROC) (GLenum target, GLenum mode);
+#endif
+
+#ifndef GL_NV_packed_depth_stencil
+#define GL_NV_packed_depth_stencil 1
+#endif
+
+#ifndef GL_NV_register_combiners2
+#define GL_NV_register_combiners2 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glCombinerStageParameterfvNV (GLenum, GLenum, const GLfloat *);
+GLAPI void APIENTRY glGetCombinerStageParameterfvNV (GLenum, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGETCOMBINERSTAGEPARAMETERFVNVPROC) (GLenum stage, GLenum pname, GLfloat *params);
+#endif
+
+#ifndef GL_NV_texture_compression_vtc
+#define GL_NV_texture_compression_vtc 1
+#endif
+
+#ifndef GL_NV_texture_rectangle
+#define GL_NV_texture_rectangle 1
+#endif
+
+#ifndef GL_NV_texture_shader
+#define GL_NV_texture_shader 1
+#endif
+
+#ifndef GL_NV_texture_shader2
+#define GL_NV_texture_shader2 1
+#endif
+
+#ifndef GL_NV_vertex_array_range2
+#define GL_NV_vertex_array_range2 1
+#endif
+
+#ifndef GL_NV_vertex_program
+#define GL_NV_vertex_program 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLboolean APIENTRY glAreProgramsResidentNV (GLsizei, const GLuint *, GLboolean *);
+GLAPI void APIENTRY glBindProgramNV (GLenum, GLuint);
+GLAPI void APIENTRY glDeleteProgramsNV (GLsizei, const GLuint *);
+GLAPI void APIENTRY glExecuteProgramNV (GLenum, GLuint, const GLfloat *);
+GLAPI void APIENTRY glGenProgramsNV (GLsizei, GLuint *);
+GLAPI void APIENTRY glGetProgramParameterdvNV (GLenum, GLuint, GLenum, GLdouble *);
+GLAPI void APIENTRY glGetProgramParameterfvNV (GLenum, GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetProgramivNV (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetProgramStringNV (GLuint, GLenum, GLubyte *);
+GLAPI void APIENTRY glGetTrackMatrixivNV (GLenum, GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetVertexAttribdvNV (GLuint, GLenum, GLdouble *);
+GLAPI void APIENTRY glGetVertexAttribfvNV (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetVertexAttribivNV (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetVertexAttribPointervNV (GLuint, GLenum, GLvoid* *);
+GLAPI GLboolean APIENTRY glIsProgramNV (GLuint);
+GLAPI void APIENTRY glLoadProgramNV (GLenum, GLuint, GLsizei, const GLubyte *);
+GLAPI void APIENTRY glProgramParameter4dNV (GLenum, GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glProgramParameter4dvNV (GLenum, GLuint, const GLdouble *);
+GLAPI void APIENTRY glProgramParameter4fNV (GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glProgramParameter4fvNV (GLenum, GLuint, const GLfloat *);
+GLAPI void APIENTRY glProgramParameters4dvNV (GLenum, GLuint, GLuint, const GLdouble *);
+GLAPI void APIENTRY glProgramParameters4fvNV (GLenum, GLuint, GLuint, const GLfloat *);
+GLAPI void APIENTRY glRequestResidentProgramsNV (GLsizei, const GLuint *);
+GLAPI void APIENTRY glTrackMatrixNV (GLenum, GLuint, GLenum, GLenum);
+GLAPI void APIENTRY glVertexAttribPointerNV (GLuint, GLint, GLenum, GLsizei, const GLvoid *);
+GLAPI void APIENTRY glVertexAttrib1dNV (GLuint, GLdouble);
+GLAPI void APIENTRY glVertexAttrib1dvNV (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib1fNV (GLuint, GLfloat);
+GLAPI void APIENTRY glVertexAttrib1fvNV (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib1sNV (GLuint, GLshort);
+GLAPI void APIENTRY glVertexAttrib1svNV (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib2dNV (GLuint, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexAttrib2dvNV (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib2fNV (GLuint, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexAttrib2fvNV (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib2sNV (GLuint, GLshort, GLshort);
+GLAPI void APIENTRY glVertexAttrib2svNV (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib3dNV (GLuint, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexAttrib3dvNV (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib3fNV (GLuint, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexAttrib3fvNV (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib3sNV (GLuint, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glVertexAttrib3svNV (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib4dNV (GLuint, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexAttrib4dvNV (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVertexAttrib4fNV (GLuint, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexAttrib4fvNV (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVertexAttrib4sNV (GLuint, GLshort, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glVertexAttrib4svNV (GLuint, const GLshort *);
+GLAPI void APIENTRY glVertexAttrib4ubNV (GLuint, GLubyte, GLubyte, GLubyte, GLubyte);
+GLAPI void APIENTRY glVertexAttrib4ubvNV (GLuint, const GLubyte *);
+GLAPI void APIENTRY glVertexAttribs1dvNV (GLuint, GLsizei, const GLdouble *);
+GLAPI void APIENTRY glVertexAttribs1fvNV (GLuint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glVertexAttribs1svNV (GLuint, GLsizei, const GLshort *);
+GLAPI void APIENTRY glVertexAttribs2dvNV (GLuint, GLsizei, const GLdouble *);
+GLAPI void APIENTRY glVertexAttribs2fvNV (GLuint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glVertexAttribs2svNV (GLuint, GLsizei, const GLshort *);
+GLAPI void APIENTRY glVertexAttribs3dvNV (GLuint, GLsizei, const GLdouble *);
+GLAPI void APIENTRY glVertexAttribs3fvNV (GLuint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glVertexAttribs3svNV (GLuint, GLsizei, const GLshort *);
+GLAPI void APIENTRY glVertexAttribs4dvNV (GLuint, GLsizei, const GLdouble *);
+GLAPI void APIENTRY glVertexAttribs4fvNV (GLuint, GLsizei, const GLfloat *);
+GLAPI void APIENTRY glVertexAttribs4svNV (GLuint, GLsizei, const GLshort *);
+GLAPI void APIENTRY glVertexAttribs4ubvNV (GLuint, GLsizei, const GLubyte *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLboolean (APIENTRYP PFNGLAREPROGRAMSRESIDENTNVPROC) (GLsizei n, const GLuint *programs, GLboolean *residences);
+typedef void (APIENTRYP PFNGLBINDPROGRAMNVPROC) (GLenum target, GLuint id);
+typedef void (APIENTRYP PFNGLDELETEPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
+typedef void (APIENTRYP PFNGLEXECUTEPROGRAMNVPROC) (GLenum target, GLuint id, const GLfloat *params);
+typedef void (APIENTRYP PFNGLGENPROGRAMSNVPROC) (GLsizei n, GLuint *programs);
+typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERDVNVPROC) (GLenum target, GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMPARAMETERFVNVPROC) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMIVNVPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMSTRINGNVPROC) (GLuint id, GLenum pname, GLubyte *program);
+typedef void (APIENTRYP PFNGLGETTRACKMATRIXIVNVPROC) (GLenum target, GLuint address, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVNVPROC) (GLuint index, GLenum pname, GLdouble *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVNVPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVNVPROC) (GLuint index, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVNVPROC) (GLuint index, GLenum pname, GLvoid* *pointer);
+typedef GLboolean (APIENTRYP PFNGLISPROGRAMNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLLOADPROGRAMNVPROC) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DNVPROC) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4DVNVPROC) (GLenum target, GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FNVPROC) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETER4FVNVPROC) (GLenum target, GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4DVNVPROC) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLPROGRAMPARAMETERS4FVNVPROC) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLREQUESTRESIDENTPROGRAMSNVPROC) (GLsizei n, const GLuint *programs);
+typedef void (APIENTRYP PFNGLTRACKMATRIXNVPROC) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERNVPROC) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DNVPROC) (GLuint index, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FNVPROC) (GLuint index, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SNVPROC) (GLuint index, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DNVPROC) (GLuint index, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FNVPROC) (GLuint index, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SNVPROC) (GLuint index, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DNVPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVNVPROC) (GLuint index, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FNVPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVNVPROC) (GLuint index, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SNVPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVNVPROC) (GLuint index, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBNVPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVNVPROC) (GLuint index, const GLubyte *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4DVNVPROC) (GLuint index, GLsizei count, const GLdouble *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4FVNVPROC) (GLuint index, GLsizei count, const GLfloat *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4SVNVPROC) (GLuint index, GLsizei count, const GLshort *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4UBVNVPROC) (GLuint index, GLsizei count, const GLubyte *v);
+#endif
+
+#ifndef GL_SGIX_texture_coordinate_clamp
+#define GL_SGIX_texture_coordinate_clamp 1
+#endif
+
+#ifndef GL_SGIX_scalebias_hint
+#define GL_SGIX_scalebias_hint 1
+#endif
+
+#ifndef GL_OML_interlace
+#define GL_OML_interlace 1
+#endif
+
+#ifndef GL_OML_subsample
+#define GL_OML_subsample 1
+#endif
+
+#ifndef GL_OML_resample
+#define GL_OML_resample 1
+#endif
+
+#ifndef GL_NV_copy_depth_to_color
+#define GL_NV_copy_depth_to_color 1
+#endif
+
+#ifndef GL_ATI_envmap_bumpmap
+#define GL_ATI_envmap_bumpmap 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glTexBumpParameterivATI (GLenum, const GLint *);
+GLAPI void APIENTRY glTexBumpParameterfvATI (GLenum, const GLfloat *);
+GLAPI void APIENTRY glGetTexBumpParameterivATI (GLenum, GLint *);
+GLAPI void APIENTRY glGetTexBumpParameterfvATI (GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERIVATIPROC) (GLenum pname, const GLint *param);
+typedef void (APIENTRYP PFNGLTEXBUMPPARAMETERFVATIPROC) (GLenum pname, const GLfloat *param);
+typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERIVATIPROC) (GLenum pname, GLint *param);
+typedef void (APIENTRYP PFNGLGETTEXBUMPPARAMETERFVATIPROC) (GLenum pname, GLfloat *param);
+#endif
+
+#ifndef GL_ATI_fragment_shader
+#define GL_ATI_fragment_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLuint APIENTRY glGenFragmentShadersATI (GLuint);
+GLAPI void APIENTRY glBindFragmentShaderATI (GLuint);
+GLAPI void APIENTRY glDeleteFragmentShaderATI (GLuint);
+GLAPI void APIENTRY glBeginFragmentShaderATI (void);
+GLAPI void APIENTRY glEndFragmentShaderATI (void);
+GLAPI void APIENTRY glPassTexCoordATI (GLuint, GLuint, GLenum);
+GLAPI void APIENTRY glSampleMapATI (GLuint, GLuint, GLenum);
+GLAPI void APIENTRY glColorFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glColorFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glColorFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glAlphaFragmentOp1ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glAlphaFragmentOp2ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glAlphaFragmentOp3ATI (GLenum, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glSetFragmentShaderConstantATI (GLuint, const GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLuint (APIENTRYP PFNGLGENFRAGMENTSHADERSATIPROC) (GLuint range);
+typedef void (APIENTRYP PFNGLBINDFRAGMENTSHADERATIPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLDELETEFRAGMENTSHADERATIPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINFRAGMENTSHADERATIPROC) (void);
+typedef void (APIENTRYP PFNGLENDFRAGMENTSHADERATIPROC) (void);
+typedef void (APIENTRYP PFNGLPASSTEXCOORDATIPROC) (GLuint dst, GLuint coord, GLenum swizzle);
+typedef void (APIENTRYP PFNGLSAMPLEMAPATIPROC) (GLuint dst, GLuint interp, GLenum swizzle);
+typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+typedef void (APIENTRYP PFNGLCOLORFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP1ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP2ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+typedef void (APIENTRYP PFNGLALPHAFRAGMENTOP3ATIPROC) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+typedef void (APIENTRYP PFNGLSETFRAGMENTSHADERCONSTANTATIPROC) (GLuint dst, const GLfloat *value);
+#endif
+
+#ifndef GL_ATI_pn_triangles
+#define GL_ATI_pn_triangles 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPNTrianglesiATI (GLenum, GLint);
+GLAPI void APIENTRY glPNTrianglesfATI (GLenum, GLfloat);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPNTRIANGLESIATIPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPNTRIANGLESFATIPROC) (GLenum pname, GLfloat param);
+#endif
+
+#ifndef GL_ATI_vertex_array_object
+#define GL_ATI_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLuint APIENTRY glNewObjectBufferATI (GLsizei, const GLvoid *, GLenum);
+GLAPI GLboolean APIENTRY glIsObjectBufferATI (GLuint);
+GLAPI void APIENTRY glUpdateObjectBufferATI (GLuint, GLuint, GLsizei, const GLvoid *, GLenum);
+GLAPI void APIENTRY glGetObjectBufferfvATI (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetObjectBufferivATI (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glFreeObjectBufferATI (GLuint);
+GLAPI void APIENTRY glArrayObjectATI (GLenum, GLint, GLenum, GLsizei, GLuint, GLuint);
+GLAPI void APIENTRY glGetArrayObjectfvATI (GLenum, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetArrayObjectivATI (GLenum, GLenum, GLint *);
+GLAPI void APIENTRY glVariantArrayObjectATI (GLuint, GLenum, GLsizei, GLuint, GLuint);
+GLAPI void APIENTRY glGetVariantArrayObjectfvATI (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetVariantArrayObjectivATI (GLuint, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLuint (APIENTRYP PFNGLNEWOBJECTBUFFERATIPROC) (GLsizei size, const GLvoid *pointer, GLenum usage);
+typedef GLboolean (APIENTRYP PFNGLISOBJECTBUFFERATIPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLUPDATEOBJECTBUFFERATIPROC) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
+typedef void (APIENTRYP PFNGLGETOBJECTBUFFERFVATIPROC) (GLuint buffer, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETOBJECTBUFFERIVATIPROC) (GLuint buffer, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLFREEOBJECTBUFFERATIPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLARRAYOBJECTATIPROC) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+typedef void (APIENTRYP PFNGLGETARRAYOBJECTFVATIPROC) (GLenum array, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETARRAYOBJECTIVATIPROC) (GLenum array, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLVARIANTARRAYOBJECTATIPROC) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTFVATIPROC) (GLuint id, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVARIANTARRAYOBJECTIVATIPROC) (GLuint id, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_EXT_vertex_shader
+#define GL_EXT_vertex_shader 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBeginVertexShaderEXT (void);
+GLAPI void APIENTRY glEndVertexShaderEXT (void);
+GLAPI void APIENTRY glBindVertexShaderEXT (GLuint);
+GLAPI GLuint APIENTRY glGenVertexShadersEXT (GLuint);
+GLAPI void APIENTRY glDeleteVertexShaderEXT (GLuint);
+GLAPI void APIENTRY glShaderOp1EXT (GLenum, GLuint, GLuint);
+GLAPI void APIENTRY glShaderOp2EXT (GLenum, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glShaderOp3EXT (GLenum, GLuint, GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glSwizzleEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
+GLAPI void APIENTRY glWriteMaskEXT (GLuint, GLuint, GLenum, GLenum, GLenum, GLenum);
+GLAPI void APIENTRY glInsertComponentEXT (GLuint, GLuint, GLuint);
+GLAPI void APIENTRY glExtractComponentEXT (GLuint, GLuint, GLuint);
+GLAPI GLuint APIENTRY glGenSymbolsEXT (GLenum, GLenum, GLenum, GLuint);
+GLAPI void APIENTRY glSetInvariantEXT (GLuint, GLenum, const GLvoid *);
+GLAPI void APIENTRY glSetLocalConstantEXT (GLuint, GLenum, const GLvoid *);
+GLAPI void APIENTRY glVariantbvEXT (GLuint, const GLbyte *);
+GLAPI void APIENTRY glVariantsvEXT (GLuint, const GLshort *);
+GLAPI void APIENTRY glVariantivEXT (GLuint, const GLint *);
+GLAPI void APIENTRY glVariantfvEXT (GLuint, const GLfloat *);
+GLAPI void APIENTRY glVariantdvEXT (GLuint, const GLdouble *);
+GLAPI void APIENTRY glVariantubvEXT (GLuint, const GLubyte *);
+GLAPI void APIENTRY glVariantusvEXT (GLuint, const GLushort *);
+GLAPI void APIENTRY glVariantuivEXT (GLuint, const GLuint *);
+GLAPI void APIENTRY glVariantPointerEXT (GLuint, GLenum, GLuint, const GLvoid *);
+GLAPI void APIENTRY glEnableVariantClientStateEXT (GLuint);
+GLAPI void APIENTRY glDisableVariantClientStateEXT (GLuint);
+GLAPI GLuint APIENTRY glBindLightParameterEXT (GLenum, GLenum);
+GLAPI GLuint APIENTRY glBindMaterialParameterEXT (GLenum, GLenum);
+GLAPI GLuint APIENTRY glBindTexGenParameterEXT (GLenum, GLenum, GLenum);
+GLAPI GLuint APIENTRY glBindTextureUnitParameterEXT (GLenum, GLenum);
+GLAPI GLuint APIENTRY glBindParameterEXT (GLenum);
+GLAPI GLboolean APIENTRY glIsVariantEnabledEXT (GLuint, GLenum);
+GLAPI void APIENTRY glGetVariantBooleanvEXT (GLuint, GLenum, GLboolean *);
+GLAPI void APIENTRY glGetVariantIntegervEXT (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetVariantFloatvEXT (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetVariantPointervEXT (GLuint, GLenum, GLvoid* *);
+GLAPI void APIENTRY glGetInvariantBooleanvEXT (GLuint, GLenum, GLboolean *);
+GLAPI void APIENTRY glGetInvariantIntegervEXT (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetInvariantFloatvEXT (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetLocalConstantBooleanvEXT (GLuint, GLenum, GLboolean *);
+GLAPI void APIENTRY glGetLocalConstantIntegervEXT (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetLocalConstantFloatvEXT (GLuint, GLenum, GLfloat *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBEGINVERTEXSHADEREXTPROC) (void);
+typedef void (APIENTRYP PFNGLENDVERTEXSHADEREXTPROC) (void);
+typedef void (APIENTRYP PFNGLBINDVERTEXSHADEREXTPROC) (GLuint id);
+typedef GLuint (APIENTRYP PFNGLGENVERTEXSHADERSEXTPROC) (GLuint range);
+typedef void (APIENTRYP PFNGLDELETEVERTEXSHADEREXTPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLSHADEROP1EXTPROC) (GLenum op, GLuint res, GLuint arg1);
+typedef void (APIENTRYP PFNGLSHADEROP2EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
+typedef void (APIENTRYP PFNGLSHADEROP3EXTPROC) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
+typedef void (APIENTRYP PFNGLSWIZZLEEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+typedef void (APIENTRYP PFNGLWRITEMASKEXTPROC) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+typedef void (APIENTRYP PFNGLINSERTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
+typedef void (APIENTRYP PFNGLEXTRACTCOMPONENTEXTPROC) (GLuint res, GLuint src, GLuint num);
+typedef GLuint (APIENTRYP PFNGLGENSYMBOLSEXTPROC) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
+typedef void (APIENTRYP PFNGLSETINVARIANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
+typedef void (APIENTRYP PFNGLSETLOCALCONSTANTEXTPROC) (GLuint id, GLenum type, const GLvoid *addr);
+typedef void (APIENTRYP PFNGLVARIANTBVEXTPROC) (GLuint id, const GLbyte *addr);
+typedef void (APIENTRYP PFNGLVARIANTSVEXTPROC) (GLuint id, const GLshort *addr);
+typedef void (APIENTRYP PFNGLVARIANTIVEXTPROC) (GLuint id, const GLint *addr);
+typedef void (APIENTRYP PFNGLVARIANTFVEXTPROC) (GLuint id, const GLfloat *addr);
+typedef void (APIENTRYP PFNGLVARIANTDVEXTPROC) (GLuint id, const GLdouble *addr);
+typedef void (APIENTRYP PFNGLVARIANTUBVEXTPROC) (GLuint id, const GLubyte *addr);
+typedef void (APIENTRYP PFNGLVARIANTUSVEXTPROC) (GLuint id, const GLushort *addr);
+typedef void (APIENTRYP PFNGLVARIANTUIVEXTPROC) (GLuint id, const GLuint *addr);
+typedef void (APIENTRYP PFNGLVARIANTPOINTEREXTPROC) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
+typedef void (APIENTRYP PFNGLENABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLDISABLEVARIANTCLIENTSTATEEXTPROC) (GLuint id);
+typedef GLuint (APIENTRYP PFNGLBINDLIGHTPARAMETEREXTPROC) (GLenum light, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDMATERIALPARAMETEREXTPROC) (GLenum face, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDTEXGENPARAMETEREXTPROC) (GLenum unit, GLenum coord, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDTEXTUREUNITPARAMETEREXTPROC) (GLenum unit, GLenum value);
+typedef GLuint (APIENTRYP PFNGLBINDPARAMETEREXTPROC) (GLenum value);
+typedef GLboolean (APIENTRYP PFNGLISVARIANTENABLEDEXTPROC) (GLuint id, GLenum cap);
+typedef void (APIENTRYP PFNGLGETVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+typedef void (APIENTRYP PFNGLGETVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+typedef void (APIENTRYP PFNGLGETVARIANTPOINTERVEXTPROC) (GLuint id, GLenum value, GLvoid* *data);
+typedef void (APIENTRYP PFNGLGETINVARIANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETINVARIANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+typedef void (APIENTRYP PFNGLGETINVARIANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+typedef void (APIENTRYP PFNGLGETLOCALCONSTANTBOOLEANVEXTPROC) (GLuint id, GLenum value, GLboolean *data);
+typedef void (APIENTRYP PFNGLGETLOCALCONSTANTINTEGERVEXTPROC) (GLuint id, GLenum value, GLint *data);
+typedef void (APIENTRYP PFNGLGETLOCALCONSTANTFLOATVEXTPROC) (GLuint id, GLenum value, GLfloat *data);
+#endif
+
+#ifndef GL_ATI_vertex_streams
+#define GL_ATI_vertex_streams 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexStream1sATI (GLenum, GLshort);
+GLAPI void APIENTRY glVertexStream1svATI (GLenum, const GLshort *);
+GLAPI void APIENTRY glVertexStream1iATI (GLenum, GLint);
+GLAPI void APIENTRY glVertexStream1ivATI (GLenum, const GLint *);
+GLAPI void APIENTRY glVertexStream1fATI (GLenum, GLfloat);
+GLAPI void APIENTRY glVertexStream1fvATI (GLenum, const GLfloat *);
+GLAPI void APIENTRY glVertexStream1dATI (GLenum, GLdouble);
+GLAPI void APIENTRY glVertexStream1dvATI (GLenum, const GLdouble *);
+GLAPI void APIENTRY glVertexStream2sATI (GLenum, GLshort, GLshort);
+GLAPI void APIENTRY glVertexStream2svATI (GLenum, const GLshort *);
+GLAPI void APIENTRY glVertexStream2iATI (GLenum, GLint, GLint);
+GLAPI void APIENTRY glVertexStream2ivATI (GLenum, const GLint *);
+GLAPI void APIENTRY glVertexStream2fATI (GLenum, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexStream2fvATI (GLenum, const GLfloat *);
+GLAPI void APIENTRY glVertexStream2dATI (GLenum, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexStream2dvATI (GLenum, const GLdouble *);
+GLAPI void APIENTRY glVertexStream3sATI (GLenum, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glVertexStream3svATI (GLenum, const GLshort *);
+GLAPI void APIENTRY glVertexStream3iATI (GLenum, GLint, GLint, GLint);
+GLAPI void APIENTRY glVertexStream3ivATI (GLenum, const GLint *);
+GLAPI void APIENTRY glVertexStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexStream3fvATI (GLenum, const GLfloat *);
+GLAPI void APIENTRY glVertexStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexStream3dvATI (GLenum, const GLdouble *);
+GLAPI void APIENTRY glVertexStream4sATI (GLenum, GLshort, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glVertexStream4svATI (GLenum, const GLshort *);
+GLAPI void APIENTRY glVertexStream4iATI (GLenum, GLint, GLint, GLint, GLint);
+GLAPI void APIENTRY glVertexStream4ivATI (GLenum, const GLint *);
+GLAPI void APIENTRY glVertexStream4fATI (GLenum, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glVertexStream4fvATI (GLenum, const GLfloat *);
+GLAPI void APIENTRY glVertexStream4dATI (GLenum, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glVertexStream4dvATI (GLenum, const GLdouble *);
+GLAPI void APIENTRY glNormalStream3bATI (GLenum, GLbyte, GLbyte, GLbyte);
+GLAPI void APIENTRY glNormalStream3bvATI (GLenum, const GLbyte *);
+GLAPI void APIENTRY glNormalStream3sATI (GLenum, GLshort, GLshort, GLshort);
+GLAPI void APIENTRY glNormalStream3svATI (GLenum, const GLshort *);
+GLAPI void APIENTRY glNormalStream3iATI (GLenum, GLint, GLint, GLint);
+GLAPI void APIENTRY glNormalStream3ivATI (GLenum, const GLint *);
+GLAPI void APIENTRY glNormalStream3fATI (GLenum, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glNormalStream3fvATI (GLenum, const GLfloat *);
+GLAPI void APIENTRY glNormalStream3dATI (GLenum, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glNormalStream3dvATI (GLenum, const GLdouble *);
+GLAPI void APIENTRY glClientActiveVertexStreamATI (GLenum);
+GLAPI void APIENTRY glVertexBlendEnviATI (GLenum, GLint);
+GLAPI void APIENTRY glVertexBlendEnvfATI (GLenum, GLfloat);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1SATIPROC) (GLenum stream, GLshort x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1IATIPROC) (GLenum stream, GLint x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1FATIPROC) (GLenum stream, GLfloat x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1DATIPROC) (GLenum stream, GLdouble x);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM1DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2SATIPROC) (GLenum stream, GLshort x, GLshort y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2IATIPROC) (GLenum stream, GLint x, GLint y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2FATIPROC) (GLenum stream, GLfloat x, GLfloat y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2DATIPROC) (GLenum stream, GLdouble x, GLdouble y);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM2DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3IATIPROC) (GLenum stream, GLint x, GLint y, GLint z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4SATIPROC) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4IATIPROC) (GLenum stream, GLint x, GLint y, GLint z, GLint w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4FATIPROC) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4DATIPROC) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLVERTEXSTREAM4DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3BATIPROC) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3BVATIPROC) (GLenum stream, const GLbyte *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3SATIPROC) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3SVATIPROC) (GLenum stream, const GLshort *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3IATIPROC) (GLenum stream, GLint nx, GLint ny, GLint nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3IVATIPROC) (GLenum stream, const GLint *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3FATIPROC) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3FVATIPROC) (GLenum stream, const GLfloat *coords);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3DATIPROC) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
+typedef void (APIENTRYP PFNGLNORMALSTREAM3DVATIPROC) (GLenum stream, const GLdouble *coords);
+typedef void (APIENTRYP PFNGLCLIENTACTIVEVERTEXSTREAMATIPROC) (GLenum stream);
+typedef void (APIENTRYP PFNGLVERTEXBLENDENVIATIPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLVERTEXBLENDENVFATIPROC) (GLenum pname, GLfloat param);
+#endif
+
+#ifndef GL_ATI_element_array
+#define GL_ATI_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glElementPointerATI (GLenum, const GLvoid *);
+GLAPI void APIENTRY glDrawElementArrayATI (GLenum, GLsizei);
+GLAPI void APIENTRY glDrawRangeElementArrayATI (GLenum, GLuint, GLuint, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLELEMENTPOINTERATIPROC) (GLenum type, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYATIPROC) (GLenum mode, GLsizei count);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYATIPROC) (GLenum mode, GLuint start, GLuint end, GLsizei count);
+#endif
+
+#ifndef GL_SUN_mesh_array
+#define GL_SUN_mesh_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawMeshArraysSUN (GLenum, GLint, GLsizei, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWMESHARRAYSSUNPROC) (GLenum mode, GLint first, GLsizei count, GLsizei width);
+#endif
+
+#ifndef GL_SUN_slice_accum
+#define GL_SUN_slice_accum 1
+#endif
+
+#ifndef GL_NV_multisample_filter_hint
+#define GL_NV_multisample_filter_hint 1
+#endif
+
+#ifndef GL_NV_depth_clamp
+#define GL_NV_depth_clamp 1
+#endif
+
+#ifndef GL_NV_occlusion_query
+#define GL_NV_occlusion_query 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenOcclusionQueriesNV (GLsizei, GLuint *);
+GLAPI void APIENTRY glDeleteOcclusionQueriesNV (GLsizei, const GLuint *);
+GLAPI GLboolean APIENTRY glIsOcclusionQueryNV (GLuint);
+GLAPI void APIENTRY glBeginOcclusionQueryNV (GLuint);
+GLAPI void APIENTRY glEndOcclusionQueryNV (void);
+GLAPI void APIENTRY glGetOcclusionQueryivNV (GLuint, GLenum, GLint *);
+GLAPI void APIENTRY glGetOcclusionQueryuivNV (GLuint, GLenum, GLuint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENOCCLUSIONQUERIESNVPROC) (GLsizei n, GLuint *ids);
+typedef void (APIENTRYP PFNGLDELETEOCCLUSIONQUERIESNVPROC) (GLsizei n, const GLuint *ids);
+typedef GLboolean (APIENTRYP PFNGLISOCCLUSIONQUERYNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLBEGINOCCLUSIONQUERYNVPROC) (GLuint id);
+typedef void (APIENTRYP PFNGLENDOCCLUSIONQUERYNVPROC) (void);
+typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYIVNVPROC) (GLuint id, GLenum pname, GLint *params);
+typedef void (APIENTRYP PFNGLGETOCCLUSIONQUERYUIVNVPROC) (GLuint id, GLenum pname, GLuint *params);
+#endif
+
+#ifndef GL_NV_point_sprite
+#define GL_NV_point_sprite 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPointParameteriNV (GLenum, GLint);
+GLAPI void APIENTRY glPointParameterivNV (GLenum, const GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPOINTPARAMETERINVPROC) (GLenum pname, GLint param);
+typedef void (APIENTRYP PFNGLPOINTPARAMETERIVNVPROC) (GLenum pname, const GLint *params);
+#endif
+
+#ifndef GL_NV_texture_shader3
+#define GL_NV_texture_shader3 1
+#endif
+
+#ifndef GL_NV_vertex_program1_1
+#define GL_NV_vertex_program1_1 1
+#endif
+
+#ifndef GL_EXT_shadow_funcs
+#define GL_EXT_shadow_funcs 1
+#endif
+
+#ifndef GL_EXT_stencil_two_side
+#define GL_EXT_stencil_two_side 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glActiveStencilFaceEXT (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLACTIVESTENCILFACEEXTPROC) (GLenum face);
+#endif
+
+#ifndef GL_ATI_text_fragment_shader
+#define GL_ATI_text_fragment_shader 1
+#endif
+
+#ifndef GL_APPLE_client_storage
+#define GL_APPLE_client_storage 1
+#endif
+
+#ifndef GL_APPLE_element_array
+#define GL_APPLE_element_array 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glElementPointerAPPLE (GLenum, const GLvoid *);
+GLAPI void APIENTRY glDrawElementArrayAPPLE (GLenum, GLint, GLsizei);
+GLAPI void APIENTRY glDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, GLint, GLsizei);
+GLAPI void APIENTRY glMultiDrawElementArrayAPPLE (GLenum, const GLint *, const GLsizei *, GLsizei);
+GLAPI void APIENTRY glMultiDrawRangeElementArrayAPPLE (GLenum, GLuint, GLuint, const GLint *, const GLsizei *, GLsizei);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLELEMENTPOINTERAPPLEPROC) (GLenum type, const GLvoid *pointer);
+typedef void (APIENTRYP PFNGLDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+typedef void (APIENTRYP PFNGLMULTIDRAWELEMENTARRAYAPPLEPROC) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+typedef void (APIENTRYP PFNGLMULTIDRAWRANGEELEMENTARRAYAPPLEPROC) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+#endif
+
+#ifndef GL_APPLE_fence
+#define GL_APPLE_fence 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glGenFencesAPPLE (GLsizei, GLuint *);
+GLAPI void APIENTRY glDeleteFencesAPPLE (GLsizei, const GLuint *);
+GLAPI void APIENTRY glSetFenceAPPLE (GLuint);
+GLAPI GLboolean APIENTRY glIsFenceAPPLE (GLuint);
+GLAPI GLboolean APIENTRY glTestFenceAPPLE (GLuint);
+GLAPI void APIENTRY glFinishFenceAPPLE (GLuint);
+GLAPI GLboolean APIENTRY glTestObjectAPPLE (GLenum, GLuint);
+GLAPI void APIENTRY glFinishObjectAPPLE (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLGENFENCESAPPLEPROC) (GLsizei n, GLuint *fences);
+typedef void (APIENTRYP PFNGLDELETEFENCESAPPLEPROC) (GLsizei n, const GLuint *fences);
+typedef void (APIENTRYP PFNGLSETFENCEAPPLEPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLISFENCEAPPLEPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLTESTFENCEAPPLEPROC) (GLuint fence);
+typedef void (APIENTRYP PFNGLFINISHFENCEAPPLEPROC) (GLuint fence);
+typedef GLboolean (APIENTRYP PFNGLTESTOBJECTAPPLEPROC) (GLenum object, GLuint name);
+typedef void (APIENTRYP PFNGLFINISHOBJECTAPPLEPROC) (GLenum object, GLint name);
+#endif
+
+#ifndef GL_APPLE_vertex_array_object
+#define GL_APPLE_vertex_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBindVertexArrayAPPLE (GLuint);
+GLAPI void APIENTRY glDeleteVertexArraysAPPLE (GLsizei, const GLuint *);
+GLAPI void APIENTRY glGenVertexArraysAPPLE (GLsizei, const GLuint *);
+GLAPI GLboolean APIENTRY glIsVertexArrayAPPLE (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBINDVERTEXARRAYAPPLEPROC) (GLuint array);
+typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
+typedef void (APIENTRYP PFNGLGENVERTEXARRAYSAPPLEPROC) (GLsizei n, const GLuint *arrays);
+typedef GLboolean (APIENTRYP PFNGLISVERTEXARRAYAPPLEPROC) (GLuint array);
+#endif
+
+#ifndef GL_APPLE_vertex_array_range
+#define GL_APPLE_vertex_array_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexArrayRangeAPPLE (GLsizei, GLvoid *);
+GLAPI void APIENTRY glFlushVertexArrayRangeAPPLE (GLsizei, GLvoid *);
+GLAPI void APIENTRY glVertexArrayParameteriAPPLE (GLenum, GLint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLFLUSHVERTEXARRAYRANGEAPPLEPROC) (GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLVERTEXARRAYPARAMETERIAPPLEPROC) (GLenum pname, GLint param);
+#endif
+
+#ifndef GL_APPLE_ycbcr_422
+#define GL_APPLE_ycbcr_422 1
+#endif
+
+#ifndef GL_S3_s3tc
+#define GL_S3_s3tc 1
+#endif
+
+#ifndef GL_ATI_draw_buffers
+#define GL_ATI_draw_buffers 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDrawBuffersATI (GLsizei, const GLenum *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDRAWBUFFERSATIPROC) (GLsizei n, const GLenum *bufs);
+#endif
+
+#ifndef GL_ATI_texture_env_combine3
+#define GL_ATI_texture_env_combine3 1
+#endif
+
+#ifndef GL_ATI_texture_float
+#define GL_ATI_texture_float 1
+#endif
+
+#ifndef GL_NV_float_buffer
+#define GL_NV_float_buffer 1
+#endif
+
+#ifndef GL_NV_fragment_program
+#define GL_NV_fragment_program 1
+/* Some NV_fragment_program entry points are shared with ARB_vertex_program. */
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glProgramNamedParameter4fNV (GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat);
+GLAPI void APIENTRY glProgramNamedParameter4dNV (GLuint, GLsizei, const GLubyte *, GLdouble, GLdouble, GLdouble, GLdouble);
+GLAPI void APIENTRY glProgramNamedParameter4fvNV (GLuint, GLsizei, const GLubyte *, const GLfloat *);
+GLAPI void APIENTRY glProgramNamedParameter4dvNV (GLuint, GLsizei, const GLubyte *, const GLdouble *);
+GLAPI void APIENTRY glGetProgramNamedParameterfvNV (GLuint, GLsizei, const GLubyte *, GLfloat *);
+GLAPI void APIENTRY glGetProgramNamedParameterdvNV (GLuint, GLsizei, const GLubyte *, GLdouble *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4FVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
+typedef void (APIENTRYP PFNGLPROGRAMNAMEDPARAMETER4DVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
+typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERFVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETPROGRAMNAMEDPARAMETERDVNVPROC) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
+#endif
+
+#ifndef GL_NV_half_float
+#define GL_NV_half_float 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertex2hNV (GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glVertex2hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glVertex3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glVertex3hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glVertex4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glVertex4hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glNormal3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glNormal3hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glColor3hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glColor4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glColor4hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glTexCoord1hNV (GLhalfNV);
+GLAPI void APIENTRY glTexCoord1hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glTexCoord2hNV (GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glTexCoord2hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glTexCoord3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glTexCoord3hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glTexCoord4hNV (GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glTexCoord4hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glMultiTexCoord1hNV (GLenum, GLhalfNV);
+GLAPI void APIENTRY glMultiTexCoord1hvNV (GLenum, const GLhalfNV *);
+GLAPI void APIENTRY glMultiTexCoord2hNV (GLenum, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glMultiTexCoord2hvNV (GLenum, const GLhalfNV *);
+GLAPI void APIENTRY glMultiTexCoord3hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glMultiTexCoord3hvNV (GLenum, const GLhalfNV *);
+GLAPI void APIENTRY glMultiTexCoord4hNV (GLenum, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glMultiTexCoord4hvNV (GLenum, const GLhalfNV *);
+GLAPI void APIENTRY glFogCoordhNV (GLhalfNV);
+GLAPI void APIENTRY glFogCoordhvNV (const GLhalfNV *);
+GLAPI void APIENTRY glSecondaryColor3hNV (GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glSecondaryColor3hvNV (const GLhalfNV *);
+GLAPI void APIENTRY glVertexWeighthNV (GLhalfNV);
+GLAPI void APIENTRY glVertexWeighthvNV (const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttrib1hNV (GLuint, GLhalfNV);
+GLAPI void APIENTRY glVertexAttrib1hvNV (GLuint, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttrib2hNV (GLuint, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glVertexAttrib2hvNV (GLuint, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttrib3hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glVertexAttrib3hvNV (GLuint, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttrib4hNV (GLuint, GLhalfNV, GLhalfNV, GLhalfNV, GLhalfNV);
+GLAPI void APIENTRY glVertexAttrib4hvNV (GLuint, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttribs1hvNV (GLuint, GLsizei, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttribs2hvNV (GLuint, GLsizei, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttribs3hvNV (GLuint, GLsizei, const GLhalfNV *);
+GLAPI void APIENTRY glVertexAttribs4hvNV (GLuint, GLsizei, const GLhalfNV *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEX2HNVPROC) (GLhalfNV x, GLhalfNV y);
+typedef void (APIENTRYP PFNGLVERTEX2HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEX3HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z);
+typedef void (APIENTRYP PFNGLVERTEX3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEX4HNVPROC) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+typedef void (APIENTRYP PFNGLVERTEX4HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLNORMAL3HNVPROC) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
+typedef void (APIENTRYP PFNGLNORMAL3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+typedef void (APIENTRYP PFNGLCOLOR3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLCOLOR4HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
+typedef void (APIENTRYP PFNGLCOLOR4HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD1HNVPROC) (GLhalfNV s);
+typedef void (APIENTRYP PFNGLTEXCOORD1HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD2HNVPROC) (GLhalfNV s, GLhalfNV t);
+typedef void (APIENTRYP PFNGLTEXCOORD2HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD3HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r);
+typedef void (APIENTRYP PFNGLTEXCOORD3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLTEXCOORD4HNVPROC) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+typedef void (APIENTRYP PFNGLTEXCOORD4HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1HNVPROC) (GLenum target, GLhalfNV s);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD1HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD2HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD3HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4HNVPROC) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+typedef void (APIENTRYP PFNGLMULTITEXCOORD4HVNVPROC) (GLenum target, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLFOGCOORDHNVPROC) (GLhalfNV fog);
+typedef void (APIENTRYP PFNGLFOGCOORDHVNVPROC) (const GLhalfNV *fog);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HNVPROC) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+typedef void (APIENTRYP PFNGLSECONDARYCOLOR3HVNVPROC) (const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTHNVPROC) (GLhalfNV weight);
+typedef void (APIENTRYP PFNGLVERTEXWEIGHTHVNVPROC) (const GLhalfNV *weight);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1HNVPROC) (GLuint index, GLhalfNV x);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB1HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB2HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB3HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4HNVPROC) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+typedef void (APIENTRYP PFNGLVERTEXATTRIB4HVNVPROC) (GLuint index, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS1HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS2HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS3HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+typedef void (APIENTRYP PFNGLVERTEXATTRIBS4HVNVPROC) (GLuint index, GLsizei n, const GLhalfNV *v);
+#endif
+
+#ifndef GL_NV_pixel_data_range
+#define GL_NV_pixel_data_range 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPixelDataRangeNV (GLenum, GLsizei, GLvoid *);
+GLAPI void APIENTRY glFlushPixelDataRangeNV (GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPIXELDATARANGENVPROC) (GLenum target, GLsizei length, GLvoid *pointer);
+typedef void (APIENTRYP PFNGLFLUSHPIXELDATARANGENVPROC) (GLenum target);
+#endif
+
+#ifndef GL_NV_primitive_restart
+#define GL_NV_primitive_restart 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glPrimitiveRestartNV (void);
+GLAPI void APIENTRY glPrimitiveRestartIndexNV (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLPRIMITIVERESTARTNVPROC) (void);
+typedef void (APIENTRYP PFNGLPRIMITIVERESTARTINDEXNVPROC) (GLuint index);
+#endif
+
+#ifndef GL_NV_texture_expand_normal
+#define GL_NV_texture_expand_normal 1
+#endif
+
+#ifndef GL_NV_vertex_program2
+#define GL_NV_vertex_program2 1
+#endif
+
+#ifndef GL_ATI_map_object_buffer
+#define GL_ATI_map_object_buffer 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI GLvoid* APIENTRY glMapObjectBufferATI (GLuint);
+GLAPI void APIENTRY glUnmapObjectBufferATI (GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef GLvoid* (APIENTRYP PFNGLMAPOBJECTBUFFERATIPROC) (GLuint buffer);
+typedef void (APIENTRYP PFNGLUNMAPOBJECTBUFFERATIPROC) (GLuint buffer);
+#endif
+
+#ifndef GL_ATI_separate_stencil
+#define GL_ATI_separate_stencil 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glStencilOpSeparateATI (GLenum, GLenum, GLenum, GLenum);
+GLAPI void APIENTRY glStencilFuncSeparateATI (GLenum, GLenum, GLint, GLuint);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEATIPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEATIPROC) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
+#endif
+
+#ifndef GL_ATI_vertex_attrib_array_object
+#define GL_ATI_vertex_attrib_array_object 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glVertexAttribArrayObjectATI (GLuint, GLint, GLenum, GLboolean, GLsizei, GLuint, GLuint);
+GLAPI void APIENTRY glGetVertexAttribArrayObjectfvATI (GLuint, GLenum, GLfloat *);
+GLAPI void APIENTRY glGetVertexAttribArrayObjectivATI (GLuint, GLenum, GLint *);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLVERTEXATTRIBARRAYOBJECTATIPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTFVATIPROC) (GLuint index, GLenum pname, GLfloat *params);
+typedef void (APIENTRYP PFNGLGETVERTEXATTRIBARRAYOBJECTIVATIPROC) (GLuint index, GLenum pname, GLint *params);
+#endif
+
+#ifndef GL_EXT_depth_bounds_test
+#define GL_EXT_depth_bounds_test 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glDepthBoundsEXT (GLclampd, GLclampd);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLDEPTHBOUNDSEXTPROC) (GLclampd zmin, GLclampd zmax);
+#endif
+
+#ifndef GL_EXT_texture_mirror_clamp
+#define GL_EXT_texture_mirror_clamp 1
+#endif
+
+#ifndef GL_EXT_blend_equation_separate
+#define GL_EXT_blend_equation_separate 1
+#ifdef GL_GLEXT_PROTOTYPES
+GLAPI void APIENTRY glBlendEquationSeparateEXT (GLenum, GLenum);
+#endif /* GL_GLEXT_PROTOTYPES */
+typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEEXTPROC) (GLenum modeRGB, GLenum modeAlpha);
+#endif
+
+#ifndef GL_MESA_pack_invert
+#define GL_MESA_pack_invert 1
+#endif
+
+#ifndef GL_MESA_ycbcr_texture
+#define GL_MESA_ycbcr_texture 1
+#endif
+
+#ifndef GL_WIN_swap_hint
+#define GL_WIN_swap_hint 1
+extern void APIENTRY glAddSwapHintRectWIN (GLint, GLint, GLsizei, GLsizei);
+typedef void (APIENTRY * PFNGLADDSWAPHINTRECTWINPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/ext/GLsdk/GL/glprocs.c b/src/ext/GLsdk/GL/glprocs.c
new file mode 100644
index 0000000..a488a49
--- /dev/null
+++ b/src/ext/GLsdk/GL/glprocs.c
@@ -0,0 +1,17859 @@
+/*
+** GLprocs utility for getting function addresses for OpenGL(R) 1.2, 
+** OpenGL 1.3, OpenGL 1.4, OpenGL 1.5 and OpenGL extension functions.
+**
+** Version:  1.1
+**
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+**
+** Initial version of glprocs.{c,h} contributed by Intel(R) Corporation.
+*/
+
+#include <assert.h>
+#include <stdlib.h>
+
+#ifdef _WIN32
+  #include <windows.h>
+  #include "gl.h"  /* Include local "gl.h". Don't include vc32 <GL/gl.h>. */
+  #include "glprocs.h"
+#else /* GLX */
+  #include <GL/gl.h>
+  #include <GL/glx.h>
+  #include <GL/glprocs.h>
+  #define wglGetProcAddress glXGetProcAddressARB
+#endif
+
+#define _ASSERT(a) assert(a)
+
+static void APIENTRY InitBlendColor (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendColor");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendColor = extproc;
+
+	glBlendColor(red, green, blue, alpha);
+}
+
+static void APIENTRY InitBlendEquation (GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendEquation");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendEquation = extproc;
+
+	glBlendEquation(mode);
+}
+
+static void APIENTRY InitDrawRangeElements (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawRangeElements");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawRangeElements = extproc;
+
+	glDrawRangeElements(mode, start, end, count, type, indices);
+}
+
+static void APIENTRY InitColorTable (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTable");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTable = extproc;
+
+	glColorTable(target, internalformat, width, format, type, table);
+}
+
+static void APIENTRY InitColorTableParameterfv (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTableParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTableParameterfv = extproc;
+
+	glColorTableParameterfv(target, pname, params);
+}
+
+static void APIENTRY InitColorTableParameteriv (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTableParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTableParameteriv = extproc;
+
+	glColorTableParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitCopyColorTable (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyColorTable");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyColorTable = extproc;
+
+	glCopyColorTable(target, internalformat, x, y, width);
+}
+
+static void APIENTRY InitGetColorTable (GLenum target, GLenum format, GLenum type, GLvoid *table)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTable");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTable = extproc;
+
+	glGetColorTable(target, format, type, table);
+}
+
+static void APIENTRY InitGetColorTableParameterfv (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableParameterfv = extproc;
+
+	glGetColorTableParameterfv(target, pname, params);
+}
+
+static void APIENTRY InitGetColorTableParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableParameteriv = extproc;
+
+	glGetColorTableParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitColorSubTable (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorSubTable");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorSubTable = extproc;
+
+	glColorSubTable(target, start, count, format, type, data);
+}
+
+static void APIENTRY InitCopyColorSubTable (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyColorSubTable");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyColorSubTable = extproc;
+
+	glCopyColorSubTable(target, start, x, y, width);
+}
+
+static void APIENTRY InitConvolutionFilter1D (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionFilter1D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionFilter1D = extproc;
+
+	glConvolutionFilter1D(target, internalformat, width, format, type, image);
+}
+
+static void APIENTRY InitConvolutionFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionFilter2D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionFilter2D = extproc;
+
+	glConvolutionFilter2D(target, internalformat, width, height, format, type, image);
+}
+
+static void APIENTRY InitConvolutionParameterf (GLenum target, GLenum pname, GLfloat params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameterf");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameterf = extproc;
+
+	glConvolutionParameterf(target, pname, params);
+}
+
+static void APIENTRY InitConvolutionParameterfv (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameterfv = extproc;
+
+	glConvolutionParameterfv(target, pname, params);
+}
+
+static void APIENTRY InitConvolutionParameteri (GLenum target, GLenum pname, GLint params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameteri");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameteri = extproc;
+
+	glConvolutionParameteri(target, pname, params);
+}
+
+static void APIENTRY InitConvolutionParameteriv (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameteriv = extproc;
+
+	glConvolutionParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitCopyConvolutionFilter1D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyConvolutionFilter1D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyConvolutionFilter1D = extproc;
+
+	glCopyConvolutionFilter1D(target, internalformat, x, y, width);
+}
+
+static void APIENTRY InitCopyConvolutionFilter2D (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyConvolutionFilter2D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyConvolutionFilter2D = extproc;
+
+	glCopyConvolutionFilter2D(target, internalformat, x, y, width, height);
+}
+
+static void APIENTRY InitGetConvolutionFilter (GLenum target, GLenum format, GLenum type, GLvoid *image)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetConvolutionFilter");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetConvolutionFilter = extproc;
+
+	glGetConvolutionFilter(target, format, type, image);
+}
+
+static void APIENTRY InitGetConvolutionParameterfv (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetConvolutionParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetConvolutionParameterfv = extproc;
+
+	glGetConvolutionParameterfv(target, pname, params);
+}
+
+static void APIENTRY InitGetConvolutionParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetConvolutionParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetConvolutionParameteriv = extproc;
+
+	glGetConvolutionParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitGetSeparableFilter (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetSeparableFilter");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetSeparableFilter = extproc;
+
+	glGetSeparableFilter(target, format, type, row, column, span);
+}
+
+static void APIENTRY InitSeparableFilter2D (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSeparableFilter2D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSeparableFilter2D = extproc;
+
+	glSeparableFilter2D(target, internalformat, width, height, format, type, row, column);
+}
+
+static void APIENTRY InitGetHistogram (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHistogram");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetHistogram = extproc;
+
+	glGetHistogram(target, reset, format, type, values);
+}
+
+static void APIENTRY InitGetHistogramParameterfv (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHistogramParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetHistogramParameterfv = extproc;
+
+	glGetHistogramParameterfv(target, pname, params);
+}
+
+static void APIENTRY InitGetHistogramParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHistogramParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetHistogramParameteriv = extproc;
+
+	glGetHistogramParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitGetMinmax (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMinmax");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMinmax = extproc;
+
+	glGetMinmax(target, reset, format, type, values);
+}
+
+static void APIENTRY InitGetMinmaxParameterfv (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMinmaxParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMinmaxParameterfv = extproc;
+
+	glGetMinmaxParameterfv(target, pname, params);
+}
+
+static void APIENTRY InitGetMinmaxParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMinmaxParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMinmaxParameteriv = extproc;
+
+	glGetMinmaxParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitHistogram (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glHistogram");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glHistogram = extproc;
+
+	glHistogram(target, width, internalformat, sink);
+}
+
+static void APIENTRY InitMinmax (GLenum target, GLenum internalformat, GLboolean sink)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMinmax");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMinmax = extproc;
+
+	glMinmax(target, internalformat, sink);
+}
+
+static void APIENTRY InitResetHistogram (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glResetHistogram");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glResetHistogram = extproc;
+
+	glResetHistogram(target);
+}
+
+static void APIENTRY InitResetMinmax (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glResetMinmax");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glResetMinmax = extproc;
+
+	glResetMinmax(target);
+}
+
+static void APIENTRY InitTexImage3D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexImage3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexImage3D = extproc;
+
+	glTexImage3D(target, level, internalformat, width, height, depth, border, format, type, pixels);
+}
+
+static void APIENTRY InitTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexSubImage3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexSubImage3D = extproc;
+
+	glTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
+}
+
+static void APIENTRY InitCopyTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyTexSubImage3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyTexSubImage3D = extproc;
+
+	glCopyTexSubImage3D(target, level, xoffset, yoffset, zoffset, x, y, width, height);
+}
+
+static void APIENTRY InitActiveTexture (GLenum texture)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glActiveTexture");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glActiveTexture = extproc;
+
+	glActiveTexture(texture);
+}
+
+static void APIENTRY InitClientActiveTexture (GLenum texture)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glClientActiveTexture");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glClientActiveTexture = extproc;
+
+	glClientActiveTexture(texture);
+}
+
+static void APIENTRY InitMultiTexCoord1d (GLenum target, GLdouble s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1d = extproc;
+
+	glMultiTexCoord1d(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1dv (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1dv = extproc;
+
+	glMultiTexCoord1dv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord1f (GLenum target, GLfloat s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1f = extproc;
+
+	glMultiTexCoord1f(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1fv (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1fv = extproc;
+
+	glMultiTexCoord1fv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord1i (GLenum target, GLint s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1i = extproc;
+
+	glMultiTexCoord1i(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1iv (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1iv = extproc;
+
+	glMultiTexCoord1iv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord1s (GLenum target, GLshort s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1s = extproc;
+
+	glMultiTexCoord1s(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1sv (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1sv = extproc;
+
+	glMultiTexCoord1sv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2d (GLenum target, GLdouble s, GLdouble t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2d = extproc;
+
+	glMultiTexCoord2d(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2dv (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2dv = extproc;
+
+	glMultiTexCoord2dv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2f (GLenum target, GLfloat s, GLfloat t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2f = extproc;
+
+	glMultiTexCoord2f(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2fv (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2fv = extproc;
+
+	glMultiTexCoord2fv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2i (GLenum target, GLint s, GLint t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2i = extproc;
+
+	glMultiTexCoord2i(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2iv (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2iv = extproc;
+
+	glMultiTexCoord2iv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2s (GLenum target, GLshort s, GLshort t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2s = extproc;
+
+	glMultiTexCoord2s(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2sv (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2sv = extproc;
+
+	glMultiTexCoord2sv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3d (GLenum target, GLdouble s, GLdouble t, GLdouble r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3d = extproc;
+
+	glMultiTexCoord3d(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3dv (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3dv = extproc;
+
+	glMultiTexCoord3dv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3f (GLenum target, GLfloat s, GLfloat t, GLfloat r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3f = extproc;
+
+	glMultiTexCoord3f(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3fv (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3fv = extproc;
+
+	glMultiTexCoord3fv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3i (GLenum target, GLint s, GLint t, GLint r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3i = extproc;
+
+	glMultiTexCoord3i(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3iv (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3iv = extproc;
+
+	glMultiTexCoord3iv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3s (GLenum target, GLshort s, GLshort t, GLshort r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3s = extproc;
+
+	glMultiTexCoord3s(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3sv (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3sv = extproc;
+
+	glMultiTexCoord3sv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4d (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4d = extproc;
+
+	glMultiTexCoord4d(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4dv (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4dv = extproc;
+
+	glMultiTexCoord4dv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4f (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4f = extproc;
+
+	glMultiTexCoord4f(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4fv (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4fv = extproc;
+
+	glMultiTexCoord4fv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4i (GLenum target, GLint s, GLint t, GLint r, GLint q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4i = extproc;
+
+	glMultiTexCoord4i(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4iv (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4iv = extproc;
+
+	glMultiTexCoord4iv(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4s (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4s = extproc;
+
+	glMultiTexCoord4s(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4sv (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4sv = extproc;
+
+	glMultiTexCoord4sv(target, v);
+}
+
+static void APIENTRY InitLoadTransposeMatrixf (const GLfloat *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLoadTransposeMatrixf");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLoadTransposeMatrixf = extproc;
+
+	glLoadTransposeMatrixf(m);
+}
+
+static void APIENTRY InitLoadTransposeMatrixd (const GLdouble *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLoadTransposeMatrixd");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLoadTransposeMatrixd = extproc;
+
+	glLoadTransposeMatrixd(m);
+}
+
+static void APIENTRY InitMultTransposeMatrixf (const GLfloat *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultTransposeMatrixf");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultTransposeMatrixf = extproc;
+
+	glMultTransposeMatrixf(m);
+}
+
+static void APIENTRY InitMultTransposeMatrixd (const GLdouble *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultTransposeMatrixd");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultTransposeMatrixd = extproc;
+
+	glMultTransposeMatrixd(m);
+}
+
+static void APIENTRY InitSampleCoverage (GLclampf value, GLboolean invert)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSampleCoverage");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSampleCoverage = extproc;
+
+	glSampleCoverage(value, invert);
+}
+
+static void APIENTRY InitCompressedTexImage3D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexImage3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexImage3D = extproc;
+
+	glCompressedTexImage3D(target, level, internalformat, width, height, depth, border, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexImage2D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexImage2D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexImage2D = extproc;
+
+	glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexImage1D (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexImage1D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexImage1D = extproc;
+
+	glCompressedTexImage1D(target, level, internalformat, width, border, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexSubImage3D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexSubImage3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexSubImage3D = extproc;
+
+	glCompressedTexSubImage3D(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexSubImage2D (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexSubImage2D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexSubImage2D = extproc;
+
+	glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexSubImage1D (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexSubImage1D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexSubImage1D = extproc;
+
+	glCompressedTexSubImage1D(target, level, xoffset, width, format, imageSize, data);
+}
+
+static void APIENTRY InitGetCompressedTexImage (GLenum target, GLint level, GLvoid *img)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCompressedTexImage");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCompressedTexImage = extproc;
+
+	glGetCompressedTexImage(target, level, img);
+}
+
+static void APIENTRY InitBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendFuncSeparate");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendFuncSeparate = extproc;
+
+	glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha);
+}
+
+static void APIENTRY InitFogCoordf (GLfloat coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordf");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordf = extproc;
+
+	glFogCoordf(coord);
+}
+
+static void APIENTRY InitFogCoordfv (const GLfloat *coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordfv = extproc;
+
+	glFogCoordfv(coord);
+}
+
+static void APIENTRY InitFogCoordd (GLdouble coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordd");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordd = extproc;
+
+	glFogCoordd(coord);
+}
+
+static void APIENTRY InitFogCoorddv (const GLdouble *coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoorddv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoorddv = extproc;
+
+	glFogCoorddv(coord);
+}
+
+static void APIENTRY InitFogCoordPointer (GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordPointer");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordPointer = extproc;
+
+	glFogCoordPointer(type, stride, pointer);
+}
+
+static void APIENTRY InitMultiDrawArrays (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiDrawArrays");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiDrawArrays = extproc;
+
+	glMultiDrawArrays(mode, first, count, primcount);
+}
+
+static void APIENTRY InitMultiDrawElements (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiDrawElements");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiDrawElements = extproc;
+
+	glMultiDrawElements(mode, count, type, indices, primcount);
+}
+
+static void APIENTRY InitPointParameterf (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterf");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterf = extproc;
+
+	glPointParameterf(pname, param);
+}
+
+static void APIENTRY InitPointParameterfv (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfv = extproc;
+
+	glPointParameterfv(pname, params);
+}
+
+static void APIENTRY InitPointParameteri (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameteri");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameteri = extproc;
+
+	glPointParameteri(pname, param);
+}
+
+static void APIENTRY InitPointParameteriv (GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameteriv = extproc;
+
+	glPointParameteriv(pname, params);
+}
+
+static void APIENTRY InitSecondaryColor3b (GLbyte red, GLbyte green, GLbyte blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3b");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3b = extproc;
+
+	glSecondaryColor3b(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3bv (const GLbyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3bv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3bv = extproc;
+
+	glSecondaryColor3bv(v);
+}
+
+static void APIENTRY InitSecondaryColor3d (GLdouble red, GLdouble green, GLdouble blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3d = extproc;
+
+	glSecondaryColor3d(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3dv (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3dv = extproc;
+
+	glSecondaryColor3dv(v);
+}
+
+static void APIENTRY InitSecondaryColor3f (GLfloat red, GLfloat green, GLfloat blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3f = extproc;
+
+	glSecondaryColor3f(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3fv (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3fv = extproc;
+
+	glSecondaryColor3fv(v);
+}
+
+static void APIENTRY InitSecondaryColor3i (GLint red, GLint green, GLint blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3i = extproc;
+
+	glSecondaryColor3i(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3iv (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3iv = extproc;
+
+	glSecondaryColor3iv(v);
+}
+
+static void APIENTRY InitSecondaryColor3s (GLshort red, GLshort green, GLshort blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3s = extproc;
+
+	glSecondaryColor3s(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3sv (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3sv = extproc;
+
+	glSecondaryColor3sv(v);
+}
+
+static void APIENTRY InitSecondaryColor3ub (GLubyte red, GLubyte green, GLubyte blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3ub");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3ub = extproc;
+
+	glSecondaryColor3ub(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3ubv (const GLubyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3ubv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3ubv = extproc;
+
+	glSecondaryColor3ubv(v);
+}
+
+static void APIENTRY InitSecondaryColor3ui (GLuint red, GLuint green, GLuint blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3ui");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3ui = extproc;
+
+	glSecondaryColor3ui(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3uiv (const GLuint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3uiv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3uiv = extproc;
+
+	glSecondaryColor3uiv(v);
+}
+
+static void APIENTRY InitSecondaryColor3us (GLushort red, GLushort green, GLushort blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3us");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3us = extproc;
+
+	glSecondaryColor3us(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3usv (const GLushort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3usv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3usv = extproc;
+
+	glSecondaryColor3usv(v);
+}
+
+static void APIENTRY InitSecondaryColorPointer (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColorPointer");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColorPointer = extproc;
+
+	glSecondaryColorPointer(size, type, stride, pointer);
+}
+
+static void APIENTRY InitWindowPos2d (GLdouble x, GLdouble y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2d = extproc;
+
+	glWindowPos2d(x, y);
+}
+
+static void APIENTRY InitWindowPos2dv (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2dv = extproc;
+
+	glWindowPos2dv(v);
+}
+
+static void APIENTRY InitWindowPos2f (GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2f = extproc;
+
+	glWindowPos2f(x, y);
+}
+
+static void APIENTRY InitWindowPos2fv (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2fv = extproc;
+
+	glWindowPos2fv(v);
+}
+
+static void APIENTRY InitWindowPos2i (GLint x, GLint y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2i = extproc;
+
+	glWindowPos2i(x, y);
+}
+
+static void APIENTRY InitWindowPos2iv (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2iv = extproc;
+
+	glWindowPos2iv(v);
+}
+
+static void APIENTRY InitWindowPos2s (GLshort x, GLshort y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2s = extproc;
+
+	glWindowPos2s(x, y);
+}
+
+static void APIENTRY InitWindowPos2sv (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2sv = extproc;
+
+	glWindowPos2sv(v);
+}
+
+static void APIENTRY InitWindowPos3d (GLdouble x, GLdouble y, GLdouble z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3d");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3d = extproc;
+
+	glWindowPos3d(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3dv (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3dv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3dv = extproc;
+
+	glWindowPos3dv(v);
+}
+
+static void APIENTRY InitWindowPos3f (GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3f");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3f = extproc;
+
+	glWindowPos3f(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3fv (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3fv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3fv = extproc;
+
+	glWindowPos3fv(v);
+}
+
+static void APIENTRY InitWindowPos3i (GLint x, GLint y, GLint z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3i");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3i = extproc;
+
+	glWindowPos3i(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3iv (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3iv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3iv = extproc;
+
+	glWindowPos3iv(v);
+}
+
+static void APIENTRY InitWindowPos3s (GLshort x, GLshort y, GLshort z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3s");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3s = extproc;
+
+	glWindowPos3s(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3sv (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3sv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3sv = extproc;
+
+	glWindowPos3sv(v);
+}
+
+static void APIENTRY InitGenQueries (GLsizei n, GLuint *ids)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenQueries");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenQueries = extproc;
+
+	glGenQueries(n, ids);
+}
+
+static void APIENTRY InitDeleteQueries (GLsizei n, const GLuint *ids)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteQueries");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteQueries = extproc;
+
+	glDeleteQueries(n, ids);
+}
+
+static GLboolean APIENTRY InitIsQuery (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsQuery");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsQuery = extproc;
+
+	return glIsQuery(id);
+}
+
+static void APIENTRY InitBeginQuery (GLenum target, GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBeginQuery");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBeginQuery = extproc;
+
+	glBeginQuery(target, id);
+}
+
+static void APIENTRY InitEndQuery (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEndQuery");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEndQuery = extproc;
+
+	glEndQuery(target);
+}
+
+static void APIENTRY InitGetQueryiv (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetQueryiv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetQueryiv = extproc;
+
+	glGetQueryiv(target, pname, params);
+}
+
+static void APIENTRY InitGetQueryObjectiv (GLuint id, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetQueryObjectiv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetQueryObjectiv = extproc;
+
+	glGetQueryObjectiv(id, pname, params);
+}
+
+static void APIENTRY InitGetQueryObjectuiv (GLuint id, GLenum pname, GLuint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetQueryObjectuiv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetQueryObjectuiv = extproc;
+
+	glGetQueryObjectuiv(id, pname, params);
+}
+
+static void APIENTRY InitBindBuffer (GLenum target, GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindBuffer");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindBuffer = extproc;
+
+	glBindBuffer(target, buffer);
+}
+
+static void APIENTRY InitDeleteBuffers (GLsizei n, const GLuint *buffers)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteBuffers");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteBuffers = extproc;
+
+	glDeleteBuffers(n, buffers);
+}
+
+static void APIENTRY InitGenBuffers (GLsizei n, GLuint *buffers)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenBuffers");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenBuffers = extproc;
+
+	glGenBuffers(n, buffers);
+}
+
+static GLboolean APIENTRY InitIsBuffer (GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsBuffer");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsBuffer = extproc;
+
+	return glIsBuffer(buffer);
+}
+
+static void APIENTRY InitBufferData (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBufferData");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBufferData = extproc;
+
+	glBufferData(target, size, data, usage);
+}
+
+static void APIENTRY InitBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBufferSubData");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBufferSubData = extproc;
+
+	glBufferSubData(target, offset, size, data);
+}
+
+static void APIENTRY InitGetBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetBufferSubData");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetBufferSubData = extproc;
+
+	glGetBufferSubData(target, offset, size, data);
+}
+
+static GLvoid* APIENTRY InitMapBuffer (GLenum target, GLenum access)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMapBuffer");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glMapBuffer = extproc;
+
+	return glMapBuffer(target, access);
+}
+
+static GLboolean APIENTRY InitUnmapBuffer (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUnmapBuffer");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glUnmapBuffer = extproc;
+
+	return glUnmapBuffer(target);
+}
+
+static void APIENTRY InitGetBufferParameteriv (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetBufferParameteriv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetBufferParameteriv = extproc;
+
+	glGetBufferParameteriv(target, pname, params);
+}
+
+static void APIENTRY InitGetBufferPointerv (GLenum target, GLenum pname, GLvoid* *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetBufferPointerv");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetBufferPointerv = extproc;
+
+	glGetBufferPointerv(target, pname, params);
+}
+
+static void APIENTRY InitActiveTextureARB (GLenum texture)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glActiveTextureARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glActiveTextureARB = extproc;
+
+	glActiveTextureARB(texture);
+}
+
+static void APIENTRY InitClientActiveTextureARB (GLenum texture)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glClientActiveTextureARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glClientActiveTextureARB = extproc;
+
+	glClientActiveTextureARB(texture);
+}
+
+static void APIENTRY InitMultiTexCoord1dARB (GLenum target, GLdouble s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1dARB = extproc;
+
+	glMultiTexCoord1dARB(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1dvARB (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1dvARB = extproc;
+
+	glMultiTexCoord1dvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord1fARB (GLenum target, GLfloat s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1fARB = extproc;
+
+	glMultiTexCoord1fARB(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1fvARB (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1fvARB = extproc;
+
+	glMultiTexCoord1fvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord1iARB (GLenum target, GLint s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1iARB = extproc;
+
+	glMultiTexCoord1iARB(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1ivARB (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1ivARB = extproc;
+
+	glMultiTexCoord1ivARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord1sARB (GLenum target, GLshort s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1sARB = extproc;
+
+	glMultiTexCoord1sARB(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1svARB (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1svARB = extproc;
+
+	glMultiTexCoord1svARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2dARB (GLenum target, GLdouble s, GLdouble t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2dARB = extproc;
+
+	glMultiTexCoord2dARB(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2dvARB (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2dvARB = extproc;
+
+	glMultiTexCoord2dvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2fARB (GLenum target, GLfloat s, GLfloat t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2fARB = extproc;
+
+	glMultiTexCoord2fARB(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2fvARB (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2fvARB = extproc;
+
+	glMultiTexCoord2fvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2iARB (GLenum target, GLint s, GLint t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2iARB = extproc;
+
+	glMultiTexCoord2iARB(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2ivARB (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2ivARB = extproc;
+
+	glMultiTexCoord2ivARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2sARB (GLenum target, GLshort s, GLshort t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2sARB = extproc;
+
+	glMultiTexCoord2sARB(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2svARB (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2svARB = extproc;
+
+	glMultiTexCoord2svARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3dARB = extproc;
+
+	glMultiTexCoord3dARB(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3dvARB (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3dvARB = extproc;
+
+	glMultiTexCoord3dvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3fARB = extproc;
+
+	glMultiTexCoord3fARB(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3fvARB (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3fvARB = extproc;
+
+	glMultiTexCoord3fvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3iARB (GLenum target, GLint s, GLint t, GLint r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3iARB = extproc;
+
+	glMultiTexCoord3iARB(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3ivARB (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3ivARB = extproc;
+
+	glMultiTexCoord3ivARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3sARB (GLenum target, GLshort s, GLshort t, GLshort r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3sARB = extproc;
+
+	glMultiTexCoord3sARB(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3svARB (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3svARB = extproc;
+
+	glMultiTexCoord3svARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4dARB (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4dARB = extproc;
+
+	glMultiTexCoord4dARB(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4dvARB (GLenum target, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4dvARB = extproc;
+
+	glMultiTexCoord4dvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4fARB (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4fARB = extproc;
+
+	glMultiTexCoord4fARB(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4fvARB (GLenum target, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4fvARB = extproc;
+
+	glMultiTexCoord4fvARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4iARB (GLenum target, GLint s, GLint t, GLint r, GLint q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4iARB = extproc;
+
+	glMultiTexCoord4iARB(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4ivARB (GLenum target, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4ivARB = extproc;
+
+	glMultiTexCoord4ivARB(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4sARB (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4sARB = extproc;
+
+	glMultiTexCoord4sARB(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4svARB (GLenum target, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4svARB = extproc;
+
+	glMultiTexCoord4svARB(target, v);
+}
+
+static void APIENTRY InitLoadTransposeMatrixfARB (const GLfloat *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLoadTransposeMatrixfARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLoadTransposeMatrixfARB = extproc;
+
+	glLoadTransposeMatrixfARB(m);
+}
+
+static void APIENTRY InitLoadTransposeMatrixdARB (const GLdouble *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLoadTransposeMatrixdARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLoadTransposeMatrixdARB = extproc;
+
+	glLoadTransposeMatrixdARB(m);
+}
+
+static void APIENTRY InitMultTransposeMatrixfARB (const GLfloat *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultTransposeMatrixfARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultTransposeMatrixfARB = extproc;
+
+	glMultTransposeMatrixfARB(m);
+}
+
+static void APIENTRY InitMultTransposeMatrixdARB (const GLdouble *m)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultTransposeMatrixdARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultTransposeMatrixdARB = extproc;
+
+	glMultTransposeMatrixdARB(m);
+}
+
+static void APIENTRY InitSampleCoverageARB (GLclampf value, GLboolean invert)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSampleCoverageARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSampleCoverageARB = extproc;
+
+	glSampleCoverageARB(value, invert);
+}
+
+static void APIENTRY InitCompressedTexImage3DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexImage3DARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexImage3DARB = extproc;
+
+	glCompressedTexImage3DARB(target, level, internalformat, width, height, depth, border, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexImage2DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexImage2DARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexImage2DARB = extproc;
+
+	glCompressedTexImage2DARB(target, level, internalformat, width, height, border, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexImage1DARB (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexImage1DARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexImage1DARB = extproc;
+
+	glCompressedTexImage1DARB(target, level, internalformat, width, border, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexSubImage3DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexSubImage3DARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexSubImage3DARB = extproc;
+
+	glCompressedTexSubImage3DARB(target, level, xoffset, yoffset, zoffset, width, height, depth, format, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexSubImage2DARB (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexSubImage2DARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexSubImage2DARB = extproc;
+
+	glCompressedTexSubImage2DARB(target, level, xoffset, yoffset, width, height, format, imageSize, data);
+}
+
+static void APIENTRY InitCompressedTexSubImage1DARB (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompressedTexSubImage1DARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompressedTexSubImage1DARB = extproc;
+
+	glCompressedTexSubImage1DARB(target, level, xoffset, width, format, imageSize, data);
+}
+
+static void APIENTRY InitGetCompressedTexImageARB (GLenum target, GLint level, GLvoid *img)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCompressedTexImageARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCompressedTexImageARB = extproc;
+
+	glGetCompressedTexImageARB(target, level, img);
+}
+
+static void APIENTRY InitPointParameterfARB (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfARB = extproc;
+
+	glPointParameterfARB(pname, param);
+}
+
+static void APIENTRY InitPointParameterfvARB (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfvARB = extproc;
+
+	glPointParameterfvARB(pname, params);
+}
+
+static void APIENTRY InitWeightbvARB (GLint size, const GLbyte *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightbvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightbvARB = extproc;
+
+	glWeightbvARB(size, weights);
+}
+
+static void APIENTRY InitWeightsvARB (GLint size, const GLshort *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightsvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightsvARB = extproc;
+
+	glWeightsvARB(size, weights);
+}
+
+static void APIENTRY InitWeightivARB (GLint size, const GLint *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightivARB = extproc;
+
+	glWeightivARB(size, weights);
+}
+
+static void APIENTRY InitWeightfvARB (GLint size, const GLfloat *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightfvARB = extproc;
+
+	glWeightfvARB(size, weights);
+}
+
+static void APIENTRY InitWeightdvARB (GLint size, const GLdouble *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightdvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightdvARB = extproc;
+
+	glWeightdvARB(size, weights);
+}
+
+static void APIENTRY InitWeightubvARB (GLint size, const GLubyte *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightubvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightubvARB = extproc;
+
+	glWeightubvARB(size, weights);
+}
+
+static void APIENTRY InitWeightusvARB (GLint size, const GLushort *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightusvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightusvARB = extproc;
+
+	glWeightusvARB(size, weights);
+}
+
+static void APIENTRY InitWeightuivARB (GLint size, const GLuint *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightuivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightuivARB = extproc;
+
+	glWeightuivARB(size, weights);
+}
+
+static void APIENTRY InitWeightPointerARB (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWeightPointerARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWeightPointerARB = extproc;
+
+	glWeightPointerARB(size, type, stride, pointer);
+}
+
+static void APIENTRY InitVertexBlendARB (GLint count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexBlendARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexBlendARB = extproc;
+
+	glVertexBlendARB(count);
+}
+
+static void APIENTRY InitCurrentPaletteMatrixARB (GLint index)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCurrentPaletteMatrixARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCurrentPaletteMatrixARB = extproc;
+
+	glCurrentPaletteMatrixARB(index);
+}
+
+static void APIENTRY InitMatrixIndexubvARB (GLint size, const GLubyte *indices)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMatrixIndexubvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMatrixIndexubvARB = extproc;
+
+	glMatrixIndexubvARB(size, indices);
+}
+
+static void APIENTRY InitMatrixIndexusvARB (GLint size, const GLushort *indices)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMatrixIndexusvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMatrixIndexusvARB = extproc;
+
+	glMatrixIndexusvARB(size, indices);
+}
+
+static void APIENTRY InitMatrixIndexuivARB (GLint size, const GLuint *indices)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMatrixIndexuivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMatrixIndexuivARB = extproc;
+
+	glMatrixIndexuivARB(size, indices);
+}
+
+static void APIENTRY InitMatrixIndexPointerARB (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMatrixIndexPointerARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMatrixIndexPointerARB = extproc;
+
+	glMatrixIndexPointerARB(size, type, stride, pointer);
+}
+
+static void APIENTRY InitWindowPos2dARB (GLdouble x, GLdouble y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2dARB = extproc;
+
+	glWindowPos2dARB(x, y);
+}
+
+static void APIENTRY InitWindowPos2dvARB (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2dvARB = extproc;
+
+	glWindowPos2dvARB(v);
+}
+
+static void APIENTRY InitWindowPos2fARB (GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2fARB = extproc;
+
+	glWindowPos2fARB(x, y);
+}
+
+static void APIENTRY InitWindowPos2fvARB (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2fvARB = extproc;
+
+	glWindowPos2fvARB(v);
+}
+
+static void APIENTRY InitWindowPos2iARB (GLint x, GLint y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2iARB = extproc;
+
+	glWindowPos2iARB(x, y);
+}
+
+static void APIENTRY InitWindowPos2ivARB (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2ivARB = extproc;
+
+	glWindowPos2ivARB(v);
+}
+
+static void APIENTRY InitWindowPos2sARB (GLshort x, GLshort y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2sARB = extproc;
+
+	glWindowPos2sARB(x, y);
+}
+
+static void APIENTRY InitWindowPos2svARB (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2svARB = extproc;
+
+	glWindowPos2svARB(v);
+}
+
+static void APIENTRY InitWindowPos3dARB (GLdouble x, GLdouble y, GLdouble z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3dARB = extproc;
+
+	glWindowPos3dARB(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3dvARB (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3dvARB = extproc;
+
+	glWindowPos3dvARB(v);
+}
+
+static void APIENTRY InitWindowPos3fARB (GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3fARB = extproc;
+
+	glWindowPos3fARB(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3fvARB (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3fvARB = extproc;
+
+	glWindowPos3fvARB(v);
+}
+
+static void APIENTRY InitWindowPos3iARB (GLint x, GLint y, GLint z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3iARB = extproc;
+
+	glWindowPos3iARB(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3ivARB (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3ivARB = extproc;
+
+	glWindowPos3ivARB(v);
+}
+
+static void APIENTRY InitWindowPos3sARB (GLshort x, GLshort y, GLshort z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3sARB = extproc;
+
+	glWindowPos3sARB(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3svARB (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3svARB = extproc;
+
+	glWindowPos3svARB(v);
+}
+
+static void APIENTRY InitVertexAttrib1dARB (GLuint index, GLdouble x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1dARB = extproc;
+
+	glVertexAttrib1dARB(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1dvARB (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1dvARB = extproc;
+
+	glVertexAttrib1dvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib1fARB (GLuint index, GLfloat x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1fARB = extproc;
+
+	glVertexAttrib1fARB(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1fvARB (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1fvARB = extproc;
+
+	glVertexAttrib1fvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib1sARB (GLuint index, GLshort x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1sARB = extproc;
+
+	glVertexAttrib1sARB(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1svARB (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1svARB = extproc;
+
+	glVertexAttrib1svARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2dARB (GLuint index, GLdouble x, GLdouble y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2dARB = extproc;
+
+	glVertexAttrib2dARB(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2dvARB (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2dvARB = extproc;
+
+	glVertexAttrib2dvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2fARB (GLuint index, GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2fARB = extproc;
+
+	glVertexAttrib2fARB(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2fvARB (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2fvARB = extproc;
+
+	glVertexAttrib2fvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2sARB (GLuint index, GLshort x, GLshort y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2sARB = extproc;
+
+	glVertexAttrib2sARB(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2svARB (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2svARB = extproc;
+
+	glVertexAttrib2svARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3dARB = extproc;
+
+	glVertexAttrib3dARB(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3dvARB (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3dvARB = extproc;
+
+	glVertexAttrib3dvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3fARB = extproc;
+
+	glVertexAttrib3fARB(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3fvARB (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3fvARB = extproc;
+
+	glVertexAttrib3fvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3sARB (GLuint index, GLshort x, GLshort y, GLshort z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3sARB = extproc;
+
+	glVertexAttrib3sARB(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3svARB (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3svARB = extproc;
+
+	glVertexAttrib3svARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4NbvARB (GLuint index, const GLbyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NbvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NbvARB = extproc;
+
+	glVertexAttrib4NbvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4NivARB (GLuint index, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NivARB = extproc;
+
+	glVertexAttrib4NivARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4NsvARB (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NsvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NsvARB = extproc;
+
+	glVertexAttrib4NsvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4NubARB (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NubARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NubARB = extproc;
+
+	glVertexAttrib4NubARB(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4NubvARB (GLuint index, const GLubyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NubvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NubvARB = extproc;
+
+	glVertexAttrib4NubvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4NuivARB (GLuint index, const GLuint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NuivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NuivARB = extproc;
+
+	glVertexAttrib4NuivARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4NusvARB (GLuint index, const GLushort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4NusvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4NusvARB = extproc;
+
+	glVertexAttrib4NusvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4bvARB (GLuint index, const GLbyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4bvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4bvARB = extproc;
+
+	glVertexAttrib4bvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4dARB (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4dARB = extproc;
+
+	glVertexAttrib4dARB(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4dvARB (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4dvARB = extproc;
+
+	glVertexAttrib4dvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4fARB (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4fARB = extproc;
+
+	glVertexAttrib4fARB(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4fvARB (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4fvARB = extproc;
+
+	glVertexAttrib4fvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4ivARB (GLuint index, const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4ivARB = extproc;
+
+	glVertexAttrib4ivARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4sARB (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4sARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4sARB = extproc;
+
+	glVertexAttrib4sARB(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4svARB (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4svARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4svARB = extproc;
+
+	glVertexAttrib4svARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4ubvARB (GLuint index, const GLubyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4ubvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4ubvARB = extproc;
+
+	glVertexAttrib4ubvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4uivARB (GLuint index, const GLuint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4uivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4uivARB = extproc;
+
+	glVertexAttrib4uivARB(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4usvARB (GLuint index, const GLushort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4usvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4usvARB = extproc;
+
+	glVertexAttrib4usvARB(index, v);
+}
+
+static void APIENTRY InitVertexAttribPointerARB (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribPointerARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribPointerARB = extproc;
+
+	glVertexAttribPointerARB(index, size, type, normalized, stride, pointer);
+}
+
+static void APIENTRY InitEnableVertexAttribArrayARB (GLuint index)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEnableVertexAttribArrayARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEnableVertexAttribArrayARB = extproc;
+
+	glEnableVertexAttribArrayARB(index);
+}
+
+static void APIENTRY InitDisableVertexAttribArrayARB (GLuint index)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDisableVertexAttribArrayARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDisableVertexAttribArrayARB = extproc;
+
+	glDisableVertexAttribArrayARB(index);
+}
+
+static void APIENTRY InitProgramStringARB (GLenum target, GLenum format, GLsizei len, const GLvoid *string)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramStringARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramStringARB = extproc;
+
+	glProgramStringARB(target, format, len, string);
+}
+
+static void APIENTRY InitBindProgramARB (GLenum target, GLuint program)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindProgramARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindProgramARB = extproc;
+
+	glBindProgramARB(target, program);
+}
+
+static void APIENTRY InitDeleteProgramsARB (GLsizei n, const GLuint *programs)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteProgramsARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteProgramsARB = extproc;
+
+	glDeleteProgramsARB(n, programs);
+}
+
+static void APIENTRY InitGenProgramsARB (GLsizei n, GLuint *programs)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenProgramsARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenProgramsARB = extproc;
+
+	glGenProgramsARB(n, programs);
+}
+
+static void APIENTRY InitProgramEnvParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramEnvParameter4dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramEnvParameter4dARB = extproc;
+
+	glProgramEnvParameter4dARB(target, index, x, y, z, w);
+}
+
+static void APIENTRY InitProgramEnvParameter4dvARB (GLenum target, GLuint index, const GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramEnvParameter4dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramEnvParameter4dvARB = extproc;
+
+	glProgramEnvParameter4dvARB(target, index, params);
+}
+
+static void APIENTRY InitProgramEnvParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramEnvParameter4fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramEnvParameter4fARB = extproc;
+
+	glProgramEnvParameter4fARB(target, index, x, y, z, w);
+}
+
+static void APIENTRY InitProgramEnvParameter4fvARB (GLenum target, GLuint index, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramEnvParameter4fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramEnvParameter4fvARB = extproc;
+
+	glProgramEnvParameter4fvARB(target, index, params);
+}
+
+static void APIENTRY InitProgramLocalParameter4dARB (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramLocalParameter4dARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramLocalParameter4dARB = extproc;
+
+	glProgramLocalParameter4dARB(target, index, x, y, z, w);
+}
+
+static void APIENTRY InitProgramLocalParameter4dvARB (GLenum target, GLuint index, const GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramLocalParameter4dvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramLocalParameter4dvARB = extproc;
+
+	glProgramLocalParameter4dvARB(target, index, params);
+}
+
+static void APIENTRY InitProgramLocalParameter4fARB (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramLocalParameter4fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramLocalParameter4fARB = extproc;
+
+	glProgramLocalParameter4fARB(target, index, x, y, z, w);
+}
+
+static void APIENTRY InitProgramLocalParameter4fvARB (GLenum target, GLuint index, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramLocalParameter4fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramLocalParameter4fvARB = extproc;
+
+	glProgramLocalParameter4fvARB(target, index, params);
+}
+
+static void APIENTRY InitGetProgramEnvParameterdvARB (GLenum target, GLuint index, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramEnvParameterdvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramEnvParameterdvARB = extproc;
+
+	glGetProgramEnvParameterdvARB(target, index, params);
+}
+
+static void APIENTRY InitGetProgramEnvParameterfvARB (GLenum target, GLuint index, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramEnvParameterfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramEnvParameterfvARB = extproc;
+
+	glGetProgramEnvParameterfvARB(target, index, params);
+}
+
+static void APIENTRY InitGetProgramLocalParameterdvARB (GLenum target, GLuint index, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramLocalParameterdvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramLocalParameterdvARB = extproc;
+
+	glGetProgramLocalParameterdvARB(target, index, params);
+}
+
+static void APIENTRY InitGetProgramLocalParameterfvARB (GLenum target, GLuint index, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramLocalParameterfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramLocalParameterfvARB = extproc;
+
+	glGetProgramLocalParameterfvARB(target, index, params);
+}
+
+static void APIENTRY InitGetProgramivARB (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramivARB = extproc;
+
+	glGetProgramivARB(target, pname, params);
+}
+
+static void APIENTRY InitGetProgramStringARB (GLenum target, GLenum pname, GLvoid *string)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramStringARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramStringARB = extproc;
+
+	glGetProgramStringARB(target, pname, string);
+}
+
+static void APIENTRY InitGetVertexAttribdvARB (GLuint index, GLenum pname, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribdvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribdvARB = extproc;
+
+	glGetVertexAttribdvARB(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribfvARB (GLuint index, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribfvARB = extproc;
+
+	glGetVertexAttribfvARB(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribivARB (GLuint index, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribivARB = extproc;
+
+	glGetVertexAttribivARB(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribPointervARB (GLuint index, GLenum pname, GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribPointervARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribPointervARB = extproc;
+
+	glGetVertexAttribPointervARB(index, pname, pointer);
+}
+
+static GLboolean APIENTRY InitIsProgramARB (GLuint program)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsProgramARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsProgramARB = extproc;
+
+	return glIsProgramARB(program);
+}
+
+static void APIENTRY InitBindBufferARB (GLenum target, GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindBufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindBufferARB = extproc;
+
+	glBindBufferARB(target, buffer);
+}
+
+static void APIENTRY InitDeleteBuffersARB (GLsizei n, const GLuint *buffers)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteBuffersARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteBuffersARB = extproc;
+
+	glDeleteBuffersARB(n, buffers);
+}
+
+static void APIENTRY InitGenBuffersARB (GLsizei n, GLuint *buffers)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenBuffersARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenBuffersARB = extproc;
+
+	glGenBuffersARB(n, buffers);
+}
+
+static GLboolean APIENTRY InitIsBufferARB (GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsBufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsBufferARB = extproc;
+
+	return glIsBufferARB(buffer);
+}
+
+static void APIENTRY InitBufferDataARB (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBufferDataARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBufferDataARB = extproc;
+
+	glBufferDataARB(target, size, data, usage);
+}
+
+static void APIENTRY InitBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBufferSubDataARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBufferSubDataARB = extproc;
+
+	glBufferSubDataARB(target, offset, size, data);
+}
+
+static void APIENTRY InitGetBufferSubDataARB (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetBufferSubDataARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetBufferSubDataARB = extproc;
+
+	glGetBufferSubDataARB(target, offset, size, data);
+}
+
+static GLvoid* APIENTRY InitMapBufferARB (GLenum target, GLenum access)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMapBufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glMapBufferARB = extproc;
+
+	return glMapBufferARB(target, access);
+}
+
+static GLboolean APIENTRY InitUnmapBufferARB (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUnmapBufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glUnmapBufferARB = extproc;
+
+	return glUnmapBufferARB(target);
+}
+
+static void APIENTRY InitGetBufferParameterivARB (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetBufferParameterivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetBufferParameterivARB = extproc;
+
+	glGetBufferParameterivARB(target, pname, params);
+}
+
+static void APIENTRY InitGetBufferPointervARB (GLenum target, GLenum pname, GLvoid* *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetBufferPointervARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetBufferPointervARB = extproc;
+
+	glGetBufferPointervARB(target, pname, params);
+}
+
+static void APIENTRY InitGenQueriesARB (GLsizei n, GLuint *ids)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenQueriesARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenQueriesARB = extproc;
+
+	glGenQueriesARB(n, ids);
+}
+
+static void APIENTRY InitDeleteQueriesARB (GLsizei n, const GLuint *ids)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteQueriesARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteQueriesARB = extproc;
+
+	glDeleteQueriesARB(n, ids);
+}
+
+static GLboolean APIENTRY InitIsQueryARB (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsQueryARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsQueryARB = extproc;
+
+	return glIsQueryARB(id);
+}
+
+static void APIENTRY InitBeginQueryARB (GLenum target, GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBeginQueryARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBeginQueryARB = extproc;
+
+	glBeginQueryARB(target, id);
+}
+
+static void APIENTRY InitEndQueryARB (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEndQueryARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEndQueryARB = extproc;
+
+	glEndQueryARB(target);
+}
+
+static void APIENTRY InitGetQueryivARB (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetQueryivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetQueryivARB = extproc;
+
+	glGetQueryivARB(target, pname, params);
+}
+
+static void APIENTRY InitGetQueryObjectivARB (GLuint id, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetQueryObjectivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetQueryObjectivARB = extproc;
+
+	glGetQueryObjectivARB(id, pname, params);
+}
+
+static void APIENTRY InitGetQueryObjectuivARB (GLuint id, GLenum pname, GLuint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetQueryObjectuivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetQueryObjectuivARB = extproc;
+
+	glGetQueryObjectuivARB(id, pname, params);
+}
+
+static void APIENTRY InitDeleteObjectARB (GLhandleARB obj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteObjectARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteObjectARB = extproc;
+
+	glDeleteObjectARB(obj);
+}
+
+static GLhandleARB APIENTRY InitGetHandleARB (GLenum pname)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHandleARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGetHandleARB = extproc;
+
+	return glGetHandleARB(pname);
+}
+
+static void APIENTRY InitDetachObjectARB (GLhandleARB containerObj, GLhandleARB attachedObj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDetachObjectARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDetachObjectARB = extproc;
+
+	glDetachObjectARB(containerObj, attachedObj);
+}
+
+static GLhandleARB APIENTRY InitCreateShaderObjectARB (GLenum shaderType)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCreateShaderObjectARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glCreateShaderObjectARB = extproc;
+
+	return glCreateShaderObjectARB(shaderType);
+}
+
+static void APIENTRY InitShaderSourceARB (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glShaderSourceARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glShaderSourceARB = extproc;
+
+	glShaderSourceARB(shaderObj, count, string, length);
+}
+
+static void APIENTRY InitCompileShaderARB (GLhandleARB shaderObj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCompileShaderARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCompileShaderARB = extproc;
+
+	glCompileShaderARB(shaderObj);
+}
+
+static GLhandleARB APIENTRY InitCreateProgramObjectARB (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCreateProgramObjectARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glCreateProgramObjectARB = extproc;
+
+	return glCreateProgramObjectARB();
+}
+
+static void APIENTRY InitAttachObjectARB (GLhandleARB containerObj, GLhandleARB obj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAttachObjectARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glAttachObjectARB = extproc;
+
+	glAttachObjectARB(containerObj, obj);
+}
+
+static void APIENTRY InitLinkProgramARB (GLhandleARB programObj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLinkProgramARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLinkProgramARB = extproc;
+
+	glLinkProgramARB(programObj);
+}
+
+static void APIENTRY InitUseProgramObjectARB (GLhandleARB programObj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUseProgramObjectARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUseProgramObjectARB = extproc;
+
+	glUseProgramObjectARB(programObj);
+}
+
+static void APIENTRY InitValidateProgramARB (GLhandleARB programObj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glValidateProgramARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glValidateProgramARB = extproc;
+
+	glValidateProgramARB(programObj);
+}
+
+static void APIENTRY InitUniform1fARB (GLint location, GLfloat v0)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform1fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform1fARB = extproc;
+
+	glUniform1fARB(location, v0);
+}
+
+static void APIENTRY InitUniform2fARB (GLint location, GLfloat v0, GLfloat v1)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform2fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform2fARB = extproc;
+
+	glUniform2fARB(location, v0, v1);
+}
+
+static void APIENTRY InitUniform3fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform3fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform3fARB = extproc;
+
+	glUniform3fARB(location, v0, v1, v2);
+}
+
+static void APIENTRY InitUniform4fARB (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform4fARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform4fARB = extproc;
+
+	glUniform4fARB(location, v0, v1, v2, v3);
+}
+
+static void APIENTRY InitUniform1iARB (GLint location, GLint v0)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform1iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform1iARB = extproc;
+
+	glUniform1iARB(location, v0);
+}
+
+static void APIENTRY InitUniform2iARB (GLint location, GLint v0, GLint v1)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform2iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform2iARB = extproc;
+
+	glUniform2iARB(location, v0, v1);
+}
+
+static void APIENTRY InitUniform3iARB (GLint location, GLint v0, GLint v1, GLint v2)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform3iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform3iARB = extproc;
+
+	glUniform3iARB(location, v0, v1, v2);
+}
+
+static void APIENTRY InitUniform4iARB (GLint location, GLint v0, GLint v1, GLint v2, GLint v3)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform4iARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform4iARB = extproc;
+
+	glUniform4iARB(location, v0, v1, v2, v3);
+}
+
+static void APIENTRY InitUniform1fvARB (GLint location, GLsizei count, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform1fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform1fvARB = extproc;
+
+	glUniform1fvARB(location, count, value);
+}
+
+static void APIENTRY InitUniform2fvARB (GLint location, GLsizei count, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform2fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform2fvARB = extproc;
+
+	glUniform2fvARB(location, count, value);
+}
+
+static void APIENTRY InitUniform3fvARB (GLint location, GLsizei count, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform3fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform3fvARB = extproc;
+
+	glUniform3fvARB(location, count, value);
+}
+
+static void APIENTRY InitUniform4fvARB (GLint location, GLsizei count, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform4fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform4fvARB = extproc;
+
+	glUniform4fvARB(location, count, value);
+}
+
+static void APIENTRY InitUniform1ivARB (GLint location, GLsizei count, const GLint *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform1ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform1ivARB = extproc;
+
+	glUniform1ivARB(location, count, value);
+}
+
+static void APIENTRY InitUniform2ivARB (GLint location, GLsizei count, const GLint *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform2ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform2ivARB = extproc;
+
+	glUniform2ivARB(location, count, value);
+}
+
+static void APIENTRY InitUniform3ivARB (GLint location, GLsizei count, const GLint *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform3ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform3ivARB = extproc;
+
+	glUniform3ivARB(location, count, value);
+}
+
+static void APIENTRY InitUniform4ivARB (GLint location, GLsizei count, const GLint *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniform4ivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniform4ivARB = extproc;
+
+	glUniform4ivARB(location, count, value);
+}
+
+static void APIENTRY InitUniformMatrix2fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniformMatrix2fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniformMatrix2fvARB = extproc;
+
+	glUniformMatrix2fvARB(location, count, transpose, value);
+}
+
+static void APIENTRY InitUniformMatrix3fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniformMatrix3fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniformMatrix3fvARB = extproc;
+
+	glUniformMatrix3fvARB(location, count, transpose, value);
+}
+
+static void APIENTRY InitUniformMatrix4fvARB (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUniformMatrix4fvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUniformMatrix4fvARB = extproc;
+
+	glUniformMatrix4fvARB(location, count, transpose, value);
+}
+
+static void APIENTRY InitGetObjectParameterfvARB (GLhandleARB obj, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetObjectParameterfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetObjectParameterfvARB = extproc;
+
+	glGetObjectParameterfvARB(obj, pname, params);
+}
+
+static void APIENTRY InitGetObjectParameterivARB (GLhandleARB obj, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetObjectParameterivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetObjectParameterivARB = extproc;
+
+	glGetObjectParameterivARB(obj, pname, params);
+}
+
+static void APIENTRY InitGetInfoLogARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetInfoLogARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetInfoLogARB = extproc;
+
+	glGetInfoLogARB(obj, maxLength, length, infoLog);
+}
+
+static void APIENTRY InitGetAttachedObjectsARB (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetAttachedObjectsARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetAttachedObjectsARB = extproc;
+
+	glGetAttachedObjectsARB(containerObj, maxCount, count, obj);
+}
+
+static GLint APIENTRY InitGetUniformLocationARB (GLhandleARB programObj, const GLcharARB *name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetUniformLocationARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGetUniformLocationARB = extproc;
+
+	return glGetUniformLocationARB(programObj, name);
+}
+
+static void APIENTRY InitGetActiveUniformARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetActiveUniformARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetActiveUniformARB = extproc;
+
+	glGetActiveUniformARB(programObj, index, maxLength, length, size, type, name);
+}
+
+static void APIENTRY InitGetUniformfvARB (GLhandleARB programObj, GLint location, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetUniformfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetUniformfvARB = extproc;
+
+	glGetUniformfvARB(programObj, location, params);
+}
+
+static void APIENTRY InitGetUniformivARB (GLhandleARB programObj, GLint location, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetUniformivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetUniformivARB = extproc;
+
+	glGetUniformivARB(programObj, location, params);
+}
+
+static void APIENTRY InitGetShaderSourceARB (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetShaderSourceARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetShaderSourceARB = extproc;
+
+	glGetShaderSourceARB(obj, maxLength, length, source);
+}
+
+static void APIENTRY InitBindAttribLocationARB (GLhandleARB programObj, GLuint index, const GLcharARB *name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindAttribLocationARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindAttribLocationARB = extproc;
+
+	glBindAttribLocationARB(programObj, index, name);
+}
+
+static void APIENTRY InitGetActiveAttribARB (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetActiveAttribARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetActiveAttribARB = extproc;
+
+	glGetActiveAttribARB(programObj, index, maxLength, length, size, type, name);
+}
+
+static GLint APIENTRY InitGetAttribLocationARB (GLhandleARB programObj, const GLcharARB *name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetAttribLocationARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGetAttribLocationARB = extproc;
+
+	return glGetAttribLocationARB(programObj, name);
+}
+
+static void APIENTRY InitBlendColorEXT (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendColorEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendColorEXT = extproc;
+
+	glBlendColorEXT(red, green, blue, alpha);
+}
+
+static void APIENTRY InitPolygonOffsetEXT (GLfloat factor, GLfloat bias)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPolygonOffsetEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPolygonOffsetEXT = extproc;
+
+	glPolygonOffsetEXT(factor, bias);
+}
+
+static void APIENTRY InitTexImage3DEXT (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexImage3DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexImage3DEXT = extproc;
+
+	glTexImage3DEXT(target, level, internalformat, width, height, depth, border, format, type, pixels);
+}
+
+static void APIENTRY InitTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexSubImage3DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexSubImage3DEXT = extproc;
+
+	glTexSubImage3DEXT(target, level, xoffset, yoffset, zoffset, width, height, depth, format, type, pixels);
+}
+
+static void APIENTRY InitGetTexFilterFuncSGIS (GLenum target, GLenum filter, GLfloat *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetTexFilterFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetTexFilterFuncSGIS = extproc;
+
+	glGetTexFilterFuncSGIS(target, filter, weights);
+}
+
+static void APIENTRY InitTexFilterFuncSGIS (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexFilterFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexFilterFuncSGIS = extproc;
+
+	glTexFilterFuncSGIS(target, filter, n, weights);
+}
+
+static void APIENTRY InitTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexSubImage1DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexSubImage1DEXT = extproc;
+
+	glTexSubImage1DEXT(target, level, xoffset, width, format, type, pixels);
+}
+
+static void APIENTRY InitTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexSubImage2DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexSubImage2DEXT = extproc;
+
+	glTexSubImage2DEXT(target, level, xoffset, yoffset, width, height, format, type, pixels);
+}
+
+static void APIENTRY InitCopyTexImage1DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyTexImage1DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyTexImage1DEXT = extproc;
+
+	glCopyTexImage1DEXT(target, level, internalformat, x, y, width, border);
+}
+
+static void APIENTRY InitCopyTexImage2DEXT (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyTexImage2DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyTexImage2DEXT = extproc;
+
+	glCopyTexImage2DEXT(target, level, internalformat, x, y, width, height, border);
+}
+
+static void APIENTRY InitCopyTexSubImage1DEXT (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyTexSubImage1DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyTexSubImage1DEXT = extproc;
+
+	glCopyTexSubImage1DEXT(target, level, xoffset, x, y, width);
+}
+
+static void APIENTRY InitCopyTexSubImage2DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyTexSubImage2DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyTexSubImage2DEXT = extproc;
+
+	glCopyTexSubImage2DEXT(target, level, xoffset, yoffset, x, y, width, height);
+}
+
+static void APIENTRY InitCopyTexSubImage3DEXT (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyTexSubImage3DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyTexSubImage3DEXT = extproc;
+
+	glCopyTexSubImage3DEXT(target, level, xoffset, yoffset, zoffset, x, y, width, height);
+}
+
+static void APIENTRY InitGetHistogramEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHistogramEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetHistogramEXT = extproc;
+
+	glGetHistogramEXT(target, reset, format, type, values);
+}
+
+static void APIENTRY InitGetHistogramParameterfvEXT (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHistogramParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetHistogramParameterfvEXT = extproc;
+
+	glGetHistogramParameterfvEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetHistogramParameterivEXT (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetHistogramParameterivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetHistogramParameterivEXT = extproc;
+
+	glGetHistogramParameterivEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetMinmaxEXT (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMinmaxEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMinmaxEXT = extproc;
+
+	glGetMinmaxEXT(target, reset, format, type, values);
+}
+
+static void APIENTRY InitGetMinmaxParameterfvEXT (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMinmaxParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMinmaxParameterfvEXT = extproc;
+
+	glGetMinmaxParameterfvEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetMinmaxParameterivEXT (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMinmaxParameterivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMinmaxParameterivEXT = extproc;
+
+	glGetMinmaxParameterivEXT(target, pname, params);
+}
+
+static void APIENTRY InitHistogramEXT (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glHistogramEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glHistogramEXT = extproc;
+
+	glHistogramEXT(target, width, internalformat, sink);
+}
+
+static void APIENTRY InitMinmaxEXT (GLenum target, GLenum internalformat, GLboolean sink)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMinmaxEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMinmaxEXT = extproc;
+
+	glMinmaxEXT(target, internalformat, sink);
+}
+
+static void APIENTRY InitResetHistogramEXT (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glResetHistogramEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glResetHistogramEXT = extproc;
+
+	glResetHistogramEXT(target);
+}
+
+static void APIENTRY InitResetMinmaxEXT (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glResetMinmaxEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glResetMinmaxEXT = extproc;
+
+	glResetMinmaxEXT(target);
+}
+
+static void APIENTRY InitConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionFilter1DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionFilter1DEXT = extproc;
+
+	glConvolutionFilter1DEXT(target, internalformat, width, format, type, image);
+}
+
+static void APIENTRY InitConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionFilter2DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionFilter2DEXT = extproc;
+
+	glConvolutionFilter2DEXT(target, internalformat, width, height, format, type, image);
+}
+
+static void APIENTRY InitConvolutionParameterfEXT (GLenum target, GLenum pname, GLfloat params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameterfEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameterfEXT = extproc;
+
+	glConvolutionParameterfEXT(target, pname, params);
+}
+
+static void APIENTRY InitConvolutionParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameterfvEXT = extproc;
+
+	glConvolutionParameterfvEXT(target, pname, params);
+}
+
+static void APIENTRY InitConvolutionParameteriEXT (GLenum target, GLenum pname, GLint params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameteriEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameteriEXT = extproc;
+
+	glConvolutionParameteriEXT(target, pname, params);
+}
+
+static void APIENTRY InitConvolutionParameterivEXT (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glConvolutionParameterivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glConvolutionParameterivEXT = extproc;
+
+	glConvolutionParameterivEXT(target, pname, params);
+}
+
+static void APIENTRY InitCopyConvolutionFilter1DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyConvolutionFilter1DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyConvolutionFilter1DEXT = extproc;
+
+	glCopyConvolutionFilter1DEXT(target, internalformat, x, y, width);
+}
+
+static void APIENTRY InitCopyConvolutionFilter2DEXT (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyConvolutionFilter2DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyConvolutionFilter2DEXT = extproc;
+
+	glCopyConvolutionFilter2DEXT(target, internalformat, x, y, width, height);
+}
+
+static void APIENTRY InitGetConvolutionFilterEXT (GLenum target, GLenum format, GLenum type, GLvoid *image)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetConvolutionFilterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetConvolutionFilterEXT = extproc;
+
+	glGetConvolutionFilterEXT(target, format, type, image);
+}
+
+static void APIENTRY InitGetConvolutionParameterfvEXT (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetConvolutionParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetConvolutionParameterfvEXT = extproc;
+
+	glGetConvolutionParameterfvEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetConvolutionParameterivEXT (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetConvolutionParameterivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetConvolutionParameterivEXT = extproc;
+
+	glGetConvolutionParameterivEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetSeparableFilterEXT (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetSeparableFilterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetSeparableFilterEXT = extproc;
+
+	glGetSeparableFilterEXT(target, format, type, row, column, span);
+}
+
+static void APIENTRY InitSeparableFilter2DEXT (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSeparableFilter2DEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSeparableFilter2DEXT = extproc;
+
+	glSeparableFilter2DEXT(target, internalformat, width, height, format, type, row, column);
+}
+
+static void APIENTRY InitColorTableSGI (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTableSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTableSGI = extproc;
+
+	glColorTableSGI(target, internalformat, width, format, type, table);
+}
+
+static void APIENTRY InitColorTableParameterfvSGI (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTableParameterfvSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTableParameterfvSGI = extproc;
+
+	glColorTableParameterfvSGI(target, pname, params);
+}
+
+static void APIENTRY InitColorTableParameterivSGI (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTableParameterivSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTableParameterivSGI = extproc;
+
+	glColorTableParameterivSGI(target, pname, params);
+}
+
+static void APIENTRY InitCopyColorTableSGI (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyColorTableSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyColorTableSGI = extproc;
+
+	glCopyColorTableSGI(target, internalformat, x, y, width);
+}
+
+static void APIENTRY InitGetColorTableSGI (GLenum target, GLenum format, GLenum type, GLvoid *table)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableSGI = extproc;
+
+	glGetColorTableSGI(target, format, type, table);
+}
+
+static void APIENTRY InitGetColorTableParameterfvSGI (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableParameterfvSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableParameterfvSGI = extproc;
+
+	glGetColorTableParameterfvSGI(target, pname, params);
+}
+
+static void APIENTRY InitGetColorTableParameterivSGI (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableParameterivSGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableParameterivSGI = extproc;
+
+	glGetColorTableParameterivSGI(target, pname, params);
+}
+
+static void APIENTRY InitPixelTexGenSGIX (GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTexGenSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTexGenSGIX = extproc;
+
+	glPixelTexGenSGIX(mode);
+}
+
+static void APIENTRY InitPixelTexGenParameteriSGIS (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTexGenParameteriSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTexGenParameteriSGIS = extproc;
+
+	glPixelTexGenParameteriSGIS(pname, param);
+}
+
+static void APIENTRY InitPixelTexGenParameterivSGIS (GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTexGenParameterivSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTexGenParameterivSGIS = extproc;
+
+	glPixelTexGenParameterivSGIS(pname, params);
+}
+
+static void APIENTRY InitPixelTexGenParameterfSGIS (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTexGenParameterfSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTexGenParameterfSGIS = extproc;
+
+	glPixelTexGenParameterfSGIS(pname, param);
+}
+
+static void APIENTRY InitPixelTexGenParameterfvSGIS (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTexGenParameterfvSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTexGenParameterfvSGIS = extproc;
+
+	glPixelTexGenParameterfvSGIS(pname, params);
+}
+
+static void APIENTRY InitGetPixelTexGenParameterivSGIS (GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetPixelTexGenParameterivSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetPixelTexGenParameterivSGIS = extproc;
+
+	glGetPixelTexGenParameterivSGIS(pname, params);
+}
+
+static void APIENTRY InitGetPixelTexGenParameterfvSGIS (GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetPixelTexGenParameterfvSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetPixelTexGenParameterfvSGIS = extproc;
+
+	glGetPixelTexGenParameterfvSGIS(pname, params);
+}
+
+static void APIENTRY InitTexImage4DSGIS (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexImage4DSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexImage4DSGIS = extproc;
+
+	glTexImage4DSGIS(target, level, internalformat, width, height, depth, size4d, border, format, type, pixels);
+}
+
+static void APIENTRY InitTexSubImage4DSGIS (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexSubImage4DSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexSubImage4DSGIS = extproc;
+
+	glTexSubImage4DSGIS(target, level, xoffset, yoffset, zoffset, woffset, width, height, depth, size4d, format, type, pixels);
+}
+
+static GLboolean APIENTRY InitAreTexturesResidentEXT (GLsizei n, const GLuint *textures, GLboolean *residences)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAreTexturesResidentEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glAreTexturesResidentEXT = extproc;
+
+	return glAreTexturesResidentEXT(n, textures, residences);
+}
+
+static void APIENTRY InitBindTextureEXT (GLenum target, GLuint texture)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindTextureEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindTextureEXT = extproc;
+
+	glBindTextureEXT(target, texture);
+}
+
+static void APIENTRY InitDeleteTexturesEXT (GLsizei n, const GLuint *textures)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteTexturesEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteTexturesEXT = extproc;
+
+	glDeleteTexturesEXT(n, textures);
+}
+
+static void APIENTRY InitGenTexturesEXT (GLsizei n, GLuint *textures)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenTexturesEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenTexturesEXT = extproc;
+
+	glGenTexturesEXT(n, textures);
+}
+
+static GLboolean APIENTRY InitIsTextureEXT (GLuint texture)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsTextureEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsTextureEXT = extproc;
+
+	return glIsTextureEXT(texture);
+}
+
+static void APIENTRY InitPrioritizeTexturesEXT (GLsizei n, const GLuint *textures, const GLclampf *priorities)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPrioritizeTexturesEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPrioritizeTexturesEXT = extproc;
+
+	glPrioritizeTexturesEXT(n, textures, priorities);
+}
+
+static void APIENTRY InitDetailTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDetailTexFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDetailTexFuncSGIS = extproc;
+
+	glDetailTexFuncSGIS(target, n, points);
+}
+
+static void APIENTRY InitGetDetailTexFuncSGIS (GLenum target, GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetDetailTexFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetDetailTexFuncSGIS = extproc;
+
+	glGetDetailTexFuncSGIS(target, points);
+}
+
+static void APIENTRY InitSharpenTexFuncSGIS (GLenum target, GLsizei n, const GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSharpenTexFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSharpenTexFuncSGIS = extproc;
+
+	glSharpenTexFuncSGIS(target, n, points);
+}
+
+static void APIENTRY InitGetSharpenTexFuncSGIS (GLenum target, GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetSharpenTexFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetSharpenTexFuncSGIS = extproc;
+
+	glGetSharpenTexFuncSGIS(target, points);
+}
+
+static void APIENTRY InitSampleMaskSGIS (GLclampf value, GLboolean invert)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSampleMaskSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSampleMaskSGIS = extproc;
+
+	glSampleMaskSGIS(value, invert);
+}
+
+static void APIENTRY InitSamplePatternSGIS (GLenum pattern)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSamplePatternSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSamplePatternSGIS = extproc;
+
+	glSamplePatternSGIS(pattern);
+}
+
+static void APIENTRY InitArrayElementEXT (GLint i)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glArrayElementEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glArrayElementEXT = extproc;
+
+	glArrayElementEXT(i);
+}
+
+static void APIENTRY InitColorPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorPointerEXT = extproc;
+
+	glColorPointerEXT(size, type, stride, count, pointer);
+}
+
+static void APIENTRY InitDrawArraysEXT (GLenum mode, GLint first, GLsizei count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawArraysEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawArraysEXT = extproc;
+
+	glDrawArraysEXT(mode, first, count);
+}
+
+static void APIENTRY InitEdgeFlagPointerEXT (GLsizei stride, GLsizei count, const GLboolean *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEdgeFlagPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEdgeFlagPointerEXT = extproc;
+
+	glEdgeFlagPointerEXT(stride, count, pointer);
+}
+
+static void APIENTRY InitGetPointervEXT (GLenum pname, GLvoid* *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetPointervEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetPointervEXT = extproc;
+
+	glGetPointervEXT(pname, params);
+}
+
+static void APIENTRY InitIndexPointerEXT (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIndexPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glIndexPointerEXT = extproc;
+
+	glIndexPointerEXT(type, stride, count, pointer);
+}
+
+static void APIENTRY InitNormalPointerEXT (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalPointerEXT = extproc;
+
+	glNormalPointerEXT(type, stride, count, pointer);
+}
+
+static void APIENTRY InitTexCoordPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoordPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoordPointerEXT = extproc;
+
+	glTexCoordPointerEXT(size, type, stride, count, pointer);
+}
+
+static void APIENTRY InitVertexPointerEXT (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexPointerEXT = extproc;
+
+	glVertexPointerEXT(size, type, stride, count, pointer);
+}
+
+static void APIENTRY InitBlendEquationEXT (GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendEquationEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendEquationEXT = extproc;
+
+	glBlendEquationEXT(mode);
+}
+
+static void APIENTRY InitSpriteParameterfSGIX (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSpriteParameterfSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSpriteParameterfSGIX = extproc;
+
+	glSpriteParameterfSGIX(pname, param);
+}
+
+static void APIENTRY InitSpriteParameterfvSGIX (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSpriteParameterfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSpriteParameterfvSGIX = extproc;
+
+	glSpriteParameterfvSGIX(pname, params);
+}
+
+static void APIENTRY InitSpriteParameteriSGIX (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSpriteParameteriSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSpriteParameteriSGIX = extproc;
+
+	glSpriteParameteriSGIX(pname, param);
+}
+
+static void APIENTRY InitSpriteParameterivSGIX (GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSpriteParameterivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSpriteParameterivSGIX = extproc;
+
+	glSpriteParameterivSGIX(pname, params);
+}
+
+static void APIENTRY InitPointParameterfEXT (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfEXT = extproc;
+
+	glPointParameterfEXT(pname, param);
+}
+
+static void APIENTRY InitPointParameterfvEXT (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfvEXT = extproc;
+
+	glPointParameterfvEXT(pname, params);
+}
+
+static void APIENTRY InitPointParameterfSGIS (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfSGIS = extproc;
+
+	glPointParameterfSGIS(pname, param);
+}
+
+static void APIENTRY InitPointParameterfvSGIS (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterfvSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterfvSGIS = extproc;
+
+	glPointParameterfvSGIS(pname, params);
+}
+
+static GLint APIENTRY InitGetInstrumentsSGIX (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetInstrumentsSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGetInstrumentsSGIX = extproc;
+
+	return glGetInstrumentsSGIX();
+}
+
+static void APIENTRY InitInstrumentsBufferSGIX (GLsizei size, GLint *buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glInstrumentsBufferSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glInstrumentsBufferSGIX = extproc;
+
+	glInstrumentsBufferSGIX(size, buffer);
+}
+
+static GLint APIENTRY InitPollInstrumentsSGIX (GLint *marker_p)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPollInstrumentsSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glPollInstrumentsSGIX = extproc;
+
+	return glPollInstrumentsSGIX(marker_p);
+}
+
+static void APIENTRY InitReadInstrumentsSGIX (GLint marker)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReadInstrumentsSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReadInstrumentsSGIX = extproc;
+
+	glReadInstrumentsSGIX(marker);
+}
+
+static void APIENTRY InitStartInstrumentsSGIX (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glStartInstrumentsSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glStartInstrumentsSGIX = extproc;
+
+	glStartInstrumentsSGIX();
+}
+
+static void APIENTRY InitStopInstrumentsSGIX (GLint marker)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glStopInstrumentsSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glStopInstrumentsSGIX = extproc;
+
+	glStopInstrumentsSGIX(marker);
+}
+
+static void APIENTRY InitFrameZoomSGIX (GLint factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFrameZoomSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFrameZoomSGIX = extproc;
+
+	glFrameZoomSGIX(factor);
+}
+
+static void APIENTRY InitTagSampleBufferSGIX (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTagSampleBufferSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTagSampleBufferSGIX = extproc;
+
+	glTagSampleBufferSGIX();
+}
+
+static void APIENTRY InitDeformationMap3dSGIX (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeformationMap3dSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeformationMap3dSGIX = extproc;
+
+	glDeformationMap3dSGIX(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points);
+}
+
+static void APIENTRY InitDeformationMap3fSGIX (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeformationMap3fSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeformationMap3fSGIX = extproc;
+
+	glDeformationMap3fSGIX(target, u1, u2, ustride, uorder, v1, v2, vstride, vorder, w1, w2, wstride, worder, points);
+}
+
+static void APIENTRY InitDeformSGIX (GLbitfield mask)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeformSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeformSGIX = extproc;
+
+	glDeformSGIX(mask);
+}
+
+static void APIENTRY InitLoadIdentityDeformationMapSGIX (GLbitfield mask)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLoadIdentityDeformationMapSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLoadIdentityDeformationMapSGIX = extproc;
+
+	glLoadIdentityDeformationMapSGIX(mask);
+}
+
+static void APIENTRY InitReferencePlaneSGIX (const GLdouble *equation)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReferencePlaneSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReferencePlaneSGIX = extproc;
+
+	glReferencePlaneSGIX(equation);
+}
+
+static void APIENTRY InitFlushRasterSGIX (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFlushRasterSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFlushRasterSGIX = extproc;
+
+	glFlushRasterSGIX();
+}
+
+static void APIENTRY InitFogFuncSGIS (GLsizei n, const GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogFuncSGIS = extproc;
+
+	glFogFuncSGIS(n, points);
+}
+
+static void APIENTRY InitGetFogFuncSGIS (GLfloat *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFogFuncSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFogFuncSGIS = extproc;
+
+	glGetFogFuncSGIS(points);
+}
+
+static void APIENTRY InitImageTransformParameteriHP (GLenum target, GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glImageTransformParameteriHP");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glImageTransformParameteriHP = extproc;
+
+	glImageTransformParameteriHP(target, pname, param);
+}
+
+static void APIENTRY InitImageTransformParameterfHP (GLenum target, GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glImageTransformParameterfHP");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glImageTransformParameterfHP = extproc;
+
+	glImageTransformParameterfHP(target, pname, param);
+}
+
+static void APIENTRY InitImageTransformParameterivHP (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glImageTransformParameterivHP");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glImageTransformParameterivHP = extproc;
+
+	glImageTransformParameterivHP(target, pname, params);
+}
+
+static void APIENTRY InitImageTransformParameterfvHP (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glImageTransformParameterfvHP");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glImageTransformParameterfvHP = extproc;
+
+	glImageTransformParameterfvHP(target, pname, params);
+}
+
+static void APIENTRY InitGetImageTransformParameterivHP (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetImageTransformParameterivHP");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetImageTransformParameterivHP = extproc;
+
+	glGetImageTransformParameterivHP(target, pname, params);
+}
+
+static void APIENTRY InitGetImageTransformParameterfvHP (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetImageTransformParameterfvHP");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetImageTransformParameterfvHP = extproc;
+
+	glGetImageTransformParameterfvHP(target, pname, params);
+}
+
+static void APIENTRY InitColorSubTableEXT (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorSubTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorSubTableEXT = extproc;
+
+	glColorSubTableEXT(target, start, count, format, type, data);
+}
+
+static void APIENTRY InitCopyColorSubTableEXT (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCopyColorSubTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCopyColorSubTableEXT = extproc;
+
+	glCopyColorSubTableEXT(target, start, x, y, width);
+}
+
+static void APIENTRY InitHintPGI (GLenum target, GLint mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glHintPGI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glHintPGI = extproc;
+
+	glHintPGI(target, mode);
+}
+
+static void APIENTRY InitColorTableEXT (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorTableEXT = extproc;
+
+	glColorTableEXT(target, internalFormat, width, format, type, table);
+}
+
+static void APIENTRY InitGetColorTableEXT (GLenum target, GLenum format, GLenum type, GLvoid *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableEXT = extproc;
+
+	glGetColorTableEXT(target, format, type, data);
+}
+
+static void APIENTRY InitGetColorTableParameterivEXT (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableParameterivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableParameterivEXT = extproc;
+
+	glGetColorTableParameterivEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetColorTableParameterfvEXT (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetColorTableParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetColorTableParameterfvEXT = extproc;
+
+	glGetColorTableParameterfvEXT(target, pname, params);
+}
+
+static void APIENTRY InitGetListParameterfvSGIX (GLuint list, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetListParameterfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetListParameterfvSGIX = extproc;
+
+	glGetListParameterfvSGIX(list, pname, params);
+}
+
+static void APIENTRY InitGetListParameterivSGIX (GLuint list, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetListParameterivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetListParameterivSGIX = extproc;
+
+	glGetListParameterivSGIX(list, pname, params);
+}
+
+static void APIENTRY InitListParameterfSGIX (GLuint list, GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glListParameterfSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glListParameterfSGIX = extproc;
+
+	glListParameterfSGIX(list, pname, param);
+}
+
+static void APIENTRY InitListParameterfvSGIX (GLuint list, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glListParameterfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glListParameterfvSGIX = extproc;
+
+	glListParameterfvSGIX(list, pname, params);
+}
+
+static void APIENTRY InitListParameteriSGIX (GLuint list, GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glListParameteriSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glListParameteriSGIX = extproc;
+
+	glListParameteriSGIX(list, pname, param);
+}
+
+static void APIENTRY InitListParameterivSGIX (GLuint list, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glListParameterivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glListParameterivSGIX = extproc;
+
+	glListParameterivSGIX(list, pname, params);
+}
+
+static void APIENTRY InitIndexMaterialEXT (GLenum face, GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIndexMaterialEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glIndexMaterialEXT = extproc;
+
+	glIndexMaterialEXT(face, mode);
+}
+
+static void APIENTRY InitIndexFuncEXT (GLenum func, GLclampf ref)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIndexFuncEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glIndexFuncEXT = extproc;
+
+	glIndexFuncEXT(func, ref);
+}
+
+static void APIENTRY InitLockArraysEXT (GLint first, GLsizei count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLockArraysEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLockArraysEXT = extproc;
+
+	glLockArraysEXT(first, count);
+}
+
+static void APIENTRY InitUnlockArraysEXT (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUnlockArraysEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUnlockArraysEXT = extproc;
+
+	glUnlockArraysEXT();
+}
+
+static void APIENTRY InitCullParameterdvEXT (GLenum pname, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCullParameterdvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCullParameterdvEXT = extproc;
+
+	glCullParameterdvEXT(pname, params);
+}
+
+static void APIENTRY InitCullParameterfvEXT (GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCullParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCullParameterfvEXT = extproc;
+
+	glCullParameterfvEXT(pname, params);
+}
+
+static void APIENTRY InitFragmentColorMaterialSGIX (GLenum face, GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentColorMaterialSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentColorMaterialSGIX = extproc;
+
+	glFragmentColorMaterialSGIX(face, mode);
+}
+
+static void APIENTRY InitFragmentLightfSGIX (GLenum light, GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightfSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightfSGIX = extproc;
+
+	glFragmentLightfSGIX(light, pname, param);
+}
+
+static void APIENTRY InitFragmentLightfvSGIX (GLenum light, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightfvSGIX = extproc;
+
+	glFragmentLightfvSGIX(light, pname, params);
+}
+
+static void APIENTRY InitFragmentLightiSGIX (GLenum light, GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightiSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightiSGIX = extproc;
+
+	glFragmentLightiSGIX(light, pname, param);
+}
+
+static void APIENTRY InitFragmentLightivSGIX (GLenum light, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightivSGIX = extproc;
+
+	glFragmentLightivSGIX(light, pname, params);
+}
+
+static void APIENTRY InitFragmentLightModelfSGIX (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightModelfSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightModelfSGIX = extproc;
+
+	glFragmentLightModelfSGIX(pname, param);
+}
+
+static void APIENTRY InitFragmentLightModelfvSGIX (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightModelfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightModelfvSGIX = extproc;
+
+	glFragmentLightModelfvSGIX(pname, params);
+}
+
+static void APIENTRY InitFragmentLightModeliSGIX (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightModeliSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightModeliSGIX = extproc;
+
+	glFragmentLightModeliSGIX(pname, param);
+}
+
+static void APIENTRY InitFragmentLightModelivSGIX (GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentLightModelivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentLightModelivSGIX = extproc;
+
+	glFragmentLightModelivSGIX(pname, params);
+}
+
+static void APIENTRY InitFragmentMaterialfSGIX (GLenum face, GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentMaterialfSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentMaterialfSGIX = extproc;
+
+	glFragmentMaterialfSGIX(face, pname, param);
+}
+
+static void APIENTRY InitFragmentMaterialfvSGIX (GLenum face, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentMaterialfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentMaterialfvSGIX = extproc;
+
+	glFragmentMaterialfvSGIX(face, pname, params);
+}
+
+static void APIENTRY InitFragmentMaterialiSGIX (GLenum face, GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentMaterialiSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentMaterialiSGIX = extproc;
+
+	glFragmentMaterialiSGIX(face, pname, param);
+}
+
+static void APIENTRY InitFragmentMaterialivSGIX (GLenum face, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFragmentMaterialivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFragmentMaterialivSGIX = extproc;
+
+	glFragmentMaterialivSGIX(face, pname, params);
+}
+
+static void APIENTRY InitGetFragmentLightfvSGIX (GLenum light, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFragmentLightfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFragmentLightfvSGIX = extproc;
+
+	glGetFragmentLightfvSGIX(light, pname, params);
+}
+
+static void APIENTRY InitGetFragmentLightivSGIX (GLenum light, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFragmentLightivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFragmentLightivSGIX = extproc;
+
+	glGetFragmentLightivSGIX(light, pname, params);
+}
+
+static void APIENTRY InitGetFragmentMaterialfvSGIX (GLenum face, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFragmentMaterialfvSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFragmentMaterialfvSGIX = extproc;
+
+	glGetFragmentMaterialfvSGIX(face, pname, params);
+}
+
+static void APIENTRY InitGetFragmentMaterialivSGIX (GLenum face, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFragmentMaterialivSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFragmentMaterialivSGIX = extproc;
+
+	glGetFragmentMaterialivSGIX(face, pname, params);
+}
+
+static void APIENTRY InitLightEnviSGIX (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLightEnviSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLightEnviSGIX = extproc;
+
+	glLightEnviSGIX(pname, param);
+}
+
+static void APIENTRY InitDrawRangeElementsEXT (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawRangeElementsEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawRangeElementsEXT = extproc;
+
+	glDrawRangeElementsEXT(mode, start, end, count, type, indices);
+}
+
+static void APIENTRY InitApplyTextureEXT (GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glApplyTextureEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glApplyTextureEXT = extproc;
+
+	glApplyTextureEXT(mode);
+}
+
+static void APIENTRY InitTextureLightEXT (GLenum pname)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTextureLightEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTextureLightEXT = extproc;
+
+	glTextureLightEXT(pname);
+}
+
+static void APIENTRY InitTextureMaterialEXT (GLenum face, GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTextureMaterialEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTextureMaterialEXT = extproc;
+
+	glTextureMaterialEXT(face, mode);
+}
+
+static void APIENTRY InitAsyncMarkerSGIX (GLuint marker)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAsyncMarkerSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glAsyncMarkerSGIX = extproc;
+
+	glAsyncMarkerSGIX(marker);
+}
+
+static GLint APIENTRY InitFinishAsyncSGIX (GLuint *markerp)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFinishAsyncSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glFinishAsyncSGIX = extproc;
+
+	return glFinishAsyncSGIX(markerp);
+}
+
+static GLint APIENTRY InitPollAsyncSGIX (GLuint *markerp)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPollAsyncSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glPollAsyncSGIX = extproc;
+
+	return glPollAsyncSGIX(markerp);
+}
+
+static GLuint APIENTRY InitGenAsyncMarkersSGIX (GLsizei range)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenAsyncMarkersSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGenAsyncMarkersSGIX = extproc;
+
+	return glGenAsyncMarkersSGIX(range);
+}
+
+static void APIENTRY InitDeleteAsyncMarkersSGIX (GLuint marker, GLsizei range)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteAsyncMarkersSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteAsyncMarkersSGIX = extproc;
+
+	glDeleteAsyncMarkersSGIX(marker, range);
+}
+
+static GLboolean APIENTRY InitIsAsyncMarkerSGIX (GLuint marker)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsAsyncMarkerSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsAsyncMarkerSGIX = extproc;
+
+	return glIsAsyncMarkerSGIX(marker);
+}
+
+static void APIENTRY InitVertexPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexPointervINTEL");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexPointervINTEL = extproc;
+
+	glVertexPointervINTEL(size, type, pointer);
+}
+
+static void APIENTRY InitNormalPointervINTEL (GLenum type, const GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalPointervINTEL");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalPointervINTEL = extproc;
+
+	glNormalPointervINTEL(type, pointer);
+}
+
+static void APIENTRY InitColorPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorPointervINTEL");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorPointervINTEL = extproc;
+
+	glColorPointervINTEL(size, type, pointer);
+}
+
+static void APIENTRY InitTexCoordPointervINTEL (GLint size, GLenum type, const GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoordPointervINTEL");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoordPointervINTEL = extproc;
+
+	glTexCoordPointervINTEL(size, type, pointer);
+}
+
+static void APIENTRY InitPixelTransformParameteriEXT (GLenum target, GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTransformParameteriEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTransformParameteriEXT = extproc;
+
+	glPixelTransformParameteriEXT(target, pname, param);
+}
+
+static void APIENTRY InitPixelTransformParameterfEXT (GLenum target, GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTransformParameterfEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTransformParameterfEXT = extproc;
+
+	glPixelTransformParameterfEXT(target, pname, param);
+}
+
+static void APIENTRY InitPixelTransformParameterivEXT (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTransformParameterivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTransformParameterivEXT = extproc;
+
+	glPixelTransformParameterivEXT(target, pname, params);
+}
+
+static void APIENTRY InitPixelTransformParameterfvEXT (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelTransformParameterfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelTransformParameterfvEXT = extproc;
+
+	glPixelTransformParameterfvEXT(target, pname, params);
+}
+
+static void APIENTRY InitSecondaryColor3bEXT (GLbyte red, GLbyte green, GLbyte blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3bEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3bEXT = extproc;
+
+	glSecondaryColor3bEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3bvEXT (const GLbyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3bvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3bvEXT = extproc;
+
+	glSecondaryColor3bvEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3dEXT (GLdouble red, GLdouble green, GLdouble blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3dEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3dEXT = extproc;
+
+	glSecondaryColor3dEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3dvEXT (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3dvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3dvEXT = extproc;
+
+	glSecondaryColor3dvEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3fEXT (GLfloat red, GLfloat green, GLfloat blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3fEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3fEXT = extproc;
+
+	glSecondaryColor3fEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3fvEXT (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3fvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3fvEXT = extproc;
+
+	glSecondaryColor3fvEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3iEXT (GLint red, GLint green, GLint blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3iEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3iEXT = extproc;
+
+	glSecondaryColor3iEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3ivEXT (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3ivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3ivEXT = extproc;
+
+	glSecondaryColor3ivEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3sEXT (GLshort red, GLshort green, GLshort blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3sEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3sEXT = extproc;
+
+	glSecondaryColor3sEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3svEXT (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3svEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3svEXT = extproc;
+
+	glSecondaryColor3svEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3ubEXT (GLubyte red, GLubyte green, GLubyte blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3ubEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3ubEXT = extproc;
+
+	glSecondaryColor3ubEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3ubvEXT (const GLubyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3ubvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3ubvEXT = extproc;
+
+	glSecondaryColor3ubvEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3uiEXT (GLuint red, GLuint green, GLuint blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3uiEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3uiEXT = extproc;
+
+	glSecondaryColor3uiEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3uivEXT (const GLuint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3uivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3uivEXT = extproc;
+
+	glSecondaryColor3uivEXT(v);
+}
+
+static void APIENTRY InitSecondaryColor3usEXT (GLushort red, GLushort green, GLushort blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3usEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3usEXT = extproc;
+
+	glSecondaryColor3usEXT(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3usvEXT (const GLushort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3usvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3usvEXT = extproc;
+
+	glSecondaryColor3usvEXT(v);
+}
+
+static void APIENTRY InitSecondaryColorPointerEXT (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColorPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColorPointerEXT = extproc;
+
+	glSecondaryColorPointerEXT(size, type, stride, pointer);
+}
+
+static void APIENTRY InitTextureNormalEXT (GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTextureNormalEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTextureNormalEXT = extproc;
+
+	glTextureNormalEXT(mode);
+}
+
+static void APIENTRY InitMultiDrawArraysEXT (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiDrawArraysEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiDrawArraysEXT = extproc;
+
+	glMultiDrawArraysEXT(mode, first, count, primcount);
+}
+
+static void APIENTRY InitMultiDrawElementsEXT (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiDrawElementsEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiDrawElementsEXT = extproc;
+
+	glMultiDrawElementsEXT(mode, count, type, indices, primcount);
+}
+
+static void APIENTRY InitFogCoordfEXT (GLfloat coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordfEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordfEXT = extproc;
+
+	glFogCoordfEXT(coord);
+}
+
+static void APIENTRY InitFogCoordfvEXT (const GLfloat *coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordfvEXT = extproc;
+
+	glFogCoordfvEXT(coord);
+}
+
+static void APIENTRY InitFogCoorddEXT (GLdouble coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoorddEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoorddEXT = extproc;
+
+	glFogCoorddEXT(coord);
+}
+
+static void APIENTRY InitFogCoorddvEXT (const GLdouble *coord)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoorddvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoorddvEXT = extproc;
+
+	glFogCoorddvEXT(coord);
+}
+
+static void APIENTRY InitFogCoordPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordPointerEXT = extproc;
+
+	glFogCoordPointerEXT(type, stride, pointer);
+}
+
+static void APIENTRY InitTangent3bEXT (GLbyte tx, GLbyte ty, GLbyte tz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3bEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3bEXT = extproc;
+
+	glTangent3bEXT(tx, ty, tz);
+}
+
+static void APIENTRY InitTangent3bvEXT (const GLbyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3bvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3bvEXT = extproc;
+
+	glTangent3bvEXT(v);
+}
+
+static void APIENTRY InitTangent3dEXT (GLdouble tx, GLdouble ty, GLdouble tz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3dEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3dEXT = extproc;
+
+	glTangent3dEXT(tx, ty, tz);
+}
+
+static void APIENTRY InitTangent3dvEXT (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3dvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3dvEXT = extproc;
+
+	glTangent3dvEXT(v);
+}
+
+static void APIENTRY InitTangent3fEXT (GLfloat tx, GLfloat ty, GLfloat tz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3fEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3fEXT = extproc;
+
+	glTangent3fEXT(tx, ty, tz);
+}
+
+static void APIENTRY InitTangent3fvEXT (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3fvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3fvEXT = extproc;
+
+	glTangent3fvEXT(v);
+}
+
+static void APIENTRY InitTangent3iEXT (GLint tx, GLint ty, GLint tz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3iEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3iEXT = extproc;
+
+	glTangent3iEXT(tx, ty, tz);
+}
+
+static void APIENTRY InitTangent3ivEXT (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3ivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3ivEXT = extproc;
+
+	glTangent3ivEXT(v);
+}
+
+static void APIENTRY InitTangent3sEXT (GLshort tx, GLshort ty, GLshort tz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3sEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3sEXT = extproc;
+
+	glTangent3sEXT(tx, ty, tz);
+}
+
+static void APIENTRY InitTangent3svEXT (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangent3svEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangent3svEXT = extproc;
+
+	glTangent3svEXT(v);
+}
+
+static void APIENTRY InitBinormal3bEXT (GLbyte bx, GLbyte by, GLbyte bz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3bEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3bEXT = extproc;
+
+	glBinormal3bEXT(bx, by, bz);
+}
+
+static void APIENTRY InitBinormal3bvEXT (const GLbyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3bvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3bvEXT = extproc;
+
+	glBinormal3bvEXT(v);
+}
+
+static void APIENTRY InitBinormal3dEXT (GLdouble bx, GLdouble by, GLdouble bz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3dEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3dEXT = extproc;
+
+	glBinormal3dEXT(bx, by, bz);
+}
+
+static void APIENTRY InitBinormal3dvEXT (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3dvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3dvEXT = extproc;
+
+	glBinormal3dvEXT(v);
+}
+
+static void APIENTRY InitBinormal3fEXT (GLfloat bx, GLfloat by, GLfloat bz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3fEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3fEXT = extproc;
+
+	glBinormal3fEXT(bx, by, bz);
+}
+
+static void APIENTRY InitBinormal3fvEXT (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3fvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3fvEXT = extproc;
+
+	glBinormal3fvEXT(v);
+}
+
+static void APIENTRY InitBinormal3iEXT (GLint bx, GLint by, GLint bz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3iEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3iEXT = extproc;
+
+	glBinormal3iEXT(bx, by, bz);
+}
+
+static void APIENTRY InitBinormal3ivEXT (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3ivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3ivEXT = extproc;
+
+	glBinormal3ivEXT(v);
+}
+
+static void APIENTRY InitBinormal3sEXT (GLshort bx, GLshort by, GLshort bz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3sEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3sEXT = extproc;
+
+	glBinormal3sEXT(bx, by, bz);
+}
+
+static void APIENTRY InitBinormal3svEXT (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormal3svEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormal3svEXT = extproc;
+
+	glBinormal3svEXT(v);
+}
+
+static void APIENTRY InitTangentPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTangentPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTangentPointerEXT = extproc;
+
+	glTangentPointerEXT(type, stride, pointer);
+}
+
+static void APIENTRY InitBinormalPointerEXT (GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBinormalPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBinormalPointerEXT = extproc;
+
+	glBinormalPointerEXT(type, stride, pointer);
+}
+
+static void APIENTRY InitFinishTextureSUNX (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFinishTextureSUNX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFinishTextureSUNX = extproc;
+
+	glFinishTextureSUNX();
+}
+
+static void APIENTRY InitGlobalAlphaFactorbSUN (GLbyte factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactorbSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactorbSUN = extproc;
+
+	glGlobalAlphaFactorbSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactorsSUN (GLshort factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactorsSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactorsSUN = extproc;
+
+	glGlobalAlphaFactorsSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactoriSUN (GLint factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactoriSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactoriSUN = extproc;
+
+	glGlobalAlphaFactoriSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactorfSUN (GLfloat factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactorfSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactorfSUN = extproc;
+
+	glGlobalAlphaFactorfSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactordSUN (GLdouble factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactordSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactordSUN = extproc;
+
+	glGlobalAlphaFactordSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactorubSUN (GLubyte factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactorubSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactorubSUN = extproc;
+
+	glGlobalAlphaFactorubSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactorusSUN (GLushort factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactorusSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactorusSUN = extproc;
+
+	glGlobalAlphaFactorusSUN(factor);
+}
+
+static void APIENTRY InitGlobalAlphaFactoruiSUN (GLuint factor)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGlobalAlphaFactoruiSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGlobalAlphaFactoruiSUN = extproc;
+
+	glGlobalAlphaFactoruiSUN(factor);
+}
+
+static void APIENTRY InitReplacementCodeuiSUN (GLuint code)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiSUN = extproc;
+
+	glReplacementCodeuiSUN(code);
+}
+
+static void APIENTRY InitReplacementCodeusSUN (GLushort code)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeusSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeusSUN = extproc;
+
+	glReplacementCodeusSUN(code);
+}
+
+static void APIENTRY InitReplacementCodeubSUN (GLubyte code)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeubSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeubSUN = extproc;
+
+	glReplacementCodeubSUN(code);
+}
+
+static void APIENTRY InitReplacementCodeuivSUN (const GLuint *code)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuivSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuivSUN = extproc;
+
+	glReplacementCodeuivSUN(code);
+}
+
+static void APIENTRY InitReplacementCodeusvSUN (const GLushort *code)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeusvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeusvSUN = extproc;
+
+	glReplacementCodeusvSUN(code);
+}
+
+static void APIENTRY InitReplacementCodeubvSUN (const GLubyte *code)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeubvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeubvSUN = extproc;
+
+	glReplacementCodeubvSUN(code);
+}
+
+static void APIENTRY InitReplacementCodePointerSUN (GLenum type, GLsizei stride, const GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodePointerSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodePointerSUN = extproc;
+
+	glReplacementCodePointerSUN(type, stride, pointer);
+}
+
+static void APIENTRY InitColor4ubVertex2fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4ubVertex2fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4ubVertex2fSUN = extproc;
+
+	glColor4ubVertex2fSUN(r, g, b, a, x, y);
+}
+
+static void APIENTRY InitColor4ubVertex2fvSUN (const GLubyte *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4ubVertex2fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4ubVertex2fvSUN = extproc;
+
+	glColor4ubVertex2fvSUN(c, v);
+}
+
+static void APIENTRY InitColor4ubVertex3fSUN (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4ubVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4ubVertex3fSUN = extproc;
+
+	glColor4ubVertex3fSUN(r, g, b, a, x, y, z);
+}
+
+static void APIENTRY InitColor4ubVertex3fvSUN (const GLubyte *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4ubVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4ubVertex3fvSUN = extproc;
+
+	glColor4ubVertex3fvSUN(c, v);
+}
+
+static void APIENTRY InitColor3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor3fVertex3fSUN = extproc;
+
+	glColor3fVertex3fSUN(r, g, b, x, y, z);
+}
+
+static void APIENTRY InitColor3fVertex3fvSUN (const GLfloat *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor3fVertex3fvSUN = extproc;
+
+	glColor3fVertex3fvSUN(c, v);
+}
+
+static void APIENTRY InitNormal3fVertex3fSUN (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormal3fVertex3fSUN = extproc;
+
+	glNormal3fVertex3fSUN(nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitNormal3fVertex3fvSUN (const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormal3fVertex3fvSUN = extproc;
+
+	glNormal3fVertex3fvSUN(n, v);
+}
+
+static void APIENTRY InitColor4fNormal3fVertex3fSUN (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4fNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4fNormal3fVertex3fSUN = extproc;
+
+	glColor4fNormal3fVertex3fSUN(r, g, b, a, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitColor4fNormal3fVertex3fvSUN (const GLfloat *c, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4fNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4fNormal3fVertex3fvSUN = extproc;
+
+	glColor4fNormal3fVertex3fvSUN(c, n, v);
+}
+
+static void APIENTRY InitTexCoord2fVertex3fSUN (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fVertex3fSUN = extproc;
+
+	glTexCoord2fVertex3fSUN(s, t, x, y, z);
+}
+
+static void APIENTRY InitTexCoord2fVertex3fvSUN (const GLfloat *tc, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fVertex3fvSUN = extproc;
+
+	glTexCoord2fVertex3fvSUN(tc, v);
+}
+
+static void APIENTRY InitTexCoord4fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord4fVertex4fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord4fVertex4fSUN = extproc;
+
+	glTexCoord4fVertex4fSUN(s, t, p, q, x, y, z, w);
+}
+
+static void APIENTRY InitTexCoord4fVertex4fvSUN (const GLfloat *tc, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord4fVertex4fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord4fVertex4fvSUN = extproc;
+
+	glTexCoord4fVertex4fvSUN(tc, v);
+}
+
+static void APIENTRY InitTexCoord2fColor4ubVertex3fSUN (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fColor4ubVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fColor4ubVertex3fSUN = extproc;
+
+	glTexCoord2fColor4ubVertex3fSUN(s, t, r, g, b, a, x, y, z);
+}
+
+static void APIENTRY InitTexCoord2fColor4ubVertex3fvSUN (const GLfloat *tc, const GLubyte *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fColor4ubVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fColor4ubVertex3fvSUN = extproc;
+
+	glTexCoord2fColor4ubVertex3fvSUN(tc, c, v);
+}
+
+static void APIENTRY InitTexCoord2fColor3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fColor3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fColor3fVertex3fSUN = extproc;
+
+	glTexCoord2fColor3fVertex3fSUN(s, t, r, g, b, x, y, z);
+}
+
+static void APIENTRY InitTexCoord2fColor3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fColor3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fColor3fVertex3fvSUN = extproc;
+
+	glTexCoord2fColor3fVertex3fvSUN(tc, c, v);
+}
+
+static void APIENTRY InitTexCoord2fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fNormal3fVertex3fSUN = extproc;
+
+	glTexCoord2fNormal3fVertex3fSUN(s, t, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitTexCoord2fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fNormal3fVertex3fvSUN = extproc;
+
+	glTexCoord2fNormal3fVertex3fvSUN(tc, n, v);
+}
+
+static void APIENTRY InitTexCoord2fColor4fNormal3fVertex3fSUN (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fColor4fNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fColor4fNormal3fVertex3fSUN = extproc;
+
+	glTexCoord2fColor4fNormal3fVertex3fSUN(s, t, r, g, b, a, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitTexCoord2fColor4fNormal3fVertex3fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2fColor4fNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2fColor4fNormal3fVertex3fvSUN = extproc;
+
+	glTexCoord2fColor4fNormal3fVertex3fvSUN(tc, c, n, v);
+}
+
+static void APIENTRY InitTexCoord4fColor4fNormal3fVertex4fSUN (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord4fColor4fNormal3fVertex4fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord4fColor4fNormal3fVertex4fSUN = extproc;
+
+	glTexCoord4fColor4fNormal3fVertex4fSUN(s, t, p, q, r, g, b, a, nx, ny, nz, x, y, z, w);
+}
+
+static void APIENTRY InitTexCoord4fColor4fNormal3fVertex4fvSUN (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord4fColor4fNormal3fVertex4fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord4fColor4fNormal3fVertex4fvSUN = extproc;
+
+	glTexCoord4fColor4fNormal3fVertex4fvSUN(tc, c, n, v);
+}
+
+static void APIENTRY InitReplacementCodeuiVertex3fSUN (GLuint rc, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiVertex3fSUN = extproc;
+
+	glReplacementCodeuiVertex3fSUN(rc, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiVertex3fvSUN (const GLuint *rc, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiVertex3fvSUN = extproc;
+
+	glReplacementCodeuiVertex3fvSUN(rc, v);
+}
+
+static void APIENTRY InitReplacementCodeuiColor4ubVertex3fSUN (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiColor4ubVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiColor4ubVertex3fSUN = extproc;
+
+	glReplacementCodeuiColor4ubVertex3fSUN(rc, r, g, b, a, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiColor4ubVertex3fvSUN (const GLuint *rc, const GLubyte *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiColor4ubVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiColor4ubVertex3fvSUN = extproc;
+
+	glReplacementCodeuiColor4ubVertex3fvSUN(rc, c, v);
+}
+
+static void APIENTRY InitReplacementCodeuiColor3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiColor3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiColor3fVertex3fSUN = extproc;
+
+	glReplacementCodeuiColor3fVertex3fSUN(rc, r, g, b, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiColor3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiColor3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiColor3fVertex3fvSUN = extproc;
+
+	glReplacementCodeuiColor3fVertex3fvSUN(rc, c, v);
+}
+
+static void APIENTRY InitReplacementCodeuiNormal3fVertex3fSUN (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiNormal3fVertex3fSUN = extproc;
+
+	glReplacementCodeuiNormal3fVertex3fSUN(rc, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiNormal3fVertex3fvSUN = extproc;
+
+	glReplacementCodeuiNormal3fVertex3fvSUN(rc, n, v);
+}
+
+static void APIENTRY InitReplacementCodeuiColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiColor4fNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiColor4fNormal3fVertex3fSUN = extproc;
+
+	glReplacementCodeuiColor4fNormal3fVertex3fSUN(rc, r, g, b, a, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiColor4fNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiColor4fNormal3fVertex3fvSUN = extproc;
+
+	glReplacementCodeuiColor4fNormal3fVertex3fvSUN(rc, c, n, v);
+}
+
+static void APIENTRY InitReplacementCodeuiTexCoord2fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiTexCoord2fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiTexCoord2fVertex3fSUN = extproc;
+
+	glReplacementCodeuiTexCoord2fVertex3fSUN(rc, s, t, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiTexCoord2fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiTexCoord2fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiTexCoord2fVertex3fvSUN = extproc;
+
+	glReplacementCodeuiTexCoord2fVertex3fvSUN(rc, tc, v);
+}
+
+static void APIENTRY InitReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN = extproc;
+
+	glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN(rc, s, t, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN = extproc;
+
+	glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN(rc, tc, n, v);
+}
+
+static void APIENTRY InitReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN = extproc;
+
+	glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN(rc, s, t, r, g, b, a, nx, ny, nz, x, y, z);
+}
+
+static void APIENTRY InitReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN = extproc;
+
+	glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN(rc, tc, c, n, v);
+}
+
+static void APIENTRY InitBlendFuncSeparateEXT (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendFuncSeparateEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendFuncSeparateEXT = extproc;
+
+	glBlendFuncSeparateEXT(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha);
+}
+
+static void APIENTRY InitBlendFuncSeparateINGR (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendFuncSeparateINGR");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendFuncSeparateINGR = extproc;
+
+	glBlendFuncSeparateINGR(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha);
+}
+
+static void APIENTRY InitVertexWeightfEXT (GLfloat weight)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexWeightfEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexWeightfEXT = extproc;
+
+	glVertexWeightfEXT(weight);
+}
+
+static void APIENTRY InitVertexWeightfvEXT (const GLfloat *weight)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexWeightfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexWeightfvEXT = extproc;
+
+	glVertexWeightfvEXT(weight);
+}
+
+static void APIENTRY InitVertexWeightPointerEXT (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexWeightPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexWeightPointerEXT = extproc;
+
+	glVertexWeightPointerEXT(size, type, stride, pointer);
+}
+
+static void APIENTRY InitFlushVertexArrayRangeNV (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFlushVertexArrayRangeNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFlushVertexArrayRangeNV = extproc;
+
+	glFlushVertexArrayRangeNV();
+}
+
+static void APIENTRY InitVertexArrayRangeNV (GLsizei length, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexArrayRangeNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexArrayRangeNV = extproc;
+
+	glVertexArrayRangeNV(length, pointer);
+}
+
+static void APIENTRY InitCombinerParameterfvNV (GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerParameterfvNV = extproc;
+
+	glCombinerParameterfvNV(pname, params);
+}
+
+static void APIENTRY InitCombinerParameterfNV (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerParameterfNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerParameterfNV = extproc;
+
+	glCombinerParameterfNV(pname, param);
+}
+
+static void APIENTRY InitCombinerParameterivNV (GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerParameterivNV = extproc;
+
+	glCombinerParameterivNV(pname, params);
+}
+
+static void APIENTRY InitCombinerParameteriNV (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerParameteriNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerParameteriNV = extproc;
+
+	glCombinerParameteriNV(pname, param);
+}
+
+static void APIENTRY InitCombinerInputNV (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerInputNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerInputNV = extproc;
+
+	glCombinerInputNV(stage, portion, variable, input, mapping, componentUsage);
+}
+
+static void APIENTRY InitCombinerOutputNV (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerOutputNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerOutputNV = extproc;
+
+	glCombinerOutputNV(stage, portion, abOutput, cdOutput, sumOutput, scale, bias, abDotProduct, cdDotProduct, muxSum);
+}
+
+static void APIENTRY InitFinalCombinerInputNV (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFinalCombinerInputNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFinalCombinerInputNV = extproc;
+
+	glFinalCombinerInputNV(variable, input, mapping, componentUsage);
+}
+
+static void APIENTRY InitGetCombinerInputParameterfvNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCombinerInputParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCombinerInputParameterfvNV = extproc;
+
+	glGetCombinerInputParameterfvNV(stage, portion, variable, pname, params);
+}
+
+static void APIENTRY InitGetCombinerInputParameterivNV (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCombinerInputParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCombinerInputParameterivNV = extproc;
+
+	glGetCombinerInputParameterivNV(stage, portion, variable, pname, params);
+}
+
+static void APIENTRY InitGetCombinerOutputParameterfvNV (GLenum stage, GLenum portion, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCombinerOutputParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCombinerOutputParameterfvNV = extproc;
+
+	glGetCombinerOutputParameterfvNV(stage, portion, pname, params);
+}
+
+static void APIENTRY InitGetCombinerOutputParameterivNV (GLenum stage, GLenum portion, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCombinerOutputParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCombinerOutputParameterivNV = extproc;
+
+	glGetCombinerOutputParameterivNV(stage, portion, pname, params);
+}
+
+static void APIENTRY InitGetFinalCombinerInputParameterfvNV (GLenum variable, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFinalCombinerInputParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFinalCombinerInputParameterfvNV = extproc;
+
+	glGetFinalCombinerInputParameterfvNV(variable, pname, params);
+}
+
+static void APIENTRY InitGetFinalCombinerInputParameterivNV (GLenum variable, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFinalCombinerInputParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFinalCombinerInputParameterivNV = extproc;
+
+	glGetFinalCombinerInputParameterivNV(variable, pname, params);
+}
+
+static void APIENTRY InitResizeBuffersMESA (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glResizeBuffersMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glResizeBuffersMESA = extproc;
+
+	glResizeBuffersMESA();
+}
+
+static void APIENTRY InitWindowPos2dMESA (GLdouble x, GLdouble y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2dMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2dMESA = extproc;
+
+	glWindowPos2dMESA(x, y);
+}
+
+static void APIENTRY InitWindowPos2dvMESA (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2dvMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2dvMESA = extproc;
+
+	glWindowPos2dvMESA(v);
+}
+
+static void APIENTRY InitWindowPos2fMESA (GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2fMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2fMESA = extproc;
+
+	glWindowPos2fMESA(x, y);
+}
+
+static void APIENTRY InitWindowPos2fvMESA (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2fvMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2fvMESA = extproc;
+
+	glWindowPos2fvMESA(v);
+}
+
+static void APIENTRY InitWindowPos2iMESA (GLint x, GLint y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2iMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2iMESA = extproc;
+
+	glWindowPos2iMESA(x, y);
+}
+
+static void APIENTRY InitWindowPos2ivMESA (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2ivMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2ivMESA = extproc;
+
+	glWindowPos2ivMESA(v);
+}
+
+static void APIENTRY InitWindowPos2sMESA (GLshort x, GLshort y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2sMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2sMESA = extproc;
+
+	glWindowPos2sMESA(x, y);
+}
+
+static void APIENTRY InitWindowPos2svMESA (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos2svMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos2svMESA = extproc;
+
+	glWindowPos2svMESA(v);
+}
+
+static void APIENTRY InitWindowPos3dMESA (GLdouble x, GLdouble y, GLdouble z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3dMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3dMESA = extproc;
+
+	glWindowPos3dMESA(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3dvMESA (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3dvMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3dvMESA = extproc;
+
+	glWindowPos3dvMESA(v);
+}
+
+static void APIENTRY InitWindowPos3fMESA (GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3fMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3fMESA = extproc;
+
+	glWindowPos3fMESA(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3fvMESA (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3fvMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3fvMESA = extproc;
+
+	glWindowPos3fvMESA(v);
+}
+
+static void APIENTRY InitWindowPos3iMESA (GLint x, GLint y, GLint z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3iMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3iMESA = extproc;
+
+	glWindowPos3iMESA(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3ivMESA (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3ivMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3ivMESA = extproc;
+
+	glWindowPos3ivMESA(v);
+}
+
+static void APIENTRY InitWindowPos3sMESA (GLshort x, GLshort y, GLshort z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3sMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3sMESA = extproc;
+
+	glWindowPos3sMESA(x, y, z);
+}
+
+static void APIENTRY InitWindowPos3svMESA (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos3svMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos3svMESA = extproc;
+
+	glWindowPos3svMESA(v);
+}
+
+static void APIENTRY InitWindowPos4dMESA (GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4dMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4dMESA = extproc;
+
+	glWindowPos4dMESA(x, y, z, w);
+}
+
+static void APIENTRY InitWindowPos4dvMESA (const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4dvMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4dvMESA = extproc;
+
+	glWindowPos4dvMESA(v);
+}
+
+static void APIENTRY InitWindowPos4fMESA (GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4fMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4fMESA = extproc;
+
+	glWindowPos4fMESA(x, y, z, w);
+}
+
+static void APIENTRY InitWindowPos4fvMESA (const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4fvMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4fvMESA = extproc;
+
+	glWindowPos4fvMESA(v);
+}
+
+static void APIENTRY InitWindowPos4iMESA (GLint x, GLint y, GLint z, GLint w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4iMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4iMESA = extproc;
+
+	glWindowPos4iMESA(x, y, z, w);
+}
+
+static void APIENTRY InitWindowPos4ivMESA (const GLint *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4ivMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4ivMESA = extproc;
+
+	glWindowPos4ivMESA(v);
+}
+
+static void APIENTRY InitWindowPos4sMESA (GLshort x, GLshort y, GLshort z, GLshort w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4sMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4sMESA = extproc;
+
+	glWindowPos4sMESA(x, y, z, w);
+}
+
+static void APIENTRY InitWindowPos4svMESA (const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWindowPos4svMESA");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWindowPos4svMESA = extproc;
+
+	glWindowPos4svMESA(v);
+}
+
+static void APIENTRY InitMultiModeDrawArraysIBM (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiModeDrawArraysIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiModeDrawArraysIBM = extproc;
+
+	glMultiModeDrawArraysIBM(mode, first, count, primcount, modestride);
+}
+
+static void APIENTRY InitMultiModeDrawElementsIBM (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiModeDrawElementsIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiModeDrawElementsIBM = extproc;
+
+	glMultiModeDrawElementsIBM(mode, count, type, indices, primcount, modestride);
+}
+
+static void APIENTRY InitColorPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorPointerListIBM = extproc;
+
+	glColorPointerListIBM(size, type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitSecondaryColorPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColorPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColorPointerListIBM = extproc;
+
+	glSecondaryColorPointerListIBM(size, type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitEdgeFlagPointerListIBM (GLint stride, const GLboolean* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEdgeFlagPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEdgeFlagPointerListIBM = extproc;
+
+	glEdgeFlagPointerListIBM(stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitFogCoordPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordPointerListIBM = extproc;
+
+	glFogCoordPointerListIBM(type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitIndexPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIndexPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glIndexPointerListIBM = extproc;
+
+	glIndexPointerListIBM(type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitNormalPointerListIBM (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalPointerListIBM = extproc;
+
+	glNormalPointerListIBM(type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitTexCoordPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoordPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoordPointerListIBM = extproc;
+
+	glTexCoordPointerListIBM(size, type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitVertexPointerListIBM (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexPointerListIBM");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexPointerListIBM = extproc;
+
+	glVertexPointerListIBM(size, type, stride, pointer, ptrstride);
+}
+
+static void APIENTRY InitTbufferMask3DFX (GLuint mask)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTbufferMask3DFX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTbufferMask3DFX = extproc;
+
+	glTbufferMask3DFX(mask);
+}
+
+static void APIENTRY InitSampleMaskEXT (GLclampf value, GLboolean invert)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSampleMaskEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSampleMaskEXT = extproc;
+
+	glSampleMaskEXT(value, invert);
+}
+
+static void APIENTRY InitSamplePatternEXT (GLenum pattern)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSamplePatternEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSamplePatternEXT = extproc;
+
+	glSamplePatternEXT(pattern);
+}
+
+static void APIENTRY InitTextureColorMaskSGIS (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTextureColorMaskSGIS");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTextureColorMaskSGIS = extproc;
+
+	glTextureColorMaskSGIS(red, green, blue, alpha);
+}
+
+static void APIENTRY InitIglooInterfaceSGIX (GLenum pname, const GLvoid *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIglooInterfaceSGIX");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glIglooInterfaceSGIX = extproc;
+
+	glIglooInterfaceSGIX(pname, params);
+}
+
+static void APIENTRY InitDeleteFencesNV (GLsizei n, const GLuint *fences)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteFencesNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteFencesNV = extproc;
+
+	glDeleteFencesNV(n, fences);
+}
+
+static void APIENTRY InitGenFencesNV (GLsizei n, GLuint *fences)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenFencesNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenFencesNV = extproc;
+
+	glGenFencesNV(n, fences);
+}
+
+static GLboolean APIENTRY InitIsFenceNV (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsFenceNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsFenceNV = extproc;
+
+	return glIsFenceNV(fence);
+}
+
+static GLboolean APIENTRY InitTestFenceNV (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTestFenceNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glTestFenceNV = extproc;
+
+	return glTestFenceNV(fence);
+}
+
+static void APIENTRY InitGetFenceivNV (GLuint fence, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetFenceivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetFenceivNV = extproc;
+
+	glGetFenceivNV(fence, pname, params);
+}
+
+static void APIENTRY InitFinishFenceNV (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFinishFenceNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFinishFenceNV = extproc;
+
+	glFinishFenceNV(fence);
+}
+
+static void APIENTRY InitSetFenceNV (GLuint fence, GLenum condition)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSetFenceNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSetFenceNV = extproc;
+
+	glSetFenceNV(fence, condition);
+}
+
+static void APIENTRY InitMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMapControlPointsNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMapControlPointsNV = extproc;
+
+	glMapControlPointsNV(target, index, type, ustride, vstride, uorder, vorder, packed, points);
+}
+
+static void APIENTRY InitMapParameterivNV (GLenum target, GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMapParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMapParameterivNV = extproc;
+
+	glMapParameterivNV(target, pname, params);
+}
+
+static void APIENTRY InitMapParameterfvNV (GLenum target, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMapParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMapParameterfvNV = extproc;
+
+	glMapParameterfvNV(target, pname, params);
+}
+
+static void APIENTRY InitGetMapControlPointsNV (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMapControlPointsNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMapControlPointsNV = extproc;
+
+	glGetMapControlPointsNV(target, index, type, ustride, vstride, packed, points);
+}
+
+static void APIENTRY InitGetMapParameterivNV (GLenum target, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMapParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMapParameterivNV = extproc;
+
+	glGetMapParameterivNV(target, pname, params);
+}
+
+static void APIENTRY InitGetMapParameterfvNV (GLenum target, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMapParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMapParameterfvNV = extproc;
+
+	glGetMapParameterfvNV(target, pname, params);
+}
+
+static void APIENTRY InitGetMapAttribParameterivNV (GLenum target, GLuint index, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMapAttribParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMapAttribParameterivNV = extproc;
+
+	glGetMapAttribParameterivNV(target, index, pname, params);
+}
+
+static void APIENTRY InitGetMapAttribParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetMapAttribParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetMapAttribParameterfvNV = extproc;
+
+	glGetMapAttribParameterfvNV(target, index, pname, params);
+}
+
+static void APIENTRY InitEvalMapsNV (GLenum target, GLenum mode)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEvalMapsNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEvalMapsNV = extproc;
+
+	glEvalMapsNV(target, mode);
+}
+
+static void APIENTRY InitCombinerStageParameterfvNV (GLenum stage, GLenum pname, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glCombinerStageParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glCombinerStageParameterfvNV = extproc;
+
+	glCombinerStageParameterfvNV(stage, pname, params);
+}
+
+static void APIENTRY InitGetCombinerStageParameterfvNV (GLenum stage, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetCombinerStageParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetCombinerStageParameterfvNV = extproc;
+
+	glGetCombinerStageParameterfvNV(stage, pname, params);
+}
+
+static GLboolean APIENTRY InitAreProgramsResidentNV (GLsizei n, const GLuint *programs, GLboolean *residences)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAreProgramsResidentNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glAreProgramsResidentNV = extproc;
+
+	return glAreProgramsResidentNV(n, programs, residences);
+}
+
+static void APIENTRY InitBindProgramNV (GLenum target, GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindProgramNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindProgramNV = extproc;
+
+	glBindProgramNV(target, id);
+}
+
+static void APIENTRY InitDeleteProgramsNV (GLsizei n, const GLuint *programs)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteProgramsNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteProgramsNV = extproc;
+
+	glDeleteProgramsNV(n, programs);
+}
+
+static void APIENTRY InitExecuteProgramNV (GLenum target, GLuint id, const GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glExecuteProgramNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glExecuteProgramNV = extproc;
+
+	glExecuteProgramNV(target, id, params);
+}
+
+static void APIENTRY InitGenProgramsNV (GLsizei n, GLuint *programs)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenProgramsNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenProgramsNV = extproc;
+
+	glGenProgramsNV(n, programs);
+}
+
+static void APIENTRY InitGetProgramParameterdvNV (GLenum target, GLuint index, GLenum pname, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramParameterdvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramParameterdvNV = extproc;
+
+	glGetProgramParameterdvNV(target, index, pname, params);
+}
+
+static void APIENTRY InitGetProgramParameterfvNV (GLenum target, GLuint index, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramParameterfvNV = extproc;
+
+	glGetProgramParameterfvNV(target, index, pname, params);
+}
+
+static void APIENTRY InitGetProgramivNV (GLuint id, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramivNV = extproc;
+
+	glGetProgramivNV(id, pname, params);
+}
+
+static void APIENTRY InitGetProgramStringNV (GLuint id, GLenum pname, GLubyte *program)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramStringNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramStringNV = extproc;
+
+	glGetProgramStringNV(id, pname, program);
+}
+
+static void APIENTRY InitGetTrackMatrixivNV (GLenum target, GLuint address, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetTrackMatrixivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetTrackMatrixivNV = extproc;
+
+	glGetTrackMatrixivNV(target, address, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribdvNV (GLuint index, GLenum pname, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribdvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribdvNV = extproc;
+
+	glGetVertexAttribdvNV(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribfvNV (GLuint index, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribfvNV = extproc;
+
+	glGetVertexAttribfvNV(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribivNV (GLuint index, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribivNV = extproc;
+
+	glGetVertexAttribivNV(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribPointervNV (GLuint index, GLenum pname, GLvoid* *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribPointervNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribPointervNV = extproc;
+
+	glGetVertexAttribPointervNV(index, pname, pointer);
+}
+
+static GLboolean APIENTRY InitIsProgramNV (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsProgramNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsProgramNV = extproc;
+
+	return glIsProgramNV(id);
+}
+
+static void APIENTRY InitLoadProgramNV (GLenum target, GLuint id, GLsizei len, const GLubyte *program)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glLoadProgramNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glLoadProgramNV = extproc;
+
+	glLoadProgramNV(target, id, len, program);
+}
+
+static void APIENTRY InitProgramParameter4dNV (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramParameter4dNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramParameter4dNV = extproc;
+
+	glProgramParameter4dNV(target, index, x, y, z, w);
+}
+
+static void APIENTRY InitProgramParameter4dvNV (GLenum target, GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramParameter4dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramParameter4dvNV = extproc;
+
+	glProgramParameter4dvNV(target, index, v);
+}
+
+static void APIENTRY InitProgramParameter4fNV (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramParameter4fNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramParameter4fNV = extproc;
+
+	glProgramParameter4fNV(target, index, x, y, z, w);
+}
+
+static void APIENTRY InitProgramParameter4fvNV (GLenum target, GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramParameter4fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramParameter4fvNV = extproc;
+
+	glProgramParameter4fvNV(target, index, v);
+}
+
+static void APIENTRY InitProgramParameters4dvNV (GLenum target, GLuint index, GLuint count, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramParameters4dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramParameters4dvNV = extproc;
+
+	glProgramParameters4dvNV(target, index, count, v);
+}
+
+static void APIENTRY InitProgramParameters4fvNV (GLenum target, GLuint index, GLuint count, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramParameters4fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramParameters4fvNV = extproc;
+
+	glProgramParameters4fvNV(target, index, count, v);
+}
+
+static void APIENTRY InitRequestResidentProgramsNV (GLsizei n, const GLuint *programs)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glRequestResidentProgramsNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glRequestResidentProgramsNV = extproc;
+
+	glRequestResidentProgramsNV(n, programs);
+}
+
+static void APIENTRY InitTrackMatrixNV (GLenum target, GLuint address, GLenum matrix, GLenum transform)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTrackMatrixNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTrackMatrixNV = extproc;
+
+	glTrackMatrixNV(target, address, matrix, transform);
+}
+
+static void APIENTRY InitVertexAttribPointerNV (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribPointerNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribPointerNV = extproc;
+
+	glVertexAttribPointerNV(index, fsize, type, stride, pointer);
+}
+
+static void APIENTRY InitVertexAttrib1dNV (GLuint index, GLdouble x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1dNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1dNV = extproc;
+
+	glVertexAttrib1dNV(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1dvNV (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1dvNV = extproc;
+
+	glVertexAttrib1dvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib1fNV (GLuint index, GLfloat x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1fNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1fNV = extproc;
+
+	glVertexAttrib1fNV(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1fvNV (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1fvNV = extproc;
+
+	glVertexAttrib1fvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib1sNV (GLuint index, GLshort x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1sNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1sNV = extproc;
+
+	glVertexAttrib1sNV(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1svNV (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1svNV = extproc;
+
+	glVertexAttrib1svNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2dNV (GLuint index, GLdouble x, GLdouble y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2dNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2dNV = extproc;
+
+	glVertexAttrib2dNV(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2dvNV (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2dvNV = extproc;
+
+	glVertexAttrib2dvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2fNV (GLuint index, GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2fNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2fNV = extproc;
+
+	glVertexAttrib2fNV(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2fvNV (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2fvNV = extproc;
+
+	glVertexAttrib2fvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2sNV (GLuint index, GLshort x, GLshort y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2sNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2sNV = extproc;
+
+	glVertexAttrib2sNV(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2svNV (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2svNV = extproc;
+
+	glVertexAttrib2svNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3dNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3dNV = extproc;
+
+	glVertexAttrib3dNV(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3dvNV (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3dvNV = extproc;
+
+	glVertexAttrib3dvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3fNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3fNV = extproc;
+
+	glVertexAttrib3fNV(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3fvNV (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3fvNV = extproc;
+
+	glVertexAttrib3fvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3sNV (GLuint index, GLshort x, GLshort y, GLshort z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3sNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3sNV = extproc;
+
+	glVertexAttrib3sNV(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3svNV (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3svNV = extproc;
+
+	glVertexAttrib3svNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4dNV (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4dNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4dNV = extproc;
+
+	glVertexAttrib4dNV(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4dvNV (GLuint index, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4dvNV = extproc;
+
+	glVertexAttrib4dvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4fNV (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4fNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4fNV = extproc;
+
+	glVertexAttrib4fNV(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4fvNV (GLuint index, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4fvNV = extproc;
+
+	glVertexAttrib4fvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4sNV (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4sNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4sNV = extproc;
+
+	glVertexAttrib4sNV(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4svNV (GLuint index, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4svNV = extproc;
+
+	glVertexAttrib4svNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4ubNV (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4ubNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4ubNV = extproc;
+
+	glVertexAttrib4ubNV(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4ubvNV (GLuint index, const GLubyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4ubvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4ubvNV = extproc;
+
+	glVertexAttrib4ubvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttribs1dvNV (GLuint index, GLsizei count, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs1dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs1dvNV = extproc;
+
+	glVertexAttribs1dvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs1fvNV (GLuint index, GLsizei count, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs1fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs1fvNV = extproc;
+
+	glVertexAttribs1fvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs1svNV (GLuint index, GLsizei count, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs1svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs1svNV = extproc;
+
+	glVertexAttribs1svNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs2dvNV (GLuint index, GLsizei count, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs2dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs2dvNV = extproc;
+
+	glVertexAttribs2dvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs2fvNV (GLuint index, GLsizei count, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs2fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs2fvNV = extproc;
+
+	glVertexAttribs2fvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs2svNV (GLuint index, GLsizei count, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs2svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs2svNV = extproc;
+
+	glVertexAttribs2svNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs3dvNV (GLuint index, GLsizei count, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs3dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs3dvNV = extproc;
+
+	glVertexAttribs3dvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs3fvNV (GLuint index, GLsizei count, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs3fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs3fvNV = extproc;
+
+	glVertexAttribs3fvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs3svNV (GLuint index, GLsizei count, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs3svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs3svNV = extproc;
+
+	glVertexAttribs3svNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs4dvNV (GLuint index, GLsizei count, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs4dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs4dvNV = extproc;
+
+	glVertexAttribs4dvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs4fvNV (GLuint index, GLsizei count, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs4fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs4fvNV = extproc;
+
+	glVertexAttribs4fvNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs4svNV (GLuint index, GLsizei count, const GLshort *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs4svNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs4svNV = extproc;
+
+	glVertexAttribs4svNV(index, count, v);
+}
+
+static void APIENTRY InitVertexAttribs4ubvNV (GLuint index, GLsizei count, const GLubyte *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs4ubvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs4ubvNV = extproc;
+
+	glVertexAttribs4ubvNV(index, count, v);
+}
+
+static void APIENTRY InitTexBumpParameterivATI (GLenum pname, const GLint *param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexBumpParameterivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexBumpParameterivATI = extproc;
+
+	glTexBumpParameterivATI(pname, param);
+}
+
+static void APIENTRY InitTexBumpParameterfvATI (GLenum pname, const GLfloat *param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexBumpParameterfvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexBumpParameterfvATI = extproc;
+
+	glTexBumpParameterfvATI(pname, param);
+}
+
+static void APIENTRY InitGetTexBumpParameterivATI (GLenum pname, GLint *param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetTexBumpParameterivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetTexBumpParameterivATI = extproc;
+
+	glGetTexBumpParameterivATI(pname, param);
+}
+
+static void APIENTRY InitGetTexBumpParameterfvATI (GLenum pname, GLfloat *param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetTexBumpParameterfvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetTexBumpParameterfvATI = extproc;
+
+	glGetTexBumpParameterfvATI(pname, param);
+}
+
+static GLuint APIENTRY InitGenFragmentShadersATI (GLuint range)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenFragmentShadersATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGenFragmentShadersATI = extproc;
+
+	return glGenFragmentShadersATI(range);
+}
+
+static void APIENTRY InitBindFragmentShaderATI (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindFragmentShaderATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindFragmentShaderATI = extproc;
+
+	glBindFragmentShaderATI(id);
+}
+
+static void APIENTRY InitDeleteFragmentShaderATI (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteFragmentShaderATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteFragmentShaderATI = extproc;
+
+	glDeleteFragmentShaderATI(id);
+}
+
+static void APIENTRY InitBeginFragmentShaderATI (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBeginFragmentShaderATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBeginFragmentShaderATI = extproc;
+
+	glBeginFragmentShaderATI();
+}
+
+static void APIENTRY InitEndFragmentShaderATI (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEndFragmentShaderATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEndFragmentShaderATI = extproc;
+
+	glEndFragmentShaderATI();
+}
+
+static void APIENTRY InitPassTexCoordATI (GLuint dst, GLuint coord, GLenum swizzle)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPassTexCoordATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPassTexCoordATI = extproc;
+
+	glPassTexCoordATI(dst, coord, swizzle);
+}
+
+static void APIENTRY InitSampleMapATI (GLuint dst, GLuint interp, GLenum swizzle)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSampleMapATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSampleMapATI = extproc;
+
+	glSampleMapATI(dst, interp, swizzle);
+}
+
+static void APIENTRY InitColorFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorFragmentOp1ATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorFragmentOp1ATI = extproc;
+
+	glColorFragmentOp1ATI(op, dst, dstMask, dstMod, arg1, arg1Rep, arg1Mod);
+}
+
+static void APIENTRY InitColorFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorFragmentOp2ATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorFragmentOp2ATI = extproc;
+
+	glColorFragmentOp2ATI(op, dst, dstMask, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod);
+}
+
+static void APIENTRY InitColorFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColorFragmentOp3ATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColorFragmentOp3ATI = extproc;
+
+	glColorFragmentOp3ATI(op, dst, dstMask, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod, arg3, arg3Rep, arg3Mod);
+}
+
+static void APIENTRY InitAlphaFragmentOp1ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAlphaFragmentOp1ATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glAlphaFragmentOp1ATI = extproc;
+
+	glAlphaFragmentOp1ATI(op, dst, dstMod, arg1, arg1Rep, arg1Mod);
+}
+
+static void APIENTRY InitAlphaFragmentOp2ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAlphaFragmentOp2ATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glAlphaFragmentOp2ATI = extproc;
+
+	glAlphaFragmentOp2ATI(op, dst, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod);
+}
+
+static void APIENTRY InitAlphaFragmentOp3ATI (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAlphaFragmentOp3ATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glAlphaFragmentOp3ATI = extproc;
+
+	glAlphaFragmentOp3ATI(op, dst, dstMod, arg1, arg1Rep, arg1Mod, arg2, arg2Rep, arg2Mod, arg3, arg3Rep, arg3Mod);
+}
+
+static void APIENTRY InitSetFragmentShaderConstantATI (GLuint dst, const GLfloat *value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSetFragmentShaderConstantATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSetFragmentShaderConstantATI = extproc;
+
+	glSetFragmentShaderConstantATI(dst, value);
+}
+
+static void APIENTRY InitPNTrianglesiATI (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPNTrianglesiATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPNTrianglesiATI = extproc;
+
+	glPNTrianglesiATI(pname, param);
+}
+
+static void APIENTRY InitPNTrianglesfATI (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPNTrianglesfATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPNTrianglesfATI = extproc;
+
+	glPNTrianglesfATI(pname, param);
+}
+
+static GLuint APIENTRY InitNewObjectBufferATI (GLsizei size, const GLvoid *pointer, GLenum usage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNewObjectBufferATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glNewObjectBufferATI = extproc;
+
+	return glNewObjectBufferATI(size, pointer, usage);
+}
+
+static GLboolean APIENTRY InitIsObjectBufferATI (GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsObjectBufferATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsObjectBufferATI = extproc;
+
+	return glIsObjectBufferATI(buffer);
+}
+
+static void APIENTRY InitUpdateObjectBufferATI (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUpdateObjectBufferATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUpdateObjectBufferATI = extproc;
+
+	glUpdateObjectBufferATI(buffer, offset, size, pointer, preserve);
+}
+
+static void APIENTRY InitGetObjectBufferfvATI (GLuint buffer, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetObjectBufferfvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetObjectBufferfvATI = extproc;
+
+	glGetObjectBufferfvATI(buffer, pname, params);
+}
+
+static void APIENTRY InitGetObjectBufferivATI (GLuint buffer, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetObjectBufferivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetObjectBufferivATI = extproc;
+
+	glGetObjectBufferivATI(buffer, pname, params);
+}
+
+static void APIENTRY InitFreeObjectBufferATI (GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFreeObjectBufferATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFreeObjectBufferATI = extproc;
+
+	glFreeObjectBufferATI(buffer);
+}
+
+static void APIENTRY InitArrayObjectATI (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glArrayObjectATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glArrayObjectATI = extproc;
+
+	glArrayObjectATI(array, size, type, stride, buffer, offset);
+}
+
+static void APIENTRY InitGetArrayObjectfvATI (GLenum array, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetArrayObjectfvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetArrayObjectfvATI = extproc;
+
+	glGetArrayObjectfvATI(array, pname, params);
+}
+
+static void APIENTRY InitGetArrayObjectivATI (GLenum array, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetArrayObjectivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetArrayObjectivATI = extproc;
+
+	glGetArrayObjectivATI(array, pname, params);
+}
+
+static void APIENTRY InitVariantArrayObjectATI (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantArrayObjectATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantArrayObjectATI = extproc;
+
+	glVariantArrayObjectATI(id, type, stride, buffer, offset);
+}
+
+static void APIENTRY InitGetVariantArrayObjectfvATI (GLuint id, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVariantArrayObjectfvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVariantArrayObjectfvATI = extproc;
+
+	glGetVariantArrayObjectfvATI(id, pname, params);
+}
+
+static void APIENTRY InitGetVariantArrayObjectivATI (GLuint id, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVariantArrayObjectivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVariantArrayObjectivATI = extproc;
+
+	glGetVariantArrayObjectivATI(id, pname, params);
+}
+
+static void APIENTRY InitBeginVertexShaderEXT (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBeginVertexShaderEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBeginVertexShaderEXT = extproc;
+
+	glBeginVertexShaderEXT();
+}
+
+static void APIENTRY InitEndVertexShaderEXT (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEndVertexShaderEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEndVertexShaderEXT = extproc;
+
+	glEndVertexShaderEXT();
+}
+
+static void APIENTRY InitBindVertexShaderEXT (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindVertexShaderEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindVertexShaderEXT = extproc;
+
+	glBindVertexShaderEXT(id);
+}
+
+static GLuint APIENTRY InitGenVertexShadersEXT (GLuint range)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenVertexShadersEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGenVertexShadersEXT = extproc;
+
+	return glGenVertexShadersEXT(range);
+}
+
+static void APIENTRY InitDeleteVertexShaderEXT (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteVertexShaderEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteVertexShaderEXT = extproc;
+
+	glDeleteVertexShaderEXT(id);
+}
+
+static void APIENTRY InitShaderOp1EXT (GLenum op, GLuint res, GLuint arg1)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glShaderOp1EXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glShaderOp1EXT = extproc;
+
+	glShaderOp1EXT(op, res, arg1);
+}
+
+static void APIENTRY InitShaderOp2EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glShaderOp2EXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glShaderOp2EXT = extproc;
+
+	glShaderOp2EXT(op, res, arg1, arg2);
+}
+
+static void APIENTRY InitShaderOp3EXT (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glShaderOp3EXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glShaderOp3EXT = extproc;
+
+	glShaderOp3EXT(op, res, arg1, arg2, arg3);
+}
+
+static void APIENTRY InitSwizzleEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSwizzleEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSwizzleEXT = extproc;
+
+	glSwizzleEXT(res, in, outX, outY, outZ, outW);
+}
+
+static void APIENTRY InitWriteMaskEXT (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glWriteMaskEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glWriteMaskEXT = extproc;
+
+	glWriteMaskEXT(res, in, outX, outY, outZ, outW);
+}
+
+static void APIENTRY InitInsertComponentEXT (GLuint res, GLuint src, GLuint num)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glInsertComponentEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glInsertComponentEXT = extproc;
+
+	glInsertComponentEXT(res, src, num);
+}
+
+static void APIENTRY InitExtractComponentEXT (GLuint res, GLuint src, GLuint num)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glExtractComponentEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glExtractComponentEXT = extproc;
+
+	glExtractComponentEXT(res, src, num);
+}
+
+static GLuint APIENTRY InitGenSymbolsEXT (GLenum datatype, GLenum storagetype, GLenum range, GLuint components)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenSymbolsEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glGenSymbolsEXT = extproc;
+
+	return glGenSymbolsEXT(datatype, storagetype, range, components);
+}
+
+static void APIENTRY InitSetInvariantEXT (GLuint id, GLenum type, const GLvoid *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSetInvariantEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSetInvariantEXT = extproc;
+
+	glSetInvariantEXT(id, type, addr);
+}
+
+static void APIENTRY InitSetLocalConstantEXT (GLuint id, GLenum type, const GLvoid *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSetLocalConstantEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSetLocalConstantEXT = extproc;
+
+	glSetLocalConstantEXT(id, type, addr);
+}
+
+static void APIENTRY InitVariantbvEXT (GLuint id, const GLbyte *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantbvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantbvEXT = extproc;
+
+	glVariantbvEXT(id, addr);
+}
+
+static void APIENTRY InitVariantsvEXT (GLuint id, const GLshort *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantsvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantsvEXT = extproc;
+
+	glVariantsvEXT(id, addr);
+}
+
+static void APIENTRY InitVariantivEXT (GLuint id, const GLint *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantivEXT = extproc;
+
+	glVariantivEXT(id, addr);
+}
+
+static void APIENTRY InitVariantfvEXT (GLuint id, const GLfloat *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantfvEXT = extproc;
+
+	glVariantfvEXT(id, addr);
+}
+
+static void APIENTRY InitVariantdvEXT (GLuint id, const GLdouble *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantdvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantdvEXT = extproc;
+
+	glVariantdvEXT(id, addr);
+}
+
+static void APIENTRY InitVariantubvEXT (GLuint id, const GLubyte *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantubvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantubvEXT = extproc;
+
+	glVariantubvEXT(id, addr);
+}
+
+static void APIENTRY InitVariantusvEXT (GLuint id, const GLushort *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantusvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantusvEXT = extproc;
+
+	glVariantusvEXT(id, addr);
+}
+
+static void APIENTRY InitVariantuivEXT (GLuint id, const GLuint *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantuivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantuivEXT = extproc;
+
+	glVariantuivEXT(id, addr);
+}
+
+static void APIENTRY InitVariantPointerEXT (GLuint id, GLenum type, GLuint stride, const GLvoid *addr)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVariantPointerEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVariantPointerEXT = extproc;
+
+	glVariantPointerEXT(id, type, stride, addr);
+}
+
+static void APIENTRY InitEnableVariantClientStateEXT (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEnableVariantClientStateEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEnableVariantClientStateEXT = extproc;
+
+	glEnableVariantClientStateEXT(id);
+}
+
+static void APIENTRY InitDisableVariantClientStateEXT (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDisableVariantClientStateEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDisableVariantClientStateEXT = extproc;
+
+	glDisableVariantClientStateEXT(id);
+}
+
+static GLuint APIENTRY InitBindLightParameterEXT (GLenum light, GLenum value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindLightParameterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glBindLightParameterEXT = extproc;
+
+	return glBindLightParameterEXT(light, value);
+}
+
+static GLuint APIENTRY InitBindMaterialParameterEXT (GLenum face, GLenum value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindMaterialParameterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glBindMaterialParameterEXT = extproc;
+
+	return glBindMaterialParameterEXT(face, value);
+}
+
+static GLuint APIENTRY InitBindTexGenParameterEXT (GLenum unit, GLenum coord, GLenum value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindTexGenParameterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glBindTexGenParameterEXT = extproc;
+
+	return glBindTexGenParameterEXT(unit, coord, value);
+}
+
+static GLuint APIENTRY InitBindTextureUnitParameterEXT (GLenum unit, GLenum value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindTextureUnitParameterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glBindTextureUnitParameterEXT = extproc;
+
+	return glBindTextureUnitParameterEXT(unit, value);
+}
+
+static GLuint APIENTRY InitBindParameterEXT (GLenum value)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindParameterEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glBindParameterEXT = extproc;
+
+	return glBindParameterEXT(value);
+}
+
+static GLboolean APIENTRY InitIsVariantEnabledEXT (GLuint id, GLenum cap)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsVariantEnabledEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsVariantEnabledEXT = extproc;
+
+	return glIsVariantEnabledEXT(id, cap);
+}
+
+static void APIENTRY InitGetVariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVariantBooleanvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVariantBooleanvEXT = extproc;
+
+	glGetVariantBooleanvEXT(id, value, data);
+}
+
+static void APIENTRY InitGetVariantIntegervEXT (GLuint id, GLenum value, GLint *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVariantIntegervEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVariantIntegervEXT = extproc;
+
+	glGetVariantIntegervEXT(id, value, data);
+}
+
+static void APIENTRY InitGetVariantFloatvEXT (GLuint id, GLenum value, GLfloat *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVariantFloatvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVariantFloatvEXT = extproc;
+
+	glGetVariantFloatvEXT(id, value, data);
+}
+
+static void APIENTRY InitGetVariantPointervEXT (GLuint id, GLenum value, GLvoid* *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVariantPointervEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVariantPointervEXT = extproc;
+
+	glGetVariantPointervEXT(id, value, data);
+}
+
+static void APIENTRY InitGetInvariantBooleanvEXT (GLuint id, GLenum value, GLboolean *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetInvariantBooleanvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetInvariantBooleanvEXT = extproc;
+
+	glGetInvariantBooleanvEXT(id, value, data);
+}
+
+static void APIENTRY InitGetInvariantIntegervEXT (GLuint id, GLenum value, GLint *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetInvariantIntegervEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetInvariantIntegervEXT = extproc;
+
+	glGetInvariantIntegervEXT(id, value, data);
+}
+
+static void APIENTRY InitGetInvariantFloatvEXT (GLuint id, GLenum value, GLfloat *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetInvariantFloatvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetInvariantFloatvEXT = extproc;
+
+	glGetInvariantFloatvEXT(id, value, data);
+}
+
+static void APIENTRY InitGetLocalConstantBooleanvEXT (GLuint id, GLenum value, GLboolean *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetLocalConstantBooleanvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetLocalConstantBooleanvEXT = extproc;
+
+	glGetLocalConstantBooleanvEXT(id, value, data);
+}
+
+static void APIENTRY InitGetLocalConstantIntegervEXT (GLuint id, GLenum value, GLint *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetLocalConstantIntegervEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetLocalConstantIntegervEXT = extproc;
+
+	glGetLocalConstantIntegervEXT(id, value, data);
+}
+
+static void APIENTRY InitGetLocalConstantFloatvEXT (GLuint id, GLenum value, GLfloat *data)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetLocalConstantFloatvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetLocalConstantFloatvEXT = extproc;
+
+	glGetLocalConstantFloatvEXT(id, value, data);
+}
+
+static void APIENTRY InitVertexStream1sATI (GLenum stream, GLshort x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1sATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1sATI = extproc;
+
+	glVertexStream1sATI(stream, x);
+}
+
+static void APIENTRY InitVertexStream1svATI (GLenum stream, const GLshort *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1svATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1svATI = extproc;
+
+	glVertexStream1svATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream1iATI (GLenum stream, GLint x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1iATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1iATI = extproc;
+
+	glVertexStream1iATI(stream, x);
+}
+
+static void APIENTRY InitVertexStream1ivATI (GLenum stream, const GLint *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1ivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1ivATI = extproc;
+
+	glVertexStream1ivATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream1fATI (GLenum stream, GLfloat x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1fATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1fATI = extproc;
+
+	glVertexStream1fATI(stream, x);
+}
+
+static void APIENTRY InitVertexStream1fvATI (GLenum stream, const GLfloat *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1fvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1fvATI = extproc;
+
+	glVertexStream1fvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream1dATI (GLenum stream, GLdouble x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1dATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1dATI = extproc;
+
+	glVertexStream1dATI(stream, x);
+}
+
+static void APIENTRY InitVertexStream1dvATI (GLenum stream, const GLdouble *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream1dvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream1dvATI = extproc;
+
+	glVertexStream1dvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream2sATI (GLenum stream, GLshort x, GLshort y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2sATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2sATI = extproc;
+
+	glVertexStream2sATI(stream, x, y);
+}
+
+static void APIENTRY InitVertexStream2svATI (GLenum stream, const GLshort *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2svATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2svATI = extproc;
+
+	glVertexStream2svATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream2iATI (GLenum stream, GLint x, GLint y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2iATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2iATI = extproc;
+
+	glVertexStream2iATI(stream, x, y);
+}
+
+static void APIENTRY InitVertexStream2ivATI (GLenum stream, const GLint *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2ivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2ivATI = extproc;
+
+	glVertexStream2ivATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream2fATI (GLenum stream, GLfloat x, GLfloat y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2fATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2fATI = extproc;
+
+	glVertexStream2fATI(stream, x, y);
+}
+
+static void APIENTRY InitVertexStream2fvATI (GLenum stream, const GLfloat *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2fvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2fvATI = extproc;
+
+	glVertexStream2fvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream2dATI (GLenum stream, GLdouble x, GLdouble y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2dATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2dATI = extproc;
+
+	glVertexStream2dATI(stream, x, y);
+}
+
+static void APIENTRY InitVertexStream2dvATI (GLenum stream, const GLdouble *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream2dvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream2dvATI = extproc;
+
+	glVertexStream2dvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream3sATI (GLenum stream, GLshort x, GLshort y, GLshort z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3sATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3sATI = extproc;
+
+	glVertexStream3sATI(stream, x, y, z);
+}
+
+static void APIENTRY InitVertexStream3svATI (GLenum stream, const GLshort *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3svATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3svATI = extproc;
+
+	glVertexStream3svATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream3iATI (GLenum stream, GLint x, GLint y, GLint z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3iATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3iATI = extproc;
+
+	glVertexStream3iATI(stream, x, y, z);
+}
+
+static void APIENTRY InitVertexStream3ivATI (GLenum stream, const GLint *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3ivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3ivATI = extproc;
+
+	glVertexStream3ivATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream3fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3fATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3fATI = extproc;
+
+	glVertexStream3fATI(stream, x, y, z);
+}
+
+static void APIENTRY InitVertexStream3fvATI (GLenum stream, const GLfloat *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3fvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3fvATI = extproc;
+
+	glVertexStream3fvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream3dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3dATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3dATI = extproc;
+
+	glVertexStream3dATI(stream, x, y, z);
+}
+
+static void APIENTRY InitVertexStream3dvATI (GLenum stream, const GLdouble *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream3dvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream3dvATI = extproc;
+
+	glVertexStream3dvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream4sATI (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4sATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4sATI = extproc;
+
+	glVertexStream4sATI(stream, x, y, z, w);
+}
+
+static void APIENTRY InitVertexStream4svATI (GLenum stream, const GLshort *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4svATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4svATI = extproc;
+
+	glVertexStream4svATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream4iATI (GLenum stream, GLint x, GLint y, GLint z, GLint w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4iATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4iATI = extproc;
+
+	glVertexStream4iATI(stream, x, y, z, w);
+}
+
+static void APIENTRY InitVertexStream4ivATI (GLenum stream, const GLint *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4ivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4ivATI = extproc;
+
+	glVertexStream4ivATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream4fATI (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4fATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4fATI = extproc;
+
+	glVertexStream4fATI(stream, x, y, z, w);
+}
+
+static void APIENTRY InitVertexStream4fvATI (GLenum stream, const GLfloat *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4fvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4fvATI = extproc;
+
+	glVertexStream4fvATI(stream, coords);
+}
+
+static void APIENTRY InitVertexStream4dATI (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4dATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4dATI = extproc;
+
+	glVertexStream4dATI(stream, x, y, z, w);
+}
+
+static void APIENTRY InitVertexStream4dvATI (GLenum stream, const GLdouble *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexStream4dvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexStream4dvATI = extproc;
+
+	glVertexStream4dvATI(stream, coords);
+}
+
+static void APIENTRY InitNormalStream3bATI (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3bATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3bATI = extproc;
+
+	glNormalStream3bATI(stream, nx, ny, nz);
+}
+
+static void APIENTRY InitNormalStream3bvATI (GLenum stream, const GLbyte *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3bvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3bvATI = extproc;
+
+	glNormalStream3bvATI(stream, coords);
+}
+
+static void APIENTRY InitNormalStream3sATI (GLenum stream, GLshort nx, GLshort ny, GLshort nz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3sATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3sATI = extproc;
+
+	glNormalStream3sATI(stream, nx, ny, nz);
+}
+
+static void APIENTRY InitNormalStream3svATI (GLenum stream, const GLshort *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3svATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3svATI = extproc;
+
+	glNormalStream3svATI(stream, coords);
+}
+
+static void APIENTRY InitNormalStream3iATI (GLenum stream, GLint nx, GLint ny, GLint nz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3iATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3iATI = extproc;
+
+	glNormalStream3iATI(stream, nx, ny, nz);
+}
+
+static void APIENTRY InitNormalStream3ivATI (GLenum stream, const GLint *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3ivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3ivATI = extproc;
+
+	glNormalStream3ivATI(stream, coords);
+}
+
+static void APIENTRY InitNormalStream3fATI (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3fATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3fATI = extproc;
+
+	glNormalStream3fATI(stream, nx, ny, nz);
+}
+
+static void APIENTRY InitNormalStream3fvATI (GLenum stream, const GLfloat *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3fvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3fvATI = extproc;
+
+	glNormalStream3fvATI(stream, coords);
+}
+
+static void APIENTRY InitNormalStream3dATI (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3dATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3dATI = extproc;
+
+	glNormalStream3dATI(stream, nx, ny, nz);
+}
+
+static void APIENTRY InitNormalStream3dvATI (GLenum stream, const GLdouble *coords)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormalStream3dvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormalStream3dvATI = extproc;
+
+	glNormalStream3dvATI(stream, coords);
+}
+
+static void APIENTRY InitClientActiveVertexStreamATI (GLenum stream)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glClientActiveVertexStreamATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glClientActiveVertexStreamATI = extproc;
+
+	glClientActiveVertexStreamATI(stream);
+}
+
+static void APIENTRY InitVertexBlendEnviATI (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexBlendEnviATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexBlendEnviATI = extproc;
+
+	glVertexBlendEnviATI(pname, param);
+}
+
+static void APIENTRY InitVertexBlendEnvfATI (GLenum pname, GLfloat param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexBlendEnvfATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexBlendEnvfATI = extproc;
+
+	glVertexBlendEnvfATI(pname, param);
+}
+
+static void APIENTRY InitElementPointerATI (GLenum type, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glElementPointerATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glElementPointerATI = extproc;
+
+	glElementPointerATI(type, pointer);
+}
+
+static void APIENTRY InitDrawElementArrayATI (GLenum mode, GLsizei count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawElementArrayATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawElementArrayATI = extproc;
+
+	glDrawElementArrayATI(mode, count);
+}
+
+static void APIENTRY InitDrawRangeElementArrayATI (GLenum mode, GLuint start, GLuint end, GLsizei count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawRangeElementArrayATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawRangeElementArrayATI = extproc;
+
+	glDrawRangeElementArrayATI(mode, start, end, count);
+}
+
+static void APIENTRY InitDrawMeshArraysSUN (GLenum mode, GLint first, GLsizei count, GLsizei width)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawMeshArraysSUN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawMeshArraysSUN = extproc;
+
+	glDrawMeshArraysSUN(mode, first, count, width);
+}
+
+static void APIENTRY InitGenOcclusionQueriesNV (GLsizei n, GLuint *ids)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenOcclusionQueriesNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenOcclusionQueriesNV = extproc;
+
+	glGenOcclusionQueriesNV(n, ids);
+}
+
+static void APIENTRY InitDeleteOcclusionQueriesNV (GLsizei n, const GLuint *ids)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteOcclusionQueriesNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteOcclusionQueriesNV = extproc;
+
+	glDeleteOcclusionQueriesNV(n, ids);
+}
+
+static GLboolean APIENTRY InitIsOcclusionQueryNV (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsOcclusionQueryNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsOcclusionQueryNV = extproc;
+
+	return glIsOcclusionQueryNV(id);
+}
+
+static void APIENTRY InitBeginOcclusionQueryNV (GLuint id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBeginOcclusionQueryNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBeginOcclusionQueryNV = extproc;
+
+	glBeginOcclusionQueryNV(id);
+}
+
+static void APIENTRY InitEndOcclusionQueryNV (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glEndOcclusionQueryNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glEndOcclusionQueryNV = extproc;
+
+	glEndOcclusionQueryNV();
+}
+
+static void APIENTRY InitGetOcclusionQueryivNV (GLuint id, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetOcclusionQueryivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetOcclusionQueryivNV = extproc;
+
+	glGetOcclusionQueryivNV(id, pname, params);
+}
+
+static void APIENTRY InitGetOcclusionQueryuivNV (GLuint id, GLenum pname, GLuint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetOcclusionQueryuivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetOcclusionQueryuivNV = extproc;
+
+	glGetOcclusionQueryuivNV(id, pname, params);
+}
+
+static void APIENTRY InitPointParameteriNV (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameteriNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameteriNV = extproc;
+
+	glPointParameteriNV(pname, param);
+}
+
+static void APIENTRY InitPointParameterivNV (GLenum pname, const GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPointParameterivNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPointParameterivNV = extproc;
+
+	glPointParameterivNV(pname, params);
+}
+
+static void APIENTRY InitActiveStencilFaceEXT (GLenum face)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glActiveStencilFaceEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glActiveStencilFaceEXT = extproc;
+
+	glActiveStencilFaceEXT(face);
+}
+
+static void APIENTRY InitElementPointerAPPLE (GLenum type, const GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glElementPointerAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glElementPointerAPPLE = extproc;
+
+	glElementPointerAPPLE(type, pointer);
+}
+
+static void APIENTRY InitDrawElementArrayAPPLE (GLenum mode, GLint first, GLsizei count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawElementArrayAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawElementArrayAPPLE = extproc;
+
+	glDrawElementArrayAPPLE(mode, first, count);
+}
+
+static void APIENTRY InitDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawRangeElementArrayAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawRangeElementArrayAPPLE = extproc;
+
+	glDrawRangeElementArrayAPPLE(mode, start, end, first, count);
+}
+
+static void APIENTRY InitMultiDrawElementArrayAPPLE (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiDrawElementArrayAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiDrawElementArrayAPPLE = extproc;
+
+	glMultiDrawElementArrayAPPLE(mode, first, count, primcount);
+}
+
+static void APIENTRY InitMultiDrawRangeElementArrayAPPLE (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiDrawRangeElementArrayAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiDrawRangeElementArrayAPPLE = extproc;
+
+	glMultiDrawRangeElementArrayAPPLE(mode, start, end, first, count, primcount);
+}
+
+static void APIENTRY InitGenFencesAPPLE (GLsizei n, GLuint *fences)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenFencesAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenFencesAPPLE = extproc;
+
+	glGenFencesAPPLE(n, fences);
+}
+
+static void APIENTRY InitDeleteFencesAPPLE (GLsizei n, const GLuint *fences)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteFencesAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteFencesAPPLE = extproc;
+
+	glDeleteFencesAPPLE(n, fences);
+}
+
+static void APIENTRY InitSetFenceAPPLE (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSetFenceAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSetFenceAPPLE = extproc;
+
+	glSetFenceAPPLE(fence);
+}
+
+static GLboolean APIENTRY InitIsFenceAPPLE (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsFenceAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsFenceAPPLE = extproc;
+
+	return glIsFenceAPPLE(fence);
+}
+
+static GLboolean APIENTRY InitTestFenceAPPLE (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTestFenceAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glTestFenceAPPLE = extproc;
+
+	return glTestFenceAPPLE(fence);
+}
+
+static void APIENTRY InitFinishFenceAPPLE (GLuint fence)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFinishFenceAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFinishFenceAPPLE = extproc;
+
+	glFinishFenceAPPLE(fence);
+}
+
+static GLboolean APIENTRY InitTestObjectAPPLE (GLenum object, GLuint name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTestObjectAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glTestObjectAPPLE = extproc;
+
+	return glTestObjectAPPLE(object, name);
+}
+
+static void APIENTRY InitFinishObjectAPPLE (GLenum object, GLint name)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFinishObjectAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFinishObjectAPPLE = extproc;
+
+	glFinishObjectAPPLE(object, name);
+}
+
+static void APIENTRY InitBindVertexArrayAPPLE (GLuint array)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBindVertexArrayAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBindVertexArrayAPPLE = extproc;
+
+	glBindVertexArrayAPPLE(array);
+}
+
+static void APIENTRY InitDeleteVertexArraysAPPLE (GLsizei n, const GLuint *arrays)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDeleteVertexArraysAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDeleteVertexArraysAPPLE = extproc;
+
+	glDeleteVertexArraysAPPLE(n, arrays);
+}
+
+static void APIENTRY InitGenVertexArraysAPPLE (GLsizei n, const GLuint *arrays)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGenVertexArraysAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGenVertexArraysAPPLE = extproc;
+
+	glGenVertexArraysAPPLE(n, arrays);
+}
+
+static GLboolean APIENTRY InitIsVertexArrayAPPLE (GLuint array)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glIsVertexArrayAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glIsVertexArrayAPPLE = extproc;
+
+	return glIsVertexArrayAPPLE(array);
+}
+
+static void APIENTRY InitVertexArrayRangeAPPLE (GLsizei length, GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexArrayRangeAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexArrayRangeAPPLE = extproc;
+
+	glVertexArrayRangeAPPLE(length, pointer);
+}
+
+static void APIENTRY InitFlushVertexArrayRangeAPPLE (GLsizei length, GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFlushVertexArrayRangeAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFlushVertexArrayRangeAPPLE = extproc;
+
+	glFlushVertexArrayRangeAPPLE(length, pointer);
+}
+
+static void APIENTRY InitVertexArrayParameteriAPPLE (GLenum pname, GLint param)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexArrayParameteriAPPLE");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexArrayParameteriAPPLE = extproc;
+
+	glVertexArrayParameteriAPPLE(pname, param);
+}
+
+static void APIENTRY InitDrawBuffersATI (GLsizei n, const GLenum *bufs)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDrawBuffersATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDrawBuffersATI = extproc;
+
+	glDrawBuffersATI(n, bufs);
+}
+
+static void APIENTRY InitProgramNamedParameter4fNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramNamedParameter4fNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramNamedParameter4fNV = extproc;
+
+	glProgramNamedParameter4fNV(id, len, name, x, y, z, w);
+}
+
+static void APIENTRY InitProgramNamedParameter4dNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramNamedParameter4dNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramNamedParameter4dNV = extproc;
+
+	glProgramNamedParameter4dNV(id, len, name, x, y, z, w);
+}
+
+static void APIENTRY InitProgramNamedParameter4fvNV (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramNamedParameter4fvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramNamedParameter4fvNV = extproc;
+
+	glProgramNamedParameter4fvNV(id, len, name, v);
+}
+
+static void APIENTRY InitProgramNamedParameter4dvNV (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glProgramNamedParameter4dvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glProgramNamedParameter4dvNV = extproc;
+
+	glProgramNamedParameter4dvNV(id, len, name, v);
+}
+
+static void APIENTRY InitGetProgramNamedParameterfvNV (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramNamedParameterfvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramNamedParameterfvNV = extproc;
+
+	glGetProgramNamedParameterfvNV(id, len, name, params);
+}
+
+static void APIENTRY InitGetProgramNamedParameterdvNV (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetProgramNamedParameterdvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetProgramNamedParameterdvNV = extproc;
+
+	glGetProgramNamedParameterdvNV(id, len, name, params);
+}
+
+static void APIENTRY InitVertex2hNV (GLhalfNV x, GLhalfNV y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertex2hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertex2hNV = extproc;
+
+	glVertex2hNV(x, y);
+}
+
+static void APIENTRY InitVertex2hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertex2hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertex2hvNV = extproc;
+
+	glVertex2hvNV(v);
+}
+
+static void APIENTRY InitVertex3hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertex3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertex3hNV = extproc;
+
+	glVertex3hNV(x, y, z);
+}
+
+static void APIENTRY InitVertex3hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertex3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertex3hvNV = extproc;
+
+	glVertex3hvNV(v);
+}
+
+static void APIENTRY InitVertex4hNV (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertex4hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertex4hNV = extproc;
+
+	glVertex4hNV(x, y, z, w);
+}
+
+static void APIENTRY InitVertex4hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertex4hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertex4hvNV = extproc;
+
+	glVertex4hvNV(v);
+}
+
+static void APIENTRY InitNormal3hNV (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormal3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormal3hNV = extproc;
+
+	glNormal3hNV(nx, ny, nz);
+}
+
+static void APIENTRY InitNormal3hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glNormal3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glNormal3hvNV = extproc;
+
+	glNormal3hvNV(v);
+}
+
+static void APIENTRY InitColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor3hNV = extproc;
+
+	glColor3hNV(red, green, blue);
+}
+
+static void APIENTRY InitColor3hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor3hvNV = extproc;
+
+	glColor3hvNV(v);
+}
+
+static void APIENTRY InitColor4hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4hNV = extproc;
+
+	glColor4hNV(red, green, blue, alpha);
+}
+
+static void APIENTRY InitColor4hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glColor4hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glColor4hvNV = extproc;
+
+	glColor4hvNV(v);
+}
+
+static void APIENTRY InitTexCoord1hNV (GLhalfNV s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord1hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord1hNV = extproc;
+
+	glTexCoord1hNV(s);
+}
+
+static void APIENTRY InitTexCoord1hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord1hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord1hvNV = extproc;
+
+	glTexCoord1hvNV(v);
+}
+
+static void APIENTRY InitTexCoord2hNV (GLhalfNV s, GLhalfNV t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2hNV = extproc;
+
+	glTexCoord2hNV(s, t);
+}
+
+static void APIENTRY InitTexCoord2hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord2hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord2hvNV = extproc;
+
+	glTexCoord2hvNV(v);
+}
+
+static void APIENTRY InitTexCoord3hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord3hNV = extproc;
+
+	glTexCoord3hNV(s, t, r);
+}
+
+static void APIENTRY InitTexCoord3hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord3hvNV = extproc;
+
+	glTexCoord3hvNV(v);
+}
+
+static void APIENTRY InitTexCoord4hNV (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord4hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord4hNV = extproc;
+
+	glTexCoord4hNV(s, t, r, q);
+}
+
+static void APIENTRY InitTexCoord4hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glTexCoord4hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glTexCoord4hvNV = extproc;
+
+	glTexCoord4hvNV(v);
+}
+
+static void APIENTRY InitMultiTexCoord1hNV (GLenum target, GLhalfNV s)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1hNV = extproc;
+
+	glMultiTexCoord1hNV(target, s);
+}
+
+static void APIENTRY InitMultiTexCoord1hvNV (GLenum target, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord1hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord1hvNV = extproc;
+
+	glMultiTexCoord1hvNV(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord2hNV (GLenum target, GLhalfNV s, GLhalfNV t)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2hNV = extproc;
+
+	glMultiTexCoord2hNV(target, s, t);
+}
+
+static void APIENTRY InitMultiTexCoord2hvNV (GLenum target, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord2hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord2hvNV = extproc;
+
+	glMultiTexCoord2hvNV(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord3hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3hNV = extproc;
+
+	glMultiTexCoord3hNV(target, s, t, r);
+}
+
+static void APIENTRY InitMultiTexCoord3hvNV (GLenum target, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord3hvNV = extproc;
+
+	glMultiTexCoord3hvNV(target, v);
+}
+
+static void APIENTRY InitMultiTexCoord4hNV (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4hNV = extproc;
+
+	glMultiTexCoord4hNV(target, s, t, r, q);
+}
+
+static void APIENTRY InitMultiTexCoord4hvNV (GLenum target, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMultiTexCoord4hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glMultiTexCoord4hvNV = extproc;
+
+	glMultiTexCoord4hvNV(target, v);
+}
+
+static void APIENTRY InitFogCoordhNV (GLhalfNV fog)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordhNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordhNV = extproc;
+
+	glFogCoordhNV(fog);
+}
+
+static void APIENTRY InitFogCoordhvNV (const GLhalfNV *fog)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFogCoordhvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFogCoordhvNV = extproc;
+
+	glFogCoordhvNV(fog);
+}
+
+static void APIENTRY InitSecondaryColor3hNV (GLhalfNV red, GLhalfNV green, GLhalfNV blue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3hNV = extproc;
+
+	glSecondaryColor3hNV(red, green, blue);
+}
+
+static void APIENTRY InitSecondaryColor3hvNV (const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glSecondaryColor3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glSecondaryColor3hvNV = extproc;
+
+	glSecondaryColor3hvNV(v);
+}
+
+static void APIENTRY InitVertexWeighthNV (GLhalfNV weight)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexWeighthNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexWeighthNV = extproc;
+
+	glVertexWeighthNV(weight);
+}
+
+static void APIENTRY InitVertexWeighthvNV (const GLhalfNV *weight)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexWeighthvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexWeighthvNV = extproc;
+
+	glVertexWeighthvNV(weight);
+}
+
+static void APIENTRY InitVertexAttrib1hNV (GLuint index, GLhalfNV x)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1hNV = extproc;
+
+	glVertexAttrib1hNV(index, x);
+}
+
+static void APIENTRY InitVertexAttrib1hvNV (GLuint index, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib1hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib1hvNV = extproc;
+
+	glVertexAttrib1hvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib2hNV (GLuint index, GLhalfNV x, GLhalfNV y)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2hNV = extproc;
+
+	glVertexAttrib2hNV(index, x, y);
+}
+
+static void APIENTRY InitVertexAttrib2hvNV (GLuint index, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib2hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib2hvNV = extproc;
+
+	glVertexAttrib2hvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib3hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3hNV = extproc;
+
+	glVertexAttrib3hNV(index, x, y, z);
+}
+
+static void APIENTRY InitVertexAttrib3hvNV (GLuint index, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib3hvNV = extproc;
+
+	glVertexAttrib3hvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttrib4hNV (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4hNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4hNV = extproc;
+
+	glVertexAttrib4hNV(index, x, y, z, w);
+}
+
+static void APIENTRY InitVertexAttrib4hvNV (GLuint index, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttrib4hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttrib4hvNV = extproc;
+
+	glVertexAttrib4hvNV(index, v);
+}
+
+static void APIENTRY InitVertexAttribs1hvNV (GLuint index, GLsizei n, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs1hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs1hvNV = extproc;
+
+	glVertexAttribs1hvNV(index, n, v);
+}
+
+static void APIENTRY InitVertexAttribs2hvNV (GLuint index, GLsizei n, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs2hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs2hvNV = extproc;
+
+	glVertexAttribs2hvNV(index, n, v);
+}
+
+static void APIENTRY InitVertexAttribs3hvNV (GLuint index, GLsizei n, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs3hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs3hvNV = extproc;
+
+	glVertexAttribs3hvNV(index, n, v);
+}
+
+static void APIENTRY InitVertexAttribs4hvNV (GLuint index, GLsizei n, const GLhalfNV *v)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribs4hvNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribs4hvNV = extproc;
+
+	glVertexAttribs4hvNV(index, n, v);
+}
+
+static void APIENTRY InitPixelDataRangeNV (GLenum target, GLsizei length, GLvoid *pointer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPixelDataRangeNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPixelDataRangeNV = extproc;
+
+	glPixelDataRangeNV(target, length, pointer);
+}
+
+static void APIENTRY InitFlushPixelDataRangeNV (GLenum target)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glFlushPixelDataRangeNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glFlushPixelDataRangeNV = extproc;
+
+	glFlushPixelDataRangeNV(target);
+}
+
+static void APIENTRY InitPrimitiveRestartNV (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPrimitiveRestartNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPrimitiveRestartNV = extproc;
+
+	glPrimitiveRestartNV();
+}
+
+static void APIENTRY InitPrimitiveRestartIndexNV (GLuint index)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glPrimitiveRestartIndexNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glPrimitiveRestartIndexNV = extproc;
+
+	glPrimitiveRestartIndexNV(index);
+}
+
+static GLvoid* APIENTRY InitMapObjectBufferATI (GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glMapObjectBufferATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	glMapObjectBufferATI = extproc;
+
+	return glMapObjectBufferATI(buffer);
+}
+
+static void APIENTRY InitUnmapObjectBufferATI (GLuint buffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glUnmapObjectBufferATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glUnmapObjectBufferATI = extproc;
+
+	glUnmapObjectBufferATI(buffer);
+}
+
+static void APIENTRY InitStencilOpSeparateATI (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glStencilOpSeparateATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glStencilOpSeparateATI = extproc;
+
+	glStencilOpSeparateATI(face, sfail, dpfail, dppass);
+}
+
+static void APIENTRY InitStencilFuncSeparateATI (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glStencilFuncSeparateATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glStencilFuncSeparateATI = extproc;
+
+	glStencilFuncSeparateATI(frontfunc, backfunc, ref, mask);
+}
+
+static void APIENTRY InitVertexAttribArrayObjectATI (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glVertexAttribArrayObjectATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glVertexAttribArrayObjectATI = extproc;
+
+	glVertexAttribArrayObjectATI(index, size, type, normalized, stride, buffer, offset);
+}
+
+static void APIENTRY InitGetVertexAttribArrayObjectfvATI (GLuint index, GLenum pname, GLfloat *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribArrayObjectfvATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribArrayObjectfvATI = extproc;
+
+	glGetVertexAttribArrayObjectfvATI(index, pname, params);
+}
+
+static void APIENTRY InitGetVertexAttribArrayObjectivATI (GLuint index, GLenum pname, GLint *params)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glGetVertexAttribArrayObjectivATI");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glGetVertexAttribArrayObjectivATI = extproc;
+
+	glGetVertexAttribArrayObjectivATI(index, pname, params);
+}
+
+static void APIENTRY InitDepthBoundsEXT (GLclampd zmin, GLclampd zmax)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glDepthBoundsEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glDepthBoundsEXT = extproc;
+
+	glDepthBoundsEXT(zmin, zmax);
+}
+
+static void APIENTRY InitBlendEquationSeparateEXT (GLenum modeRGB, GLenum modeAlpha)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glBlendEquationSeparateEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glBlendEquationSeparateEXT = extproc;
+
+	glBlendEquationSeparateEXT(modeRGB, modeAlpha);
+}
+
+static void APIENTRY InitAddSwapHintRectWIN (GLint x, GLint y, GLsizei width, GLsizei height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("glAddSwapHintRectWIN");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	glAddSwapHintRectWIN = extproc;
+
+	glAddSwapHintRectWIN(x, y, width, height);
+}
+
+#ifdef _WIN32
+
+static HANDLE WINAPI InitCreateBufferRegionARB (HDC hDC, int iLayerPlane, UINT uType)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglCreateBufferRegionARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglCreateBufferRegionARB = extproc;
+
+	return wglCreateBufferRegionARB(hDC, iLayerPlane, uType);
+}
+
+static VOID WINAPI InitDeleteBufferRegionARB (HANDLE hRegion)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDeleteBufferRegionARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	wglDeleteBufferRegionARB = extproc;
+
+	wglDeleteBufferRegionARB(hRegion);
+}
+
+static BOOL WINAPI InitSaveBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSaveBufferRegionARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSaveBufferRegionARB = extproc;
+
+	return wglSaveBufferRegionARB(hRegion, x, y, width, height);
+}
+
+static BOOL WINAPI InitRestoreBufferRegionARB (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglRestoreBufferRegionARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglRestoreBufferRegionARB = extproc;
+
+	return wglRestoreBufferRegionARB(hRegion, x, y, width, height, xSrc, ySrc);
+}
+
+static const WINAPI InitGetExtensionsStringARB (HDC hdc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetExtensionsStringARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetExtensionsStringARB = extproc;
+
+	return wglGetExtensionsStringARB(hdc);
+}
+
+static BOOL WINAPI InitGetPixelFormatAttribivARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetPixelFormatAttribivARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetPixelFormatAttribivARB = extproc;
+
+	return wglGetPixelFormatAttribivARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
+}
+
+static BOOL WINAPI InitGetPixelFormatAttribfvARB (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetPixelFormatAttribfvARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetPixelFormatAttribfvARB = extproc;
+
+	return wglGetPixelFormatAttribfvARB(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
+}
+
+static BOOL WINAPI InitChoosePixelFormatARB (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglChoosePixelFormatARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglChoosePixelFormatARB = extproc;
+
+	return wglChoosePixelFormatARB(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
+}
+
+static BOOL WINAPI InitMakeContextCurrentARB (HDC hDrawDC, HDC hReadDC, HGLRC hglrc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglMakeContextCurrentARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglMakeContextCurrentARB = extproc;
+
+	return wglMakeContextCurrentARB(hDrawDC, hReadDC, hglrc);
+}
+
+static HDC WINAPI InitGetCurrentReadDCARB (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetCurrentReadDCARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetCurrentReadDCARB = extproc;
+
+	return wglGetCurrentReadDCARB();
+}
+
+static HPBUFFERARB WINAPI InitCreatePbufferARB (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglCreatePbufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglCreatePbufferARB = extproc;
+
+	return wglCreatePbufferARB(hDC, iPixelFormat, iWidth, iHeight, piAttribList);
+}
+
+static HDC WINAPI InitGetPbufferDCARB (HPBUFFERARB hPbuffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetPbufferDCARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetPbufferDCARB = extproc;
+
+	return wglGetPbufferDCARB(hPbuffer);
+}
+
+static int WINAPI InitReleasePbufferDCARB (HPBUFFERARB hPbuffer, HDC hDC)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglReleasePbufferDCARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglReleasePbufferDCARB = extproc;
+
+	return wglReleasePbufferDCARB(hPbuffer, hDC);
+}
+
+static BOOL WINAPI InitDestroyPbufferARB (HPBUFFERARB hPbuffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDestroyPbufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglDestroyPbufferARB = extproc;
+
+	return wglDestroyPbufferARB(hPbuffer);
+}
+
+static BOOL WINAPI InitQueryPbufferARB (HPBUFFERARB hPbuffer, int iAttribute, int *piValue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglQueryPbufferARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglQueryPbufferARB = extproc;
+
+	return wglQueryPbufferARB(hPbuffer, iAttribute, piValue);
+}
+
+static BOOL WINAPI InitBindTexImageARB (HPBUFFERARB hPbuffer, int iBuffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglBindTexImageARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglBindTexImageARB = extproc;
+
+	return wglBindTexImageARB(hPbuffer, iBuffer);
+}
+
+static BOOL WINAPI InitReleaseTexImageARB (HPBUFFERARB hPbuffer, int iBuffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglReleaseTexImageARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglReleaseTexImageARB = extproc;
+
+	return wglReleaseTexImageARB(hPbuffer, iBuffer);
+}
+
+static BOOL WINAPI InitSetPbufferAttribARB (HPBUFFERARB hPbuffer, const int *piAttribList)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSetPbufferAttribARB");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSetPbufferAttribARB = extproc;
+
+	return wglSetPbufferAttribARB(hPbuffer, piAttribList);
+}
+
+static GLboolean WINAPI InitCreateDisplayColorTableEXT (GLushort id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglCreateDisplayColorTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglCreateDisplayColorTableEXT = extproc;
+
+	return wglCreateDisplayColorTableEXT(id);
+}
+
+static GLboolean WINAPI InitLoadDisplayColorTableEXT (const GLushort *table, GLuint length)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglLoadDisplayColorTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglLoadDisplayColorTableEXT = extproc;
+
+	return wglLoadDisplayColorTableEXT(table, length);
+}
+
+static GLboolean WINAPI InitBindDisplayColorTableEXT (GLushort id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglBindDisplayColorTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglBindDisplayColorTableEXT = extproc;
+
+	return wglBindDisplayColorTableEXT(id);
+}
+
+static VOID WINAPI InitDestroyDisplayColorTableEXT (GLushort id)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDestroyDisplayColorTableEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	wglDestroyDisplayColorTableEXT = extproc;
+
+	wglDestroyDisplayColorTableEXT(id);
+}
+
+static const WINAPI InitGetExtensionsStringEXT (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetExtensionsStringEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetExtensionsStringEXT = extproc;
+
+	return wglGetExtensionsStringEXT();
+}
+
+static BOOL WINAPI InitMakeContextCurrentEXT (HDC hDrawDC, HDC hReadDC, HGLRC hglrc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglMakeContextCurrentEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglMakeContextCurrentEXT = extproc;
+
+	return wglMakeContextCurrentEXT(hDrawDC, hReadDC, hglrc);
+}
+
+static HDC WINAPI InitGetCurrentReadDCEXT (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetCurrentReadDCEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetCurrentReadDCEXT = extproc;
+
+	return wglGetCurrentReadDCEXT();
+}
+
+static HPBUFFEREXT WINAPI InitCreatePbufferEXT (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglCreatePbufferEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglCreatePbufferEXT = extproc;
+
+	return wglCreatePbufferEXT(hDC, iPixelFormat, iWidth, iHeight, piAttribList);
+}
+
+static HDC WINAPI InitGetPbufferDCEXT (HPBUFFEREXT hPbuffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetPbufferDCEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetPbufferDCEXT = extproc;
+
+	return wglGetPbufferDCEXT(hPbuffer);
+}
+
+static int WINAPI InitReleasePbufferDCEXT (HPBUFFEREXT hPbuffer, HDC hDC)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglReleasePbufferDCEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglReleasePbufferDCEXT = extproc;
+
+	return wglReleasePbufferDCEXT(hPbuffer, hDC);
+}
+
+static BOOL WINAPI InitDestroyPbufferEXT (HPBUFFEREXT hPbuffer)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDestroyPbufferEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglDestroyPbufferEXT = extproc;
+
+	return wglDestroyPbufferEXT(hPbuffer);
+}
+
+static BOOL WINAPI InitQueryPbufferEXT (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglQueryPbufferEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglQueryPbufferEXT = extproc;
+
+	return wglQueryPbufferEXT(hPbuffer, iAttribute, piValue);
+}
+
+static BOOL WINAPI InitGetPixelFormatAttribivEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetPixelFormatAttribivEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetPixelFormatAttribivEXT = extproc;
+
+	return wglGetPixelFormatAttribivEXT(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, piValues);
+}
+
+static BOOL WINAPI InitGetPixelFormatAttribfvEXT (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetPixelFormatAttribfvEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetPixelFormatAttribfvEXT = extproc;
+
+	return wglGetPixelFormatAttribfvEXT(hdc, iPixelFormat, iLayerPlane, nAttributes, piAttributes, pfValues);
+}
+
+static BOOL WINAPI InitChoosePixelFormatEXT (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglChoosePixelFormatEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglChoosePixelFormatEXT = extproc;
+
+	return wglChoosePixelFormatEXT(hdc, piAttribIList, pfAttribFList, nMaxFormats, piFormats, nNumFormats);
+}
+
+static BOOL WINAPI InitSwapIntervalEXT (int interval)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSwapIntervalEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSwapIntervalEXT = extproc;
+
+	return wglSwapIntervalEXT(interval);
+}
+
+static int WINAPI InitGetSwapIntervalEXT (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetSwapIntervalEXT");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetSwapIntervalEXT = extproc;
+
+	return wglGetSwapIntervalEXT();
+}
+
+static void* WINAPI InitAllocateMemoryNV (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglAllocateMemoryNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglAllocateMemoryNV = extproc;
+
+	return wglAllocateMemoryNV(size, readfreq, writefreq, priority);
+}
+
+static void WINAPI InitFreeMemoryNV (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglFreeMemoryNV");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return;
+	}
+
+	wglFreeMemoryNV = extproc;
+
+	wglFreeMemoryNV();
+}
+
+static BOOL WINAPI InitGetSyncValuesOML (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetSyncValuesOML");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetSyncValuesOML = extproc;
+
+	return wglGetSyncValuesOML(hdc, ust, msc, sbc);
+}
+
+static BOOL WINAPI InitGetMscRateOML (HDC hdc, INT32 *numerator, INT32 *denominator)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetMscRateOML");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetMscRateOML = extproc;
+
+	return wglGetMscRateOML(hdc, numerator, denominator);
+}
+
+static INT64 WINAPI InitSwapBuffersMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSwapBuffersMscOML");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSwapBuffersMscOML = extproc;
+
+	return wglSwapBuffersMscOML(hdc, target_msc, divisor, remainder);
+}
+
+static INT64 WINAPI InitSwapLayerBuffersMscOML (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSwapLayerBuffersMscOML");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSwapLayerBuffersMscOML = extproc;
+
+	return wglSwapLayerBuffersMscOML(hdc, fuPlanes, target_msc, divisor, remainder);
+}
+
+static BOOL WINAPI InitWaitForMscOML (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglWaitForMscOML");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglWaitForMscOML = extproc;
+
+	return wglWaitForMscOML(hdc, target_msc, divisor, remainder, ust, msc, sbc);
+}
+
+static BOOL WINAPI InitWaitForSbcOML (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglWaitForSbcOML");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglWaitForSbcOML = extproc;
+
+	return wglWaitForSbcOML(hdc, target_sbc, ust, msc, sbc);
+}
+
+static BOOL WINAPI InitGetDigitalVideoParametersI3D (HDC hDC, int iAttribute, int *piValue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetDigitalVideoParametersI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetDigitalVideoParametersI3D = extproc;
+
+	return wglGetDigitalVideoParametersI3D(hDC, iAttribute, piValue);
+}
+
+static BOOL WINAPI InitSetDigitalVideoParametersI3D (HDC hDC, int iAttribute, const int *piValue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSetDigitalVideoParametersI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSetDigitalVideoParametersI3D = extproc;
+
+	return wglSetDigitalVideoParametersI3D(hDC, iAttribute, piValue);
+}
+
+static BOOL WINAPI InitGetGammaTableParametersI3D (HDC hDC, int iAttribute, int *piValue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetGammaTableParametersI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetGammaTableParametersI3D = extproc;
+
+	return wglGetGammaTableParametersI3D(hDC, iAttribute, piValue);
+}
+
+static BOOL WINAPI InitSetGammaTableParametersI3D (HDC hDC, int iAttribute, const int *piValue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSetGammaTableParametersI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSetGammaTableParametersI3D = extproc;
+
+	return wglSetGammaTableParametersI3D(hDC, iAttribute, piValue);
+}
+
+static BOOL WINAPI InitGetGammaTableI3D (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetGammaTableI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetGammaTableI3D = extproc;
+
+	return wglGetGammaTableI3D(hDC, iEntries, puRed, puGreen, puBlue);
+}
+
+static BOOL WINAPI InitSetGammaTableI3D (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglSetGammaTableI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglSetGammaTableI3D = extproc;
+
+	return wglSetGammaTableI3D(hDC, iEntries, puRed, puGreen, puBlue);
+}
+
+static BOOL WINAPI InitEnableGenlockI3D (HDC hDC)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglEnableGenlockI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglEnableGenlockI3D = extproc;
+
+	return wglEnableGenlockI3D(hDC);
+}
+
+static BOOL WINAPI InitDisableGenlockI3D (HDC hDC)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDisableGenlockI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglDisableGenlockI3D = extproc;
+
+	return wglDisableGenlockI3D(hDC);
+}
+
+static BOOL WINAPI InitIsEnabledGenlockI3D (HDC hDC, BOOL *pFlag)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglIsEnabledGenlockI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglIsEnabledGenlockI3D = extproc;
+
+	return wglIsEnabledGenlockI3D(hDC, pFlag);
+}
+
+static BOOL WINAPI InitGenlockSourceI3D (HDC hDC, UINT uSource)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGenlockSourceI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGenlockSourceI3D = extproc;
+
+	return wglGenlockSourceI3D(hDC, uSource);
+}
+
+static BOOL WINAPI InitGetGenlockSourceI3D (HDC hDC, UINT *uSource)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetGenlockSourceI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetGenlockSourceI3D = extproc;
+
+	return wglGetGenlockSourceI3D(hDC, uSource);
+}
+
+static BOOL WINAPI InitGenlockSourceEdgeI3D (HDC hDC, UINT uEdge)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGenlockSourceEdgeI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGenlockSourceEdgeI3D = extproc;
+
+	return wglGenlockSourceEdgeI3D(hDC, uEdge);
+}
+
+static BOOL WINAPI InitGetGenlockSourceEdgeI3D (HDC hDC, UINT *uEdge)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetGenlockSourceEdgeI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetGenlockSourceEdgeI3D = extproc;
+
+	return wglGetGenlockSourceEdgeI3D(hDC, uEdge);
+}
+
+static BOOL WINAPI InitGenlockSampleRateI3D (HDC hDC, UINT uRate)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGenlockSampleRateI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGenlockSampleRateI3D = extproc;
+
+	return wglGenlockSampleRateI3D(hDC, uRate);
+}
+
+static BOOL WINAPI InitGetGenlockSampleRateI3D (HDC hDC, UINT *uRate)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetGenlockSampleRateI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetGenlockSampleRateI3D = extproc;
+
+	return wglGetGenlockSampleRateI3D(hDC, uRate);
+}
+
+static BOOL WINAPI InitGenlockSourceDelayI3D (HDC hDC, UINT uDelay)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGenlockSourceDelayI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGenlockSourceDelayI3D = extproc;
+
+	return wglGenlockSourceDelayI3D(hDC, uDelay);
+}
+
+static BOOL WINAPI InitGetGenlockSourceDelayI3D (HDC hDC, UINT *uDelay)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetGenlockSourceDelayI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetGenlockSourceDelayI3D = extproc;
+
+	return wglGetGenlockSourceDelayI3D(hDC, uDelay);
+}
+
+static BOOL WINAPI InitQueryGenlockMaxSourceDelayI3D (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglQueryGenlockMaxSourceDelayI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglQueryGenlockMaxSourceDelayI3D = extproc;
+
+	return wglQueryGenlockMaxSourceDelayI3D(hDC, uMaxLineDelay, uMaxPixelDelay);
+}
+
+static LPVOID WINAPI InitCreateImageBufferI3D (HDC hDC, DWORD dwSize, UINT uFlags)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglCreateImageBufferI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglCreateImageBufferI3D = extproc;
+
+	return wglCreateImageBufferI3D(hDC, dwSize, uFlags);
+}
+
+static BOOL WINAPI InitDestroyImageBufferI3D (HDC hDC, LPVOID pAddress)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDestroyImageBufferI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglDestroyImageBufferI3D = extproc;
+
+	return wglDestroyImageBufferI3D(hDC, pAddress);
+}
+
+static BOOL WINAPI InitAssociateImageBufferEventsI3D (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglAssociateImageBufferEventsI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglAssociateImageBufferEventsI3D = extproc;
+
+	return wglAssociateImageBufferEventsI3D(hDC, pEvent, pAddress, pSize, count);
+}
+
+static BOOL WINAPI InitReleaseImageBufferEventsI3D (HDC hDC, const LPVOID *pAddress, UINT count)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglReleaseImageBufferEventsI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglReleaseImageBufferEventsI3D = extproc;
+
+	return wglReleaseImageBufferEventsI3D(hDC, pAddress, count);
+}
+
+static BOOL WINAPI InitEnableFrameLockI3D (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglEnableFrameLockI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglEnableFrameLockI3D = extproc;
+
+	return wglEnableFrameLockI3D();
+}
+
+static BOOL WINAPI InitDisableFrameLockI3D (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglDisableFrameLockI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglDisableFrameLockI3D = extproc;
+
+	return wglDisableFrameLockI3D();
+}
+
+static BOOL WINAPI InitIsEnabledFrameLockI3D (BOOL *pFlag)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglIsEnabledFrameLockI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglIsEnabledFrameLockI3D = extproc;
+
+	return wglIsEnabledFrameLockI3D(pFlag);
+}
+
+static BOOL WINAPI InitQueryFrameLockMasterI3D (BOOL *pFlag)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglQueryFrameLockMasterI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglQueryFrameLockMasterI3D = extproc;
+
+	return wglQueryFrameLockMasterI3D(pFlag);
+}
+
+static BOOL WINAPI InitGetFrameUsageI3D (float *pUsage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglGetFrameUsageI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglGetFrameUsageI3D = extproc;
+
+	return wglGetFrameUsageI3D(pUsage);
+}
+
+static BOOL WINAPI InitBeginFrameTrackingI3D (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglBeginFrameTrackingI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglBeginFrameTrackingI3D = extproc;
+
+	return wglBeginFrameTrackingI3D();
+}
+
+static BOOL WINAPI InitEndFrameTrackingI3D (void)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglEndFrameTrackingI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglEndFrameTrackingI3D = extproc;
+
+	return wglEndFrameTrackingI3D();
+}
+
+static BOOL WINAPI InitQueryFrameTrackingI3D (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage)
+{
+	void *extproc;
+
+	extproc = (void *) wglGetProcAddress("wglQueryFrameTrackingI3D");
+
+	if (extproc == NULL) {
+		_ASSERT(0);
+		return 0;
+	}
+
+	wglQueryFrameTrackingI3D = extproc;
+
+	return wglQueryFrameTrackingI3D(pFrameCount, pMissedFrames, pLastMissedUsage);
+}
+
+#endif /* _WIN32 */
+
+_GLextensionProcs _extensionProcs = {
+	InitBlendColor,
+	InitBlendEquation,
+	InitDrawRangeElements,
+	InitColorTable,
+	InitColorTableParameterfv,
+	InitColorTableParameteriv,
+	InitCopyColorTable,
+	InitGetColorTable,
+	InitGetColorTableParameterfv,
+	InitGetColorTableParameteriv,
+	InitColorSubTable,
+	InitCopyColorSubTable,
+	InitConvolutionFilter1D,
+	InitConvolutionFilter2D,
+	InitConvolutionParameterf,
+	InitConvolutionParameterfv,
+	InitConvolutionParameteri,
+	InitConvolutionParameteriv,
+	InitCopyConvolutionFilter1D,
+	InitCopyConvolutionFilter2D,
+	InitGetConvolutionFilter,
+	InitGetConvolutionParameterfv,
+	InitGetConvolutionParameteriv,
+	InitGetSeparableFilter,
+	InitSeparableFilter2D,
+	InitGetHistogram,
+	InitGetHistogramParameterfv,
+	InitGetHistogramParameteriv,
+	InitGetMinmax,
+	InitGetMinmaxParameterfv,
+	InitGetMinmaxParameteriv,
+	InitHistogram,
+	InitMinmax,
+	InitResetHistogram,
+	InitResetMinmax,
+	InitTexImage3D,
+	InitTexSubImage3D,
+	InitCopyTexSubImage3D,
+	InitActiveTexture,
+	InitClientActiveTexture,
+	InitMultiTexCoord1d,
+	InitMultiTexCoord1dv,
+	InitMultiTexCoord1f,
+	InitMultiTexCoord1fv,
+	InitMultiTexCoord1i,
+	InitMultiTexCoord1iv,
+	InitMultiTexCoord1s,
+	InitMultiTexCoord1sv,
+	InitMultiTexCoord2d,
+	InitMultiTexCoord2dv,
+	InitMultiTexCoord2f,
+	InitMultiTexCoord2fv,
+	InitMultiTexCoord2i,
+	InitMultiTexCoord2iv,
+	InitMultiTexCoord2s,
+	InitMultiTexCoord2sv,
+	InitMultiTexCoord3d,
+	InitMultiTexCoord3dv,
+	InitMultiTexCoord3f,
+	InitMultiTexCoord3fv,
+	InitMultiTexCoord3i,
+	InitMultiTexCoord3iv,
+	InitMultiTexCoord3s,
+	InitMultiTexCoord3sv,
+	InitMultiTexCoord4d,
+	InitMultiTexCoord4dv,
+	InitMultiTexCoord4f,
+	InitMultiTexCoord4fv,
+	InitMultiTexCoord4i,
+	InitMultiTexCoord4iv,
+	InitMultiTexCoord4s,
+	InitMultiTexCoord4sv,
+	InitLoadTransposeMatrixf,
+	InitLoadTransposeMatrixd,
+	InitMultTransposeMatrixf,
+	InitMultTransposeMatrixd,
+	InitSampleCoverage,
+	InitCompressedTexImage3D,
+	InitCompressedTexImage2D,
+	InitCompressedTexImage1D,
+	InitCompressedTexSubImage3D,
+	InitCompressedTexSubImage2D,
+	InitCompressedTexSubImage1D,
+	InitGetCompressedTexImage,
+	InitBlendFuncSeparate,
+	InitFogCoordf,
+	InitFogCoordfv,
+	InitFogCoordd,
+	InitFogCoorddv,
+	InitFogCoordPointer,
+	InitMultiDrawArrays,
+	InitMultiDrawElements,
+	InitPointParameterf,
+	InitPointParameterfv,
+	InitPointParameteri,
+	InitPointParameteriv,
+	InitSecondaryColor3b,
+	InitSecondaryColor3bv,
+	InitSecondaryColor3d,
+	InitSecondaryColor3dv,
+	InitSecondaryColor3f,
+	InitSecondaryColor3fv,
+	InitSecondaryColor3i,
+	InitSecondaryColor3iv,
+	InitSecondaryColor3s,
+	InitSecondaryColor3sv,
+	InitSecondaryColor3ub,
+	InitSecondaryColor3ubv,
+	InitSecondaryColor3ui,
+	InitSecondaryColor3uiv,
+	InitSecondaryColor3us,
+	InitSecondaryColor3usv,
+	InitSecondaryColorPointer,
+	InitWindowPos2d,
+	InitWindowPos2dv,
+	InitWindowPos2f,
+	InitWindowPos2fv,
+	InitWindowPos2i,
+	InitWindowPos2iv,
+	InitWindowPos2s,
+	InitWindowPos2sv,
+	InitWindowPos3d,
+	InitWindowPos3dv,
+	InitWindowPos3f,
+	InitWindowPos3fv,
+	InitWindowPos3i,
+	InitWindowPos3iv,
+	InitWindowPos3s,
+	InitWindowPos3sv,
+	InitGenQueries,
+	InitDeleteQueries,
+	InitIsQuery,
+	InitBeginQuery,
+	InitEndQuery,
+	InitGetQueryiv,
+	InitGetQueryObjectiv,
+	InitGetQueryObjectuiv,
+	InitBindBuffer,
+	InitDeleteBuffers,
+	InitGenBuffers,
+	InitIsBuffer,
+	InitBufferData,
+	InitBufferSubData,
+	InitGetBufferSubData,
+	InitMapBuffer,
+	InitUnmapBuffer,
+	InitGetBufferParameteriv,
+	InitGetBufferPointerv,
+	InitActiveTextureARB,
+	InitClientActiveTextureARB,
+	InitMultiTexCoord1dARB,
+	InitMultiTexCoord1dvARB,
+	InitMultiTexCoord1fARB,
+	InitMultiTexCoord1fvARB,
+	InitMultiTexCoord1iARB,
+	InitMultiTexCoord1ivARB,
+	InitMultiTexCoord1sARB,
+	InitMultiTexCoord1svARB,
+	InitMultiTexCoord2dARB,
+	InitMultiTexCoord2dvARB,
+	InitMultiTexCoord2fARB,
+	InitMultiTexCoord2fvARB,
+	InitMultiTexCoord2iARB,
+	InitMultiTexCoord2ivARB,
+	InitMultiTexCoord2sARB,
+	InitMultiTexCoord2svARB,
+	InitMultiTexCoord3dARB,
+	InitMultiTexCoord3dvARB,
+	InitMultiTexCoord3fARB,
+	InitMultiTexCoord3fvARB,
+	InitMultiTexCoord3iARB,
+	InitMultiTexCoord3ivARB,
+	InitMultiTexCoord3sARB,
+	InitMultiTexCoord3svARB,
+	InitMultiTexCoord4dARB,
+	InitMultiTexCoord4dvARB,
+	InitMultiTexCoord4fARB,
+	InitMultiTexCoord4fvARB,
+	InitMultiTexCoord4iARB,
+	InitMultiTexCoord4ivARB,
+	InitMultiTexCoord4sARB,
+	InitMultiTexCoord4svARB,
+	InitLoadTransposeMatrixfARB,
+	InitLoadTransposeMatrixdARB,
+	InitMultTransposeMatrixfARB,
+	InitMultTransposeMatrixdARB,
+	InitSampleCoverageARB,
+	InitCompressedTexImage3DARB,
+	InitCompressedTexImage2DARB,
+	InitCompressedTexImage1DARB,
+	InitCompressedTexSubImage3DARB,
+	InitCompressedTexSubImage2DARB,
+	InitCompressedTexSubImage1DARB,
+	InitGetCompressedTexImageARB,
+	InitPointParameterfARB,
+	InitPointParameterfvARB,
+	InitWeightbvARB,
+	InitWeightsvARB,
+	InitWeightivARB,
+	InitWeightfvARB,
+	InitWeightdvARB,
+	InitWeightubvARB,
+	InitWeightusvARB,
+	InitWeightuivARB,
+	InitWeightPointerARB,
+	InitVertexBlendARB,
+	InitCurrentPaletteMatrixARB,
+	InitMatrixIndexubvARB,
+	InitMatrixIndexusvARB,
+	InitMatrixIndexuivARB,
+	InitMatrixIndexPointerARB,
+	InitWindowPos2dARB,
+	InitWindowPos2dvARB,
+	InitWindowPos2fARB,
+	InitWindowPos2fvARB,
+	InitWindowPos2iARB,
+	InitWindowPos2ivARB,
+	InitWindowPos2sARB,
+	InitWindowPos2svARB,
+	InitWindowPos3dARB,
+	InitWindowPos3dvARB,
+	InitWindowPos3fARB,
+	InitWindowPos3fvARB,
+	InitWindowPos3iARB,
+	InitWindowPos3ivARB,
+	InitWindowPos3sARB,
+	InitWindowPos3svARB,
+	InitVertexAttrib1dARB,
+	InitVertexAttrib1dvARB,
+	InitVertexAttrib1fARB,
+	InitVertexAttrib1fvARB,
+	InitVertexAttrib1sARB,
+	InitVertexAttrib1svARB,
+	InitVertexAttrib2dARB,
+	InitVertexAttrib2dvARB,
+	InitVertexAttrib2fARB,
+	InitVertexAttrib2fvARB,
+	InitVertexAttrib2sARB,
+	InitVertexAttrib2svARB,
+	InitVertexAttrib3dARB,
+	InitVertexAttrib3dvARB,
+	InitVertexAttrib3fARB,
+	InitVertexAttrib3fvARB,
+	InitVertexAttrib3sARB,
+	InitVertexAttrib3svARB,
+	InitVertexAttrib4NbvARB,
+	InitVertexAttrib4NivARB,
+	InitVertexAttrib4NsvARB,
+	InitVertexAttrib4NubARB,
+	InitVertexAttrib4NubvARB,
+	InitVertexAttrib4NuivARB,
+	InitVertexAttrib4NusvARB,
+	InitVertexAttrib4bvARB,
+	InitVertexAttrib4dARB,
+	InitVertexAttrib4dvARB,
+	InitVertexAttrib4fARB,
+	InitVertexAttrib4fvARB,
+	InitVertexAttrib4ivARB,
+	InitVertexAttrib4sARB,
+	InitVertexAttrib4svARB,
+	InitVertexAttrib4ubvARB,
+	InitVertexAttrib4uivARB,
+	InitVertexAttrib4usvARB,
+	InitVertexAttribPointerARB,
+	InitEnableVertexAttribArrayARB,
+	InitDisableVertexAttribArrayARB,
+	InitProgramStringARB,
+	InitBindProgramARB,
+	InitDeleteProgramsARB,
+	InitGenProgramsARB,
+	InitProgramEnvParameter4dARB,
+	InitProgramEnvParameter4dvARB,
+	InitProgramEnvParameter4fARB,
+	InitProgramEnvParameter4fvARB,
+	InitProgramLocalParameter4dARB,
+	InitProgramLocalParameter4dvARB,
+	InitProgramLocalParameter4fARB,
+	InitProgramLocalParameter4fvARB,
+	InitGetProgramEnvParameterdvARB,
+	InitGetProgramEnvParameterfvARB,
+	InitGetProgramLocalParameterdvARB,
+	InitGetProgramLocalParameterfvARB,
+	InitGetProgramivARB,
+	InitGetProgramStringARB,
+	InitGetVertexAttribdvARB,
+	InitGetVertexAttribfvARB,
+	InitGetVertexAttribivARB,
+	InitGetVertexAttribPointervARB,
+	InitIsProgramARB,
+	InitBindBufferARB,
+	InitDeleteBuffersARB,
+	InitGenBuffersARB,
+	InitIsBufferARB,
+	InitBufferDataARB,
+	InitBufferSubDataARB,
+	InitGetBufferSubDataARB,
+	InitMapBufferARB,
+	InitUnmapBufferARB,
+	InitGetBufferParameterivARB,
+	InitGetBufferPointervARB,
+	InitGenQueriesARB,
+	InitDeleteQueriesARB,
+	InitIsQueryARB,
+	InitBeginQueryARB,
+	InitEndQueryARB,
+	InitGetQueryivARB,
+	InitGetQueryObjectivARB,
+	InitGetQueryObjectuivARB,
+	InitDeleteObjectARB,
+	InitGetHandleARB,
+	InitDetachObjectARB,
+	InitCreateShaderObjectARB,
+	InitShaderSourceARB,
+	InitCompileShaderARB,
+	InitCreateProgramObjectARB,
+	InitAttachObjectARB,
+	InitLinkProgramARB,
+	InitUseProgramObjectARB,
+	InitValidateProgramARB,
+	InitUniform1fARB,
+	InitUniform2fARB,
+	InitUniform3fARB,
+	InitUniform4fARB,
+	InitUniform1iARB,
+	InitUniform2iARB,
+	InitUniform3iARB,
+	InitUniform4iARB,
+	InitUniform1fvARB,
+	InitUniform2fvARB,
+	InitUniform3fvARB,
+	InitUniform4fvARB,
+	InitUniform1ivARB,
+	InitUniform2ivARB,
+	InitUniform3ivARB,
+	InitUniform4ivARB,
+	InitUniformMatrix2fvARB,
+	InitUniformMatrix3fvARB,
+	InitUniformMatrix4fvARB,
+	InitGetObjectParameterfvARB,
+	InitGetObjectParameterivARB,
+	InitGetInfoLogARB,
+	InitGetAttachedObjectsARB,
+	InitGetUniformLocationARB,
+	InitGetActiveUniformARB,
+	InitGetUniformfvARB,
+	InitGetUniformivARB,
+	InitGetShaderSourceARB,
+	InitBindAttribLocationARB,
+	InitGetActiveAttribARB,
+	InitGetAttribLocationARB,
+	InitBlendColorEXT,
+	InitPolygonOffsetEXT,
+	InitTexImage3DEXT,
+	InitTexSubImage3DEXT,
+	InitGetTexFilterFuncSGIS,
+	InitTexFilterFuncSGIS,
+	InitTexSubImage1DEXT,
+	InitTexSubImage2DEXT,
+	InitCopyTexImage1DEXT,
+	InitCopyTexImage2DEXT,
+	InitCopyTexSubImage1DEXT,
+	InitCopyTexSubImage2DEXT,
+	InitCopyTexSubImage3DEXT,
+	InitGetHistogramEXT,
+	InitGetHistogramParameterfvEXT,
+	InitGetHistogramParameterivEXT,
+	InitGetMinmaxEXT,
+	InitGetMinmaxParameterfvEXT,
+	InitGetMinmaxParameterivEXT,
+	InitHistogramEXT,
+	InitMinmaxEXT,
+	InitResetHistogramEXT,
+	InitResetMinmaxEXT,
+	InitConvolutionFilter1DEXT,
+	InitConvolutionFilter2DEXT,
+	InitConvolutionParameterfEXT,
+	InitConvolutionParameterfvEXT,
+	InitConvolutionParameteriEXT,
+	InitConvolutionParameterivEXT,
+	InitCopyConvolutionFilter1DEXT,
+	InitCopyConvolutionFilter2DEXT,
+	InitGetConvolutionFilterEXT,
+	InitGetConvolutionParameterfvEXT,
+	InitGetConvolutionParameterivEXT,
+	InitGetSeparableFilterEXT,
+	InitSeparableFilter2DEXT,
+	InitColorTableSGI,
+	InitColorTableParameterfvSGI,
+	InitColorTableParameterivSGI,
+	InitCopyColorTableSGI,
+	InitGetColorTableSGI,
+	InitGetColorTableParameterfvSGI,
+	InitGetColorTableParameterivSGI,
+	InitPixelTexGenSGIX,
+	InitPixelTexGenParameteriSGIS,
+	InitPixelTexGenParameterivSGIS,
+	InitPixelTexGenParameterfSGIS,
+	InitPixelTexGenParameterfvSGIS,
+	InitGetPixelTexGenParameterivSGIS,
+	InitGetPixelTexGenParameterfvSGIS,
+	InitTexImage4DSGIS,
+	InitTexSubImage4DSGIS,
+	InitAreTexturesResidentEXT,
+	InitBindTextureEXT,
+	InitDeleteTexturesEXT,
+	InitGenTexturesEXT,
+	InitIsTextureEXT,
+	InitPrioritizeTexturesEXT,
+	InitDetailTexFuncSGIS,
+	InitGetDetailTexFuncSGIS,
+	InitSharpenTexFuncSGIS,
+	InitGetSharpenTexFuncSGIS,
+	InitSampleMaskSGIS,
+	InitSamplePatternSGIS,
+	InitArrayElementEXT,
+	InitColorPointerEXT,
+	InitDrawArraysEXT,
+	InitEdgeFlagPointerEXT,
+	InitGetPointervEXT,
+	InitIndexPointerEXT,
+	InitNormalPointerEXT,
+	InitTexCoordPointerEXT,
+	InitVertexPointerEXT,
+	InitBlendEquationEXT,
+	InitSpriteParameterfSGIX,
+	InitSpriteParameterfvSGIX,
+	InitSpriteParameteriSGIX,
+	InitSpriteParameterivSGIX,
+	InitPointParameterfEXT,
+	InitPointParameterfvEXT,
+	InitPointParameterfSGIS,
+	InitPointParameterfvSGIS,
+	InitGetInstrumentsSGIX,
+	InitInstrumentsBufferSGIX,
+	InitPollInstrumentsSGIX,
+	InitReadInstrumentsSGIX,
+	InitStartInstrumentsSGIX,
+	InitStopInstrumentsSGIX,
+	InitFrameZoomSGIX,
+	InitTagSampleBufferSGIX,
+	InitDeformationMap3dSGIX,
+	InitDeformationMap3fSGIX,
+	InitDeformSGIX,
+	InitLoadIdentityDeformationMapSGIX,
+	InitReferencePlaneSGIX,
+	InitFlushRasterSGIX,
+	InitFogFuncSGIS,
+	InitGetFogFuncSGIS,
+	InitImageTransformParameteriHP,
+	InitImageTransformParameterfHP,
+	InitImageTransformParameterivHP,
+	InitImageTransformParameterfvHP,
+	InitGetImageTransformParameterivHP,
+	InitGetImageTransformParameterfvHP,
+	InitColorSubTableEXT,
+	InitCopyColorSubTableEXT,
+	InitHintPGI,
+	InitColorTableEXT,
+	InitGetColorTableEXT,
+	InitGetColorTableParameterivEXT,
+	InitGetColorTableParameterfvEXT,
+	InitGetListParameterfvSGIX,
+	InitGetListParameterivSGIX,
+	InitListParameterfSGIX,
+	InitListParameterfvSGIX,
+	InitListParameteriSGIX,
+	InitListParameterivSGIX,
+	InitIndexMaterialEXT,
+	InitIndexFuncEXT,
+	InitLockArraysEXT,
+	InitUnlockArraysEXT,
+	InitCullParameterdvEXT,
+	InitCullParameterfvEXT,
+	InitFragmentColorMaterialSGIX,
+	InitFragmentLightfSGIX,
+	InitFragmentLightfvSGIX,
+	InitFragmentLightiSGIX,
+	InitFragmentLightivSGIX,
+	InitFragmentLightModelfSGIX,
+	InitFragmentLightModelfvSGIX,
+	InitFragmentLightModeliSGIX,
+	InitFragmentLightModelivSGIX,
+	InitFragmentMaterialfSGIX,
+	InitFragmentMaterialfvSGIX,
+	InitFragmentMaterialiSGIX,
+	InitFragmentMaterialivSGIX,
+	InitGetFragmentLightfvSGIX,
+	InitGetFragmentLightivSGIX,
+	InitGetFragmentMaterialfvSGIX,
+	InitGetFragmentMaterialivSGIX,
+	InitLightEnviSGIX,
+	InitDrawRangeElementsEXT,
+	InitApplyTextureEXT,
+	InitTextureLightEXT,
+	InitTextureMaterialEXT,
+	InitAsyncMarkerSGIX,
+	InitFinishAsyncSGIX,
+	InitPollAsyncSGIX,
+	InitGenAsyncMarkersSGIX,
+	InitDeleteAsyncMarkersSGIX,
+	InitIsAsyncMarkerSGIX,
+	InitVertexPointervINTEL,
+	InitNormalPointervINTEL,
+	InitColorPointervINTEL,
+	InitTexCoordPointervINTEL,
+	InitPixelTransformParameteriEXT,
+	InitPixelTransformParameterfEXT,
+	InitPixelTransformParameterivEXT,
+	InitPixelTransformParameterfvEXT,
+	InitSecondaryColor3bEXT,
+	InitSecondaryColor3bvEXT,
+	InitSecondaryColor3dEXT,
+	InitSecondaryColor3dvEXT,
+	InitSecondaryColor3fEXT,
+	InitSecondaryColor3fvEXT,
+	InitSecondaryColor3iEXT,
+	InitSecondaryColor3ivEXT,
+	InitSecondaryColor3sEXT,
+	InitSecondaryColor3svEXT,
+	InitSecondaryColor3ubEXT,
+	InitSecondaryColor3ubvEXT,
+	InitSecondaryColor3uiEXT,
+	InitSecondaryColor3uivEXT,
+	InitSecondaryColor3usEXT,
+	InitSecondaryColor3usvEXT,
+	InitSecondaryColorPointerEXT,
+	InitTextureNormalEXT,
+	InitMultiDrawArraysEXT,
+	InitMultiDrawElementsEXT,
+	InitFogCoordfEXT,
+	InitFogCoordfvEXT,
+	InitFogCoorddEXT,
+	InitFogCoorddvEXT,
+	InitFogCoordPointerEXT,
+	InitTangent3bEXT,
+	InitTangent3bvEXT,
+	InitTangent3dEXT,
+	InitTangent3dvEXT,
+	InitTangent3fEXT,
+	InitTangent3fvEXT,
+	InitTangent3iEXT,
+	InitTangent3ivEXT,
+	InitTangent3sEXT,
+	InitTangent3svEXT,
+	InitBinormal3bEXT,
+	InitBinormal3bvEXT,
+	InitBinormal3dEXT,
+	InitBinormal3dvEXT,
+	InitBinormal3fEXT,
+	InitBinormal3fvEXT,
+	InitBinormal3iEXT,
+	InitBinormal3ivEXT,
+	InitBinormal3sEXT,
+	InitBinormal3svEXT,
+	InitTangentPointerEXT,
+	InitBinormalPointerEXT,
+	InitFinishTextureSUNX,
+	InitGlobalAlphaFactorbSUN,
+	InitGlobalAlphaFactorsSUN,
+	InitGlobalAlphaFactoriSUN,
+	InitGlobalAlphaFactorfSUN,
+	InitGlobalAlphaFactordSUN,
+	InitGlobalAlphaFactorubSUN,
+	InitGlobalAlphaFactorusSUN,
+	InitGlobalAlphaFactoruiSUN,
+	InitReplacementCodeuiSUN,
+	InitReplacementCodeusSUN,
+	InitReplacementCodeubSUN,
+	InitReplacementCodeuivSUN,
+	InitReplacementCodeusvSUN,
+	InitReplacementCodeubvSUN,
+	InitReplacementCodePointerSUN,
+	InitColor4ubVertex2fSUN,
+	InitColor4ubVertex2fvSUN,
+	InitColor4ubVertex3fSUN,
+	InitColor4ubVertex3fvSUN,
+	InitColor3fVertex3fSUN,
+	InitColor3fVertex3fvSUN,
+	InitNormal3fVertex3fSUN,
+	InitNormal3fVertex3fvSUN,
+	InitColor4fNormal3fVertex3fSUN,
+	InitColor4fNormal3fVertex3fvSUN,
+	InitTexCoord2fVertex3fSUN,
+	InitTexCoord2fVertex3fvSUN,
+	InitTexCoord4fVertex4fSUN,
+	InitTexCoord4fVertex4fvSUN,
+	InitTexCoord2fColor4ubVertex3fSUN,
+	InitTexCoord2fColor4ubVertex3fvSUN,
+	InitTexCoord2fColor3fVertex3fSUN,
+	InitTexCoord2fColor3fVertex3fvSUN,
+	InitTexCoord2fNormal3fVertex3fSUN,
+	InitTexCoord2fNormal3fVertex3fvSUN,
+	InitTexCoord2fColor4fNormal3fVertex3fSUN,
+	InitTexCoord2fColor4fNormal3fVertex3fvSUN,
+	InitTexCoord4fColor4fNormal3fVertex4fSUN,
+	InitTexCoord4fColor4fNormal3fVertex4fvSUN,
+	InitReplacementCodeuiVertex3fSUN,
+	InitReplacementCodeuiVertex3fvSUN,
+	InitReplacementCodeuiColor4ubVertex3fSUN,
+	InitReplacementCodeuiColor4ubVertex3fvSUN,
+	InitReplacementCodeuiColor3fVertex3fSUN,
+	InitReplacementCodeuiColor3fVertex3fvSUN,
+	InitReplacementCodeuiNormal3fVertex3fSUN,
+	InitReplacementCodeuiNormal3fVertex3fvSUN,
+	InitReplacementCodeuiColor4fNormal3fVertex3fSUN,
+	InitReplacementCodeuiColor4fNormal3fVertex3fvSUN,
+	InitReplacementCodeuiTexCoord2fVertex3fSUN,
+	InitReplacementCodeuiTexCoord2fVertex3fvSUN,
+	InitReplacementCodeuiTexCoord2fNormal3fVertex3fSUN,
+	InitReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN,
+	InitReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN,
+	InitReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN,
+	InitBlendFuncSeparateEXT,
+	InitBlendFuncSeparateINGR,
+	InitVertexWeightfEXT,
+	InitVertexWeightfvEXT,
+	InitVertexWeightPointerEXT,
+	InitFlushVertexArrayRangeNV,
+	InitVertexArrayRangeNV,
+	InitCombinerParameterfvNV,
+	InitCombinerParameterfNV,
+	InitCombinerParameterivNV,
+	InitCombinerParameteriNV,
+	InitCombinerInputNV,
+	InitCombinerOutputNV,
+	InitFinalCombinerInputNV,
+	InitGetCombinerInputParameterfvNV,
+	InitGetCombinerInputParameterivNV,
+	InitGetCombinerOutputParameterfvNV,
+	InitGetCombinerOutputParameterivNV,
+	InitGetFinalCombinerInputParameterfvNV,
+	InitGetFinalCombinerInputParameterivNV,
+	InitResizeBuffersMESA,
+	InitWindowPos2dMESA,
+	InitWindowPos2dvMESA,
+	InitWindowPos2fMESA,
+	InitWindowPos2fvMESA,
+	InitWindowPos2iMESA,
+	InitWindowPos2ivMESA,
+	InitWindowPos2sMESA,
+	InitWindowPos2svMESA,
+	InitWindowPos3dMESA,
+	InitWindowPos3dvMESA,
+	InitWindowPos3fMESA,
+	InitWindowPos3fvMESA,
+	InitWindowPos3iMESA,
+	InitWindowPos3ivMESA,
+	InitWindowPos3sMESA,
+	InitWindowPos3svMESA,
+	InitWindowPos4dMESA,
+	InitWindowPos4dvMESA,
+	InitWindowPos4fMESA,
+	InitWindowPos4fvMESA,
+	InitWindowPos4iMESA,
+	InitWindowPos4ivMESA,
+	InitWindowPos4sMESA,
+	InitWindowPos4svMESA,
+	InitMultiModeDrawArraysIBM,
+	InitMultiModeDrawElementsIBM,
+	InitColorPointerListIBM,
+	InitSecondaryColorPointerListIBM,
+	InitEdgeFlagPointerListIBM,
+	InitFogCoordPointerListIBM,
+	InitIndexPointerListIBM,
+	InitNormalPointerListIBM,
+	InitTexCoordPointerListIBM,
+	InitVertexPointerListIBM,
+	InitTbufferMask3DFX,
+	InitSampleMaskEXT,
+	InitSamplePatternEXT,
+	InitTextureColorMaskSGIS,
+	InitIglooInterfaceSGIX,
+	InitDeleteFencesNV,
+	InitGenFencesNV,
+	InitIsFenceNV,
+	InitTestFenceNV,
+	InitGetFenceivNV,
+	InitFinishFenceNV,
+	InitSetFenceNV,
+	InitMapControlPointsNV,
+	InitMapParameterivNV,
+	InitMapParameterfvNV,
+	InitGetMapControlPointsNV,
+	InitGetMapParameterivNV,
+	InitGetMapParameterfvNV,
+	InitGetMapAttribParameterivNV,
+	InitGetMapAttribParameterfvNV,
+	InitEvalMapsNV,
+	InitCombinerStageParameterfvNV,
+	InitGetCombinerStageParameterfvNV,
+	InitAreProgramsResidentNV,
+	InitBindProgramNV,
+	InitDeleteProgramsNV,
+	InitExecuteProgramNV,
+	InitGenProgramsNV,
+	InitGetProgramParameterdvNV,
+	InitGetProgramParameterfvNV,
+	InitGetProgramivNV,
+	InitGetProgramStringNV,
+	InitGetTrackMatrixivNV,
+	InitGetVertexAttribdvNV,
+	InitGetVertexAttribfvNV,
+	InitGetVertexAttribivNV,
+	InitGetVertexAttribPointervNV,
+	InitIsProgramNV,
+	InitLoadProgramNV,
+	InitProgramParameter4dNV,
+	InitProgramParameter4dvNV,
+	InitProgramParameter4fNV,
+	InitProgramParameter4fvNV,
+	InitProgramParameters4dvNV,
+	InitProgramParameters4fvNV,
+	InitRequestResidentProgramsNV,
+	InitTrackMatrixNV,
+	InitVertexAttribPointerNV,
+	InitVertexAttrib1dNV,
+	InitVertexAttrib1dvNV,
+	InitVertexAttrib1fNV,
+	InitVertexAttrib1fvNV,
+	InitVertexAttrib1sNV,
+	InitVertexAttrib1svNV,
+	InitVertexAttrib2dNV,
+	InitVertexAttrib2dvNV,
+	InitVertexAttrib2fNV,
+	InitVertexAttrib2fvNV,
+	InitVertexAttrib2sNV,
+	InitVertexAttrib2svNV,
+	InitVertexAttrib3dNV,
+	InitVertexAttrib3dvNV,
+	InitVertexAttrib3fNV,
+	InitVertexAttrib3fvNV,
+	InitVertexAttrib3sNV,
+	InitVertexAttrib3svNV,
+	InitVertexAttrib4dNV,
+	InitVertexAttrib4dvNV,
+	InitVertexAttrib4fNV,
+	InitVertexAttrib4fvNV,
+	InitVertexAttrib4sNV,
+	InitVertexAttrib4svNV,
+	InitVertexAttrib4ubNV,
+	InitVertexAttrib4ubvNV,
+	InitVertexAttribs1dvNV,
+	InitVertexAttribs1fvNV,
+	InitVertexAttribs1svNV,
+	InitVertexAttribs2dvNV,
+	InitVertexAttribs2fvNV,
+	InitVertexAttribs2svNV,
+	InitVertexAttribs3dvNV,
+	InitVertexAttribs3fvNV,
+	InitVertexAttribs3svNV,
+	InitVertexAttribs4dvNV,
+	InitVertexAttribs4fvNV,
+	InitVertexAttribs4svNV,
+	InitVertexAttribs4ubvNV,
+	InitTexBumpParameterivATI,
+	InitTexBumpParameterfvATI,
+	InitGetTexBumpParameterivATI,
+	InitGetTexBumpParameterfvATI,
+	InitGenFragmentShadersATI,
+	InitBindFragmentShaderATI,
+	InitDeleteFragmentShaderATI,
+	InitBeginFragmentShaderATI,
+	InitEndFragmentShaderATI,
+	InitPassTexCoordATI,
+	InitSampleMapATI,
+	InitColorFragmentOp1ATI,
+	InitColorFragmentOp2ATI,
+	InitColorFragmentOp3ATI,
+	InitAlphaFragmentOp1ATI,
+	InitAlphaFragmentOp2ATI,
+	InitAlphaFragmentOp3ATI,
+	InitSetFragmentShaderConstantATI,
+	InitPNTrianglesiATI,
+	InitPNTrianglesfATI,
+	InitNewObjectBufferATI,
+	InitIsObjectBufferATI,
+	InitUpdateObjectBufferATI,
+	InitGetObjectBufferfvATI,
+	InitGetObjectBufferivATI,
+	InitFreeObjectBufferATI,
+	InitArrayObjectATI,
+	InitGetArrayObjectfvATI,
+	InitGetArrayObjectivATI,
+	InitVariantArrayObjectATI,
+	InitGetVariantArrayObjectfvATI,
+	InitGetVariantArrayObjectivATI,
+	InitBeginVertexShaderEXT,
+	InitEndVertexShaderEXT,
+	InitBindVertexShaderEXT,
+	InitGenVertexShadersEXT,
+	InitDeleteVertexShaderEXT,
+	InitShaderOp1EXT,
+	InitShaderOp2EXT,
+	InitShaderOp3EXT,
+	InitSwizzleEXT,
+	InitWriteMaskEXT,
+	InitInsertComponentEXT,
+	InitExtractComponentEXT,
+	InitGenSymbolsEXT,
+	InitSetInvariantEXT,
+	InitSetLocalConstantEXT,
+	InitVariantbvEXT,
+	InitVariantsvEXT,
+	InitVariantivEXT,
+	InitVariantfvEXT,
+	InitVariantdvEXT,
+	InitVariantubvEXT,
+	InitVariantusvEXT,
+	InitVariantuivEXT,
+	InitVariantPointerEXT,
+	InitEnableVariantClientStateEXT,
+	InitDisableVariantClientStateEXT,
+	InitBindLightParameterEXT,
+	InitBindMaterialParameterEXT,
+	InitBindTexGenParameterEXT,
+	InitBindTextureUnitParameterEXT,
+	InitBindParameterEXT,
+	InitIsVariantEnabledEXT,
+	InitGetVariantBooleanvEXT,
+	InitGetVariantIntegervEXT,
+	InitGetVariantFloatvEXT,
+	InitGetVariantPointervEXT,
+	InitGetInvariantBooleanvEXT,
+	InitGetInvariantIntegervEXT,
+	InitGetInvariantFloatvEXT,
+	InitGetLocalConstantBooleanvEXT,
+	InitGetLocalConstantIntegervEXT,
+	InitGetLocalConstantFloatvEXT,
+	InitVertexStream1sATI,
+	InitVertexStream1svATI,
+	InitVertexStream1iATI,
+	InitVertexStream1ivATI,
+	InitVertexStream1fATI,
+	InitVertexStream1fvATI,
+	InitVertexStream1dATI,
+	InitVertexStream1dvATI,
+	InitVertexStream2sATI,
+	InitVertexStream2svATI,
+	InitVertexStream2iATI,
+	InitVertexStream2ivATI,
+	InitVertexStream2fATI,
+	InitVertexStream2fvATI,
+	InitVertexStream2dATI,
+	InitVertexStream2dvATI,
+	InitVertexStream3sATI,
+	InitVertexStream3svATI,
+	InitVertexStream3iATI,
+	InitVertexStream3ivATI,
+	InitVertexStream3fATI,
+	InitVertexStream3fvATI,
+	InitVertexStream3dATI,
+	InitVertexStream3dvATI,
+	InitVertexStream4sATI,
+	InitVertexStream4svATI,
+	InitVertexStream4iATI,
+	InitVertexStream4ivATI,
+	InitVertexStream4fATI,
+	InitVertexStream4fvATI,
+	InitVertexStream4dATI,
+	InitVertexStream4dvATI,
+	InitNormalStream3bATI,
+	InitNormalStream3bvATI,
+	InitNormalStream3sATI,
+	InitNormalStream3svATI,
+	InitNormalStream3iATI,
+	InitNormalStream3ivATI,
+	InitNormalStream3fATI,
+	InitNormalStream3fvATI,
+	InitNormalStream3dATI,
+	InitNormalStream3dvATI,
+	InitClientActiveVertexStreamATI,
+	InitVertexBlendEnviATI,
+	InitVertexBlendEnvfATI,
+	InitElementPointerATI,
+	InitDrawElementArrayATI,
+	InitDrawRangeElementArrayATI,
+	InitDrawMeshArraysSUN,
+	InitGenOcclusionQueriesNV,
+	InitDeleteOcclusionQueriesNV,
+	InitIsOcclusionQueryNV,
+	InitBeginOcclusionQueryNV,
+	InitEndOcclusionQueryNV,
+	InitGetOcclusionQueryivNV,
+	InitGetOcclusionQueryuivNV,
+	InitPointParameteriNV,
+	InitPointParameterivNV,
+	InitActiveStencilFaceEXT,
+	InitElementPointerAPPLE,
+	InitDrawElementArrayAPPLE,
+	InitDrawRangeElementArrayAPPLE,
+	InitMultiDrawElementArrayAPPLE,
+	InitMultiDrawRangeElementArrayAPPLE,
+	InitGenFencesAPPLE,
+	InitDeleteFencesAPPLE,
+	InitSetFenceAPPLE,
+	InitIsFenceAPPLE,
+	InitTestFenceAPPLE,
+	InitFinishFenceAPPLE,
+	InitTestObjectAPPLE,
+	InitFinishObjectAPPLE,
+	InitBindVertexArrayAPPLE,
+	InitDeleteVertexArraysAPPLE,
+	InitGenVertexArraysAPPLE,
+	InitIsVertexArrayAPPLE,
+	InitVertexArrayRangeAPPLE,
+	InitFlushVertexArrayRangeAPPLE,
+	InitVertexArrayParameteriAPPLE,
+	InitDrawBuffersATI,
+	InitProgramNamedParameter4fNV,
+	InitProgramNamedParameter4dNV,
+	InitProgramNamedParameter4fvNV,
+	InitProgramNamedParameter4dvNV,
+	InitGetProgramNamedParameterfvNV,
+	InitGetProgramNamedParameterdvNV,
+	InitVertex2hNV,
+	InitVertex2hvNV,
+	InitVertex3hNV,
+	InitVertex3hvNV,
+	InitVertex4hNV,
+	InitVertex4hvNV,
+	InitNormal3hNV,
+	InitNormal3hvNV,
+	InitColor3hNV,
+	InitColor3hvNV,
+	InitColor4hNV,
+	InitColor4hvNV,
+	InitTexCoord1hNV,
+	InitTexCoord1hvNV,
+	InitTexCoord2hNV,
+	InitTexCoord2hvNV,
+	InitTexCoord3hNV,
+	InitTexCoord3hvNV,
+	InitTexCoord4hNV,
+	InitTexCoord4hvNV,
+	InitMultiTexCoord1hNV,
+	InitMultiTexCoord1hvNV,
+	InitMultiTexCoord2hNV,
+	InitMultiTexCoord2hvNV,
+	InitMultiTexCoord3hNV,
+	InitMultiTexCoord3hvNV,
+	InitMultiTexCoord4hNV,
+	InitMultiTexCoord4hvNV,
+	InitFogCoordhNV,
+	InitFogCoordhvNV,
+	InitSecondaryColor3hNV,
+	InitSecondaryColor3hvNV,
+	InitVertexWeighthNV,
+	InitVertexWeighthvNV,
+	InitVertexAttrib1hNV,
+	InitVertexAttrib1hvNV,
+	InitVertexAttrib2hNV,
+	InitVertexAttrib2hvNV,
+	InitVertexAttrib3hNV,
+	InitVertexAttrib3hvNV,
+	InitVertexAttrib4hNV,
+	InitVertexAttrib4hvNV,
+	InitVertexAttribs1hvNV,
+	InitVertexAttribs2hvNV,
+	InitVertexAttribs3hvNV,
+	InitVertexAttribs4hvNV,
+	InitPixelDataRangeNV,
+	InitFlushPixelDataRangeNV,
+	InitPrimitiveRestartNV,
+	InitPrimitiveRestartIndexNV,
+	InitMapObjectBufferATI,
+	InitUnmapObjectBufferATI,
+	InitStencilOpSeparateATI,
+	InitStencilFuncSeparateATI,
+	InitVertexAttribArrayObjectATI,
+	InitGetVertexAttribArrayObjectfvATI,
+	InitGetVertexAttribArrayObjectivATI,
+	InitDepthBoundsEXT,
+	InitBlendEquationSeparateEXT,
+	InitAddSwapHintRectWIN,
+#ifdef _WIN32
+	InitCreateBufferRegionARB,
+	InitDeleteBufferRegionARB,
+	InitSaveBufferRegionARB,
+	InitRestoreBufferRegionARB,
+	InitGetExtensionsStringARB,
+	InitGetPixelFormatAttribivARB,
+	InitGetPixelFormatAttribfvARB,
+	InitChoosePixelFormatARB,
+	InitMakeContextCurrentARB,
+	InitGetCurrentReadDCARB,
+	InitCreatePbufferARB,
+	InitGetPbufferDCARB,
+	InitReleasePbufferDCARB,
+	InitDestroyPbufferARB,
+	InitQueryPbufferARB,
+	InitBindTexImageARB,
+	InitReleaseTexImageARB,
+	InitSetPbufferAttribARB,
+	InitCreateDisplayColorTableEXT,
+	InitLoadDisplayColorTableEXT,
+	InitBindDisplayColorTableEXT,
+	InitDestroyDisplayColorTableEXT,
+	InitGetExtensionsStringEXT,
+	InitMakeContextCurrentEXT,
+	InitGetCurrentReadDCEXT,
+	InitCreatePbufferEXT,
+	InitGetPbufferDCEXT,
+	InitReleasePbufferDCEXT,
+	InitDestroyPbufferEXT,
+	InitQueryPbufferEXT,
+	InitGetPixelFormatAttribivEXT,
+	InitGetPixelFormatAttribfvEXT,
+	InitChoosePixelFormatEXT,
+	InitSwapIntervalEXT,
+	InitGetSwapIntervalEXT,
+	InitAllocateMemoryNV,
+	InitFreeMemoryNV,
+	InitGetSyncValuesOML,
+	InitGetMscRateOML,
+	InitSwapBuffersMscOML,
+	InitSwapLayerBuffersMscOML,
+	InitWaitForMscOML,
+	InitWaitForSbcOML,
+	InitGetDigitalVideoParametersI3D,
+	InitSetDigitalVideoParametersI3D,
+	InitGetGammaTableParametersI3D,
+	InitSetGammaTableParametersI3D,
+	InitGetGammaTableI3D,
+	InitSetGammaTableI3D,
+	InitEnableGenlockI3D,
+	InitDisableGenlockI3D,
+	InitIsEnabledGenlockI3D,
+	InitGenlockSourceI3D,
+	InitGetGenlockSourceI3D,
+	InitGenlockSourceEdgeI3D,
+	InitGetGenlockSourceEdgeI3D,
+	InitGenlockSampleRateI3D,
+	InitGetGenlockSampleRateI3D,
+	InitGenlockSourceDelayI3D,
+	InitGetGenlockSourceDelayI3D,
+	InitQueryGenlockMaxSourceDelayI3D,
+	InitCreateImageBufferI3D,
+	InitDestroyImageBufferI3D,
+	InitAssociateImageBufferEventsI3D,
+	InitReleaseImageBufferEventsI3D,
+	InitEnableFrameLockI3D,
+	InitDisableFrameLockI3D,
+	InitIsEnabledFrameLockI3D,
+	InitQueryFrameLockMasterI3D,
+	InitGetFrameUsageI3D,
+	InitBeginFrameTrackingI3D,
+	InitEndFrameTrackingI3D,
+	InitQueryFrameTrackingI3D,
+#endif /* _WIN32 */
+};
diff --git a/src/ext/GLsdk/GL/glprocs.h b/src/ext/GLsdk/GL/glprocs.h
new file mode 100644
index 0000000..0dfda44
--- /dev/null
+++ b/src/ext/GLsdk/GL/glprocs.h
@@ -0,0 +1,2213 @@
+#ifndef _GLPROCS_H_
+#define _GLPROCS_H_
+
+/*
+** GLprocs utility for getting function addresses for OpenGL(R) 1.2, 
+** OpenGL 1.3, OpenGL 1.4, OpenGL 1.5 and OpenGL extension functions.
+**
+** Version:  1.1
+**
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+**
+** Initial version of glprocs.{c,h} contributed by Intel(R) Corporation.
+*/
+
+#ifdef _WIN32
+  #include "glext.h"
+  #include "wglext.h"
+#else
+  #include <GL/glext.h>
+#endif
+
+#ifndef _WIN32 /* non-Windows environment */
+  #ifndef APIENTRY
+    #define APIENTRY
+  #endif
+  #ifdef __GNUC__
+    #define _inline __inline__
+  #else
+    #define _inline
+  #endif
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Structure of all OpenGL {1.2, 1.3, 1.4, 1.5}, GL extension procs.*/
+
+typedef struct {
+  void (APIENTRY *BlendColor) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+  void (APIENTRY *BlendEquation) (GLenum mode);
+  void (APIENTRY *DrawRangeElements) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+  void (APIENTRY *ColorTable) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+  void (APIENTRY *ColorTableParameterfv) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *ColorTableParameteriv) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *CopyColorTable) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *GetColorTable) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+  void (APIENTRY *GetColorTableParameterfv) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetColorTableParameteriv) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *ColorSubTable) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+  void (APIENTRY *CopyColorSubTable) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *ConvolutionFilter1D) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+  void (APIENTRY *ConvolutionFilter2D) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+  void (APIENTRY *ConvolutionParameterf) (GLenum target, GLenum pname, GLfloat params);
+  void (APIENTRY *ConvolutionParameterfv) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *ConvolutionParameteri) (GLenum target, GLenum pname, GLint params);
+  void (APIENTRY *ConvolutionParameteriv) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *CopyConvolutionFilter1D) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *CopyConvolutionFilter2D) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+  void (APIENTRY *GetConvolutionFilter) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+  void (APIENTRY *GetConvolutionParameterfv) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetConvolutionParameteriv) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetSeparableFilter) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+  void (APIENTRY *SeparableFilter2D) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+  void (APIENTRY *GetHistogram) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  void (APIENTRY *GetHistogramParameterfv) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetHistogramParameteriv) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetMinmax) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  void (APIENTRY *GetMinmaxParameterfv) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetMinmaxParameteriv) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *Histogram) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+  void (APIENTRY *Minmax) (GLenum target, GLenum internalformat, GLboolean sink);
+  void (APIENTRY *ResetHistogram) (GLenum target);
+  void (APIENTRY *ResetMinmax) (GLenum target);
+  void (APIENTRY *TexImage3D) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *TexSubImage3D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *CopyTexSubImage3D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+  void (APIENTRY *ActiveTexture) (GLenum texture);
+  void (APIENTRY *ClientActiveTexture) (GLenum texture);
+  void (APIENTRY *MultiTexCoord1d) (GLenum target, GLdouble s);
+  void (APIENTRY *MultiTexCoord1dv) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord1f) (GLenum target, GLfloat s);
+  void (APIENTRY *MultiTexCoord1fv) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord1i) (GLenum target, GLint s);
+  void (APIENTRY *MultiTexCoord1iv) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord1s) (GLenum target, GLshort s);
+  void (APIENTRY *MultiTexCoord1sv) (GLenum target, const GLshort *v);
+  void (APIENTRY *MultiTexCoord2d) (GLenum target, GLdouble s, GLdouble t);
+  void (APIENTRY *MultiTexCoord2dv) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord2f) (GLenum target, GLfloat s, GLfloat t);
+  void (APIENTRY *MultiTexCoord2fv) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord2i) (GLenum target, GLint s, GLint t);
+  void (APIENTRY *MultiTexCoord2iv) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord2s) (GLenum target, GLshort s, GLshort t);
+  void (APIENTRY *MultiTexCoord2sv) (GLenum target, const GLshort *v);
+  void (APIENTRY *MultiTexCoord3d) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+  void (APIENTRY *MultiTexCoord3dv) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord3f) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+  void (APIENTRY *MultiTexCoord3fv) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord3i) (GLenum target, GLint s, GLint t, GLint r);
+  void (APIENTRY *MultiTexCoord3iv) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord3s) (GLenum target, GLshort s, GLshort t, GLshort r);
+  void (APIENTRY *MultiTexCoord3sv) (GLenum target, const GLshort *v);
+  void (APIENTRY *MultiTexCoord4d) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+  void (APIENTRY *MultiTexCoord4dv) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord4f) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+  void (APIENTRY *MultiTexCoord4fv) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord4i) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+  void (APIENTRY *MultiTexCoord4iv) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord4s) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+  void (APIENTRY *MultiTexCoord4sv) (GLenum target, const GLshort *v);
+  void (APIENTRY *LoadTransposeMatrixf) (const GLfloat *m);
+  void (APIENTRY *LoadTransposeMatrixd) (const GLdouble *m);
+  void (APIENTRY *MultTransposeMatrixf) (const GLfloat *m);
+  void (APIENTRY *MultTransposeMatrixd) (const GLdouble *m);
+  void (APIENTRY *SampleCoverage) (GLclampf value, GLboolean invert);
+  void (APIENTRY *CompressedTexImage3D) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexImage2D) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexImage1D) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexSubImage3D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexSubImage2D) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexSubImage1D) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *GetCompressedTexImage) (GLenum target, GLint level, GLvoid *img);
+  void (APIENTRY *BlendFuncSeparate) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+  void (APIENTRY *FogCoordf) (GLfloat coord);
+  void (APIENTRY *FogCoordfv) (const GLfloat *coord);
+  void (APIENTRY *FogCoordd) (GLdouble coord);
+  void (APIENTRY *FogCoorddv) (const GLdouble *coord);
+  void (APIENTRY *FogCoordPointer) (GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *MultiDrawArrays) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+  void (APIENTRY *MultiDrawElements) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+  void (APIENTRY *PointParameterf) (GLenum pname, GLfloat param);
+  void (APIENTRY *PointParameterfv) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *PointParameteri) (GLenum pname, GLint param);
+  void (APIENTRY *PointParameteriv) (GLenum pname, const GLint *params);
+  void (APIENTRY *SecondaryColor3b) (GLbyte red, GLbyte green, GLbyte blue);
+  void (APIENTRY *SecondaryColor3bv) (const GLbyte *v);
+  void (APIENTRY *SecondaryColor3d) (GLdouble red, GLdouble green, GLdouble blue);
+  void (APIENTRY *SecondaryColor3dv) (const GLdouble *v);
+  void (APIENTRY *SecondaryColor3f) (GLfloat red, GLfloat green, GLfloat blue);
+  void (APIENTRY *SecondaryColor3fv) (const GLfloat *v);
+  void (APIENTRY *SecondaryColor3i) (GLint red, GLint green, GLint blue);
+  void (APIENTRY *SecondaryColor3iv) (const GLint *v);
+  void (APIENTRY *SecondaryColor3s) (GLshort red, GLshort green, GLshort blue);
+  void (APIENTRY *SecondaryColor3sv) (const GLshort *v);
+  void (APIENTRY *SecondaryColor3ub) (GLubyte red, GLubyte green, GLubyte blue);
+  void (APIENTRY *SecondaryColor3ubv) (const GLubyte *v);
+  void (APIENTRY *SecondaryColor3ui) (GLuint red, GLuint green, GLuint blue);
+  void (APIENTRY *SecondaryColor3uiv) (const GLuint *v);
+  void (APIENTRY *SecondaryColor3us) (GLushort red, GLushort green, GLushort blue);
+  void (APIENTRY *SecondaryColor3usv) (const GLushort *v);
+  void (APIENTRY *SecondaryColorPointer) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *WindowPos2d) (GLdouble x, GLdouble y);
+  void (APIENTRY *WindowPos2dv) (const GLdouble *v);
+  void (APIENTRY *WindowPos2f) (GLfloat x, GLfloat y);
+  void (APIENTRY *WindowPos2fv) (const GLfloat *v);
+  void (APIENTRY *WindowPos2i) (GLint x, GLint y);
+  void (APIENTRY *WindowPos2iv) (const GLint *v);
+  void (APIENTRY *WindowPos2s) (GLshort x, GLshort y);
+  void (APIENTRY *WindowPos2sv) (const GLshort *v);
+  void (APIENTRY *WindowPos3d) (GLdouble x, GLdouble y, GLdouble z);
+  void (APIENTRY *WindowPos3dv) (const GLdouble *v);
+  void (APIENTRY *WindowPos3f) (GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *WindowPos3fv) (const GLfloat *v);
+  void (APIENTRY *WindowPos3i) (GLint x, GLint y, GLint z);
+  void (APIENTRY *WindowPos3iv) (const GLint *v);
+  void (APIENTRY *WindowPos3s) (GLshort x, GLshort y, GLshort z);
+  void (APIENTRY *WindowPos3sv) (const GLshort *v);
+  void (APIENTRY *GenQueries) (GLsizei n, GLuint *ids);
+  void (APIENTRY *DeleteQueries) (GLsizei n, const GLuint *ids);
+  GLboolean (APIENTRY *IsQuery) (GLuint id);
+  void (APIENTRY *BeginQuery) (GLenum target, GLuint id);
+  void (APIENTRY *EndQuery) (GLenum target);
+  void (APIENTRY *GetQueryiv) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetQueryObjectiv) (GLuint id, GLenum pname, GLint *params);
+  void (APIENTRY *GetQueryObjectuiv) (GLuint id, GLenum pname, GLuint *params);
+  void (APIENTRY *BindBuffer) (GLenum target, GLuint buffer);
+  void (APIENTRY *DeleteBuffers) (GLsizei n, const GLuint *buffers);
+  void (APIENTRY *GenBuffers) (GLsizei n, GLuint *buffers);
+  GLboolean (APIENTRY *IsBuffer) (GLuint buffer);
+  void (APIENTRY *BufferData) (GLenum target, GLsizeiptr size, const GLvoid *data, GLenum usage);
+  void (APIENTRY *BufferSubData) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid *data);
+  void (APIENTRY *GetBufferSubData) (GLenum target, GLintptr offset, GLsizeiptr size, GLvoid *data);
+  GLvoid* (APIENTRY *MapBuffer) (GLenum target, GLenum access);
+  GLboolean (APIENTRY *UnmapBuffer) (GLenum target);
+  void (APIENTRY *GetBufferParameteriv) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetBufferPointerv) (GLenum target, GLenum pname, GLvoid* *params);
+  void (APIENTRY *ActiveTextureARB) (GLenum texture);
+  void (APIENTRY *ClientActiveTextureARB) (GLenum texture);
+  void (APIENTRY *MultiTexCoord1dARB) (GLenum target, GLdouble s);
+  void (APIENTRY *MultiTexCoord1dvARB) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord1fARB) (GLenum target, GLfloat s);
+  void (APIENTRY *MultiTexCoord1fvARB) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord1iARB) (GLenum target, GLint s);
+  void (APIENTRY *MultiTexCoord1ivARB) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord1sARB) (GLenum target, GLshort s);
+  void (APIENTRY *MultiTexCoord1svARB) (GLenum target, const GLshort *v);
+  void (APIENTRY *MultiTexCoord2dARB) (GLenum target, GLdouble s, GLdouble t);
+  void (APIENTRY *MultiTexCoord2dvARB) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord2fARB) (GLenum target, GLfloat s, GLfloat t);
+  void (APIENTRY *MultiTexCoord2fvARB) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord2iARB) (GLenum target, GLint s, GLint t);
+  void (APIENTRY *MultiTexCoord2ivARB) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord2sARB) (GLenum target, GLshort s, GLshort t);
+  void (APIENTRY *MultiTexCoord2svARB) (GLenum target, const GLshort *v);
+  void (APIENTRY *MultiTexCoord3dARB) (GLenum target, GLdouble s, GLdouble t, GLdouble r);
+  void (APIENTRY *MultiTexCoord3dvARB) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord3fARB) (GLenum target, GLfloat s, GLfloat t, GLfloat r);
+  void (APIENTRY *MultiTexCoord3fvARB) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord3iARB) (GLenum target, GLint s, GLint t, GLint r);
+  void (APIENTRY *MultiTexCoord3ivARB) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord3sARB) (GLenum target, GLshort s, GLshort t, GLshort r);
+  void (APIENTRY *MultiTexCoord3svARB) (GLenum target, const GLshort *v);
+  void (APIENTRY *MultiTexCoord4dARB) (GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q);
+  void (APIENTRY *MultiTexCoord4dvARB) (GLenum target, const GLdouble *v);
+  void (APIENTRY *MultiTexCoord4fARB) (GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+  void (APIENTRY *MultiTexCoord4fvARB) (GLenum target, const GLfloat *v);
+  void (APIENTRY *MultiTexCoord4iARB) (GLenum target, GLint s, GLint t, GLint r, GLint q);
+  void (APIENTRY *MultiTexCoord4ivARB) (GLenum target, const GLint *v);
+  void (APIENTRY *MultiTexCoord4sARB) (GLenum target, GLshort s, GLshort t, GLshort r, GLshort q);
+  void (APIENTRY *MultiTexCoord4svARB) (GLenum target, const GLshort *v);
+  void (APIENTRY *LoadTransposeMatrixfARB) (const GLfloat *m);
+  void (APIENTRY *LoadTransposeMatrixdARB) (const GLdouble *m);
+  void (APIENTRY *MultTransposeMatrixfARB) (const GLfloat *m);
+  void (APIENTRY *MultTransposeMatrixdARB) (const GLdouble *m);
+  void (APIENTRY *SampleCoverageARB) (GLclampf value, GLboolean invert);
+  void (APIENTRY *CompressedTexImage3DARB) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexImage2DARB) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexImage1DARB) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexSubImage3DARB) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexSubImage2DARB) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *CompressedTexSubImage1DARB) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data);
+  void (APIENTRY *GetCompressedTexImageARB) (GLenum target, GLint level, GLvoid *img);
+  void (APIENTRY *PointParameterfARB) (GLenum pname, GLfloat param);
+  void (APIENTRY *PointParameterfvARB) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *WeightbvARB) (GLint size, const GLbyte *weights);
+  void (APIENTRY *WeightsvARB) (GLint size, const GLshort *weights);
+  void (APIENTRY *WeightivARB) (GLint size, const GLint *weights);
+  void (APIENTRY *WeightfvARB) (GLint size, const GLfloat *weights);
+  void (APIENTRY *WeightdvARB) (GLint size, const GLdouble *weights);
+  void (APIENTRY *WeightubvARB) (GLint size, const GLubyte *weights);
+  void (APIENTRY *WeightusvARB) (GLint size, const GLushort *weights);
+  void (APIENTRY *WeightuivARB) (GLint size, const GLuint *weights);
+  void (APIENTRY *WeightPointerARB) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *VertexBlendARB) (GLint count);
+  void (APIENTRY *CurrentPaletteMatrixARB) (GLint index);
+  void (APIENTRY *MatrixIndexubvARB) (GLint size, const GLubyte *indices);
+  void (APIENTRY *MatrixIndexusvARB) (GLint size, const GLushort *indices);
+  void (APIENTRY *MatrixIndexuivARB) (GLint size, const GLuint *indices);
+  void (APIENTRY *MatrixIndexPointerARB) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *WindowPos2dARB) (GLdouble x, GLdouble y);
+  void (APIENTRY *WindowPos2dvARB) (const GLdouble *v);
+  void (APIENTRY *WindowPos2fARB) (GLfloat x, GLfloat y);
+  void (APIENTRY *WindowPos2fvARB) (const GLfloat *v);
+  void (APIENTRY *WindowPos2iARB) (GLint x, GLint y);
+  void (APIENTRY *WindowPos2ivARB) (const GLint *v);
+  void (APIENTRY *WindowPos2sARB) (GLshort x, GLshort y);
+  void (APIENTRY *WindowPos2svARB) (const GLshort *v);
+  void (APIENTRY *WindowPos3dARB) (GLdouble x, GLdouble y, GLdouble z);
+  void (APIENTRY *WindowPos3dvARB) (const GLdouble *v);
+  void (APIENTRY *WindowPos3fARB) (GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *WindowPos3fvARB) (const GLfloat *v);
+  void (APIENTRY *WindowPos3iARB) (GLint x, GLint y, GLint z);
+  void (APIENTRY *WindowPos3ivARB) (const GLint *v);
+  void (APIENTRY *WindowPos3sARB) (GLshort x, GLshort y, GLshort z);
+  void (APIENTRY *WindowPos3svARB) (const GLshort *v);
+  void (APIENTRY *VertexAttrib1dARB) (GLuint index, GLdouble x);
+  void (APIENTRY *VertexAttrib1dvARB) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib1fARB) (GLuint index, GLfloat x);
+  void (APIENTRY *VertexAttrib1fvARB) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib1sARB) (GLuint index, GLshort x);
+  void (APIENTRY *VertexAttrib1svARB) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib2dARB) (GLuint index, GLdouble x, GLdouble y);
+  void (APIENTRY *VertexAttrib2dvARB) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib2fARB) (GLuint index, GLfloat x, GLfloat y);
+  void (APIENTRY *VertexAttrib2fvARB) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib2sARB) (GLuint index, GLshort x, GLshort y);
+  void (APIENTRY *VertexAttrib2svARB) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib3dARB) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+  void (APIENTRY *VertexAttrib3dvARB) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib3fARB) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *VertexAttrib3fvARB) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib3sARB) (GLuint index, GLshort x, GLshort y, GLshort z);
+  void (APIENTRY *VertexAttrib3svARB) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib4NbvARB) (GLuint index, const GLbyte *v);
+  void (APIENTRY *VertexAttrib4NivARB) (GLuint index, const GLint *v);
+  void (APIENTRY *VertexAttrib4NsvARB) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib4NubARB) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+  void (APIENTRY *VertexAttrib4NubvARB) (GLuint index, const GLubyte *v);
+  void (APIENTRY *VertexAttrib4NuivARB) (GLuint index, const GLuint *v);
+  void (APIENTRY *VertexAttrib4NusvARB) (GLuint index, const GLushort *v);
+  void (APIENTRY *VertexAttrib4bvARB) (GLuint index, const GLbyte *v);
+  void (APIENTRY *VertexAttrib4dARB) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *VertexAttrib4dvARB) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib4fARB) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *VertexAttrib4fvARB) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib4ivARB) (GLuint index, const GLint *v);
+  void (APIENTRY *VertexAttrib4sARB) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+  void (APIENTRY *VertexAttrib4svARB) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib4ubvARB) (GLuint index, const GLubyte *v);
+  void (APIENTRY *VertexAttrib4uivARB) (GLuint index, const GLuint *v);
+  void (APIENTRY *VertexAttrib4usvARB) (GLuint index, const GLushort *v);
+  void (APIENTRY *VertexAttribPointerARB) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *EnableVertexAttribArrayARB) (GLuint index);
+  void (APIENTRY *DisableVertexAttribArrayARB) (GLuint index);
+  void (APIENTRY *ProgramStringARB) (GLenum target, GLenum format, GLsizei len, const GLvoid *string);
+  void (APIENTRY *BindProgramARB) (GLenum target, GLuint program);
+  void (APIENTRY *DeleteProgramsARB) (GLsizei n, const GLuint *programs);
+  void (APIENTRY *GenProgramsARB) (GLsizei n, GLuint *programs);
+  void (APIENTRY *ProgramEnvParameter4dARB) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *ProgramEnvParameter4dvARB) (GLenum target, GLuint index, const GLdouble *params);
+  void (APIENTRY *ProgramEnvParameter4fARB) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *ProgramEnvParameter4fvARB) (GLenum target, GLuint index, const GLfloat *params);
+  void (APIENTRY *ProgramLocalParameter4dARB) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *ProgramLocalParameter4dvARB) (GLenum target, GLuint index, const GLdouble *params);
+  void (APIENTRY *ProgramLocalParameter4fARB) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *ProgramLocalParameter4fvARB) (GLenum target, GLuint index, const GLfloat *params);
+  void (APIENTRY *GetProgramEnvParameterdvARB) (GLenum target, GLuint index, GLdouble *params);
+  void (APIENTRY *GetProgramEnvParameterfvARB) (GLenum target, GLuint index, GLfloat *params);
+  void (APIENTRY *GetProgramLocalParameterdvARB) (GLenum target, GLuint index, GLdouble *params);
+  void (APIENTRY *GetProgramLocalParameterfvARB) (GLenum target, GLuint index, GLfloat *params);
+  void (APIENTRY *GetProgramivARB) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetProgramStringARB) (GLenum target, GLenum pname, GLvoid *string);
+  void (APIENTRY *GetVertexAttribdvARB) (GLuint index, GLenum pname, GLdouble *params);
+  void (APIENTRY *GetVertexAttribfvARB) (GLuint index, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetVertexAttribivARB) (GLuint index, GLenum pname, GLint *params);
+  void (APIENTRY *GetVertexAttribPointervARB) (GLuint index, GLenum pname, GLvoid* *pointer);
+  GLboolean (APIENTRY *IsProgramARB) (GLuint program);
+  void (APIENTRY *BindBufferARB) (GLenum target, GLuint buffer);
+  void (APIENTRY *DeleteBuffersARB) (GLsizei n, const GLuint *buffers);
+  void (APIENTRY *GenBuffersARB) (GLsizei n, GLuint *buffers);
+  GLboolean (APIENTRY *IsBufferARB) (GLuint buffer);
+  void (APIENTRY *BufferDataARB) (GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage);
+  void (APIENTRY *BufferSubDataARB) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, const GLvoid *data);
+  void (APIENTRY *GetBufferSubDataARB) (GLenum target, GLintptrARB offset, GLsizeiptrARB size, GLvoid *data);
+  GLvoid* (APIENTRY *MapBufferARB) (GLenum target, GLenum access);
+  GLboolean (APIENTRY *UnmapBufferARB) (GLenum target);
+  void (APIENTRY *GetBufferParameterivARB) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetBufferPointervARB) (GLenum target, GLenum pname, GLvoid* *params);
+  void (APIENTRY *GenQueriesARB) (GLsizei n, GLuint *ids);
+  void (APIENTRY *DeleteQueriesARB) (GLsizei n, const GLuint *ids);
+  GLboolean (APIENTRY *IsQueryARB) (GLuint id);
+  void (APIENTRY *BeginQueryARB) (GLenum target, GLuint id);
+  void (APIENTRY *EndQueryARB) (GLenum target);
+  void (APIENTRY *GetQueryivARB) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetQueryObjectivARB) (GLuint id, GLenum pname, GLint *params);
+  void (APIENTRY *GetQueryObjectuivARB) (GLuint id, GLenum pname, GLuint *params);
+  void (APIENTRY *DeleteObjectARB) (GLhandleARB obj);
+  GLhandleARB (APIENTRY *GetHandleARB) (GLenum pname);
+  void (APIENTRY *DetachObjectARB) (GLhandleARB containerObj, GLhandleARB attachedObj);
+  GLhandleARB (APIENTRY *CreateShaderObjectARB) (GLenum shaderType);
+  void (APIENTRY *ShaderSourceARB) (GLhandleARB shaderObj, GLsizei count, const GLcharARB* *string, const GLint *length);
+  void (APIENTRY *CompileShaderARB) (GLhandleARB shaderObj);
+  GLhandleARB (APIENTRY *CreateProgramObjectARB) (void);
+  void (APIENTRY *AttachObjectARB) (GLhandleARB containerObj, GLhandleARB obj);
+  void (APIENTRY *LinkProgramARB) (GLhandleARB programObj);
+  void (APIENTRY *UseProgramObjectARB) (GLhandleARB programObj);
+  void (APIENTRY *ValidateProgramARB) (GLhandleARB programObj);
+  void (APIENTRY *Uniform1fARB) (GLint location, GLfloat v0);
+  void (APIENTRY *Uniform2fARB) (GLint location, GLfloat v0, GLfloat v1);
+  void (APIENTRY *Uniform3fARB) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2);
+  void (APIENTRY *Uniform4fARB) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
+  void (APIENTRY *Uniform1iARB) (GLint location, GLint v0);
+  void (APIENTRY *Uniform2iARB) (GLint location, GLint v0, GLint v1);
+  void (APIENTRY *Uniform3iARB) (GLint location, GLint v0, GLint v1, GLint v2);
+  void (APIENTRY *Uniform4iARB) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3);
+  void (APIENTRY *Uniform1fvARB) (GLint location, GLsizei count, const GLfloat *value);
+  void (APIENTRY *Uniform2fvARB) (GLint location, GLsizei count, const GLfloat *value);
+  void (APIENTRY *Uniform3fvARB) (GLint location, GLsizei count, const GLfloat *value);
+  void (APIENTRY *Uniform4fvARB) (GLint location, GLsizei count, const GLfloat *value);
+  void (APIENTRY *Uniform1ivARB) (GLint location, GLsizei count, const GLint *value);
+  void (APIENTRY *Uniform2ivARB) (GLint location, GLsizei count, const GLint *value);
+  void (APIENTRY *Uniform3ivARB) (GLint location, GLsizei count, const GLint *value);
+  void (APIENTRY *Uniform4ivARB) (GLint location, GLsizei count, const GLint *value);
+  void (APIENTRY *UniformMatrix2fvARB) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  void (APIENTRY *UniformMatrix3fvARB) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  void (APIENTRY *UniformMatrix4fvARB) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
+  void (APIENTRY *GetObjectParameterfvARB) (GLhandleARB obj, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetObjectParameterivARB) (GLhandleARB obj, GLenum pname, GLint *params);
+  void (APIENTRY *GetInfoLogARB) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog);
+  void (APIENTRY *GetAttachedObjectsARB) (GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj);
+  GLint (APIENTRY *GetUniformLocationARB) (GLhandleARB programObj, const GLcharARB *name);
+  void (APIENTRY *GetActiveUniformARB) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+  void (APIENTRY *GetUniformfvARB) (GLhandleARB programObj, GLint location, GLfloat *params);
+  void (APIENTRY *GetUniformivARB) (GLhandleARB programObj, GLint location, GLint *params);
+  void (APIENTRY *GetShaderSourceARB) (GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source);
+  void (APIENTRY *BindAttribLocationARB) (GLhandleARB programObj, GLuint index, const GLcharARB *name);
+  void (APIENTRY *GetActiveAttribARB) (GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name);
+  GLint (APIENTRY *GetAttribLocationARB) (GLhandleARB programObj, const GLcharARB *name);
+  void (APIENTRY *BlendColorEXT) (GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);
+  void (APIENTRY *PolygonOffsetEXT) (GLfloat factor, GLfloat bias);
+  void (APIENTRY *TexImage3DEXT) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *TexSubImage3DEXT) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *GetTexFilterFuncSGIS) (GLenum target, GLenum filter, GLfloat *weights);
+  void (APIENTRY *TexFilterFuncSGIS) (GLenum target, GLenum filter, GLsizei n, const GLfloat *weights);
+  void (APIENTRY *TexSubImage1DEXT) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *TexSubImage2DEXT) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *CopyTexImage1DEXT) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border);
+  void (APIENTRY *CopyTexImage2DEXT) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border);
+  void (APIENTRY *CopyTexSubImage1DEXT) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *CopyTexSubImage2DEXT) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+  void (APIENTRY *CopyTexSubImage3DEXT) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height);
+  void (APIENTRY *GetHistogramEXT) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  void (APIENTRY *GetHistogramParameterfvEXT) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetHistogramParameterivEXT) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetMinmaxEXT) (GLenum target, GLboolean reset, GLenum format, GLenum type, GLvoid *values);
+  void (APIENTRY *GetMinmaxParameterfvEXT) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetMinmaxParameterivEXT) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *HistogramEXT) (GLenum target, GLsizei width, GLenum internalformat, GLboolean sink);
+  void (APIENTRY *MinmaxEXT) (GLenum target, GLenum internalformat, GLboolean sink);
+  void (APIENTRY *ResetHistogramEXT) (GLenum target);
+  void (APIENTRY *ResetMinmaxEXT) (GLenum target);
+  void (APIENTRY *ConvolutionFilter1DEXT) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *image);
+  void (APIENTRY *ConvolutionFilter2DEXT) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *image);
+  void (APIENTRY *ConvolutionParameterfEXT) (GLenum target, GLenum pname, GLfloat params);
+  void (APIENTRY *ConvolutionParameterfvEXT) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *ConvolutionParameteriEXT) (GLenum target, GLenum pname, GLint params);
+  void (APIENTRY *ConvolutionParameterivEXT) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *CopyConvolutionFilter1DEXT) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *CopyConvolutionFilter2DEXT) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height);
+  void (APIENTRY *GetConvolutionFilterEXT) (GLenum target, GLenum format, GLenum type, GLvoid *image);
+  void (APIENTRY *GetConvolutionParameterfvEXT) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetConvolutionParameterivEXT) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetSeparableFilterEXT) (GLenum target, GLenum format, GLenum type, GLvoid *row, GLvoid *column, GLvoid *span);
+  void (APIENTRY *SeparableFilter2DEXT) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *row, const GLvoid *column);
+  void (APIENTRY *ColorTableSGI) (GLenum target, GLenum internalformat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+  void (APIENTRY *ColorTableParameterfvSGI) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *ColorTableParameterivSGI) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *CopyColorTableSGI) (GLenum target, GLenum internalformat, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *GetColorTableSGI) (GLenum target, GLenum format, GLenum type, GLvoid *table);
+  void (APIENTRY *GetColorTableParameterfvSGI) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetColorTableParameterivSGI) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *PixelTexGenSGIX) (GLenum mode);
+  void (APIENTRY *PixelTexGenParameteriSGIS) (GLenum pname, GLint param);
+  void (APIENTRY *PixelTexGenParameterivSGIS) (GLenum pname, const GLint *params);
+  void (APIENTRY *PixelTexGenParameterfSGIS) (GLenum pname, GLfloat param);
+  void (APIENTRY *PixelTexGenParameterfvSGIS) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *GetPixelTexGenParameterivSGIS) (GLenum pname, GLint *params);
+  void (APIENTRY *GetPixelTexGenParameterfvSGIS) (GLenum pname, GLfloat *params);
+  void (APIENTRY *TexImage4DSGIS) (GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLint border, GLenum format, GLenum type, const GLvoid *pixels);
+  void (APIENTRY *TexSubImage4DSGIS) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint woffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei size4d, GLenum format, GLenum type, const GLvoid *pixels);
+  GLboolean (APIENTRY *AreTexturesResidentEXT) (GLsizei n, const GLuint *textures, GLboolean *residences);
+  void (APIENTRY *BindTextureEXT) (GLenum target, GLuint texture);
+  void (APIENTRY *DeleteTexturesEXT) (GLsizei n, const GLuint *textures);
+  void (APIENTRY *GenTexturesEXT) (GLsizei n, GLuint *textures);
+  GLboolean (APIENTRY *IsTextureEXT) (GLuint texture);
+  void (APIENTRY *PrioritizeTexturesEXT) (GLsizei n, const GLuint *textures, const GLclampf *priorities);
+  void (APIENTRY *DetailTexFuncSGIS) (GLenum target, GLsizei n, const GLfloat *points);
+  void (APIENTRY *GetDetailTexFuncSGIS) (GLenum target, GLfloat *points);
+  void (APIENTRY *SharpenTexFuncSGIS) (GLenum target, GLsizei n, const GLfloat *points);
+  void (APIENTRY *GetSharpenTexFuncSGIS) (GLenum target, GLfloat *points);
+  void (APIENTRY *SampleMaskSGIS) (GLclampf value, GLboolean invert);
+  void (APIENTRY *SamplePatternSGIS) (GLenum pattern);
+  void (APIENTRY *ArrayElementEXT) (GLint i);
+  void (APIENTRY *ColorPointerEXT) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  void (APIENTRY *DrawArraysEXT) (GLenum mode, GLint first, GLsizei count);
+  void (APIENTRY *EdgeFlagPointerEXT) (GLsizei stride, GLsizei count, const GLboolean *pointer);
+  void (APIENTRY *GetPointervEXT) (GLenum pname, GLvoid* *params);
+  void (APIENTRY *IndexPointerEXT) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  void (APIENTRY *NormalPointerEXT) (GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  void (APIENTRY *TexCoordPointerEXT) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  void (APIENTRY *VertexPointerEXT) (GLint size, GLenum type, GLsizei stride, GLsizei count, const GLvoid *pointer);
+  void (APIENTRY *BlendEquationEXT) (GLenum mode);
+  void (APIENTRY *SpriteParameterfSGIX) (GLenum pname, GLfloat param);
+  void (APIENTRY *SpriteParameterfvSGIX) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *SpriteParameteriSGIX) (GLenum pname, GLint param);
+  void (APIENTRY *SpriteParameterivSGIX) (GLenum pname, const GLint *params);
+  void (APIENTRY *PointParameterfEXT) (GLenum pname, GLfloat param);
+  void (APIENTRY *PointParameterfvEXT) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *PointParameterfSGIS) (GLenum pname, GLfloat param);
+  void (APIENTRY *PointParameterfvSGIS) (GLenum pname, const GLfloat *params);
+  GLint (APIENTRY *GetInstrumentsSGIX) (void);
+  void (APIENTRY *InstrumentsBufferSGIX) (GLsizei size, GLint *buffer);
+  GLint (APIENTRY *PollInstrumentsSGIX) (GLint *marker_p);
+  void (APIENTRY *ReadInstrumentsSGIX) (GLint marker);
+  void (APIENTRY *StartInstrumentsSGIX) (void);
+  void (APIENTRY *StopInstrumentsSGIX) (GLint marker);
+  void (APIENTRY *FrameZoomSGIX) (GLint factor);
+  void (APIENTRY *TagSampleBufferSGIX) (void);
+  void (APIENTRY *DeformationMap3dSGIX) (GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, GLdouble w1, GLdouble w2, GLint wstride, GLint worder, const GLdouble *points);
+  void (APIENTRY *DeformationMap3fSGIX) (GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, GLfloat w1, GLfloat w2, GLint wstride, GLint worder, const GLfloat *points);
+  void (APIENTRY *DeformSGIX) (GLbitfield mask);
+  void (APIENTRY *LoadIdentityDeformationMapSGIX) (GLbitfield mask);
+  void (APIENTRY *ReferencePlaneSGIX) (const GLdouble *equation);
+  void (APIENTRY *FlushRasterSGIX) (void);
+  void (APIENTRY *FogFuncSGIS) (GLsizei n, const GLfloat *points);
+  void (APIENTRY *GetFogFuncSGIS) (GLfloat *points);
+  void (APIENTRY *ImageTransformParameteriHP) (GLenum target, GLenum pname, GLint param);
+  void (APIENTRY *ImageTransformParameterfHP) (GLenum target, GLenum pname, GLfloat param);
+  void (APIENTRY *ImageTransformParameterivHP) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *ImageTransformParameterfvHP) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *GetImageTransformParameterivHP) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetImageTransformParameterfvHP) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *ColorSubTableEXT) (GLenum target, GLsizei start, GLsizei count, GLenum format, GLenum type, const GLvoid *data);
+  void (APIENTRY *CopyColorSubTableEXT) (GLenum target, GLsizei start, GLint x, GLint y, GLsizei width);
+  void (APIENTRY *HintPGI) (GLenum target, GLint mode);
+  void (APIENTRY *ColorTableEXT) (GLenum target, GLenum internalFormat, GLsizei width, GLenum format, GLenum type, const GLvoid *table);
+  void (APIENTRY *GetColorTableEXT) (GLenum target, GLenum format, GLenum type, GLvoid *data);
+  void (APIENTRY *GetColorTableParameterivEXT) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetColorTableParameterfvEXT) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetListParameterfvSGIX) (GLuint list, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetListParameterivSGIX) (GLuint list, GLenum pname, GLint *params);
+  void (APIENTRY *ListParameterfSGIX) (GLuint list, GLenum pname, GLfloat param);
+  void (APIENTRY *ListParameterfvSGIX) (GLuint list, GLenum pname, const GLfloat *params);
+  void (APIENTRY *ListParameteriSGIX) (GLuint list, GLenum pname, GLint param);
+  void (APIENTRY *ListParameterivSGIX) (GLuint list, GLenum pname, const GLint *params);
+  void (APIENTRY *IndexMaterialEXT) (GLenum face, GLenum mode);
+  void (APIENTRY *IndexFuncEXT) (GLenum func, GLclampf ref);
+  void (APIENTRY *LockArraysEXT) (GLint first, GLsizei count);
+  void (APIENTRY *UnlockArraysEXT) (void);
+  void (APIENTRY *CullParameterdvEXT) (GLenum pname, GLdouble *params);
+  void (APIENTRY *CullParameterfvEXT) (GLenum pname, GLfloat *params);
+  void (APIENTRY *FragmentColorMaterialSGIX) (GLenum face, GLenum mode);
+  void (APIENTRY *FragmentLightfSGIX) (GLenum light, GLenum pname, GLfloat param);
+  void (APIENTRY *FragmentLightfvSGIX) (GLenum light, GLenum pname, const GLfloat *params);
+  void (APIENTRY *FragmentLightiSGIX) (GLenum light, GLenum pname, GLint param);
+  void (APIENTRY *FragmentLightivSGIX) (GLenum light, GLenum pname, const GLint *params);
+  void (APIENTRY *FragmentLightModelfSGIX) (GLenum pname, GLfloat param);
+  void (APIENTRY *FragmentLightModelfvSGIX) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *FragmentLightModeliSGIX) (GLenum pname, GLint param);
+  void (APIENTRY *FragmentLightModelivSGIX) (GLenum pname, const GLint *params);
+  void (APIENTRY *FragmentMaterialfSGIX) (GLenum face, GLenum pname, GLfloat param);
+  void (APIENTRY *FragmentMaterialfvSGIX) (GLenum face, GLenum pname, const GLfloat *params);
+  void (APIENTRY *FragmentMaterialiSGIX) (GLenum face, GLenum pname, GLint param);
+  void (APIENTRY *FragmentMaterialivSGIX) (GLenum face, GLenum pname, const GLint *params);
+  void (APIENTRY *GetFragmentLightfvSGIX) (GLenum light, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetFragmentLightivSGIX) (GLenum light, GLenum pname, GLint *params);
+  void (APIENTRY *GetFragmentMaterialfvSGIX) (GLenum face, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetFragmentMaterialivSGIX) (GLenum face, GLenum pname, GLint *params);
+  void (APIENTRY *LightEnviSGIX) (GLenum pname, GLint param);
+  void (APIENTRY *DrawRangeElementsEXT) (GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices);
+  void (APIENTRY *ApplyTextureEXT) (GLenum mode);
+  void (APIENTRY *TextureLightEXT) (GLenum pname);
+  void (APIENTRY *TextureMaterialEXT) (GLenum face, GLenum mode);
+  void (APIENTRY *AsyncMarkerSGIX) (GLuint marker);
+  GLint (APIENTRY *FinishAsyncSGIX) (GLuint *markerp);
+  GLint (APIENTRY *PollAsyncSGIX) (GLuint *markerp);
+  GLuint (APIENTRY *GenAsyncMarkersSGIX) (GLsizei range);
+  void (APIENTRY *DeleteAsyncMarkersSGIX) (GLuint marker, GLsizei range);
+  GLboolean (APIENTRY *IsAsyncMarkerSGIX) (GLuint marker);
+  void (APIENTRY *VertexPointervINTEL) (GLint size, GLenum type, const GLvoid* *pointer);
+  void (APIENTRY *NormalPointervINTEL) (GLenum type, const GLvoid* *pointer);
+  void (APIENTRY *ColorPointervINTEL) (GLint size, GLenum type, const GLvoid* *pointer);
+  void (APIENTRY *TexCoordPointervINTEL) (GLint size, GLenum type, const GLvoid* *pointer);
+  void (APIENTRY *PixelTransformParameteriEXT) (GLenum target, GLenum pname, GLint param);
+  void (APIENTRY *PixelTransformParameterfEXT) (GLenum target, GLenum pname, GLfloat param);
+  void (APIENTRY *PixelTransformParameterivEXT) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *PixelTransformParameterfvEXT) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *SecondaryColor3bEXT) (GLbyte red, GLbyte green, GLbyte blue);
+  void (APIENTRY *SecondaryColor3bvEXT) (const GLbyte *v);
+  void (APIENTRY *SecondaryColor3dEXT) (GLdouble red, GLdouble green, GLdouble blue);
+  void (APIENTRY *SecondaryColor3dvEXT) (const GLdouble *v);
+  void (APIENTRY *SecondaryColor3fEXT) (GLfloat red, GLfloat green, GLfloat blue);
+  void (APIENTRY *SecondaryColor3fvEXT) (const GLfloat *v);
+  void (APIENTRY *SecondaryColor3iEXT) (GLint red, GLint green, GLint blue);
+  void (APIENTRY *SecondaryColor3ivEXT) (const GLint *v);
+  void (APIENTRY *SecondaryColor3sEXT) (GLshort red, GLshort green, GLshort blue);
+  void (APIENTRY *SecondaryColor3svEXT) (const GLshort *v);
+  void (APIENTRY *SecondaryColor3ubEXT) (GLubyte red, GLubyte green, GLubyte blue);
+  void (APIENTRY *SecondaryColor3ubvEXT) (const GLubyte *v);
+  void (APIENTRY *SecondaryColor3uiEXT) (GLuint red, GLuint green, GLuint blue);
+  void (APIENTRY *SecondaryColor3uivEXT) (const GLuint *v);
+  void (APIENTRY *SecondaryColor3usEXT) (GLushort red, GLushort green, GLushort blue);
+  void (APIENTRY *SecondaryColor3usvEXT) (const GLushort *v);
+  void (APIENTRY *SecondaryColorPointerEXT) (GLint size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *TextureNormalEXT) (GLenum mode);
+  void (APIENTRY *MultiDrawArraysEXT) (GLenum mode, GLint *first, GLsizei *count, GLsizei primcount);
+  void (APIENTRY *MultiDrawElementsEXT) (GLenum mode, const GLsizei *count, GLenum type, const GLvoid* *indices, GLsizei primcount);
+  void (APIENTRY *FogCoordfEXT) (GLfloat coord);
+  void (APIENTRY *FogCoordfvEXT) (const GLfloat *coord);
+  void (APIENTRY *FogCoorddEXT) (GLdouble coord);
+  void (APIENTRY *FogCoorddvEXT) (const GLdouble *coord);
+  void (APIENTRY *FogCoordPointerEXT) (GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *Tangent3bEXT) (GLbyte tx, GLbyte ty, GLbyte tz);
+  void (APIENTRY *Tangent3bvEXT) (const GLbyte *v);
+  void (APIENTRY *Tangent3dEXT) (GLdouble tx, GLdouble ty, GLdouble tz);
+  void (APIENTRY *Tangent3dvEXT) (const GLdouble *v);
+  void (APIENTRY *Tangent3fEXT) (GLfloat tx, GLfloat ty, GLfloat tz);
+  void (APIENTRY *Tangent3fvEXT) (const GLfloat *v);
+  void (APIENTRY *Tangent3iEXT) (GLint tx, GLint ty, GLint tz);
+  void (APIENTRY *Tangent3ivEXT) (const GLint *v);
+  void (APIENTRY *Tangent3sEXT) (GLshort tx, GLshort ty, GLshort tz);
+  void (APIENTRY *Tangent3svEXT) (const GLshort *v);
+  void (APIENTRY *Binormal3bEXT) (GLbyte bx, GLbyte by, GLbyte bz);
+  void (APIENTRY *Binormal3bvEXT) (const GLbyte *v);
+  void (APIENTRY *Binormal3dEXT) (GLdouble bx, GLdouble by, GLdouble bz);
+  void (APIENTRY *Binormal3dvEXT) (const GLdouble *v);
+  void (APIENTRY *Binormal3fEXT) (GLfloat bx, GLfloat by, GLfloat bz);
+  void (APIENTRY *Binormal3fvEXT) (const GLfloat *v);
+  void (APIENTRY *Binormal3iEXT) (GLint bx, GLint by, GLint bz);
+  void (APIENTRY *Binormal3ivEXT) (const GLint *v);
+  void (APIENTRY *Binormal3sEXT) (GLshort bx, GLshort by, GLshort bz);
+  void (APIENTRY *Binormal3svEXT) (const GLshort *v);
+  void (APIENTRY *TangentPointerEXT) (GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *BinormalPointerEXT) (GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *FinishTextureSUNX) (void);
+  void (APIENTRY *GlobalAlphaFactorbSUN) (GLbyte factor);
+  void (APIENTRY *GlobalAlphaFactorsSUN) (GLshort factor);
+  void (APIENTRY *GlobalAlphaFactoriSUN) (GLint factor);
+  void (APIENTRY *GlobalAlphaFactorfSUN) (GLfloat factor);
+  void (APIENTRY *GlobalAlphaFactordSUN) (GLdouble factor);
+  void (APIENTRY *GlobalAlphaFactorubSUN) (GLubyte factor);
+  void (APIENTRY *GlobalAlphaFactorusSUN) (GLushort factor);
+  void (APIENTRY *GlobalAlphaFactoruiSUN) (GLuint factor);
+  void (APIENTRY *ReplacementCodeuiSUN) (GLuint code);
+  void (APIENTRY *ReplacementCodeusSUN) (GLushort code);
+  void (APIENTRY *ReplacementCodeubSUN) (GLubyte code);
+  void (APIENTRY *ReplacementCodeuivSUN) (const GLuint *code);
+  void (APIENTRY *ReplacementCodeusvSUN) (const GLushort *code);
+  void (APIENTRY *ReplacementCodeubvSUN) (const GLubyte *code);
+  void (APIENTRY *ReplacementCodePointerSUN) (GLenum type, GLsizei stride, const GLvoid* *pointer);
+  void (APIENTRY *Color4ubVertex2fSUN) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y);
+  void (APIENTRY *Color4ubVertex2fvSUN) (const GLubyte *c, const GLfloat *v);
+  void (APIENTRY *Color4ubVertex3fSUN) (GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *Color4ubVertex3fvSUN) (const GLubyte *c, const GLfloat *v);
+  void (APIENTRY *Color3fVertex3fSUN) (GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *Color3fVertex3fvSUN) (const GLfloat *c, const GLfloat *v);
+  void (APIENTRY *Normal3fVertex3fSUN) (GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *Normal3fVertex3fvSUN) (const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *Color4fNormal3fVertex3fSUN) (GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *Color4fNormal3fVertex3fvSUN) (const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *TexCoord2fVertex3fSUN) (GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *TexCoord2fVertex3fvSUN) (const GLfloat *tc, const GLfloat *v);
+  void (APIENTRY *TexCoord4fVertex4fSUN) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *TexCoord4fVertex4fvSUN) (const GLfloat *tc, const GLfloat *v);
+  void (APIENTRY *TexCoord2fColor4ubVertex3fSUN) (GLfloat s, GLfloat t, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *TexCoord2fColor4ubVertex3fvSUN) (const GLfloat *tc, const GLubyte *c, const GLfloat *v);
+  void (APIENTRY *TexCoord2fColor3fVertex3fSUN) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *TexCoord2fColor3fVertex3fvSUN) (const GLfloat *tc, const GLfloat *c, const GLfloat *v);
+  void (APIENTRY *TexCoord2fNormal3fVertex3fSUN) (GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *TexCoord2fNormal3fVertex3fvSUN) (const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *TexCoord2fColor4fNormal3fVertex3fSUN) (GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *TexCoord2fColor4fNormal3fVertex3fvSUN) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *TexCoord4fColor4fNormal3fVertex4fSUN) (GLfloat s, GLfloat t, GLfloat p, GLfloat q, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *TexCoord4fColor4fNormal3fVertex4fvSUN) (const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiVertex3fSUN) (GLuint rc, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiVertex3fvSUN) (const GLuint *rc, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiColor4ubVertex3fSUN) (GLuint rc, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiColor4ubVertex3fvSUN) (const GLuint *rc, const GLubyte *c, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiColor3fVertex3fSUN) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiColor3fVertex3fvSUN) (const GLuint *rc, const GLfloat *c, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiNormal3fVertex3fSUN) (GLuint rc, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiNormal3fVertex3fvSUN) (const GLuint *rc, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiColor4fNormal3fVertex3fSUN) (GLuint rc, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiColor4fNormal3fVertex3fvSUN) (const GLuint *rc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiTexCoord2fVertex3fSUN) (GLuint rc, GLfloat s, GLfloat t, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiTexCoord2fVertex3fvSUN) (const GLuint *rc, const GLfloat *tc, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiTexCoord2fNormal3fVertex3fSUN) (GLuint rc, GLfloat s, GLfloat t, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN) (const GLuint *rc, const GLfloat *tc, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *ReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN) (GLuint rc, GLfloat s, GLfloat t, GLfloat r, GLfloat g, GLfloat b, GLfloat a, GLfloat nx, GLfloat ny, GLfloat nz, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *ReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN) (const GLuint *rc, const GLfloat *tc, const GLfloat *c, const GLfloat *n, const GLfloat *v);
+  void (APIENTRY *BlendFuncSeparateEXT) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+  void (APIENTRY *BlendFuncSeparateINGR) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
+  void (APIENTRY *VertexWeightfEXT) (GLfloat weight);
+  void (APIENTRY *VertexWeightfvEXT) (const GLfloat *weight);
+  void (APIENTRY *VertexWeightPointerEXT) (GLsizei size, GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *FlushVertexArrayRangeNV) (void);
+  void (APIENTRY *VertexArrayRangeNV) (GLsizei length, const GLvoid *pointer);
+  void (APIENTRY *CombinerParameterfvNV) (GLenum pname, const GLfloat *params);
+  void (APIENTRY *CombinerParameterfNV) (GLenum pname, GLfloat param);
+  void (APIENTRY *CombinerParameterivNV) (GLenum pname, const GLint *params);
+  void (APIENTRY *CombinerParameteriNV) (GLenum pname, GLint param);
+  void (APIENTRY *CombinerInputNV) (GLenum stage, GLenum portion, GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+  void (APIENTRY *CombinerOutputNV) (GLenum stage, GLenum portion, GLenum abOutput, GLenum cdOutput, GLenum sumOutput, GLenum scale, GLenum bias, GLboolean abDotProduct, GLboolean cdDotProduct, GLboolean muxSum);
+  void (APIENTRY *FinalCombinerInputNV) (GLenum variable, GLenum input, GLenum mapping, GLenum componentUsage);
+  void (APIENTRY *GetCombinerInputParameterfvNV) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetCombinerInputParameterivNV) (GLenum stage, GLenum portion, GLenum variable, GLenum pname, GLint *params);
+  void (APIENTRY *GetCombinerOutputParameterfvNV) (GLenum stage, GLenum portion, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetCombinerOutputParameterivNV) (GLenum stage, GLenum portion, GLenum pname, GLint *params);
+  void (APIENTRY *GetFinalCombinerInputParameterfvNV) (GLenum variable, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetFinalCombinerInputParameterivNV) (GLenum variable, GLenum pname, GLint *params);
+  void (APIENTRY *ResizeBuffersMESA) (void);
+  void (APIENTRY *WindowPos2dMESA) (GLdouble x, GLdouble y);
+  void (APIENTRY *WindowPos2dvMESA) (const GLdouble *v);
+  void (APIENTRY *WindowPos2fMESA) (GLfloat x, GLfloat y);
+  void (APIENTRY *WindowPos2fvMESA) (const GLfloat *v);
+  void (APIENTRY *WindowPos2iMESA) (GLint x, GLint y);
+  void (APIENTRY *WindowPos2ivMESA) (const GLint *v);
+  void (APIENTRY *WindowPos2sMESA) (GLshort x, GLshort y);
+  void (APIENTRY *WindowPos2svMESA) (const GLshort *v);
+  void (APIENTRY *WindowPos3dMESA) (GLdouble x, GLdouble y, GLdouble z);
+  void (APIENTRY *WindowPos3dvMESA) (const GLdouble *v);
+  void (APIENTRY *WindowPos3fMESA) (GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *WindowPos3fvMESA) (const GLfloat *v);
+  void (APIENTRY *WindowPos3iMESA) (GLint x, GLint y, GLint z);
+  void (APIENTRY *WindowPos3ivMESA) (const GLint *v);
+  void (APIENTRY *WindowPos3sMESA) (GLshort x, GLshort y, GLshort z);
+  void (APIENTRY *WindowPos3svMESA) (const GLshort *v);
+  void (APIENTRY *WindowPos4dMESA) (GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *WindowPos4dvMESA) (const GLdouble *v);
+  void (APIENTRY *WindowPos4fMESA) (GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *WindowPos4fvMESA) (const GLfloat *v);
+  void (APIENTRY *WindowPos4iMESA) (GLint x, GLint y, GLint z, GLint w);
+  void (APIENTRY *WindowPos4ivMESA) (const GLint *v);
+  void (APIENTRY *WindowPos4sMESA) (GLshort x, GLshort y, GLshort z, GLshort w);
+  void (APIENTRY *WindowPos4svMESA) (const GLshort *v);
+  void (APIENTRY *MultiModeDrawArraysIBM) (const GLenum *mode, const GLint *first, const GLsizei *count, GLsizei primcount, GLint modestride);
+  void (APIENTRY *MultiModeDrawElementsIBM) (const GLenum *mode, const GLsizei *count, GLenum type, const GLvoid* const *indices, GLsizei primcount, GLint modestride);
+  void (APIENTRY *ColorPointerListIBM) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *SecondaryColorPointerListIBM) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *EdgeFlagPointerListIBM) (GLint stride, const GLboolean* *pointer, GLint ptrstride);
+  void (APIENTRY *FogCoordPointerListIBM) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *IndexPointerListIBM) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *NormalPointerListIBM) (GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *TexCoordPointerListIBM) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *VertexPointerListIBM) (GLint size, GLenum type, GLint stride, const GLvoid* *pointer, GLint ptrstride);
+  void (APIENTRY *TbufferMask3DFX) (GLuint mask);
+  void (APIENTRY *SampleMaskEXT) (GLclampf value, GLboolean invert);
+  void (APIENTRY *SamplePatternEXT) (GLenum pattern);
+  void (APIENTRY *TextureColorMaskSGIS) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha);
+  void (APIENTRY *IglooInterfaceSGIX) (GLenum pname, const GLvoid *params);
+  void (APIENTRY *DeleteFencesNV) (GLsizei n, const GLuint *fences);
+  void (APIENTRY *GenFencesNV) (GLsizei n, GLuint *fences);
+  GLboolean (APIENTRY *IsFenceNV) (GLuint fence);
+  GLboolean (APIENTRY *TestFenceNV) (GLuint fence);
+  void (APIENTRY *GetFenceivNV) (GLuint fence, GLenum pname, GLint *params);
+  void (APIENTRY *FinishFenceNV) (GLuint fence);
+  void (APIENTRY *SetFenceNV) (GLuint fence, GLenum condition);
+  void (APIENTRY *MapControlPointsNV) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLint uorder, GLint vorder, GLboolean packed, const GLvoid *points);
+  void (APIENTRY *MapParameterivNV) (GLenum target, GLenum pname, const GLint *params);
+  void (APIENTRY *MapParameterfvNV) (GLenum target, GLenum pname, const GLfloat *params);
+  void (APIENTRY *GetMapControlPointsNV) (GLenum target, GLuint index, GLenum type, GLsizei ustride, GLsizei vstride, GLboolean packed, GLvoid *points);
+  void (APIENTRY *GetMapParameterivNV) (GLenum target, GLenum pname, GLint *params);
+  void (APIENTRY *GetMapParameterfvNV) (GLenum target, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetMapAttribParameterivNV) (GLenum target, GLuint index, GLenum pname, GLint *params);
+  void (APIENTRY *GetMapAttribParameterfvNV) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+  void (APIENTRY *EvalMapsNV) (GLenum target, GLenum mode);
+  void (APIENTRY *CombinerStageParameterfvNV) (GLenum stage, GLenum pname, const GLfloat *params);
+  void (APIENTRY *GetCombinerStageParameterfvNV) (GLenum stage, GLenum pname, GLfloat *params);
+  GLboolean (APIENTRY *AreProgramsResidentNV) (GLsizei n, const GLuint *programs, GLboolean *residences);
+  void (APIENTRY *BindProgramNV) (GLenum target, GLuint id);
+  void (APIENTRY *DeleteProgramsNV) (GLsizei n, const GLuint *programs);
+  void (APIENTRY *ExecuteProgramNV) (GLenum target, GLuint id, const GLfloat *params);
+  void (APIENTRY *GenProgramsNV) (GLsizei n, GLuint *programs);
+  void (APIENTRY *GetProgramParameterdvNV) (GLenum target, GLuint index, GLenum pname, GLdouble *params);
+  void (APIENTRY *GetProgramParameterfvNV) (GLenum target, GLuint index, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetProgramivNV) (GLuint id, GLenum pname, GLint *params);
+  void (APIENTRY *GetProgramStringNV) (GLuint id, GLenum pname, GLubyte *program);
+  void (APIENTRY *GetTrackMatrixivNV) (GLenum target, GLuint address, GLenum pname, GLint *params);
+  void (APIENTRY *GetVertexAttribdvNV) (GLuint index, GLenum pname, GLdouble *params);
+  void (APIENTRY *GetVertexAttribfvNV) (GLuint index, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetVertexAttribivNV) (GLuint index, GLenum pname, GLint *params);
+  void (APIENTRY *GetVertexAttribPointervNV) (GLuint index, GLenum pname, GLvoid* *pointer);
+  GLboolean (APIENTRY *IsProgramNV) (GLuint id);
+  void (APIENTRY *LoadProgramNV) (GLenum target, GLuint id, GLsizei len, const GLubyte *program);
+  void (APIENTRY *ProgramParameter4dNV) (GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *ProgramParameter4dvNV) (GLenum target, GLuint index, const GLdouble *v);
+  void (APIENTRY *ProgramParameter4fNV) (GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *ProgramParameter4fvNV) (GLenum target, GLuint index, const GLfloat *v);
+  void (APIENTRY *ProgramParameters4dvNV) (GLenum target, GLuint index, GLuint count, const GLdouble *v);
+  void (APIENTRY *ProgramParameters4fvNV) (GLenum target, GLuint index, GLuint count, const GLfloat *v);
+  void (APIENTRY *RequestResidentProgramsNV) (GLsizei n, const GLuint *programs);
+  void (APIENTRY *TrackMatrixNV) (GLenum target, GLuint address, GLenum matrix, GLenum transform);
+  void (APIENTRY *VertexAttribPointerNV) (GLuint index, GLint fsize, GLenum type, GLsizei stride, const GLvoid *pointer);
+  void (APIENTRY *VertexAttrib1dNV) (GLuint index, GLdouble x);
+  void (APIENTRY *VertexAttrib1dvNV) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib1fNV) (GLuint index, GLfloat x);
+  void (APIENTRY *VertexAttrib1fvNV) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib1sNV) (GLuint index, GLshort x);
+  void (APIENTRY *VertexAttrib1svNV) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib2dNV) (GLuint index, GLdouble x, GLdouble y);
+  void (APIENTRY *VertexAttrib2dvNV) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib2fNV) (GLuint index, GLfloat x, GLfloat y);
+  void (APIENTRY *VertexAttrib2fvNV) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib2sNV) (GLuint index, GLshort x, GLshort y);
+  void (APIENTRY *VertexAttrib2svNV) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib3dNV) (GLuint index, GLdouble x, GLdouble y, GLdouble z);
+  void (APIENTRY *VertexAttrib3dvNV) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib3fNV) (GLuint index, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *VertexAttrib3fvNV) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib3sNV) (GLuint index, GLshort x, GLshort y, GLshort z);
+  void (APIENTRY *VertexAttrib3svNV) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib4dNV) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *VertexAttrib4dvNV) (GLuint index, const GLdouble *v);
+  void (APIENTRY *VertexAttrib4fNV) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *VertexAttrib4fvNV) (GLuint index, const GLfloat *v);
+  void (APIENTRY *VertexAttrib4sNV) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w);
+  void (APIENTRY *VertexAttrib4svNV) (GLuint index, const GLshort *v);
+  void (APIENTRY *VertexAttrib4ubNV) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w);
+  void (APIENTRY *VertexAttrib4ubvNV) (GLuint index, const GLubyte *v);
+  void (APIENTRY *VertexAttribs1dvNV) (GLuint index, GLsizei count, const GLdouble *v);
+  void (APIENTRY *VertexAttribs1fvNV) (GLuint index, GLsizei count, const GLfloat *v);
+  void (APIENTRY *VertexAttribs1svNV) (GLuint index, GLsizei count, const GLshort *v);
+  void (APIENTRY *VertexAttribs2dvNV) (GLuint index, GLsizei count, const GLdouble *v);
+  void (APIENTRY *VertexAttribs2fvNV) (GLuint index, GLsizei count, const GLfloat *v);
+  void (APIENTRY *VertexAttribs2svNV) (GLuint index, GLsizei count, const GLshort *v);
+  void (APIENTRY *VertexAttribs3dvNV) (GLuint index, GLsizei count, const GLdouble *v);
+  void (APIENTRY *VertexAttribs3fvNV) (GLuint index, GLsizei count, const GLfloat *v);
+  void (APIENTRY *VertexAttribs3svNV) (GLuint index, GLsizei count, const GLshort *v);
+  void (APIENTRY *VertexAttribs4dvNV) (GLuint index, GLsizei count, const GLdouble *v);
+  void (APIENTRY *VertexAttribs4fvNV) (GLuint index, GLsizei count, const GLfloat *v);
+  void (APIENTRY *VertexAttribs4svNV) (GLuint index, GLsizei count, const GLshort *v);
+  void (APIENTRY *VertexAttribs4ubvNV) (GLuint index, GLsizei count, const GLubyte *v);
+  void (APIENTRY *TexBumpParameterivATI) (GLenum pname, const GLint *param);
+  void (APIENTRY *TexBumpParameterfvATI) (GLenum pname, const GLfloat *param);
+  void (APIENTRY *GetTexBumpParameterivATI) (GLenum pname, GLint *param);
+  void (APIENTRY *GetTexBumpParameterfvATI) (GLenum pname, GLfloat *param);
+  GLuint (APIENTRY *GenFragmentShadersATI) (GLuint range);
+  void (APIENTRY *BindFragmentShaderATI) (GLuint id);
+  void (APIENTRY *DeleteFragmentShaderATI) (GLuint id);
+  void (APIENTRY *BeginFragmentShaderATI) (void);
+  void (APIENTRY *EndFragmentShaderATI) (void);
+  void (APIENTRY *PassTexCoordATI) (GLuint dst, GLuint coord, GLenum swizzle);
+  void (APIENTRY *SampleMapATI) (GLuint dst, GLuint interp, GLenum swizzle);
+  void (APIENTRY *ColorFragmentOp1ATI) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+  void (APIENTRY *ColorFragmentOp2ATI) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+  void (APIENTRY *ColorFragmentOp3ATI) (GLenum op, GLuint dst, GLuint dstMask, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+  void (APIENTRY *AlphaFragmentOp1ATI) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod);
+  void (APIENTRY *AlphaFragmentOp2ATI) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod);
+  void (APIENTRY *AlphaFragmentOp3ATI) (GLenum op, GLuint dst, GLuint dstMod, GLuint arg1, GLuint arg1Rep, GLuint arg1Mod, GLuint arg2, GLuint arg2Rep, GLuint arg2Mod, GLuint arg3, GLuint arg3Rep, GLuint arg3Mod);
+  void (APIENTRY *SetFragmentShaderConstantATI) (GLuint dst, const GLfloat *value);
+  void (APIENTRY *PNTrianglesiATI) (GLenum pname, GLint param);
+  void (APIENTRY *PNTrianglesfATI) (GLenum pname, GLfloat param);
+  GLuint (APIENTRY *NewObjectBufferATI) (GLsizei size, const GLvoid *pointer, GLenum usage);
+  GLboolean (APIENTRY *IsObjectBufferATI) (GLuint buffer);
+  void (APIENTRY *UpdateObjectBufferATI) (GLuint buffer, GLuint offset, GLsizei size, const GLvoid *pointer, GLenum preserve);
+  void (APIENTRY *GetObjectBufferfvATI) (GLuint buffer, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetObjectBufferivATI) (GLuint buffer, GLenum pname, GLint *params);
+  void (APIENTRY *FreeObjectBufferATI) (GLuint buffer);
+  void (APIENTRY *ArrayObjectATI) (GLenum array, GLint size, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+  void (APIENTRY *GetArrayObjectfvATI) (GLenum array, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetArrayObjectivATI) (GLenum array, GLenum pname, GLint *params);
+  void (APIENTRY *VariantArrayObjectATI) (GLuint id, GLenum type, GLsizei stride, GLuint buffer, GLuint offset);
+  void (APIENTRY *GetVariantArrayObjectfvATI) (GLuint id, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetVariantArrayObjectivATI) (GLuint id, GLenum pname, GLint *params);
+  void (APIENTRY *BeginVertexShaderEXT) (void);
+  void (APIENTRY *EndVertexShaderEXT) (void);
+  void (APIENTRY *BindVertexShaderEXT) (GLuint id);
+  GLuint (APIENTRY *GenVertexShadersEXT) (GLuint range);
+  void (APIENTRY *DeleteVertexShaderEXT) (GLuint id);
+  void (APIENTRY *ShaderOp1EXT) (GLenum op, GLuint res, GLuint arg1);
+  void (APIENTRY *ShaderOp2EXT) (GLenum op, GLuint res, GLuint arg1, GLuint arg2);
+  void (APIENTRY *ShaderOp3EXT) (GLenum op, GLuint res, GLuint arg1, GLuint arg2, GLuint arg3);
+  void (APIENTRY *SwizzleEXT) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+  void (APIENTRY *WriteMaskEXT) (GLuint res, GLuint in, GLenum outX, GLenum outY, GLenum outZ, GLenum outW);
+  void (APIENTRY *InsertComponentEXT) (GLuint res, GLuint src, GLuint num);
+  void (APIENTRY *ExtractComponentEXT) (GLuint res, GLuint src, GLuint num);
+  GLuint (APIENTRY *GenSymbolsEXT) (GLenum datatype, GLenum storagetype, GLenum range, GLuint components);
+  void (APIENTRY *SetInvariantEXT) (GLuint id, GLenum type, const GLvoid *addr);
+  void (APIENTRY *SetLocalConstantEXT) (GLuint id, GLenum type, const GLvoid *addr);
+  void (APIENTRY *VariantbvEXT) (GLuint id, const GLbyte *addr);
+  void (APIENTRY *VariantsvEXT) (GLuint id, const GLshort *addr);
+  void (APIENTRY *VariantivEXT) (GLuint id, const GLint *addr);
+  void (APIENTRY *VariantfvEXT) (GLuint id, const GLfloat *addr);
+  void (APIENTRY *VariantdvEXT) (GLuint id, const GLdouble *addr);
+  void (APIENTRY *VariantubvEXT) (GLuint id, const GLubyte *addr);
+  void (APIENTRY *VariantusvEXT) (GLuint id, const GLushort *addr);
+  void (APIENTRY *VariantuivEXT) (GLuint id, const GLuint *addr);
+  void (APIENTRY *VariantPointerEXT) (GLuint id, GLenum type, GLuint stride, const GLvoid *addr);
+  void (APIENTRY *EnableVariantClientStateEXT) (GLuint id);
+  void (APIENTRY *DisableVariantClientStateEXT) (GLuint id);
+  GLuint (APIENTRY *BindLightParameterEXT) (GLenum light, GLenum value);
+  GLuint (APIENTRY *BindMaterialParameterEXT) (GLenum face, GLenum value);
+  GLuint (APIENTRY *BindTexGenParameterEXT) (GLenum unit, GLenum coord, GLenum value);
+  GLuint (APIENTRY *BindTextureUnitParameterEXT) (GLenum unit, GLenum value);
+  GLuint (APIENTRY *BindParameterEXT) (GLenum value);
+  GLboolean (APIENTRY *IsVariantEnabledEXT) (GLuint id, GLenum cap);
+  void (APIENTRY *GetVariantBooleanvEXT) (GLuint id, GLenum value, GLboolean *data);
+  void (APIENTRY *GetVariantIntegervEXT) (GLuint id, GLenum value, GLint *data);
+  void (APIENTRY *GetVariantFloatvEXT) (GLuint id, GLenum value, GLfloat *data);
+  void (APIENTRY *GetVariantPointervEXT) (GLuint id, GLenum value, GLvoid* *data);
+  void (APIENTRY *GetInvariantBooleanvEXT) (GLuint id, GLenum value, GLboolean *data);
+  void (APIENTRY *GetInvariantIntegervEXT) (GLuint id, GLenum value, GLint *data);
+  void (APIENTRY *GetInvariantFloatvEXT) (GLuint id, GLenum value, GLfloat *data);
+  void (APIENTRY *GetLocalConstantBooleanvEXT) (GLuint id, GLenum value, GLboolean *data);
+  void (APIENTRY *GetLocalConstantIntegervEXT) (GLuint id, GLenum value, GLint *data);
+  void (APIENTRY *GetLocalConstantFloatvEXT) (GLuint id, GLenum value, GLfloat *data);
+  void (APIENTRY *VertexStream1sATI) (GLenum stream, GLshort x);
+  void (APIENTRY *VertexStream1svATI) (GLenum stream, const GLshort *coords);
+  void (APIENTRY *VertexStream1iATI) (GLenum stream, GLint x);
+  void (APIENTRY *VertexStream1ivATI) (GLenum stream, const GLint *coords);
+  void (APIENTRY *VertexStream1fATI) (GLenum stream, GLfloat x);
+  void (APIENTRY *VertexStream1fvATI) (GLenum stream, const GLfloat *coords);
+  void (APIENTRY *VertexStream1dATI) (GLenum stream, GLdouble x);
+  void (APIENTRY *VertexStream1dvATI) (GLenum stream, const GLdouble *coords);
+  void (APIENTRY *VertexStream2sATI) (GLenum stream, GLshort x, GLshort y);
+  void (APIENTRY *VertexStream2svATI) (GLenum stream, const GLshort *coords);
+  void (APIENTRY *VertexStream2iATI) (GLenum stream, GLint x, GLint y);
+  void (APIENTRY *VertexStream2ivATI) (GLenum stream, const GLint *coords);
+  void (APIENTRY *VertexStream2fATI) (GLenum stream, GLfloat x, GLfloat y);
+  void (APIENTRY *VertexStream2fvATI) (GLenum stream, const GLfloat *coords);
+  void (APIENTRY *VertexStream2dATI) (GLenum stream, GLdouble x, GLdouble y);
+  void (APIENTRY *VertexStream2dvATI) (GLenum stream, const GLdouble *coords);
+  void (APIENTRY *VertexStream3sATI) (GLenum stream, GLshort x, GLshort y, GLshort z);
+  void (APIENTRY *VertexStream3svATI) (GLenum stream, const GLshort *coords);
+  void (APIENTRY *VertexStream3iATI) (GLenum stream, GLint x, GLint y, GLint z);
+  void (APIENTRY *VertexStream3ivATI) (GLenum stream, const GLint *coords);
+  void (APIENTRY *VertexStream3fATI) (GLenum stream, GLfloat x, GLfloat y, GLfloat z);
+  void (APIENTRY *VertexStream3fvATI) (GLenum stream, const GLfloat *coords);
+  void (APIENTRY *VertexStream3dATI) (GLenum stream, GLdouble x, GLdouble y, GLdouble z);
+  void (APIENTRY *VertexStream3dvATI) (GLenum stream, const GLdouble *coords);
+  void (APIENTRY *VertexStream4sATI) (GLenum stream, GLshort x, GLshort y, GLshort z, GLshort w);
+  void (APIENTRY *VertexStream4svATI) (GLenum stream, const GLshort *coords);
+  void (APIENTRY *VertexStream4iATI) (GLenum stream, GLint x, GLint y, GLint z, GLint w);
+  void (APIENTRY *VertexStream4ivATI) (GLenum stream, const GLint *coords);
+  void (APIENTRY *VertexStream4fATI) (GLenum stream, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *VertexStream4fvATI) (GLenum stream, const GLfloat *coords);
+  void (APIENTRY *VertexStream4dATI) (GLenum stream, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *VertexStream4dvATI) (GLenum stream, const GLdouble *coords);
+  void (APIENTRY *NormalStream3bATI) (GLenum stream, GLbyte nx, GLbyte ny, GLbyte nz);
+  void (APIENTRY *NormalStream3bvATI) (GLenum stream, const GLbyte *coords);
+  void (APIENTRY *NormalStream3sATI) (GLenum stream, GLshort nx, GLshort ny, GLshort nz);
+  void (APIENTRY *NormalStream3svATI) (GLenum stream, const GLshort *coords);
+  void (APIENTRY *NormalStream3iATI) (GLenum stream, GLint nx, GLint ny, GLint nz);
+  void (APIENTRY *NormalStream3ivATI) (GLenum stream, const GLint *coords);
+  void (APIENTRY *NormalStream3fATI) (GLenum stream, GLfloat nx, GLfloat ny, GLfloat nz);
+  void (APIENTRY *NormalStream3fvATI) (GLenum stream, const GLfloat *coords);
+  void (APIENTRY *NormalStream3dATI) (GLenum stream, GLdouble nx, GLdouble ny, GLdouble nz);
+  void (APIENTRY *NormalStream3dvATI) (GLenum stream, const GLdouble *coords);
+  void (APIENTRY *ClientActiveVertexStreamATI) (GLenum stream);
+  void (APIENTRY *VertexBlendEnviATI) (GLenum pname, GLint param);
+  void (APIENTRY *VertexBlendEnvfATI) (GLenum pname, GLfloat param);
+  void (APIENTRY *ElementPointerATI) (GLenum type, const GLvoid *pointer);
+  void (APIENTRY *DrawElementArrayATI) (GLenum mode, GLsizei count);
+  void (APIENTRY *DrawRangeElementArrayATI) (GLenum mode, GLuint start, GLuint end, GLsizei count);
+  void (APIENTRY *DrawMeshArraysSUN) (GLenum mode, GLint first, GLsizei count, GLsizei width);
+  void (APIENTRY *GenOcclusionQueriesNV) (GLsizei n, GLuint *ids);
+  void (APIENTRY *DeleteOcclusionQueriesNV) (GLsizei n, const GLuint *ids);
+  GLboolean (APIENTRY *IsOcclusionQueryNV) (GLuint id);
+  void (APIENTRY *BeginOcclusionQueryNV) (GLuint id);
+  void (APIENTRY *EndOcclusionQueryNV) (void);
+  void (APIENTRY *GetOcclusionQueryivNV) (GLuint id, GLenum pname, GLint *params);
+  void (APIENTRY *GetOcclusionQueryuivNV) (GLuint id, GLenum pname, GLuint *params);
+  void (APIENTRY *PointParameteriNV) (GLenum pname, GLint param);
+  void (APIENTRY *PointParameterivNV) (GLenum pname, const GLint *params);
+  void (APIENTRY *ActiveStencilFaceEXT) (GLenum face);
+  void (APIENTRY *ElementPointerAPPLE) (GLenum type, const GLvoid *pointer);
+  void (APIENTRY *DrawElementArrayAPPLE) (GLenum mode, GLint first, GLsizei count);
+  void (APIENTRY *DrawRangeElementArrayAPPLE) (GLenum mode, GLuint start, GLuint end, GLint first, GLsizei count);
+  void (APIENTRY *MultiDrawElementArrayAPPLE) (GLenum mode, const GLint *first, const GLsizei *count, GLsizei primcount);
+  void (APIENTRY *MultiDrawRangeElementArrayAPPLE) (GLenum mode, GLuint start, GLuint end, const GLint *first, const GLsizei *count, GLsizei primcount);
+  void (APIENTRY *GenFencesAPPLE) (GLsizei n, GLuint *fences);
+  void (APIENTRY *DeleteFencesAPPLE) (GLsizei n, const GLuint *fences);
+  void (APIENTRY *SetFenceAPPLE) (GLuint fence);
+  GLboolean (APIENTRY *IsFenceAPPLE) (GLuint fence);
+  GLboolean (APIENTRY *TestFenceAPPLE) (GLuint fence);
+  void (APIENTRY *FinishFenceAPPLE) (GLuint fence);
+  GLboolean (APIENTRY *TestObjectAPPLE) (GLenum object, GLuint name);
+  void (APIENTRY *FinishObjectAPPLE) (GLenum object, GLint name);
+  void (APIENTRY *BindVertexArrayAPPLE) (GLuint array);
+  void (APIENTRY *DeleteVertexArraysAPPLE) (GLsizei n, const GLuint *arrays);
+  void (APIENTRY *GenVertexArraysAPPLE) (GLsizei n, const GLuint *arrays);
+  GLboolean (APIENTRY *IsVertexArrayAPPLE) (GLuint array);
+  void (APIENTRY *VertexArrayRangeAPPLE) (GLsizei length, GLvoid *pointer);
+  void (APIENTRY *FlushVertexArrayRangeAPPLE) (GLsizei length, GLvoid *pointer);
+  void (APIENTRY *VertexArrayParameteriAPPLE) (GLenum pname, GLint param);
+  void (APIENTRY *DrawBuffersATI) (GLsizei n, const GLenum *bufs);
+  void (APIENTRY *ProgramNamedParameter4fNV) (GLuint id, GLsizei len, const GLubyte *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+  void (APIENTRY *ProgramNamedParameter4dNV) (GLuint id, GLsizei len, const GLubyte *name, GLdouble x, GLdouble y, GLdouble z, GLdouble w);
+  void (APIENTRY *ProgramNamedParameter4fvNV) (GLuint id, GLsizei len, const GLubyte *name, const GLfloat *v);
+  void (APIENTRY *ProgramNamedParameter4dvNV) (GLuint id, GLsizei len, const GLubyte *name, const GLdouble *v);
+  void (APIENTRY *GetProgramNamedParameterfvNV) (GLuint id, GLsizei len, const GLubyte *name, GLfloat *params);
+  void (APIENTRY *GetProgramNamedParameterdvNV) (GLuint id, GLsizei len, const GLubyte *name, GLdouble *params);
+  void (APIENTRY *Vertex2hNV) (GLhalfNV x, GLhalfNV y);
+  void (APIENTRY *Vertex2hvNV) (const GLhalfNV *v);
+  void (APIENTRY *Vertex3hNV) (GLhalfNV x, GLhalfNV y, GLhalfNV z);
+  void (APIENTRY *Vertex3hvNV) (const GLhalfNV *v);
+  void (APIENTRY *Vertex4hNV) (GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+  void (APIENTRY *Vertex4hvNV) (const GLhalfNV *v);
+  void (APIENTRY *Normal3hNV) (GLhalfNV nx, GLhalfNV ny, GLhalfNV nz);
+  void (APIENTRY *Normal3hvNV) (const GLhalfNV *v);
+  void (APIENTRY *Color3hNV) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+  void (APIENTRY *Color3hvNV) (const GLhalfNV *v);
+  void (APIENTRY *Color4hNV) (GLhalfNV red, GLhalfNV green, GLhalfNV blue, GLhalfNV alpha);
+  void (APIENTRY *Color4hvNV) (const GLhalfNV *v);
+  void (APIENTRY *TexCoord1hNV) (GLhalfNV s);
+  void (APIENTRY *TexCoord1hvNV) (const GLhalfNV *v);
+  void (APIENTRY *TexCoord2hNV) (GLhalfNV s, GLhalfNV t);
+  void (APIENTRY *TexCoord2hvNV) (const GLhalfNV *v);
+  void (APIENTRY *TexCoord3hNV) (GLhalfNV s, GLhalfNV t, GLhalfNV r);
+  void (APIENTRY *TexCoord3hvNV) (const GLhalfNV *v);
+  void (APIENTRY *TexCoord4hNV) (GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+  void (APIENTRY *TexCoord4hvNV) (const GLhalfNV *v);
+  void (APIENTRY *MultiTexCoord1hNV) (GLenum target, GLhalfNV s);
+  void (APIENTRY *MultiTexCoord1hvNV) (GLenum target, const GLhalfNV *v);
+  void (APIENTRY *MultiTexCoord2hNV) (GLenum target, GLhalfNV s, GLhalfNV t);
+  void (APIENTRY *MultiTexCoord2hvNV) (GLenum target, const GLhalfNV *v);
+  void (APIENTRY *MultiTexCoord3hNV) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r);
+  void (APIENTRY *MultiTexCoord3hvNV) (GLenum target, const GLhalfNV *v);
+  void (APIENTRY *MultiTexCoord4hNV) (GLenum target, GLhalfNV s, GLhalfNV t, GLhalfNV r, GLhalfNV q);
+  void (APIENTRY *MultiTexCoord4hvNV) (GLenum target, const GLhalfNV *v);
+  void (APIENTRY *FogCoordhNV) (GLhalfNV fog);
+  void (APIENTRY *FogCoordhvNV) (const GLhalfNV *fog);
+  void (APIENTRY *SecondaryColor3hNV) (GLhalfNV red, GLhalfNV green, GLhalfNV blue);
+  void (APIENTRY *SecondaryColor3hvNV) (const GLhalfNV *v);
+  void (APIENTRY *VertexWeighthNV) (GLhalfNV weight);
+  void (APIENTRY *VertexWeighthvNV) (const GLhalfNV *weight);
+  void (APIENTRY *VertexAttrib1hNV) (GLuint index, GLhalfNV x);
+  void (APIENTRY *VertexAttrib1hvNV) (GLuint index, const GLhalfNV *v);
+  void (APIENTRY *VertexAttrib2hNV) (GLuint index, GLhalfNV x, GLhalfNV y);
+  void (APIENTRY *VertexAttrib2hvNV) (GLuint index, const GLhalfNV *v);
+  void (APIENTRY *VertexAttrib3hNV) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z);
+  void (APIENTRY *VertexAttrib3hvNV) (GLuint index, const GLhalfNV *v);
+  void (APIENTRY *VertexAttrib4hNV) (GLuint index, GLhalfNV x, GLhalfNV y, GLhalfNV z, GLhalfNV w);
+  void (APIENTRY *VertexAttrib4hvNV) (GLuint index, const GLhalfNV *v);
+  void (APIENTRY *VertexAttribs1hvNV) (GLuint index, GLsizei n, const GLhalfNV *v);
+  void (APIENTRY *VertexAttribs2hvNV) (GLuint index, GLsizei n, const GLhalfNV *v);
+  void (APIENTRY *VertexAttribs3hvNV) (GLuint index, GLsizei n, const GLhalfNV *v);
+  void (APIENTRY *VertexAttribs4hvNV) (GLuint index, GLsizei n, const GLhalfNV *v);
+  void (APIENTRY *PixelDataRangeNV) (GLenum target, GLsizei length, GLvoid *pointer);
+  void (APIENTRY *FlushPixelDataRangeNV) (GLenum target);
+  void (APIENTRY *PrimitiveRestartNV) (void);
+  void (APIENTRY *PrimitiveRestartIndexNV) (GLuint index);
+  GLvoid* (APIENTRY *MapObjectBufferATI) (GLuint buffer);
+  void (APIENTRY *UnmapObjectBufferATI) (GLuint buffer);
+  void (APIENTRY *StencilOpSeparateATI) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
+  void (APIENTRY *StencilFuncSeparateATI) (GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask);
+  void (APIENTRY *VertexAttribArrayObjectATI) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, GLuint buffer, GLuint offset);
+  void (APIENTRY *GetVertexAttribArrayObjectfvATI) (GLuint index, GLenum pname, GLfloat *params);
+  void (APIENTRY *GetVertexAttribArrayObjectivATI) (GLuint index, GLenum pname, GLint *params);
+  void (APIENTRY *DepthBoundsEXT) (GLclampd zmin, GLclampd zmax);
+  void (APIENTRY *BlendEquationSeparateEXT) (GLenum modeRGB, GLenum modeAlpha);
+  void (APIENTRY *AddSwapHintRectWIN) (GLint x, GLint y, GLsizei width, GLsizei height);
+#ifdef _WIN32
+  HANDLE (WINAPI *CreateBufferRegionARB) (HDC hDC, int iLayerPlane, UINT uType);
+  VOID (WINAPI *DeleteBufferRegionARB) (HANDLE hRegion);
+  BOOL (WINAPI *SaveBufferRegionARB) (HANDLE hRegion, int x, int y, int width, int height);
+  BOOL (WINAPI *RestoreBufferRegionARB) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
+  const (WINAPI *GetExtensionsStringARB) (HDC hdc);
+  BOOL (WINAPI *GetPixelFormatAttribivARB) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
+  BOOL (WINAPI *GetPixelFormatAttribfvARB) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
+  BOOL (WINAPI *ChoosePixelFormatARB) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+  BOOL (WINAPI *MakeContextCurrentARB) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+  HDC (WINAPI *GetCurrentReadDCARB) (void);
+  HPBUFFERARB (WINAPI *CreatePbufferARB) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+  HDC (WINAPI *GetPbufferDCARB) (HPBUFFERARB hPbuffer);
+  int (WINAPI *ReleasePbufferDCARB) (HPBUFFERARB hPbuffer, HDC hDC);
+  BOOL (WINAPI *DestroyPbufferARB) (HPBUFFERARB hPbuffer);
+  BOOL (WINAPI *QueryPbufferARB) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
+  BOOL (WINAPI *BindTexImageARB) (HPBUFFERARB hPbuffer, int iBuffer);
+  BOOL (WINAPI *ReleaseTexImageARB) (HPBUFFERARB hPbuffer, int iBuffer);
+  BOOL (WINAPI *SetPbufferAttribARB) (HPBUFFERARB hPbuffer, const int *piAttribList);
+  GLboolean (WINAPI *CreateDisplayColorTableEXT) (GLushort id);
+  GLboolean (WINAPI *LoadDisplayColorTableEXT) (const GLushort *table, GLuint length);
+  GLboolean (WINAPI *BindDisplayColorTableEXT) (GLushort id);
+  VOID (WINAPI *DestroyDisplayColorTableEXT) (GLushort id);
+  const (WINAPI *GetExtensionsStringEXT) (void);
+  BOOL (WINAPI *MakeContextCurrentEXT) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+  HDC (WINAPI *GetCurrentReadDCEXT) (void);
+  HPBUFFEREXT (WINAPI *CreatePbufferEXT) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+  HDC (WINAPI *GetPbufferDCEXT) (HPBUFFEREXT hPbuffer);
+  int (WINAPI *ReleasePbufferDCEXT) (HPBUFFEREXT hPbuffer, HDC hDC);
+  BOOL (WINAPI *DestroyPbufferEXT) (HPBUFFEREXT hPbuffer);
+  BOOL (WINAPI *QueryPbufferEXT) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
+  BOOL (WINAPI *GetPixelFormatAttribivEXT) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
+  BOOL (WINAPI *GetPixelFormatAttribfvEXT) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
+  BOOL (WINAPI *ChoosePixelFormatEXT) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+  BOOL (WINAPI *SwapIntervalEXT) (int interval);
+  int (WINAPI *GetSwapIntervalEXT) (void);
+  void* (WINAPI *AllocateMemoryNV) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
+  void (WINAPI *FreeMemoryNV) (void);
+  BOOL (WINAPI *GetSyncValuesOML) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
+  BOOL (WINAPI *GetMscRateOML) (HDC hdc, INT32 *numerator, INT32 *denominator);
+  INT64 (WINAPI *SwapBuffersMscOML) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
+  INT64 (WINAPI *SwapLayerBuffersMscOML) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
+  BOOL (WINAPI *WaitForMscOML) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
+  BOOL (WINAPI *WaitForSbcOML) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
+  BOOL (WINAPI *GetDigitalVideoParametersI3D) (HDC hDC, int iAttribute, int *piValue);
+  BOOL (WINAPI *SetDigitalVideoParametersI3D) (HDC hDC, int iAttribute, const int *piValue);
+  BOOL (WINAPI *GetGammaTableParametersI3D) (HDC hDC, int iAttribute, int *piValue);
+  BOOL (WINAPI *SetGammaTableParametersI3D) (HDC hDC, int iAttribute, const int *piValue);
+  BOOL (WINAPI *GetGammaTableI3D) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
+  BOOL (WINAPI *SetGammaTableI3D) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
+  BOOL (WINAPI *EnableGenlockI3D) (HDC hDC);
+  BOOL (WINAPI *DisableGenlockI3D) (HDC hDC);
+  BOOL (WINAPI *IsEnabledGenlockI3D) (HDC hDC, BOOL *pFlag);
+  BOOL (WINAPI *GenlockSourceI3D) (HDC hDC, UINT uSource);
+  BOOL (WINAPI *GetGenlockSourceI3D) (HDC hDC, UINT *uSource);
+  BOOL (WINAPI *GenlockSourceEdgeI3D) (HDC hDC, UINT uEdge);
+  BOOL (WINAPI *GetGenlockSourceEdgeI3D) (HDC hDC, UINT *uEdge);
+  BOOL (WINAPI *GenlockSampleRateI3D) (HDC hDC, UINT uRate);
+  BOOL (WINAPI *GetGenlockSampleRateI3D) (HDC hDC, UINT *uRate);
+  BOOL (WINAPI *GenlockSourceDelayI3D) (HDC hDC, UINT uDelay);
+  BOOL (WINAPI *GetGenlockSourceDelayI3D) (HDC hDC, UINT *uDelay);
+  BOOL (WINAPI *QueryGenlockMaxSourceDelayI3D) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
+  LPVOID (WINAPI *CreateImageBufferI3D) (HDC hDC, DWORD dwSize, UINT uFlags);
+  BOOL (WINAPI *DestroyImageBufferI3D) (HDC hDC, LPVOID pAddress);
+  BOOL (WINAPI *AssociateImageBufferEventsI3D) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
+  BOOL (WINAPI *ReleaseImageBufferEventsI3D) (HDC hDC, const LPVOID *pAddress, UINT count);
+  BOOL (WINAPI *EnableFrameLockI3D) (void);
+  BOOL (WINAPI *DisableFrameLockI3D) (void);
+  BOOL (WINAPI *IsEnabledFrameLockI3D) (BOOL *pFlag);
+  BOOL (WINAPI *QueryFrameLockMasterI3D) (BOOL *pFlag);
+  BOOL (WINAPI *GetFrameUsageI3D) (float *pUsage);
+  BOOL (WINAPI *BeginFrameTrackingI3D) (void);
+  BOOL (WINAPI *EndFrameTrackingI3D) (void);
+  BOOL (WINAPI *QueryFrameTrackingI3D) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
+#endif /* _WIN32 */
+} _GLextensionProcs;
+
+#define glBlendColor                     (_GET_TLS_PROCTABLE()->BlendColor)
+#define glBlendEquation                  (_GET_TLS_PROCTABLE()->BlendEquation)
+#define glDrawRangeElements              (_GET_TLS_PROCTABLE()->DrawRangeElements)
+#define glColorTable                     (_GET_TLS_PROCTABLE()->ColorTable)
+#define glColorTableParameterfv          (_GET_TLS_PROCTABLE()->ColorTableParameterfv)
+#define glColorTableParameteriv          (_GET_TLS_PROCTABLE()->ColorTableParameteriv)
+#define glCopyColorTable                 (_GET_TLS_PROCTABLE()->CopyColorTable)
+#define glGetColorTable                  (_GET_TLS_PROCTABLE()->GetColorTable)
+#define glGetColorTableParameterfv       (_GET_TLS_PROCTABLE()->GetColorTableParameterfv)
+#define glGetColorTableParameteriv       (_GET_TLS_PROCTABLE()->GetColorTableParameteriv)
+#define glColorSubTable                  (_GET_TLS_PROCTABLE()->ColorSubTable)
+#define glCopyColorSubTable              (_GET_TLS_PROCTABLE()->CopyColorSubTable)
+#define glConvolutionFilter1D            (_GET_TLS_PROCTABLE()->ConvolutionFilter1D)
+#define glConvolutionFilter2D            (_GET_TLS_PROCTABLE()->ConvolutionFilter2D)
+#define glConvolutionParameterf          (_GET_TLS_PROCTABLE()->ConvolutionParameterf)
+#define glConvolutionParameterfv         (_GET_TLS_PROCTABLE()->ConvolutionParameterfv)
+#define glConvolutionParameteri          (_GET_TLS_PROCTABLE()->ConvolutionParameteri)
+#define glConvolutionParameteriv         (_GET_TLS_PROCTABLE()->ConvolutionParameteriv)
+#define glCopyConvolutionFilter1D        (_GET_TLS_PROCTABLE()->CopyConvolutionFilter1D)
+#define glCopyConvolutionFilter2D        (_GET_TLS_PROCTABLE()->CopyConvolutionFilter2D)
+#define glGetConvolutionFilter           (_GET_TLS_PROCTABLE()->GetConvolutionFilter)
+#define glGetConvolutionParameterfv      (_GET_TLS_PROCTABLE()->GetConvolutionParameterfv)
+#define glGetConvolutionParameteriv      (_GET_TLS_PROCTABLE()->GetConvolutionParameteriv)
+#define glGetSeparableFilter             (_GET_TLS_PROCTABLE()->GetSeparableFilter)
+#define glSeparableFilter2D              (_GET_TLS_PROCTABLE()->SeparableFilter2D)
+#define glGetHistogram                   (_GET_TLS_PROCTABLE()->GetHistogram)
+#define glGetHistogramParameterfv        (_GET_TLS_PROCTABLE()->GetHistogramParameterfv)
+#define glGetHistogramParameteriv        (_GET_TLS_PROCTABLE()->GetHistogramParameteriv)
+#define glGetMinmax                      (_GET_TLS_PROCTABLE()->GetMinmax)
+#define glGetMinmaxParameterfv           (_GET_TLS_PROCTABLE()->GetMinmaxParameterfv)
+#define glGetMinmaxParameteriv           (_GET_TLS_PROCTABLE()->GetMinmaxParameteriv)
+#define glHistogram                      (_GET_TLS_PROCTABLE()->Histogram)
+#define glMinmax                         (_GET_TLS_PROCTABLE()->Minmax)
+#define glResetHistogram                 (_GET_TLS_PROCTABLE()->ResetHistogram)
+#define glResetMinmax                    (_GET_TLS_PROCTABLE()->ResetMinmax)
+#define glTexImage3D                     (_GET_TLS_PROCTABLE()->TexImage3D)
+#define glTexSubImage3D                  (_GET_TLS_PROCTABLE()->TexSubImage3D)
+#define glCopyTexSubImage3D              (_GET_TLS_PROCTABLE()->CopyTexSubImage3D)
+#define glActiveTexture                  (_GET_TLS_PROCTABLE()->ActiveTexture)
+#define glClientActiveTexture            (_GET_TLS_PROCTABLE()->ClientActiveTexture)
+#define glMultiTexCoord1d                (_GET_TLS_PROCTABLE()->MultiTexCoord1d)
+#define glMultiTexCoord1dv               (_GET_TLS_PROCTABLE()->MultiTexCoord1dv)
+#define glMultiTexCoord1f                (_GET_TLS_PROCTABLE()->MultiTexCoord1f)
+#define glMultiTexCoord1fv               (_GET_TLS_PROCTABLE()->MultiTexCoord1fv)
+#define glMultiTexCoord1i                (_GET_TLS_PROCTABLE()->MultiTexCoord1i)
+#define glMultiTexCoord1iv               (_GET_TLS_PROCTABLE()->MultiTexCoord1iv)
+#define glMultiTexCoord1s                (_GET_TLS_PROCTABLE()->MultiTexCoord1s)
+#define glMultiTexCoord1sv               (_GET_TLS_PROCTABLE()->MultiTexCoord1sv)
+#define glMultiTexCoord2d                (_GET_TLS_PROCTABLE()->MultiTexCoord2d)
+#define glMultiTexCoord2dv               (_GET_TLS_PROCTABLE()->MultiTexCoord2dv)
+#define glMultiTexCoord2f                (_GET_TLS_PROCTABLE()->MultiTexCoord2f)
+#define glMultiTexCoord2fv               (_GET_TLS_PROCTABLE()->MultiTexCoord2fv)
+#define glMultiTexCoord2i                (_GET_TLS_PROCTABLE()->MultiTexCoord2i)
+#define glMultiTexCoord2iv               (_GET_TLS_PROCTABLE()->MultiTexCoord2iv)
+#define glMultiTexCoord2s                (_GET_TLS_PROCTABLE()->MultiTexCoord2s)
+#define glMultiTexCoord2sv               (_GET_TLS_PROCTABLE()->MultiTexCoord2sv)
+#define glMultiTexCoord3d                (_GET_TLS_PROCTABLE()->MultiTexCoord3d)
+#define glMultiTexCoord3dv               (_GET_TLS_PROCTABLE()->MultiTexCoord3dv)
+#define glMultiTexCoord3f                (_GET_TLS_PROCTABLE()->MultiTexCoord3f)
+#define glMultiTexCoord3fv               (_GET_TLS_PROCTABLE()->MultiTexCoord3fv)
+#define glMultiTexCoord3i                (_GET_TLS_PROCTABLE()->MultiTexCoord3i)
+#define glMultiTexCoord3iv               (_GET_TLS_PROCTABLE()->MultiTexCoord3iv)
+#define glMultiTexCoord3s                (_GET_TLS_PROCTABLE()->MultiTexCoord3s)
+#define glMultiTexCoord3sv               (_GET_TLS_PROCTABLE()->MultiTexCoord3sv)
+#define glMultiTexCoord4d                (_GET_TLS_PROCTABLE()->MultiTexCoord4d)
+#define glMultiTexCoord4dv               (_GET_TLS_PROCTABLE()->MultiTexCoord4dv)
+#define glMultiTexCoord4f                (_GET_TLS_PROCTABLE()->MultiTexCoord4f)
+#define glMultiTexCoord4fv               (_GET_TLS_PROCTABLE()->MultiTexCoord4fv)
+#define glMultiTexCoord4i                (_GET_TLS_PROCTABLE()->MultiTexCoord4i)
+#define glMultiTexCoord4iv               (_GET_TLS_PROCTABLE()->MultiTexCoord4iv)
+#define glMultiTexCoord4s                (_GET_TLS_PROCTABLE()->MultiTexCoord4s)
+#define glMultiTexCoord4sv               (_GET_TLS_PROCTABLE()->MultiTexCoord4sv)
+#define glLoadTransposeMatrixf           (_GET_TLS_PROCTABLE()->LoadTransposeMatrixf)
+#define glLoadTransposeMatrixd           (_GET_TLS_PROCTABLE()->LoadTransposeMatrixd)
+#define glMultTransposeMatrixf           (_GET_TLS_PROCTABLE()->MultTransposeMatrixf)
+#define glMultTransposeMatrixd           (_GET_TLS_PROCTABLE()->MultTransposeMatrixd)
+#define glSampleCoverage                 (_GET_TLS_PROCTABLE()->SampleCoverage)
+#define glCompressedTexImage3D           (_GET_TLS_PROCTABLE()->CompressedTexImage3D)
+#define glCompressedTexImage2D           (_GET_TLS_PROCTABLE()->CompressedTexImage2D)
+#define glCompressedTexImage1D           (_GET_TLS_PROCTABLE()->CompressedTexImage1D)
+#define glCompressedTexSubImage3D        (_GET_TLS_PROCTABLE()->CompressedTexSubImage3D)
+#define glCompressedTexSubImage2D        (_GET_TLS_PROCTABLE()->CompressedTexSubImage2D)
+#define glCompressedTexSubImage1D        (_GET_TLS_PROCTABLE()->CompressedTexSubImage1D)
+#define glGetCompressedTexImage          (_GET_TLS_PROCTABLE()->GetCompressedTexImage)
+#define glBlendFuncSeparate              (_GET_TLS_PROCTABLE()->BlendFuncSeparate)
+#define glFogCoordf                      (_GET_TLS_PROCTABLE()->FogCoordf)
+#define glFogCoordfv                     (_GET_TLS_PROCTABLE()->FogCoordfv)
+#define glFogCoordd                      (_GET_TLS_PROCTABLE()->FogCoordd)
+#define glFogCoorddv                     (_GET_TLS_PROCTABLE()->FogCoorddv)
+#define glFogCoordPointer                (_GET_TLS_PROCTABLE()->FogCoordPointer)
+#define glMultiDrawArrays                (_GET_TLS_PROCTABLE()->MultiDrawArrays)
+#define glMultiDrawElements              (_GET_TLS_PROCTABLE()->MultiDrawElements)
+#define glPointParameterf                (_GET_TLS_PROCTABLE()->PointParameterf)
+#define glPointParameterfv               (_GET_TLS_PROCTABLE()->PointParameterfv)
+#define glPointParameteri                (_GET_TLS_PROCTABLE()->PointParameteri)
+#define glPointParameteriv               (_GET_TLS_PROCTABLE()->PointParameteriv)
+#define glSecondaryColor3b               (_GET_TLS_PROCTABLE()->SecondaryColor3b)
+#define glSecondaryColor3bv              (_GET_TLS_PROCTABLE()->SecondaryColor3bv)
+#define glSecondaryColor3d               (_GET_TLS_PROCTABLE()->SecondaryColor3d)
+#define glSecondaryColor3dv              (_GET_TLS_PROCTABLE()->SecondaryColor3dv)
+#define glSecondaryColor3f               (_GET_TLS_PROCTABLE()->SecondaryColor3f)
+#define glSecondaryColor3fv              (_GET_TLS_PROCTABLE()->SecondaryColor3fv)
+#define glSecondaryColor3i               (_GET_TLS_PROCTABLE()->SecondaryColor3i)
+#define glSecondaryColor3iv              (_GET_TLS_PROCTABLE()->SecondaryColor3iv)
+#define glSecondaryColor3s               (_GET_TLS_PROCTABLE()->SecondaryColor3s)
+#define glSecondaryColor3sv              (_GET_TLS_PROCTABLE()->SecondaryColor3sv)
+#define glSecondaryColor3ub              (_GET_TLS_PROCTABLE()->SecondaryColor3ub)
+#define glSecondaryColor3ubv             (_GET_TLS_PROCTABLE()->SecondaryColor3ubv)
+#define glSecondaryColor3ui              (_GET_TLS_PROCTABLE()->SecondaryColor3ui)
+#define glSecondaryColor3uiv             (_GET_TLS_PROCTABLE()->SecondaryColor3uiv)
+#define glSecondaryColor3us              (_GET_TLS_PROCTABLE()->SecondaryColor3us)
+#define glSecondaryColor3usv             (_GET_TLS_PROCTABLE()->SecondaryColor3usv)
+#define glSecondaryColorPointer          (_GET_TLS_PROCTABLE()->SecondaryColorPointer)
+#define glWindowPos2d                    (_GET_TLS_PROCTABLE()->WindowPos2d)
+#define glWindowPos2dv                   (_GET_TLS_PROCTABLE()->WindowPos2dv)
+#define glWindowPos2f                    (_GET_TLS_PROCTABLE()->WindowPos2f)
+#define glWindowPos2fv                   (_GET_TLS_PROCTABLE()->WindowPos2fv)
+#define glWindowPos2i                    (_GET_TLS_PROCTABLE()->WindowPos2i)
+#define glWindowPos2iv                   (_GET_TLS_PROCTABLE()->WindowPos2iv)
+#define glWindowPos2s                    (_GET_TLS_PROCTABLE()->WindowPos2s)
+#define glWindowPos2sv                   (_GET_TLS_PROCTABLE()->WindowPos2sv)
+#define glWindowPos3d                    (_GET_TLS_PROCTABLE()->WindowPos3d)
+#define glWindowPos3dv                   (_GET_TLS_PROCTABLE()->WindowPos3dv)
+#define glWindowPos3f                    (_GET_TLS_PROCTABLE()->WindowPos3f)
+#define glWindowPos3fv                   (_GET_TLS_PROCTABLE()->WindowPos3fv)
+#define glWindowPos3i                    (_GET_TLS_PROCTABLE()->WindowPos3i)
+#define glWindowPos3iv                   (_GET_TLS_PROCTABLE()->WindowPos3iv)
+#define glWindowPos3s                    (_GET_TLS_PROCTABLE()->WindowPos3s)
+#define glWindowPos3sv                   (_GET_TLS_PROCTABLE()->WindowPos3sv)
+#define glGenQueries                     (_GET_TLS_PROCTABLE()->GenQueries)
+#define glDeleteQueries                  (_GET_TLS_PROCTABLE()->DeleteQueries)
+#define glIsQuery                        (_GET_TLS_PROCTABLE()->IsQuery)
+#define glBeginQuery                     (_GET_TLS_PROCTABLE()->BeginQuery)
+#define glEndQuery                       (_GET_TLS_PROCTABLE()->EndQuery)
+#define glGetQueryiv                     (_GET_TLS_PROCTABLE()->GetQueryiv)
+#define glGetQueryObjectiv               (_GET_TLS_PROCTABLE()->GetQueryObjectiv)
+#define glGetQueryObjectuiv              (_GET_TLS_PROCTABLE()->GetQueryObjectuiv)
+#define glBindBuffer                     (_GET_TLS_PROCTABLE()->BindBuffer)
+#define glDeleteBuffers                  (_GET_TLS_PROCTABLE()->DeleteBuffers)
+#define glGenBuffers                     (_GET_TLS_PROCTABLE()->GenBuffers)
+#define glIsBuffer                       (_GET_TLS_PROCTABLE()->IsBuffer)
+#define glBufferData                     (_GET_TLS_PROCTABLE()->BufferData)
+#define glBufferSubData                  (_GET_TLS_PROCTABLE()->BufferSubData)
+#define glGetBufferSubData               (_GET_TLS_PROCTABLE()->GetBufferSubData)
+#define glMapBuffer                      (_GET_TLS_PROCTABLE()->MapBuffer)
+#define glUnmapBuffer                    (_GET_TLS_PROCTABLE()->UnmapBuffer)
+#define glGetBufferParameteriv           (_GET_TLS_PROCTABLE()->GetBufferParameteriv)
+#define glGetBufferPointerv              (_GET_TLS_PROCTABLE()->GetBufferPointerv)
+#define glActiveTextureARB               (_GET_TLS_PROCTABLE()->ActiveTextureARB)
+#define glClientActiveTextureARB         (_GET_TLS_PROCTABLE()->ClientActiveTextureARB)
+#define glMultiTexCoord1dARB             (_GET_TLS_PROCTABLE()->MultiTexCoord1dARB)
+#define glMultiTexCoord1dvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord1dvARB)
+#define glMultiTexCoord1fARB             (_GET_TLS_PROCTABLE()->MultiTexCoord1fARB)
+#define glMultiTexCoord1fvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord1fvARB)
+#define glMultiTexCoord1iARB             (_GET_TLS_PROCTABLE()->MultiTexCoord1iARB)
+#define glMultiTexCoord1ivARB            (_GET_TLS_PROCTABLE()->MultiTexCoord1ivARB)
+#define glMultiTexCoord1sARB             (_GET_TLS_PROCTABLE()->MultiTexCoord1sARB)
+#define glMultiTexCoord1svARB            (_GET_TLS_PROCTABLE()->MultiTexCoord1svARB)
+#define glMultiTexCoord2dARB             (_GET_TLS_PROCTABLE()->MultiTexCoord2dARB)
+#define glMultiTexCoord2dvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord2dvARB)
+#define glMultiTexCoord2fARB             (_GET_TLS_PROCTABLE()->MultiTexCoord2fARB)
+#define glMultiTexCoord2fvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord2fvARB)
+#define glMultiTexCoord2iARB             (_GET_TLS_PROCTABLE()->MultiTexCoord2iARB)
+#define glMultiTexCoord2ivARB            (_GET_TLS_PROCTABLE()->MultiTexCoord2ivARB)
+#define glMultiTexCoord2sARB             (_GET_TLS_PROCTABLE()->MultiTexCoord2sARB)
+#define glMultiTexCoord2svARB            (_GET_TLS_PROCTABLE()->MultiTexCoord2svARB)
+#define glMultiTexCoord3dARB             (_GET_TLS_PROCTABLE()->MultiTexCoord3dARB)
+#define glMultiTexCoord3dvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord3dvARB)
+#define glMultiTexCoord3fARB             (_GET_TLS_PROCTABLE()->MultiTexCoord3fARB)
+#define glMultiTexCoord3fvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord3fvARB)
+#define glMultiTexCoord3iARB             (_GET_TLS_PROCTABLE()->MultiTexCoord3iARB)
+#define glMultiTexCoord3ivARB            (_GET_TLS_PROCTABLE()->MultiTexCoord3ivARB)
+#define glMultiTexCoord3sARB             (_GET_TLS_PROCTABLE()->MultiTexCoord3sARB)
+#define glMultiTexCoord3svARB            (_GET_TLS_PROCTABLE()->MultiTexCoord3svARB)
+#define glMultiTexCoord4dARB             (_GET_TLS_PROCTABLE()->MultiTexCoord4dARB)
+#define glMultiTexCoord4dvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord4dvARB)
+#define glMultiTexCoord4fARB             (_GET_TLS_PROCTABLE()->MultiTexCoord4fARB)
+#define glMultiTexCoord4fvARB            (_GET_TLS_PROCTABLE()->MultiTexCoord4fvARB)
+#define glMultiTexCoord4iARB             (_GET_TLS_PROCTABLE()->MultiTexCoord4iARB)
+#define glMultiTexCoord4ivARB            (_GET_TLS_PROCTABLE()->MultiTexCoord4ivARB)
+#define glMultiTexCoord4sARB             (_GET_TLS_PROCTABLE()->MultiTexCoord4sARB)
+#define glMultiTexCoord4svARB            (_GET_TLS_PROCTABLE()->MultiTexCoord4svARB)
+#define glLoadTransposeMatrixfARB        (_GET_TLS_PROCTABLE()->LoadTransposeMatrixfARB)
+#define glLoadTransposeMatrixdARB        (_GET_TLS_PROCTABLE()->LoadTransposeMatrixdARB)
+#define glMultTransposeMatrixfARB        (_GET_TLS_PROCTABLE()->MultTransposeMatrixfARB)
+#define glMultTransposeMatrixdARB        (_GET_TLS_PROCTABLE()->MultTransposeMatrixdARB)
+#define glSampleCoverageARB              (_GET_TLS_PROCTABLE()->SampleCoverageARB)
+#define glCompressedTexImage3DARB        (_GET_TLS_PROCTABLE()->CompressedTexImage3DARB)
+#define glCompressedTexImage2DARB        (_GET_TLS_PROCTABLE()->CompressedTexImage2DARB)
+#define glCompressedTexImage1DARB        (_GET_TLS_PROCTABLE()->CompressedTexImage1DARB)
+#define glCompressedTexSubImage3DARB     (_GET_TLS_PROCTABLE()->CompressedTexSubImage3DARB)
+#define glCompressedTexSubImage2DARB     (_GET_TLS_PROCTABLE()->CompressedTexSubImage2DARB)
+#define glCompressedTexSubImage1DARB     (_GET_TLS_PROCTABLE()->CompressedTexSubImage1DARB)
+#define glGetCompressedTexImageARB       (_GET_TLS_PROCTABLE()->GetCompressedTexImageARB)
+#define glPointParameterfARB             (_GET_TLS_PROCTABLE()->PointParameterfARB)
+#define glPointParameterfvARB            (_GET_TLS_PROCTABLE()->PointParameterfvARB)
+#define glWeightbvARB                    (_GET_TLS_PROCTABLE()->WeightbvARB)
+#define glWeightsvARB                    (_GET_TLS_PROCTABLE()->WeightsvARB)
+#define glWeightivARB                    (_GET_TLS_PROCTABLE()->WeightivARB)
+#define glWeightfvARB                    (_GET_TLS_PROCTABLE()->WeightfvARB)
+#define glWeightdvARB                    (_GET_TLS_PROCTABLE()->WeightdvARB)
+#define glWeightubvARB                   (_GET_TLS_PROCTABLE()->WeightubvARB)
+#define glWeightusvARB                   (_GET_TLS_PROCTABLE()->WeightusvARB)
+#define glWeightuivARB                   (_GET_TLS_PROCTABLE()->WeightuivARB)
+#define glWeightPointerARB               (_GET_TLS_PROCTABLE()->WeightPointerARB)
+#define glVertexBlendARB                 (_GET_TLS_PROCTABLE()->VertexBlendARB)
+#define glCurrentPaletteMatrixARB        (_GET_TLS_PROCTABLE()->CurrentPaletteMatrixARB)
+#define glMatrixIndexubvARB              (_GET_TLS_PROCTABLE()->MatrixIndexubvARB)
+#define glMatrixIndexusvARB              (_GET_TLS_PROCTABLE()->MatrixIndexusvARB)
+#define glMatrixIndexuivARB              (_GET_TLS_PROCTABLE()->MatrixIndexuivARB)
+#define glMatrixIndexPointerARB          (_GET_TLS_PROCTABLE()->MatrixIndexPointerARB)
+#define glWindowPos2dARB                 (_GET_TLS_PROCTABLE()->WindowPos2dARB)
+#define glWindowPos2dvARB                (_GET_TLS_PROCTABLE()->WindowPos2dvARB)
+#define glWindowPos2fARB                 (_GET_TLS_PROCTABLE()->WindowPos2fARB)
+#define glWindowPos2fvARB                (_GET_TLS_PROCTABLE()->WindowPos2fvARB)
+#define glWindowPos2iARB                 (_GET_TLS_PROCTABLE()->WindowPos2iARB)
+#define glWindowPos2ivARB                (_GET_TLS_PROCTABLE()->WindowPos2ivARB)
+#define glWindowPos2sARB                 (_GET_TLS_PROCTABLE()->WindowPos2sARB)
+#define glWindowPos2svARB                (_GET_TLS_PROCTABLE()->WindowPos2svARB)
+#define glWindowPos3dARB                 (_GET_TLS_PROCTABLE()->WindowPos3dARB)
+#define glWindowPos3dvARB                (_GET_TLS_PROCTABLE()->WindowPos3dvARB)
+#define glWindowPos3fARB                 (_GET_TLS_PROCTABLE()->WindowPos3fARB)
+#define glWindowPos3fvARB                (_GET_TLS_PROCTABLE()->WindowPos3fvARB)
+#define glWindowPos3iARB                 (_GET_TLS_PROCTABLE()->WindowPos3iARB)
+#define glWindowPos3ivARB                (_GET_TLS_PROCTABLE()->WindowPos3ivARB)
+#define glWindowPos3sARB                 (_GET_TLS_PROCTABLE()->WindowPos3sARB)
+#define glWindowPos3svARB                (_GET_TLS_PROCTABLE()->WindowPos3svARB)
+#define glVertexAttrib1dARB              (_GET_TLS_PROCTABLE()->VertexAttrib1dARB)
+#define glVertexAttrib1dvARB             (_GET_TLS_PROCTABLE()->VertexAttrib1dvARB)
+#define glVertexAttrib1fARB              (_GET_TLS_PROCTABLE()->VertexAttrib1fARB)
+#define glVertexAttrib1fvARB             (_GET_TLS_PROCTABLE()->VertexAttrib1fvARB)
+#define glVertexAttrib1sARB              (_GET_TLS_PROCTABLE()->VertexAttrib1sARB)
+#define glVertexAttrib1svARB             (_GET_TLS_PROCTABLE()->VertexAttrib1svARB)
+#define glVertexAttrib2dARB              (_GET_TLS_PROCTABLE()->VertexAttrib2dARB)
+#define glVertexAttrib2dvARB             (_GET_TLS_PROCTABLE()->VertexAttrib2dvARB)
+#define glVertexAttrib2fARB              (_GET_TLS_PROCTABLE()->VertexAttrib2fARB)
+#define glVertexAttrib2fvARB             (_GET_TLS_PROCTABLE()->VertexAttrib2fvARB)
+#define glVertexAttrib2sARB              (_GET_TLS_PROCTABLE()->VertexAttrib2sARB)
+#define glVertexAttrib2svARB             (_GET_TLS_PROCTABLE()->VertexAttrib2svARB)
+#define glVertexAttrib3dARB              (_GET_TLS_PROCTABLE()->VertexAttrib3dARB)
+#define glVertexAttrib3dvARB             (_GET_TLS_PROCTABLE()->VertexAttrib3dvARB)
+#define glVertexAttrib3fARB              (_GET_TLS_PROCTABLE()->VertexAttrib3fARB)
+#define glVertexAttrib3fvARB             (_GET_TLS_PROCTABLE()->VertexAttrib3fvARB)
+#define glVertexAttrib3sARB              (_GET_TLS_PROCTABLE()->VertexAttrib3sARB)
+#define glVertexAttrib3svARB             (_GET_TLS_PROCTABLE()->VertexAttrib3svARB)
+#define glVertexAttrib4NbvARB            (_GET_TLS_PROCTABLE()->VertexAttrib4NbvARB)
+#define glVertexAttrib4NivARB            (_GET_TLS_PROCTABLE()->VertexAttrib4NivARB)
+#define glVertexAttrib4NsvARB            (_GET_TLS_PROCTABLE()->VertexAttrib4NsvARB)
+#define glVertexAttrib4NubARB            (_GET_TLS_PROCTABLE()->VertexAttrib4NubARB)
+#define glVertexAttrib4NubvARB           (_GET_TLS_PROCTABLE()->VertexAttrib4NubvARB)
+#define glVertexAttrib4NuivARB           (_GET_TLS_PROCTABLE()->VertexAttrib4NuivARB)
+#define glVertexAttrib4NusvARB           (_GET_TLS_PROCTABLE()->VertexAttrib4NusvARB)
+#define glVertexAttrib4bvARB             (_GET_TLS_PROCTABLE()->VertexAttrib4bvARB)
+#define glVertexAttrib4dARB              (_GET_TLS_PROCTABLE()->VertexAttrib4dARB)
+#define glVertexAttrib4dvARB             (_GET_TLS_PROCTABLE()->VertexAttrib4dvARB)
+#define glVertexAttrib4fARB              (_GET_TLS_PROCTABLE()->VertexAttrib4fARB)
+#define glVertexAttrib4fvARB             (_GET_TLS_PROCTABLE()->VertexAttrib4fvARB)
+#define glVertexAttrib4ivARB             (_GET_TLS_PROCTABLE()->VertexAttrib4ivARB)
+#define glVertexAttrib4sARB              (_GET_TLS_PROCTABLE()->VertexAttrib4sARB)
+#define glVertexAttrib4svARB             (_GET_TLS_PROCTABLE()->VertexAttrib4svARB)
+#define glVertexAttrib4ubvARB            (_GET_TLS_PROCTABLE()->VertexAttrib4ubvARB)
+#define glVertexAttrib4uivARB            (_GET_TLS_PROCTABLE()->VertexAttrib4uivARB)
+#define glVertexAttrib4usvARB            (_GET_TLS_PROCTABLE()->VertexAttrib4usvARB)
+#define glVertexAttribPointerARB         (_GET_TLS_PROCTABLE()->VertexAttribPointerARB)
+#define glEnableVertexAttribArrayARB     (_GET_TLS_PROCTABLE()->EnableVertexAttribArrayARB)
+#define glDisableVertexAttribArrayARB    (_GET_TLS_PROCTABLE()->DisableVertexAttribArrayARB)
+#define glProgramStringARB               (_GET_TLS_PROCTABLE()->ProgramStringARB)
+#define glBindProgramARB                 (_GET_TLS_PROCTABLE()->BindProgramARB)
+#define glDeleteProgramsARB              (_GET_TLS_PROCTABLE()->DeleteProgramsARB)
+#define glGenProgramsARB                 (_GET_TLS_PROCTABLE()->GenProgramsARB)
+#define glProgramEnvParameter4dARB       (_GET_TLS_PROCTABLE()->ProgramEnvParameter4dARB)
+#define glProgramEnvParameter4dvARB      (_GET_TLS_PROCTABLE()->ProgramEnvParameter4dvARB)
+#define glProgramEnvParameter4fARB       (_GET_TLS_PROCTABLE()->ProgramEnvParameter4fARB)
+#define glProgramEnvParameter4fvARB      (_GET_TLS_PROCTABLE()->ProgramEnvParameter4fvARB)
+#define glProgramLocalParameter4dARB     (_GET_TLS_PROCTABLE()->ProgramLocalParameter4dARB)
+#define glProgramLocalParameter4dvARB    (_GET_TLS_PROCTABLE()->ProgramLocalParameter4dvARB)
+#define glProgramLocalParameter4fARB     (_GET_TLS_PROCTABLE()->ProgramLocalParameter4fARB)
+#define glProgramLocalParameter4fvARB    (_GET_TLS_PROCTABLE()->ProgramLocalParameter4fvARB)
+#define glGetProgramEnvParameterdvARB    (_GET_TLS_PROCTABLE()->GetProgramEnvParameterdvARB)
+#define glGetProgramEnvParameterfvARB    (_GET_TLS_PROCTABLE()->GetProgramEnvParameterfvARB)
+#define glGetProgramLocalParameterdvARB  (_GET_TLS_PROCTABLE()->GetProgramLocalParameterdvARB)
+#define glGetProgramLocalParameterfvARB  (_GET_TLS_PROCTABLE()->GetProgramLocalParameterfvARB)
+#define glGetProgramivARB                (_GET_TLS_PROCTABLE()->GetProgramivARB)
+#define glGetProgramStringARB            (_GET_TLS_PROCTABLE()->GetProgramStringARB)
+#define glGetVertexAttribdvARB           (_GET_TLS_PROCTABLE()->GetVertexAttribdvARB)
+#define glGetVertexAttribfvARB           (_GET_TLS_PROCTABLE()->GetVertexAttribfvARB)
+#define glGetVertexAttribivARB           (_GET_TLS_PROCTABLE()->GetVertexAttribivARB)
+#define glGetVertexAttribPointervARB     (_GET_TLS_PROCTABLE()->GetVertexAttribPointervARB)
+#define glIsProgramARB                   (_GET_TLS_PROCTABLE()->IsProgramARB)
+#define glBindBufferARB                  (_GET_TLS_PROCTABLE()->BindBufferARB)
+#define glDeleteBuffersARB               (_GET_TLS_PROCTABLE()->DeleteBuffersARB)
+#define glGenBuffersARB                  (_GET_TLS_PROCTABLE()->GenBuffersARB)
+#define glIsBufferARB                    (_GET_TLS_PROCTABLE()->IsBufferARB)
+#define glBufferDataARB                  (_GET_TLS_PROCTABLE()->BufferDataARB)
+#define glBufferSubDataARB               (_GET_TLS_PROCTABLE()->BufferSubDataARB)
+#define glGetBufferSubDataARB            (_GET_TLS_PROCTABLE()->GetBufferSubDataARB)
+#define glMapBufferARB                   (_GET_TLS_PROCTABLE()->MapBufferARB)
+#define glUnmapBufferARB                 (_GET_TLS_PROCTABLE()->UnmapBufferARB)
+#define glGetBufferParameterivARB        (_GET_TLS_PROCTABLE()->GetBufferParameterivARB)
+#define glGetBufferPointervARB           (_GET_TLS_PROCTABLE()->GetBufferPointervARB)
+#define glGenQueriesARB                  (_GET_TLS_PROCTABLE()->GenQueriesARB)
+#define glDeleteQueriesARB               (_GET_TLS_PROCTABLE()->DeleteQueriesARB)
+#define glIsQueryARB                     (_GET_TLS_PROCTABLE()->IsQueryARB)
+#define glBeginQueryARB                  (_GET_TLS_PROCTABLE()->BeginQueryARB)
+#define glEndQueryARB                    (_GET_TLS_PROCTABLE()->EndQueryARB)
+#define glGetQueryivARB                  (_GET_TLS_PROCTABLE()->GetQueryivARB)
+#define glGetQueryObjectivARB            (_GET_TLS_PROCTABLE()->GetQueryObjectivARB)
+#define glGetQueryObjectuivARB           (_GET_TLS_PROCTABLE()->GetQueryObjectuivARB)
+#define glDeleteObjectARB                (_GET_TLS_PROCTABLE()->DeleteObjectARB)
+#define glGetHandleARB                   (_GET_TLS_PROCTABLE()->GetHandleARB)
+#define glDetachObjectARB                (_GET_TLS_PROCTABLE()->DetachObjectARB)
+#define glCreateShaderObjectARB          (_GET_TLS_PROCTABLE()->CreateShaderObjectARB)
+#define glShaderSourceARB                (_GET_TLS_PROCTABLE()->ShaderSourceARB)
+#define glCompileShaderARB               (_GET_TLS_PROCTABLE()->CompileShaderARB)
+#define glCreateProgramObjectARB         (_GET_TLS_PROCTABLE()->CreateProgramObjectARB)
+#define glAttachObjectARB                (_GET_TLS_PROCTABLE()->AttachObjectARB)
+#define glLinkProgramARB                 (_GET_TLS_PROCTABLE()->LinkProgramARB)
+#define glUseProgramObjectARB            (_GET_TLS_PROCTABLE()->UseProgramObjectARB)
+#define glValidateProgramARB             (_GET_TLS_PROCTABLE()->ValidateProgramARB)
+#define glUniform1fARB                   (_GET_TLS_PROCTABLE()->Uniform1fARB)
+#define glUniform2fARB                   (_GET_TLS_PROCTABLE()->Uniform2fARB)
+#define glUniform3fARB                   (_GET_TLS_PROCTABLE()->Uniform3fARB)
+#define glUniform4fARB                   (_GET_TLS_PROCTABLE()->Uniform4fARB)
+#define glUniform1iARB                   (_GET_TLS_PROCTABLE()->Uniform1iARB)
+#define glUniform2iARB                   (_GET_TLS_PROCTABLE()->Uniform2iARB)
+#define glUniform3iARB                   (_GET_TLS_PROCTABLE()->Uniform3iARB)
+#define glUniform4iARB                   (_GET_TLS_PROCTABLE()->Uniform4iARB)
+#define glUniform1fvARB                  (_GET_TLS_PROCTABLE()->Uniform1fvARB)
+#define glUniform2fvARB                  (_GET_TLS_PROCTABLE()->Uniform2fvARB)
+#define glUniform3fvARB                  (_GET_TLS_PROCTABLE()->Uniform3fvARB)
+#define glUniform4fvARB                  (_GET_TLS_PROCTABLE()->Uniform4fvARB)
+#define glUniform1ivARB                  (_GET_TLS_PROCTABLE()->Uniform1ivARB)
+#define glUniform2ivARB                  (_GET_TLS_PROCTABLE()->Uniform2ivARB)
+#define glUniform3ivARB                  (_GET_TLS_PROCTABLE()->Uniform3ivARB)
+#define glUniform4ivARB                  (_GET_TLS_PROCTABLE()->Uniform4ivARB)
+#define glUniformMatrix2fvARB            (_GET_TLS_PROCTABLE()->UniformMatrix2fvARB)
+#define glUniformMatrix3fvARB            (_GET_TLS_PROCTABLE()->UniformMatrix3fvARB)
+#define glUniformMatrix4fvARB            (_GET_TLS_PROCTABLE()->UniformMatrix4fvARB)
+#define glGetObjectParameterfvARB        (_GET_TLS_PROCTABLE()->GetObjectParameterfvARB)
+#define glGetObjectParameterivARB        (_GET_TLS_PROCTABLE()->GetObjectParameterivARB)
+#define glGetInfoLogARB                  (_GET_TLS_PROCTABLE()->GetInfoLogARB)
+#define glGetAttachedObjectsARB          (_GET_TLS_PROCTABLE()->GetAttachedObjectsARB)
+#define glGetUniformLocationARB          (_GET_TLS_PROCTABLE()->GetUniformLocationARB)
+#define glGetActiveUniformARB            (_GET_TLS_PROCTABLE()->GetActiveUniformARB)
+#define glGetUniformfvARB                (_GET_TLS_PROCTABLE()->GetUniformfvARB)
+#define glGetUniformivARB                (_GET_TLS_PROCTABLE()->GetUniformivARB)
+#define glGetShaderSourceARB             (_GET_TLS_PROCTABLE()->GetShaderSourceARB)
+#define glBindAttribLocationARB          (_GET_TLS_PROCTABLE()->BindAttribLocationARB)
+#define glGetActiveAttribARB             (_GET_TLS_PROCTABLE()->GetActiveAttribARB)
+#define glGetAttribLocationARB           (_GET_TLS_PROCTABLE()->GetAttribLocationARB)
+#define glBlendColorEXT                  (_GET_TLS_PROCTABLE()->BlendColorEXT)
+#define glPolygonOffsetEXT               (_GET_TLS_PROCTABLE()->PolygonOffsetEXT)
+#define glTexImage3DEXT                  (_GET_TLS_PROCTABLE()->TexImage3DEXT)
+#define glTexSubImage3DEXT               (_GET_TLS_PROCTABLE()->TexSubImage3DEXT)
+#define glGetTexFilterFuncSGIS           (_GET_TLS_PROCTABLE()->GetTexFilterFuncSGIS)
+#define glTexFilterFuncSGIS              (_GET_TLS_PROCTABLE()->TexFilterFuncSGIS)
+#define glTexSubImage1DEXT               (_GET_TLS_PROCTABLE()->TexSubImage1DEXT)
+#define glTexSubImage2DEXT               (_GET_TLS_PROCTABLE()->TexSubImage2DEXT)
+#define glCopyTexImage1DEXT              (_GET_TLS_PROCTABLE()->CopyTexImage1DEXT)
+#define glCopyTexImage2DEXT              (_GET_TLS_PROCTABLE()->CopyTexImage2DEXT)
+#define glCopyTexSubImage1DEXT           (_GET_TLS_PROCTABLE()->CopyTexSubImage1DEXT)
+#define glCopyTexSubImage2DEXT           (_GET_TLS_PROCTABLE()->CopyTexSubImage2DEXT)
+#define glCopyTexSubImage3DEXT           (_GET_TLS_PROCTABLE()->CopyTexSubImage3DEXT)
+#define glGetHistogramEXT                (_GET_TLS_PROCTABLE()->GetHistogramEXT)
+#define glGetHistogramParameterfvEXT     (_GET_TLS_PROCTABLE()->GetHistogramParameterfvEXT)
+#define glGetHistogramParameterivEXT     (_GET_TLS_PROCTABLE()->GetHistogramParameterivEXT)
+#define glGetMinmaxEXT                   (_GET_TLS_PROCTABLE()->GetMinmaxEXT)
+#define glGetMinmaxParameterfvEXT        (_GET_TLS_PROCTABLE()->GetMinmaxParameterfvEXT)
+#define glGetMinmaxParameterivEXT        (_GET_TLS_PROCTABLE()->GetMinmaxParameterivEXT)
+#define glHistogramEXT                   (_GET_TLS_PROCTABLE()->HistogramEXT)
+#define glMinmaxEXT                      (_GET_TLS_PROCTABLE()->MinmaxEXT)
+#define glResetHistogramEXT              (_GET_TLS_PROCTABLE()->ResetHistogramEXT)
+#define glResetMinmaxEXT                 (_GET_TLS_PROCTABLE()->ResetMinmaxEXT)
+#define glConvolutionFilter1DEXT         (_GET_TLS_PROCTABLE()->ConvolutionFilter1DEXT)
+#define glConvolutionFilter2DEXT         (_GET_TLS_PROCTABLE()->ConvolutionFilter2DEXT)
+#define glConvolutionParameterfEXT       (_GET_TLS_PROCTABLE()->ConvolutionParameterfEXT)
+#define glConvolutionParameterfvEXT      (_GET_TLS_PROCTABLE()->ConvolutionParameterfvEXT)
+#define glConvolutionParameteriEXT       (_GET_TLS_PROCTABLE()->ConvolutionParameteriEXT)
+#define glConvolutionParameterivEXT      (_GET_TLS_PROCTABLE()->ConvolutionParameterivEXT)
+#define glCopyConvolutionFilter1DEXT     (_GET_TLS_PROCTABLE()->CopyConvolutionFilter1DEXT)
+#define glCopyConvolutionFilter2DEXT     (_GET_TLS_PROCTABLE()->CopyConvolutionFilter2DEXT)
+#define glGetConvolutionFilterEXT        (_GET_TLS_PROCTABLE()->GetConvolutionFilterEXT)
+#define glGetConvolutionParameterfvEXT   (_GET_TLS_PROCTABLE()->GetConvolutionParameterfvEXT)
+#define glGetConvolutionParameterivEXT   (_GET_TLS_PROCTABLE()->GetConvolutionParameterivEXT)
+#define glGetSeparableFilterEXT          (_GET_TLS_PROCTABLE()->GetSeparableFilterEXT)
+#define glSeparableFilter2DEXT           (_GET_TLS_PROCTABLE()->SeparableFilter2DEXT)
+#define glColorTableSGI                  (_GET_TLS_PROCTABLE()->ColorTableSGI)
+#define glColorTableParameterfvSGI       (_GET_TLS_PROCTABLE()->ColorTableParameterfvSGI)
+#define glColorTableParameterivSGI       (_GET_TLS_PROCTABLE()->ColorTableParameterivSGI)
+#define glCopyColorTableSGI              (_GET_TLS_PROCTABLE()->CopyColorTableSGI)
+#define glGetColorTableSGI               (_GET_TLS_PROCTABLE()->GetColorTableSGI)
+#define glGetColorTableParameterfvSGI    (_GET_TLS_PROCTABLE()->GetColorTableParameterfvSGI)
+#define glGetColorTableParameterivSGI    (_GET_TLS_PROCTABLE()->GetColorTableParameterivSGI)
+#define glPixelTexGenSGIX                (_GET_TLS_PROCTABLE()->PixelTexGenSGIX)
+#define glPixelTexGenParameteriSGIS      (_GET_TLS_PROCTABLE()->PixelTexGenParameteriSGIS)
+#define glPixelTexGenParameterivSGIS     (_GET_TLS_PROCTABLE()->PixelTexGenParameterivSGIS)
+#define glPixelTexGenParameterfSGIS      (_GET_TLS_PROCTABLE()->PixelTexGenParameterfSGIS)
+#define glPixelTexGenParameterfvSGIS     (_GET_TLS_PROCTABLE()->PixelTexGenParameterfvSGIS)
+#define glGetPixelTexGenParameterivSGIS  (_GET_TLS_PROCTABLE()->GetPixelTexGenParameterivSGIS)
+#define glGetPixelTexGenParameterfvSGIS  (_GET_TLS_PROCTABLE()->GetPixelTexGenParameterfvSGIS)
+#define glTexImage4DSGIS                 (_GET_TLS_PROCTABLE()->TexImage4DSGIS)
+#define glTexSubImage4DSGIS              (_GET_TLS_PROCTABLE()->TexSubImage4DSGIS)
+#define glAreTexturesResidentEXT         (_GET_TLS_PROCTABLE()->AreTexturesResidentEXT)
+#define glBindTextureEXT                 (_GET_TLS_PROCTABLE()->BindTextureEXT)
+#define glDeleteTexturesEXT              (_GET_TLS_PROCTABLE()->DeleteTexturesEXT)
+#define glGenTexturesEXT                 (_GET_TLS_PROCTABLE()->GenTexturesEXT)
+#define glIsTextureEXT                   (_GET_TLS_PROCTABLE()->IsTextureEXT)
+#define glPrioritizeTexturesEXT          (_GET_TLS_PROCTABLE()->PrioritizeTexturesEXT)
+#define glDetailTexFuncSGIS              (_GET_TLS_PROCTABLE()->DetailTexFuncSGIS)
+#define glGetDetailTexFuncSGIS           (_GET_TLS_PROCTABLE()->GetDetailTexFuncSGIS)
+#define glSharpenTexFuncSGIS             (_GET_TLS_PROCTABLE()->SharpenTexFuncSGIS)
+#define glGetSharpenTexFuncSGIS          (_GET_TLS_PROCTABLE()->GetSharpenTexFuncSGIS)
+#define glSampleMaskSGIS                 (_GET_TLS_PROCTABLE()->SampleMaskSGIS)
+#define glSamplePatternSGIS              (_GET_TLS_PROCTABLE()->SamplePatternSGIS)
+#define glArrayElementEXT                (_GET_TLS_PROCTABLE()->ArrayElementEXT)
+#define glColorPointerEXT                (_GET_TLS_PROCTABLE()->ColorPointerEXT)
+#define glDrawArraysEXT                  (_GET_TLS_PROCTABLE()->DrawArraysEXT)
+#define glEdgeFlagPointerEXT             (_GET_TLS_PROCTABLE()->EdgeFlagPointerEXT)
+#define glGetPointervEXT                 (_GET_TLS_PROCTABLE()->GetPointervEXT)
+#define glIndexPointerEXT                (_GET_TLS_PROCTABLE()->IndexPointerEXT)
+#define glNormalPointerEXT               (_GET_TLS_PROCTABLE()->NormalPointerEXT)
+#define glTexCoordPointerEXT             (_GET_TLS_PROCTABLE()->TexCoordPointerEXT)
+#define glVertexPointerEXT               (_GET_TLS_PROCTABLE()->VertexPointerEXT)
+#define glBlendEquationEXT               (_GET_TLS_PROCTABLE()->BlendEquationEXT)
+#define glSpriteParameterfSGIX           (_GET_TLS_PROCTABLE()->SpriteParameterfSGIX)
+#define glSpriteParameterfvSGIX          (_GET_TLS_PROCTABLE()->SpriteParameterfvSGIX)
+#define glSpriteParameteriSGIX           (_GET_TLS_PROCTABLE()->SpriteParameteriSGIX)
+#define glSpriteParameterivSGIX          (_GET_TLS_PROCTABLE()->SpriteParameterivSGIX)
+#define glPointParameterfEXT             (_GET_TLS_PROCTABLE()->PointParameterfEXT)
+#define glPointParameterfvEXT            (_GET_TLS_PROCTABLE()->PointParameterfvEXT)
+#define glPointParameterfSGIS            (_GET_TLS_PROCTABLE()->PointParameterfSGIS)
+#define glPointParameterfvSGIS           (_GET_TLS_PROCTABLE()->PointParameterfvSGIS)
+#define glGetInstrumentsSGIX             (_GET_TLS_PROCTABLE()->GetInstrumentsSGIX)
+#define glInstrumentsBufferSGIX          (_GET_TLS_PROCTABLE()->InstrumentsBufferSGIX)
+#define glPollInstrumentsSGIX            (_GET_TLS_PROCTABLE()->PollInstrumentsSGIX)
+#define glReadInstrumentsSGIX            (_GET_TLS_PROCTABLE()->ReadInstrumentsSGIX)
+#define glStartInstrumentsSGIX           (_GET_TLS_PROCTABLE()->StartInstrumentsSGIX)
+#define glStopInstrumentsSGIX            (_GET_TLS_PROCTABLE()->StopInstrumentsSGIX)
+#define glFrameZoomSGIX                  (_GET_TLS_PROCTABLE()->FrameZoomSGIX)
+#define glTagSampleBufferSGIX            (_GET_TLS_PROCTABLE()->TagSampleBufferSGIX)
+#define glDeformationMap3dSGIX           (_GET_TLS_PROCTABLE()->DeformationMap3dSGIX)
+#define glDeformationMap3fSGIX           (_GET_TLS_PROCTABLE()->DeformationMap3fSGIX)
+#define glDeformSGIX                     (_GET_TLS_PROCTABLE()->DeformSGIX)
+#define glLoadIdentityDeformationMapSGIX (_GET_TLS_PROCTABLE()->LoadIdentityDeformationMapSGIX)
+#define glReferencePlaneSGIX             (_GET_TLS_PROCTABLE()->ReferencePlaneSGIX)
+#define glFlushRasterSGIX                (_GET_TLS_PROCTABLE()->FlushRasterSGIX)
+#define glFogFuncSGIS                    (_GET_TLS_PROCTABLE()->FogFuncSGIS)
+#define glGetFogFuncSGIS                 (_GET_TLS_PROCTABLE()->GetFogFuncSGIS)
+#define glImageTransformParameteriHP     (_GET_TLS_PROCTABLE()->ImageTransformParameteriHP)
+#define glImageTransformParameterfHP     (_GET_TLS_PROCTABLE()->ImageTransformParameterfHP)
+#define glImageTransformParameterivHP    (_GET_TLS_PROCTABLE()->ImageTransformParameterivHP)
+#define glImageTransformParameterfvHP    (_GET_TLS_PROCTABLE()->ImageTransformParameterfvHP)
+#define glGetImageTransformParameterivHP (_GET_TLS_PROCTABLE()->GetImageTransformParameterivHP)
+#define glGetImageTransformParameterfvHP (_GET_TLS_PROCTABLE()->GetImageTransformParameterfvHP)
+#define glColorSubTableEXT               (_GET_TLS_PROCTABLE()->ColorSubTableEXT)
+#define glCopyColorSubTableEXT           (_GET_TLS_PROCTABLE()->CopyColorSubTableEXT)
+#define glHintPGI                        (_GET_TLS_PROCTABLE()->HintPGI)
+#define glColorTableEXT                  (_GET_TLS_PROCTABLE()->ColorTableEXT)
+#define glGetColorTableEXT               (_GET_TLS_PROCTABLE()->GetColorTableEXT)
+#define glGetColorTableParameterivEXT    (_GET_TLS_PROCTABLE()->GetColorTableParameterivEXT)
+#define glGetColorTableParameterfvEXT    (_GET_TLS_PROCTABLE()->GetColorTableParameterfvEXT)
+#define glGetListParameterfvSGIX         (_GET_TLS_PROCTABLE()->GetListParameterfvSGIX)
+#define glGetListParameterivSGIX         (_GET_TLS_PROCTABLE()->GetListParameterivSGIX)
+#define glListParameterfSGIX             (_GET_TLS_PROCTABLE()->ListParameterfSGIX)
+#define glListParameterfvSGIX            (_GET_TLS_PROCTABLE()->ListParameterfvSGIX)
+#define glListParameteriSGIX             (_GET_TLS_PROCTABLE()->ListParameteriSGIX)
+#define glListParameterivSGIX            (_GET_TLS_PROCTABLE()->ListParameterivSGIX)
+#define glIndexMaterialEXT               (_GET_TLS_PROCTABLE()->IndexMaterialEXT)
+#define glIndexFuncEXT                   (_GET_TLS_PROCTABLE()->IndexFuncEXT)
+#define glLockArraysEXT                  (_GET_TLS_PROCTABLE()->LockArraysEXT)
+#define glUnlockArraysEXT                (_GET_TLS_PROCTABLE()->UnlockArraysEXT)
+#define glCullParameterdvEXT             (_GET_TLS_PROCTABLE()->CullParameterdvEXT)
+#define glCullParameterfvEXT             (_GET_TLS_PROCTABLE()->CullParameterfvEXT)
+#define glFragmentColorMaterialSGIX      (_GET_TLS_PROCTABLE()->FragmentColorMaterialSGIX)
+#define glFragmentLightfSGIX             (_GET_TLS_PROCTABLE()->FragmentLightfSGIX)
+#define glFragmentLightfvSGIX            (_GET_TLS_PROCTABLE()->FragmentLightfvSGIX)
+#define glFragmentLightiSGIX             (_GET_TLS_PROCTABLE()->FragmentLightiSGIX)
+#define glFragmentLightivSGIX            (_GET_TLS_PROCTABLE()->FragmentLightivSGIX)
+#define glFragmentLightModelfSGIX        (_GET_TLS_PROCTABLE()->FragmentLightModelfSGIX)
+#define glFragmentLightModelfvSGIX       (_GET_TLS_PROCTABLE()->FragmentLightModelfvSGIX)
+#define glFragmentLightModeliSGIX        (_GET_TLS_PROCTABLE()->FragmentLightModeliSGIX)
+#define glFragmentLightModelivSGIX       (_GET_TLS_PROCTABLE()->FragmentLightModelivSGIX)
+#define glFragmentMaterialfSGIX          (_GET_TLS_PROCTABLE()->FragmentMaterialfSGIX)
+#define glFragmentMaterialfvSGIX         (_GET_TLS_PROCTABLE()->FragmentMaterialfvSGIX)
+#define glFragmentMaterialiSGIX          (_GET_TLS_PROCTABLE()->FragmentMaterialiSGIX)
+#define glFragmentMaterialivSGIX         (_GET_TLS_PROCTABLE()->FragmentMaterialivSGIX)
+#define glGetFragmentLightfvSGIX         (_GET_TLS_PROCTABLE()->GetFragmentLightfvSGIX)
+#define glGetFragmentLightivSGIX         (_GET_TLS_PROCTABLE()->GetFragmentLightivSGIX)
+#define glGetFragmentMaterialfvSGIX      (_GET_TLS_PROCTABLE()->GetFragmentMaterialfvSGIX)
+#define glGetFragmentMaterialivSGIX      (_GET_TLS_PROCTABLE()->GetFragmentMaterialivSGIX)
+#define glLightEnviSGIX                  (_GET_TLS_PROCTABLE()->LightEnviSGIX)
+#define glDrawRangeElementsEXT           (_GET_TLS_PROCTABLE()->DrawRangeElementsEXT)
+#define glApplyTextureEXT                (_GET_TLS_PROCTABLE()->ApplyTextureEXT)
+#define glTextureLightEXT                (_GET_TLS_PROCTABLE()->TextureLightEXT)
+#define glTextureMaterialEXT             (_GET_TLS_PROCTABLE()->TextureMaterialEXT)
+#define glAsyncMarkerSGIX                (_GET_TLS_PROCTABLE()->AsyncMarkerSGIX)
+#define glFinishAsyncSGIX                (_GET_TLS_PROCTABLE()->FinishAsyncSGIX)
+#define glPollAsyncSGIX                  (_GET_TLS_PROCTABLE()->PollAsyncSGIX)
+#define glGenAsyncMarkersSGIX            (_GET_TLS_PROCTABLE()->GenAsyncMarkersSGIX)
+#define glDeleteAsyncMarkersSGIX         (_GET_TLS_PROCTABLE()->DeleteAsyncMarkersSGIX)
+#define glIsAsyncMarkerSGIX              (_GET_TLS_PROCTABLE()->IsAsyncMarkerSGIX)
+#define glVertexPointervINTEL            (_GET_TLS_PROCTABLE()->VertexPointervINTEL)
+#define glNormalPointervINTEL            (_GET_TLS_PROCTABLE()->NormalPointervINTEL)
+#define glColorPointervINTEL             (_GET_TLS_PROCTABLE()->ColorPointervINTEL)
+#define glTexCoordPointervINTEL          (_GET_TLS_PROCTABLE()->TexCoordPointervINTEL)
+#define glPixelTransformParameteriEXT    (_GET_TLS_PROCTABLE()->PixelTransformParameteriEXT)
+#define glPixelTransformParameterfEXT    (_GET_TLS_PROCTABLE()->PixelTransformParameterfEXT)
+#define glPixelTransformParameterivEXT   (_GET_TLS_PROCTABLE()->PixelTransformParameterivEXT)
+#define glPixelTransformParameterfvEXT   (_GET_TLS_PROCTABLE()->PixelTransformParameterfvEXT)
+#define glSecondaryColor3bEXT            (_GET_TLS_PROCTABLE()->SecondaryColor3bEXT)
+#define glSecondaryColor3bvEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3bvEXT)
+#define glSecondaryColor3dEXT            (_GET_TLS_PROCTABLE()->SecondaryColor3dEXT)
+#define glSecondaryColor3dvEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3dvEXT)
+#define glSecondaryColor3fEXT            (_GET_TLS_PROCTABLE()->SecondaryColor3fEXT)
+#define glSecondaryColor3fvEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3fvEXT)
+#define glSecondaryColor3iEXT            (_GET_TLS_PROCTABLE()->SecondaryColor3iEXT)
+#define glSecondaryColor3ivEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3ivEXT)
+#define glSecondaryColor3sEXT            (_GET_TLS_PROCTABLE()->SecondaryColor3sEXT)
+#define glSecondaryColor3svEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3svEXT)
+#define glSecondaryColor3ubEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3ubEXT)
+#define glSecondaryColor3ubvEXT          (_GET_TLS_PROCTABLE()->SecondaryColor3ubvEXT)
+#define glSecondaryColor3uiEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3uiEXT)
+#define glSecondaryColor3uivEXT          (_GET_TLS_PROCTABLE()->SecondaryColor3uivEXT)
+#define glSecondaryColor3usEXT           (_GET_TLS_PROCTABLE()->SecondaryColor3usEXT)
+#define glSecondaryColor3usvEXT          (_GET_TLS_PROCTABLE()->SecondaryColor3usvEXT)
+#define glSecondaryColorPointerEXT       (_GET_TLS_PROCTABLE()->SecondaryColorPointerEXT)
+#define glTextureNormalEXT               (_GET_TLS_PROCTABLE()->TextureNormalEXT)
+#define glMultiDrawArraysEXT             (_GET_TLS_PROCTABLE()->MultiDrawArraysEXT)
+#define glMultiDrawElementsEXT           (_GET_TLS_PROCTABLE()->MultiDrawElementsEXT)
+#define glFogCoordfEXT                   (_GET_TLS_PROCTABLE()->FogCoordfEXT)
+#define glFogCoordfvEXT                  (_GET_TLS_PROCTABLE()->FogCoordfvEXT)
+#define glFogCoorddEXT                   (_GET_TLS_PROCTABLE()->FogCoorddEXT)
+#define glFogCoorddvEXT                  (_GET_TLS_PROCTABLE()->FogCoorddvEXT)
+#define glFogCoordPointerEXT             (_GET_TLS_PROCTABLE()->FogCoordPointerEXT)
+#define glTangent3bEXT                   (_GET_TLS_PROCTABLE()->Tangent3bEXT)
+#define glTangent3bvEXT                  (_GET_TLS_PROCTABLE()->Tangent3bvEXT)
+#define glTangent3dEXT                   (_GET_TLS_PROCTABLE()->Tangent3dEXT)
+#define glTangent3dvEXT                  (_GET_TLS_PROCTABLE()->Tangent3dvEXT)
+#define glTangent3fEXT                   (_GET_TLS_PROCTABLE()->Tangent3fEXT)
+#define glTangent3fvEXT                  (_GET_TLS_PROCTABLE()->Tangent3fvEXT)
+#define glTangent3iEXT                   (_GET_TLS_PROCTABLE()->Tangent3iEXT)
+#define glTangent3ivEXT                  (_GET_TLS_PROCTABLE()->Tangent3ivEXT)
+#define glTangent3sEXT                   (_GET_TLS_PROCTABLE()->Tangent3sEXT)
+#define glTangent3svEXT                  (_GET_TLS_PROCTABLE()->Tangent3svEXT)
+#define glBinormal3bEXT                  (_GET_TLS_PROCTABLE()->Binormal3bEXT)
+#define glBinormal3bvEXT                 (_GET_TLS_PROCTABLE()->Binormal3bvEXT)
+#define glBinormal3dEXT                  (_GET_TLS_PROCTABLE()->Binormal3dEXT)
+#define glBinormal3dvEXT                 (_GET_TLS_PROCTABLE()->Binormal3dvEXT)
+#define glBinormal3fEXT                  (_GET_TLS_PROCTABLE()->Binormal3fEXT)
+#define glBinormal3fvEXT                 (_GET_TLS_PROCTABLE()->Binormal3fvEXT)
+#define glBinormal3iEXT                  (_GET_TLS_PROCTABLE()->Binormal3iEXT)
+#define glBinormal3ivEXT                 (_GET_TLS_PROCTABLE()->Binormal3ivEXT)
+#define glBinormal3sEXT                  (_GET_TLS_PROCTABLE()->Binormal3sEXT)
+#define glBinormal3svEXT                 (_GET_TLS_PROCTABLE()->Binormal3svEXT)
+#define glTangentPointerEXT              (_GET_TLS_PROCTABLE()->TangentPointerEXT)
+#define glBinormalPointerEXT             (_GET_TLS_PROCTABLE()->BinormalPointerEXT)
+#define glFinishTextureSUNX              (_GET_TLS_PROCTABLE()->FinishTextureSUNX)
+#define glGlobalAlphaFactorbSUN          (_GET_TLS_PROCTABLE()->GlobalAlphaFactorbSUN)
+#define glGlobalAlphaFactorsSUN          (_GET_TLS_PROCTABLE()->GlobalAlphaFactorsSUN)
+#define glGlobalAlphaFactoriSUN          (_GET_TLS_PROCTABLE()->GlobalAlphaFactoriSUN)
+#define glGlobalAlphaFactorfSUN          (_GET_TLS_PROCTABLE()->GlobalAlphaFactorfSUN)
+#define glGlobalAlphaFactordSUN          (_GET_TLS_PROCTABLE()->GlobalAlphaFactordSUN)
+#define glGlobalAlphaFactorubSUN         (_GET_TLS_PROCTABLE()->GlobalAlphaFactorubSUN)
+#define glGlobalAlphaFactorusSUN         (_GET_TLS_PROCTABLE()->GlobalAlphaFactorusSUN)
+#define glGlobalAlphaFactoruiSUN         (_GET_TLS_PROCTABLE()->GlobalAlphaFactoruiSUN)
+#define glReplacementCodeuiSUN           (_GET_TLS_PROCTABLE()->ReplacementCodeuiSUN)
+#define glReplacementCodeusSUN           (_GET_TLS_PROCTABLE()->ReplacementCodeusSUN)
+#define glReplacementCodeubSUN           (_GET_TLS_PROCTABLE()->ReplacementCodeubSUN)
+#define glReplacementCodeuivSUN          (_GET_TLS_PROCTABLE()->ReplacementCodeuivSUN)
+#define glReplacementCodeusvSUN          (_GET_TLS_PROCTABLE()->ReplacementCodeusvSUN)
+#define glReplacementCodeubvSUN          (_GET_TLS_PROCTABLE()->ReplacementCodeubvSUN)
+#define glReplacementCodePointerSUN      (_GET_TLS_PROCTABLE()->ReplacementCodePointerSUN)
+#define glColor4ubVertex2fSUN            (_GET_TLS_PROCTABLE()->Color4ubVertex2fSUN)
+#define glColor4ubVertex2fvSUN           (_GET_TLS_PROCTABLE()->Color4ubVertex2fvSUN)
+#define glColor4ubVertex3fSUN            (_GET_TLS_PROCTABLE()->Color4ubVertex3fSUN)
+#define glColor4ubVertex3fvSUN           (_GET_TLS_PROCTABLE()->Color4ubVertex3fvSUN)
+#define glColor3fVertex3fSUN             (_GET_TLS_PROCTABLE()->Color3fVertex3fSUN)
+#define glColor3fVertex3fvSUN            (_GET_TLS_PROCTABLE()->Color3fVertex3fvSUN)
+#define glNormal3fVertex3fSUN            (_GET_TLS_PROCTABLE()->Normal3fVertex3fSUN)
+#define glNormal3fVertex3fvSUN           (_GET_TLS_PROCTABLE()->Normal3fVertex3fvSUN)
+#define glColor4fNormal3fVertex3fSUN     (_GET_TLS_PROCTABLE()->Color4fNormal3fVertex3fSUN)
+#define glColor4fNormal3fVertex3fvSUN    (_GET_TLS_PROCTABLE()->Color4fNormal3fVertex3fvSUN)
+#define glTexCoord2fVertex3fSUN          (_GET_TLS_PROCTABLE()->TexCoord2fVertex3fSUN)
+#define glTexCoord2fVertex3fvSUN         (_GET_TLS_PROCTABLE()->TexCoord2fVertex3fvSUN)
+#define glTexCoord4fVertex4fSUN          (_GET_TLS_PROCTABLE()->TexCoord4fVertex4fSUN)
+#define glTexCoord4fVertex4fvSUN         (_GET_TLS_PROCTABLE()->TexCoord4fVertex4fvSUN)
+#define glTexCoord2fColor4ubVertex3fSUN  (_GET_TLS_PROCTABLE()->TexCoord2fColor4ubVertex3fSUN)
+#define glTexCoord2fColor4ubVertex3fvSUN (_GET_TLS_PROCTABLE()->TexCoord2fColor4ubVertex3fvSUN)
+#define glTexCoord2fColor3fVertex3fSUN   (_GET_TLS_PROCTABLE()->TexCoord2fColor3fVertex3fSUN)
+#define glTexCoord2fColor3fVertex3fvSUN  (_GET_TLS_PROCTABLE()->TexCoord2fColor3fVertex3fvSUN)
+#define glTexCoord2fNormal3fVertex3fSUN  (_GET_TLS_PROCTABLE()->TexCoord2fNormal3fVertex3fSUN)
+#define glTexCoord2fNormal3fVertex3fvSUN (_GET_TLS_PROCTABLE()->TexCoord2fNormal3fVertex3fvSUN)
+#define glTexCoord2fColor4fNormal3fVertex3fSUN (_GET_TLS_PROCTABLE()->TexCoord2fColor4fNormal3fVertex3fSUN)
+#define glTexCoord2fColor4fNormal3fVertex3fvSUN (_GET_TLS_PROCTABLE()->TexCoord2fColor4fNormal3fVertex3fvSUN)
+#define glTexCoord4fColor4fNormal3fVertex4fSUN (_GET_TLS_PROCTABLE()->TexCoord4fColor4fNormal3fVertex4fSUN)
+#define glTexCoord4fColor4fNormal3fVertex4fvSUN (_GET_TLS_PROCTABLE()->TexCoord4fColor4fNormal3fVertex4fvSUN)
+#define glReplacementCodeuiVertex3fSUN   (_GET_TLS_PROCTABLE()->ReplacementCodeuiVertex3fSUN)
+#define glReplacementCodeuiVertex3fvSUN  (_GET_TLS_PROCTABLE()->ReplacementCodeuiVertex3fvSUN)
+#define glReplacementCodeuiColor4ubVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiColor4ubVertex3fSUN)
+#define glReplacementCodeuiColor4ubVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiColor4ubVertex3fvSUN)
+#define glReplacementCodeuiColor3fVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiColor3fVertex3fSUN)
+#define glReplacementCodeuiColor3fVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiColor3fVertex3fvSUN)
+#define glReplacementCodeuiNormal3fVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiNormal3fVertex3fSUN)
+#define glReplacementCodeuiNormal3fVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiNormal3fVertex3fvSUN)
+#define glReplacementCodeuiColor4fNormal3fVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiColor4fNormal3fVertex3fSUN)
+#define glReplacementCodeuiColor4fNormal3fVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiColor4fNormal3fVertex3fvSUN)
+#define glReplacementCodeuiTexCoord2fVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiTexCoord2fVertex3fSUN)
+#define glReplacementCodeuiTexCoord2fVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiTexCoord2fVertex3fvSUN)
+#define glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiTexCoord2fNormal3fVertex3fSUN)
+#define glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN)
+#define glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN)
+#define glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN (_GET_TLS_PROCTABLE()->ReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN)
+#define glBlendFuncSeparateEXT           (_GET_TLS_PROCTABLE()->BlendFuncSeparateEXT)
+#define glBlendFuncSeparateINGR          (_GET_TLS_PROCTABLE()->BlendFuncSeparateINGR)
+#define glVertexWeightfEXT               (_GET_TLS_PROCTABLE()->VertexWeightfEXT)
+#define glVertexWeightfvEXT              (_GET_TLS_PROCTABLE()->VertexWeightfvEXT)
+#define glVertexWeightPointerEXT         (_GET_TLS_PROCTABLE()->VertexWeightPointerEXT)
+#define glFlushVertexArrayRangeNV        (_GET_TLS_PROCTABLE()->FlushVertexArrayRangeNV)
+#define glVertexArrayRangeNV             (_GET_TLS_PROCTABLE()->VertexArrayRangeNV)
+#define glCombinerParameterfvNV          (_GET_TLS_PROCTABLE()->CombinerParameterfvNV)
+#define glCombinerParameterfNV           (_GET_TLS_PROCTABLE()->CombinerParameterfNV)
+#define glCombinerParameterivNV          (_GET_TLS_PROCTABLE()->CombinerParameterivNV)
+#define glCombinerParameteriNV           (_GET_TLS_PROCTABLE()->CombinerParameteriNV)
+#define glCombinerInputNV                (_GET_TLS_PROCTABLE()->CombinerInputNV)
+#define glCombinerOutputNV               (_GET_TLS_PROCTABLE()->CombinerOutputNV)
+#define glFinalCombinerInputNV           (_GET_TLS_PROCTABLE()->FinalCombinerInputNV)
+#define glGetCombinerInputParameterfvNV  (_GET_TLS_PROCTABLE()->GetCombinerInputParameterfvNV)
+#define glGetCombinerInputParameterivNV  (_GET_TLS_PROCTABLE()->GetCombinerInputParameterivNV)
+#define glGetCombinerOutputParameterfvNV (_GET_TLS_PROCTABLE()->GetCombinerOutputParameterfvNV)
+#define glGetCombinerOutputParameterivNV (_GET_TLS_PROCTABLE()->GetCombinerOutputParameterivNV)
+#define glGetFinalCombinerInputParameterfvNV (_GET_TLS_PROCTABLE()->GetFinalCombinerInputParameterfvNV)
+#define glGetFinalCombinerInputParameterivNV (_GET_TLS_PROCTABLE()->GetFinalCombinerInputParameterivNV)
+#define glResizeBuffersMESA              (_GET_TLS_PROCTABLE()->ResizeBuffersMESA)
+#define glWindowPos2dMESA                (_GET_TLS_PROCTABLE()->WindowPos2dMESA)
+#define glWindowPos2dvMESA               (_GET_TLS_PROCTABLE()->WindowPos2dvMESA)
+#define glWindowPos2fMESA                (_GET_TLS_PROCTABLE()->WindowPos2fMESA)
+#define glWindowPos2fvMESA               (_GET_TLS_PROCTABLE()->WindowPos2fvMESA)
+#define glWindowPos2iMESA                (_GET_TLS_PROCTABLE()->WindowPos2iMESA)
+#define glWindowPos2ivMESA               (_GET_TLS_PROCTABLE()->WindowPos2ivMESA)
+#define glWindowPos2sMESA                (_GET_TLS_PROCTABLE()->WindowPos2sMESA)
+#define glWindowPos2svMESA               (_GET_TLS_PROCTABLE()->WindowPos2svMESA)
+#define glWindowPos3dMESA                (_GET_TLS_PROCTABLE()->WindowPos3dMESA)
+#define glWindowPos3dvMESA               (_GET_TLS_PROCTABLE()->WindowPos3dvMESA)
+#define glWindowPos3fMESA                (_GET_TLS_PROCTABLE()->WindowPos3fMESA)
+#define glWindowPos3fvMESA               (_GET_TLS_PROCTABLE()->WindowPos3fvMESA)
+#define glWindowPos3iMESA                (_GET_TLS_PROCTABLE()->WindowPos3iMESA)
+#define glWindowPos3ivMESA               (_GET_TLS_PROCTABLE()->WindowPos3ivMESA)
+#define glWindowPos3sMESA                (_GET_TLS_PROCTABLE()->WindowPos3sMESA)
+#define glWindowPos3svMESA               (_GET_TLS_PROCTABLE()->WindowPos3svMESA)
+#define glWindowPos4dMESA                (_GET_TLS_PROCTABLE()->WindowPos4dMESA)
+#define glWindowPos4dvMESA               (_GET_TLS_PROCTABLE()->WindowPos4dvMESA)
+#define glWindowPos4fMESA                (_GET_TLS_PROCTABLE()->WindowPos4fMESA)
+#define glWindowPos4fvMESA               (_GET_TLS_PROCTABLE()->WindowPos4fvMESA)
+#define glWindowPos4iMESA                (_GET_TLS_PROCTABLE()->WindowPos4iMESA)
+#define glWindowPos4ivMESA               (_GET_TLS_PROCTABLE()->WindowPos4ivMESA)
+#define glWindowPos4sMESA                (_GET_TLS_PROCTABLE()->WindowPos4sMESA)
+#define glWindowPos4svMESA               (_GET_TLS_PROCTABLE()->WindowPos4svMESA)
+#define glMultiModeDrawArraysIBM         (_GET_TLS_PROCTABLE()->MultiModeDrawArraysIBM)
+#define glMultiModeDrawElementsIBM       (_GET_TLS_PROCTABLE()->MultiModeDrawElementsIBM)
+#define glColorPointerListIBM            (_GET_TLS_PROCTABLE()->ColorPointerListIBM)
+#define glSecondaryColorPointerListIBM   (_GET_TLS_PROCTABLE()->SecondaryColorPointerListIBM)
+#define glEdgeFlagPointerListIBM         (_GET_TLS_PROCTABLE()->EdgeFlagPointerListIBM)
+#define glFogCoordPointerListIBM         (_GET_TLS_PROCTABLE()->FogCoordPointerListIBM)
+#define glIndexPointerListIBM            (_GET_TLS_PROCTABLE()->IndexPointerListIBM)
+#define glNormalPointerListIBM           (_GET_TLS_PROCTABLE()->NormalPointerListIBM)
+#define glTexCoordPointerListIBM         (_GET_TLS_PROCTABLE()->TexCoordPointerListIBM)
+#define glVertexPointerListIBM           (_GET_TLS_PROCTABLE()->VertexPointerListIBM)
+#define glTbufferMask3DFX                (_GET_TLS_PROCTABLE()->TbufferMask3DFX)
+#define glSampleMaskEXT                  (_GET_TLS_PROCTABLE()->SampleMaskEXT)
+#define glSamplePatternEXT               (_GET_TLS_PROCTABLE()->SamplePatternEXT)
+#define glTextureColorMaskSGIS           (_GET_TLS_PROCTABLE()->TextureColorMaskSGIS)
+#define glIglooInterfaceSGIX             (_GET_TLS_PROCTABLE()->IglooInterfaceSGIX)
+#define glDeleteFencesNV                 (_GET_TLS_PROCTABLE()->DeleteFencesNV)
+#define glGenFencesNV                    (_GET_TLS_PROCTABLE()->GenFencesNV)
+#define glIsFenceNV                      (_GET_TLS_PROCTABLE()->IsFenceNV)
+#define glTestFenceNV                    (_GET_TLS_PROCTABLE()->TestFenceNV)
+#define glGetFenceivNV                   (_GET_TLS_PROCTABLE()->GetFenceivNV)
+#define glFinishFenceNV                  (_GET_TLS_PROCTABLE()->FinishFenceNV)
+#define glSetFenceNV                     (_GET_TLS_PROCTABLE()->SetFenceNV)
+#define glMapControlPointsNV             (_GET_TLS_PROCTABLE()->MapControlPointsNV)
+#define glMapParameterivNV               (_GET_TLS_PROCTABLE()->MapParameterivNV)
+#define glMapParameterfvNV               (_GET_TLS_PROCTABLE()->MapParameterfvNV)
+#define glGetMapControlPointsNV          (_GET_TLS_PROCTABLE()->GetMapControlPointsNV)
+#define glGetMapParameterivNV            (_GET_TLS_PROCTABLE()->GetMapParameterivNV)
+#define glGetMapParameterfvNV            (_GET_TLS_PROCTABLE()->GetMapParameterfvNV)
+#define glGetMapAttribParameterivNV      (_GET_TLS_PROCTABLE()->GetMapAttribParameterivNV)
+#define glGetMapAttribParameterfvNV      (_GET_TLS_PROCTABLE()->GetMapAttribParameterfvNV)
+#define glEvalMapsNV                     (_GET_TLS_PROCTABLE()->EvalMapsNV)
+#define glCombinerStageParameterfvNV     (_GET_TLS_PROCTABLE()->CombinerStageParameterfvNV)
+#define glGetCombinerStageParameterfvNV  (_GET_TLS_PROCTABLE()->GetCombinerStageParameterfvNV)
+#define glAreProgramsResidentNV          (_GET_TLS_PROCTABLE()->AreProgramsResidentNV)
+#define glBindProgramNV                  (_GET_TLS_PROCTABLE()->BindProgramNV)
+#define glDeleteProgramsNV               (_GET_TLS_PROCTABLE()->DeleteProgramsNV)
+#define glExecuteProgramNV               (_GET_TLS_PROCTABLE()->ExecuteProgramNV)
+#define glGenProgramsNV                  (_GET_TLS_PROCTABLE()->GenProgramsNV)
+#define glGetProgramParameterdvNV        (_GET_TLS_PROCTABLE()->GetProgramParameterdvNV)
+#define glGetProgramParameterfvNV        (_GET_TLS_PROCTABLE()->GetProgramParameterfvNV)
+#define glGetProgramivNV                 (_GET_TLS_PROCTABLE()->GetProgramivNV)
+#define glGetProgramStringNV             (_GET_TLS_PROCTABLE()->GetProgramStringNV)
+#define glGetTrackMatrixivNV             (_GET_TLS_PROCTABLE()->GetTrackMatrixivNV)
+#define glGetVertexAttribdvNV            (_GET_TLS_PROCTABLE()->GetVertexAttribdvNV)
+#define glGetVertexAttribfvNV            (_GET_TLS_PROCTABLE()->GetVertexAttribfvNV)
+#define glGetVertexAttribivNV            (_GET_TLS_PROCTABLE()->GetVertexAttribivNV)
+#define glGetVertexAttribPointervNV      (_GET_TLS_PROCTABLE()->GetVertexAttribPointervNV)
+#define glIsProgramNV                    (_GET_TLS_PROCTABLE()->IsProgramNV)
+#define glLoadProgramNV                  (_GET_TLS_PROCTABLE()->LoadProgramNV)
+#define glProgramParameter4dNV           (_GET_TLS_PROCTABLE()->ProgramParameter4dNV)
+#define glProgramParameter4dvNV          (_GET_TLS_PROCTABLE()->ProgramParameter4dvNV)
+#define glProgramParameter4fNV           (_GET_TLS_PROCTABLE()->ProgramParameter4fNV)
+#define glProgramParameter4fvNV          (_GET_TLS_PROCTABLE()->ProgramParameter4fvNV)
+#define glProgramParameters4dvNV         (_GET_TLS_PROCTABLE()->ProgramParameters4dvNV)
+#define glProgramParameters4fvNV         (_GET_TLS_PROCTABLE()->ProgramParameters4fvNV)
+#define glRequestResidentProgramsNV      (_GET_TLS_PROCTABLE()->RequestResidentProgramsNV)
+#define glTrackMatrixNV                  (_GET_TLS_PROCTABLE()->TrackMatrixNV)
+#define glVertexAttribPointerNV          (_GET_TLS_PROCTABLE()->VertexAttribPointerNV)
+#define glVertexAttrib1dNV               (_GET_TLS_PROCTABLE()->VertexAttrib1dNV)
+#define glVertexAttrib1dvNV              (_GET_TLS_PROCTABLE()->VertexAttrib1dvNV)
+#define glVertexAttrib1fNV               (_GET_TLS_PROCTABLE()->VertexAttrib1fNV)
+#define glVertexAttrib1fvNV              (_GET_TLS_PROCTABLE()->VertexAttrib1fvNV)
+#define glVertexAttrib1sNV               (_GET_TLS_PROCTABLE()->VertexAttrib1sNV)
+#define glVertexAttrib1svNV              (_GET_TLS_PROCTABLE()->VertexAttrib1svNV)
+#define glVertexAttrib2dNV               (_GET_TLS_PROCTABLE()->VertexAttrib2dNV)
+#define glVertexAttrib2dvNV              (_GET_TLS_PROCTABLE()->VertexAttrib2dvNV)
+#define glVertexAttrib2fNV               (_GET_TLS_PROCTABLE()->VertexAttrib2fNV)
+#define glVertexAttrib2fvNV              (_GET_TLS_PROCTABLE()->VertexAttrib2fvNV)
+#define glVertexAttrib2sNV               (_GET_TLS_PROCTABLE()->VertexAttrib2sNV)
+#define glVertexAttrib2svNV              (_GET_TLS_PROCTABLE()->VertexAttrib2svNV)
+#define glVertexAttrib3dNV               (_GET_TLS_PROCTABLE()->VertexAttrib3dNV)
+#define glVertexAttrib3dvNV              (_GET_TLS_PROCTABLE()->VertexAttrib3dvNV)
+#define glVertexAttrib3fNV               (_GET_TLS_PROCTABLE()->VertexAttrib3fNV)
+#define glVertexAttrib3fvNV              (_GET_TLS_PROCTABLE()->VertexAttrib3fvNV)
+#define glVertexAttrib3sNV               (_GET_TLS_PROCTABLE()->VertexAttrib3sNV)
+#define glVertexAttrib3svNV              (_GET_TLS_PROCTABLE()->VertexAttrib3svNV)
+#define glVertexAttrib4dNV               (_GET_TLS_PROCTABLE()->VertexAttrib4dNV)
+#define glVertexAttrib4dvNV              (_GET_TLS_PROCTABLE()->VertexAttrib4dvNV)
+#define glVertexAttrib4fNV               (_GET_TLS_PROCTABLE()->VertexAttrib4fNV)
+#define glVertexAttrib4fvNV              (_GET_TLS_PROCTABLE()->VertexAttrib4fvNV)
+#define glVertexAttrib4sNV               (_GET_TLS_PROCTABLE()->VertexAttrib4sNV)
+#define glVertexAttrib4svNV              (_GET_TLS_PROCTABLE()->VertexAttrib4svNV)
+#define glVertexAttrib4ubNV              (_GET_TLS_PROCTABLE()->VertexAttrib4ubNV)
+#define glVertexAttrib4ubvNV             (_GET_TLS_PROCTABLE()->VertexAttrib4ubvNV)
+#define glVertexAttribs1dvNV             (_GET_TLS_PROCTABLE()->VertexAttribs1dvNV)
+#define glVertexAttribs1fvNV             (_GET_TLS_PROCTABLE()->VertexAttribs1fvNV)
+#define glVertexAttribs1svNV             (_GET_TLS_PROCTABLE()->VertexAttribs1svNV)
+#define glVertexAttribs2dvNV             (_GET_TLS_PROCTABLE()->VertexAttribs2dvNV)
+#define glVertexAttribs2fvNV             (_GET_TLS_PROCTABLE()->VertexAttribs2fvNV)
+#define glVertexAttribs2svNV             (_GET_TLS_PROCTABLE()->VertexAttribs2svNV)
+#define glVertexAttribs3dvNV             (_GET_TLS_PROCTABLE()->VertexAttribs3dvNV)
+#define glVertexAttribs3fvNV             (_GET_TLS_PROCTABLE()->VertexAttribs3fvNV)
+#define glVertexAttribs3svNV             (_GET_TLS_PROCTABLE()->VertexAttribs3svNV)
+#define glVertexAttribs4dvNV             (_GET_TLS_PROCTABLE()->VertexAttribs4dvNV)
+#define glVertexAttribs4fvNV             (_GET_TLS_PROCTABLE()->VertexAttribs4fvNV)
+#define glVertexAttribs4svNV             (_GET_TLS_PROCTABLE()->VertexAttribs4svNV)
+#define glVertexAttribs4ubvNV            (_GET_TLS_PROCTABLE()->VertexAttribs4ubvNV)
+#define glTexBumpParameterivATI          (_GET_TLS_PROCTABLE()->TexBumpParameterivATI)
+#define glTexBumpParameterfvATI          (_GET_TLS_PROCTABLE()->TexBumpParameterfvATI)
+#define glGetTexBumpParameterivATI       (_GET_TLS_PROCTABLE()->GetTexBumpParameterivATI)
+#define glGetTexBumpParameterfvATI       (_GET_TLS_PROCTABLE()->GetTexBumpParameterfvATI)
+#define glGenFragmentShadersATI          (_GET_TLS_PROCTABLE()->GenFragmentShadersATI)
+#define glBindFragmentShaderATI          (_GET_TLS_PROCTABLE()->BindFragmentShaderATI)
+#define glDeleteFragmentShaderATI        (_GET_TLS_PROCTABLE()->DeleteFragmentShaderATI)
+#define glBeginFragmentShaderATI         (_GET_TLS_PROCTABLE()->BeginFragmentShaderATI)
+#define glEndFragmentShaderATI           (_GET_TLS_PROCTABLE()->EndFragmentShaderATI)
+#define glPassTexCoordATI                (_GET_TLS_PROCTABLE()->PassTexCoordATI)
+#define glSampleMapATI                   (_GET_TLS_PROCTABLE()->SampleMapATI)
+#define glColorFragmentOp1ATI            (_GET_TLS_PROCTABLE()->ColorFragmentOp1ATI)
+#define glColorFragmentOp2ATI            (_GET_TLS_PROCTABLE()->ColorFragmentOp2ATI)
+#define glColorFragmentOp3ATI            (_GET_TLS_PROCTABLE()->ColorFragmentOp3ATI)
+#define glAlphaFragmentOp1ATI            (_GET_TLS_PROCTABLE()->AlphaFragmentOp1ATI)
+#define glAlphaFragmentOp2ATI            (_GET_TLS_PROCTABLE()->AlphaFragmentOp2ATI)
+#define glAlphaFragmentOp3ATI            (_GET_TLS_PROCTABLE()->AlphaFragmentOp3ATI)
+#define glSetFragmentShaderConstantATI   (_GET_TLS_PROCTABLE()->SetFragmentShaderConstantATI)
+#define glPNTrianglesiATI                (_GET_TLS_PROCTABLE()->PNTrianglesiATI)
+#define glPNTrianglesfATI                (_GET_TLS_PROCTABLE()->PNTrianglesfATI)
+#define glNewObjectBufferATI             (_GET_TLS_PROCTABLE()->NewObjectBufferATI)
+#define glIsObjectBufferATI              (_GET_TLS_PROCTABLE()->IsObjectBufferATI)
+#define glUpdateObjectBufferATI          (_GET_TLS_PROCTABLE()->UpdateObjectBufferATI)
+#define glGetObjectBufferfvATI           (_GET_TLS_PROCTABLE()->GetObjectBufferfvATI)
+#define glGetObjectBufferivATI           (_GET_TLS_PROCTABLE()->GetObjectBufferivATI)
+#define glFreeObjectBufferATI            (_GET_TLS_PROCTABLE()->FreeObjectBufferATI)
+#define glArrayObjectATI                 (_GET_TLS_PROCTABLE()->ArrayObjectATI)
+#define glGetArrayObjectfvATI            (_GET_TLS_PROCTABLE()->GetArrayObjectfvATI)
+#define glGetArrayObjectivATI            (_GET_TLS_PROCTABLE()->GetArrayObjectivATI)
+#define glVariantArrayObjectATI          (_GET_TLS_PROCTABLE()->VariantArrayObjectATI)
+#define glGetVariantArrayObjectfvATI     (_GET_TLS_PROCTABLE()->GetVariantArrayObjectfvATI)
+#define glGetVariantArrayObjectivATI     (_GET_TLS_PROCTABLE()->GetVariantArrayObjectivATI)
+#define glBeginVertexShaderEXT           (_GET_TLS_PROCTABLE()->BeginVertexShaderEXT)
+#define glEndVertexShaderEXT             (_GET_TLS_PROCTABLE()->EndVertexShaderEXT)
+#define glBindVertexShaderEXT            (_GET_TLS_PROCTABLE()->BindVertexShaderEXT)
+#define glGenVertexShadersEXT            (_GET_TLS_PROCTABLE()->GenVertexShadersEXT)
+#define glDeleteVertexShaderEXT          (_GET_TLS_PROCTABLE()->DeleteVertexShaderEXT)
+#define glShaderOp1EXT                   (_GET_TLS_PROCTABLE()->ShaderOp1EXT)
+#define glShaderOp2EXT                   (_GET_TLS_PROCTABLE()->ShaderOp2EXT)
+#define glShaderOp3EXT                   (_GET_TLS_PROCTABLE()->ShaderOp3EXT)
+#define glSwizzleEXT                     (_GET_TLS_PROCTABLE()->SwizzleEXT)
+#define glWriteMaskEXT                   (_GET_TLS_PROCTABLE()->WriteMaskEXT)
+#define glInsertComponentEXT             (_GET_TLS_PROCTABLE()->InsertComponentEXT)
+#define glExtractComponentEXT            (_GET_TLS_PROCTABLE()->ExtractComponentEXT)
+#define glGenSymbolsEXT                  (_GET_TLS_PROCTABLE()->GenSymbolsEXT)
+#define glSetInvariantEXT                (_GET_TLS_PROCTABLE()->SetInvariantEXT)
+#define glSetLocalConstantEXT            (_GET_TLS_PROCTABLE()->SetLocalConstantEXT)
+#define glVariantbvEXT                   (_GET_TLS_PROCTABLE()->VariantbvEXT)
+#define glVariantsvEXT                   (_GET_TLS_PROCTABLE()->VariantsvEXT)
+#define glVariantivEXT                   (_GET_TLS_PROCTABLE()->VariantivEXT)
+#define glVariantfvEXT                   (_GET_TLS_PROCTABLE()->VariantfvEXT)
+#define glVariantdvEXT                   (_GET_TLS_PROCTABLE()->VariantdvEXT)
+#define glVariantubvEXT                  (_GET_TLS_PROCTABLE()->VariantubvEXT)
+#define glVariantusvEXT                  (_GET_TLS_PROCTABLE()->VariantusvEXT)
+#define glVariantuivEXT                  (_GET_TLS_PROCTABLE()->VariantuivEXT)
+#define glVariantPointerEXT              (_GET_TLS_PROCTABLE()->VariantPointerEXT)
+#define glEnableVariantClientStateEXT    (_GET_TLS_PROCTABLE()->EnableVariantClientStateEXT)
+#define glDisableVariantClientStateEXT   (_GET_TLS_PROCTABLE()->DisableVariantClientStateEXT)
+#define glBindLightParameterEXT          (_GET_TLS_PROCTABLE()->BindLightParameterEXT)
+#define glBindMaterialParameterEXT       (_GET_TLS_PROCTABLE()->BindMaterialParameterEXT)
+#define glBindTexGenParameterEXT         (_GET_TLS_PROCTABLE()->BindTexGenParameterEXT)
+#define glBindTextureUnitParameterEXT    (_GET_TLS_PROCTABLE()->BindTextureUnitParameterEXT)
+#define glBindParameterEXT               (_GET_TLS_PROCTABLE()->BindParameterEXT)
+#define glIsVariantEnabledEXT            (_GET_TLS_PROCTABLE()->IsVariantEnabledEXT)
+#define glGetVariantBooleanvEXT          (_GET_TLS_PROCTABLE()->GetVariantBooleanvEXT)
+#define glGetVariantIntegervEXT          (_GET_TLS_PROCTABLE()->GetVariantIntegervEXT)
+#define glGetVariantFloatvEXT            (_GET_TLS_PROCTABLE()->GetVariantFloatvEXT)
+#define glGetVariantPointervEXT          (_GET_TLS_PROCTABLE()->GetVariantPointervEXT)
+#define glGetInvariantBooleanvEXT        (_GET_TLS_PROCTABLE()->GetInvariantBooleanvEXT)
+#define glGetInvariantIntegervEXT        (_GET_TLS_PROCTABLE()->GetInvariantIntegervEXT)
+#define glGetInvariantFloatvEXT          (_GET_TLS_PROCTABLE()->GetInvariantFloatvEXT)
+#define glGetLocalConstantBooleanvEXT    (_GET_TLS_PROCTABLE()->GetLocalConstantBooleanvEXT)
+#define glGetLocalConstantIntegervEXT    (_GET_TLS_PROCTABLE()->GetLocalConstantIntegervEXT)
+#define glGetLocalConstantFloatvEXT      (_GET_TLS_PROCTABLE()->GetLocalConstantFloatvEXT)
+#define glVertexStream1sATI              (_GET_TLS_PROCTABLE()->VertexStream1sATI)
+#define glVertexStream1svATI             (_GET_TLS_PROCTABLE()->VertexStream1svATI)
+#define glVertexStream1iATI              (_GET_TLS_PROCTABLE()->VertexStream1iATI)
+#define glVertexStream1ivATI             (_GET_TLS_PROCTABLE()->VertexStream1ivATI)
+#define glVertexStream1fATI              (_GET_TLS_PROCTABLE()->VertexStream1fATI)
+#define glVertexStream1fvATI             (_GET_TLS_PROCTABLE()->VertexStream1fvATI)
+#define glVertexStream1dATI              (_GET_TLS_PROCTABLE()->VertexStream1dATI)
+#define glVertexStream1dvATI             (_GET_TLS_PROCTABLE()->VertexStream1dvATI)
+#define glVertexStream2sATI              (_GET_TLS_PROCTABLE()->VertexStream2sATI)
+#define glVertexStream2svATI             (_GET_TLS_PROCTABLE()->VertexStream2svATI)
+#define glVertexStream2iATI              (_GET_TLS_PROCTABLE()->VertexStream2iATI)
+#define glVertexStream2ivATI             (_GET_TLS_PROCTABLE()->VertexStream2ivATI)
+#define glVertexStream2fATI              (_GET_TLS_PROCTABLE()->VertexStream2fATI)
+#define glVertexStream2fvATI             (_GET_TLS_PROCTABLE()->VertexStream2fvATI)
+#define glVertexStream2dATI              (_GET_TLS_PROCTABLE()->VertexStream2dATI)
+#define glVertexStream2dvATI             (_GET_TLS_PROCTABLE()->VertexStream2dvATI)
+#define glVertexStream3sATI              (_GET_TLS_PROCTABLE()->VertexStream3sATI)
+#define glVertexStream3svATI             (_GET_TLS_PROCTABLE()->VertexStream3svATI)
+#define glVertexStream3iATI              (_GET_TLS_PROCTABLE()->VertexStream3iATI)
+#define glVertexStream3ivATI             (_GET_TLS_PROCTABLE()->VertexStream3ivATI)
+#define glVertexStream3fATI              (_GET_TLS_PROCTABLE()->VertexStream3fATI)
+#define glVertexStream3fvATI             (_GET_TLS_PROCTABLE()->VertexStream3fvATI)
+#define glVertexStream3dATI              (_GET_TLS_PROCTABLE()->VertexStream3dATI)
+#define glVertexStream3dvATI             (_GET_TLS_PROCTABLE()->VertexStream3dvATI)
+#define glVertexStream4sATI              (_GET_TLS_PROCTABLE()->VertexStream4sATI)
+#define glVertexStream4svATI             (_GET_TLS_PROCTABLE()->VertexStream4svATI)
+#define glVertexStream4iATI              (_GET_TLS_PROCTABLE()->VertexStream4iATI)
+#define glVertexStream4ivATI             (_GET_TLS_PROCTABLE()->VertexStream4ivATI)
+#define glVertexStream4fATI              (_GET_TLS_PROCTABLE()->VertexStream4fATI)
+#define glVertexStream4fvATI             (_GET_TLS_PROCTABLE()->VertexStream4fvATI)
+#define glVertexStream4dATI              (_GET_TLS_PROCTABLE()->VertexStream4dATI)
+#define glVertexStream4dvATI             (_GET_TLS_PROCTABLE()->VertexStream4dvATI)
+#define glNormalStream3bATI              (_GET_TLS_PROCTABLE()->NormalStream3bATI)
+#define glNormalStream3bvATI             (_GET_TLS_PROCTABLE()->NormalStream3bvATI)
+#define glNormalStream3sATI              (_GET_TLS_PROCTABLE()->NormalStream3sATI)
+#define glNormalStream3svATI             (_GET_TLS_PROCTABLE()->NormalStream3svATI)
+#define glNormalStream3iATI              (_GET_TLS_PROCTABLE()->NormalStream3iATI)
+#define glNormalStream3ivATI             (_GET_TLS_PROCTABLE()->NormalStream3ivATI)
+#define glNormalStream3fATI              (_GET_TLS_PROCTABLE()->NormalStream3fATI)
+#define glNormalStream3fvATI             (_GET_TLS_PROCTABLE()->NormalStream3fvATI)
+#define glNormalStream3dATI              (_GET_TLS_PROCTABLE()->NormalStream3dATI)
+#define glNormalStream3dvATI             (_GET_TLS_PROCTABLE()->NormalStream3dvATI)
+#define glClientActiveVertexStreamATI    (_GET_TLS_PROCTABLE()->ClientActiveVertexStreamATI)
+#define glVertexBlendEnviATI             (_GET_TLS_PROCTABLE()->VertexBlendEnviATI)
+#define glVertexBlendEnvfATI             (_GET_TLS_PROCTABLE()->VertexBlendEnvfATI)
+#define glElementPointerATI              (_GET_TLS_PROCTABLE()->ElementPointerATI)
+#define glDrawElementArrayATI            (_GET_TLS_PROCTABLE()->DrawElementArrayATI)
+#define glDrawRangeElementArrayATI       (_GET_TLS_PROCTABLE()->DrawRangeElementArrayATI)
+#define glDrawMeshArraysSUN              (_GET_TLS_PROCTABLE()->DrawMeshArraysSUN)
+#define glGenOcclusionQueriesNV          (_GET_TLS_PROCTABLE()->GenOcclusionQueriesNV)
+#define glDeleteOcclusionQueriesNV       (_GET_TLS_PROCTABLE()->DeleteOcclusionQueriesNV)
+#define glIsOcclusionQueryNV             (_GET_TLS_PROCTABLE()->IsOcclusionQueryNV)
+#define glBeginOcclusionQueryNV          (_GET_TLS_PROCTABLE()->BeginOcclusionQueryNV)
+#define glEndOcclusionQueryNV            (_GET_TLS_PROCTABLE()->EndOcclusionQueryNV)
+#define glGetOcclusionQueryivNV          (_GET_TLS_PROCTABLE()->GetOcclusionQueryivNV)
+#define glGetOcclusionQueryuivNV         (_GET_TLS_PROCTABLE()->GetOcclusionQueryuivNV)
+#define glPointParameteriNV              (_GET_TLS_PROCTABLE()->PointParameteriNV)
+#define glPointParameterivNV             (_GET_TLS_PROCTABLE()->PointParameterivNV)
+#define glActiveStencilFaceEXT           (_GET_TLS_PROCTABLE()->ActiveStencilFaceEXT)
+#define glElementPointerAPPLE            (_GET_TLS_PROCTABLE()->ElementPointerAPPLE)
+#define glDrawElementArrayAPPLE          (_GET_TLS_PROCTABLE()->DrawElementArrayAPPLE)
+#define glDrawRangeElementArrayAPPLE     (_GET_TLS_PROCTABLE()->DrawRangeElementArrayAPPLE)
+#define glMultiDrawElementArrayAPPLE     (_GET_TLS_PROCTABLE()->MultiDrawElementArrayAPPLE)
+#define glMultiDrawRangeElementArrayAPPLE (_GET_TLS_PROCTABLE()->MultiDrawRangeElementArrayAPPLE)
+#define glGenFencesAPPLE                 (_GET_TLS_PROCTABLE()->GenFencesAPPLE)
+#define glDeleteFencesAPPLE              (_GET_TLS_PROCTABLE()->DeleteFencesAPPLE)
+#define glSetFenceAPPLE                  (_GET_TLS_PROCTABLE()->SetFenceAPPLE)
+#define glIsFenceAPPLE                   (_GET_TLS_PROCTABLE()->IsFenceAPPLE)
+#define glTestFenceAPPLE                 (_GET_TLS_PROCTABLE()->TestFenceAPPLE)
+#define glFinishFenceAPPLE               (_GET_TLS_PROCTABLE()->FinishFenceAPPLE)
+#define glTestObjectAPPLE                (_GET_TLS_PROCTABLE()->TestObjectAPPLE)
+#define glFinishObjectAPPLE              (_GET_TLS_PROCTABLE()->FinishObjectAPPLE)
+#define glBindVertexArrayAPPLE           (_GET_TLS_PROCTABLE()->BindVertexArrayAPPLE)
+#define glDeleteVertexArraysAPPLE        (_GET_TLS_PROCTABLE()->DeleteVertexArraysAPPLE)
+#define glGenVertexArraysAPPLE           (_GET_TLS_PROCTABLE()->GenVertexArraysAPPLE)
+#define glIsVertexArrayAPPLE             (_GET_TLS_PROCTABLE()->IsVertexArrayAPPLE)
+#define glVertexArrayRangeAPPLE          (_GET_TLS_PROCTABLE()->VertexArrayRangeAPPLE)
+#define glFlushVertexArrayRangeAPPLE     (_GET_TLS_PROCTABLE()->FlushVertexArrayRangeAPPLE)
+#define glVertexArrayParameteriAPPLE     (_GET_TLS_PROCTABLE()->VertexArrayParameteriAPPLE)
+#define glDrawBuffersATI                 (_GET_TLS_PROCTABLE()->DrawBuffersATI)
+#define glProgramNamedParameter4fNV      (_GET_TLS_PROCTABLE()->ProgramNamedParameter4fNV)
+#define glProgramNamedParameter4dNV      (_GET_TLS_PROCTABLE()->ProgramNamedParameter4dNV)
+#define glProgramNamedParameter4fvNV     (_GET_TLS_PROCTABLE()->ProgramNamedParameter4fvNV)
+#define glProgramNamedParameter4dvNV     (_GET_TLS_PROCTABLE()->ProgramNamedParameter4dvNV)
+#define glGetProgramNamedParameterfvNV   (_GET_TLS_PROCTABLE()->GetProgramNamedParameterfvNV)
+#define glGetProgramNamedParameterdvNV   (_GET_TLS_PROCTABLE()->GetProgramNamedParameterdvNV)
+#define glVertex2hNV                     (_GET_TLS_PROCTABLE()->Vertex2hNV)
+#define glVertex2hvNV                    (_GET_TLS_PROCTABLE()->Vertex2hvNV)
+#define glVertex3hNV                     (_GET_TLS_PROCTABLE()->Vertex3hNV)
+#define glVertex3hvNV                    (_GET_TLS_PROCTABLE()->Vertex3hvNV)
+#define glVertex4hNV                     (_GET_TLS_PROCTABLE()->Vertex4hNV)
+#define glVertex4hvNV                    (_GET_TLS_PROCTABLE()->Vertex4hvNV)
+#define glNormal3hNV                     (_GET_TLS_PROCTABLE()->Normal3hNV)
+#define glNormal3hvNV                    (_GET_TLS_PROCTABLE()->Normal3hvNV)
+#define glColor3hNV                      (_GET_TLS_PROCTABLE()->Color3hNV)
+#define glColor3hvNV                     (_GET_TLS_PROCTABLE()->Color3hvNV)
+#define glColor4hNV                      (_GET_TLS_PROCTABLE()->Color4hNV)
+#define glColor4hvNV                     (_GET_TLS_PROCTABLE()->Color4hvNV)
+#define glTexCoord1hNV                   (_GET_TLS_PROCTABLE()->TexCoord1hNV)
+#define glTexCoord1hvNV                  (_GET_TLS_PROCTABLE()->TexCoord1hvNV)
+#define glTexCoord2hNV                   (_GET_TLS_PROCTABLE()->TexCoord2hNV)
+#define glTexCoord2hvNV                  (_GET_TLS_PROCTABLE()->TexCoord2hvNV)
+#define glTexCoord3hNV                   (_GET_TLS_PROCTABLE()->TexCoord3hNV)
+#define glTexCoord3hvNV                  (_GET_TLS_PROCTABLE()->TexCoord3hvNV)
+#define glTexCoord4hNV                   (_GET_TLS_PROCTABLE()->TexCoord4hNV)
+#define glTexCoord4hvNV                  (_GET_TLS_PROCTABLE()->TexCoord4hvNV)
+#define glMultiTexCoord1hNV              (_GET_TLS_PROCTABLE()->MultiTexCoord1hNV)
+#define glMultiTexCoord1hvNV             (_GET_TLS_PROCTABLE()->MultiTexCoord1hvNV)
+#define glMultiTexCoord2hNV              (_GET_TLS_PROCTABLE()->MultiTexCoord2hNV)
+#define glMultiTexCoord2hvNV             (_GET_TLS_PROCTABLE()->MultiTexCoord2hvNV)
+#define glMultiTexCoord3hNV              (_GET_TLS_PROCTABLE()->MultiTexCoord3hNV)
+#define glMultiTexCoord3hvNV             (_GET_TLS_PROCTABLE()->MultiTexCoord3hvNV)
+#define glMultiTexCoord4hNV              (_GET_TLS_PROCTABLE()->MultiTexCoord4hNV)
+#define glMultiTexCoord4hvNV             (_GET_TLS_PROCTABLE()->MultiTexCoord4hvNV)
+#define glFogCoordhNV                    (_GET_TLS_PROCTABLE()->FogCoordhNV)
+#define glFogCoordhvNV                   (_GET_TLS_PROCTABLE()->FogCoordhvNV)
+#define glSecondaryColor3hNV             (_GET_TLS_PROCTABLE()->SecondaryColor3hNV)
+#define glSecondaryColor3hvNV            (_GET_TLS_PROCTABLE()->SecondaryColor3hvNV)
+#define glVertexWeighthNV                (_GET_TLS_PROCTABLE()->VertexWeighthNV)
+#define glVertexWeighthvNV               (_GET_TLS_PROCTABLE()->VertexWeighthvNV)
+#define glVertexAttrib1hNV               (_GET_TLS_PROCTABLE()->VertexAttrib1hNV)
+#define glVertexAttrib1hvNV              (_GET_TLS_PROCTABLE()->VertexAttrib1hvNV)
+#define glVertexAttrib2hNV               (_GET_TLS_PROCTABLE()->VertexAttrib2hNV)
+#define glVertexAttrib2hvNV              (_GET_TLS_PROCTABLE()->VertexAttrib2hvNV)
+#define glVertexAttrib3hNV               (_GET_TLS_PROCTABLE()->VertexAttrib3hNV)
+#define glVertexAttrib3hvNV              (_GET_TLS_PROCTABLE()->VertexAttrib3hvNV)
+#define glVertexAttrib4hNV               (_GET_TLS_PROCTABLE()->VertexAttrib4hNV)
+#define glVertexAttrib4hvNV              (_GET_TLS_PROCTABLE()->VertexAttrib4hvNV)
+#define glVertexAttribs1hvNV             (_GET_TLS_PROCTABLE()->VertexAttribs1hvNV)
+#define glVertexAttribs2hvNV             (_GET_TLS_PROCTABLE()->VertexAttribs2hvNV)
+#define glVertexAttribs3hvNV             (_GET_TLS_PROCTABLE()->VertexAttribs3hvNV)
+#define glVertexAttribs4hvNV             (_GET_TLS_PROCTABLE()->VertexAttribs4hvNV)
+#define glPixelDataRangeNV               (_GET_TLS_PROCTABLE()->PixelDataRangeNV)
+#define glFlushPixelDataRangeNV          (_GET_TLS_PROCTABLE()->FlushPixelDataRangeNV)
+#define glPrimitiveRestartNV             (_GET_TLS_PROCTABLE()->PrimitiveRestartNV)
+#define glPrimitiveRestartIndexNV        (_GET_TLS_PROCTABLE()->PrimitiveRestartIndexNV)
+#define glMapObjectBufferATI             (_GET_TLS_PROCTABLE()->MapObjectBufferATI)
+#define glUnmapObjectBufferATI           (_GET_TLS_PROCTABLE()->UnmapObjectBufferATI)
+#define glStencilOpSeparateATI           (_GET_TLS_PROCTABLE()->StencilOpSeparateATI)
+#define glStencilFuncSeparateATI         (_GET_TLS_PROCTABLE()->StencilFuncSeparateATI)
+#define glVertexAttribArrayObjectATI     (_GET_TLS_PROCTABLE()->VertexAttribArrayObjectATI)
+#define glGetVertexAttribArrayObjectfvATI (_GET_TLS_PROCTABLE()->GetVertexAttribArrayObjectfvATI)
+#define glGetVertexAttribArrayObjectivATI (_GET_TLS_PROCTABLE()->GetVertexAttribArrayObjectivATI)
+#define glDepthBoundsEXT                 (_GET_TLS_PROCTABLE()->DepthBoundsEXT)
+#define glBlendEquationSeparateEXT       (_GET_TLS_PROCTABLE()->BlendEquationSeparateEXT)
+#define glAddSwapHintRectWIN             (_GET_TLS_PROCTABLE()->AddSwapHintRectWIN)
+#ifdef _WIN32
+#define wglCreateBufferRegionARB          (_GET_TLS_PROCTABLE()->CreateBufferRegionARB)
+#define wglDeleteBufferRegionARB          (_GET_TLS_PROCTABLE()->DeleteBufferRegionARB)
+#define wglSaveBufferRegionARB            (_GET_TLS_PROCTABLE()->SaveBufferRegionARB)
+#define wglRestoreBufferRegionARB         (_GET_TLS_PROCTABLE()->RestoreBufferRegionARB)
+#define wglGetExtensionsStringARB         (_GET_TLS_PROCTABLE()->GetExtensionsStringARB)
+#define wglGetPixelFormatAttribivARB      (_GET_TLS_PROCTABLE()->GetPixelFormatAttribivARB)
+#define wglGetPixelFormatAttribfvARB      (_GET_TLS_PROCTABLE()->GetPixelFormatAttribfvARB)
+#define wglChoosePixelFormatARB           (_GET_TLS_PROCTABLE()->ChoosePixelFormatARB)
+#define wglMakeContextCurrentARB          (_GET_TLS_PROCTABLE()->MakeContextCurrentARB)
+#define wglGetCurrentReadDCARB            (_GET_TLS_PROCTABLE()->GetCurrentReadDCARB)
+#define wglCreatePbufferARB               (_GET_TLS_PROCTABLE()->CreatePbufferARB)
+#define wglGetPbufferDCARB                (_GET_TLS_PROCTABLE()->GetPbufferDCARB)
+#define wglReleasePbufferDCARB            (_GET_TLS_PROCTABLE()->ReleasePbufferDCARB)
+#define wglDestroyPbufferARB              (_GET_TLS_PROCTABLE()->DestroyPbufferARB)
+#define wglQueryPbufferARB                (_GET_TLS_PROCTABLE()->QueryPbufferARB)
+#define wglBindTexImageARB                (_GET_TLS_PROCTABLE()->BindTexImageARB)
+#define wglReleaseTexImageARB             (_GET_TLS_PROCTABLE()->ReleaseTexImageARB)
+#define wglSetPbufferAttribARB            (_GET_TLS_PROCTABLE()->SetPbufferAttribARB)
+#define wglCreateDisplayColorTableEXT     (_GET_TLS_PROCTABLE()->CreateDisplayColorTableEXT)
+#define wglLoadDisplayColorTableEXT       (_GET_TLS_PROCTABLE()->LoadDisplayColorTableEXT)
+#define wglBindDisplayColorTableEXT       (_GET_TLS_PROCTABLE()->BindDisplayColorTableEXT)
+#define wglDestroyDisplayColorTableEXT    (_GET_TLS_PROCTABLE()->DestroyDisplayColorTableEXT)
+#define wglGetExtensionsStringEXT         (_GET_TLS_PROCTABLE()->GetExtensionsStringEXT)
+#define wglMakeContextCurrentEXT          (_GET_TLS_PROCTABLE()->MakeContextCurrentEXT)
+#define wglGetCurrentReadDCEXT            (_GET_TLS_PROCTABLE()->GetCurrentReadDCEXT)
+#define wglCreatePbufferEXT               (_GET_TLS_PROCTABLE()->CreatePbufferEXT)
+#define wglGetPbufferDCEXT                (_GET_TLS_PROCTABLE()->GetPbufferDCEXT)
+#define wglReleasePbufferDCEXT            (_GET_TLS_PROCTABLE()->ReleasePbufferDCEXT)
+#define wglDestroyPbufferEXT              (_GET_TLS_PROCTABLE()->DestroyPbufferEXT)
+#define wglQueryPbufferEXT                (_GET_TLS_PROCTABLE()->QueryPbufferEXT)
+#define wglGetPixelFormatAttribivEXT      (_GET_TLS_PROCTABLE()->GetPixelFormatAttribivEXT)
+#define wglGetPixelFormatAttribfvEXT      (_GET_TLS_PROCTABLE()->GetPixelFormatAttribfvEXT)
+#define wglChoosePixelFormatEXT           (_GET_TLS_PROCTABLE()->ChoosePixelFormatEXT)
+#define wglSwapIntervalEXT                (_GET_TLS_PROCTABLE()->SwapIntervalEXT)
+#define wglGetSwapIntervalEXT             (_GET_TLS_PROCTABLE()->GetSwapIntervalEXT)
+#define wglAllocateMemoryNV               (_GET_TLS_PROCTABLE()->AllocateMemoryNV)
+#define wglFreeMemoryNV                   (_GET_TLS_PROCTABLE()->FreeMemoryNV)
+#define wglGetSyncValuesOML               (_GET_TLS_PROCTABLE()->GetSyncValuesOML)
+#define wglGetMscRateOML                  (_GET_TLS_PROCTABLE()->GetMscRateOML)
+#define wglSwapBuffersMscOML              (_GET_TLS_PROCTABLE()->SwapBuffersMscOML)
+#define wglSwapLayerBuffersMscOML         (_GET_TLS_PROCTABLE()->SwapLayerBuffersMscOML)
+#define wglWaitForMscOML                  (_GET_TLS_PROCTABLE()->WaitForMscOML)
+#define wglWaitForSbcOML                  (_GET_TLS_PROCTABLE()->WaitForSbcOML)
+#define wglGetDigitalVideoParametersI3D   (_GET_TLS_PROCTABLE()->GetDigitalVideoParametersI3D)
+#define wglSetDigitalVideoParametersI3D   (_GET_TLS_PROCTABLE()->SetDigitalVideoParametersI3D)
+#define wglGetGammaTableParametersI3D     (_GET_TLS_PROCTABLE()->GetGammaTableParametersI3D)
+#define wglSetGammaTableParametersI3D     (_GET_TLS_PROCTABLE()->SetGammaTableParametersI3D)
+#define wglGetGammaTableI3D               (_GET_TLS_PROCTABLE()->GetGammaTableI3D)
+#define wglSetGammaTableI3D               (_GET_TLS_PROCTABLE()->SetGammaTableI3D)
+#define wglEnableGenlockI3D               (_GET_TLS_PROCTABLE()->EnableGenlockI3D)
+#define wglDisableGenlockI3D              (_GET_TLS_PROCTABLE()->DisableGenlockI3D)
+#define wglIsEnabledGenlockI3D            (_GET_TLS_PROCTABLE()->IsEnabledGenlockI3D)
+#define wglGenlockSourceI3D               (_GET_TLS_PROCTABLE()->GenlockSourceI3D)
+#define wglGetGenlockSourceI3D            (_GET_TLS_PROCTABLE()->GetGenlockSourceI3D)
+#define wglGenlockSourceEdgeI3D           (_GET_TLS_PROCTABLE()->GenlockSourceEdgeI3D)
+#define wglGetGenlockSourceEdgeI3D        (_GET_TLS_PROCTABLE()->GetGenlockSourceEdgeI3D)
+#define wglGenlockSampleRateI3D           (_GET_TLS_PROCTABLE()->GenlockSampleRateI3D)
+#define wglGetGenlockSampleRateI3D        (_GET_TLS_PROCTABLE()->GetGenlockSampleRateI3D)
+#define wglGenlockSourceDelayI3D          (_GET_TLS_PROCTABLE()->GenlockSourceDelayI3D)
+#define wglGetGenlockSourceDelayI3D       (_GET_TLS_PROCTABLE()->GetGenlockSourceDelayI3D)
+#define wglQueryGenlockMaxSourceDelayI3D  (_GET_TLS_PROCTABLE()->QueryGenlockMaxSourceDelayI3D)
+#define wglCreateImageBufferI3D           (_GET_TLS_PROCTABLE()->CreateImageBufferI3D)
+#define wglDestroyImageBufferI3D          (_GET_TLS_PROCTABLE()->DestroyImageBufferI3D)
+#define wglAssociateImageBufferEventsI3D  (_GET_TLS_PROCTABLE()->AssociateImageBufferEventsI3D)
+#define wglReleaseImageBufferEventsI3D    (_GET_TLS_PROCTABLE()->ReleaseImageBufferEventsI3D)
+#define wglEnableFrameLockI3D             (_GET_TLS_PROCTABLE()->EnableFrameLockI3D)
+#define wglDisableFrameLockI3D            (_GET_TLS_PROCTABLE()->DisableFrameLockI3D)
+#define wglIsEnabledFrameLockI3D          (_GET_TLS_PROCTABLE()->IsEnabledFrameLockI3D)
+#define wglQueryFrameLockMasterI3D        (_GET_TLS_PROCTABLE()->QueryFrameLockMasterI3D)
+#define wglGetFrameUsageI3D               (_GET_TLS_PROCTABLE()->GetFrameUsageI3D)
+#define wglBeginFrameTrackingI3D          (_GET_TLS_PROCTABLE()->BeginFrameTrackingI3D)
+#define wglEndFrameTrackingI3D            (_GET_TLS_PROCTABLE()->EndFrameTrackingI3D)
+#define wglQueryFrameTrackingI3D          (_GET_TLS_PROCTABLE()->QueryFrameTrackingI3D)
+#endif /* _WIN32 */
+
+#ifndef _APP_PROCTABLE
+
+/*
+ * Applications can replace the following function with its own function
+ * for accessing thread local proc/context dependent proc table.
+ * The following default function works for most applications which
+ * are using the same device for all their contexts - even if 
+ * the contexts are on different threads.
+ */
+
+static _inline _GLextensionProcs *_GET_TLS_PROCTABLE(void)
+
+{
+	extern _GLextensionProcs _extensionProcs;
+
+	return (&_extensionProcs);
+}
+
+#else
+
+/*
+ * Application should replace this compiled function with 
+ * an inlined function for maximum performance. 
+ */
+
+extern _GLextensionProcs *_GET_TLS_PROCTABLE(void);
+
+#endif
+
+/*
+ * Provide an initialization function for the application 
+ * to initialize its own proc tables in case the application 
+ * needs to use multiple proc tables. 
+ */
+
+static _inline void _InitExtensionProcs(_GLextensionProcs *appProcs)
+{
+	extern _GLextensionProcs _extensionProcs;
+
+	*appProcs = _extensionProcs;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* _GLPROCS_H_ */
diff --git a/src/ext/GLsdk/GL/wglext.h b/src/ext/GLsdk/GL/wglext.h
new file mode 100644
index 0000000..22ad105
--- /dev/null
+++ b/src/ext/GLsdk/GL/wglext.h
@@ -0,0 +1,611 @@
+#ifndef __wglext_h_
+#define __wglext_h_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2002 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#ifndef APIENTRY
+#define APIENTRY
+#endif
+#ifndef APIENTRYP
+#define APIENTRYP APIENTRY *
+#endif
+#ifndef GLAPI
+#define GLAPI extern
+#endif
+
+/*************************************************************/
+
+/* Header file version number */
+/* wglext.h last updated 2002/03/22 */
+/* Current version at http://oss.sgi.com/projects/ogl-sample/registry/ */
+#define WGL_WGLEXT_VERSION 4
+
+#ifndef WGL_ARB_buffer_region
+#define WGL_FRONT_COLOR_BUFFER_BIT_ARB 0x00000001
+#define WGL_BACK_COLOR_BUFFER_BIT_ARB  0x00000002
+#define WGL_DEPTH_BUFFER_BIT_ARB       0x00000004
+#define WGL_STENCIL_BUFFER_BIT_ARB     0x00000008
+#endif
+
+#ifndef WGL_ARB_multisample
+#define WGL_SAMPLE_BUFFERS_ARB         0x2041
+#define WGL_SAMPLES_ARB                0x2042
+#endif
+
+#ifndef WGL_ARB_extensions_string
+#endif
+
+#ifndef WGL_ARB_pixel_format
+#define WGL_NUMBER_PIXEL_FORMATS_ARB   0x2000
+#define WGL_DRAW_TO_WINDOW_ARB         0x2001
+#define WGL_DRAW_TO_BITMAP_ARB         0x2002
+#define WGL_ACCELERATION_ARB           0x2003
+#define WGL_NEED_PALETTE_ARB           0x2004
+#define WGL_NEED_SYSTEM_PALETTE_ARB    0x2005
+#define WGL_SWAP_LAYER_BUFFERS_ARB     0x2006
+#define WGL_SWAP_METHOD_ARB            0x2007
+#define WGL_NUMBER_OVERLAYS_ARB        0x2008
+#define WGL_NUMBER_UNDERLAYS_ARB       0x2009
+#define WGL_TRANSPARENT_ARB            0x200A
+#define WGL_TRANSPARENT_RED_VALUE_ARB  0x2037
+#define WGL_TRANSPARENT_GREEN_VALUE_ARB 0x2038
+#define WGL_TRANSPARENT_BLUE_VALUE_ARB 0x2039
+#define WGL_TRANSPARENT_ALPHA_VALUE_ARB 0x203A
+#define WGL_TRANSPARENT_INDEX_VALUE_ARB 0x203B
+#define WGL_SHARE_DEPTH_ARB            0x200C
+#define WGL_SHARE_STENCIL_ARB          0x200D
+#define WGL_SHARE_ACCUM_ARB            0x200E
+#define WGL_SUPPORT_GDI_ARB            0x200F
+#define WGL_SUPPORT_OPENGL_ARB         0x2010
+#define WGL_DOUBLE_BUFFER_ARB          0x2011
+#define WGL_STEREO_ARB                 0x2012
+#define WGL_PIXEL_TYPE_ARB             0x2013
+#define WGL_COLOR_BITS_ARB             0x2014
+#define WGL_RED_BITS_ARB               0x2015
+#define WGL_RED_SHIFT_ARB              0x2016
+#define WGL_GREEN_BITS_ARB             0x2017
+#define WGL_GREEN_SHIFT_ARB            0x2018
+#define WGL_BLUE_BITS_ARB              0x2019
+#define WGL_BLUE_SHIFT_ARB             0x201A
+#define WGL_ALPHA_BITS_ARB             0x201B
+#define WGL_ALPHA_SHIFT_ARB            0x201C
+#define WGL_ACCUM_BITS_ARB             0x201D
+#define WGL_ACCUM_RED_BITS_ARB         0x201E
+#define WGL_ACCUM_GREEN_BITS_ARB       0x201F
+#define WGL_ACCUM_BLUE_BITS_ARB        0x2020
+#define WGL_ACCUM_ALPHA_BITS_ARB       0x2021
+#define WGL_DEPTH_BITS_ARB             0x2022
+#define WGL_STENCIL_BITS_ARB           0x2023
+#define WGL_AUX_BUFFERS_ARB            0x2024
+#define WGL_NO_ACCELERATION_ARB        0x2025
+#define WGL_GENERIC_ACCELERATION_ARB   0x2026
+#define WGL_FULL_ACCELERATION_ARB      0x2027
+#define WGL_SWAP_EXCHANGE_ARB          0x2028
+#define WGL_SWAP_COPY_ARB              0x2029
+#define WGL_SWAP_UNDEFINED_ARB         0x202A
+#define WGL_TYPE_RGBA_ARB              0x202B
+#define WGL_TYPE_COLORINDEX_ARB        0x202C
+#endif
+
+#ifndef WGL_ARB_make_current_read
+#define ERROR_INVALID_PIXEL_TYPE_ARB   0x2043
+#define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
+#endif
+
+#ifndef WGL_ARB_pbuffer
+#define WGL_DRAW_TO_PBUFFER_ARB        0x202D
+#define WGL_MAX_PBUFFER_PIXELS_ARB     0x202E
+#define WGL_MAX_PBUFFER_WIDTH_ARB      0x202F
+#define WGL_MAX_PBUFFER_HEIGHT_ARB     0x2030
+#define WGL_PBUFFER_LARGEST_ARB        0x2033
+#define WGL_PBUFFER_WIDTH_ARB          0x2034
+#define WGL_PBUFFER_HEIGHT_ARB         0x2035
+#define WGL_PBUFFER_LOST_ARB           0x2036
+#endif
+
+#ifndef WGL_ARB_render_texture
+#define WGL_BIND_TO_TEXTURE_RGB_ARB    0x2070
+#define WGL_BIND_TO_TEXTURE_RGBA_ARB   0x2071
+#define WGL_TEXTURE_FORMAT_ARB         0x2072
+#define WGL_TEXTURE_TARGET_ARB         0x2073
+#define WGL_MIPMAP_TEXTURE_ARB         0x2074
+#define WGL_TEXTURE_RGB_ARB            0x2075
+#define WGL_TEXTURE_RGBA_ARB           0x2076
+#define WGL_NO_TEXTURE_ARB             0x2077
+#define WGL_TEXTURE_CUBE_MAP_ARB       0x2078
+#define WGL_TEXTURE_1D_ARB             0x2079
+#define WGL_TEXTURE_2D_ARB             0x207A
+#define WGL_MIPMAP_LEVEL_ARB           0x207B
+#define WGL_CUBE_MAP_FACE_ARB          0x207C
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB 0x207D
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB 0x207E
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB 0x207F
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB 0x2080
+#define WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB 0x2081
+#define WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB 0x2082
+#define WGL_FRONT_LEFT_ARB             0x2083
+#define WGL_FRONT_RIGHT_ARB            0x2084
+#define WGL_BACK_LEFT_ARB              0x2085
+#define WGL_BACK_RIGHT_ARB             0x2086
+#define WGL_AUX0_ARB                   0x2087
+#define WGL_AUX1_ARB                   0x2088
+#define WGL_AUX2_ARB                   0x2089
+#define WGL_AUX3_ARB                   0x208A
+#define WGL_AUX4_ARB                   0x208B
+#define WGL_AUX5_ARB                   0x208C
+#define WGL_AUX6_ARB                   0x208D
+#define WGL_AUX7_ARB                   0x208E
+#define WGL_AUX8_ARB                   0x208F
+#define WGL_AUX9_ARB                   0x2090
+#endif
+
+#ifndef WGL_EXT_make_current_read
+#define ERROR_INVALID_PIXEL_TYPE_EXT   0x2043
+#endif
+
+#ifndef WGL_EXT_pixel_format
+#define WGL_NUMBER_PIXEL_FORMATS_EXT   0x2000
+#define WGL_DRAW_TO_WINDOW_EXT         0x2001
+#define WGL_DRAW_TO_BITMAP_EXT         0x2002
+#define WGL_ACCELERATION_EXT           0x2003
+#define WGL_NEED_PALETTE_EXT           0x2004
+#define WGL_NEED_SYSTEM_PALETTE_EXT    0x2005
+#define WGL_SWAP_LAYER_BUFFERS_EXT     0x2006
+#define WGL_SWAP_METHOD_EXT            0x2007
+#define WGL_NUMBER_OVERLAYS_EXT        0x2008
+#define WGL_NUMBER_UNDERLAYS_EXT       0x2009
+#define WGL_TRANSPARENT_EXT            0x200A
+#define WGL_TRANSPARENT_VALUE_EXT      0x200B
+#define WGL_SHARE_DEPTH_EXT            0x200C
+#define WGL_SHARE_STENCIL_EXT          0x200D
+#define WGL_SHARE_ACCUM_EXT            0x200E
+#define WGL_SUPPORT_GDI_EXT            0x200F
+#define WGL_SUPPORT_OPENGL_EXT         0x2010
+#define WGL_DOUBLE_BUFFER_EXT          0x2011
+#define WGL_STEREO_EXT                 0x2012
+#define WGL_PIXEL_TYPE_EXT             0x2013
+#define WGL_COLOR_BITS_EXT             0x2014
+#define WGL_RED_BITS_EXT               0x2015
+#define WGL_RED_SHIFT_EXT              0x2016
+#define WGL_GREEN_BITS_EXT             0x2017
+#define WGL_GREEN_SHIFT_EXT            0x2018
+#define WGL_BLUE_BITS_EXT              0x2019
+#define WGL_BLUE_SHIFT_EXT             0x201A
+#define WGL_ALPHA_BITS_EXT             0x201B
+#define WGL_ALPHA_SHIFT_EXT            0x201C
+#define WGL_ACCUM_BITS_EXT             0x201D
+#define WGL_ACCUM_RED_BITS_EXT         0x201E
+#define WGL_ACCUM_GREEN_BITS_EXT       0x201F
+#define WGL_ACCUM_BLUE_BITS_EXT        0x2020
+#define WGL_ACCUM_ALPHA_BITS_EXT       0x2021
+#define WGL_DEPTH_BITS_EXT             0x2022
+#define WGL_STENCIL_BITS_EXT           0x2023
+#define WGL_AUX_BUFFERS_EXT            0x2024
+#define WGL_NO_ACCELERATION_EXT        0x2025
+#define WGL_GENERIC_ACCELERATION_EXT   0x2026
+#define WGL_FULL_ACCELERATION_EXT      0x2027
+#define WGL_SWAP_EXCHANGE_EXT          0x2028
+#define WGL_SWAP_COPY_EXT              0x2029
+#define WGL_SWAP_UNDEFINED_EXT         0x202A
+#define WGL_TYPE_RGBA_EXT              0x202B
+#define WGL_TYPE_COLORINDEX_EXT        0x202C
+#endif
+
+#ifndef WGL_EXT_pbuffer
+#define WGL_DRAW_TO_PBUFFER_EXT        0x202D
+#define WGL_MAX_PBUFFER_PIXELS_EXT     0x202E
+#define WGL_MAX_PBUFFER_WIDTH_EXT      0x202F
+#define WGL_MAX_PBUFFER_HEIGHT_EXT     0x2030
+#define WGL_OPTIMAL_PBUFFER_WIDTH_EXT  0x2031
+#define WGL_OPTIMAL_PBUFFER_HEIGHT_EXT 0x2032
+#define WGL_PBUFFER_LARGEST_EXT        0x2033
+#define WGL_PBUFFER_WIDTH_EXT          0x2034
+#define WGL_PBUFFER_HEIGHT_EXT         0x2035
+#endif
+
+#ifndef WGL_EXT_depth_float
+#define WGL_DEPTH_FLOAT_EXT            0x2040
+#endif
+
+#ifndef WGL_3DFX_multisample
+#define WGL_SAMPLE_BUFFERS_3DFX        0x2060
+#define WGL_SAMPLES_3DFX               0x2061
+#endif
+
+#ifndef WGL_EXT_multisample
+#define WGL_SAMPLE_BUFFERS_EXT         0x2041
+#define WGL_SAMPLES_EXT                0x2042
+#endif
+
+#ifndef WGL_I3D_digital_video_control
+#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D 0x2050
+#define WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D 0x2051
+#define WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D 0x2052
+#define WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D 0x2053
+#endif
+
+#ifndef WGL_I3D_gamma
+#define WGL_GAMMA_TABLE_SIZE_I3D       0x204E
+#define WGL_GAMMA_EXCLUDE_DESKTOP_I3D  0x204F
+#endif
+
+#ifndef WGL_I3D_genlock
+#define WGL_GENLOCK_SOURCE_MULTIVIEW_I3D 0x2044
+#define WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D 0x2045
+#define WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D 0x2046
+#define WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D 0x2047
+#define WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D 0x2048
+#define WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D 0x2049
+#define WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D 0x204A
+#define WGL_GENLOCK_SOURCE_EDGE_RISING_I3D 0x204B
+#define WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D 0x204C
+#endif
+
+#ifndef WGL_I3D_image_buffer
+#define WGL_IMAGE_BUFFER_MIN_ACCESS_I3D 0x00000001
+#define WGL_IMAGE_BUFFER_LOCK_I3D      0x00000002
+#endif
+
+#ifndef WGL_I3D_swap_frame_lock
+#endif
+
+#ifndef WGL_NV_render_depth_texture
+#define WGL_BIND_TO_TEXTURE_DEPTH_NV   0x20A3
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV 0x20A4
+#define WGL_DEPTH_TEXTURE_FORMAT_NV    0x20A5
+#define WGL_TEXTURE_DEPTH_COMPONENT_NV 0x20A6
+#define WGL_DEPTH_COMPONENT_NV         0x20A7
+#endif
+
+#ifndef WGL_NV_render_texture_rectangle
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV 0x20A0
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV 0x20A1
+#define WGL_TEXTURE_RECTANGLE_NV       0x20A2
+#endif
+
+#ifndef WGL_NV_float_buffer
+#define WGL_FLOAT_COMPONENTS_NV        0x20B0
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV 0x20B1
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV 0x20B2
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV 0x20B3
+#define WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV 0x20B4
+#define WGL_TEXTURE_FLOAT_R_NV         0x20B5
+#define WGL_TEXTURE_FLOAT_RG_NV        0x20B6
+#define WGL_TEXTURE_FLOAT_RGB_NV       0x20B7
+#define WGL_TEXTURE_FLOAT_RGBA_NV      0x20B8
+#endif
+
+
+/*************************************************************/
+
+#ifndef WGL_ARB_pbuffer
+DECLARE_HANDLE(HPBUFFERARB);
+#endif
+#ifndef WGL_EXT_pbuffer
+DECLARE_HANDLE(HPBUFFEREXT);
+#endif
+
+#ifndef WGL_ARB_buffer_region
+#define WGL_ARB_buffer_region 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HANDLE WINAPI wglCreateBufferRegionARB (HDC, int, UINT);
+extern VOID WINAPI wglDeleteBufferRegionARB (HANDLE);
+extern BOOL WINAPI wglSaveBufferRegionARB (HANDLE, int, int, int, int);
+extern BOOL WINAPI wglRestoreBufferRegionARB (HANDLE, int, int, int, int, int, int);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HANDLE (WINAPI * PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
+typedef VOID (WINAPI * PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
+typedef BOOL (WINAPI * PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
+typedef BOOL (WINAPI * PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
+#endif
+
+#ifndef WGL_ARB_multisample
+#define WGL_ARB_multisample 1
+#endif
+
+#ifndef WGL_ARB_extensions_string
+#define WGL_ARB_extensions_string 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern const char * WINAPI wglGetExtensionsStringARB (HDC);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
+#endif
+
+#ifndef WGL_ARB_pixel_format
+#define WGL_ARB_pixel_format 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetPixelFormatAttribivARB (HDC, int, int, UINT, const int *, int *);
+extern BOOL WINAPI wglGetPixelFormatAttribfvARB (HDC, int, int, UINT, const int *, FLOAT *);
+extern BOOL WINAPI wglChoosePixelFormatARB (HDC, const int *, const FLOAT *, UINT, int *, UINT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
+typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif
+
+#ifndef WGL_ARB_make_current_read
+#define WGL_ARB_make_current_read 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglMakeContextCurrentARB (HDC, HDC, HGLRC);
+extern HDC WINAPI wglGetCurrentReadDCARB (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCARBPROC) (void);
+#endif
+
+#ifndef WGL_ARB_pbuffer
+#define WGL_ARB_pbuffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HPBUFFERARB WINAPI wglCreatePbufferARB (HDC, int, int, int, const int *);
+extern HDC WINAPI wglGetPbufferDCARB (HPBUFFERARB);
+extern int WINAPI wglReleasePbufferDCARB (HPBUFFERARB, HDC);
+extern BOOL WINAPI wglDestroyPbufferARB (HPBUFFERARB);
+extern BOOL WINAPI wglQueryPbufferARB (HPBUFFERARB, int, int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HPBUFFERARB (WINAPI * PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+typedef HDC (WINAPI * PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
+typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
+typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
+typedef BOOL (WINAPI * PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_ARB_render_texture
+#define WGL_ARB_render_texture 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglBindTexImageARB (HPBUFFERARB, int);
+extern BOOL WINAPI wglReleaseTexImageARB (HPBUFFERARB, int);
+extern BOOL WINAPI wglSetPbufferAttribARB (HPBUFFERARB, const int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
+typedef BOOL (WINAPI * PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
+typedef BOOL (WINAPI * PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
+#endif
+
+#ifndef WGL_EXT_display_color_table
+#define WGL_EXT_display_color_table 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern GLboolean WINAPI wglCreateDisplayColorTableEXT (GLushort);
+extern GLboolean WINAPI wglLoadDisplayColorTableEXT (const GLushort *, GLuint);
+extern GLboolean WINAPI wglBindDisplayColorTableEXT (GLushort);
+extern VOID WINAPI wglDestroyDisplayColorTableEXT (GLushort);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef GLboolean (WINAPI * PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+typedef GLboolean (WINAPI * PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
+typedef GLboolean (WINAPI * PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+typedef VOID (WINAPI * PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
+#endif
+
+#ifndef WGL_EXT_extensions_string
+#define WGL_EXT_extensions_string 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern const char * WINAPI wglGetExtensionsStringEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef const char * (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_make_current_read
+#define WGL_EXT_make_current_read 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglMakeContextCurrentEXT (HDC, HDC, HGLRC);
+extern HDC WINAPI wglGetCurrentReadDCEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
+typedef HDC (WINAPI * PFNWGLGETCURRENTREADDCEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_pbuffer
+#define WGL_EXT_pbuffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern HPBUFFEREXT WINAPI wglCreatePbufferEXT (HDC, int, int, int, const int *);
+extern HDC WINAPI wglGetPbufferDCEXT (HPBUFFEREXT);
+extern int WINAPI wglReleasePbufferDCEXT (HPBUFFEREXT, HDC);
+extern BOOL WINAPI wglDestroyPbufferEXT (HPBUFFEREXT);
+extern BOOL WINAPI wglQueryPbufferEXT (HPBUFFEREXT, int, int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef HPBUFFEREXT (WINAPI * PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
+typedef HDC (WINAPI * PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
+typedef int (WINAPI * PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
+typedef BOOL (WINAPI * PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
+typedef BOOL (WINAPI * PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
+#endif
+
+#ifndef WGL_EXT_pixel_format
+#define WGL_EXT_pixel_format 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetPixelFormatAttribivEXT (HDC, int, int, UINT, int *, int *);
+extern BOOL WINAPI wglGetPixelFormatAttribfvEXT (HDC, int, int, UINT, int *, FLOAT *);
+extern BOOL WINAPI wglChoosePixelFormatEXT (HDC, const int *, const FLOAT *, UINT, int *, UINT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
+typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
+typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
+#endif
+
+#ifndef WGL_EXT_swap_control
+#define WGL_EXT_swap_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglSwapIntervalEXT (int);
+extern int WINAPI wglGetSwapIntervalEXT (void);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
+typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
+#endif
+
+#ifndef WGL_EXT_depth_float
+#define WGL_EXT_depth_float 1
+#endif
+
+#ifndef WGL_NV_vertex_array_range
+#define WGL_NV_vertex_array_range 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern void* WINAPI wglAllocateMemoryNV (GLsizei, GLfloat, GLfloat, GLfloat);
+extern void WINAPI wglFreeMemoryNV (void *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef void* (WINAPI * PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
+typedef void (WINAPI * PFNWGLFREEMEMORYNVPROC) (void *pointer);
+#endif
+
+#ifndef WGL_3DFX_multisample
+#define WGL_3DFX_multisample 1
+#endif
+
+#ifndef WGL_EXT_multisample
+#define WGL_EXT_multisample 1
+#endif
+
+#ifndef WGL_OML_sync_control
+#define WGL_OML_sync_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetSyncValuesOML (HDC, INT64 *, INT64 *, INT64 *);
+extern BOOL WINAPI wglGetMscRateOML (HDC, INT32 *, INT32 *);
+extern INT64 WINAPI wglSwapBuffersMscOML (HDC, INT64, INT64, INT64);
+extern INT64 WINAPI wglSwapLayerBuffersMscOML (HDC, int, INT64, INT64, INT64);
+extern BOOL WINAPI wglWaitForMscOML (HDC, INT64, INT64, INT64, INT64 *, INT64 *, INT64 *);
+extern BOOL WINAPI wglWaitForSbcOML (HDC, INT64, INT64 *, INT64 *, INT64 *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
+typedef BOOL (WINAPI * PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
+typedef INT64 (WINAPI * PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
+typedef INT64 (WINAPI * PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
+typedef BOOL (WINAPI * PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
+typedef BOOL (WINAPI * PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
+#endif
+
+#ifndef WGL_I3D_digital_video_control
+#define WGL_I3D_digital_video_control 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetDigitalVideoParametersI3D (HDC, int, int *);
+extern BOOL WINAPI wglSetDigitalVideoParametersI3D (HDC, int, const int *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
+typedef BOOL (WINAPI * PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
+#endif
+
+#ifndef WGL_I3D_gamma
+#define WGL_I3D_gamma 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetGammaTableParametersI3D (HDC, int, int *);
+extern BOOL WINAPI wglSetGammaTableParametersI3D (HDC, int, const int *);
+extern BOOL WINAPI wglGetGammaTableI3D (HDC, int, USHORT *, USHORT *, USHORT *);
+extern BOOL WINAPI wglSetGammaTableI3D (HDC, int, const USHORT *, const USHORT *, const USHORT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
+typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
+typedef BOOL (WINAPI * PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
+typedef BOOL (WINAPI * PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
+#endif
+
+#ifndef WGL_I3D_genlock
+#define WGL_I3D_genlock 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglEnableGenlockI3D (HDC);
+extern BOOL WINAPI wglDisableGenlockI3D (HDC);
+extern BOOL WINAPI wglIsEnabledGenlockI3D (HDC, BOOL *);
+extern BOOL WINAPI wglGenlockSourceI3D (HDC, UINT);
+extern BOOL WINAPI wglGetGenlockSourceI3D (HDC, UINT *);
+extern BOOL WINAPI wglGenlockSourceEdgeI3D (HDC, UINT);
+extern BOOL WINAPI wglGetGenlockSourceEdgeI3D (HDC, UINT *);
+extern BOOL WINAPI wglGenlockSampleRateI3D (HDC, UINT);
+extern BOOL WINAPI wglGetGenlockSampleRateI3D (HDC, UINT *);
+extern BOOL WINAPI wglGenlockSourceDelayI3D (HDC, UINT);
+extern BOOL WINAPI wglGetGenlockSourceDelayI3D (HDC, UINT *);
+extern BOOL WINAPI wglQueryGenlockMaxSourceDelayI3D (HDC, UINT *, UINT *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
+typedef BOOL (WINAPI * PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
+typedef BOOL (WINAPI * PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
+typedef BOOL (WINAPI * PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
+typedef BOOL (WINAPI * PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
+typedef BOOL (WINAPI * PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
+#endif
+
+#ifndef WGL_I3D_image_buffer
+#define WGL_I3D_image_buffer 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern LPVOID WINAPI wglCreateImageBufferI3D (HDC, DWORD, UINT);
+extern BOOL WINAPI wglDestroyImageBufferI3D (HDC, LPVOID);
+extern BOOL WINAPI wglAssociateImageBufferEventsI3D (HDC, const HANDLE *, const LPVOID *, const DWORD *, UINT);
+extern BOOL WINAPI wglReleaseImageBufferEventsI3D (HDC, const LPVOID *, UINT);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef LPVOID (WINAPI * PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
+typedef BOOL (WINAPI * PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
+typedef BOOL (WINAPI * PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
+typedef BOOL (WINAPI * PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
+#endif
+
+#ifndef WGL_I3D_swap_frame_lock
+#define WGL_I3D_swap_frame_lock 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglEnableFrameLockI3D (void);
+extern BOOL WINAPI wglDisableFrameLockI3D (void);
+extern BOOL WINAPI wglIsEnabledFrameLockI3D (BOOL *);
+extern BOOL WINAPI wglQueryFrameLockMasterI3D (BOOL *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLENABLEFRAMELOCKI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
+typedef BOOL (WINAPI * PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
+#endif
+
+#ifndef WGL_I3D_swap_frame_usage
+#define WGL_I3D_swap_frame_usage 1
+#ifdef WGL_WGLEXT_PROTOTYPES
+extern BOOL WINAPI wglGetFrameUsageI3D (float *);
+extern BOOL WINAPI wglBeginFrameTrackingI3D (void);
+extern BOOL WINAPI wglEndFrameTrackingI3D (void);
+extern BOOL WINAPI wglQueryFrameTrackingI3D (DWORD *, DWORD *, float *);
+#endif /* WGL_WGLEXT_PROTOTYPES */
+typedef BOOL (WINAPI * PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
+typedef BOOL (WINAPI * PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLENDFRAMETRACKINGI3DPROC) (void);
+typedef BOOL (WINAPI * PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/ext/GLsdk/README b/src/ext/GLsdk/README
new file mode 100644
index 0000000..0154e04
--- /dev/null
+++ b/src/ext/GLsdk/README
@@ -0,0 +1,110 @@
+The currently shipping OpenGL32.DLL from Microsoft only has entry points
+for OpenGL 1.1. If an application wants to use OpenGL {1.2, 1.3, 1.4, 1.5}
+functions, it has to use wglGetProcAddress() in order to obtain the entry
+points from the driver. The files in this distribution enable the application
+pretend that there is full support for OpenGL {1.2/1.3/1.4/1.5} if the
+underlying implementation supports OpenGL {1.2/1.3/1.4/1.5}.
+
+A useful feature of the framework is that it provides a safety layer by
+initializing each function to a "default" initialization function with
+matching arguments and return type. On debug builds, the initialization
+function adds an ASSERT to catch unwitting usage of NULL function pointers
+by the application.
+
+The framework is also readily usable for multi-context and multi-threaded
+applications, including application code that demonstrates how to
+achieve this.
+
+Additionally, this distribution provides full support for all the 
+extension entry points in glext.h and wglext.h.
+
+In order to use this scheme, the application needs to do the following:
+
+=====================================================================
+
+For applications that do not create rendering contexts on different devices 
+(e.g. multi-display with different vendors supporting the two displays):
+
+1. Include "glprocs.h"  in addition to including "gl.h"
+2. Compile "glprocs.c" and ensure that glprocs.obj is linked with the
+   application code.
+3. Call OpenGL{1.2,1.3,1.4,1.5} and extension procs after verifying that
+   the implementation has support for the underlying feature. Example:
+
+   if (supports12) {
+       glDrawRangeElements (.....)
+   }
+   
+   NOTE: The application can call "glGetString(GL_VERSION)" to determine
+   the version of OpenGL supported on a particular implementation.
+
+=====================================================================
+
+For aplications that create rendering contexts on different devices, the
+application has to perform the following additional steps:
+
+1. Allocate memory for _GLextensionProcs in the application data
+   structures for each device. Example:
+
+   typedef struct {
+        appType             appData;
+
+        _GLextensionProcs   extensionProcs;
+   } ContextData;
+
+   ContextData cdev1, cdev2;
+
+2. Initialize the extension procs.
+
+   _InitExtensionProcs (&cdev1.extensionProcs);
+   _InitExtensionProcs (&cdev2.extensionProcs);
+
+3. Provide a mechanism for accessing the current device. Example:
+
+   ContextData *currentContextData;
+
+   static _inline _GLextensionProcs *_GET_TLS_PROCTABLE(void)
+   {
+       return (&currentContxtData->extensionProcs);
+   }
+
+   Another Example (when the two different devices are being used
+   on two different contexts):
+
+   static _inline _GLextensionProcs *_GET_TLS_PROCTABLE(void)
+   {
+       ContextData *tla = GetThreadSpecificData();
+       return (&tla->extensionProcs);
+   }
+
+   (NOTE: Aplication has to replace this function in glprocs.h with 
+    its own customized function).
+        
+=====================================================================
+
+This distribution additionally contains the following:
+
+Windows Demo Source:
+--------------------
+windemo:
+    demogl.{c|h} - sample initialization, rendering functions and a sample
+    data structure for tracking per-window data (useful for apps. with 
+    multiple windows).
+    Makefile:Builds all the demos (singlewin, multiwin, and multithread)
+
+singlewin:
+    demo.c: Shows how to use the SDK for an application with a single window.
+    Makefile: Builds the singlewin sample (demo.exe).
+
+multiwin:
+    demo.c: Shows how to use the SDK for an application with two windows
+    Makefile: Builds the multiwin sample (demo.exe)
+
+multithread:
+    demo.c: Shows how to use the SDK for a multi-threaded application.
+    Makefile: Builds the multithread sample (demo.exe).
+
+GLX Demo Source:
+--------------------
+glxdemo:
+GLX demo similar to the singlewin Windows demo.
diff --git a/src/ext/GLsdk/glxdemo/Makefile b/src/ext/GLsdk/glxdemo/Makefile
new file mode 100644
index 0000000..33923bb
--- /dev/null
+++ b/src/ext/GLsdk/glxdemo/Makefile
@@ -0,0 +1,20 @@
+CC = gcc
+CFLAGS = -c -g -Wall -I/usr/include -I..
+LIBS = -L/usr/lib -lGL
+
+demo: demo.o glprocs.o
+	$(CC) demo.o glprocs.o $(LIBS) -o $@
+
+demo.o: demo.c ../GL/glprocs.h
+	$(CC) $(CFLAGS) demo.c
+
+glprocs.o: glprocs.c ../GL/glprocs.h
+	$(CC) $(CFLAGS) glprocs.c
+
+glprocs.c:
+	ln -s ../GL/glprocs.c .
+
+
+clean:
+	rm -f *.o demo glprocs.c
+
diff --git a/src/ext/GLsdk/glxdemo/demo.c b/src/ext/GLsdk/glxdemo/demo.c
new file mode 100644
index 0000000..16ce5b7
--- /dev/null
+++ b/src/ext/GLsdk/glxdemo/demo.c
@@ -0,0 +1,358 @@
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#include <assert.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <X11/Xlib.h>
+#include <X11/keysym.h>
+#include <GL/gl.h>
+#include <GL/glx.h>
+#include "GL/glprocs.h"
+
+
+/*
+ * Define a structure keeping all application data on a per window
+ * basis.
+ */
+
+typedef struct {        
+    /* Intialized data */
+
+    char  *windowTitle;
+
+    int   xpos;
+    int   ypos;
+    int   width;    /* Size of client region */
+    int   height;
+
+    int   pfdFlags; /* Flags for selecting pixel format descriptor */
+
+    /* Computed data */
+
+    int   hasMultitexture;  /* Supports multi-texture */
+    int   hasWinSwapHint;   /* Supports WinSwapHint */
+
+    int   spin;             /* Rotation angle of triangle per window */
+    int   texid;            /* Texture id per window */
+
+    Display *display;
+    GLXContext context;
+    Window window;
+
+    /* If we are using multiple renderers in a single process or on 
+     * multiple threads, we must keep our function table for 
+     * OpenGL 1.2, OpenGL 1.3 and extension functions 
+     */
+
+#ifdef _APP_PROCTABLE
+    _GLextensionProcs extensionProcs;
+#endif
+} WindowData;
+
+/*
+  Using strstr for extension search can result in false positives
+  because of substring matches. Since extension names in the
+  extension string are separated by spaces, this can be fixed simply
+  by looking for a space OR the end-of-string character immediately
+  following the extension we're looking for (by skipping ahead 'len'
+  characters).
+*/
+static GLboolean IsExtensionSupported(const GLubyte *extensionStr,
+                                      const GLubyte *checkExtension)
+{
+    const GLubyte  *s;
+	GLint len;
+
+	s = extensionStr;
+	len = strlen (checkExtension);
+
+	while ((s = strstr (s, checkExtension)) != NULL) {
+		s += len;
+
+		if ((*s == ' ') || (*s == '\0')) {
+			return (GL_TRUE);
+		}
+	}
+
+	return (GL_FALSE);
+}
+
+/*
+ * Initialize the OpenGL context - create textures, check the extensions
+ * supported by the driver etc.
+ */
+static void
+InitializeOpenGL(WindowData *pwdata)
+{
+    const GLubyte *extstrGL;
+
+    GLubyte image[] = {
+        0xFF, 0x00, 0xFF, 0x00,
+        0x00, 0xFF, 0x00, 0xFF,
+        0xFF, 0x00, 0xFF, 0x00,
+        0x00, 0xFF, 0x00, 0xFF,
+    };
+
+    /* Setup the extensions */
+
+    extstrGL = glGetString(GL_EXTENSIONS);
+
+    /* Check for multi-texture extension. */
+
+    if (GL_TRUE == IsExtensionSupported (extstrGL, "GL_ARB_multitexture")) {
+        pwdata->hasMultitexture = GL_TRUE;
+
+        /* Multi-texturing is supported. Create a texture for unit1 and
+         * bind it in MODULATE mode.
+         */
+
+        /* ==========================================================
+         * ==========================================================
+         * Use an extension function without doing anything special!
+         * OpenGL 1.2, OpenGL 1.3 procs can be used similarly - as
+         * long we ensure it is supported - just as we have done
+         * for multi-texturing here.
+         * ==========================================================
+         * ==========================================================
+         */
+
+        glActiveTextureARB (GL_TEXTURE1_ARB);       /* Use unit1 */
+
+        glGenTextures (1, &pwdata->texid);
+
+        glBindTexture (GL_TEXTURE_2D, pwdata->texid);   /* Bound on unit 1 */
+        glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, 4, 4, 0, 
+                            GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
+
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+
+        glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+
+        glEnable (GL_TEXTURE_2D);
+    }
+}
+
+
+
+static void
+DrawScene(WindowData *pwdata)
+{
+    /* Render a triangle - multi-textured if ARB_multitexture is supported. */
+
+    glClearColor (0.0, 0.0, 0.0, 0.0);          /* BLACK */
+    glClear (GL_COLOR_BUFFER_BIT);
+
+    glMatrixMode (GL_MODELVIEW);
+    glLoadIdentity();
+
+    glRotatef (pwdata->spin, 0.0, 0.0, 1.0);
+
+    pwdata->spin += 2;
+
+    if (pwdata->spin >= 360) {
+        pwdata->spin = 0;
+    }
+
+    if (pwdata->hasMultitexture) {
+        /*
+         * ==========================================================
+         * ==========================================================
+         * Use an extension function without doing anything special!
+         * OpenGL 1.2, OpenGL 1.3 procs can be used similarly - as
+         * long we ensure it is supported - just as we have done
+         * for MultiTexCoord here.
+         * ==========================================================
+         * ==========================================================
+         */ 
+
+        glBegin( GL_POLYGON );
+            glMultiTexCoord2fARB (GL_TEXTURE1_ARB, 0.0, 0.0);
+            glColor3f (1.0, 0.0, 0.0); 
+            glVertex3f(0.0, 0.0, 0.0);
+                                
+            glMultiTexCoord2fARB (GL_TEXTURE1_ARB, 1.0, 0.0);
+            glColor3f (0.0, 1.0, 0.0); 
+            glVertex3f(0.5, 0.0, 0.0);
+
+            glMultiTexCoord2fARB (GL_TEXTURE1_ARB, 1.0, 1.0);
+            glColor3f (0.0, 0.0, 1.0); 
+            glVertex3f(0.5, 0.5, 0.0);          
+        glEnd();
+    } else {
+        glBegin( GL_POLYGON );
+            glColor3f (1.0, 0.0, 0.0); 
+            glVertex3f(0.0, 0.0, 0.0);
+                                
+            glColor3f (0.0, 1.0, 0.0); 
+            glVertex3f(0.5, 0.0, 0.0);
+
+            glColor3f (0.0, 0.0, 1.0); 
+            glVertex3f(0.5, 0.5, 0.0);          
+        glEnd();
+    }
+
+    glXSwapBuffers(pwdata->display, pwdata->window);
+}
+
+
+/*
+ * Create an RGB OpenGL window.
+ * Return the window and context handles.
+ */
+static void
+MakeWindow( Display *dpy, const char *name,
+            int x, int y, int width, int height,
+            WindowData *winData )
+{
+   int attrib[] = { GLX_RGBA,
+		    GLX_RED_SIZE, 1,
+		    GLX_GREEN_SIZE, 1,
+		    GLX_BLUE_SIZE, 1,
+                    GLX_DOUBLEBUFFER,
+		    None };
+   int scrnum;
+   XSetWindowAttributes attr;
+   unsigned long mask;
+   Window root;
+   Window win;
+   GLXContext ctx;
+   XVisualInfo *visinfo;
+
+   scrnum = DefaultScreen( dpy );
+   root = RootWindow( dpy, scrnum );
+
+   visinfo = glXChooseVisual( dpy, scrnum, attrib );
+   if (!visinfo) {
+      printf("Error: couldn't get an RGB, Double-buffered visual\n");
+      exit(1);
+   }
+
+   /* window attributes */
+   attr.background_pixel = 0;
+   attr.border_pixel = 0;
+   attr.colormap = XCreateColormap( dpy, root, visinfo->visual, AllocNone);
+   attr.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask;
+   mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask;
+
+   win = XCreateWindow( dpy, root, 0, 0, width, height,
+		        0, visinfo->depth, InputOutput,
+		        visinfo->visual, mask, &attr );
+
+   /* set hints and properties */
+   {
+      XSizeHints sizehints;
+      sizehints.x = x;
+      sizehints.y = y;
+      sizehints.width  = width;
+      sizehints.height = height;
+      sizehints.flags = USSize | USPosition;
+      XSetNormalHints(dpy, win, &sizehints);
+      XSetStandardProperties(dpy, win, name, name,
+                              None, (char **)NULL, 0, &sizehints);
+   }
+
+   ctx = glXCreateContext( dpy, visinfo, NULL, True );
+   if (!ctx) {
+      printf("Error: glXCreateContext failed\n");
+      exit(1);
+   }
+
+   XFree(visinfo);
+
+   winData->display = dpy;
+   winData->window = win;
+   winData->context = ctx;
+}
+
+
+static void
+EventLoop(WindowData *winData)
+{
+   while (1) {
+      static long mask = StructureNotifyMask | ExposureMask | KeyPressMask;
+      XEvent event;
+      while (XCheckWindowEvent(winData->display, winData->window,
+                               mask, &event)) {
+         if (event.xany.window == winData->window) {
+            switch (event.type) {
+            case Expose:
+               DrawScene(winData);
+               break;
+            case ConfigureNotify:
+               glViewport(0, 0,
+                          event.xconfigure.width, event.xconfigure.height);
+               break;
+            case KeyPress:
+               {
+                  char buffer[10];
+                  int r;
+                  r = XLookupString(&event.xkey, buffer, sizeof(buffer),
+                                    NULL, NULL);
+                  if (buffer[0] == 27) {
+                     /* escape */
+                        return;
+                  }
+               }
+            }
+         }
+      }
+      DrawScene(winData);
+   }
+}
+
+
+int
+main(int argc, char *argv[])
+{
+   Display *dpy;
+   WindowData winData;
+
+   dpy = XOpenDisplay(NULL);
+   if (!dpy) {
+      printf("Error: couldn't open default display.\n");
+      return -1;
+   }
+
+   MakeWindow(dpy, "glprocs test", 0, 0, 300, 300, &winData);
+   XMapWindow(dpy, winData.window);
+   glXMakeCurrent(dpy, winData.window, winData.context);
+
+   InitializeOpenGL(&winData);
+
+   EventLoop(&winData);
+
+   glXDestroyContext(dpy, winData.context);
+   XDestroyWindow(dpy, winData.window);
+   XCloseDisplay(dpy);
+
+   return 0;
+}
diff --git a/src/ext/GLsdk/windemo/Makefile b/src/ext/GLsdk/windemo/Makefile
new file mode 100644
index 0000000..d9931d0
--- /dev/null
+++ b/src/ext/GLsdk/windemo/Makefile
@@ -0,0 +1,29 @@
+MAKE = $(MAKE) /nologo          # Turn off copyright notice
+
+all: singlewin.exe multiwin.exe multithread.exe
+
+singlewin.exe: 
+    @cd singlewin
+    @$(MAKE) /$(MAKEFLAGS)
+    @cd ..
+
+multiwin.exe: 
+    @cd multiwin
+    @$(MAKE) /$(MAKEFLAGS)
+    @cd ..
+
+multithread.exe: 
+    @cd multithread
+    @$(MAKE) /$(MAKEFLAGS)
+    @cd ..
+
+clean:
+    @cd singlewin
+    @$(MAKE) /$(MAKEFLAGS) clean
+    @cd ..
+    @cd multiwin
+    @$(MAKE) /$(MAKEFLAGS) clean
+    @cd ..
+    @cd multithread
+    @$(MAKE) /$(MAKEFLAGS) clean
+    @cd ..
diff --git a/src/ext/GLsdk/windemo/README b/src/ext/GLsdk/windemo/README
new file mode 100644
index 0000000..b2f5407
--- /dev/null
+++ b/src/ext/GLsdk/windemo/README
@@ -0,0 +1,24 @@
+demogl.{c,h} - OpenGL rendering routines (this directory. Shared by
+               programs in threee directories below).
+
+The following three directories have the same "demo.c" program which
+uses demogl, but is setup three different ways.
+
+singlewin   - Window setup to render in a single window. Most normal 
+              aplications work this way and don't have do anything 
+              special for OpenGL 1.2, 1.3 and extension procs.
+
+multiwin    - Multiple windows with a single message loop. At any given
+              time, there is only context which is current. The application
+              defines its own method for accessing the proc table 
+              (see _APP_PROCTABLE flag in the Makefile). Since there is
+              only window which is current, a global variable can be used
+              to provide reference to the current proc table.
+
+multithread - Multiple windows with a multiple message loops using 
+              multiple threads. At any given time, there can be multiple
+              current contexts.  The application defines its own method 
+              for accessing the proc table (see _APP_PROCTABLE flag in 
+              the Makefile). However, there can me multiple current contexts
+              on different thread, the application uses thread local 
+              storage to define proper access to the current proc table.
diff --git a/src/ext/GLsdk/windemo/demogl.c b/src/ext/GLsdk/windemo/demogl.c
new file mode 100644
index 0000000..35eb4e0
--- /dev/null
+++ b/src/ext/GLsdk/windemo/demogl.c
@@ -0,0 +1,203 @@
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#include <windows.h>    // Required inclusion on windows
+#include <GL/gl.h>      // OpenGL definitions
+#include <GL/glprocs.h> // OpenGL {1.2, 1.3, 1.4, 1.5} and extension functions
+
+#include "demogl.h"
+
+
+//====================================================================
+//  Using strstr for extension search can result in false positives
+//  because of substring matches. Since extension names in the
+//  extension string are separated by spaces, this can be fixed simply
+//  by looking for a space OR the end-of-string character immediately
+//  following the extension we're looking for (by skipping ahead 'len'
+//  characters).
+//====================================================================
+static GLboolean IsExtensionSupported(const GLubyte *extensionStr,
+                                      const GLubyte *checkExtension)
+{
+    const GLubyte  *s;
+	GLint len;
+
+	s = extensionStr;
+	len = strlen (checkExtension);
+
+	while ((s = strstr (s, checkExtension)) != NULL) {
+		s += len;
+
+		if ((*s == ' ') || (*s == '\0')) {
+			return (GL_TRUE);
+		}
+	}
+
+	return (GL_FALSE);
+}
+//========================================================================
+// Initialize the OpenGL context - create textures, check the extensions
+// supported by the driver etc.
+
+void InitializeOpenGL (WindowData *pwdata)
+{
+    const GLubyte *extstrGL;
+
+    GLubyte image[] = {
+        0xFF, 0x00, 0xFF, 0x00,
+        0x00, 0xFF, 0x00, 0xFF,
+        0xFF, 0x00, 0xFF, 0x00,
+        0x00, 0xFF, 0x00, 0xFF,
+    };
+
+    // Setup the extensions
+
+    extstrGL = glGetString (GL_EXTENSIONS);
+
+    // Check for WIN_swap_hint extension.
+    if (GL_TRUE == IsExtensionSupported(extstrGL, "GL_WIN_swap_hint")) {
+        pwdata->hasWinSwapHint = TRUE;
+    }
+
+    // Check for multi-texture extension.
+    if (GL_TRUE == IsExtensionSupported (extstrGL, "GL_ARB_multitexture")) {
+        pwdata->hasMultitexture = TRUE;
+
+        // Multi-texturing is supported. Create a texture for unit1 and
+        // bind it in MODULATE mode.
+
+        //==========================================================
+        //==========================================================
+        // Use an extension function without doing anything special!
+        // OpenGL 1.2, OpenGL 1.3 procs can be used similarly - as
+        // long we ensure it is supported - just as we have done
+        // for multi-texturing here.
+        //==========================================================
+        //==========================================================
+
+        glActiveTextureARB (GL_TEXTURE1_ARB);       // Use unit1
+
+        glGenTextures (1, &pwdata->texid);
+
+        glBindTexture (GL_TEXTURE_2D, pwdata->texid);   // Bound on unit 1
+        glTexImage2D (GL_TEXTURE_2D, 0, GL_LUMINANCE, 4, 4, 0, 
+                            GL_LUMINANCE, GL_UNSIGNED_BYTE, image);
+
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+        glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+
+        glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
+
+        glEnable (GL_TEXTURE_2D);
+    }
+}
+
+//========================================================================
+
+void DrawScene (WindowData *pwdata)
+{
+    // If WIN_swap_hint extension is supported, use it to create GREEN
+    // border around the frame. We render the first frame with GREEN.
+    // The second frame is the actual rendering rectangle - but is 
+    // swapped with a smaller swap rectangle.
+
+    if (pwdata->hasWinSwapHint) {
+        glClearColor (0.0, 1.0, 0.0, 0.0);      // GREEN
+        glClear(GL_COLOR_BUFFER_BIT);
+
+        SwapBuffers (pwdata->hDC);
+
+        // Setup the swap hint rect for the next frame
+
+        //==========================================================
+        //==========================================================
+        // Use an extension function without doing anything special!
+        // OpenGL 1.2, OpenGL 1.3 procs can be used similarly - as
+        // long we ensure it is supported - just as we have done
+        // for SwapHint here.
+        //==========================================================
+        //==========================================================
+
+        glAddSwapHintRectWIN(20, 20, pwdata->width - 40, pwdata->height - 40);
+    }
+
+    // Render a triangle - multi-textured if ARB_multitexture is supported.
+
+    glClearColor (0.0, 0.0, 0.0, 0.0);          // BLACK
+    glClear(GL_COLOR_BUFFER_BIT);
+
+    glMatrixMode (GL_MODELVIEW);
+    glLoadIdentity();
+
+    glRotatef (pwdata->spin, 0.0, 0.0, 1.0);
+
+    pwdata->spin += 2;
+
+    if (pwdata->spin >= 360) {
+        pwdata->spin = 0;
+    }
+
+    if (pwdata->hasMultitexture) {
+        //==========================================================
+        //==========================================================
+        // Use an extension function without doing anything special!
+        // OpenGL 1.2, OpenGL 1.3 procs can be used similarly - as
+        // long we ensure it is supported - just as we have done
+        // for MultiTexCoord here.
+        //==========================================================
+        //==========================================================
+
+        glBegin( GL_POLYGON );
+            glMultiTexCoord2fARB (GL_TEXTURE1_ARB, 0.0, 0.0);
+            glColor3f (1.0, 0.0, 0.0); 
+            glVertex3f(0.0, 0.0, 0.0);
+                                
+            glMultiTexCoord2fARB (GL_TEXTURE1_ARB, 1.0, 0.0);
+            glColor3f (0.0, 1.0, 0.0); 
+            glVertex3f(0.5, 0.0, 0.0);
+
+            glMultiTexCoord2fARB (GL_TEXTURE1_ARB, 1.0, 1.0);
+            glColor3f (0.0, 0.0, 1.0); 
+            glVertex3f(0.5, 0.5, 0.0);          
+        glEnd();
+    } else {
+        glBegin( GL_POLYGON );
+            glColor3f (1.0, 0.0, 0.0); 
+            glVertex3f(0.0, 0.0, 0.0);
+                                
+            glColor3f (0.0, 1.0, 0.0); 
+            glVertex3f(0.5, 0.0, 0.0);
+
+            glColor3f (0.0, 0.0, 1.0); 
+            glVertex3f(0.5, 0.5, 0.0);          
+        glEnd();
+    }
+
+    SwapBuffers (pwdata->hDC);
+}
diff --git a/src/ext/GLsdk/windemo/demogl.h b/src/ext/GLsdk/windemo/demogl.h
new file mode 100644
index 0000000..4fc93e8
--- /dev/null
+++ b/src/ext/GLsdk/windemo/demogl.h
@@ -0,0 +1,74 @@
+#ifndef __DEMOGL_H__ 
+#define __DEMOGL_H__ 
+   
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+// Define a structure keeping all application data on a per window
+// basis.
+
+typedef struct {        
+    // Intialized data
+
+    char  *windowTitle;
+
+    int   xpos;
+    int   ypos;
+    int   width;    // Size of client region
+    int   height;
+
+    int   pfdFlags; // Flags for selecting pixel format descriptor
+
+    // Computed data
+
+    int   hasMultitexture;  // Supports multi-texture
+    int   hasWinSwapHint;   // Supports WinSwapHint
+
+    int   spin;             // Rotation angle of triangle per window
+    int   texid;            // Texture id per window
+
+    HWND  hWnd;     // Main window handle.
+    HDC   hDC;      // Device context
+    HGLRC hRC;      // OpenGL context
+
+    // If we are using multiple renderers in a single process or on 
+    // multiple threads, we must keep our function table for 
+    // OpenGL 1.2, OpenGL 1.3 and extension functions 
+
+#ifdef _APP_PROCTABLE
+    _GLextensionProcs extensionProcs;
+#endif
+} WindowData;
+
+// Extern defintions for rendering functions in demogl.c.
+   
+void InitializeOpenGL (WindowData *pwdata);
+void DrawScene (WindowData *pwdata);
+
+#endif /* __DEMOGL_H__ */ 
diff --git a/src/ext/GLsdk/windemo/multithread/Makefile b/src/ext/GLsdk/windemo/multithread/Makefile
new file mode 100644
index 0000000..be9dd2b
--- /dev/null
+++ b/src/ext/GLsdk/windemo/multithread/Makefile
@@ -0,0 +1,39 @@
+GLSDKDIR = ..\..
+
+INCS = -I$(GLSDKDIR)
+INCS = $(INCS) -I..         # add demogl directory
+
+LIBS = GDI32.lib User32.lib OpenGL32.lib GLU32.lib
+
+# By default build release binaries.
+
+!if "$(BLDENV)" == ""
+CFLAGS  = -c
+LNFLAGS =
+!else
+CFLAGS  = -c -Od -Zi 
+LNFLAGS = -debug -debugtype:cv -pdbtype:con
+!endif
+
+#*********************************************************************
+# Since this is a multi-thread/multi-device application, we define
+# our own proctable.
+
+CFLAGS = $(CFLAGS) -D_APP_PROCTABLE
+
+#*********************************************************************
+
+demo: demo.obj demogl.obj glprocs.obj
+    link demo.obj demogl.obj glprocs.obj $(LIBS) $(LNFLAGS)
+
+demo.obj: demo.c ..\demogl.h
+    cl $(CFLAGS) $(INCS) demo.c
+
+demogl.obj: ..\demogl.c ..\demogl.h
+    cl $(CFLAGS) $(INCS) ..\demogl.c
+
+glprocs.obj: $(GLSDKDIR)\GL\glprocs.c
+    cl $(CFLAGS) $(INCS) $(GLSDKDIR)\GL\glprocs.c
+
+clean: 
+    @erase demo.obj glprocs.obj demogl.obj demo.exe *.pdb *.ilk > nul
diff --git a/src/ext/GLsdk/windemo/multithread/demo.c b/src/ext/GLsdk/windemo/multithread/demo.c
new file mode 100644
index 0000000..262709a
--- /dev/null
+++ b/src/ext/GLsdk/windemo/multithread/demo.c
@@ -0,0 +1,340 @@
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#include <windows.h>    // Required inclusion on windows
+#include <GL/gl.h>      // OpenGL definitions
+#include <GL/glprocs.h>
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "demogl.h"
+
+static WNDCLASSEX wcx;
+static char szAppName[] = "OpenGL";
+HINSTANCE _hInstance;
+
+WindowData wdata[] = {
+    {"MS OpenGL",   50,  50, 150, 150, 
+        PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_GENERIC_FORMAT},
+
+    {"ICD OpenGL",  50, 250, 200, 200, 
+        PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER},    
+};
+
+int nWnd = sizeof (wdata) / sizeof (wdata[0]);;
+
+#define TESTFLAGS (PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_GENERIC_FORMAT)
+
+//******************************************************************
+//******************************************************************
+
+DWORD tlsIndex;     // Index for thread local data.
+
+// Function to get thread local proc table.
+
+_GLextensionProcs *_GET_TLS_PROCTABLE(void) 
+{
+    WindowData *pwdata;
+
+    // Get pointer to thread local data.
+
+    pwdata = TlsGetValue (tlsIndex);
+
+    // Return the pointer to the extension proc table 
+    // hanging off the thread local data.
+
+    return (&pwdata->extensionProcs);
+}
+
+//******************************************************************
+//******************************************************************
+    
+//========================================================================
+// Setup a pixel format for a window, create context and initialize 
+// OpenGL 1.2 procs.
+
+void SetupWindow (HWND hWnd, WindowData *pwdata)
+{
+    int iPixelFormat = 0;
+    int numPixelFmts;
+    PIXELFORMATDESCRIPTOR pfd;
+    int i;
+
+    pwdata->hDC = GetDC (hWnd);     // Create a DC for the window.
+
+    // Search for a pixel format which matches the flags specified for
+    // the window.
+
+    numPixelFmts = DescribePixelFormat (pwdata->hDC, 1, sizeof (pfd), NULL);
+
+    for (i = 0; i < numPixelFmts; i++) {
+        DescribePixelFormat (pwdata->hDC, i+1, sizeof(pfd), &pfd);
+
+        if ((pfd.dwFlags & TESTFLAGS) == pwdata->pfdFlags) {
+            iPixelFormat = i+1;
+            break;
+        }
+    }
+
+    if (iPixelFormat == 0) {        // Did not find a suitable pixel format
+        assert (0);
+        exit(1);
+    }
+
+    // Set pixel format for the window
+
+    if (SetPixelFormat (pwdata->hDC, iPixelFormat, &pfd) == FALSE) {
+        assert (0);
+        exit (1);
+    }
+
+    // Create a context for the window
+
+    pwdata->hRC = wglCreateContext (pwdata->hDC);
+
+    // Bind this context to this thread. Since each thread is working on
+    // each window, we have to do MakeCurrent only once.
+
+    wglMakeCurrent (pwdata->hDC, pwdata->hRC);
+
+    // Initialize the OpenGL context.
+
+    InitializeOpenGL (pwdata);
+}
+
+//========================================================================
+// Proc to receive window messages
+
+LONG WINAPI WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+    PAINTSTRUCT ps;
+    WindowData  *pwdata;
+    RECT        rect;
+
+    // Obtain the window data for this thread. Note that WM_CREATE cannot
+    // "read" the values in window data since it has not yet been setup until
+    // we have gone through creation/initialization.
+
+    pwdata = TlsGetValue (tlsIndex);
+
+    // Process the window message.
+
+    switch (msg) {
+    case WM_CREATE:
+        SetupWindow (hWnd, ((LPCREATESTRUCT) lParam)->lpCreateParams);
+        return (0);
+
+    case WM_SIZE:
+        pwdata->width  = LOWORD (lParam);
+        pwdata->height = HIWORD (lParam);
+
+        glViewport (0, 0, pwdata->width, pwdata->height);
+        return 0;
+
+    case WM_PAINT:
+        // Since each thread has its own context, we don't have
+        // to do a MakeCurrent for each paint message.
+
+        BeginPaint (hWnd, &ps);
+        DrawScene(pwdata);          // Update the client area
+        EndPaint (hWnd, &ps);
+
+        return 0;       
+            
+    case WM_DESTROY:
+        // Delete the context. 
+
+        wglDeleteContext (pwdata->hRC);
+
+        PostQuitMessage( 0 );
+        return 0;
+    }
+
+    return DefWindowProc (hWnd, msg, wParam, lParam);
+}
+
+//========================================================================
+
+int ThreadMain (void *vi)
+{
+    int i = (int) vi;
+
+    MSG msg;  // message struct 
+
+    //******************************************************************
+    //******************************************************************
+    // Store the windowData for this thread in the thread local data.
+
+    TlsSetValue (tlsIndex, &wdata[i]);
+
+    // Initialize the OpenGL extension proc table for this window data.
+    // (One time intiailization per device context). We do it early
+    // so that even wgl Extensions are correctly available to the thread.
+
+    _InitExtensionProcs (&wdata[i].extensionProcs);
+
+    //******************************************************************
+    //******************************************************************
+
+    // Fill in the window class structure with parameters 
+    // that describe the main window. 
+ 
+    wcx.cbSize = sizeof(wcx);           // size of structure 
+    wcx.style = CS_HREDRAW | 
+            CS_VREDRAW;                 // redraw if size changes 
+    wcx.lpfnWndProc = WndProc;          // points to window procedure 
+    wcx.cbClsExtra = 0;                 // no extra class memory 
+    wcx.cbWndExtra = 0;                 // no extra window memory 
+    wcx.hInstance = _hInstance;          // handle to instance 
+    wcx.hIcon = LoadIcon(NULL, 
+        IDI_APPLICATION);               // predefined app. icon 
+    wcx.hCursor = LoadCursor(NULL, 
+        IDC_ARROW);                     // predefined arrow 
+    wcx.hbrBackground = GetStockObject( 
+        WHITE_BRUSH);                   // white background brush 
+    wcx.lpszMenuName =  NULL;           // name of menu resource 
+    wcx.lpszClassName = szAppName;      // name of window class 
+    wcx.hIconSm = LoadImage(_hInstance, // small class icon 
+        MAKEINTRESOURCE(5),
+        IMAGE_ICON, 
+        GetSystemMetrics(SM_CXSMICON), 
+        GetSystemMetrics(SM_CYSMICON), 
+        LR_DEFAULTCOLOR); 
+ 
+    // Register the window class. 
+ 
+    RegisterClassEx(&wcx);
+    // Create a window for the application.
+
+    wdata[i].hWnd = CreateWindow(
+                szAppName,              // Application name
+                wdata[i].windowTitle,   // Window title text
+                WS_OVERLAPPEDWINDOW |   // Window style 
+                WS_CLIPCHILDREN |       // Needed for OpenGL
+                WS_CLIPSIBLINGS,        // Needed for OpenGL
+                wdata[i].xpos,  wdata[i].ypos, 
+                wdata[i].width, wdata[i].height,
+                NULL,                   // No parent window
+                NULL,                   // Use the window class menu.
+                _hInstance,             // This instance owns this window
+                &wdata[i]);             // Application window data structure
+
+    // Check for window creation
+
+    if (!wdata[i].hWnd) {
+        assert (0);
+        exit (1);
+    }
+
+    // Make the window visible & update its client area
+
+    ShowWindow (wdata[i].hWnd, SW_SHOWNORMAL);
+    UpdateWindow (wdata[i].hWnd);            // Send WM_PAINT message
+
+    // Enter the Windows message loop. Get and dispatch messages
+    // until WM_QUIT.
+
+    while (GetMessage(&msg, // message structure
+               NULL,        // handle of window receiving the message
+               0,           // lowest message id to examine
+               0)) {        // highest message id to examine
+        TranslateMessage (&msg);
+        DispatchMessage (&msg);
+    }
+
+    UnregisterClass(szAppName, _hInstance);
+
+    return (msg.wParam);
+}
+
+//========================================================================
+// Windows main program.
+
+int WINAPI WinMain (HINSTANCE hInstance,
+                    HINSTANCE hPrevInstance,
+                    LPSTR lpszCmdLine, int nCmdShow)
+{
+
+    WNDCLASS wc;   // windows class sruct
+
+    int      i;
+    HANDLE   hThread;   
+    DWORD    IDThread;
+
+    _hInstance = hInstance; // Save for later use.
+
+    // Fill in window class structure with parameters that
+    //  describe the main window.
+
+    wc.style         = CS_HREDRAW | CS_VREDRAW;     // Class style(s).
+    wc.lpfnWndProc   = (WNDPROC)WndProc;            // Window Procedure
+    wc.cbClsExtra    = 0;     
+    wc.cbWndExtra    = 0;    
+    wc.hInstance     = hInstance;                   // Owner of this class
+    wc.hIcon         = NULL;                        // Icon name 
+    wc.hCursor       = LoadCursor(NULL, IDC_ARROW); // Cursor
+    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);    // Default color
+    wc.lpszMenuName  = NULL; 
+    wc.lpszClassName = szAppName;                   // Name to register as
+
+    // Register the window class
+
+    RegisterClass( &wc );
+
+    //******************************************************************
+    //******************************************************************
+    // For multi-threaded applications, allocate a thread local storage
+    // for storing a global for each thread.
+
+    if ( (tlsIndex = TlsAlloc()) == -1) {
+        assert (0);
+        exit(1);
+    }
+
+    //******************************************************************
+    //******************************************************************
+
+    for (i = 0; i < nWnd; i++) {
+        hThread = CreateThread (NULL, 0, 
+                                (LPTHREAD_START_ROUTINE) ThreadMain, 
+                                (void *) i, 0, &IDThread);
+
+        if (hThread == NULL) {
+            assert (0);
+            exit(1);
+        }
+    }
+
+    // We don't nee this thread anymore since the two threads are 
+    // taking care of the two windows independently. However, we 
+    // exit the thread and not the process.
+
+    ExitThread (0);
+}
diff --git a/src/ext/GLsdk/windemo/multiwin/Makefile b/src/ext/GLsdk/windemo/multiwin/Makefile
new file mode 100644
index 0000000..80d13de
--- /dev/null
+++ b/src/ext/GLsdk/windemo/multiwin/Makefile
@@ -0,0 +1,37 @@
+GLSDKDIR = ..\..
+
+INCS = -I$(GLSDKDIR)
+INCS = $(INCS) -I..         # add demogl directory
+
+LIBS = GDI32.lib User32.lib OpenGL32.lib GLU32.lib
+
+!if ("$(BLDENV)" == "")
+CFLAGS  = -c
+LNFLAGS =
+!else
+CFLAGS  = -c -Od -Zi 
+LNFLAGS = -debug -debugtype:cv -pdbtype:con
+!endif
+
+#*********************************************************************
+# Since this is a multi-thread/multi-device application, we define
+# our own proctable.
+
+CFLAGS = $(CFLAGS) -D_APP_PROCTABLE
+
+#*********************************************************************
+
+demo: demo.obj demogl.obj glprocs.obj
+    link demo.obj demogl.obj glprocs.obj $(LIBS) $(LNFLAGS)
+
+demo.obj: demo.c ..\demogl.h
+    cl $(CFLAGS) $(INCS) demo.c
+
+demogl.obj: ..\demogl.c ..\demogl.h
+    cl $(CFLAGS) $(INCS) ..\demogl.c
+
+glprocs.obj: $(GLSDKDIR)\GL\glprocs.c
+    cl $(CFLAGS) $(INCS) $(GLSDKDIR)\GL\glprocs.c
+
+clean: 
+    @erase demo.obj glprocs.obj demogl.obj demo.exe *.pdb *.ilk > nul
diff --git a/src/ext/GLsdk/windemo/multiwin/demo.c b/src/ext/GLsdk/windemo/multiwin/demo.c
new file mode 100644
index 0000000..e549925
--- /dev/null
+++ b/src/ext/GLsdk/windemo/multiwin/demo.c
@@ -0,0 +1,313 @@
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#include <windows.h>    // Required inclusion on windows
+#include <GL/gl.h>      // OpenGL definitions
+#include <GL/glprocs.h>
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "demogl.h"
+
+static char szAppName[] = "OpenGL";
+HINSTANCE _hInstance;
+
+WindowData wdata[] = {
+    {"MS OpenGL",   50,  50, 150, 150, 
+        PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_GENERIC_FORMAT},
+
+    {"ICD OpenGL",  50, 250, 200, 200, 
+        PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER},    
+};
+
+int nWnd = sizeof (wdata) / sizeof (wdata[0]);;
+
+#define TESTFLAGS (PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_GENERIC_FORMAT)
+
+//******************************************************************
+//******************************************************************
+
+WindowData  *currentWindowData;
+
+// Function to get thread local proc table.
+
+_GLextensionProcs *_GET_TLS_PROCTABLE(void) 
+{
+    // Return the pointer to the extension proc table 
+    // hanging off the current local data.
+
+    return (&currentWindowData->extensionProcs);
+}
+
+//******************************************************************
+//******************************************************************
+    
+//========================================================================
+// Setup a pixel format for a window, create context and initialize 
+// OpenGL 1.2 procs.
+
+void SetupWindow (HWND hWnd, WindowData *pwdata)
+{
+    int iPixelFormat = 0;
+    int numPixelFmts;
+    PIXELFORMATDESCRIPTOR pfd;
+    int i;
+
+    pwdata->hDC = GetDC (hWnd);     // Create a DC for the window.
+
+    // Search for a pixel format which matches the flags specified for
+    // the window.
+
+    numPixelFmts = DescribePixelFormat (pwdata->hDC, 1, sizeof (pfd), NULL);
+
+    for (i = 0; i < numPixelFmts; i++) {
+        DescribePixelFormat (pwdata->hDC, i+1, sizeof(pfd), &pfd);
+
+        if ((pfd.dwFlags & TESTFLAGS) == pwdata->pfdFlags) {
+            iPixelFormat = i+1;
+            break;
+        }
+    }
+
+    if (iPixelFormat == 0) {        // Did not find a suitable pixel format
+        assert (0);
+        exit(1);
+    }
+
+    // Set pixel format for the window
+
+    if (SetPixelFormat (pwdata->hDC, iPixelFormat, &pfd) == FALSE) {
+        assert (0);
+        exit (1);
+    }
+
+    // Create a context for the window
+
+    pwdata->hRC = wglCreateContext (pwdata->hDC);
+
+    // Bind this context to this thread. Since each thread is working on
+    // each window, we have to do MakeCurrent only once.
+
+    wglMakeCurrent (pwdata->hDC, pwdata->hRC);
+
+    //********************************************************
+    //********************************************************
+    // Every time we do MakeCurrent, we must setup the global
+    // ptr to currentWindowData so that we have the correct
+    // proc table for OpenGL functions.
+
+    currentWindowData = pwdata;
+
+    //********************************************************
+    //********************************************************
+
+    // Initialize the OpenGL context.
+
+    InitializeOpenGL (pwdata);
+}
+
+//========================================================================
+// Proc to receive window messages
+
+LONG WINAPI WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+    PAINTSTRUCT ps;
+    WindowData  *pwdata;
+    RECT        rect;
+
+    // Obtain the window data for this thread. Note that WM_CREATE cannot
+    // "read" the values in window data since it has not yet been setup until
+    // we have gone through creation/initialization. Also, pwdata as
+    // computed below is incorrect when we receive WM_CREATE msg.
+
+    if (hWnd == wdata[0].hWnd) {
+        pwdata = &wdata[0];
+    } else {
+        pwdata = &wdata[1];
+    }
+
+    // Process the window message.
+
+    switch (msg) {
+    case WM_CREATE:
+        SetupWindow (hWnd, ((LPCREATESTRUCT) lParam)->lpCreateParams);
+        return (0);
+
+    case WM_SIZE:
+        pwdata->width  = LOWORD (lParam);
+        pwdata->height = HIWORD (lParam);
+
+        glViewport (0, 0, pwdata->width, pwdata->height);
+        return 0;
+
+    case WM_PAINT:
+        // Since both the contexts are running on the same thread,
+        // make the context for the current window current 
+        // before rendering.
+
+        wglMakeCurrent (pwdata->hDC, pwdata->hRC);
+
+        //********************************************************
+        //********************************************************
+        // Every time we do MakeCurrent, we must setup the global
+        // ptr to currentWindowData so that we have the correct
+        // proc table for OpenGL functions.
+    
+        currentWindowData = pwdata;
+    
+        //********************************************************
+        //********************************************************
+
+        BeginPaint (hWnd, &ps);
+        DrawScene(pwdata);          // Update the client area
+        EndPaint (hWnd, &ps);
+
+        return 0;       
+            
+    case WM_DESTROY:
+        // Delete the context. 
+
+        wglDeleteContext (pwdata->hRC);
+
+        // In multi-window scenario, post the quit message
+        // only when the number of window becomes zero.
+
+        nWnd -= 1;
+
+        if (nWnd == 0) {
+            PostQuitMessage( 0 );
+        }
+        return 0;
+    }
+
+    return DefWindowProc (hWnd, msg, wParam, lParam);
+}
+
+//========================================================================
+
+int ThreadMain (int i)
+{
+    //******************************************************************
+    //******************************************************************
+
+    // Initialize the OpenGL extension proc table for this window data.
+    // (One time intiailization per device context). We do it early
+    // so that even wgl Extensions are correctly available to the thread.
+
+    _InitExtensionProcs (&wdata[i].extensionProcs);
+
+    //******************************************************************
+    //******************************************************************
+
+    // Create a window for the application.
+
+    wdata[i].hWnd = CreateWindow(
+                szAppName,              // Application name
+                wdata[i].windowTitle,   // Window title text
+                WS_OVERLAPPEDWINDOW |   // Window style 
+                WS_CLIPCHILDREN |       // Needed for OpenGL
+                WS_CLIPSIBLINGS,        // Needed for OpenGL
+                wdata[i].xpos,  wdata[i].ypos, 
+                wdata[i].width, wdata[i].height,
+                NULL,                   // No parent window
+                NULL,                   // Use the window class menu.
+                _hInstance,             // This instance owns this window
+                &wdata[i]);             // Application window data structure
+
+    // Check for window creation
+
+    if (!wdata[i].hWnd) {
+        assert (0);
+        exit (1);
+    }
+
+    // Make the window visible & update its client area
+
+    ShowWindow (wdata[i].hWnd, SW_SHOWNORMAL);
+    UpdateWindow (wdata[i].hWnd);            // Send WM_PAINT message
+
+    return (0);
+}
+
+//========================================================================
+// Windows main program.
+
+int WINAPI WinMain (HINSTANCE hInstance,
+                    HINSTANCE hPrevInstance,
+                    LPSTR lpszCmdLine, int nCmdShow)
+{
+
+    WNDCLASS wc;   // windows class sruct
+
+    int      i;
+    HANDLE   hThread;   
+    DWORD    IDThread;
+
+    MSG msg;  // message struct 
+
+    _hInstance = hInstance; // Save for later use.
+
+    // Fill in window class structure with parameters that
+    //  describe the main window.
+
+    wc.style         = CS_HREDRAW | CS_VREDRAW;     // Class style(s).
+    wc.lpfnWndProc   = (WNDPROC)WndProc;            // Window Procedure
+    wc.cbClsExtra    = 0;     
+    wc.cbWndExtra    = 0;    
+    wc.hInstance     = hInstance;                   // Owner of this class
+    wc.hIcon         = NULL;                        // Icon name 
+    wc.hCursor       = LoadCursor(NULL, IDC_ARROW); // Cursor
+    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);    // Default color
+    wc.lpszMenuName  = NULL; 
+    wc.lpszClassName = szAppName;                   // Name to register as
+
+    // Register the window class
+
+    RegisterClass( &wc );
+
+    // Create multiple windows without creating threads.
+
+    for (i = 0; i < nWnd; i++) {
+        ThreadMain (i);
+    }
+
+    // Enter the Windows message loop. Get and dispatch messages
+    // until WM_QUIT.
+
+    while (GetMessage(&msg, // message structure
+               NULL,        // handle of window receiving the message
+               0,           // lowest message id to examine
+               0)) {        // highest message id to examine
+        TranslateMessage (&msg);
+        DispatchMessage (&msg);
+    }
+
+    return (msg.wParam);
+}
diff --git a/src/ext/GLsdk/windemo/singlewin/Makefile b/src/ext/GLsdk/windemo/singlewin/Makefile
new file mode 100644
index 0000000..3f4d088
--- /dev/null
+++ b/src/ext/GLsdk/windemo/singlewin/Makefile
@@ -0,0 +1,29 @@
+GLSDKDIR = ..\..
+
+INCS = -I$(GLSDKDIR)
+INCS = $(INCS) -I..         # add windemo directory
+
+LIBS = GDI32.lib User32.lib OpenGL32.lib GLU32.lib
+
+!if ("$(BLDENV)" == "")
+CFLAGS  = -c
+LNFLAGS =
+!else
+CFLAGS  = -c -Od -Zi 
+LNFLAGS = -debug -debugtype:cv -pdbtype:con
+!endif
+
+demo: demo.obj demogl.obj glprocs.obj
+    link demo.obj demogl.obj glprocs.obj $(LIBS) $(LNFLAGS)
+
+demo.obj: demo.c ..\demogl.h
+    cl $(CFLAGS) $(INCS) demo.c
+
+demogl.obj: ..\demogl.c ..\demogl.h
+    cl $(CFLAGS) $(INCS) ..\demogl.c
+
+glprocs.obj: $(GLSDKDIR)\GL\glprocs.c
+    cl $(CFLAGS) $(INCS) $(GLSDKDIR)\GL\glprocs.c
+
+clean: 
+    @erase demo.obj glprocs.obj demogl.obj demo.exe *.pdb *.ilk > nul
diff --git a/src/ext/GLsdk/windemo/singlewin/demo.c b/src/ext/GLsdk/windemo/singlewin/demo.c
new file mode 100644
index 0000000..7c59e49
--- /dev/null
+++ b/src/ext/GLsdk/windemo/singlewin/demo.c
@@ -0,0 +1,245 @@
+/*
+** License Applicability. Except to the extent portions of this file are
+** made subject to an alternative license as permitted in the SGI Free
+** Software License B, Version 1.1 (the "License"), the contents of this
+** file are subject only to the provisions of the License. You may not use
+** this file except in compliance with the License. You may obtain a copy
+** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
+** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
+** 
+** http://oss.sgi.com/projects/FreeB
+** 
+** Note that, as provided in the License, the Software is distributed on an
+** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
+** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
+** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
+** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
+** 
+** Original Code. The Original Code is: OpenGL Sample Implementation,
+** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
+** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
+** Copyright in any portions created by third parties is as indicated
+** elsewhere herein. All Rights Reserved.
+** 
+** Additional Notice Provisions: This software was created using the
+** OpenGL(R) version 1.2.1 Sample Implementation published by SGI, but has
+** not been independently verified as being compliant with the OpenGL(R)
+** version 1.2.1 Specification.
+*/
+
+#include <windows.h>    // Required inclusion on windows
+#include <GL/gl.h>      // OpenGL definitions
+#include <GL/glprocs.h>
+
+#include <stdio.h>
+#include <assert.h>
+
+#include "demogl.h"
+
+static char szAppName[] = "OpenGL";
+HINSTANCE _hInstance;
+
+WindowData wdata[] = {
+    {"ICD OpenGL",  50, 250, 200, 200, 
+        PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER},    
+};
+
+int nWnd = sizeof (wdata) / sizeof (wdata[0]);;
+
+#define TESTFLAGS (PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER | PFD_GENERIC_FORMAT)
+
+//========================================================================
+// Setup a pixel format for a window, create context and initialize 
+// OpenGL 1.2 procs.
+
+void SetupWindow (HWND hWnd, WindowData *pwdata)
+{
+    int iPixelFormat = 0;
+    int numPixelFmts;
+    PIXELFORMATDESCRIPTOR pfd;
+    int i;
+
+    pwdata->hDC = GetDC (hWnd);     // Create a DC for the window.
+
+    // Search for a pixel format which matches the flags specified for
+    // the window.
+
+    numPixelFmts = DescribePixelFormat (pwdata->hDC, 1, sizeof (pfd), NULL);
+
+    for (i = 0; i < numPixelFmts; i++) {
+        DescribePixelFormat (pwdata->hDC, i+1, sizeof(pfd), &pfd);
+
+        if ((pfd.dwFlags & TESTFLAGS) == pwdata->pfdFlags) {
+            iPixelFormat = i+1;
+            break;
+        }
+    }
+
+    if (iPixelFormat == 0) {        // Did not find a suitable pixel format
+        assert (0);
+        exit(1);
+    }
+
+    // Set pixel format for the window
+
+    if (SetPixelFormat (pwdata->hDC, iPixelFormat, &pfd) == FALSE) {
+        assert (0);
+        exit (1);
+    }
+
+    // Create a context for the window
+
+    pwdata->hRC = wglCreateContext (pwdata->hDC);
+
+    // Bind this context to this thread. Since each thread is working on
+    // each window, we have to do MakeCurrent only once.
+
+    wglMakeCurrent (pwdata->hDC, pwdata->hRC);
+
+    // Initialize the OpenGL context.
+
+    InitializeOpenGL (pwdata);
+}
+
+//========================================================================
+// Proc to receive window messages
+
+LONG WINAPI WndProc (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+    PAINTSTRUCT ps;
+    WindowData  *pwdata;
+    RECT        rect;
+
+    // Obtain the window data for this thread. Note that WM_CREATE cannot
+    // "read" the values in window data since it has not yet been setup until
+    // we have gone through creation/initialization. Also, pwdata as
+    // computed below is incorrect when we receive WM_CREATE msg.
+
+    if (hWnd == wdata[0].hWnd) {
+        pwdata = &wdata[0];
+    } else {
+        pwdata = &wdata[1];
+    }
+
+    // Process the window message.
+
+    switch (msg) {
+    case WM_CREATE:
+        SetupWindow (hWnd, ((LPCREATESTRUCT) lParam)->lpCreateParams);
+        return (0);
+
+    case WM_SIZE:
+        pwdata->width  = LOWORD (lParam);
+        pwdata->height = HIWORD (lParam);
+
+        glViewport (0, 0, pwdata->width, pwdata->height);
+        return 0;
+
+    case WM_PAINT:
+        BeginPaint (hWnd, &ps);
+        DrawScene(pwdata);          // Update the client area
+        EndPaint (hWnd, &ps);
+
+        return 0;       
+            
+    case WM_DESTROY:
+        // Delete the context. 
+
+        wglDeleteContext (pwdata->hRC);
+
+        PostQuitMessage( 0 );
+        return 0;
+    }
+
+    return DefWindowProc (hWnd, msg, wParam, lParam);
+}
+
+//========================================================================
+
+int ThreadMain (int i)
+{
+    // Create a window for the application.
+
+    wdata[i].hWnd = CreateWindow(
+                szAppName,              // Application name
+                wdata[i].windowTitle,   // Window title text
+                WS_OVERLAPPEDWINDOW |   // Window style 
+                WS_CLIPCHILDREN |       // Needed for OpenGL
+                WS_CLIPSIBLINGS,        // Needed for OpenGL
+                wdata[i].xpos,  wdata[i].ypos, 
+                wdata[i].width, wdata[i].height,
+                NULL,                   // No parent window
+                NULL,                   // Use the window class menu.
+                _hInstance,             // This instance owns this window
+                &wdata[i]);             // Application window data structure
+
+    // Check for window creation
+
+    if (!wdata[i].hWnd) {
+        assert (0);
+        exit (1);
+    }
+
+    // Make the window visible & update its client area
+
+    ShowWindow (wdata[i].hWnd, SW_SHOWNORMAL);
+    UpdateWindow (wdata[i].hWnd);            // Send WM_PAINT message
+
+    return (0);
+}
+
+//========================================================================
+// Windows main program.
+
+int WINAPI WinMain (HINSTANCE hInstance,
+                    HINSTANCE hPrevInstance,
+                    LPSTR lpszCmdLine, int nCmdShow)
+{
+
+    WNDCLASS wc;   // windows class sruct
+
+    int      i;
+    HANDLE   hThread;   
+    DWORD    IDThread;
+
+    MSG msg;  // message struct 
+
+    _hInstance = hInstance; // Save for later use.
+
+    // Fill in window class structure with parameters that
+    //  describe the main window.
+
+    wc.style         = CS_HREDRAW | CS_VREDRAW;     // Class style(s).
+    wc.lpfnWndProc   = (WNDPROC)WndProc;            // Window Procedure
+    wc.cbClsExtra    = 0;     
+    wc.cbWndExtra    = 0;    
+    wc.hInstance     = hInstance;                   // Owner of this class
+    wc.hIcon         = NULL;                        // Icon name 
+    wc.hCursor       = LoadCursor(NULL, IDC_ARROW); // Cursor
+    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);    // Default color
+    wc.lpszMenuName  = NULL; 
+    wc.lpszClassName = szAppName;                   // Name to register as
+
+    // Register the window class
+
+    RegisterClass( &wc );
+
+    // Create a single window without creating threads.
+
+    for (i = 0; i < nWnd; i++) {
+        ThreadMain (0);
+    }
+
+    // Enter the Windows message loop. Get and dispatch messages
+    // until WM_QUIT.
+
+    while (GetMessage(&msg, // message structure
+               NULL,        // handle of window receiving the message
+               0,           // lowest message id to examine
+               0)) {        // highest message id to examine
+        TranslateMessage (&msg);
+        DispatchMessage (&msg);
+    }
+
+    return (msg.wParam);
+}
diff --git a/src/ext/ftgl/FTBuffer.cpp b/src/ext/ftgl/FTBuffer.cpp
new file mode 100644
index 0000000..3815bb1
--- /dev/null
+++ b/src/ext/ftgl/FTBuffer.cpp
@@ -0,0 +1,69 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+
+FTBuffer::FTBuffer()
+ : width(0),
+   height(0),
+   pixels(0),
+   pos(FTPoint())
+{
+}
+
+
+FTBuffer::~FTBuffer()
+{
+    if(pixels)
+    {
+        delete[] pixels;
+    }
+}
+
+
+void FTBuffer::Size(int w, int h)
+{
+    if(w == width && h == height)
+    {
+        return;
+    }
+
+    if(w * h != width * height)
+    {
+        if(pixels)
+        {
+            delete[] pixels;
+        }
+        pixels = new unsigned char[w * h];
+    }
+
+    memset(pixels, 0, w * h);
+    width = w;
+    height = h;
+}
+
diff --git a/src/ext/ftgl/FTCharToGlyphIndexMap.h b/src/ext/ftgl/FTCharToGlyphIndexMap.h
new file mode 100644
index 0000000..3aa10a1
--- /dev/null
+++ b/src/ext/ftgl/FTCharToGlyphIndexMap.h
@@ -0,0 +1,155 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef    __FTCharToGlyphIndexMap__
+#define    __FTCharToGlyphIndexMap__
+
+#include <stdlib.h>
+
+#include "FTGL/ftgl.h"
+
+/**
+ * Provides a non-STL alternative to the STL map<unsigned long, unsigned long>
+ * which maps character codes to glyph indices inside FTCharmap.
+ *
+ * Implementation:
+ *   - NumberOfBuckets buckets are considered.
+ *   - Each bucket has BucketSize entries.
+ *   - When the glyph index for the character code C has to be stored, the
+ *     bucket this character belongs to is found using 'C div BucketSize'.
+ *     If this bucket has not been allocated yet, do it now.
+ *     The entry in the bucked is found using 'C mod BucketSize'.
+ *     If it is set to IndexNotFound, then the glyph entry has not been set.
+ *   - Try to mimic the calls made to the STL map API.
+ *
+ * Caveats:
+ *   - The glyph index is now a signed long instead of unsigned long, so
+ *     the special value IndexNotFound (= -1) can be used to specify that the
+ *     glyph index has not been stored yet.
+ */
+class FTCharToGlyphIndexMap
+{
+    public:
+
+        typedef unsigned long CharacterCode;
+        typedef signed long GlyphIndex;
+
+        enum
+        {
+            NumberOfBuckets = 256,
+            BucketSize = 256,
+            IndexNotFound = -1
+        };
+
+        FTCharToGlyphIndexMap()
+        {
+            this->Indices = 0;
+        }
+
+        virtual ~FTCharToGlyphIndexMap()
+        {
+            if(this->Indices)
+            {
+                // Free all buckets
+                this->clear();
+
+                // Free main structure
+                delete [] this->Indices;
+                this->Indices = 0;
+            }
+        }
+
+        void clear()
+        {
+            if(this->Indices)
+            {
+                for(int i = 0; i < FTCharToGlyphIndexMap::NumberOfBuckets; i++)
+                {
+                    if(this->Indices[i])
+                    {
+                        delete [] this->Indices[i];
+                        this->Indices[i] = 0;
+                    }
+                }
+            }
+        }
+
+        const GlyphIndex find(CharacterCode c)
+        {
+            if(!this->Indices)
+            {
+                return 0;
+            }
+
+            // Find position of char code in buckets
+            div_t pos = div(c, FTCharToGlyphIndexMap::BucketSize);
+
+            if(!this->Indices[pos.quot])
+            {
+                return 0;
+            }
+
+            const FTCharToGlyphIndexMap::GlyphIndex *ptr = &this->Indices[pos.quot][pos.rem];
+            if(*ptr == FTCharToGlyphIndexMap::IndexNotFound)
+            {
+                return 0;
+            }
+
+            return *ptr;
+        }
+
+        void insert(CharacterCode c, GlyphIndex g)
+        {
+            if(!this->Indices)
+            {
+                this->Indices = new GlyphIndex* [FTCharToGlyphIndexMap::NumberOfBuckets];
+                for(int i = 0; i < FTCharToGlyphIndexMap::NumberOfBuckets; i++)
+                {
+                    this->Indices[i] = 0;
+                }
+            }
+
+            // Find position of char code in buckets
+            div_t pos = div(c, FTCharToGlyphIndexMap::BucketSize);
+
+            // Allocate bucket if does not exist yet
+            if(!this->Indices[pos.quot])
+            {
+                this->Indices[pos.quot] = new GlyphIndex [FTCharToGlyphIndexMap::BucketSize];
+                for(int i = 0; i < FTCharToGlyphIndexMap::BucketSize; i++)
+                {
+                    this->Indices[pos.quot][i] = FTCharToGlyphIndexMap::IndexNotFound;
+                }
+            }
+
+            this->Indices[pos.quot][pos.rem] = g;
+        }
+
+    private:
+        GlyphIndex** Indices;
+};
+
+
+#endif  //  __FTCharToGlyphIndexMap__
diff --git a/src/ext/ftgl/FTCharmap.cpp b/src/ext/ftgl/FTCharmap.cpp
new file mode 100644
index 0000000..64a2180
--- /dev/null
+++ b/src/ext/ftgl/FTCharmap.cpp
@@ -0,0 +1,106 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTFace.h"
+#include "FTCharmap.h"
+
+
+FTCharmap::FTCharmap(FTFace* face)
+:   ftFace(*(face->Face())),
+    err(0)
+{
+    if(!ftFace->charmap)
+    {
+        if(!ftFace->num_charmaps)
+        {
+            // This face doesn't even have one charmap!
+            err = 0x96; // Invalid_CharMap_Format
+            return;
+        }
+
+        err = FT_Set_Charmap(ftFace, ftFace->charmaps[0]);
+    }
+
+    ftEncoding = ftFace->charmap->encoding;
+
+    for(unsigned int i = 0; i < FTCharmap::MAX_PRECOMPUTED; i++)
+    {
+        charIndexCache[i] = FT_Get_Char_Index(ftFace, i);
+    }
+}
+
+
+FTCharmap::~FTCharmap()
+{
+    charMap.clear();
+}
+
+
+bool FTCharmap::CharMap(FT_Encoding encoding)
+{
+    if(ftEncoding == encoding)
+    {
+        err = 0;
+        return true;
+    }
+
+    err = FT_Select_Charmap(ftFace, encoding);
+
+    if(!err)
+    {
+        ftEncoding = encoding;
+        charMap.clear();
+    }
+
+    return !err;
+}
+
+
+unsigned int FTCharmap::GlyphListIndex(const unsigned int characterCode)
+{
+    return charMap.find(characterCode);
+}
+
+
+unsigned int FTCharmap::FontIndex(const unsigned int characterCode)
+{
+    if(characterCode < FTCharmap::MAX_PRECOMPUTED)
+    {
+        return charIndexCache[characterCode];
+    }
+
+    return FT_Get_Char_Index(ftFace, characterCode);
+}
+
+
+void FTCharmap::InsertIndex(const unsigned int characterCode,
+                            const size_t containerIndex)
+{
+    charMap.insert(characterCode, static_cast<FTCharToGlyphIndexMap::GlyphIndex>(containerIndex));
+}
+
diff --git a/src/ext/ftgl/FTCharmap.h b/src/ext/ftgl/FTCharmap.h
new file mode 100644
index 0000000..f4ce867
--- /dev/null
+++ b/src/ext/ftgl/FTCharmap.h
@@ -0,0 +1,165 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTCharmap__
+#define     __FTCharmap__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+
+#include "FTGL/ftgl.h"
+#include "FTCharToGlyphIndexMap.h"
+
+
+/**
+ * FTCharmap takes care of specifying the encoding for a font and mapping
+ * character codes to glyph indices.
+ *
+ * It doesn't preprocess all indices, only on an as needed basis. This may
+ * seem like a performance penalty but it is quicker than using the 'raw'
+ * freetype calls and will save significant amounts of memory when dealing
+ * with unicode encoding
+ *
+ * @see "Freetype 2 Documentation"
+ *
+ */
+
+class FTFace;
+
+class FTCharmap
+{
+    public:
+        /**
+         * Constructor
+         */
+        FTCharmap(FTFace* face);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTCharmap();
+
+        /**
+         * Queries for the current character map code.
+         *
+         * @return  The current character map code.
+         */
+        FT_Encoding Encoding() const { return ftEncoding; }
+
+        /**
+         * Sets the character map for the face. If an error occurs the object is not modified.
+         * Valid encodings as at Freetype 2.0.4
+         *      ft_encoding_none
+         *      ft_encoding_symbol
+         *      ft_encoding_unicode
+         *      ft_encoding_latin_2
+         *      ft_encoding_sjis
+         *      ft_encoding_gb2312
+         *      ft_encoding_big5
+         *      ft_encoding_wansung
+         *      ft_encoding_johab
+         *      ft_encoding_adobe_standard
+         *      ft_encoding_adobe_expert
+         *      ft_encoding_adobe_custom
+         *      ft_encoding_apple_roman
+         *
+         * @param encoding  the Freetype encoding symbol. See above.
+         * @return          <code>true</code> if charmap was valid and set
+         *                  correctly.
+         */
+        bool CharMap(FT_Encoding encoding);
+
+        /**
+         * Get the FTGlyphContainer index of the input character.
+         *
+         * @param characterCode The character code of the requested glyph in
+         *                      the current encoding eg apple roman.
+         * @return      The FTGlyphContainer index for the character or zero
+         *              if it wasn't found
+         */
+        unsigned int GlyphListIndex(const unsigned int characterCode);
+
+        /**
+         * Get the font glyph index of the input character.
+         *
+         * @param characterCode The character code of the requested glyph in
+         *                      the current encoding eg apple roman.
+         * @return      The glyph index for the character.
+         */
+        unsigned int FontIndex(const unsigned int characterCode);
+
+        /**
+         * Set the FTGlyphContainer index of the character code.
+         *
+         * @param characterCode  The character code of the requested glyph in
+         *                       the current encoding eg apple roman.
+         * @param containerIndex The index into the FTGlyphContainer of the
+         *                       character code.
+         */
+        void InsertIndex(const unsigned int characterCode,
+                         const size_t containerIndex);
+
+        /**
+         * Queries for errors.
+         *
+         * @return  The current error code. Zero means no error.
+         */
+        FT_Error Error() const { return err; }
+
+    private:
+        /**
+         * Current character map code.
+         */
+        FT_Encoding ftEncoding;
+
+        /**
+         * The current Freetype face.
+         */
+        const FT_Face ftFace;
+
+        /**
+         * A structure that maps glyph indices to character codes
+         *
+         * < character code, face glyph index>
+         */
+        typedef FTCharToGlyphIndexMap CharacterMap;
+        CharacterMap charMap;
+
+        /**
+         * Precomputed font indices.
+         */
+        static const unsigned int MAX_PRECOMPUTED = 128;
+        unsigned int charIndexCache[MAX_PRECOMPUTED];
+
+        /**
+         * Current error code.
+         */
+        FT_Error err;
+};
+
+
+#endif  //  __FTCharmap__
diff --git a/src/ext/ftgl/FTContour.cpp b/src/ext/ftgl/FTContour.cpp
new file mode 100644
index 0000000..cef1f3b
--- /dev/null
+++ b/src/ext/ftgl/FTContour.cpp
@@ -0,0 +1,245 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTContour.h"
+
+#include <math.h>
+
+static const unsigned int BEZIER_STEPS = 5;
+
+
+void FTContour::AddPoint(FTPoint point)
+{
+    if(pointList.empty() || (point != pointList[pointList.size() - 1]
+                              && point != pointList[0]))
+    {
+        pointList.push_back(point);
+    }
+}
+
+
+void FTContour::AddOutsetPoint(FTPoint point)
+{
+    outsetPointList.push_back(point);
+}
+
+
+void FTContour::AddFrontPoint(FTPoint point)
+{
+    frontPointList.push_back(point);
+}
+
+
+void FTContour::AddBackPoint(FTPoint point)
+{
+    backPointList.push_back(point);
+}
+
+
+void FTContour::evaluateQuadraticCurve(FTPoint A, FTPoint B, FTPoint C)
+{
+    for(unsigned int i = 1; i < BEZIER_STEPS; i++)
+    {
+        float t = static_cast<float>(i) / BEZIER_STEPS;
+
+        FTPoint U = (1.0f - t) * A + t * B;
+        FTPoint V = (1.0f - t) * B + t * C;
+
+        AddPoint((1.0f - t) * U + t * V);
+    }
+}
+
+
+void FTContour::evaluateCubicCurve(FTPoint A, FTPoint B, FTPoint C, FTPoint D)
+{
+    for(unsigned int i = 0; i < BEZIER_STEPS; i++)
+    {
+        float t = static_cast<float>(i) / BEZIER_STEPS;
+
+        FTPoint U = (1.0f - t) * A + t * B;
+        FTPoint V = (1.0f - t) * B + t * C;
+        FTPoint W = (1.0f - t) * C + t * D;
+
+        FTPoint M = (1.0f - t) * U + t * V;
+        FTPoint N = (1.0f - t) * V + t * W;
+
+        AddPoint((1.0f - t) * M + t * N);
+    }
+}
+
+
+// This function is a bit tricky. Given a path ABC, it returns the
+// coordinates of the outset point facing B on the left at a distance
+// of 64.0.
+//                                         M
+//                            - - - - - - X
+//                             ^         / '
+//                             | 64.0   /   '
+//  X---->-----X     ==>    X--v-------X     '
+// A          B \          A          B \   .>'
+//               \                       \<'  64.0
+//                \                       \                  .
+//                 \                       \                 .
+//                C X                     C X
+//
+FTPoint FTContour::ComputeOutsetPoint(FTPoint A, FTPoint B, FTPoint C)
+{
+    /* Build the rotation matrix from 'ba' vector */
+    FTPoint ba = (A - B).Normalise();
+    FTPoint bc = C - B;
+
+    /* Rotate bc to the left */
+    FTPoint tmp(bc.X() * -ba.X() + bc.Y() * -ba.Y(),
+                bc.X() * ba.Y() + bc.Y() * -ba.X());
+
+    /* Compute the vector bisecting 'abc' */
+    FTGL_DOUBLE norm = sqrt(tmp.X() * tmp.X() + tmp.Y() * tmp.Y());
+    FTGL_DOUBLE dist = 64.0 * sqrt((norm - tmp.X()) / (norm + tmp.X()));
+    tmp.X(tmp.Y() < 0.0 ? dist : -dist);
+    tmp.Y(64.0);
+
+    /* Rotate the new bc to the right */
+    return FTPoint(tmp.X() * -ba.X() + tmp.Y() * ba.Y(),
+                   tmp.X() * -ba.Y() + tmp.Y() * -ba.X());
+}
+
+
+void FTContour::SetParity(int parity)
+{
+    size_t size = PointCount();
+    FTPoint vOutset;
+
+    if(((parity & 1) && clockwise) || (!(parity & 1) && !clockwise))
+    {
+        // Contour orientation is wrong! We must reverse all points.
+        // FIXME: could it be worth writing FTVector::reverse() for this?
+        for(size_t i = 0; i < size / 2; i++)
+        {
+            FTPoint tmp = pointList[i];
+            pointList[i] = pointList[size - 1 - i];
+            pointList[size - 1 -i] = tmp;
+        }
+
+        clockwise = !clockwise;
+    }
+
+    for(size_t i = 0; i < size; i++)
+    {
+        size_t prev, cur, next;
+
+        prev = (i + size - 1) % size;
+        cur = i;
+        next = (i + size + 1) % size;
+
+        vOutset = ComputeOutsetPoint(Point(prev), Point(cur), Point(next));
+        AddOutsetPoint(vOutset);
+    }
+}
+
+
+FTContour::FTContour(FT_Vector* contour, char* tags, unsigned int n)
+{
+    FTPoint prev, cur(contour[(n - 1) % n]), next(contour[0]);
+    FTPoint a, b = next - cur;
+    double olddir, dir = atan2((next - cur).Y(), (next - cur).X());
+    double angle = 0.0;
+
+    // See http://freetype.sourceforge.net/freetype2/docs/glyphs/glyphs-6.html
+    // for a full description of FreeType tags.
+    for(unsigned int i = 0; i < n; i++)
+    {
+        prev = cur;
+        cur = next;
+        next = FTPoint(contour[(i + 1) % n]);
+        olddir = dir;
+        dir = atan2((next - cur).Y(), (next - cur).X());
+
+        // Compute our path's new direction.
+        double t = dir - olddir;
+        if(t < -M_PI) t += 2 * M_PI;
+        if(t > M_PI) t -= 2 * M_PI;
+        angle += t;
+
+        // Only process point tags we know.
+        if(n < 2 || FT_CURVE_TAG(tags[i]) == FT_Curve_Tag_On)
+        {
+            AddPoint(cur);
+        }
+        else if(FT_CURVE_TAG(tags[i]) == FT_Curve_Tag_Conic)
+        {
+            FTPoint prev2 = prev, next2 = next;
+
+            // Previous point is either the real previous point (an "on"
+            // point), or the midpoint between the current one and the
+            // previous "conic off" point.
+            if(FT_CURVE_TAG(tags[(i - 1 + n) % n]) == FT_Curve_Tag_Conic)
+            {
+                prev2 = (cur + prev) * 0.5;
+                AddPoint(prev2);
+            }
+
+            // Next point is either the real next point or the midpoint.
+            if(FT_CURVE_TAG(tags[(i + 1) % n]) == FT_Curve_Tag_Conic)
+            {
+                next2 = (cur + next) * 0.5;
+            }
+
+            evaluateQuadraticCurve(prev2, cur, next2);
+        }
+        else if(FT_CURVE_TAG(tags[i]) == FT_Curve_Tag_Cubic
+                 && FT_CURVE_TAG(tags[(i + 1) % n]) == FT_Curve_Tag_Cubic)
+        {
+            evaluateCubicCurve(prev, cur, next,
+                               FTPoint(contour[(i + 2) % n]));
+        }
+    }
+
+    // If final angle is positive (+2PI), it's an anti-clockwise contour,
+    // otherwise (-2PI) it's clockwise.
+    clockwise = (angle < 0.0);
+}
+
+
+void FTContour::buildFrontOutset(float outset)
+{
+    for(size_t i = 0; i < PointCount(); ++i)
+    {
+        AddFrontPoint(Point(i) + Outset(i) * outset);
+    }
+}
+
+
+void FTContour::buildBackOutset(float outset)
+{
+    for(size_t i = 0; i < PointCount(); ++i)
+    {
+        AddBackPoint(Point(i) + Outset(i) * outset);
+    }
+}
+
diff --git a/src/ext/ftgl/FTContour.h b/src/ext/ftgl/FTContour.h
new file mode 100644
index 0000000..4cfff6c
--- /dev/null
+++ b/src/ext/ftgl/FTContour.h
@@ -0,0 +1,209 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTContour__
+#define     __FTContour__
+
+#include "FTGL/ftgl.h"
+
+#include "FTVector.h"
+
+
+/**
+ * FTContour class is a container of points that describe a vector font
+ * outline. It is used as a container for the output of the bezier curve
+ * evaluator in FTVectoriser.
+ *
+ * @see FTOutlineGlyph
+ * @see FTPolygonGlyph
+ * @see FTPoint
+ */
+class FTContour
+{
+    public:
+        /**
+         * Constructor
+         *
+         * @param contour
+         * @param pointTags
+         * @param numberOfPoints
+         */
+        FTContour(FT_Vector* contour, char* pointTags, unsigned int numberOfPoints);
+
+        /**
+         * Destructor
+         */
+        ~FTContour()
+        {
+            pointList.clear();
+            outsetPointList.clear();
+            frontPointList.clear();
+            backPointList.clear();
+        }
+
+        /**
+         * Return a point at index.
+         *
+         * @param index of the point in the curve.
+         * @return const point reference
+         */
+        const FTPoint& Point(size_t index) const { return pointList[index]; }
+
+        /**
+         * Return a point at index.
+         *
+         * @param index of the point in the outset curve.
+         * @return const point reference
+         */
+        const FTPoint& Outset(size_t index) const { return outsetPointList[index]; }
+
+        /**
+         * Return a point at index of the front outset contour.
+         *
+         * @param index of the point in the curve.
+         * @return const point reference
+         */
+        const FTPoint& FrontPoint(size_t index) const
+        {
+            if(frontPointList.size() == 0)
+                return Point(index);
+            return frontPointList[index];
+        }
+
+
+        /**
+         * Return a point at index of the back outset contour.
+         *
+         * @param index of the point in the curve.
+         * @return const point reference
+         */
+        const FTPoint& BackPoint(size_t index) const
+        {
+            if(backPointList.size() == 0)
+                return Point(index);
+             return backPointList[index];
+        }
+
+        /**
+         * How many points define this contour
+         *
+         * @return the number of points in this contour
+         */
+        size_t PointCount() const { return pointList.size(); }
+
+        /**
+         * Make sure the glyph has the proper parity and create the front/back
+         * outset contour.
+         *
+         * @param parity  The contour's parity within the glyph.
+         */
+        void SetParity(int parity);
+
+        // FIXME: this should probably go away.
+        void buildFrontOutset(float outset);
+        void buildBackOutset(float outset);
+
+    private:
+        /**
+         * Add a point to this contour. This function tests for duplicate
+         * points.
+         *
+         * @param point The point to be added to the contour.
+         */
+        inline void AddPoint(FTPoint point);
+
+        /**
+         * Add a point to this contour. This function tests for duplicate
+         * points.
+         *
+         * @param point The point to be added to the contour.
+         */
+        inline void AddOutsetPoint(FTPoint point);
+
+        /*
+         * Add a point to this outset contour. This function tests for duplicate
+         * points.
+         *
+         * @param point The point to be added to the contour outset.
+         */
+        inline void AddFrontPoint(FTPoint point);
+        inline void AddBackPoint(FTPoint point);
+
+        /**
+         * De Casteljau (bezier) algorithm contributed by Jed Soane
+         * Evaluates a quadratic or conic (second degree) curve
+         */
+        inline void evaluateQuadraticCurve(FTPoint, FTPoint, FTPoint);
+
+        /**
+         * De Casteljau (bezier) algorithm contributed by Jed Soane
+         * Evaluates a cubic (third degree) curve
+         */
+        inline void evaluateCubicCurve(FTPoint, FTPoint, FTPoint, FTPoint);
+
+        /**
+         * Compute the vector norm
+         */
+        inline FTGL_DOUBLE NormVector(const FTPoint &v);
+
+        /**
+         * Compute a rotation matrix from a vector
+         */
+        inline void RotationMatrix(const FTPoint &a, const FTPoint &b, FTGL_DOUBLE *matRot, FTGL_DOUBLE *invRot);
+
+        /**
+         * Matrix and vector multiplication
+         */
+        inline void MultMatrixVect(FTGL_DOUBLE *mat, FTPoint &v);
+
+        /**
+         * Compute the vector bisecting from a vector 'v' and a distance 'd'
+         */
+        inline void ComputeBisec(FTPoint &v);
+
+        /**
+         * Compute the outset point coordinates
+         */
+        inline FTPoint ComputeOutsetPoint(FTPoint a, FTPoint b, FTPoint c);
+
+        /**
+         *  The list of points in this contour
+         */
+        typedef FTVector<FTPoint> PointVector;
+        PointVector pointList;
+        PointVector outsetPointList;
+        PointVector frontPointList;
+        PointVector backPointList;
+
+        /**
+         *  Is this contour clockwise or anti-clockwise?
+         */
+        bool clockwise;
+};
+
+#endif // __FTContour__
+
diff --git a/src/ext/ftgl/FTFace.cpp b/src/ext/ftgl/FTFace.cpp
new file mode 100644
index 0000000..542c521
--- /dev/null
+++ b/src/ext/ftgl/FTFace.cpp
@@ -0,0 +1,232 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTFace.h"
+#include "FTLibrary.h"
+
+#include FT_TRUETYPE_TABLES_H
+
+FTFace::FTFace(const char* fontFilePath, bool precomputeKerning)
+:   numGlyphs(0),
+    fontEncodingList(0),
+    kerningCache(0),
+    err(0)
+{
+    const FT_Long DEFAULT_FACE_INDEX = 0;
+    ftFace = new FT_Face;
+
+    err = FT_New_Face(*FTLibrary::Instance().GetLibrary(), fontFilePath,
+                      DEFAULT_FACE_INDEX, ftFace);
+    if(err)
+    {
+        delete ftFace;
+        ftFace = 0;
+        return;
+    }
+
+    numGlyphs = (*ftFace)->num_glyphs;
+    hasKerningTable = (FT_HAS_KERNING((*ftFace)) != 0);
+
+    if(hasKerningTable && precomputeKerning)
+    {
+        BuildKerningCache();
+    }
+}
+
+
+FTFace::FTFace(const unsigned char *pBufferBytes, size_t bufferSizeInBytes,
+               bool precomputeKerning)
+:   numGlyphs(0),
+    fontEncodingList(0),
+    kerningCache(0),
+    err(0)
+{
+    const FT_Long DEFAULT_FACE_INDEX = 0;
+    ftFace = new FT_Face;
+
+    err = FT_New_Memory_Face(*FTLibrary::Instance().GetLibrary(),
+                             (FT_Byte const *)pBufferBytes, (FT_Long)bufferSizeInBytes,
+                             DEFAULT_FACE_INDEX, ftFace);
+    if(err)
+    {
+        delete ftFace;
+        ftFace = 0;
+        return;
+    }
+
+    numGlyphs = (*ftFace)->num_glyphs;
+    hasKerningTable = (FT_HAS_KERNING((*ftFace)) != 0);
+
+    if(hasKerningTable && precomputeKerning)
+    {
+        BuildKerningCache();
+    }
+}
+
+
+FTFace::~FTFace()
+{
+    if(kerningCache)
+    {
+        delete[] kerningCache;
+    }
+
+    if(ftFace)
+    {
+        FT_Done_Face(*ftFace);
+        delete ftFace;
+        ftFace = 0;
+    }
+}
+
+
+bool FTFace::Attach(const char* fontFilePath)
+{
+    err = FT_Attach_File(*ftFace, fontFilePath);
+    return !err;
+}
+
+
+bool FTFace::Attach(const unsigned char *pBufferBytes,
+                    size_t bufferSizeInBytes)
+{
+    FT_Open_Args open;
+
+    open.flags = FT_OPEN_MEMORY;
+    open.memory_base = (FT_Byte const *)pBufferBytes;
+    open.memory_size = (FT_Long)bufferSizeInBytes;
+
+    err = FT_Attach_Stream(*ftFace, &open);
+    return !err;
+}
+
+
+const FTSize& FTFace::Size(const unsigned int size, const unsigned int res)
+{
+    charSize.CharSize(ftFace, size, res, res);
+    err = charSize.Error();
+
+    return charSize;
+}
+
+
+unsigned int FTFace::CharMapCount() const
+{
+    return (*ftFace)->num_charmaps;
+}
+
+
+FT_Encoding* FTFace::CharMapList()
+{
+    if(0 == fontEncodingList)
+    {
+        fontEncodingList = new FT_Encoding[CharMapCount()];
+        for(size_t i = 0; i < CharMapCount(); ++i)
+        {
+            fontEncodingList[i] = (*ftFace)->charmaps[i]->encoding;
+        }
+    }
+
+    return fontEncodingList;
+}
+
+
+FTPoint FTFace::KernAdvance(unsigned int index1, unsigned int index2)
+{
+    float x, y;
+
+    if(!hasKerningTable || !index1 || !index2)
+    {
+        return FTPoint(0.0f, 0.0f);
+    }
+
+    if(kerningCache && index1 < FTFace::MAX_PRECOMPUTED
+        && index2 < FTFace::MAX_PRECOMPUTED)
+    {
+        x = kerningCache[2 * (index2 * FTFace::MAX_PRECOMPUTED + index1)];
+        y = kerningCache[2 * (index2 * FTFace::MAX_PRECOMPUTED + index1) + 1];
+        return FTPoint(x, y);
+    }
+
+    FT_Vector kernAdvance;
+    kernAdvance.x = kernAdvance.y = 0;
+
+    err = FT_Get_Kerning(*ftFace, index1, index2, ft_kerning_unfitted,
+                         &kernAdvance);
+    if(err)
+    {
+        return FTPoint(0.0f, 0.0f);
+    }
+
+    x = static_cast<float>(kernAdvance.x) / 64.0f;
+    y = static_cast<float>(kernAdvance.y) / 64.0f;
+
+    return FTPoint(x, y);
+}
+
+
+FT_GlyphSlot FTFace::Glyph(unsigned int index, FT_Int load_flags)
+{
+    err = FT_Load_Glyph(*ftFace, index, load_flags);
+    if(err)
+    {
+        return NULL;
+    }
+
+    return (*ftFace)->glyph;
+}
+
+
+void FTFace::BuildKerningCache()
+{
+    FT_Vector kernAdvance;
+    kernAdvance.x = 0;
+    kernAdvance.y = 0;
+    kerningCache = new float[FTFace::MAX_PRECOMPUTED
+                              * FTFace::MAX_PRECOMPUTED * 2];
+    for(unsigned int j = 0; j < FTFace::MAX_PRECOMPUTED; j++)
+    {
+        for(unsigned int i = 0; i < FTFace::MAX_PRECOMPUTED; i++)
+        {
+            err = FT_Get_Kerning(*ftFace, i, j, ft_kerning_unfitted,
+                                 &kernAdvance);
+            if(err)
+            {
+                delete[] kerningCache;
+                kerningCache = NULL;
+                return;
+            }
+
+            kerningCache[2 * (j * FTFace::MAX_PRECOMPUTED + i)] =
+                                static_cast<float>(kernAdvance.x) / 64.0f;
+            kerningCache[2 * (j * FTFace::MAX_PRECOMPUTED + i) + 1] =
+                                static_cast<float>(kernAdvance.y) / 64.0f;
+        }
+    }
+}
+
diff --git a/src/ext/ftgl/FTFace.h b/src/ext/ftgl/FTFace.h
new file mode 100644
index 0000000..0e903b5
--- /dev/null
+++ b/src/ext/ftgl/FTFace.h
@@ -0,0 +1,181 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTFace__
+#define     __FTFace__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+
+#include "FTGL/ftgl.h"
+
+#include "FTSize.h"
+
+/**
+ * FTFace class provides an abstraction layer for the Freetype Face.
+ *
+ * @see "Freetype 2 Documentation"
+ *
+ */
+class FTFace
+{
+    public:
+        /**
+         * Opens and reads a face file. Error is set.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTFace(const char* fontFilePath, bool precomputeKerning = true);
+
+        /**
+         * Read face data from an in-memory buffer. Error is set.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTFace(const unsigned char *pBufferBytes, size_t bufferSizeInBytes,
+               bool precomputeKerning = true);
+
+        /**
+         * Destructor
+         *
+         * Disposes of the current Freetype Face.
+         */
+        virtual ~FTFace();
+
+        /**
+         * Attach auxilliary file to font (e.g., font metrics).
+         *
+         * @param fontFilePath  auxilliary font file path.
+         * @return          <code>true</code> if file has opened
+         *                  successfully.
+         */
+        bool Attach(const char* fontFilePath);
+
+        /**
+         * Attach auxilliary data to font (e.g., font metrics) from memory
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         * @return          <code>true</code> if file has opened
+         *                  successfully.
+         */
+        bool Attach(const unsigned char *pBufferBytes,
+                    size_t bufferSizeInBytes);
+
+        /**
+         * Get the freetype face object..
+         *
+         * @return pointer to an FT_Face.
+         */
+        FT_Face* Face() const { return ftFace; }
+
+        /**
+         * Sets the char size for the current face.
+         *
+         * This doesn't guarantee that the size was set correctly. Clients
+         * should check errors.
+         *
+         * @param size      the face size in points (1/72 inch)
+         * @param res       the resolution of the target device.
+         * @return          <code>FTSize</code> object
+         */
+        const FTSize& Size(const unsigned int size, const unsigned int res);
+
+        /**
+         * Get the number of character maps in this face.
+         *
+         * @return character map count.
+         */
+        unsigned int CharMapCount() const;
+
+        /**
+         * Get a list of character maps in this face.
+         *
+         * @return pointer to the first encoding.
+         */
+        FT_Encoding* CharMapList();
+
+        /**
+         * Gets the kerning vector between two glyphs
+         */
+        FTPoint KernAdvance(unsigned int index1, unsigned int index2);
+
+        /**
+         * Loads and creates a Freetype glyph.
+         */
+        FT_GlyphSlot Glyph(unsigned int index, FT_Int load_flags);
+
+        /**
+         * Gets the number of glyphs in the current face.
+         */
+        unsigned int GlyphCount() const { return numGlyphs; }
+
+        /**
+         * Queries for errors.
+         *
+         * @return  The current error code.
+         */
+        FT_Error Error() const { return err; }
+
+    private:
+        /**
+         * The Freetype face
+         */
+        FT_Face* ftFace;
+
+        /**
+         * The size object associated with this face
+         */
+        FTSize  charSize;
+
+        /**
+         * The number of glyphs in this face
+         */
+        int numGlyphs;
+
+        FT_Encoding* fontEncodingList;
+
+        /**
+         * This face has kerning tables
+         */
+        bool hasKerningTable;
+
+        /**
+         * If this face has kerning tables, we can cache them.
+         */
+        void BuildKerningCache();
+        static const unsigned int MAX_PRECOMPUTED = 128;
+        float *kerningCache;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+};
+
+
+#endif  //  __FTFace__
diff --git a/src/ext/ftgl/FTFont/FTBitmapFont.cpp b/src/ext/ftgl/FTFont/FTBitmapFont.cpp
new file mode 100644
index 0000000..ebf3f1e
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTBitmapFont.cpp
@@ -0,0 +1,106 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTBitmapFontImpl.h"
+
+
+//
+//  FTBitmapFont
+//
+
+
+FTBitmapFont::FTBitmapFont(char const *fontFilePath) :
+    FTFont(new FTBitmapFontImpl(this, fontFilePath))
+{}
+
+
+FTBitmapFont::FTBitmapFont(unsigned char const *pBufferBytes,
+                           size_t bufferSizeInBytes) :
+    FTFont(new FTBitmapFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTBitmapFont::~FTBitmapFont()
+{}
+
+
+FTGlyph* FTBitmapFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    return new FTBitmapGlyph(ftGlyph);
+}
+
+
+//
+//  FTBitmapFontImpl
+//
+
+
+template <typename T>
+inline FTPoint FTBitmapFontImpl::RenderI(const T* string, const int len,
+                                         FTPoint position, FTPoint spacing,
+                                         int renderMode)
+{
+    // Protect GL_BLEND
+    glPushAttrib(GL_COLOR_BUFFER_BIT);
+
+    // Protect glPixelStorei() calls (also in FTBitmapGlyphImpl::RenderImpl)
+    glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
+
+    glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
+    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+    glDisable(GL_BLEND);
+
+    FTPoint tmp = FTFontImpl::Render(string, len,
+                                     position, spacing, renderMode);
+
+    glPopClientAttrib();
+    glPopAttrib();
+
+    return tmp;
+}
+
+
+FTPoint FTBitmapFontImpl::Render(const char * string, const int len,
+                                 FTPoint position, FTPoint spacing,
+                                 int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
+
+FTPoint FTBitmapFontImpl::Render(const wchar_t * string, const int len,
+                                 FTPoint position, FTPoint spacing,
+                                 int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
diff --git a/src/ext/ftgl/FTFont/FTBitmapFontImpl.h b/src/ext/ftgl/FTFont/FTBitmapFontImpl.h
new file mode 100644
index 0000000..7f733d6
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTBitmapFontImpl.h
@@ -0,0 +1,62 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTBitmapFontImpl__
+#define __FTBitmapFontImpl__
+
+#include "FTFontImpl.h"
+
+class FTGlyph;
+
+class FTBitmapFontImpl : public FTFontImpl
+{
+    friend class FTBitmapFont;
+
+    protected:
+        FTBitmapFontImpl(FTFont *ftFont, const char* fontFilePath) :
+            FTFontImpl(ftFont, fontFilePath) {};
+
+        FTBitmapFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                         size_t bufferSizeInBytes) :
+            FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes) {};
+
+        virtual FTPoint Render(const char *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+        virtual FTPoint Render(const wchar_t *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+    private:
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline FTPoint RenderI(const T *s, const int len,
+                               FTPoint position, FTPoint spacing, int mode);
+};
+
+#endif  //  __FTBitmapFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTBufferFont.cpp b/src/ext/ftgl/FTFont/FTBufferFont.cpp
new file mode 100644
index 0000000..e48e2ab
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTBufferFont.cpp
@@ -0,0 +1,349 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <wchar.h>
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTBufferFontImpl.h"
+
+
+//
+//  FTBufferFont
+//
+
+
+FTBufferFont::FTBufferFont(char const *fontFilePath) :
+    FTFont(new FTBufferFontImpl(this, fontFilePath))
+{}
+
+
+FTBufferFont::FTBufferFont(unsigned char const *pBufferBytes,
+                           size_t bufferSizeInBytes) :
+    FTFont(new FTBufferFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTBufferFont::~FTBufferFont()
+{}
+
+
+FTGlyph* FTBufferFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    FTBufferFontImpl *myimpl = dynamic_cast<FTBufferFontImpl *>(impl);
+    if(!myimpl)
+    {
+        return NULL;
+    }
+
+    return myimpl->MakeGlyphImpl(ftGlyph);
+}
+
+
+//
+//  FTBufferFontImpl
+//
+
+
+FTBufferFontImpl::FTBufferFontImpl(FTFont *ftFont, const char* fontFilePath) :
+    FTFontImpl(ftFont, fontFilePath),
+    buffer(new FTBuffer())
+{
+    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
+
+    glGenTextures(BUFFER_CACHE_SIZE, idCache);
+
+    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
+    {
+        stringCache[i] = NULL;
+        glBindTexture(GL_TEXTURE_2D, idCache[i]);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    }
+
+    lastString = 0;
+}
+
+
+FTBufferFontImpl::FTBufferFontImpl(FTFont *ftFont,
+                                   const unsigned char *pBufferBytes,
+                                   size_t bufferSizeInBytes) :
+    FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes),
+    buffer(new FTBuffer())
+{
+    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
+
+    glGenTextures(BUFFER_CACHE_SIZE, idCache);
+
+    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
+    {
+        stringCache[i] = NULL;
+        glBindTexture(GL_TEXTURE_2D, idCache[i]);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+    }
+
+    lastString = 0;
+}
+
+
+FTBufferFontImpl::~FTBufferFontImpl()
+{
+    glDeleteTextures(BUFFER_CACHE_SIZE, idCache);
+
+    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
+    {
+        if(stringCache[i])
+        {
+            free(stringCache[i]);
+        }
+    }
+
+    delete buffer;
+}
+
+
+FTGlyph* FTBufferFontImpl::MakeGlyphImpl(FT_GlyphSlot ftGlyph)
+{
+    return new FTBufferGlyph(ftGlyph, buffer);
+}
+
+
+bool FTBufferFontImpl::FaceSize(const unsigned int size,
+                                const unsigned int res)
+{
+    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
+    {
+        if(stringCache[i])
+        {
+            free(stringCache[i]);
+            stringCache[i] = NULL;
+        }
+    }
+
+    return FTFontImpl::FaceSize(size, res);
+}
+
+
+static inline GLuint NextPowerOf2(GLuint in)
+{
+     in -= 1;
+
+     in |= in >> 16;
+     in |= in >> 8;
+     in |= in >> 4;
+     in |= in >> 2;
+     in |= in >> 1;
+
+     return in + 1;
+}
+
+
+inline int StringCompare(void const *a, char const *b, int len)
+{
+    return len < 0 ? strcmp((char const *)a, b)
+                   : strncmp((char const *)a, b, len);
+}
+
+
+inline int StringCompare(void const *a, wchar_t const *b, int len)
+{
+    return len < 0 ? wcscmp((wchar_t const *)a, b)
+                   : wcsncmp((wchar_t const *)a, b, len);
+}
+
+
+inline char *StringCopy(char const *s, int len)
+{
+    if(len < 0)
+    {
+        return strdup(s);
+    }
+    else
+    {
+#ifdef HAVE_STRNDUP
+        return strndup(s, len);
+#else
+        char *s2 = (char*)malloc(len + 1);
+        memcpy(s2, s, len);
+        s2[len] = 0;
+        return s2;
+#endif
+    }
+}
+
+
+inline wchar_t *StringCopy(wchar_t const *s, int len)
+{
+    if(len < 0)
+    {
+#if defined HAVE_WCSDUP
+        return wcsdup(s);
+#else
+        len = (int)wcslen(s);
+#endif
+    }
+
+    wchar_t *s2 = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
+    memcpy(s2, s, len * sizeof(wchar_t));
+    s2[len] = 0;
+    return s2;
+}
+
+
+template <typename T>
+inline FTPoint FTBufferFontImpl::RenderI(const T* string, const int len,
+                                         FTPoint position, FTPoint spacing,
+                                         int renderMode)
+{
+    const float padding = 3.0f;
+    int width, height, texWidth, texHeight;
+    int cacheIndex = -1;
+    bool inCache = false;
+
+    // Protect blending functions, GL_BLEND and GL_TEXTURE_2D
+    glPushAttrib(GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT);
+
+    // Protect glPixelStorei() calls
+    glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
+
+    glEnable(GL_BLEND);
+    glEnable(GL_TEXTURE_2D);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE
+
+    // Search whether the string is already in a texture we uploaded
+    for(int n = 0; n < BUFFER_CACHE_SIZE; n++)
+    {
+        int i = (lastString + n + BUFFER_CACHE_SIZE) % BUFFER_CACHE_SIZE;
+
+        if(stringCache[i] && !StringCompare(stringCache[i], string, len))
+        {
+            cacheIndex = i;
+            inCache = true;
+            break;
+        }
+    }
+
+    // If the string was not found, we need to put it in the cache and compute
+    // its new bounding box.
+    if(!inCache)
+    {
+        // FIXME: this cache is not very efficient. We should first expire
+        // strings that are not used very often.
+        cacheIndex = lastString;
+        lastString = (lastString + 1) % BUFFER_CACHE_SIZE;
+
+        if(stringCache[cacheIndex])
+        {
+            free(stringCache[cacheIndex]);
+        }
+        // FIXME: only the first N bytes are copied; we want the first N chars.
+        stringCache[cacheIndex] = StringCopy(string, len);
+        bboxCache[cacheIndex] = BBox(string, len, FTPoint(), spacing);
+    }
+
+    FTBBox bbox = bboxCache[cacheIndex];
+
+    width = static_cast<int>(bbox.Upper().X() - bbox.Lower().X()
+                              + padding + padding + 0.5);
+    height = static_cast<int>(bbox.Upper().Y() - bbox.Lower().Y()
+                               + padding + padding + 0.5);
+
+    texWidth = NextPowerOf2(width);
+    texHeight = NextPowerOf2(height);
+
+    glBindTexture(GL_TEXTURE_2D, idCache[cacheIndex]);
+
+    // If the string was not found, we need to render the text in a new
+    // texture buffer, then upload it to the OpenGL layer.
+    if(!inCache)
+    {
+        buffer->Size(texWidth, texHeight);
+        buffer->Pos(FTPoint(padding, padding) - bbox.Lower());
+
+        advanceCache[cacheIndex] =
+              FTFontImpl::Render(string, len, FTPoint(), spacing, renderMode);
+
+        glBindTexture(GL_TEXTURE_2D, idCache[cacheIndex]);
+
+        glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
+        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+        /* TODO: use glTexSubImage2D later? */
+        glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texWidth, texHeight, 0,
+                     GL_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)buffer->Pixels());
+
+        buffer->Size(0, 0);
+    }
+
+    FTPoint low = position + bbox.Lower();
+    FTPoint up = position + bbox.Upper();
+
+    glBegin(GL_QUADS);
+        glNormal3f(0.0f, 0.0f, 1.0f);
+        glTexCoord2f(padding / texWidth,
+                     (texHeight - height + padding) / texHeight);
+        glVertex2f(low.Xf(), up.Yf());
+        glTexCoord2f(padding / texWidth,
+                     (texHeight - padding) / texHeight);
+        glVertex2f(low.Xf(), low.Yf());
+        glTexCoord2f((width - padding) / texWidth,
+                     (texHeight - padding) / texHeight);
+        glVertex2f(up.Xf(), low.Yf());
+        glTexCoord2f((width - padding) / texWidth,
+                     (texHeight - height + padding) / texHeight);
+        glVertex2f(up.Xf(), up.Yf());
+    glEnd();
+
+    glPopClientAttrib();
+    glPopAttrib();
+
+    return position + advanceCache[cacheIndex];
+}
+
+
+FTPoint FTBufferFontImpl::Render(const char * string, const int len,
+                                 FTPoint position, FTPoint spacing,
+                                 int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
+
+FTPoint FTBufferFontImpl::Render(const wchar_t * string, const int len,
+                                 FTPoint position, FTPoint spacing,
+                                 int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
diff --git a/src/ext/ftgl/FTFont/FTBufferFontImpl.h b/src/ext/ftgl/FTFont/FTBufferFontImpl.h
new file mode 100644
index 0000000..15557f6
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTBufferFontImpl.h
@@ -0,0 +1,81 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTBufferFontImpl__
+#define __FTBufferFontImpl__
+
+#include "FTFontImpl.h"
+
+class FTGlyph;
+class FTBuffer;
+
+class FTBufferFontImpl : public FTFontImpl
+{
+    friend class FTBufferFont;
+
+    protected:
+        FTBufferFontImpl(FTFont *ftFont, const char* fontFilePath);
+
+        FTBufferFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                         size_t bufferSizeInBytes);
+
+        virtual ~FTBufferFontImpl();
+
+        virtual FTPoint Render(const char *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+        virtual FTPoint Render(const wchar_t *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+        virtual bool FaceSize(const unsigned int size,
+                              const unsigned int res);
+
+    private:
+        /**
+         * Create an FTBufferGlyph object for the base class.
+         */
+        FTGlyph* MakeGlyphImpl(FT_GlyphSlot ftGlyph);
+
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline FTPoint RenderI(const T *s, const int len,
+                               FTPoint position, FTPoint spacing, int mode);
+
+        /* Pixel buffer */
+        FTBuffer *buffer;
+
+        static const int BUFFER_CACHE_SIZE = 16;
+        /* Texture IDs */
+        GLuint idCache[BUFFER_CACHE_SIZE];
+        void *stringCache[BUFFER_CACHE_SIZE];
+        FTBBox bboxCache[BUFFER_CACHE_SIZE];
+        FTPoint advanceCache[BUFFER_CACHE_SIZE];
+        int lastString;
+};
+
+#endif  //  __FTBufferFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTExtrudeFont.cpp b/src/ext/ftgl/FTFont/FTExtrudeFont.cpp
new file mode 100644
index 0000000..9e8eb72
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTExtrudeFont.cpp
@@ -0,0 +1,89 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTExtrudeFontImpl.h"
+
+
+//
+//  FTExtrudeFont
+//
+
+
+FTExtrudeFont::FTExtrudeFont(char const *fontFilePath) :
+    FTFont(new FTExtrudeFontImpl(this, fontFilePath))
+{}
+
+
+FTExtrudeFont::FTExtrudeFont(const unsigned char *pBufferBytes,
+                             size_t bufferSizeInBytes) :
+    FTFont(new FTExtrudeFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTExtrudeFont::~FTExtrudeFont()
+{}
+
+
+FTGlyph* FTExtrudeFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    FTExtrudeFontImpl *myimpl = dynamic_cast<FTExtrudeFontImpl *>(impl);
+    if(!myimpl)
+    {
+        return NULL;
+    }
+
+    return new FTExtrudeGlyph(ftGlyph, myimpl->depth, myimpl->front,
+                              myimpl->back, myimpl->useDisplayLists);
+}
+
+
+//
+//  FTExtrudeFontImpl
+//
+
+
+FTExtrudeFontImpl::FTExtrudeFontImpl(FTFont *ftFont, const char* fontFilePath)
+: FTFontImpl(ftFont, fontFilePath),
+  depth(0.0f), front(0.0f), back(0.0f)
+{
+    load_flags = FT_LOAD_NO_HINTING;
+}
+
+
+FTExtrudeFontImpl::FTExtrudeFontImpl(FTFont *ftFont,
+                                     const unsigned char *pBufferBytes,
+                                     size_t bufferSizeInBytes)
+: FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes),
+  depth(0.0f), front(0.0f), back(0.0f)
+{
+    load_flags = FT_LOAD_NO_HINTING;
+}
+
diff --git a/src/ext/ftgl/FTFont/FTExtrudeFontImpl.h b/src/ext/ftgl/FTFont/FTExtrudeFontImpl.h
new file mode 100644
index 0000000..c2ddf27
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTExtrudeFontImpl.h
@@ -0,0 +1,81 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTExtrudeFontImpl__
+#define __FTExtrudeFontImpl__
+
+#include "FTFontImpl.h"
+
+class FTGlyph;
+
+class FTExtrudeFontImpl : public FTFontImpl
+{
+    friend class FTExtrudeFont;
+
+    protected:
+        FTExtrudeFontImpl(FTFont *ftFont, const char* fontFilePath);
+
+        FTExtrudeFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                          size_t bufferSizeInBytes);
+
+        /**
+         * Set the extrusion distance for the font.
+         *
+         * @param d  The extrusion distance.
+         */
+        virtual void Depth(float d) { depth = d; }
+
+        /**
+         * Set the outset distance for the font. Only implemented by
+         * FTOutlineFont, FTPolygonFont and FTExtrudeFont
+         *
+         * @param o  The outset distance.
+         */
+        virtual void Outset(float o) { front = back = o; }
+
+        /**
+         * Set the outset distance for the font. Only implemented by
+         * FTExtrudeFont
+         *
+         * @param f  The front outset distance.
+         * @param b  The back outset distance.
+         */
+        virtual void Outset(float f, float b) { front = f; back = b; }
+
+    private:
+        /**
+         * The extrusion distance for the font.
+         */
+        float depth;
+
+        /**
+         * The outset distance (front and back) for the font.
+         */
+        float front, back;
+};
+
+#endif // __FTExtrudeFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTFont.cpp b/src/ext/ftgl/FTFont/FTFont.cpp
new file mode 100644
index 0000000..a7206fb
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTFont.cpp
@@ -0,0 +1,552 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTInternals.h"
+#include "FTUnicode.h"
+
+#include "FTFontImpl.h"
+
+#include "FTBitmapFontImpl.h"
+#include "FTExtrudeFontImpl.h"
+#include "FTOutlineFontImpl.h"
+#include "FTPixmapFontImpl.h"
+#include "FTPolygonFontImpl.h"
+#include "FTTextureFontImpl.h"
+
+#include "FTGlyphContainer.h"
+#include "FTFace.h"
+
+
+//
+//  FTFont
+//
+
+
+FTFont::FTFont(char const *fontFilePath)
+{
+    impl = new FTFontImpl(this, fontFilePath);
+}
+
+
+FTFont::FTFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
+{
+    impl = new FTFontImpl(this, pBufferBytes, bufferSizeInBytes);
+}
+
+
+FTFont::FTFont(FTFontImpl *pImpl)
+{
+    impl = pImpl;
+}
+
+
+FTFont::~FTFont()
+{
+    delete impl;
+}
+
+
+bool FTFont::Attach(const char* fontFilePath)
+{
+    return impl->Attach(fontFilePath);
+}
+
+
+bool FTFont::Attach(const unsigned char *pBufferBytes, size_t bufferSizeInBytes)
+{
+    return impl->Attach(pBufferBytes, bufferSizeInBytes);
+}
+
+
+bool FTFont::FaceSize(const unsigned int size, const unsigned int res)
+{
+    return impl->FaceSize(size, res);
+}
+
+
+unsigned int FTFont::FaceSize() const
+{
+    return impl->FaceSize();
+}
+
+
+void FTFont::Depth(float depth)
+{
+    return impl->Depth(depth);
+}
+
+
+void FTFont::Outset(float outset)
+{
+    return impl->Outset(outset);
+}
+
+
+void FTFont::Outset(float front, float back)
+{
+    return impl->Outset(front, back);
+}
+
+
+void FTFont::GlyphLoadFlags(FT_Int flags)
+{
+    return impl->GlyphLoadFlags(flags);
+}
+
+
+bool FTFont::CharMap(FT_Encoding encoding)
+{
+    return impl->CharMap(encoding);
+}
+
+
+unsigned int FTFont::CharMapCount() const
+{
+    return impl->CharMapCount();
+}
+
+
+FT_Encoding* FTFont::CharMapList()
+{
+    return impl->CharMapList();
+}
+
+
+void FTFont::UseDisplayList(bool useList)
+{
+    return impl->UseDisplayList(useList);
+}
+
+
+float FTFont::Ascender() const
+{
+    return impl->Ascender();
+}
+
+
+float FTFont::Descender() const
+{
+    return impl->Descender();
+}
+
+
+float FTFont::LineHeight() const
+{
+    return impl->LineHeight();
+}
+
+
+FTPoint FTFont::Render(const char * string, const int len,
+                       FTPoint position, FTPoint spacing, int renderMode)
+{
+    return impl->Render(string, len, position, spacing, renderMode);
+}
+
+
+FTPoint FTFont::Render(const wchar_t * string, const int len,
+                       FTPoint position, FTPoint spacing, int renderMode)
+{
+    return impl->Render(string, len, position, spacing, renderMode);
+}
+
+
+float FTFont::Advance(const char * string, const int len, FTPoint spacing)
+{
+    return impl->Advance(string, len, spacing);
+}
+
+
+float FTFont::Advance(const wchar_t * string, const int len, FTPoint spacing)
+{
+    return impl->Advance(string, len, spacing);
+}
+
+
+FTBBox FTFont::BBox(const char *string, const int len,
+                    FTPoint position, FTPoint spacing)
+{
+    return impl->BBox(string, len, position, spacing);
+}
+
+
+FTBBox FTFont::BBox(const wchar_t *string, const int len,
+                    FTPoint position, FTPoint spacing)
+{
+    return impl->BBox(string, len, position, spacing);
+}
+
+
+FT_Error FTFont::Error() const
+{
+    return impl->err;
+}
+
+
+//
+//  FTFontImpl
+//
+
+
+FTFontImpl::FTFontImpl(FTFont *ftFont, char const *fontFilePath) :
+    face(fontFilePath),
+    useDisplayLists(true),
+    load_flags(FT_LOAD_DEFAULT),
+    intf(ftFont),
+    glyphList(0)
+{
+    err = face.Error();
+    if(err == 0)
+    {
+        glyphList = new FTGlyphContainer(&face);
+    }
+}
+
+
+FTFontImpl::FTFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                       size_t bufferSizeInBytes) :
+    face(pBufferBytes, bufferSizeInBytes),
+    useDisplayLists(true),
+    load_flags(FT_LOAD_DEFAULT),
+    intf(ftFont),
+    glyphList(0)
+{
+    err = face.Error();
+    if(err == 0)
+    {
+        glyphList = new FTGlyphContainer(&face);
+    }
+}
+
+
+FTFontImpl::~FTFontImpl()
+{
+    if(glyphList)
+    {
+        delete glyphList;
+    }
+}
+
+
+bool FTFontImpl::Attach(const char* fontFilePath)
+{
+    if(!face.Attach(fontFilePath))
+    {
+        err = face.Error();
+        return false;
+    }
+
+    err = 0;
+    return true;
+}
+
+
+bool FTFontImpl::Attach(const unsigned char *pBufferBytes,
+                        size_t bufferSizeInBytes)
+{
+    if(!face.Attach(pBufferBytes, bufferSizeInBytes))
+    {
+        err = face.Error();
+        return false;
+    }
+
+    err = 0;
+    return true;
+}
+
+
+bool FTFontImpl::FaceSize(const unsigned int size, const unsigned int res)
+{
+    if(glyphList != NULL)
+    {
+        delete glyphList;
+        glyphList = NULL;
+    }
+
+    charSize = face.Size(size, res);
+    err = face.Error();
+
+    if(err != 0)
+    {
+        return false;
+    }
+
+    glyphList = new FTGlyphContainer(&face);
+    return true;
+}
+
+
+unsigned int FTFontImpl::FaceSize() const
+{
+    return charSize.CharSize();
+}
+
+
+void FTFontImpl::Depth(float depth)
+{
+    ;
+}
+
+
+void FTFontImpl::Outset(float outset)
+{
+    ;
+}
+
+
+void FTFontImpl::Outset(float front, float back)
+{
+    ;
+}
+
+
+void FTFontImpl::GlyphLoadFlags(FT_Int flags)
+{
+    load_flags = flags;
+}
+
+
+bool FTFontImpl::CharMap(FT_Encoding encoding)
+{
+    bool result = glyphList->CharMap(encoding);
+    err = glyphList->Error();
+    return result;
+}
+
+
+unsigned int FTFontImpl::CharMapCount() const
+{
+    return face.CharMapCount();
+}
+
+
+FT_Encoding* FTFontImpl::CharMapList()
+{
+    return face.CharMapList();
+}
+
+
+void FTFontImpl::UseDisplayList(bool useList)
+{
+    useDisplayLists = useList;
+}
+
+
+float FTFontImpl::Ascender() const
+{
+    return charSize.Ascender();
+}
+
+
+float FTFontImpl::Descender() const
+{
+    return charSize.Descender();
+}
+
+
+float FTFontImpl::LineHeight() const
+{
+    return charSize.Height();
+}
+
+
+template <typename T>
+inline FTBBox FTFontImpl::BBoxI(const T* string, const int len,
+                                FTPoint position, FTPoint spacing)
+{
+    FTBBox totalBBox;
+
+    /* Only compute the bounds if string is non-empty. */
+    if(string && ('\0' != string[0]))
+    {
+        // for multibyte - we can't rely on sizeof(T) == character
+        FTUnicodeStringItr<T> ustr(string);
+        unsigned int thisChar = *ustr++;
+        unsigned int nextChar = *ustr;
+
+        if(CheckGlyph(thisChar))
+        {
+            totalBBox = glyphList->BBox(thisChar);
+            totalBBox += position;
+
+            position += FTPoint(glyphList->Advance(thisChar, nextChar), 0.0);
+        }
+
+        /* Expand totalBox by each glyph in string */
+        for(int i = 1; (len < 0 && *ustr) || (len >= 0 && i < len); i++)
+        {
+            thisChar = *ustr++;
+            nextChar = *ustr;
+
+            if(CheckGlyph(thisChar))
+            {
+                position += spacing;
+
+                FTBBox tempBBox = glyphList->BBox(thisChar);
+                tempBBox += position;
+                totalBBox |= tempBBox;
+
+                position += FTPoint(glyphList->Advance(thisChar, nextChar),
+                                    0.0);
+            }
+        }
+    }
+
+    return totalBBox;
+}
+
+
+FTBBox FTFontImpl::BBox(const char *string, const int len,
+                        FTPoint position, FTPoint spacing)
+{
+    /* The chars need to be unsigned because they are cast to int later */
+    return BBoxI((const unsigned char *)string, len, position, spacing);
+}
+
+
+FTBBox FTFontImpl::BBox(const wchar_t *string, const int len,
+                        FTPoint position, FTPoint spacing)
+{
+    return BBoxI(string, len, position, spacing);
+}
+
+
+template <typename T>
+inline float FTFontImpl::AdvanceI(const T* string, const int len,
+                                  FTPoint spacing)
+{
+    float advance = 0.0f;
+    FTUnicodeStringItr<T> ustr(string);
+
+    for(int i = 0; (len < 0 && *ustr) || (len >= 0 && i < len); i++)
+    {
+        unsigned int thisChar = *ustr++;
+        unsigned int nextChar = *ustr;
+
+        if(CheckGlyph(thisChar))
+        {
+            advance += glyphList->Advance(thisChar, nextChar);
+        }
+
+        if(nextChar)
+        {
+            advance += spacing.Xf();
+        }
+    }
+
+    return advance;
+}
+
+
+float FTFontImpl::Advance(const char* string, const int len, FTPoint spacing)
+{
+    /* The chars need to be unsigned because they are cast to int later */
+    return AdvanceI((const unsigned char *)string, len, spacing);
+}
+
+
+float FTFontImpl::Advance(const wchar_t* string, const int len, FTPoint spacing)
+{
+    return AdvanceI(string, len, spacing);
+}
+
+
+template <typename T>
+inline FTPoint FTFontImpl::RenderI(const T* string, const int len,
+                                   FTPoint position, FTPoint spacing,
+                                   int renderMode)
+{
+    // for multibyte - we can't rely on sizeof(T) == character
+    FTUnicodeStringItr<T> ustr(string);
+
+    for(int i = 0; (len < 0 && *ustr) || (len >= 0 && i < len); i++)
+    {
+        unsigned int thisChar = *ustr++;
+        unsigned int nextChar = *ustr;
+
+        if(CheckGlyph(thisChar))
+        {
+            position += glyphList->Render(thisChar, nextChar,
+                                          position, renderMode);
+        }
+
+        if(nextChar)
+        {
+            position += spacing;
+        }
+    }
+
+    return position;
+}
+
+
+FTPoint FTFontImpl::Render(const char * string, const int len,
+                           FTPoint position, FTPoint spacing, int renderMode)
+{
+    return RenderI((const unsigned char *)string,
+                   len, position, spacing, renderMode);
+}
+
+
+FTPoint FTFontImpl::Render(const wchar_t * string, const int len,
+                           FTPoint position, FTPoint spacing, int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
+
+bool FTFontImpl::CheckGlyph(const unsigned int characterCode)
+{
+    if(glyphList->Glyph(characterCode))
+    {
+        return true;
+    }
+
+    unsigned int glyphIndex = glyphList->FontIndex(characterCode);
+    FT_GlyphSlot ftSlot = face.Glyph(glyphIndex, load_flags);
+    if(!ftSlot)
+    {
+        err = face.Error();
+        return false;
+    }
+
+    FTGlyph* tempGlyph = intf->MakeGlyph(ftSlot);
+    if(!tempGlyph)
+    {
+        if(0 == err)
+        {
+            err = 0x13;
+        }
+
+        return false;
+    }
+
+    glyphList->Add(tempGlyph, characterCode);
+
+    return true;
+}
+
diff --git a/src/ext/ftgl/FTFont/FTFontGlue.cpp b/src/ext/ftgl/FTFont/FTFontGlue.cpp
new file mode 100644
index 0000000..b23e787
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTFontGlue.cpp
@@ -0,0 +1,227 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTInternals.h"
+
+static const FTPoint static_ftpoint;
+static const FTBBox static_ftbbox;
+
+FTGL_BEGIN_C_DECLS
+
+#define C_TOR(cname, cargs, cxxname, cxxarg, cxxtype) \
+    FTGLfont* cname cargs \
+    { \
+        cxxname *f = new cxxname cxxarg; \
+        if(f->Error()) \
+        { \
+            delete f; \
+            return NULL; \
+        } \
+        FTGLfont *ftgl = (FTGLfont *)malloc(sizeof(FTGLfont)); \
+        ftgl->ptr = f; \
+        ftgl->type = cxxtype; \
+        return ftgl; \
+    }
+
+// FTBitmapFont::FTBitmapFont();
+C_TOR(ftglCreateBitmapFont, (const char *fontname),
+      FTBitmapFont, (fontname), FONT_BITMAP);
+
+// FTBufferFont::FTBufferFont();
+C_TOR(ftglCreateBufferFont, (const char *fontname),
+      FTBufferFont, (fontname), FONT_BUFFER);
+
+// FTExtrudeFont::FTExtrudeFont();
+C_TOR(ftglCreateExtrudeFont, (const char *fontname),
+      FTExtrudeFont, (fontname), FONT_EXTRUDE);
+
+// FTOutlineFont::FTOutlineFont();
+C_TOR(ftglCreateOutlineFont, (const char *fontname),
+      FTOutlineFont, (fontname), FONT_OUTLINE);
+
+// FTPixmapFont::FTPixmapFont();
+C_TOR(ftglCreatePixmapFont, (const char *fontname),
+      FTPixmapFont, (fontname), FONT_PIXMAP);
+
+// FTPolygonFont::FTPolygonFont();
+C_TOR(ftglCreatePolygonFont, (const char *fontname),
+      FTPolygonFont, (fontname), FONT_POLYGON);
+
+// FTTextureFont::FTTextureFont();
+C_TOR(ftglCreateTextureFont, (const char *fontname),
+      FTTextureFont, (fontname), FONT_TEXTURE);
+
+// FTCustomFont::FTCustomFont();
+class FTCustomFont : public FTFont
+{
+public:
+    FTCustomFont(char const *fontFilePath, void *p,
+                 FTGLglyph * (*makeglyph) (FT_GlyphSlot, void *))
+     : FTFont(fontFilePath),
+       data(p),
+       makeglyphCallback(makeglyph)
+    {}
+
+    ~FTCustomFont()
+    {}
+
+    FTGlyph* MakeGlyph(FT_GlyphSlot slot)
+    {
+        FTGLglyph *g = makeglyphCallback(slot, data);
+        FTGlyph *glyph = g->ptr;
+        // XXX: we no longer need g, and no one will free it for us. Not
+        // very elegant, and we need to make sure no one else will try to
+        // use it.
+        free(g);
+        return glyph;
+    }
+
+private:
+    void *data;
+    FTGLglyph *(*makeglyphCallback) (FT_GlyphSlot, void *);
+};
+
+C_TOR(ftglCreateCustomFont, (char const *fontFilePath, void *data,
+                   FTGLglyph * (*makeglyphCallback) (FT_GlyphSlot, void *)),
+      FTCustomFont, (fontFilePath, data, makeglyphCallback), FONT_CUSTOM);
+
+#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \
+    cret cname cargs \
+    { \
+        if(!f || !f->ptr) \
+        { \
+            fprintf(stderr, "FTGL warning: NULL pointer in %s\n", #cname); \
+            cxxerr; \
+        } \
+        return f->ptr->cxxname cxxarg; \
+    }
+
+// FTFont::~FTFont();
+void ftglDestroyFont(FTGLfont *f)
+{
+    if(!f || !f->ptr)
+    {
+        fprintf(stderr, "FTGL warning: NULL pointer in %s\n", __FUNCTION__);
+        return;
+    }
+    delete f->ptr;
+    free(f);
+}
+
+// bool FTFont::Attach(const char* fontFilePath);
+C_FUN(int, ftglAttachFile, (FTGLfont *f, const char* path),
+      return 0, Attach, (path));
+
+// bool FTFont::Attach(const unsigned char *pBufferBytes,
+//                     size_t bufferSizeInBytes);
+C_FUN(int, ftglAttachData, (FTGLfont *f, const unsigned char *p, size_t s),
+      return 0, Attach, (p, s));
+
+// void FTFont::GlyphLoadFlags(FT_Int flags);
+C_FUN(void, ftglSetFontGlyphLoadFlags, (FTGLfont *f, FT_Int flags),
+      return, GlyphLoadFlags, (flags));
+
+// bool FTFont::CharMap(FT_Encoding encoding);
+C_FUN(int, ftglSetFontCharMap, (FTGLfont *f, FT_Encoding enc),
+      return 0, CharMap, (enc));
+
+// unsigned int FTFont::CharMapCount();
+C_FUN(unsigned int, ftglGetFontCharMapCount, (FTGLfont *f),
+      return 0, CharMapCount, ());
+
+// FT_Encoding* FTFont::CharMapList();
+C_FUN(FT_Encoding *, ftglGetFontCharMapList, (FTGLfont* f),
+      return NULL, CharMapList, ());
+
+// virtual bool FTFont::FaceSize(const unsigned int size,
+//                               const unsigned int res = 72);
+C_FUN(int, ftglSetFontFaceSize, (FTGLfont *f, unsigned int s, unsigned int r),
+      return 0, FaceSize, (s, r > 0 ? r : 72));
+
+// unsigned int FTFont::FaceSize() const;
+// XXX: need to call FaceSize() as FTFont::FaceSize() because of FTGLTexture
+C_FUN(unsigned int, ftglGetFontFaceSize, (FTGLfont *f),
+      return 0, FTFont::FaceSize, ());
+
+// virtual void FTFont::Depth(float depth);
+C_FUN(void, ftglSetFontDepth, (FTGLfont *f, float d), return, Depth, (d));
+
+// virtual void FTFont::Outset(float front, float back);
+C_FUN(void, ftglSetFontOutset, (FTGLfont *f, float front, float back),
+      return, FTFont::Outset, (front, back));
+
+// void FTFont::UseDisplayList(bool useList);
+C_FUN(void, ftglSetFontDisplayList, (FTGLfont *f, int l),
+      return, UseDisplayList, (l != 0));
+
+// float FTFont::Ascender() const;
+C_FUN(float, ftglGetFontAscender, (FTGLfont *f), return 0.f, Ascender, ());
+
+// float FTFont::Descender() const;
+C_FUN(float, ftglGetFontDescender, (FTGLfont *f), return 0.f, Descender, ());
+
+// float FTFont::LineHeight() const;
+C_FUN(float, ftglGetFontLineHeight, (FTGLfont *f), return 0.f, LineHeight, ());
+
+// void FTFont::BBox(const char* string, float& llx, float& lly, float& llz,
+//                   float& urx, float& ury, float& urz);
+extern "C++" {
+C_FUN(static FTBBox, _ftglGetFontBBox, (FTGLfont *f, char const *s, int len),
+      return static_ftbbox, BBox, (s, len));
+}
+
+void ftglGetFontBBox(FTGLfont *f, const char* s, int len, float c[6])
+{
+    FTBBox ret = _ftglGetFontBBox(f, s, len);
+    FTPoint lower = ret.Lower(), upper = ret.Upper();
+    c[0] = lower.Xf(); c[1] = lower.Yf(); c[2] = lower.Zf();
+    c[3] = upper.Xf(); c[4] = upper.Yf(); c[5] = upper.Zf();
+}
+
+// float FTFont::Advance(const char* string);
+C_FUN(float, ftglGetFontAdvance, (FTGLfont *f, char const *s),
+      return 0.0, Advance, (s));
+
+// virtual void Render(const char* string, int renderMode);
+extern "C++" {
+C_FUN(static FTPoint, _ftglRenderFont, (FTGLfont *f, char const *s, int len,
+                                        FTPoint pos, FTPoint spacing, int mode),
+      return static_ftpoint, Render, (s, len, pos, spacing, mode));
+}
+
+void ftglRenderFont(FTGLfont *f, const char *s, int mode)
+{
+    _ftglRenderFont(f, s, -1, FTPoint(), FTPoint(), mode);
+}
+
+// FT_Error FTFont::Error() const;
+C_FUN(FT_Error, ftglGetFontError, (FTGLfont *f), return -1, Error, ());
+
+FTGL_END_C_DECLS
+
diff --git a/src/ext/ftgl/FTFont/FTFontImpl.h b/src/ext/ftgl/FTFont/FTFontImpl.h
new file mode 100644
index 0000000..36c3bf8
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTFontImpl.h
@@ -0,0 +1,162 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTFontImpl__
+#define __FTFontImpl__
+
+#include "FTGL/ftgl.h"
+
+#include "FTFace.h"
+
+class FTGlyphContainer;
+class FTGlyph;
+
+class FTFontImpl
+{
+        friend class FTFont;
+
+    protected:
+        FTFontImpl(FTFont *ftFont, char const *fontFilePath);
+
+        FTFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                   size_t bufferSizeInBytes);
+
+        virtual ~FTFontImpl();
+
+        virtual bool Attach(const char* fontFilePath);
+
+        virtual bool Attach(const unsigned char *pBufferBytes,
+                            size_t bufferSizeInBytes);
+
+        virtual void GlyphLoadFlags(FT_Int flags);
+
+        virtual bool CharMap(FT_Encoding encoding);
+
+        virtual unsigned int CharMapCount() const;
+
+        virtual FT_Encoding* CharMapList();
+
+        virtual void UseDisplayList(bool useList);
+
+        virtual float Ascender() const;
+
+        virtual float Descender() const;
+
+        virtual float LineHeight() const;
+
+        virtual bool FaceSize(const unsigned int size,
+                              const unsigned int res);
+
+        virtual unsigned int FaceSize() const;
+
+        virtual void Depth(float depth);
+
+        virtual void Outset(float outset);
+
+        virtual void Outset(float front, float back);
+
+        virtual FTBBox BBox(const char *s, const int len, FTPoint, FTPoint);
+
+        virtual FTBBox BBox(const wchar_t *s, const int len, FTPoint, FTPoint);
+
+        virtual float Advance(const char *s, const int len, FTPoint);
+
+        virtual float Advance(const wchar_t *s, const int len, FTPoint);
+
+        virtual FTPoint Render(const char *s, const int len,
+                               FTPoint, FTPoint, int);
+
+        virtual FTPoint Render(const wchar_t *s, const int len,
+                               FTPoint, FTPoint, int);
+
+        /**
+         * Current face object
+         */
+        FTFace face;
+
+        /**
+         * Current size object
+         */
+        FTSize charSize;
+
+        /**
+         * Flag to enable or disable the use of Display Lists inside FTGL
+         * <code>true</code> turns ON display lists.
+         * <code>false</code> turns OFF display lists.
+         */
+        bool useDisplayLists;
+
+        /**
+         * The default glyph loading flags.
+         */
+        FT_Int load_flags;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+
+    private:
+        /**
+         * A link back to the interface of which we are the implementation.
+         */
+        FTFont *intf;
+
+        /**
+         * Check that the glyph at <code>chr</code> exist. If not load it.
+         *
+         * @param chr  character index
+         * @return <code>true</code> if the glyph can be created.
+         */
+        bool CheckGlyph(const unsigned int chr);
+
+        /**
+         * An object that holds a list of glyphs
+         */
+        FTGlyphContainer* glyphList;
+
+        /**
+         * Current pen or cursor position;
+         */
+        FTPoint pen;
+
+        /* Internal generic BBox() implementation */
+        template <typename T>
+        inline FTBBox BBoxI(const T *s, const int len,
+                            FTPoint position, FTPoint spacing);
+
+        /* Internal generic Advance() implementation */
+        template <typename T>
+        inline float AdvanceI(const T *s, const int len, FTPoint spacing);
+
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline FTPoint RenderI(const T *s, const int len,
+                               FTPoint position, FTPoint spacing, int mode);
+};
+
+#endif  //  __FTFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTOutlineFont.cpp b/src/ext/ftgl/FTFont/FTOutlineFont.cpp
new file mode 100644
index 0000000..9ebc9a0
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTOutlineFont.cpp
@@ -0,0 +1,129 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTOutlineFontImpl.h"
+
+
+//
+//  FTOutlineFont
+//
+
+
+FTOutlineFont::FTOutlineFont(char const *fontFilePath) :
+    FTFont(new FTOutlineFontImpl(this, fontFilePath))
+{}
+
+
+FTOutlineFont::FTOutlineFont(const unsigned char *pBufferBytes,
+                             size_t bufferSizeInBytes) :
+    FTFont(new FTOutlineFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTOutlineFont::~FTOutlineFont()
+{}
+
+
+FTGlyph* FTOutlineFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    FTOutlineFontImpl *myimpl = dynamic_cast<FTOutlineFontImpl *>(impl);
+    if(!myimpl)
+    {
+        return NULL;
+    }
+
+    return new FTOutlineGlyph(ftGlyph, myimpl->outset,
+                              myimpl->useDisplayLists);
+}
+
+
+//
+//  FTOutlineFontImpl
+//
+
+
+FTOutlineFontImpl::FTOutlineFontImpl(FTFont *ftFont, const char* fontFilePath)
+: FTFontImpl(ftFont, fontFilePath),
+  outset(0.0f)
+{
+    load_flags = FT_LOAD_NO_HINTING;
+}
+
+
+FTOutlineFontImpl::FTOutlineFontImpl(FTFont *ftFont,
+                                     const unsigned char *pBufferBytes,
+                                     size_t bufferSizeInBytes)
+: FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes),
+  outset(0.0f)
+{
+    load_flags = FT_LOAD_NO_HINTING;
+}
+
+
+template <typename T>
+inline FTPoint FTOutlineFontImpl::RenderI(const T* string, const int len,
+                                          FTPoint position, FTPoint spacing,
+                                          int renderMode)
+{
+    // Protect GL_TEXTURE_2D, glHint(), GL_LINE_SMOOTH and blending functions
+    glPushAttrib(GL_ENABLE_BIT | GL_HINT_BIT | GL_LINE_BIT
+                  | GL_COLOR_BUFFER_BIT);
+
+    glDisable(GL_TEXTURE_2D);
+    glEnable(GL_LINE_SMOOTH);
+    glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
+    glEnable(GL_BLEND);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE
+
+    FTPoint tmp = FTFontImpl::Render(string, len,
+                                     position, spacing, renderMode);
+
+    glPopAttrib();
+
+    return tmp;
+}
+
+
+FTPoint FTOutlineFontImpl::Render(const char * string, const int len,
+                                  FTPoint position, FTPoint spacing,
+                                  int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
+
+FTPoint FTOutlineFontImpl::Render(const wchar_t * string, const int len,
+                                  FTPoint position, FTPoint spacing,
+                                  int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
diff --git a/src/ext/ftgl/FTFont/FTOutlineFontImpl.h b/src/ext/ftgl/FTFont/FTOutlineFontImpl.h
new file mode 100644
index 0000000..38b4d26
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTOutlineFontImpl.h
@@ -0,0 +1,73 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTOutlineFontImpl__
+#define __FTOutlineFontImpl__
+
+#include "FTFontImpl.h"
+
+class FTGlyph;
+
+class FTOutlineFontImpl : public FTFontImpl
+{
+    friend class FTOutlineFont;
+
+    protected:
+        FTOutlineFontImpl(FTFont *ftFont, const char* fontFilePath);
+
+        FTOutlineFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                          size_t bufferSizeInBytes);
+
+        /**
+         * Set the outset distance for the font. Only implemented by
+         * FTOutlineFont, FTPolygonFont and FTExtrudeFont
+         *
+         * @param outset  The outset distance.
+         */
+        virtual void Outset(float o) { outset = o; }
+
+        virtual FTPoint Render(const char *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+        virtual FTPoint Render(const wchar_t *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+    private:
+        /**
+         * The outset distance for the font.
+         */
+        float outset;
+
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline FTPoint RenderI(const T *s, const int len,
+                               FTPoint position, FTPoint spacing, int mode);
+};
+
+#endif // __FTOutlineFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTPixmapFont.cpp b/src/ext/ftgl/FTFont/FTPixmapFont.cpp
new file mode 100644
index 0000000..6296a3b
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTPixmapFont.cpp
@@ -0,0 +1,135 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTPixmapFontImpl.h"
+
+
+//
+//  FTPixmapFont
+//
+
+
+FTPixmapFont::FTPixmapFont(char const *fontFilePath) :
+    FTFont(new FTPixmapFontImpl(this, fontFilePath))
+{}
+
+
+FTPixmapFont::FTPixmapFont(const unsigned char *pBufferBytes,
+                           size_t bufferSizeInBytes) :
+    FTFont(new FTPixmapFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTPixmapFont::~FTPixmapFont()
+{}
+
+
+FTGlyph* FTPixmapFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    return new FTPixmapGlyph(ftGlyph);
+}
+
+
+//
+//  FTPixmapFontImpl
+//
+
+
+FTPixmapFontImpl::FTPixmapFontImpl(FTFont *ftFont, const char* fontFilePath)
+: FTFontImpl(ftFont, fontFilePath)
+{
+    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
+}
+
+
+FTPixmapFontImpl::FTPixmapFontImpl(FTFont *ftFont,
+                                   const unsigned char *pBufferBytes,
+                                   size_t bufferSizeInBytes)
+: FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes)
+{
+    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
+}
+
+
+template <typename T>
+inline FTPoint FTPixmapFontImpl::RenderI(const T* string, const int len,
+                                         FTPoint position, FTPoint spacing,
+                                         int renderMode)
+{
+    // Protect GL_TEXTURE_2D and GL_BLEND, glPixelTransferf(), and blending
+    // functions.
+    glPushAttrib(GL_ENABLE_BIT | GL_PIXEL_MODE_BIT | GL_COLOR_BUFFER_BIT
+               | GL_POLYGON_BIT);
+    
+    // Protect glPixelStorei() calls (made by FTPixmapGlyphImpl::RenderImpl).
+    glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
+
+    // Needed on OSX
+    glPolygonMode(GL_FRONT, GL_FILL);    
+    
+    glEnable(GL_BLEND);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+
+    glDisable(GL_TEXTURE_2D);
+
+    GLfloat ftglColour[4];
+    glGetFloatv(GL_CURRENT_RASTER_COLOR, ftglColour);
+
+    glPixelTransferf(GL_RED_SCALE, ftglColour[0]);
+    glPixelTransferf(GL_GREEN_SCALE, ftglColour[1]);
+    glPixelTransferf(GL_BLUE_SCALE, ftglColour[2]);
+    glPixelTransferf(GL_ALPHA_SCALE, ftglColour[3]);
+
+    FTPoint tmp = FTFontImpl::Render(string, len,
+                                     position, spacing, renderMode);
+
+    glPopClientAttrib();
+    glPopAttrib();
+
+    return tmp;
+}
+
+
+FTPoint FTPixmapFontImpl::Render(const char * string, const int len,
+                                 FTPoint position, FTPoint spacing,
+                                 int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
+
+FTPoint FTPixmapFontImpl::Render(const wchar_t * string, const int len,
+                                 FTPoint position, FTPoint spacing,
+                                 int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
diff --git a/src/ext/ftgl/FTFont/FTPixmapFontImpl.h b/src/ext/ftgl/FTFont/FTPixmapFontImpl.h
new file mode 100644
index 0000000..321f4a6
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTPixmapFontImpl.h
@@ -0,0 +1,60 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTPixmapFontImpl__
+#define __FTPixmapFontImpl__
+
+#include "FTFontImpl.h"
+
+class FTGlyph;
+
+class FTPixmapFontImpl : public FTFontImpl
+{
+    friend class FTPixmapFont;
+
+    protected:
+        FTPixmapFontImpl(FTFont *ftFont, const char* fontFilePath);
+
+        FTPixmapFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                         size_t bufferSizeInBytes);
+
+        virtual FTPoint Render(const char *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+        virtual FTPoint Render(const wchar_t *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+    private:
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline FTPoint RenderI(const T *s, const int len,
+                               FTPoint position, FTPoint spacing, int mode);
+};
+
+#endif  //  __FTPixmapFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTPolygonFont.cpp b/src/ext/ftgl/FTFont/FTPolygonFont.cpp
new file mode 100644
index 0000000..83c3ad1
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTPolygonFont.cpp
@@ -0,0 +1,89 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTPolygonFontImpl.h"
+
+
+//
+//  FTPolygonFont
+//
+
+
+FTPolygonFont::FTPolygonFont(char const *fontFilePath) :
+    FTFont(new FTPolygonFontImpl(this, fontFilePath))
+{}
+
+
+FTPolygonFont::FTPolygonFont(const unsigned char *pBufferBytes,
+                             size_t bufferSizeInBytes) :
+    FTFont(new FTPolygonFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTPolygonFont::~FTPolygonFont()
+{}
+
+
+FTGlyph* FTPolygonFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    FTPolygonFontImpl *myimpl = dynamic_cast<FTPolygonFontImpl *>(impl);
+    if(!myimpl)
+    {
+        return NULL;
+    }
+
+    return new FTPolygonGlyph(ftGlyph, myimpl->outset,
+                              myimpl->useDisplayLists);
+}
+
+
+//
+//  FTPolygonFontImpl
+//
+
+
+FTPolygonFontImpl::FTPolygonFontImpl(FTFont *ftFont, const char* fontFilePath)
+: FTFontImpl(ftFont, fontFilePath),
+  outset(0.0f)
+{
+    load_flags = FT_LOAD_NO_HINTING;
+}
+
+
+FTPolygonFontImpl::FTPolygonFontImpl(FTFont *ftFont,
+                                     const unsigned char *pBufferBytes,
+                                     size_t bufferSizeInBytes)
+: FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes),
+  outset(0.0f)
+{
+    load_flags = FT_LOAD_NO_HINTING;
+}
+
diff --git a/src/ext/ftgl/FTFont/FTPolygonFontImpl.h b/src/ext/ftgl/FTFont/FTPolygonFontImpl.h
new file mode 100644
index 0000000..47b35a6
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTPolygonFontImpl.h
@@ -0,0 +1,60 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTPolygonFontImpl__
+#define __FTPolygonFontImpl__
+
+#include "FTFontImpl.h"
+
+class FTGlyph;
+
+class FTPolygonFontImpl : public FTFontImpl
+{
+    friend class FTPolygonFont;
+
+    protected:
+        FTPolygonFontImpl(FTFont *ftFont, const char* fontFilePath);
+
+        FTPolygonFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                          size_t bufferSizeInBytes);
+
+        /**
+         * Set the outset distance for the font. Only implemented by
+         * FTOutlineFont, FTPolygonFont and FTExtrudeFont
+         *
+         * @param depth  The outset distance.
+         */
+        virtual void Outset(float o) { outset = o; }
+
+    private:
+        /**
+         * The outset distance (front and back) for the font.
+         */
+        float outset;
+};
+
+#endif  //  __FTPolygonFontImpl__
+
diff --git a/src/ext/ftgl/FTFont/FTTextureFont.cpp b/src/ext/ftgl/FTFont/FTTextureFont.cpp
new file mode 100644
index 0000000..4e385ea
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTTextureFont.cpp
@@ -0,0 +1,267 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <cassert>
+#include <string> // For memset
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+
+#include "../FTGlyph/FTTextureGlyphImpl.h"
+#include "./FTTextureFontImpl.h"
+
+
+//
+//  FTTextureFont
+//
+
+
+FTTextureFont::FTTextureFont(char const *fontFilePath) :
+    FTFont(new FTTextureFontImpl(this, fontFilePath))
+{}
+
+
+FTTextureFont::FTTextureFont(const unsigned char *pBufferBytes,
+                             size_t bufferSizeInBytes) :
+    FTFont(new FTTextureFontImpl(this, pBufferBytes, bufferSizeInBytes))
+{}
+
+
+FTTextureFont::~FTTextureFont()
+{}
+
+
+FTGlyph* FTTextureFont::MakeGlyph(FT_GlyphSlot ftGlyph)
+{
+    FTTextureFontImpl *myimpl = dynamic_cast<FTTextureFontImpl *>(impl);
+    if(!myimpl)
+    {
+        return NULL;
+    }
+
+    return myimpl->MakeGlyphImpl(ftGlyph);
+}
+
+
+//
+//  FTTextureFontImpl
+//
+
+
+static inline GLuint NextPowerOf2(GLuint in)
+{
+     in -= 1;
+
+     in |= in >> 16;
+     in |= in >> 8;
+     in |= in >> 4;
+     in |= in >> 2;
+     in |= in >> 1;
+
+     return in + 1;
+}
+
+
+FTTextureFontImpl::FTTextureFontImpl(FTFont *ftFont, const char* fontFilePath)
+:   FTFontImpl(ftFont, fontFilePath),
+    maximumGLTextureSize(0),
+    textureWidth(0),
+    textureHeight(0),
+    glyphHeight(0),
+    glyphWidth(0),
+    padding(3),
+    xOffset(0),
+    yOffset(0)
+{
+    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
+    remGlyphs = numGlyphs = face.GlyphCount();
+}
+
+
+FTTextureFontImpl::FTTextureFontImpl(FTFont *ftFont,
+                                     const unsigned char *pBufferBytes,
+                                     size_t bufferSizeInBytes)
+:   FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes),
+    maximumGLTextureSize(0),
+    textureWidth(0),
+    textureHeight(0),
+    glyphHeight(0),
+    glyphWidth(0),
+    padding(3),
+    xOffset(0),
+    yOffset(0)
+{
+    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
+    remGlyphs = numGlyphs = face.GlyphCount();
+}
+
+
+FTTextureFontImpl::~FTTextureFontImpl()
+{
+    if(textureIDList.size())
+    {
+        glDeleteTextures((GLsizei)textureIDList.size(),
+                         (const GLuint*)&textureIDList[0]);
+    }
+}
+
+
+FTGlyph* FTTextureFontImpl::MakeGlyphImpl(FT_GlyphSlot ftGlyph)
+{
+    glyphHeight = static_cast<int>(charSize.Height() + 0.5);
+    glyphWidth = static_cast<int>(charSize.Width() + 0.5);
+
+    if(glyphHeight < 1) glyphHeight = 1;
+    if(glyphWidth < 1) glyphWidth = 1;
+
+    if(textureIDList.empty())
+    {
+        textureIDList.push_back(CreateTexture());
+        xOffset = yOffset = padding;
+    }
+
+    if(xOffset > (textureWidth - glyphWidth))
+    {
+        xOffset = padding;
+        yOffset += glyphHeight;
+
+        if(yOffset > (textureHeight - glyphHeight))
+        {
+            textureIDList.push_back(CreateTexture());
+            yOffset = padding;
+        }
+    }
+
+    FTTextureGlyph* tempGlyph = new FTTextureGlyph(ftGlyph, textureIDList[textureIDList.size() - 1],
+                                                    xOffset, yOffset, textureWidth, textureHeight);
+    xOffset += static_cast<int>(tempGlyph->BBox().Upper().X() - tempGlyph->BBox().Lower().X() + padding + 0.5);
+
+    --remGlyphs;
+
+    return tempGlyph;
+}
+
+
+void FTTextureFontImpl::CalculateTextureSize()
+{
+    if(!maximumGLTextureSize)
+    {
+        maximumGLTextureSize = 1024;
+        glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint*)&maximumGLTextureSize);
+        assert(maximumGLTextureSize); // If you hit this then you have an invalid OpenGL context.
+    }
+
+    textureWidth = NextPowerOf2((remGlyphs * glyphWidth) + (padding * 2));
+    textureWidth = textureWidth > maximumGLTextureSize ? maximumGLTextureSize : textureWidth;
+
+    int h = static_cast<int>((textureWidth - (padding * 2)) / glyphWidth + 0.5);
+
+    textureHeight = NextPowerOf2(((numGlyphs / h) + 1) * glyphHeight);
+    textureHeight = textureHeight > maximumGLTextureSize ? maximumGLTextureSize : textureHeight;
+}
+
+
+GLuint FTTextureFontImpl::CreateTexture()
+{
+    CalculateTextureSize();
+
+    int totalMemory = textureWidth * textureHeight;
+    unsigned char* textureMemory = new unsigned char[totalMemory];
+    memset(textureMemory, 0, totalMemory);
+
+    GLuint textID;
+    glGenTextures(1, (GLuint*)&textID);
+
+    glBindTexture(GL_TEXTURE_2D, textID);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+
+    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, textureWidth, textureHeight,
+                 0, GL_ALPHA, GL_UNSIGNED_BYTE, textureMemory);
+
+    delete [] textureMemory;
+
+    return textID;
+}
+
+
+bool FTTextureFontImpl::FaceSize(const unsigned int size, const unsigned int res)
+{
+    if(!textureIDList.empty())
+    {
+        glDeleteTextures((GLsizei)textureIDList.size(), (const GLuint*)&textureIDList[0]);
+        textureIDList.clear();
+        remGlyphs = numGlyphs = face.GlyphCount();
+    }
+
+    return FTFontImpl::FaceSize(size, res);
+}
+
+
+template <typename T>
+inline FTPoint FTTextureFontImpl::RenderI(const T* string, const int len,
+                                          FTPoint position, FTPoint spacing,
+                                          int renderMode)
+{
+    // Protect GL_TEXTURE_2D, GL_BLEND and blending functions
+    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT);
+
+    glEnable(GL_BLEND);
+    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE
+
+    glEnable(GL_TEXTURE_2D);
+
+    FTTextureGlyphImpl::ResetActiveTexture();
+
+    FTPoint tmp = FTFontImpl::Render(string, len,
+                                     position, spacing, renderMode);
+
+    glPopAttrib();
+
+    return tmp;
+}
+
+
+FTPoint FTTextureFontImpl::Render(const char * string, const int len,
+                                  FTPoint position, FTPoint spacing,
+                                  int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
+
+FTPoint FTTextureFontImpl::Render(const wchar_t * string, const int len,
+                                  FTPoint position, FTPoint spacing,
+                                  int renderMode)
+{
+    return RenderI(string, len, position, spacing, renderMode);
+}
+
diff --git a/src/ext/ftgl/FTFont/FTTextureFontImpl.h b/src/ext/ftgl/FTFont/FTTextureFontImpl.h
new file mode 100644
index 0000000..c9cf22b
--- /dev/null
+++ b/src/ext/ftgl/FTFont/FTTextureFontImpl.h
@@ -0,0 +1,152 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTTextureFontImpl__
+#define __FTTextureFontImpl__
+
+#include "FTFontImpl.h"
+
+#include "FTVector.h"
+
+class FTTextureGlyph;
+
+class FTTextureFontImpl : public FTFontImpl
+{
+    friend class FTTextureFont;
+
+    protected:
+        FTTextureFontImpl(FTFont *ftFont, const char* fontFilePath);
+
+        FTTextureFontImpl(FTFont *ftFont, const unsigned char *pBufferBytes,
+                          size_t bufferSizeInBytes);
+
+        virtual ~FTTextureFontImpl();
+
+        /**
+         * Set the char size for the current face.
+         *
+         * @param size      the face size in points (1/72 inch)
+         * @param res       the resolution of the target device.
+         * @return          <code>true</code> if size was set correctly
+         */
+        virtual bool FaceSize(const unsigned int size,
+                              const unsigned int res = 72);
+
+        virtual FTPoint Render(const char *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+        virtual FTPoint Render(const wchar_t *s, const int len,
+                               FTPoint position, FTPoint spacing,
+                               int renderMode);
+
+    private:
+        /**
+         * Create an FTTextureGlyph object for the base class.
+         */
+        FTGlyph* MakeGlyphImpl(FT_GlyphSlot ftGlyph);
+
+        /**
+         * Get the size of a block of memory required to layout the glyphs
+         *
+         * Calculates a width and height based on the glyph sizes and the
+         * number of glyphs. It over estimates.
+         */
+        inline void CalculateTextureSize();
+
+        /**
+         * Creates a 'blank' OpenGL texture object.
+         *
+         * The format is GL_ALPHA and the params are
+         * GL_TEXTURE_WRAP_S = GL_CLAMP
+         * GL_TEXTURE_WRAP_T = GL_CLAMP
+         * GL_TEXTURE_MAG_FILTER = GL_LINEAR
+         * GL_TEXTURE_MIN_FILTER = GL_LINEAR
+         * Note that mipmapping is NOT used
+         */
+        inline GLuint CreateTexture();
+
+        /**
+         * The maximum texture dimension on this OpenGL implemetation
+         */
+        GLsizei maximumGLTextureSize;
+
+        /**
+         * The minimum texture width required to hold the glyphs
+         */
+        GLsizei textureWidth;
+
+        /**
+         * The minimum texture height required to hold the glyphs
+         */
+        GLsizei textureHeight;
+
+        /**
+         *An array of texture ids
+         */
+        FTVector<GLuint> textureIDList;
+
+        /**
+         * The max height for glyphs in the current font
+         */
+        int glyphHeight;
+
+        /**
+         * The max width for glyphs in the current font
+         */
+        int glyphWidth;
+
+        /**
+         * A value to be added to the height and width to ensure that
+         * glyphs don't overlap in the texture
+         */
+        unsigned int padding;
+
+        /**
+         *
+         */
+        unsigned int numGlyphs;
+
+        /**
+         */
+        unsigned int remGlyphs;
+
+        /**
+         */
+        int xOffset;
+
+        /**
+         */
+        int yOffset;
+
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline FTPoint RenderI(const T *s, const int len,
+                               FTPoint position, FTPoint spacing, int mode);
+};
+
+#endif // __FTTextureFontImpl__
+
diff --git a/src/ext/ftgl/FTGL/FTBBox.h b/src/ext/ftgl/FTGL/FTBBox.h
new file mode 100644
index 0000000..858ff7a
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTBBox.h
@@ -0,0 +1,180 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTBBox__
+#define __FTBBox__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTBBox is a convenience class for handling bounding boxes.
+ */
+class FTGL_EXPORT FTBBox
+{
+    public:
+        /**
+         * Default constructor. Bounding box is set to zero.
+         */
+        FTBBox()
+        :   lower(0.0f, 0.0f, 0.0f),
+            upper(0.0f, 0.0f, 0.0f)
+        {}
+
+        /**
+         * Constructor.
+         */
+        FTBBox(float lx, float ly, float lz, float ux, float uy, float uz)
+        :   lower(lx, ly, lz),
+            upper(ux, uy, uz)
+        {}
+
+        /**
+         * Constructor.
+         */
+        FTBBox(FTPoint l, FTPoint u)
+        :   lower(l),
+            upper(u)
+        {}
+
+        /**
+         * Constructor. Extracts a bounding box from a freetype glyph. Uses
+         * the control box for the glyph. <code>FT_Glyph_Get_CBox()</code>
+         *
+         * @param glyph A freetype glyph
+         */
+        FTBBox(FT_GlyphSlot glyph)
+        :   lower(0.0f, 0.0f, 0.0f),
+            upper(0.0f, 0.0f, 0.0f)
+        {
+            FT_BBox bbox;
+            FT_Outline_Get_CBox(&(glyph->outline), &bbox);
+
+            lower.X(static_cast<float>(bbox.xMin) / 64.0f);
+            lower.Y(static_cast<float>(bbox.yMin) / 64.0f);
+            lower.Z(0.0f);
+            upper.X(static_cast<float>(bbox.xMax) / 64.0f);
+            upper.Y(static_cast<float>(bbox.yMax) / 64.0f);
+            upper.Z(0.0f);
+        }
+
+        /**
+         * Destructor
+         */
+        ~FTBBox()
+        {}
+
+        /**
+         * Mark the bounds invalid by setting all lower dimensions greater
+         * than the upper dimensions.
+         */
+        void Invalidate()
+        {
+            lower = FTPoint(1.0f, 1.0f, 1.0f);
+            upper = FTPoint(-1.0f, -1.0f, -1.0f);
+        }
+
+        /**
+         * Determines if this bounding box is valid.
+         *
+         * @return True if all lower values are <= the corresponding
+         *         upper values.
+         */
+        bool IsValid()
+        {
+            return lower.X() <= upper.X()
+                && lower.Y() <= upper.Y()
+                && lower.Z() <= upper.Z();
+        }
+
+        /**
+         * Move the Bounding Box by a vector.
+         *
+         * @param vector  The vector to move the bbox in 3D space.
+         */
+        FTBBox& operator += (const FTPoint vector)
+        {
+            lower += vector;
+            upper += vector;
+
+            return *this;
+        }
+
+        /**
+         * Combine two bounding boxes. The result is the smallest bounding
+         * box containing the two original boxes.
+         *
+         * @param bbox  The bounding box to merge with the second one.
+         */
+        FTBBox& operator |= (const FTBBox& bbox)
+        {
+            if(bbox.lower.X() < lower.X()) lower.X(bbox.lower.X());
+            if(bbox.lower.Y() < lower.Y()) lower.Y(bbox.lower.Y());
+            if(bbox.lower.Z() < lower.Z()) lower.Z(bbox.lower.Z());
+            if(bbox.upper.X() > upper.X()) upper.X(bbox.upper.X());
+            if(bbox.upper.Y() > upper.Y()) upper.Y(bbox.upper.Y());
+            if(bbox.upper.Z() > upper.Z()) upper.Z(bbox.upper.Z());
+
+            return *this;
+        }
+
+        void SetDepth(float depth)
+        {
+            if(depth > 0)
+                upper.Z(lower.Z() + depth);
+            else
+                lower.Z(upper.Z() + depth);
+        }
+
+
+        inline FTPoint const Upper() const
+        {
+            return upper;
+        }
+
+
+        inline FTPoint const Lower() const
+        {
+            return lower;
+        }
+
+    private:
+        /**
+         * The bounds of the box
+         */
+        FTPoint lower, upper;
+};
+
+#endif //__cplusplus
+
+#endif  //  __FTBBox__
+
diff --git a/src/ext/ftgl/FTGL/FTBitmapGlyph.h b/src/ext/ftgl/FTGL/FTBitmapGlyph.h
new file mode 100644
index 0000000..f8ef87f
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTBitmapGlyph.h
@@ -0,0 +1,82 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTBitmapGlyph__
+#define __FTBitmapGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTBitmapGlyph is a specialisation of FTGlyph for creating bitmaps.
+ */
+class FTGL_EXPORT FTBitmapGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor
+         *
+         * @param glyph The Freetype glyph to be processed
+         */
+        FTBitmapGlyph(FT_GlyphSlot glyph);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTBitmapGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialisation of FTGLglyph for creating bitmaps.
+ *
+ * @param glyph The Freetype glyph to be processed
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreateBitmapGlyph(FT_GlyphSlot glyph);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTBitmapGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTBuffer.h b/src/ext/ftgl/FTGL/FTBuffer.h
new file mode 100644
index 0000000..11f33b5
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTBuffer.h
@@ -0,0 +1,127 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning Please use <FTGL/ftgl.h> instead of <FTBuffer.h>.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTBuffer__
+#define __FTBuffer__
+
+#ifdef __cplusplus
+
+/**
+ * FTBuffer is a helper class for pixel buffers.
+ *
+ * It provides the interface between FTBufferFont and FTBufferGlyph to
+ * optimise rendering operations.
+ *
+ * @see FTBufferGlyph
+ * @see FTBufferFont
+ */
+class FTGL_EXPORT FTBuffer
+{
+    public:
+        /**
+         * Default constructor.
+         */
+        FTBuffer();
+
+        /**
+         * Destructor
+         */
+        ~FTBuffer();
+
+        /**
+         * Get the pen's position in the buffer.
+         *
+         * @return  The pen's position as an FTPoint object.
+         */
+        inline FTPoint Pos() const
+        {
+            return pos;
+        }
+
+        /**
+         * Set the pen's position in the buffer.
+         *
+         * @param arg  An FTPoint object with the desired pen's position.
+         */
+        inline void Pos(FTPoint arg)
+        {
+            pos = arg;
+        }
+
+        /**
+         * Set the buffer's size.
+         *
+         * @param w  The buffer's desired width, in pixels.
+         * @param h  The buffer's desired height, in pixels.
+         */
+        void Size(int w, int h);
+
+        /**
+         * Get the buffer's width.
+         *
+         * @return  The buffer's width, in pixels.
+         */
+        inline int Width() const { return width; }
+
+        /**
+         * Get the buffer's height.
+         *
+         * @return  The buffer's height, in pixels.
+         */
+        inline int Height() const { return height; }
+
+        /**
+         * Get the buffer's direct pixel buffer.
+         *
+         * @return  A read-write pointer to the buffer's pixels.
+         */
+        inline unsigned char *Pixels() const { return pixels; }
+
+    private:
+        /**
+         * Buffer's width and height.
+         */
+        int width, height;
+
+        /**
+         * Buffer's pixel buffer.
+         */
+        unsigned char *pixels;
+
+        /**
+         * Buffer's internal pen position.
+         */
+        FTPoint pos;
+};
+
+#endif //__cplusplus
+
+#endif // __FTBuffer__
+
diff --git a/src/ext/ftgl/FTGL/FTBufferFont.h b/src/ext/ftgl/FTGL/FTBufferFont.h
new file mode 100644
index 0000000..15d358d
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTBufferFont.h
@@ -0,0 +1,99 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning Please use <FTGL/ftgl.h> instead of <FTBufferFont.h>.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTBufferFont__
+#define __FTBufferFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTBufferFont is a specialisation of the FTFont class for handling
+ * memory buffer fonts.
+ *
+ * @see     FTFont
+ */
+class FTGL_EXPORT FTBufferFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTBufferFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTBufferFont(const unsigned char *pBufferBytes,
+                     size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        ~FTBufferFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling memory buffer fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ */
+FTGL_EXPORT FTGLfont *ftglCreateBufferFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTBufferFont__
+
diff --git a/src/ext/ftgl/FTGL/FTBufferGlyph.h b/src/ext/ftgl/FTGL/FTBufferGlyph.h
new file mode 100644
index 0000000..cb7b3ed
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTBufferGlyph.h
@@ -0,0 +1,69 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning Please use <FTGL/ftgl.h> instead of <FTBufferGlyph.h>.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTBufferGlyph__
+#define __FTBufferGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTBufferGlyph is a specialisation of FTGlyph for memory buffer rendering.
+ */
+class FTGL_EXPORT FTBufferGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor
+         *
+         * @param glyph The Freetype glyph to be processed
+         * @param buffer  An FTBuffer object in which to render the glyph.
+         */
+        FTBufferGlyph(FT_GlyphSlot glyph, FTBuffer *buffer);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTBufferGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#endif //__cplusplus
+
+#endif  //  __FTBufferGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTExtrdGlyph.h b/src/ext/ftgl/FTGL/FTExtrdGlyph.h
new file mode 100644
index 0000000..c1eaa54
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTExtrdGlyph.h
@@ -0,0 +1,104 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTExtrudeGlyph__
+#define __FTExtrudeGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTExtrudeGlyph is a specialisation of FTGlyph for creating tessellated
+ * extruded polygon glyphs.
+ */
+class FTGL_EXPORT FTExtrudeGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor. Sets the Error to Invalid_Outline if the glyph isn't
+         * an outline.
+         *
+         * @param glyph The Freetype glyph to be processed
+         * @param depth The distance along the z axis to extrude the glyph
+         * @param frontOutset outset contour size
+         * @param backOutset outset contour size
+         * @param useDisplayList Enable or disable the use of Display Lists
+         *                       for this glyph
+         *                       <code>true</code> turns ON display lists.
+         *                       <code>false</code> turns OFF display lists.
+         */
+        FTExtrudeGlyph(FT_GlyphSlot glyph, float depth, float frontOutset,
+                       float backOutset, bool useDisplayList);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTExtrudeGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#define FTExtrdGlyph FTExtrudeGlyph
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialisation of FTGLglyph for creating tessellated
+ * extruded polygon glyphs.
+ *
+ * @param glyph The Freetype glyph to be processed
+ * @param depth The distance along the z axis to extrude the glyph
+ * @param frontOutset outset contour size
+ * @param backOutset outset contour size
+ * @param useDisplayList Enable or disable the use of Display Lists
+ *                       for this glyph
+ *                       <code>true</code> turns ON display lists.
+ *                       <code>false</code> turns OFF display lists.
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreateExtrudeGlyph(FT_GlyphSlot glyph, float depth,
+                                float frontOutset, float backOutset,
+                                int useDisplayList);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTExtrudeGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTFont.h b/src/ext/ftgl/FTGL/FTFont.h
new file mode 100644
index 0000000..0799fff
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTFont.h
@@ -0,0 +1,584 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTFont__
+#define __FTFont__
+
+#ifdef __cplusplus
+
+class FTFontImpl;
+
+/**
+ * FTFont is the public interface for the FTGL library.
+ *
+ * Specific font classes are derived from this class. It uses the helper
+ * classes FTFace and FTSize to access the Freetype library. This class
+ * is abstract and deriving classes must implement the protected
+ * <code>MakeGlyph</code> function to create glyphs of the
+ * appropriate type.
+ *
+ * It is good practice after using these functions to test the error
+ * code returned. <code>FT_Error Error()</code>. Check the freetype file
+ * fterrdef.h for error definitions.
+ *
+ * @see     FTFace
+ * @see     FTSize
+ */
+class FTGL_EXPORT FTFont
+{
+    protected:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTFont(char const *fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTFont(const unsigned char *pBufferBytes, size_t bufferSizeInBytes);
+
+    private:
+        /* Allow our internal subclasses to access the private constructor */
+        friend class FTBitmapFont;
+        friend class FTBufferFont;
+        friend class FTExtrudeFont;
+        friend class FTOutlineFont;
+        friend class FTPixmapFont;
+        friend class FTPolygonFont;
+        friend class FTTextureFont;
+
+        /**
+         * Internal FTGL FTFont constructor. For private use only.
+         *
+         * @param pImpl  Internal implementation object. Will be destroyed
+         *               upon FTFont deletion.
+         */
+        FTFont(FTFontImpl *pImpl);
+
+    public:
+        virtual ~FTFont();
+
+        /**
+         * Attach auxilliary file to font e.g font metrics.
+         *
+         * Note: not all font formats implement this function.
+         *
+         * @param fontFilePath  auxilliary font file path.
+         * @return          <code>true</code> if file has been attached
+         *                  successfully.
+         */
+        virtual bool Attach(const char* fontFilePath);
+
+        /**
+         * Attach auxilliary data to font e.g font metrics, from memory.
+         *
+         * Note: not all font formats implement this function.
+         *
+         * @param pBufferBytes  the in-memory buffer.
+         * @param bufferSizeInBytes  the length of the buffer in bytes.
+         * @return          <code>true</code> if file has been attached
+         *                  successfully.
+         */
+        virtual bool Attach(const unsigned char *pBufferBytes,
+                            size_t bufferSizeInBytes);
+
+        /**
+         * Set the glyph loading flags. By default, fonts use the most
+         * sensible flags when loading a font's glyph using FT_Load_Glyph().
+         * This function allows to override the default flags.
+         *
+         * @param flags  The glyph loading flags.
+         */
+        virtual void GlyphLoadFlags(FT_Int flags);
+
+        /**
+         * Set the character map for the face.
+         *
+         * @param encoding      Freetype enumerate for char map code.
+         * @return              <code>true</code> if charmap was valid and
+         *                      set correctly.
+         */
+        virtual bool CharMap(FT_Encoding encoding);
+
+        /**
+         * Get the number of character maps in this face.
+         *
+         * @return character map count.
+         */
+        virtual unsigned int CharMapCount() const;
+
+        /**
+         * Get a list of character maps in this face.
+         *
+         * @return pointer to the first encoding.
+         */
+        virtual FT_Encoding* CharMapList();
+
+        /**
+         * Set the char size for the current face.
+         *
+         * @param size      the face size in points (1/72 inch)
+         * @param res       the resolution of the target device.
+         * @return          <code>true</code> if size was set correctly
+         */
+        virtual bool FaceSize(const unsigned int size,
+                              const unsigned int res = 72);
+
+        /**
+         * Get the current face size in points (1/72 inch).
+         *
+         * @return face size
+         */
+        virtual unsigned int FaceSize() const;
+
+        /**
+         * Set the extrusion distance for the font. Only implemented by
+         * FTExtrudeFont
+         *
+         * @param depth  The extrusion distance.
+         */
+        virtual void Depth(float depth);
+
+        /**
+         * Set the outset distance for the font. Only implemented by
+         * FTOutlineFont, FTPolygonFont and FTExtrudeFont
+         *
+         * @param outset  The outset distance.
+         */
+        virtual void Outset(float outset);
+
+        /**
+         * Set the front and back outset distances for the font. Only
+         * implemented by FTExtrudeFont
+         *
+         * @param front  The front outset distance.
+         * @param back   The back outset distance.
+         */
+        virtual void Outset(float front, float back);
+
+        /**
+         * Enable or disable the use of Display Lists inside FTGL
+         *
+         * @param  useList <code>true</code> turns ON display lists.
+         *                 <code>false</code> turns OFF display lists.
+         */
+        virtual void UseDisplayList(bool useList);
+
+        /**
+         * Get the global ascender height for the face.
+         *
+         * @return  Ascender height
+         */
+        virtual float Ascender() const;
+
+        /**
+         * Gets the global descender height for the face.
+         *
+         * @return  Descender height
+         */
+        virtual float Descender() const;
+
+        /**
+         * Gets the line spacing for the font.
+         *
+         * @return  Line height
+         */
+        virtual float LineHeight() const;
+
+        /**
+         * Get the bounding box for a string.
+         *
+         * @param string  A char buffer.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param spacing  A displacement vector to add after each character
+         *                 has been checked (optional).
+         * @return  The corresponding bounding box.
+         */
+        virtual FTBBox BBox(const char *string, const int len = -1,
+                            FTPoint position = FTPoint(),
+                            FTPoint spacing = FTPoint());
+
+        /**
+         * Get the bounding box for a string (deprecated).
+         *
+         * @param string  A char buffer.
+         * @param llx  Lower left near x coordinate.
+         * @param lly  Lower left near y coordinate.
+         * @param llz  Lower left near z coordinate.
+         * @param urx  Upper right far x coordinate.
+         * @param ury  Upper right far y coordinate.
+         * @param urz  Upper right far z coordinate.
+         */
+        void BBox(const char* string, float& llx, float& lly, float& llz,
+                  float& urx, float& ury, float& urz)
+        {
+            FTBBox b = BBox(string);
+            llx = b.Lower().Xf(); lly = b.Lower().Yf(); llz = b.Lower().Zf();
+            urx = b.Upper().Xf(); ury = b.Upper().Yf(); urz = b.Upper().Zf();
+        }
+
+        /**
+         * Get the bounding box for a string.
+         *
+         * @param string  A wchar_t buffer.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param spacing  A displacement vector to add after each character
+         *                 has been checked (optional).
+         * @return  The corresponding bounding box.
+         */
+        virtual FTBBox BBox(const wchar_t *string, const int len = -1,
+                            FTPoint position = FTPoint(),
+                            FTPoint spacing = FTPoint());
+
+        /**
+         * Get the bounding box for a string (deprecated).
+         *
+         * @param string  A wchar_t buffer.
+         * @param llx  Lower left near x coordinate.
+         * @param lly  Lower left near y coordinate.
+         * @param llz  Lower left near z coordinate.
+         * @param urx  Upper right far x coordinate.
+         * @param ury  Upper right far y coordinate.
+         * @param urz  Upper right far z coordinate.
+         */
+        void BBox(const wchar_t* string, float& llx, float& lly, float& llz,
+                  float& urx, float& ury, float& urz)
+        {
+            FTBBox b = BBox(string);
+            llx = b.Lower().Xf(); lly = b.Lower().Yf(); llz = b.Lower().Zf();
+            urx = b.Upper().Xf(); ury = b.Upper().Yf(); urz = b.Upper().Zf();
+        }
+
+        /**
+         * Get the advance for a string.
+         *
+         * @param string  'C' style string to be checked.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param spacing  A displacement vector to add after each character
+         *                 has been checked (optional).
+         * @return  The string's advance width.
+         */
+        virtual float Advance(const char* string, const int len = -1,
+                              FTPoint spacing = FTPoint());
+
+        /**
+         * Get the advance for a string.
+         *
+         * @param string  A wchar_t string
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param spacing  A displacement vector to add after each character
+         *                 has been checked (optional).
+         * @return  The string's advance width.
+         */
+        virtual float Advance(const wchar_t* string, const int len = -1,
+                              FTPoint spacing = FTPoint());
+
+        /**
+         * Render a string of characters.
+         *
+         * @param string  'C' style string to be output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param spacing  A displacement vector to add after each character
+         *                 has been displayed (optional).
+         * @param renderMode  Render mode to use for display (optional).
+         * @return  The new pen position after the last character was output.
+         */
+        virtual FTPoint Render(const char* string, const int len = -1,
+                               FTPoint position = FTPoint(),
+                               FTPoint spacing = FTPoint(),
+                               int renderMode = FTGL::RENDER_ALL);
+
+        /**
+         * Render a string of characters
+         *
+         * @param string    wchar_t string to be output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param spacing  A displacement vector to add after each character
+         *                 has been displayed (optional).
+         * @param renderMode  Render mode to use for display (optional).
+         * @return  The new pen position after the last character was output.
+         */
+        virtual FTPoint Render(const wchar_t *string, const int len = -1,
+                               FTPoint position = FTPoint(),
+                               FTPoint spacing = FTPoint(),
+                               int renderMode = FTGL::RENDER_ALL);
+
+        /**
+         * Queries the Font for errors.
+         *
+         * @return  The current error code.
+         */
+        virtual FT_Error Error() const;
+
+    protected:
+        /* Allow impl to access MakeGlyph */
+        friend class FTFontImpl;
+
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot) = 0;
+
+    private:
+        /**
+         * Internal FTGL FTFont implementation object. For private use only.
+         */
+        FTFontImpl *impl;
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * FTGLfont is the public interface for the FTGL library.
+ *
+ * It is good practice after using these functions to test the error
+ * code returned. <code>FT_Error Error()</code>. Check the freetype file
+ * fterrdef.h for error definitions.
+ */
+struct _FTGLFont;
+typedef struct _FTGLfont FTGLfont;
+
+/**
+ * Create a custom FTGL font object.
+ *
+ * @param fontFilePath  The font file name.
+ * @param data  A pointer to private data that will be passed to callbacks.
+ * @param makeglyphCallback  A glyph-making callback function.
+ * @return  An FTGLfont* object.
+ */
+FTGL_EXPORT FTGLfont *ftglCreateCustomFont(char const *fontFilePath,
+                                           void *data,
+                   FTGLglyph * (*makeglyphCallback) (FT_GlyphSlot, void *));
+
+/**
+ * Destroy an FTGL font object.
+ *
+ * @param font  An FTGLfont* object.
+ */
+FTGL_EXPORT void ftglDestroyFont(FTGLfont* font);
+
+/**
+ * Attach auxilliary file to font e.g. font metrics.
+ *
+ * Note: not all font formats implement this function.
+ *
+ * @param font  An FTGLfont* object.
+ * @param path  Auxilliary font file path.
+ * @return  1 if file has been attached successfully.
+ */
+FTGL_EXPORT int ftglAttachFile(FTGLfont* font, const char* path);
+
+/**
+ * Attach auxilliary data to font, e.g. font metrics, from memory.
+ *
+ * Note: not all font formats implement this function.
+ *
+ * @param font  An FTGLfont* object.
+ * @param data  The in-memory buffer.
+ * @param size  The length of the buffer in bytes.
+ * @return  1 if file has been attached successfully.
+ */
+FTGL_EXPORT int ftglAttachData(FTGLfont* font, const unsigned char * data,
+                               size_t size);
+
+/**
+ * Set the character map for the face.
+ *
+ * @param font  An FTGLfont* object.
+ * @param encoding  Freetype enumerate for char map code.
+ * @return  1 if charmap was valid and set correctly.
+ */
+FTGL_EXPORT int ftglSetFontCharMap(FTGLfont* font, FT_Encoding encoding);
+
+/**
+ * Get the number of character maps in this face.
+ *
+ * @param font  An FTGLfont* object.
+ * @return character map count.
+ */
+FTGL_EXPORT unsigned int ftglGetFontCharMapCount(FTGLfont* font);
+
+/**
+ * Get a list of character maps in this face.
+ *
+ * @param font  An FTGLfont* object.
+ * @return pointer to the first encoding.
+ */
+FTGL_EXPORT FT_Encoding* ftglGetFontCharMapList(FTGLfont* font);
+
+/**
+ * Set the char size for the current face.
+ *
+ * @param font  An FTGLfont* object.
+ * @param size  The face size in points (1/72 inch).
+ * @param res  The resolution of the target device, or 0 to use the default
+ *             value of 72.
+ * @return  1 if size was set correctly.
+ */
+FTGL_EXPORT int ftglSetFontFaceSize(FTGLfont* font, unsigned int size,
+                                    unsigned int res);
+
+/**
+ * Get the current face size in points (1/72 inch).
+ *
+ * @param font  An FTGLfont* object.
+ * @return face size
+ */
+FTGL_EXPORT unsigned int ftglGetFontFaceSize(FTGLfont* font);
+
+/**
+ * Set the extrusion distance for the font. Only implemented by
+ * FTExtrudeFont.
+ *
+ * @param font  An FTGLfont* object.
+ * @param depth  The extrusion distance.
+ */
+FTGL_EXPORT void ftglSetFontDepth(FTGLfont* font, float depth);
+
+/**
+ * Set the outset distance for the font. Only FTOutlineFont, FTPolygonFont
+ * and FTExtrudeFont implement front outset. Only FTExtrudeFont implements
+ * back outset.
+ *
+ * @param font  An FTGLfont* object.
+ * @param front  The front outset distance.
+ * @param back  The back outset distance.
+ */
+FTGL_EXPORT void ftglSetFontOutset(FTGLfont* font, float front, float back);
+
+/**
+ * Enable or disable the use of Display Lists inside FTGL.
+ *
+ * @param font  An FTGLfont* object.
+ * @param useList  1 turns ON display lists.
+ *                 0 turns OFF display lists.
+ */
+FTGL_EXPORT void ftglSetFontDisplayList(FTGLfont* font, int useList);
+
+/**
+ * Get the global ascender height for the face.
+ *
+ * @param font  An FTGLfont* object.
+ * @return  Ascender height
+ */
+FTGL_EXPORT float ftglGetFontAscender(FTGLfont* font);
+
+/**
+ * Gets the global descender height for the face.
+ *
+ * @param font  An FTGLfont* object.
+ * @return  Descender height
+ */
+FTGL_EXPORT float ftglGetFontDescender(FTGLfont* font);
+
+/**
+ * Gets the line spacing for the font.
+ *
+ * @param font  An FTGLfont* object.
+ * @return  Line height
+ */
+FTGL_EXPORT float ftglGetFontLineHeight(FTGLfont* font);
+
+/**
+ * Get the bounding box for a string.
+ *
+ * @param font  An FTGLfont* object.
+ * @param string  A char buffer
+ * @param len  The length of the string. If < 0 then all characters will be
+ *             checked until a null character is encountered (optional).
+ * @param bounds  An array of 6 float values where the bounding box's lower
+ *                left near and upper right far 3D coordinates will be stored.
+ */
+FTGL_EXPORT void ftglGetFontBBox(FTGLfont* font, const char *string,
+                                 int len, float bounds[6]);
+
+/**
+ * Get the advance width for a string.
+ *
+ * @param font  An FTGLfont* object.
+ * @param string  A char string.
+ * @return  Advance width
+ */
+FTGL_EXPORT float ftglGetFontAdvance(FTGLfont* font, const char *string);
+
+/**
+ * Render a string of characters.
+ *
+ * @param font  An FTGLfont* object.
+ * @param string  Char string to be output.
+ * @param mode  Render mode to display.
+ */
+FTGL_EXPORT void ftglRenderFont(FTGLfont* font, const char *string, int mode);
+
+/**
+ * Query a font for errors.
+ *
+ * @param font  An FTGLfont* object.
+ * @return  The current error code.
+ */
+FTGL_EXPORT FT_Error ftglGetFontError(FTGLfont* font);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGLBitmapFont.h b/src/ext/ftgl/FTGL/FTGLBitmapFont.h
new file mode 100644
index 0000000..d2fb1ba
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGLBitmapFont.h
@@ -0,0 +1,103 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTBitmapFont__
+#define __FTBitmapFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTBitmapFont is a specialisation of the FTFont class for handling
+ * Bitmap fonts
+ *
+ * @see     FTFont
+ */
+class FTGL_EXPORT FTBitmapFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTBitmapFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTBitmapFont(const unsigned char *pBufferBytes,
+                     size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        ~FTBitmapFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#define FTGLBitmapFont FTBitmapFont
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling bitmap fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ */
+FTGL_EXPORT FTGLfont *ftglCreateBitmapFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTBitmapFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGLExtrdFont.h b/src/ext/ftgl/FTGL/FTGLExtrdFont.h
new file mode 100644
index 0000000..47d6714
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGLExtrdFont.h
@@ -0,0 +1,105 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTExtrudeFont__
+#define __FTExtrudeFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTExtrudeFont is a specialisation of the FTFont class for handling
+ * extruded Polygon fonts
+ *
+ * @see FTFont
+ * @see FTPolygonFont
+ */
+class FTGL_EXPORT FTExtrudeFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTExtrudeFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTExtrudeFont(const unsigned char *pBufferBytes,
+                      size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        ~FTExtrudeFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#define FTGLExtrdFont FTExtrudeFont
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling extruded poygon fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ * @see  ftglCreatePolygonFont
+ */
+FTGL_EXPORT FTGLfont *ftglCreateExtrudeFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif // __FTExtrudeFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGLOutlineFont.h b/src/ext/ftgl/FTGL/FTGLOutlineFont.h
new file mode 100644
index 0000000..bbf62da
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGLOutlineFont.h
@@ -0,0 +1,103 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTOutlineFont__
+#define __FTOutlineFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTOutlineFont is a specialisation of the FTFont class for handling
+ * Vector Outline fonts
+ *
+ * @see     FTFont
+ */
+class FTGL_EXPORT FTOutlineFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTOutlineFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTOutlineFont(const unsigned char *pBufferBytes,
+                      size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        ~FTOutlineFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#define FTGLOutlineFont FTOutlineFont
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling vector outline fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ */
+FTGL_EXPORT FTGLfont *ftglCreateOutlineFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif // __FTOutlineFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGLPixmapFont.h b/src/ext/ftgl/FTGL/FTGLPixmapFont.h
new file mode 100644
index 0000000..c90b9c5
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGLPixmapFont.h
@@ -0,0 +1,103 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTPixmapFont__
+#define __FTPixmapFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTPixmapFont is a specialisation of the FTFont class for handling
+ * Pixmap (Grey Scale) fonts
+ *
+ * @see     FTFont
+ */
+class FTGL_EXPORT FTPixmapFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTPixmapFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTPixmapFont(const unsigned char *pBufferBytes,
+                     size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        ~FTPixmapFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#define FTGLPixmapFont FTPixmapFont
+
+#endif // __cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling pixmap (grey scale) fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ */
+FTGL_EXPORT FTGLfont *ftglCreatePixmapFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTPixmapFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGLPolygonFont.h b/src/ext/ftgl/FTGL/FTGLPolygonFont.h
new file mode 100644
index 0000000..1dab097
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGLPolygonFont.h
@@ -0,0 +1,104 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTPolygonFont__
+#define __FTPolygonFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTPolygonFont is a specialisation of the FTFont class for handling
+ * tesselated Polygon Mesh fonts
+ *
+ * @see     FTFont
+ */
+class FTGL_EXPORT FTPolygonFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTPolygonFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTPolygonFont(const unsigned char *pBufferBytes,
+                      size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        ~FTPolygonFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#define FTGLPolygonFont FTPolygonFont
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling tesselated polygon
+ * mesh fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ */
+FTGL_EXPORT FTGLfont *ftglCreatePolygonFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTPolygonFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGLTextureFont.h b/src/ext/ftgl/FTGL/FTGLTextureFont.h
new file mode 100644
index 0000000..03991e9
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGLTextureFont.h
@@ -0,0 +1,103 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTTextureFont__
+#define __FTTextureFont__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTTextureFont is a specialisation of the FTFont class for handling
+ * Texture mapped fonts
+ *
+ * @see     FTFont
+ */
+class  FTGL_EXPORT FTTextureFont : public FTFont
+{
+    public:
+        /**
+         * Open and read a font file. Sets Error flag.
+         *
+         * @param fontFilePath  font file path.
+         */
+        FTTextureFont(const char* fontFilePath);
+
+        /**
+         * Open and read a font from a buffer in memory. Sets Error flag.
+         * The buffer is owned by the client and is NOT copied by FTGL. The
+         * pointer must be valid while using FTGL.
+         *
+         * @param pBufferBytes  the in-memory buffer
+         * @param bufferSizeInBytes  the length of the buffer in bytes
+         */
+        FTTextureFont(const unsigned char *pBufferBytes,
+                      size_t bufferSizeInBytes);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTTextureFont();
+
+    protected:
+        /**
+         * Construct a glyph of the correct type.
+         *
+         * Clients must override the function and return their specialised
+         * FTGlyph.
+         *
+         * @param slot  A FreeType glyph slot.
+         * @return  An FT****Glyph or <code>null</code> on failure.
+         */
+        virtual FTGlyph* MakeGlyph(FT_GlyphSlot slot);
+};
+
+#define FTGLTextureFont FTTextureFont
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialised FTGLfont object for handling texture-mapped fonts.
+ *
+ * @param file  The font file name.
+ * @return  An FTGLfont* object.
+ *
+ * @see  FTGLfont
+ */
+FTGL_EXPORT FTGLfont *ftglCreateTextureFont(const char *file);
+
+FTGL_END_C_DECLS
+
+#endif // __FTTextureFont__
+
diff --git a/src/ext/ftgl/FTGL/FTGlyph.h b/src/ext/ftgl/FTGL/FTGlyph.h
new file mode 100644
index 0000000..a5023b2
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTGlyph.h
@@ -0,0 +1,201 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTGlyph__
+#define __FTGlyph__
+
+#ifdef __cplusplus
+
+class FTGlyphImpl;
+
+/**
+ * FTGlyph is the base class for FTGL glyphs.
+ *
+ * It provides the interface between Freetype glyphs and their openGL
+ * renderable counterparts. This is an abstract class and derived classes
+ * must implement the <code>Render</code> function.
+ *
+ * @see FTBBox
+ * @see FTPoint
+ */
+class FTGL_EXPORT FTGlyph
+{
+    protected:
+        /**
+         * Create a glyph.
+         *
+         * @param glyph  The Freetype glyph to be processed
+         */
+        FTGlyph(FT_GlyphSlot glyph);
+
+    private:
+        /**
+         * Internal FTGL FTGlyph constructor. For private use only.
+         *
+         * @param pImpl  Internal implementation object. Will be destroyed
+         *               upon FTGlyph deletion.
+         */
+        FTGlyph(FTGlyphImpl *pImpl);
+
+        /* Allow our internal subclasses to access the private constructor */
+        friend class FTBitmapGlyph;
+        friend class FTBufferGlyph;
+        friend class FTExtrudeGlyph;
+        friend class FTOutlineGlyph;
+        friend class FTPixmapGlyph;
+        friend class FTPolygonGlyph;
+        friend class FTTextureGlyph;
+
+    public:
+        /**
+          * Destructor
+          */
+        virtual ~FTGlyph();
+
+        /**
+         * Renders this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode) = 0;
+
+        /**
+         * Return the advance width for this glyph.
+         *
+         * @return  advance width.
+         */
+        virtual float Advance() const;
+
+        /**
+         * Return the bounding box for this glyph.
+         *
+         * @return  bounding box.
+         */
+        virtual const FTBBox& BBox() const;
+
+        /**
+         * Queries for errors.
+         *
+         * @return  The current error code.
+         */
+        virtual FT_Error Error() const;
+
+    private:
+        /**
+         * Internal FTGL FTGlyph implementation object. For private use only.
+         */
+        FTGlyphImpl *impl;
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * FTGLglyph is the base class for FTGL glyphs.
+ *
+ * It provides the interface between Freetype glyphs and their openGL
+ * renderable counterparts. This is an abstract class and derived classes
+ * must implement the ftglRenderGlyph() function.
+ */
+struct _FTGLGlyph;
+typedef struct _FTGLglyph FTGLglyph;
+
+/**
+ * Create a custom FTGL glyph object.
+ * FIXME: maybe get rid of "base" and have advanceCallback etc. functions
+ *
+ * @param base  The base FTGLglyph* to subclass.
+ * @param data  A pointer to private data that will be passed to callbacks.
+ * @param renderCallback  A rendering callback function.
+ * @param destroyCallback  A callback function to be called upon destruction.
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreateCustomGlyph(FTGLglyph *base, void *data,
+    void (*renderCallback) (FTGLglyph *, void *, FTGL_DOUBLE, FTGL_DOUBLE,
+                             int, FTGL_DOUBLE *, FTGL_DOUBLE *),
+    void (*destroyCallback) (FTGLglyph *, void *));
+
+/**
+ * Destroy an FTGL glyph object.
+ *
+ * @param glyph  An FTGLglyph* object.
+ */
+FTGL_EXPORT void ftglDestroyGlyph(FTGLglyph *glyph);
+
+/**
+ * Render a glyph at the current pen position and compute the corresponding
+ * advance.
+ *
+ * @param glyph  An FTGLglyph* object.
+ * @param penx  The current pen's X position.
+ * @param peny  The current pen's Y position.
+ * @param renderMode  Render mode to display
+ * @param advancex  A pointer to an FTGL_DOUBLE where to write the advance's X
+ *                  component.
+ * @param advancey  A pointer to an FTGL_DOUBLE where to write the advance's Y
+ *                  component.
+ */
+FTGL_EXPORT void ftglRenderGlyph(FTGLglyph *glyph, FTGL_DOUBLE penx,
+                                 FTGL_DOUBLE peny, int renderMode,
+                                 FTGL_DOUBLE *advancex, FTGL_DOUBLE *advancey);
+/**
+ * Return the advance for a glyph.
+ *
+ * @param glyph  An FTGLglyph* object.
+ * @return  The advance's X component.
+ */
+FTGL_EXPORT float ftglGetGlyphAdvance(FTGLglyph *glyph);
+
+/**
+ * Return the bounding box for a glyph.
+ *
+ * @param glyph  An FTGLglyph* object.
+ * @param bounds  An array of 6 float values where the bounding box's lower
+ *                left near and upper right far 3D coordinates will be stored.
+ */
+FTGL_EXPORT void ftglGetGlyphBBox(FTGLglyph *glyph, float bounds[6]);
+
+/**
+ * Query a glyph for errors.
+ *
+ * @param glyph  An FTGLglyph* object.
+ * @return  The current error code.
+ */
+FTGL_EXPORT FT_Error ftglGetGlyphError(FTGLglyph* glyph);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTLayout.h b/src/ext/ftgl/FTGL/FTLayout.h
new file mode 100644
index 0000000..329b98a
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTLayout.h
@@ -0,0 +1,192 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTLayout__
+#define __FTLayout__
+
+#ifdef __cplusplus
+
+
+class FTLayoutImpl;
+
+/**
+ * FTLayout is the interface for layout managers that render text.
+ *
+ * Specific layout manager classes are derived from this class. This class
+ * is abstract and deriving classes must implement the protected
+ * <code>Render</code> methods to render formatted text and
+ * <code>BBox</code> methods to determine the bounding box of output text.
+ *
+ * @see     FTFont
+ * @see     FTBBox
+ */
+class FTGL_EXPORT FTLayout
+{
+    protected:
+        FTLayout();
+
+    private:
+        /**
+         * Internal FTGL FTLayout constructor. For private use only.
+         *
+         * @param pImpl  Internal implementation object. Will be destroyed
+         *               upon FTLayout deletion.
+         */
+        FTLayout(FTLayoutImpl *pImpl);
+
+        /* Allow our internal subclasses to access the private constructor */
+        friend class FTSimpleLayout;
+
+    public:
+        /**
+         * Destructor
+         */
+        virtual ~FTLayout();
+
+        /**
+         * Get the bounding box for a formatted string.
+         *
+         * @param string  A char string.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @return  The corresponding bounding box.
+         */
+        virtual FTBBox BBox(const char* string, const int len = -1,
+                            FTPoint position = FTPoint()) = 0;
+
+        /**
+         * Get the bounding box for a formatted string.
+         *
+         * @param string  A wchar_t string.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @return  The corresponding bounding box.
+         */
+        virtual FTBBox BBox(const wchar_t* string, const int len = -1,
+                            FTPoint position = FTPoint()) = 0;
+
+        /**
+         * Render a string of characters.
+         *
+         * @param string    'C' style string to be output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param renderMode  Render mode to display (optional)
+         */
+        virtual void Render(const char *string, const int len = -1,
+                            FTPoint position = FTPoint(),
+                            int renderMode = FTGL::RENDER_ALL) = 0;
+
+        /**
+         * Render a string of characters.
+         *
+         * @param string    wchar_t string to be output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param renderMode  Render mode to display (optional)
+         */
+        virtual void Render(const wchar_t *string, const int len = -1,
+                            FTPoint position = FTPoint(),
+                            int renderMode = FTGL::RENDER_ALL) = 0;
+
+        /**
+         * Queries the Layout for errors.
+         *
+         * @return  The current error code.
+         */
+        virtual FT_Error Error() const;
+
+    private:
+        /**
+         * Internal FTGL FTLayout implementation object. For private use only.
+         */
+        FTLayoutImpl *impl;
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * FTGLlayout is the interface for layout managers that render text.
+ */
+struct _FTGLlayout;
+typedef struct _FTGLlayout FTGLlayout;
+
+/**
+ * Destroy an FTGL layout object.
+ *
+ * @param layout  An FTGLlayout* object.
+ */
+FTGL_EXPORT void ftglDestroyLayout(FTGLlayout* layout);
+
+/**
+ * Get the bounding box for a string.
+ *
+ * @param layout  An FTGLlayout* object.
+ * @param string  A char buffer
+ * @param bounds  An array of 6 float values where the bounding box's lower
+ *                left near and upper right far 3D coordinates will be stored.
+ */
+FTGL_EXPORT void ftglGetLayoutBBox(FTGLlayout *layout, const char* string,
+                                   float bounds[6]);
+
+/**
+ * Render a string of characters.
+ *
+ * @param layout  An FTGLlayout* object.
+ * @param string  Char string to be output.
+ * @param mode  Render mode to display.
+ */
+FTGL_EXPORT void ftglRenderLayout(FTGLlayout *layout, const char *string,
+                                  int mode);
+
+/**
+ * Query a layout for errors.
+ *
+ * @param layout  An FTGLlayout* object.
+ * @return  The current error code.
+ */
+FTGL_EXPORT FT_Error ftglGetLayoutError(FTGLlayout* layout);
+
+FTGL_END_C_DECLS
+
+#endif  /* __FTLayout__ */
+
diff --git a/src/ext/ftgl/FTGL/FTOutlineGlyph.h b/src/ext/ftgl/FTGL/FTOutlineGlyph.h
new file mode 100644
index 0000000..2919139
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTOutlineGlyph.h
@@ -0,0 +1,94 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTOutlineGlyph__
+#define __FTOutlineGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTOutlineGlyph is a specialisation of FTGlyph for creating outlines.
+ */
+class FTGL_EXPORT FTOutlineGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor. Sets the Error to Invalid_Outline if the glyphs isn't
+         * an outline.
+         *
+         * @param glyph The Freetype glyph to be processed
+         * @param outset outset distance
+         * @param useDisplayList Enable or disable the use of Display Lists
+         *                       for this glyph
+         *                       <code>true</code> turns ON display lists.
+         *                       <code>false</code> turns OFF display lists.
+         */
+        FTOutlineGlyph(FT_GlyphSlot glyph, float outset, bool useDisplayList);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTOutlineGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialisation of FTGLglyph for creating outlines.
+ *
+ * @param glyph The Freetype glyph to be processed
+ * @param outset outset contour size
+ * @param useDisplayList Enable or disable the use of Display Lists
+ *                       for this glyph
+ *                       <code>true</code> turns ON display lists.
+ *                       <code>false</code> turns OFF display lists.
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreateOutlineGlyph(FT_GlyphSlot glyph, float outset,
+                                  int useDisplayList);
+
+FTGL_END_C_DECLS
+
+#endif  // __FTOutlineGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTPixmapGlyph.h b/src/ext/ftgl/FTGL/FTPixmapGlyph.h
new file mode 100644
index 0000000..d9a317f
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTPixmapGlyph.h
@@ -0,0 +1,82 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTPixmapGlyph__
+#define __FTPixmapGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTPixmapGlyph is a specialisation of FTGlyph for creating pixmaps.
+ */
+class  FTGL_EXPORT FTPixmapGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor
+         *
+         * @param glyph The Freetype glyph to be processed
+         */
+        FTPixmapGlyph(FT_GlyphSlot glyph);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTPixmapGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialisation of FTGLglyph for creating pixmaps.
+ *
+ * @param glyph The Freetype glyph to be processed
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreatePixmapGlyph(FT_GlyphSlot glyph);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTPixmapGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTPoint.h b/src/ext/ftgl/FTGL/FTPoint.h
new file mode 100644
index 0000000..fef4af6
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTPoint.h
@@ -0,0 +1,274 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTPoint__
+#define __FTPoint__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTPoint class is a basic 3-dimensional point or vector.
+ */
+class FTGL_EXPORT FTPoint
+{
+    public:
+        /**
+         * Default constructor. Point is set to zero.
+         */
+        inline FTPoint()
+        {
+            values[0] = 0;
+            values[1] = 0;
+            values[2] = 0;
+        }
+
+        /**
+         * Constructor. Z coordinate is set to zero if unspecified.
+         *
+         * @param x First component
+         * @param y Second component
+         * @param z Third component
+         */
+        inline FTPoint(const FTGL_DOUBLE x, const FTGL_DOUBLE y,
+                       const FTGL_DOUBLE z = 0)
+        {
+            values[0] = x;
+            values[1] = y;
+            values[2] = z;
+        }
+
+        /**
+         * Constructor. This converts an FT_Vector to an FTPoint
+         *
+         * @param ft_vector A freetype vector
+         */
+        inline FTPoint(const FT_Vector& ft_vector)
+        {
+            values[0] = ft_vector.x;
+            values[1] = ft_vector.y;
+            values[2] = 0;
+        }
+
+        /**
+         * Normalise a point's coordinates. If the coordinates are zero,
+         * the point is left untouched.
+         *
+         * @return A vector of norm one.
+         */
+        FTPoint Normalise();
+
+
+        /**
+         * Operator += In Place Addition.
+         *
+         * @param point
+         * @return this plus point.
+         */
+        inline FTPoint& operator += (const FTPoint& point)
+        {
+            values[0] += point.values[0];
+            values[1] += point.values[1];
+            values[2] += point.values[2];
+
+            return *this;
+        }
+
+        /**
+         * Operator +
+         *
+         * @param point
+         * @return this plus point.
+         */
+        inline FTPoint operator + (const FTPoint& point) const
+        {
+            FTPoint temp;
+            temp.values[0] = values[0] + point.values[0];
+            temp.values[1] = values[1] + point.values[1];
+            temp.values[2] = values[2] + point.values[2];
+
+            return temp;
+        }
+
+         /**
+         * Operator -= In Place Substraction.
+         *
+         * @param point
+         * @return this minus point.
+         */
+        inline FTPoint& operator -= (const FTPoint& point)
+        {
+            values[0] -= point.values[0];
+            values[1] -= point.values[1];
+            values[2] -= point.values[2];
+
+            return *this;
+        }
+
+        /**
+         * Operator -
+         *
+         * @param point
+         * @return this minus point.
+         */
+        inline FTPoint operator - (const FTPoint& point) const
+        {
+            FTPoint temp;
+            temp.values[0] = values[0] - point.values[0];
+            temp.values[1] = values[1] - point.values[1];
+            temp.values[2] = values[2] - point.values[2];
+
+            return temp;
+        }
+
+        /**
+         * Operator *  Scalar multiplication
+         *
+         * @param multiplier
+         * @return <code>this</code> multiplied by <code>multiplier</code>.
+         */
+        inline FTPoint operator * (double multiplier) const
+        {
+            FTPoint temp;
+            temp.values[0] = values[0] * multiplier;
+            temp.values[1] = values[1] * multiplier;
+            temp.values[2] = values[2] * multiplier;
+
+            return temp;
+        }
+
+
+        /**
+         * Operator *  Scalar multiplication
+         *
+         * @param point
+         * @param multiplier
+         * @return <code>multiplier</code> multiplied by <code>point</code>.
+         */
+        inline friend FTPoint operator * (double multiplier, FTPoint& point)
+        {
+            return point * multiplier;
+        }
+
+
+        /**
+         * Operator *  Scalar product
+         *
+         * @param a  First vector.
+         * @param b  Second vector.
+         * @return  <code>a.b</code> scalar product.
+         */
+        inline friend double operator * (FTPoint &a, FTPoint& b)
+        {
+            return a.values[0] * b.values[0]
+                 + a.values[1] * b.values[1]
+                 + a.values[2] * b.values[2];
+        }
+
+
+        /**
+         * Operator ^  Vector product
+         *
+         * @param point Second point
+         * @return this vector point.
+         */
+        inline FTPoint operator ^ (const FTPoint& point)
+        {
+            FTPoint temp;
+            temp.values[0] = values[1] * point.values[2]
+                              - values[2] * point.values[1];
+            temp.values[1] = values[2] * point.values[0]
+                              - values[0] * point.values[2];
+            temp.values[2] = values[0] * point.values[1]
+                              - values[1] * point.values[0];
+            return temp;
+        }
+
+
+        /**
+         * Operator == Tests for equality
+         *
+         * @param a
+         * @param b
+         * @return true if a & b are equal
+         */
+        friend bool operator == (const FTPoint &a, const FTPoint &b);
+
+
+        /**
+         * Operator != Tests for non equality
+         *
+         * @param a
+         * @param b
+         * @return true if a & b are not equal
+         */
+        friend bool operator != (const FTPoint &a, const FTPoint &b);
+
+
+        /**
+         * Cast to FTGL_DOUBLE*
+         */
+        inline operator const FTGL_DOUBLE*() const
+        {
+            return values;
+        }
+
+
+        /**
+         * Setters
+         */
+        inline void X(FTGL_DOUBLE x) { values[0] = x; };
+        inline void Y(FTGL_DOUBLE y) { values[1] = y; };
+        inline void Z(FTGL_DOUBLE z) { values[2] = z; };
+
+
+        /**
+         * Getters
+         */
+        inline FTGL_DOUBLE X() const { return values[0]; };
+        inline FTGL_DOUBLE Y() const { return values[1]; };
+        inline FTGL_DOUBLE Z() const { return values[2]; };
+        inline FTGL_FLOAT Xf() const { return static_cast<FTGL_FLOAT>(values[0]); };
+        inline FTGL_FLOAT Yf() const { return static_cast<FTGL_FLOAT>(values[1]); };
+        inline FTGL_FLOAT Zf() const { return static_cast<FTGL_FLOAT>(values[2]); };
+
+    private:
+        /**
+         * The point data
+         */
+        FTGL_DOUBLE values[3];
+};
+
+#endif //__cplusplus
+
+#endif  //  __FTPoint__
+
diff --git a/src/ext/ftgl/FTGL/FTPolyGlyph.h b/src/ext/ftgl/FTGL/FTPolyGlyph.h
new file mode 100644
index 0000000..ce3b000
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTPolyGlyph.h
@@ -0,0 +1,98 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTPolygonGlyph__
+#define __FTPolygonGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTPolygonGlyph is a specialisation of FTGlyph for creating tessellated
+ * polygon glyphs.
+ */
+class FTGL_EXPORT FTPolygonGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor. Sets the Error to Invalid_Outline if the glyphs
+         * isn't an outline.
+         *
+         * @param glyph The Freetype glyph to be processed
+         * @param outset  The outset distance
+         * @param useDisplayList Enable or disable the use of Display Lists
+         *                       for this glyph
+         *                       <code>true</code> turns ON display lists.
+         *                       <code>false</code> turns OFF display lists.
+         */
+        FTPolygonGlyph(FT_GlyphSlot glyph, float outset, bool useDisplayList);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTPolygonGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#define FTPolyGlyph FTPolygonGlyph
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialisation of FTGLglyph for creating tessellated
+ * polygon glyphs.
+ *
+ * @param glyph The Freetype glyph to be processed
+ * @param outset outset contour size
+ * @param useDisplayList Enable or disable the use of Display Lists
+ *                       for this glyph
+ *                       <code>true</code> turns ON display lists.
+ *                       <code>false</code> turns OFF display lists.
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreatePolygonGlyph(FT_GlyphSlot glyph, float outset,
+                                              int useDisplayList);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTPolygonGlyph__
+
diff --git a/src/ext/ftgl/FTGL/FTSimpleLayout.h b/src/ext/ftgl/FTGL/FTSimpleLayout.h
new file mode 100644
index 0000000..c778b18
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTSimpleLayout.h
@@ -0,0 +1,191 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTSimpleLayout__
+#define __FTSimpleLayout__
+
+#ifdef __cplusplus
+
+
+class FTFont;
+
+/**
+ * FTSimpleLayout is a specialisation of FTLayout for simple text boxes.
+ *
+ * This class has basic support for text wrapping, left, right and centered
+ * alignment, and text justification.
+ *
+ * @see     FTLayout
+ */
+class FTGL_EXPORT FTSimpleLayout : public FTLayout
+{
+    public:
+        /**
+         * Initializes line spacing to 1.0, alignment to
+         * ALIGN_LEFT and wrap to 100.0
+         */
+        FTSimpleLayout();
+
+        /**
+         * Destructor
+         */
+        ~FTSimpleLayout();
+
+        /**
+         * Get the bounding box for a formatted string.
+         *
+         * @param string  A char string.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @return  The corresponding bounding box.
+         */
+        virtual FTBBox BBox(const char* string, const int len = -1,
+                            FTPoint position = FTPoint());
+
+        /**
+         * Get the bounding box for a formatted string.
+         *
+         * @param string  A wchar_t string.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be checked until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @return  The corresponding bounding box.
+         */
+        virtual FTBBox BBox(const wchar_t* string, const int len = -1,
+                            FTPoint position = FTPoint());
+
+        /**
+         * Render a string of characters.
+         *
+         * @param string    'C' style string to be output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param renderMode  Render mode to display (optional)
+         */
+        virtual void Render(const char *string, const int len = -1,
+                            FTPoint position = FTPoint(),
+                            int renderMode = FTGL::RENDER_ALL);
+
+        /**
+         * Render a string of characters.
+         *
+         * @param string    wchar_t string to be output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered
+         *             (optional).
+         * @param position  The pen position of the first character (optional).
+         * @param renderMode  Render mode to display (optional)
+         */
+        virtual void Render(const wchar_t *string, const int len = -1,
+                            FTPoint position = FTPoint(),
+                            int renderMode = FTGL::RENDER_ALL);
+
+        /**
+         * Set the font to use for rendering the text.
+         *
+         * @param fontInit A pointer to the new font.  The font is
+         *                 referenced by this but will not be
+         *                 disposed of when this is deleted.
+         */
+        void SetFont(FTFont *fontInit);
+
+        /**
+         * @return The current font.
+         */
+        FTFont *GetFont();
+
+        /**
+         * The maximum line length for formatting text.
+         *
+         * @param LineLength The new line length.
+         */
+        void SetLineLength(const float LineLength);
+
+        /**
+         * @return The current line length.
+         */
+        float GetLineLength() const;
+
+        /**
+         * The text alignment mode used to distribute
+         * space within a line or rendered text.
+         *
+         * @param Alignment The new alignment mode.
+         */
+        void SetAlignment(const FTGL::TextAlignment Alignment);
+
+        /**
+         * @return The text alignment mode.
+         */
+        FTGL::TextAlignment GetAlignment() const;
+
+        /**
+         * Sets the line height.
+         *
+         * @param LineSpacing The height of each line of text expressed as
+         *                    a percentage of the current fonts line height.
+         */
+        void SetLineSpacing(const float LineSpacing);
+
+        /**
+         * @return The line spacing.
+         */
+        float GetLineSpacing() const;
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+FTGL_EXPORT FTGLlayout *ftglCreateSimpleLayout(void);
+
+FTGL_EXPORT void ftglSetLayoutFont(FTGLlayout *, FTGLfont*);
+FTGL_EXPORT FTGLfont *ftglGetLayoutFont(FTGLlayout *);
+
+FTGL_EXPORT void ftglSetLayoutLineLength(FTGLlayout *, const float);
+FTGL_EXPORT float ftglGetLayoutLineLength(FTGLlayout *);
+
+FTGL_EXPORT void ftglSetLayoutAlignment(FTGLlayout *, const int);
+FTGL_EXPORT int ftglGetLayoutAlignement(FTGLlayout *);
+
+FTGL_EXPORT void ftglSetLayoutLineSpacing(FTGLlayout *, const float);
+FTGL_EXPORT float ftglGetLayoutLineSpacing(FTGLlayout *);
+
+FTGL_END_C_DECLS
+
+#endif  /* __FTSimpleLayout__ */
+
diff --git a/src/ext/ftgl/FTGL/FTTextureGlyph.h b/src/ext/ftgl/FTGL/FTTextureGlyph.h
new file mode 100644
index 0000000..ec545f3
--- /dev/null
+++ b/src/ext/ftgl/FTGL/FTTextureGlyph.h
@@ -0,0 +1,99 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#   warning This header is deprecated. Please use <FTGL/ftgl.h> from now.
+#   include <FTGL/ftgl.h>
+#endif
+
+#ifndef __FTTextureGlyph__
+#define __FTTextureGlyph__
+
+#ifdef __cplusplus
+
+
+/**
+ * FTTextureGlyph is a specialisation of FTGlyph for creating texture
+ * glyphs.
+ */
+class FTGL_EXPORT FTTextureGlyph : public FTGlyph
+{
+    public:
+        /**
+         * Constructor
+         *
+         * @param glyph     The Freetype glyph to be processed
+         * @param id        The id of the texture that this glyph will be
+         *                  drawn in
+         * @param xOffset   The x offset into the parent texture to draw
+         *                  this glyph
+         * @param yOffset   The y offset into the parent texture to draw
+         *                  this glyph
+         * @param width     The width of the parent texture
+         * @param height    The height (number of rows) of the parent texture
+         */
+        FTTextureGlyph(FT_GlyphSlot glyph, int id, int xOffset, int yOffset,
+                       int width, int height);
+
+        /**
+         * Destructor
+         */
+        virtual ~FTTextureGlyph();
+
+        /**
+         * Render this glyph at the current pen position.
+         *
+         * @param pen  The current pen position.
+         * @param renderMode  Render mode to display
+         * @return  The advance distance for this glyph.
+         */
+        virtual const FTPoint& Render(const FTPoint& pen, int renderMode);
+};
+
+#endif //__cplusplus
+
+FTGL_BEGIN_C_DECLS
+
+/**
+ * Create a specialisation of FTGLglyph for creating pixmaps.
+ *
+ * @param glyph The Freetype glyph to be processed.
+ * @param id  The id of the texture that this glyph will be drawn in.
+ * @param xOffset  The x offset into the parent texture to draw this glyph.
+ * @param yOffset  The y offset into the parent texture to draw this glyph.
+ * @param width  The width of the parent texture.
+ * @param height  The height (number of rows) of the parent texture.
+ * @return  An FTGLglyph* object.
+ */
+FTGL_EXPORT FTGLglyph *ftglCreateTextureGlyph(FT_GlyphSlot glyph, int id,
+                                              int xOffset, int yOffset,
+                                              int width, int height);
+
+FTGL_END_C_DECLS
+
+#endif  //  __FTTextureGlyph__
+
diff --git a/src/ext/ftgl/FTGL/ftgl.h b/src/ext/ftgl/FTGL/ftgl.h
new file mode 100644
index 0000000..f5d043c
--- /dev/null
+++ b/src/ext/ftgl/FTGL/ftgl.h
@@ -0,0 +1,135 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ * Copyright (c) 2008 Sean Morrison <learner at brlcad.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __ftgl__
+#define __ftgl__
+
+/* We need the Freetype headers */
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+#include FT_OUTLINE_H
+
+/* Floating point types used by the library */
+typedef double   FTGL_DOUBLE;
+typedef float    FTGL_FLOAT;
+
+/* Macros used to declare C-linkage types and symbols */
+#ifdef __cplusplus
+#   define FTGL_BEGIN_C_DECLS extern "C" { namespace FTGL {
+#   define FTGL_END_C_DECLS } }
+#else
+#   define FTGL_BEGIN_C_DECLS
+#   define FTGL_END_C_DECLS
+#endif
+
+#ifdef __cplusplus
+namespace FTGL
+{
+    typedef enum
+    {
+        RENDER_FRONT = 0x0001,
+        RENDER_BACK  = 0x0002,
+        RENDER_SIDE  = 0x0004,
+        RENDER_ALL   = 0xffff
+    } RenderMode;
+
+    typedef enum
+    {
+        ALIGN_LEFT    = 0,
+        ALIGN_CENTER  = 1,
+        ALIGN_RIGHT   = 2,
+        ALIGN_JUSTIFY = 3
+    } TextAlignment;
+}
+#else
+#   define FTGL_RENDER_FRONT 0x0001
+#   define FTGL_RENDER_BACK  0x0002
+#   define FTGL_RENDER_SIDE  0x0004
+#   define FTGL_RENDER_ALL   0xffff
+
+#   define FTGL_ALIGN_LEFT    0
+#   define FTGL_ALIGN_CENTER  1
+#   define FTGL_ALIGN_RIGHT   2
+#   define FTGL_ALIGN_JUSTIFY 3
+#endif
+
+// Compiler-specific conditional compilation
+#ifdef _MSC_VER // MS Visual C++
+
+    // Disable various warning.
+    // 4786: template name too long
+    #pragma warning(disable : 4251)
+    #pragma warning(disable : 4275)
+    #pragma warning(disable : 4786)
+
+    // The following definitions control how symbols are exported.
+    // If the target is a static library ensure that FTGL_LIBRARY_STATIC
+    // is defined. If building a dynamic library (ie DLL) ensure the
+    // FTGL_LIBRARY macro is defined, as it will mark symbols for
+    // export. If compiling a project to _use_ the _dynamic_ library
+    // version of the library, no definition is required.
+    #ifdef FTGL_LIBRARY_STATIC      // static lib - no special export required
+    #  define FTGL_EXPORT
+    #elif FTGL_LIBRARY              // dynamic lib - must export/import symbols appropriately.
+    #  define FTGL_EXPORT   __declspec(dllexport)
+    #else
+    #  define FTGL_EXPORT   __declspec(dllimport)
+    #endif
+
+#else
+    // Compiler that is not MS Visual C++.
+    // Ensure that the export symbol is defined (and blank)
+    #define FTGL_EXPORT
+#endif
+
+#include <FTGL/FTPoint.h>
+#include <FTGL/FTBBox.h>
+#include <FTGL/FTBuffer.h>
+
+#include <FTGL/FTGlyph.h>
+#include <FTGL/FTBitmapGlyph.h>
+#include <FTGL/FTBufferGlyph.h>
+#include <FTGL/FTExtrdGlyph.h>
+#include <FTGL/FTOutlineGlyph.h>
+#include <FTGL/FTPixmapGlyph.h>
+#include <FTGL/FTPolyGlyph.h>
+#include <FTGL/FTTextureGlyph.h>
+
+#include <FTGL/FTFont.h>
+#include <FTGL/FTGLBitmapFont.h>
+#include <FTGL/FTBufferFont.h>
+#include <FTGL/FTGLExtrdFont.h>
+#include <FTGL/FTGLOutlineFont.h>
+#include <FTGL/FTGLPixmapFont.h>
+#include <FTGL/FTGLPolygonFont.h>
+#include <FTGL/FTGLTextureFont.h>
+
+#include <FTGL/FTLayout.h>
+#include <FTGL/FTSimpleLayout.h>
+
+#endif  //  __ftgl__
diff --git a/src/ext/ftgl/FTGlyph/FTBitmapGlyph.cpp b/src/ext/ftgl/FTGlyph/FTBitmapGlyph.cpp
new file mode 100644
index 0000000..989c890
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTBitmapGlyph.cpp
@@ -0,0 +1,128 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <string>
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTBitmapGlyphImpl.h"
+
+
+//
+//  FTGLBitmapGlyph
+//
+
+
+FTBitmapGlyph::FTBitmapGlyph(FT_GlyphSlot glyph) :
+    FTGlyph(new FTBitmapGlyphImpl(glyph))
+{}
+
+
+FTBitmapGlyph::~FTBitmapGlyph()
+{}
+
+
+const FTPoint& FTBitmapGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTBitmapGlyphImpl *myimpl = dynamic_cast<FTBitmapGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLBitmapGlyphImpl
+//
+
+
+FTBitmapGlyphImpl::FTBitmapGlyphImpl(FT_GlyphSlot glyph)
+:   FTGlyphImpl(glyph),
+    destWidth(0),
+    destHeight(0),
+    data(0)
+{
+    err = FT_Render_Glyph(glyph, FT_RENDER_MODE_MONO);
+    if(err || ft_glyph_format_bitmap != glyph->format)
+    {
+        return;
+    }
+
+    FT_Bitmap bitmap = glyph->bitmap;
+
+    unsigned int srcWidth = bitmap.width;
+    unsigned int srcHeight = bitmap.rows;
+    unsigned int srcPitch = bitmap.pitch;
+
+    destWidth = srcWidth;
+    destHeight = srcHeight;
+    destPitch = srcPitch;
+
+    if(destWidth && destHeight)
+    {
+        data = new unsigned char[destPitch * destHeight];
+        unsigned char* dest = data + ((destHeight - 1) * destPitch);
+
+        unsigned char* src = bitmap.buffer;
+
+        for(unsigned int y = 0; y < srcHeight; ++y)
+        {
+            memcpy(dest, src, srcPitch);
+            dest -= destPitch;
+            src += srcPitch;
+        }
+    }
+
+    pos = FTPoint(glyph->bitmap_left, static_cast<int>(srcHeight) - glyph->bitmap_top, 0.0);
+}
+
+
+FTBitmapGlyphImpl::~FTBitmapGlyphImpl()
+{
+    delete [] data;
+}
+
+
+const FTPoint& FTBitmapGlyphImpl::RenderImpl(const FTPoint& pen, int renderMode)
+{
+    if(data)
+    {
+        float dx, dy;
+
+        dx = pen.Xf() + pos.Xf();
+        dy = pen.Yf() - pos.Yf();
+
+        glBitmap(0, 0, 0.0f, 0.0f, dx, dy, (const GLubyte*)0);
+        glPixelStorei(GL_UNPACK_ROW_LENGTH, destPitch * 8);
+        glBitmap(destWidth, destHeight, 0.0f, 0.0, 0.0, 0.0,
+                 (const GLubyte*)data);
+        glBitmap(0, 0, 0.0f, 0.0f, -dx, -dy, (const GLubyte*)0);
+    }
+
+    return advance;
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTBitmapGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTBitmapGlyphImpl.h
new file mode 100644
index 0000000..c61a679
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTBitmapGlyphImpl.h
@@ -0,0 +1,71 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTBitmapGlyphImpl__
+#define __FTBitmapGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTBitmapGlyphImpl : public FTGlyphImpl
+{
+    friend class FTBitmapGlyph;
+
+    protected:
+        FTBitmapGlyphImpl(FT_GlyphSlot glyph);
+
+        virtual ~FTBitmapGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        /**
+         * The width of the glyph 'image'
+         */
+        unsigned int destWidth;
+
+        /**
+         * The height of the glyph 'image'
+         */
+        unsigned int destHeight;
+
+        /**
+         * The pitch of the glyph 'image'
+         */
+        unsigned int destPitch;
+
+        /**
+         * Vector from the pen position to the topleft corner of the bitmap
+         */
+        FTPoint pos;
+
+        /**
+         * Pointer to the 'image' data
+         */
+        unsigned char* data;
+};
+
+#endif  //  __FTBitmapGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTBufferGlyph.cpp b/src/ext/ftgl/FTGlyph/FTBufferGlyph.cpp
new file mode 100644
index 0000000..7a78b0e
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTBufferGlyph.cpp
@@ -0,0 +1,121 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <string>
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTBufferGlyphImpl.h"
+
+
+//
+//  FTGLBufferGlyph
+//
+
+
+FTBufferGlyph::FTBufferGlyph(FT_GlyphSlot glyph, FTBuffer *buffer) :
+    FTGlyph(new FTBufferGlyphImpl(glyph, buffer))
+{}
+
+
+FTBufferGlyph::~FTBufferGlyph()
+{}
+
+
+const FTPoint& FTBufferGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTBufferGlyphImpl *myimpl = dynamic_cast<FTBufferGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLBufferGlyphImpl
+//
+
+
+FTBufferGlyphImpl::FTBufferGlyphImpl(FT_GlyphSlot glyph, FTBuffer *p)
+:   FTGlyphImpl(glyph),
+    has_bitmap(false),
+    buffer(p)
+{
+    err = FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL);
+    if(err || glyph->format != ft_glyph_format_bitmap)
+    {
+        return;
+    }
+
+    bitmap = glyph->bitmap;
+    pixels = new unsigned char[bitmap.pitch * bitmap.rows];
+    memcpy(pixels, bitmap.buffer, bitmap.pitch * bitmap.rows);
+
+    if(bitmap.width && bitmap.rows)
+    {
+        has_bitmap = true;
+        corner = FTPoint(glyph->bitmap_left, glyph->bitmap_top);
+    }
+}
+
+
+FTBufferGlyphImpl::~FTBufferGlyphImpl()
+{
+    delete[] pixels;
+}
+
+
+const FTPoint& FTBufferGlyphImpl::RenderImpl(const FTPoint& pen, int renderMode)
+{
+    if(has_bitmap)
+    {
+        FTPoint pos(buffer->Pos() + pen + corner);
+        int dx = (int)(pos.Xf() + 0.5f);
+        int dy = buffer->Height() - (int)(pos.Yf() + 0.5f);
+        unsigned char * dest = buffer->Pixels() + dx + dy * buffer->Width();
+
+        for(int y = 0; y < bitmap.rows; y++)
+        {
+            // FIXME: change the loop bounds instead of doing this test
+            if(y + dy < 0 || y + dy >= buffer->Height()) continue;
+
+            for(int x = 0; x < bitmap.width; x++)
+            {
+                if(x + dx < 0 || x + dx >= buffer->Width()) continue;
+
+                unsigned char p = pixels[y * bitmap.pitch + x];
+
+                if(p)
+                {
+                    dest[y * buffer->Width() + x] = p;
+                }
+            }
+        }
+    }
+
+    return advance;
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTBufferGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTBufferGlyphImpl.h
new file mode 100644
index 0000000..5a15049
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTBufferGlyphImpl.h
@@ -0,0 +1,52 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTBufferGlyphImpl__
+#define __FTBufferGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTBufferGlyphImpl : public FTGlyphImpl
+{
+    friend class FTBufferGlyph;
+
+    protected:
+        FTBufferGlyphImpl(FT_GlyphSlot glyph, FTBuffer *p);
+
+        virtual ~FTBufferGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        bool has_bitmap;
+        FT_Bitmap bitmap;
+        unsigned char *pixels;
+        FTPoint corner;
+
+        FTBuffer *buffer;
+};
+
+#endif  //  __FTBufferGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTExtrudeGlyph.cpp b/src/ext/ftgl/FTGlyph/FTExtrudeGlyph.cpp
new file mode 100644
index 0000000..df0496e
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTExtrudeGlyph.cpp
@@ -0,0 +1,265 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <iostream>
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTExtrudeGlyphImpl.h"
+#include "FTVectoriser.h"
+
+
+//
+//  FTGLExtrudeGlyph
+//
+
+
+FTExtrudeGlyph::FTExtrudeGlyph(FT_GlyphSlot glyph, float depth,
+                               float frontOutset, float backOutset,
+                               bool useDisplayList) :
+    FTGlyph(new FTExtrudeGlyphImpl(glyph, depth, frontOutset, backOutset,
+                                   useDisplayList))
+{}
+
+
+FTExtrudeGlyph::~FTExtrudeGlyph()
+{}
+
+
+const FTPoint& FTExtrudeGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTExtrudeGlyphImpl *myimpl = dynamic_cast<FTExtrudeGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLExtrudeGlyphImpl
+//
+
+
+FTExtrudeGlyphImpl::FTExtrudeGlyphImpl(FT_GlyphSlot glyph, float _depth,
+                                       float _frontOutset, float _backOutset,
+                                       bool useDisplayList)
+:   FTGlyphImpl(glyph),
+    vectoriser(0),
+    glList(0)
+{
+    bBox.SetDepth(-_depth);
+
+    if(ft_glyph_format_outline != glyph->format)
+    {
+        err = 0x14; // Invalid_Outline
+        return;
+    }
+
+    vectoriser = new FTVectoriser(glyph);
+
+    if((vectoriser->ContourCount() < 1) || (vectoriser->PointCount() < 3))
+    {
+        delete vectoriser;
+        vectoriser = NULL;
+        return;
+    }
+
+    hscale = glyph->face->size->metrics.x_ppem * 64;
+    vscale = glyph->face->size->metrics.y_ppem * 64;
+    depth = _depth;
+    frontOutset = _frontOutset;
+    backOutset = _backOutset;
+
+    if(useDisplayList)
+    {
+        glList = glGenLists(3);
+
+        /* Front face */
+        glNewList(glList + 0, GL_COMPILE);
+        RenderFront();
+        glEndList();
+
+        /* Back face */
+        glNewList(glList + 1, GL_COMPILE);
+        RenderBack();
+        glEndList();
+
+        /* Side face */
+        glNewList(glList + 2, GL_COMPILE);
+        RenderSide();
+        glEndList();
+
+        delete vectoriser;
+        vectoriser = NULL;
+    }
+}
+
+
+FTExtrudeGlyphImpl::~FTExtrudeGlyphImpl()
+{
+    if(glList)
+    {
+        glDeleteLists(glList, 3);
+    }
+    else if(vectoriser)
+    {
+        delete vectoriser;
+    }
+}
+
+
+const FTPoint& FTExtrudeGlyphImpl::RenderImpl(const FTPoint& pen,
+                                              int renderMode)
+{
+    glTranslatef(pen.Xf(), pen.Yf(), pen.Zf());
+    if(glList)
+    {
+        if(renderMode & FTGL::RENDER_FRONT)
+            glCallList(glList + 0);
+        if(renderMode & FTGL::RENDER_BACK)
+            glCallList(glList + 1);
+        if(renderMode & FTGL::RENDER_SIDE)
+            glCallList(glList + 2);
+    }
+    else if(vectoriser)
+    {
+        if(renderMode & FTGL::RENDER_FRONT)
+            RenderFront();
+        if(renderMode & FTGL::RENDER_BACK)
+            RenderBack();
+        if(renderMode & FTGL::RENDER_SIDE)
+            RenderSide();
+    }
+    glTranslatef(-pen.Xf(), -pen.Yf(), -pen.Zf());
+
+    return advance;
+}
+
+
+void FTExtrudeGlyphImpl::RenderFront()
+{
+    vectoriser->MakeMesh(1.0, 1, frontOutset);
+    glNormal3d(0.0, 0.0, 1.0);
+
+    const FTMesh *mesh = vectoriser->GetMesh();
+    for(unsigned int j = 0; j < mesh->TesselationCount(); ++j)
+    {
+        const FTTesselation* subMesh = mesh->Tesselation(j);
+        unsigned int polygonType = subMesh->PolygonType();
+
+        glBegin(polygonType);
+            for(unsigned int i = 0; i < subMesh->PointCount(); ++i)
+            {
+                FTPoint pt = subMesh->Point(i);
+
+                glTexCoord2f(pt.Xf() / hscale,
+                             pt.Yf() / vscale);
+
+                glVertex3f(pt.Xf() / 64.0f,
+                           pt.Yf() / 64.0f,
+                           0.0f);
+            }
+        glEnd();
+    }
+}
+
+
+void FTExtrudeGlyphImpl::RenderBack()
+{
+    vectoriser->MakeMesh(-1.0, 2, backOutset);
+    glNormal3d(0.0, 0.0, -1.0);
+
+    const FTMesh *mesh = vectoriser->GetMesh();
+    for(unsigned int j = 0; j < mesh->TesselationCount(); ++j)
+    {
+        const FTTesselation* subMesh = mesh->Tesselation(j);
+        unsigned int polygonType = subMesh->PolygonType();
+
+        glBegin(polygonType);
+            for(unsigned int i = 0; i < subMesh->PointCount(); ++i)
+            {
+                FTPoint pt = subMesh->Point(i);
+
+                glTexCoord2f(subMesh->Point(i).Xf() / hscale,
+                             subMesh->Point(i).Yf() / vscale);
+
+                glVertex3f(subMesh->Point(i).Xf() / 64.0f,
+                           subMesh->Point(i).Yf() / 64.0f,
+                           -depth);
+            }
+        glEnd();
+    }
+}
+
+
+void FTExtrudeGlyphImpl::RenderSide()
+{
+    int contourFlag = vectoriser->ContourFlag();
+
+    for(size_t c = 0; c < vectoriser->ContourCount(); ++c)
+    {
+        const FTContour* contour = vectoriser->Contour(c);
+        size_t n = contour->PointCount();
+
+        if(n < 2)
+        {
+            continue;
+        }
+
+        glBegin(GL_QUAD_STRIP);
+            for(size_t j = 0; j <= n; ++j)
+            {
+                size_t cur = (j == n) ? 0 : j;
+                size_t next = (cur == n - 1) ? 0 : cur + 1;
+
+                FTPoint frontPt = contour->FrontPoint(cur);
+                FTPoint nextPt = contour->FrontPoint(next);
+                FTPoint backPt = contour->BackPoint(cur);
+
+                FTPoint normal = FTPoint(0.f, 0.f, 1.f) ^ (frontPt - nextPt);
+                if(normal != FTPoint(0.0f, 0.0f, 0.0f))
+                {
+                    glNormal3dv(static_cast<const FTGL_DOUBLE*>(normal.Normalise()));
+                }
+
+                glTexCoord2f(frontPt.Xf() / hscale, frontPt.Yf() / vscale);
+
+                if(contourFlag & ft_outline_reverse_fill)
+                {
+                    glVertex3f(backPt.Xf() / 64.0f, backPt.Yf() / 64.0f, 0.0f);
+                    glVertex3f(frontPt.Xf() / 64.0f, frontPt.Yf() / 64.0f, -depth);
+                }
+                else
+                {
+                    glVertex3f(backPt.Xf() / 64.0f, backPt.Yf() / 64.0f, -depth);
+                    glVertex3f(frontPt.Xf() / 64.0f, frontPt.Yf() / 64.0f, 0.0f);
+                }
+            }
+        glEnd();
+    }
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTExtrudeGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTExtrudeGlyphImpl.h
new file mode 100644
index 0000000..7c547c7
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTExtrudeGlyphImpl.h
@@ -0,0 +1,69 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTExtrudeGlyphImpl__
+#define __FTExtrudeGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTVectoriser;
+
+class FTExtrudeGlyphImpl : public FTGlyphImpl
+{
+    friend class FTExtrudeGlyph;
+
+    protected:
+        FTExtrudeGlyphImpl(FT_GlyphSlot glyph, float depth, float frontOutset,
+                           float backOutset, bool useDisplayList);
+
+        virtual ~FTExtrudeGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        /**
+         * Private rendering methods.
+         */
+        void RenderFront();
+        void RenderBack();
+        void RenderSide();
+
+        /**
+         * Private rendering variables.
+         */
+        unsigned int hscale, vscale;
+        float depth;
+        float frontOutset, backOutset;
+        FTVectoriser *vectoriser;
+
+        /**
+         * OpenGL display list
+         */
+        GLuint glList;
+};
+
+#endif  //  __FTExtrudeGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTGlyph.cpp b/src/ext/ftgl/FTGlyph/FTGlyph.cpp
new file mode 100644
index 0000000..4d3dff6
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTGlyph.cpp
@@ -0,0 +1,112 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTGlyphImpl.h"
+
+
+//
+//  FTGlyph
+//
+
+
+FTGlyph::FTGlyph(FT_GlyphSlot glyph)
+{
+    impl = new FTGlyphImpl(glyph);
+}
+
+
+FTGlyph::FTGlyph(FTGlyphImpl *pImpl)
+{
+    impl = pImpl;
+}
+
+
+FTGlyph::~FTGlyph()
+{
+    delete impl;
+}
+
+
+float FTGlyph::Advance() const
+{
+    return impl->Advance();
+}
+
+
+const FTBBox& FTGlyph::BBox() const
+{
+    return impl->BBox();
+}
+
+
+FT_Error FTGlyph::Error() const
+{
+    return impl->Error();
+}
+
+
+//
+//  FTGlyphImpl
+//
+
+
+FTGlyphImpl::FTGlyphImpl(FT_GlyphSlot glyph, bool useList) : err(0)
+{
+    if(glyph)
+    {
+        bBox = FTBBox(glyph);
+        advance = FTPoint(glyph->advance.x / 64.0f,
+                          glyph->advance.y / 64.0f);
+    }
+}
+
+
+FTGlyphImpl::~FTGlyphImpl()
+{}
+
+
+float FTGlyphImpl::Advance() const
+{
+    return advance.Xf();
+}
+
+
+const FTBBox& FTGlyphImpl::BBox() const
+{
+    return bBox;
+}
+
+
+FT_Error FTGlyphImpl::Error() const
+{
+    return err;
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTGlyphGlue.cpp b/src/ext/ftgl/FTGlyph/FTGlyphGlue.cpp
new file mode 100644
index 0000000..0fbbc01
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTGlyphGlue.cpp
@@ -0,0 +1,198 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+
+static const FTPoint static_ftpoint;
+static const FTBBox static_ftbbox;
+
+FTGL_BEGIN_C_DECLS
+
+#define C_TOR(cname, cargs, cxxname, cxxarg, cxxtype) \
+    FTGLglyph* cname cargs \
+    { \
+        cxxname *g = new cxxname cxxarg; \
+        if(g->Error()) \
+        { \
+            delete g; \
+            return NULL; \
+        } \
+        FTGLglyph *ftgl = (FTGLglyph *)malloc(sizeof(FTGLglyph)); \
+        ftgl->ptr = g; \
+        ftgl->type = cxxtype; \
+        return ftgl; \
+    }
+
+// FTBitmapGlyph::FTBitmapGlyph();
+C_TOR(ftglCreateBitmapGlyph, (FT_GlyphSlot glyph),
+      FTBitmapGlyph, (glyph), GLYPH_BITMAP);
+
+// FTBufferGlyph::FTBufferGlyph();
+// FIXME: not implemented
+
+// FTExtrudeGlyph::FTExtrudeGlyph();
+C_TOR(ftglCreateExtrudeGlyph, (FT_GlyphSlot glyph, float depth,
+                   float frontOutset, float backOutset, int useDisplayList),
+      FTExtrudeGlyph, (glyph, depth, frontOutset, backOutset, (useDisplayList != 0)),
+      GLYPH_EXTRUDE);
+
+// FTOutlineGlyph::FTOutlineGlyph();
+C_TOR(ftglCreateOutlineGlyph, (FT_GlyphSlot glyph, float outset,
+                               int useDisplayList),
+      FTOutlineGlyph, (glyph, outset, (useDisplayList != 0)), GLYPH_OUTLINE);
+
+// FTPixmapGlyph::FTPixmapGlyph();
+C_TOR(ftglCreatePixmapGlyph, (FT_GlyphSlot glyph),
+      FTPixmapGlyph, (glyph), GLYPH_PIXMAP);
+
+// FTPolygonGlyph::FTPolygonGlyph();
+C_TOR(ftglCreatePolygonGlyph, (FT_GlyphSlot glyph, float outset,
+                               int useDisplayList),
+      FTPolygonGlyph, (glyph, outset, (useDisplayList != 0)), GLYPH_POLYGON);
+
+// FTTextureGlyph::FTTextureGlyph();
+C_TOR(ftglCreateTextureGlyph, (FT_GlyphSlot glyph, int id, int xOffset,
+                               int yOffset, int width, int height),
+      FTTextureGlyph, (glyph, id, xOffset, yOffset, width, height),
+      GLYPH_TEXTURE);
+
+// FTCustomGlyph::FTCustomGlyph();
+class FTCustomGlyph : public FTGlyph
+{
+public:
+    FTCustomGlyph(FTGLglyph *base, void *p,
+                  void (*render) (FTGLglyph *, void *, FTGL_DOUBLE, FTGL_DOUBLE,
+                                  int, FTGL_DOUBLE *, FTGL_DOUBLE *),
+                  void (*destroy) (FTGLglyph *, void *))
+     : FTGlyph((FT_GlyphSlot)0),
+       baseGlyph(base),
+       data(p),
+       renderCallback(render),
+       destroyCallback(destroy)
+    {}
+
+    ~FTCustomGlyph()
+    {
+        destroyCallback(baseGlyph, data);
+    }
+
+    float Advance() const { return baseGlyph->ptr->Advance(); }
+
+    const FTPoint& Render(const FTPoint& pen, int renderMode)
+    {
+        FTGL_DOUBLE advancex, advancey;
+        renderCallback(baseGlyph, data, pen.X(), pen.Y(), renderMode,
+                       &advancex, &advancey);
+        advance = FTPoint(advancex, advancey);
+        return advance;
+    }
+
+    const FTBBox& BBox() const { return baseGlyph->ptr->BBox(); }
+
+    FT_Error Error() const { return baseGlyph->ptr->Error(); }
+
+private:
+    FTPoint advance;
+    FTGLglyph *baseGlyph;
+    void *data;
+    void (*renderCallback) (FTGLglyph *, void *, FTGL_DOUBLE, FTGL_DOUBLE,
+                            int, FTGL_DOUBLE *, FTGL_DOUBLE *);
+    void (*destroyCallback) (FTGLglyph *, void *);
+};
+
+C_TOR(ftglCreateCustomGlyph, (FTGLglyph *base, void *data,
+         void (*renderCallback) (FTGLglyph *, void *, FTGL_DOUBLE, FTGL_DOUBLE,
+                                 int, FTGL_DOUBLE *, FTGL_DOUBLE *),
+         void (*destroyCallback) (FTGLglyph *, void *)),
+      FTCustomGlyph, (base, data, renderCallback, destroyCallback),
+      GLYPH_CUSTOM);
+
+#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \
+    cret cname cargs \
+    { \
+        if(!g || !g->ptr) \
+        { \
+            fprintf(stderr, "FTGL warning: NULL pointer in %s\n", #cname); \
+            cxxerr; \
+        } \
+        return g->ptr->cxxname cxxarg; \
+    }
+
+// FTGlyph::~FTGlyph();
+void ftglDestroyGlyph(FTGLglyph *g)
+{
+    if(!g || !g->ptr)
+    {
+        fprintf(stderr, "FTGL warning: NULL pointer in %s\n", __FUNCTION__);
+        return;
+    }
+    delete g->ptr;
+    free(g);
+}
+
+// const FTPoint& FTGlyph::Render(const FTPoint& pen, int renderMode);
+extern "C++" {
+C_FUN(static const FTPoint&, _ftglRenderGlyph, (FTGLglyph *g,
+                                   const FTPoint& pen, int renderMode),
+      return static_ftpoint, Render, (pen, renderMode));
+}
+
+void ftglRenderGlyph(FTGLglyph *g, FTGL_DOUBLE penx, FTGL_DOUBLE peny,
+                     int renderMode, FTGL_DOUBLE *advancex,
+                     FTGL_DOUBLE *advancey)
+{
+    FTPoint pen(penx, peny);
+    FTPoint ret = _ftglRenderGlyph(g, pen, renderMode);
+    *advancex = ret.X();
+    *advancey = ret.Y();
+}
+
+// float FTGlyph::Advance() const;
+C_FUN(float, ftglGetGlyphAdvance, (FTGLglyph *g), return 0.0, Advance, ());
+
+// const FTBBox& FTGlyph::BBox() const;
+extern "C++" {
+C_FUN(static const FTBBox&, _ftglGetGlyphBBox, (FTGLglyph *g),
+      return static_ftbbox, BBox, ());
+}
+
+void ftglGetGlyphBBox(FTGLglyph *g, float bounds[6])
+{
+    FTBBox ret = _ftglGetGlyphBBox(g);
+    FTPoint lower = ret.Lower(), upper = ret.Upper();
+    bounds[0] = lower.Xf(); bounds[1] = lower.Yf(); bounds[2] = lower.Zf();
+    bounds[3] = upper.Xf(); bounds[4] = upper.Yf(); bounds[5] = upper.Zf();
+}
+
+// FT_Error FTGlyph::Error() const;
+C_FUN(FT_Error, ftglGetGlyphError, (FTGLglyph *g), return -1, Error, ());
+
+FTGL_END_C_DECLS
+
diff --git a/src/ext/ftgl/FTGlyph/FTGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTGlyphImpl.h
new file mode 100644
index 0000000..37ea96f
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTGlyphImpl.h
@@ -0,0 +1,64 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTGlyphImpl__
+#define __FTGlyphImpl__
+
+#include "FTGL/ftgl.h"
+
+class FTGlyphImpl
+{
+    friend class FTGlyph;
+
+    protected:
+        FTGlyphImpl(FT_GlyphSlot glyph, bool useDisplayList = true);
+
+        virtual ~FTGlyphImpl();
+
+        float Advance() const;
+
+        const FTBBox& BBox() const;
+
+        FT_Error Error() const;
+
+        /**
+         * The advance distance for this glyph
+         */
+        FTPoint advance;
+
+        /**
+         * The bounding box of this glyph.
+         */
+        FTBBox bBox;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+};
+
+#endif  //  __FTGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTOutlineGlyph.cpp b/src/ext/ftgl/FTGlyph/FTOutlineGlyph.cpp
new file mode 100644
index 0000000..48e11f7
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTOutlineGlyph.cpp
@@ -0,0 +1,149 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTOutlineGlyphImpl.h"
+#include "FTVectoriser.h"
+
+
+//
+//  FTGLOutlineGlyph
+//
+
+
+FTOutlineGlyph::FTOutlineGlyph(FT_GlyphSlot glyph, float outset,
+                               bool useDisplayList) :
+    FTGlyph(new FTOutlineGlyphImpl(glyph, outset, useDisplayList))
+{}
+
+
+FTOutlineGlyph::~FTOutlineGlyph()
+{}
+
+
+const FTPoint& FTOutlineGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTOutlineGlyphImpl *myimpl = dynamic_cast<FTOutlineGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLOutlineGlyphImpl
+//
+
+
+FTOutlineGlyphImpl::FTOutlineGlyphImpl(FT_GlyphSlot glyph, float _outset,
+                                       bool useDisplayList)
+:   FTGlyphImpl(glyph),
+    glList(0)
+{
+    if(ft_glyph_format_outline != glyph->format)
+    {
+        err = 0x14; // Invalid_Outline
+        return;
+    }
+
+    vectoriser = new FTVectoriser(glyph);
+
+    if((vectoriser->ContourCount() < 1) || (vectoriser->PointCount() < 3))
+    {
+        delete vectoriser;
+        vectoriser = NULL;
+        return;
+    }
+
+    outset = _outset;
+
+    if(useDisplayList)
+    {
+        glList = glGenLists(1);
+        glNewList(glList, GL_COMPILE);
+
+        DoRender();
+
+        glEndList();
+
+        delete vectoriser;
+        vectoriser = NULL;
+    }
+}
+
+
+FTOutlineGlyphImpl::~FTOutlineGlyphImpl()
+{
+    if(glList)
+    {
+        glDeleteLists(glList, 1);
+    }
+    else if(vectoriser)
+    {
+        delete vectoriser;
+    }
+}
+
+
+const FTPoint& FTOutlineGlyphImpl::RenderImpl(const FTPoint& pen,
+                                              int renderMode)
+{
+    glTranslatef(pen.Xf(), pen.Yf(), pen.Zf());
+    if(glList)
+    {
+        glCallList(glList);
+    }
+    else if(vectoriser)
+    {
+        DoRender();
+    }
+    glTranslatef(-pen.Xf(), -pen.Yf(), -pen.Zf());
+
+    return advance;
+}
+
+
+void FTOutlineGlyphImpl::DoRender()
+{
+    for(unsigned int c = 0; c < vectoriser->ContourCount(); ++c)
+    {
+        const FTContour* contour = vectoriser->Contour(c);
+
+        glBegin(GL_LINE_LOOP);
+            for(unsigned int i = 0; i < contour->PointCount(); ++i)
+            {
+                FTPoint point = FTPoint(contour->Point(i).X() + contour->Outset(i).X() * outset,
+                                        contour->Point(i).Y() + contour->Outset(i).Y() * outset,
+                                        0);
+                glVertex2f(point.Xf() / 64.0f, point.Yf() / 64.0f);
+            }
+        glEnd();
+    }
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTOutlineGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTOutlineGlyphImpl.h
new file mode 100644
index 0000000..ead4b12
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTOutlineGlyphImpl.h
@@ -0,0 +1,69 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTOutlineGlyphImpl__
+#define __FTOutlineGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTVectoriser;
+
+class FTOutlineGlyphImpl : public FTGlyphImpl
+{
+    friend class FTOutlineGlyph;
+
+    protected:
+        FTOutlineGlyphImpl(FT_GlyphSlot glyph, float outset,
+                           bool useDisplayList);
+
+        virtual ~FTOutlineGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        /**
+         * Private rendering method.
+         */
+        void DoRender();
+
+        /**
+         * Private rendering variables.
+         */
+        FTVectoriser *vectoriser;
+
+        /**
+         * Private rendering variables.
+         */
+        float outset;
+
+        /**
+         * OpenGL display list
+         */
+        GLuint glList;
+};
+
+#endif  // __FTOutlineGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTPixmapGlyph.cpp b/src/ext/ftgl/FTGlyph/FTPixmapGlyph.cpp
new file mode 100644
index 0000000..5301e43
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTPixmapGlyph.cpp
@@ -0,0 +1,139 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <math.h>
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTPixmapGlyphImpl.h"
+
+
+//
+//  FTGLPixmapGlyph
+//
+
+
+FTPixmapGlyph::FTPixmapGlyph(FT_GlyphSlot glyph) :
+    FTGlyph(new FTPixmapGlyphImpl(glyph))
+{}
+
+
+FTPixmapGlyph::~FTPixmapGlyph()
+{}
+
+
+const FTPoint& FTPixmapGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTPixmapGlyphImpl *myimpl = dynamic_cast<FTPixmapGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLPixmapGlyphImpl
+//
+
+
+FTPixmapGlyphImpl::FTPixmapGlyphImpl(FT_GlyphSlot glyph)
+:   FTGlyphImpl(glyph),
+    destWidth(0),
+    destHeight(0),
+    data(0)
+{
+    err = FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL);
+    if(err || ft_glyph_format_bitmap != glyph->format)
+    {
+        return;
+    }
+
+    FT_Bitmap bitmap = glyph->bitmap;
+
+    //check the pixel mode
+    //ft_pixel_mode_grays
+
+    int srcWidth = bitmap.width;
+    int srcHeight = bitmap.rows;
+
+    destWidth = srcWidth;
+    destHeight = srcHeight;
+
+    if(destWidth && destHeight)
+    {
+        data = new unsigned char[destWidth * destHeight * 2];
+        unsigned char* src = bitmap.buffer;
+
+        unsigned char* dest = data + ((destHeight - 1) * destWidth * 2);
+        size_t destStep = destWidth * 2 * 2;
+
+        for(int y = 0; y < srcHeight; ++y)
+        {
+            for(int x = 0; x < srcWidth; ++x)
+            {
+                *dest++ = static_cast<unsigned char>(255);
+                *dest++ = *src++;
+            }
+            dest -= destStep;
+        }
+
+        destHeight = srcHeight;
+    }
+
+    pos.X(glyph->bitmap_left);
+    pos.Y(srcHeight - glyph->bitmap_top);
+}
+
+
+FTPixmapGlyphImpl::~FTPixmapGlyphImpl()
+{
+    delete [] data;
+}
+
+
+const FTPoint& FTPixmapGlyphImpl::RenderImpl(const FTPoint& pen,
+                                             int renderMode)
+{
+    if(data)
+    {
+        float dx, dy;
+
+        dx = floor(pen.Xf() + pos.Xf());
+        dy = floor(pen.Yf() - pos.Yf());
+
+        glBitmap(0, 0, 0.0f, 0.0f, dx, dy, (const GLubyte*)0);
+        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 2);
+
+        glDrawPixels(destWidth, destHeight, GL_LUMINANCE_ALPHA,
+                     GL_UNSIGNED_BYTE, (const GLvoid*)data);
+        glBitmap(0, 0, 0.0f, 0.0f, -dx, -dy, (const GLubyte*)0);
+    }
+
+    return advance;
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTPixmapGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTPixmapGlyphImpl.h
new file mode 100644
index 0000000..8331469
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTPixmapGlyphImpl.h
@@ -0,0 +1,67 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTPixmapGlyphImpl__
+#define __FTPixmapGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTPixmapGlyphImpl : public FTGlyphImpl
+{
+    friend class FTPixmapGlyph;
+
+    protected:
+        FTPixmapGlyphImpl(FT_GlyphSlot glyph);
+
+        virtual ~FTPixmapGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        /**
+         * The width of the glyph 'image'
+         */
+        int destWidth;
+
+        /**
+         * The height of the glyph 'image'
+         */
+        int destHeight;
+
+        /**
+         * Vector from the pen position to the topleft corner of the pixmap
+         */
+        FTPoint pos;
+
+        /**
+         * Pointer to the 'image' data
+         */
+        unsigned char* data;
+
+};
+
+#endif  //  __FTPixmapGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTPolygonGlyph.cpp b/src/ext/ftgl/FTGlyph/FTPolygonGlyph.cpp
new file mode 100644
index 0000000..6db3581
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTPolygonGlyph.cpp
@@ -0,0 +1,156 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTPolygonGlyphImpl.h"
+#include "FTVectoriser.h"
+
+
+//
+//  FTGLPolyGlyph
+//
+
+
+FTPolygonGlyph::FTPolygonGlyph(FT_GlyphSlot glyph, float outset,
+                               bool useDisplayList) :
+    FTGlyph(new FTPolygonGlyphImpl(glyph, outset, useDisplayList))
+{}
+
+
+FTPolygonGlyph::~FTPolygonGlyph()
+{}
+
+
+const FTPoint& FTPolygonGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTPolygonGlyphImpl *myimpl = dynamic_cast<FTPolygonGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLPolyGlyphImpl
+//
+
+
+FTPolygonGlyphImpl::FTPolygonGlyphImpl(FT_GlyphSlot glyph, float _outset,
+                                       bool useDisplayList)
+:   FTGlyphImpl(glyph),
+    glList(0)
+{
+    if(ft_glyph_format_outline != glyph->format)
+    {
+        err = 0x14; // Invalid_Outline
+        return;
+    }
+
+    vectoriser = new FTVectoriser(glyph);
+
+    if((vectoriser->ContourCount() < 1) || (vectoriser->PointCount() < 3))
+    {
+        delete vectoriser;
+        vectoriser = NULL;
+        return;
+    }
+
+
+    hscale = glyph->face->size->metrics.x_ppem * 64;
+    vscale = glyph->face->size->metrics.y_ppem * 64;
+    outset = _outset;
+
+    if(useDisplayList)
+    {
+        glList = glGenLists(1);
+        glNewList(glList, GL_COMPILE);
+
+        DoRender();
+
+        glEndList();
+
+        delete vectoriser;
+        vectoriser = NULL;
+    }
+}
+
+
+FTPolygonGlyphImpl::~FTPolygonGlyphImpl()
+{
+    if(glList)
+    {
+        glDeleteLists(glList, 1);
+    }
+    else if(vectoriser)
+    {
+        delete vectoriser;
+    }
+}
+
+
+const FTPoint& FTPolygonGlyphImpl::RenderImpl(const FTPoint& pen,
+                                              int renderMode)
+{
+    glTranslatef(pen.Xf(), pen.Yf(), pen.Zf());
+    if(glList)
+    {
+        glCallList(glList);
+    }
+    else if(vectoriser)
+    {
+        DoRender();
+    }
+    glTranslatef(-pen.Xf(), -pen.Yf(), -pen.Zf());
+
+    return advance;
+}
+
+
+void FTPolygonGlyphImpl::DoRender()
+{
+    vectoriser->MakeMesh(1.0, 1, outset);
+
+    const FTMesh *mesh = vectoriser->GetMesh();
+
+    for(unsigned int t = 0; t < mesh->TesselationCount(); ++t)
+    {
+        const FTTesselation* subMesh = mesh->Tesselation(t);
+        unsigned int polygonType = subMesh->PolygonType();
+
+        glBegin(polygonType);
+            for(unsigned int i = 0; i < subMesh->PointCount(); ++i)
+            {
+                FTPoint point = subMesh->Point(i);
+                glTexCoord2f(point.Xf() / hscale, point.Yf() / vscale);
+                glVertex3f(point.Xf() / 64.0f, point.Yf() / 64.0f, 0.0f);
+            }
+        glEnd();
+    }
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTPolygonGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTPolygonGlyphImpl.h
new file mode 100644
index 0000000..e353391
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTPolygonGlyphImpl.h
@@ -0,0 +1,66 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTPolygonGlyphImpl__
+#define __FTPolygonGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTVectoriser;
+
+class FTPolygonGlyphImpl : public FTGlyphImpl
+{
+    friend class FTPolygonGlyph;
+
+    public:
+        FTPolygonGlyphImpl(FT_GlyphSlot glyph, float outset,
+                           bool useDisplayList);
+
+        virtual ~FTPolygonGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        /**
+         * Private rendering method.
+         */
+        void DoRender();
+
+        /**
+         * Private rendering variables.
+         */
+        unsigned int hscale, vscale;
+        FTVectoriser *vectoriser;
+        float outset;
+
+        /**
+         * OpenGL display list
+         */
+        GLuint glList;
+};
+
+#endif  //  __FTPolygonGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyph/FTTextureGlyph.cpp b/src/ext/ftgl/FTGlyph/FTTextureGlyph.cpp
new file mode 100644
index 0000000..a9cf2e8
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTTextureGlyph.cpp
@@ -0,0 +1,153 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <math.h>
+
+#include "FTGL/ftgl.h"
+
+#include "FTInternals.h"
+#include "FTTextureGlyphImpl.h"
+
+
+//
+//  FTGLTextureGlyph
+//
+
+
+FTTextureGlyph::FTTextureGlyph(FT_GlyphSlot glyph, int id, int xOffset,
+                               int yOffset, int width, int height) :
+    FTGlyph(new FTTextureGlyphImpl(glyph, id, xOffset, yOffset, width, height))
+{}
+
+
+FTTextureGlyph::~FTTextureGlyph()
+{}
+
+
+const FTPoint& FTTextureGlyph::Render(const FTPoint& pen, int renderMode)
+{
+    FTTextureGlyphImpl *myimpl = dynamic_cast<FTTextureGlyphImpl *>(impl);
+    return myimpl->RenderImpl(pen, renderMode);
+}
+
+
+//
+//  FTGLTextureGlyphImpl
+//
+
+
+GLint FTTextureGlyphImpl::activeTextureID = 0;
+
+FTTextureGlyphImpl::FTTextureGlyphImpl(FT_GlyphSlot glyph, int id, int xOffset,
+                                       int yOffset, int width, int height)
+:   FTGlyphImpl(glyph),
+    destWidth(0),
+    destHeight(0),
+    glTextureID(id)
+{
+    /* FIXME: need to propagate the render mode all the way down to
+     * here in order to get FT_RENDER_MODE_MONO aliased fonts.
+     */
+
+    err = FT_Render_Glyph(glyph, FT_RENDER_MODE_NORMAL);
+    if(err || glyph->format != ft_glyph_format_bitmap)
+    {
+        return;
+    }
+
+    FT_Bitmap      bitmap = glyph->bitmap;
+
+    destWidth  = bitmap.width;
+    destHeight = bitmap.rows;
+
+    if(destWidth && destHeight)
+    {
+        glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
+        glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
+        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
+        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+
+        glBindTexture(GL_TEXTURE_2D, glTextureID);
+        glTexSubImage2D(GL_TEXTURE_2D, 0, xOffset, yOffset, destWidth, destHeight, GL_ALPHA, GL_UNSIGNED_BYTE, bitmap.buffer);
+
+        glPopClientAttrib();
+    }
+
+
+//      0
+//      +----+
+//      |    |
+//      |    |
+//      |    |
+//      +----+
+//           1
+
+    uv[0].X(static_cast<float>(xOffset) / static_cast<float>(width));
+    uv[0].Y(static_cast<float>(yOffset) / static_cast<float>(height));
+    uv[1].X(static_cast<float>(xOffset + destWidth) / static_cast<float>(width));
+    uv[1].Y(static_cast<float>(yOffset + destHeight) / static_cast<float>(height));
+
+    corner = FTPoint(glyph->bitmap_left, glyph->bitmap_top);
+}
+
+
+FTTextureGlyphImpl::~FTTextureGlyphImpl()
+{}
+
+
+const FTPoint& FTTextureGlyphImpl::RenderImpl(const FTPoint& pen,
+                                              int renderMode)
+{
+    float dx, dy;
+
+    if(activeTextureID != glTextureID)
+    {
+        glBindTexture(GL_TEXTURE_2D, (GLuint)glTextureID);
+        activeTextureID = glTextureID;
+    }
+
+    dx = floor(pen.Xf() + corner.Xf());
+    dy = floor(pen.Yf() + corner.Yf());
+
+    glBegin(GL_QUADS);
+        glTexCoord2f(uv[0].Xf(), uv[0].Yf());
+        glVertex2f(dx, dy);
+
+        glTexCoord2f(uv[0].Xf(), uv[1].Yf());
+        glVertex2f(dx, dy - destHeight);
+
+        glTexCoord2f(uv[1].Xf(), uv[1].Yf());
+        glVertex2f(dx + destWidth, dy - destHeight);
+
+        glTexCoord2f(uv[1].Xf(), uv[0].Yf());
+        glVertex2f(dx + destWidth, dy);
+    glEnd();
+
+    return advance;
+}
+
diff --git a/src/ext/ftgl/FTGlyph/FTTextureGlyphImpl.h b/src/ext/ftgl/FTGlyph/FTTextureGlyphImpl.h
new file mode 100644
index 0000000..793af04
--- /dev/null
+++ b/src/ext/ftgl/FTGlyph/FTTextureGlyphImpl.h
@@ -0,0 +1,88 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTTextureGlyphImpl__
+#define __FTTextureGlyphImpl__
+
+#include "FTGlyphImpl.h"
+
+class FTTextureGlyphImpl : public FTGlyphImpl
+{
+    friend class FTTextureGlyph;
+    friend class FTTextureFontImpl;
+
+    protected:
+        FTTextureGlyphImpl(FT_GlyphSlot glyph, int id, int xOffset,
+                           int yOffset, int width, int height);
+
+        virtual ~FTTextureGlyphImpl();
+
+        virtual const FTPoint& RenderImpl(const FTPoint& pen, int renderMode);
+
+    private:
+        /**
+         * Reset the currently active texture to zero to get into a known
+         * state before drawing a string. This is to get round possible
+         * threading issues.
+         */
+        static void ResetActiveTexture() { activeTextureID = 0; }
+
+        /**
+         * The width of the glyph 'image'
+         */
+        int destWidth;
+
+        /**
+         * The height of the glyph 'image'
+         */
+        int destHeight;
+
+        /**
+         * Vector from the pen position to the topleft corner of the pixmap
+         */
+        FTPoint corner;
+
+        /**
+         * The texture co-ords of this glyph within the texture.
+         */
+        FTPoint uv[2];
+
+        /**
+         * The texture index that this glyph is contained in.
+         */
+        int glTextureID;
+
+        /**
+         * The texture index of the currently active texture
+         *
+         * We keep track of the currently active texture to try to reduce the
+         * number of texture bind operations.
+         */
+        static GLint activeTextureID;
+};
+
+#endif  //  __FTTextureGlyphImpl__
+
diff --git a/src/ext/ftgl/FTGlyphContainer.cpp b/src/ext/ftgl/FTGlyphContainer.cpp
new file mode 100644
index 0000000..54c1de4
--- /dev/null
+++ b/src/ext/ftgl/FTGlyphContainer.cpp
@@ -0,0 +1,119 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "FTGlyphContainer.h"
+#include "FTFace.h"
+#include "FTCharmap.h"
+
+
+FTGlyphContainer::FTGlyphContainer(FTFace* f)
+:   face(f),
+    err(0)
+{
+    glyphs.push_back(NULL);
+    charMap = new FTCharmap(face);
+}
+
+
+FTGlyphContainer::~FTGlyphContainer()
+{
+    GlyphVector::iterator it;
+    for(it = glyphs.begin(); it != glyphs.end(); ++it)
+    {
+        delete *it;
+    }
+
+    glyphs.clear();
+    delete charMap;
+}
+
+
+bool FTGlyphContainer::CharMap(FT_Encoding encoding)
+{
+    bool result = charMap->CharMap(encoding);
+    err = charMap->Error();
+    return result;
+}
+
+
+unsigned int FTGlyphContainer::FontIndex(const unsigned int charCode) const
+{
+    return charMap->FontIndex(charCode);
+}
+
+
+void FTGlyphContainer::Add(FTGlyph* tempGlyph, const unsigned int charCode)
+{
+    charMap->InsertIndex(charCode, glyphs.size());
+    glyphs.push_back(tempGlyph);
+}
+
+
+const FTGlyph* const FTGlyphContainer::Glyph(const unsigned int charCode) const
+{
+    unsigned int index = charMap->GlyphListIndex(charCode);
+    return glyphs[index];
+}
+
+
+FTBBox FTGlyphContainer::BBox(const unsigned int charCode) const
+{
+    return Glyph(charCode)->BBox();
+}
+
+
+float FTGlyphContainer::Advance(const unsigned int charCode,
+                                const unsigned int nextCharCode)
+{
+    unsigned int left = charMap->FontIndex(charCode);
+    unsigned int right = charMap->FontIndex(nextCharCode);
+
+    return face->KernAdvance(left, right).Xf() + Glyph(charCode)->Advance();
+}
+
+
+FTPoint FTGlyphContainer::Render(const unsigned int charCode,
+                                 const unsigned int nextCharCode,
+                                 FTPoint penPosition, int renderMode)
+{
+    unsigned int left = charMap->FontIndex(charCode);
+    unsigned int right = charMap->FontIndex(nextCharCode);
+
+    FTPoint kernAdvance = face->KernAdvance(left, right);
+
+    if(!face->Error())
+    {
+        unsigned int index = charMap->GlyphListIndex(charCode);
+        kernAdvance += glyphs[index]->Render(penPosition, renderMode);
+    }
+
+    return kernAdvance;
+}
+
diff --git a/src/ext/ftgl/FTGlyphContainer.h b/src/ext/ftgl/FTGlyphContainer.h
new file mode 100644
index 0000000..d4bbb74
--- /dev/null
+++ b/src/ext/ftgl/FTGlyphContainer.h
@@ -0,0 +1,155 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTGlyphContainer__
+#define     __FTGlyphContainer__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_GLYPH_H
+
+#include "FTGL/ftgl.h"
+
+#include "FTVector.h"
+
+class FTFace;
+class FTGlyph;
+class FTCharmap;
+
+/**
+ * FTGlyphContainer holds the post processed FTGlyph objects.
+ *
+ * @see FTGlyph
+ */
+class FTGlyphContainer
+{
+        typedef FTVector<FTGlyph*> GlyphVector;
+    public:
+        /**
+         * Constructor
+         *
+         * @param face      The Freetype face
+         */
+        FTGlyphContainer(FTFace* face);
+
+        /**
+         * Destructor
+         */
+        ~FTGlyphContainer();
+
+        /**
+         * Sets the character map for the face.
+         *
+         * @param encoding      the Freetype encoding symbol. See above.
+         * @return              <code>true</code> if charmap was valid
+         *                      and set correctly
+         */
+        bool CharMap(FT_Encoding encoding);
+
+        /**
+         * Get the font index of the input character.
+         *
+         * @param characterCode The character code of the requested glyph in the
+         *                      current encoding eg apple roman.
+         * @return      The font index for the character.
+         */
+        unsigned int FontIndex(const unsigned int characterCode) const;
+
+        /**
+         * Adds a glyph to this glyph list.
+         *
+         * @param glyph         The FTGlyph to be inserted into the container
+         * @param characterCode The char code of the glyph NOT the glyph index.
+         */
+        void Add(FTGlyph* glyph, const unsigned int characterCode);
+
+        /**
+         * Get a glyph from the glyph list
+         *
+         * @param characterCode The char code of the glyph NOT the glyph index
+         * @return              An FTGlyph or <code>null</code> is it hasn't been
+         * loaded.
+         */
+        const FTGlyph* const Glyph(const unsigned int characterCode) const;
+
+        /**
+         * Get the bounding box for a character.
+         * @param characterCode The char code of the glyph NOT the glyph index
+         */
+        FTBBox BBox(const unsigned int characterCode) const;
+
+        /**
+        * Returns the kerned advance width for a glyph.
+        *
+        * @param characterCode     glyph index of the character
+        * @param nextCharacterCode the next glyph in a string
+        * @return                  advance width
+        */
+        float Advance(const unsigned int characterCode,
+                      const unsigned int nextCharacterCode);
+
+        /**
+         * Renders a character
+         * @param characterCode      the glyph to be Rendered
+         * @param nextCharacterCode  the next glyph in the string. Used for kerning.
+         * @param penPosition        the position to Render the glyph
+         * @param renderMode         Render mode to display
+         * @return                   The distance to advance the pen position after Rendering
+         */
+        FTPoint Render(const unsigned int characterCode,
+                       const unsigned int nextCharacterCode,
+                       FTPoint penPosition, int renderMode);
+
+        /**
+         * Queries the Font for errors.
+         *
+         * @return  The current error code.
+         */
+        FT_Error Error() const { return err; }
+
+    private:
+        /**
+         * The FTGL face
+         */
+        FTFace* face;
+
+        /**
+         * The Character Map object associated with the current face
+         */
+        FTCharmap* charMap;
+
+        /**
+         * A structure to hold the glyphs
+         */
+        GlyphVector glyphs;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+};
+
+
+#endif  //  __FTGlyphContainer__
diff --git a/src/ext/ftgl/FTInternals.h b/src/ext/ftgl/FTInternals.h
new file mode 100644
index 0000000..9d6bcc0
--- /dev/null
+++ b/src/ext/ftgl/FTInternals.h
@@ -0,0 +1,145 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTINTERNALS_H__
+#define __FTINTERNALS_H__
+
+#include "FTGL/ftgl.h"
+
+#include <stdlib.h>
+#include <stdio.h>
+
+
+// Fixes for deprecated identifiers in 2.1.5
+#ifndef FT_OPEN_MEMORY
+    #define FT_OPEN_MEMORY (FT_Open_Flags)1
+#endif
+
+#ifndef FT_RENDER_MODE_MONO
+    #define FT_RENDER_MODE_MONO ft_render_mode_mono
+#endif
+
+#ifndef FT_RENDER_MODE_NORMAL
+    #define FT_RENDER_MODE_NORMAL ft_render_mode_normal
+#endif
+
+
+#ifdef WIN32
+
+    // Under windows avoid including <windows.h> is overrated.
+    // Sure, it can be avoided and "name space pollution" can be
+    // avoided, but why? It really doesn't make that much difference
+    // these days.
+    #define  WIN32_LEAN_AND_MEAN
+    #include <windows.h>
+
+    #ifndef __gl_h_
+        #include <GL/gl.h>
+        #include <GL/glu.h>
+    #endif
+
+#else
+
+    // Non windows platforms - don't require nonsense as seen above :-)
+    #ifndef __gl_h_
+        #ifdef SDL_main
+            #include "SDL_opengl.h"
+        #elif __APPLE_CC__
+            #include <OpenGL/gl.h>
+            #include <OpenGL/glu.h>
+        #else
+            #include <GL/gl.h>
+            #if defined (__sun__) && !defined (__sparc__)
+                #include <mesa/glu.h>
+            #else
+                #include <GL/glu.h>
+            #endif
+        #endif
+
+    #endif
+
+    // Required for compatibility with glext.h style function definitions of
+    // OpenGL extensions, such as in src/osg/Point.cpp.
+    #ifndef APIENTRY
+        #define APIENTRY
+    #endif
+#endif
+
+FTGL_BEGIN_C_DECLS
+
+typedef enum
+{
+    GLYPH_CUSTOM,
+    GLYPH_BITMAP,
+    GLYPH_BUFFER,
+    GLYPH_PIXMAP,
+    GLYPH_OUTLINE,
+    GLYPH_POLYGON,
+    GLYPH_EXTRUDE,
+    GLYPH_TEXTURE
+} GlyphType;
+
+struct _FTGLglyph
+{
+    FTGlyph *ptr;
+    FTGL::GlyphType type;
+};
+
+typedef enum
+{
+    FONT_CUSTOM,
+    FONT_BITMAP,
+    FONT_BUFFER,
+    FONT_PIXMAP,
+    FONT_OUTLINE,
+    FONT_POLYGON,
+    FONT_EXTRUDE,
+    FONT_TEXTURE
+} FontType;
+
+struct _FTGLfont
+{
+    FTFont *ptr;
+    FTGL::FontType type;
+};
+
+typedef enum
+{
+    LAYOUT_SIMPLE
+} LayoutType;
+
+struct _FTGLlayout
+{
+    FTLayout *ptr;
+    FTGLfont *font;
+    FTGL::LayoutType type;
+};
+
+FTGL_END_C_DECLS
+
+#endif  //__FTINTERNALS_H__
+
diff --git a/src/ext/ftgl/FTLayout/FTLayout.cpp b/src/ext/ftgl/FTLayout/FTLayout.cpp
new file mode 100644
index 0000000..d4298bd
--- /dev/null
+++ b/src/ext/ftgl/FTLayout/FTLayout.cpp
@@ -0,0 +1,80 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTGL/ftgl.h"
+
+#include "../FTFont/FTFontImpl.h"
+#include "./FTLayoutImpl.h"
+
+
+//
+//  FTLayout
+//
+
+
+FTLayout::FTLayout()
+{
+    impl = new FTLayoutImpl();
+}
+
+
+FTLayout::FTLayout(FTLayoutImpl *pImpl)
+{
+    impl = pImpl;
+}
+
+
+FTLayout::~FTLayout()
+{
+    delete impl;
+}
+
+
+FT_Error FTLayout::Error() const
+{
+    return impl->err;
+}
+
+
+//
+//  FTLayoutImpl
+//
+
+
+FTLayoutImpl::FTLayoutImpl() :
+    err(0)
+{
+    ;
+}
+
+
+FTLayoutImpl::~FTLayoutImpl()
+{
+    ;
+}
+
diff --git a/src/ext/ftgl/FTLayout/FTLayoutGlue.cpp b/src/ext/ftgl/FTLayout/FTLayoutGlue.cpp
new file mode 100644
index 0000000..60f428d
--- /dev/null
+++ b/src/ext/ftgl/FTLayout/FTLayoutGlue.cpp
@@ -0,0 +1,171 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTInternals.h"
+
+static const FTBBox static_ftbbox;
+
+FTGL_BEGIN_C_DECLS
+
+#define C_TOR(cname, cargs, cxxname, cxxarg, cxxtype) \
+    FTGLlayout* cname cargs \
+    { \
+        cxxname *l = new cxxname cxxarg; \
+        if(l->Error()) \
+        { \
+            delete l; \
+            return NULL; \
+        } \
+        FTGLlayout *ftgl = (FTGLlayout *)malloc(sizeof(FTGLlayout)); \
+        ftgl->ptr = l; \
+        ftgl->type = cxxtype; \
+        return ftgl; \
+    }
+
+// FTSimpleLayout::FTSimpleLayout();
+C_TOR(ftglCreateSimpleLayout, (), FTSimpleLayout, (), LAYOUT_SIMPLE);
+
+#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \
+    cret cname cargs \
+    { \
+        if(!l || !l->ptr) \
+        { \
+            fprintf(stderr, "FTGL warning: NULL pointer in %s\n", #cname); \
+            cxxerr; \
+        } \
+        return l->ptr->cxxname cxxarg; \
+    }
+
+// FTLayout::~FTLayout();
+void ftglDestroyLayout(FTGLlayout *l)
+{
+    if(!l || !l->ptr)
+    {
+        fprintf(stderr, "FTGL warning: NULL pointer in %s\n", __FUNCTION__);
+        return;
+    }
+    delete l->ptr;
+    free(l);
+}
+
+// virtual FTBBox FTLayout::BBox(const char* string)
+extern "C++" {
+C_FUN(static FTBBox, _ftgGetlLayoutBBox, (FTGLlayout *l, const char *s),
+      return static_ftbbox, BBox, (s));
+}
+
+void ftgGetlLayoutBBox(FTGLlayout *l, const char * s, float c[6])
+{
+    FTBBox ret = _ftgGetlLayoutBBox(l, s);
+    FTPoint lower = ret.Lower(), upper = ret.Upper();
+    c[0] = lower.Xf(); c[1] = lower.Yf(); c[2] = lower.Zf();
+    c[3] = upper.Xf(); c[4] = upper.Yf(); c[5] = upper.Zf();
+}
+
+// virtual void FTLayout::Render(const char* string, int renderMode);
+C_FUN(void, ftglRenderLayout, (FTGLlayout *l, const char *s, int r),
+      return, Render, (s, r));
+
+// FT_Error FTLayout::Error() const;
+C_FUN(FT_Error, ftglGetLayoutError, (FTGLlayout *l), return -1, Error, ());
+
+// void FTSimpleLayout::SetFont(FTFont *fontInit)
+void ftglSetLayoutFont(FTGLlayout *l, FTGLfont *font)
+{
+    if(!l || !l->ptr)
+    {
+        fprintf(stderr, "FTGL warning: NULL pointer in %s\n", __FUNCTION__);
+        return;
+    }
+    if(l->type != FTGL::LAYOUT_SIMPLE)
+    {
+        fprintf(stderr, "FTGL warning: %s not implemented for %d\n",
+                        __FUNCTION__, l->type);
+    }
+    l->font = font;
+    return dynamic_cast<FTSimpleLayout*>(l->ptr)->SetFont(font->ptr);
+}
+
+// FTFont *FTSimpleLayout::GetFont()
+FTGLfont *ftglGetLayoutFont(FTGLlayout *l)
+{
+    if(!l || !l->ptr)
+    {
+        fprintf(stderr, "FTGL warning: NULL pointer in %s\n", __FUNCTION__);
+        return NULL;
+    }
+    if(l->type != FTGL::LAYOUT_SIMPLE)
+    {
+        fprintf(stderr, "FTGL warning: %s not implemented for %d\n",
+                        __FUNCTION__, l->type);
+    }
+    return l->font;
+}
+
+#undef C_FUN
+
+#define C_FUN(cret, cname, cargs, cxxerr, cxxname, cxxarg) \
+    cret cname cargs \
+    { \
+        if(!l || !l->ptr) \
+        { \
+            fprintf(stderr, "FTGL warning: NULL pointer in %s\n", #cname); \
+            cxxerr; \
+        } \
+        if(l->type != FTGL::LAYOUT_SIMPLE) \
+        { \
+            fprintf(stderr, "FTGL warning: %s not implemented for %d\n", \
+                            __FUNCTION__, l->type); \
+            cxxerr; \
+        } \
+        return dynamic_cast<FTSimpleLayout*>(l->ptr)->cxxname cxxarg; \
+    }
+
+// void FTSimpleLayout::SetLineLength(const float LineLength);
+C_FUN(void, ftglSetLayoutLineLength, (FTGLlayout *l, const float length),
+      return, SetLineLength, (length));
+
+// float FTSimpleLayout::GetLineLength() const
+C_FUN(float, ftglGetLayoutLineLength, (FTGLlayout *l),
+      return 0.0f, GetLineLength, ());
+
+// void FTSimpleLayout::SetAlignment(const TextAlignment Alignment)
+C_FUN(void, ftglSetLayoutAlignment, (FTGLlayout *l, const int a),
+      return, SetAlignment, ((FTGL::TextAlignment)a));
+
+// TextAlignment FTSimpleLayout::GetAlignment() const
+C_FUN(int, ftglGetLayoutAlignement, (FTGLlayout *l),
+      return FTGL::ALIGN_LEFT, GetAlignment, ());
+
+// void FTSimpleLayout::SetLineSpacing(const float LineSpacing)
+C_FUN(void, ftglSetLayoutLineSpacing, (FTGLlayout *l, const float f),
+      return, SetLineSpacing, (f));
+
+FTGL_END_C_DECLS
+
diff --git a/src/ext/ftgl/FTLayout/FTLayoutImpl.h b/src/ext/ftgl/FTLayout/FTLayoutImpl.h
new file mode 100644
index 0000000..85df50d
--- /dev/null
+++ b/src/ext/ftgl/FTLayout/FTLayoutImpl.h
@@ -0,0 +1,56 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTLayoutImpl__
+#define __FTLayoutImpl__
+
+#include "FTSize.h"
+#include "FTGlyphContainer.h"
+
+
+class FTLayoutImpl
+{
+        friend class FTLayout;
+
+    protected:
+        FTLayoutImpl();
+
+        virtual ~FTLayoutImpl();
+
+    protected:
+        /**
+         * Current pen or cursor position;
+         */
+        FTPoint pen;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+};
+
+#endif  //  __FTLayoutImpl__
+
diff --git a/src/ext/ftgl/FTLayout/FTSimpleLayout.cpp b/src/ext/ftgl/FTLayout/FTSimpleLayout.cpp
new file mode 100644
index 0000000..b5a7beb
--- /dev/null
+++ b/src/ext/ftgl/FTLayout/FTSimpleLayout.cpp
@@ -0,0 +1,460 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <ctype.h>
+#include <wctype.h>
+
+#include "FTInternals.h"
+#include "FTUnicode.h"
+
+#include "FTGlyphContainer.h"
+#include "FTSimpleLayoutImpl.h"
+
+
+//
+//  FTSimpleLayout
+//
+
+
+FTSimpleLayout::FTSimpleLayout() :
+    FTLayout(new FTSimpleLayoutImpl())
+{}
+
+
+FTSimpleLayout::~FTSimpleLayout()
+{}
+
+
+FTBBox FTSimpleLayout::BBox(const char *string, const int len, FTPoint pos)
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->BBox(string, len, pos);
+}
+
+
+FTBBox FTSimpleLayout::BBox(const wchar_t *string, const int len, FTPoint pos)
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->BBox(string, len, pos);
+}
+
+
+void FTSimpleLayout::Render(const char *string, const int len, FTPoint pos,
+                            int renderMode)
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->Render(string, len, pos,
+                                                           renderMode);
+}
+
+
+void FTSimpleLayout::Render(const wchar_t* string, const int len, FTPoint pos,
+                            int renderMode)
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->Render(string, len, pos,
+                                                           renderMode);
+}
+
+
+void FTSimpleLayout::SetFont(FTFont *fontInit)
+{
+    dynamic_cast<FTSimpleLayoutImpl*>(impl)->currentFont = fontInit;
+}
+
+
+FTFont *FTSimpleLayout::GetFont()
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->currentFont;
+}
+
+
+void FTSimpleLayout::SetLineLength(const float LineLength)
+{
+    dynamic_cast<FTSimpleLayoutImpl*>(impl)->lineLength = LineLength;
+}
+
+
+float FTSimpleLayout::GetLineLength() const
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->lineLength;
+}
+
+
+void FTSimpleLayout::SetAlignment(const FTGL::TextAlignment Alignment)
+{
+    dynamic_cast<FTSimpleLayoutImpl*>(impl)->alignment = Alignment;
+}
+
+
+FTGL::TextAlignment FTSimpleLayout::GetAlignment() const
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->alignment;
+}
+
+
+void FTSimpleLayout::SetLineSpacing(const float LineSpacing)
+{
+    dynamic_cast<FTSimpleLayoutImpl*>(impl)->lineSpacing = LineSpacing;
+}
+
+
+float FTSimpleLayout::GetLineSpacing() const
+{
+    return dynamic_cast<FTSimpleLayoutImpl*>(impl)->lineSpacing;
+}
+
+
+//
+//  FTSimpleLayoutImpl
+//
+
+
+FTSimpleLayoutImpl::FTSimpleLayoutImpl()
+{
+    currentFont = NULL;
+    lineLength = 100.0f;
+    alignment = FTGL::ALIGN_LEFT;
+    lineSpacing = 1.0f;
+}
+
+
+template <typename T>
+inline FTBBox FTSimpleLayoutImpl::BBoxI(const T* string, const int len,
+                                        FTPoint position)
+{
+    FTBBox tmp;
+
+    WrapText(string, len, position, 0, &tmp);
+
+    return tmp;
+}
+
+
+FTBBox FTSimpleLayoutImpl::BBox(const char *string, const int len,
+                                FTPoint position)
+{
+    return BBoxI(string, len, position);
+}
+
+
+FTBBox FTSimpleLayoutImpl::BBox(const wchar_t *string, const int len,
+                                FTPoint position)
+{
+    return BBoxI(string, len, position);
+}
+
+
+template <typename T>
+inline void FTSimpleLayoutImpl::RenderI(const T *string, const int len,
+                                        FTPoint position, int renderMode)
+{
+    pen = FTPoint(0.0f, 0.0f);
+    WrapText(string, len, position, renderMode, NULL);
+}
+
+
+void FTSimpleLayoutImpl::Render(const char *string, const int len,
+                                FTPoint position, int renderMode)
+{
+    RenderI(string, len, position, renderMode);
+}
+
+
+void FTSimpleLayoutImpl::Render(const wchar_t* string, const int len,
+                                FTPoint position, int renderMode)
+{
+    RenderI(string, len, position, renderMode);
+}
+
+
+template <typename T>
+inline void FTSimpleLayoutImpl::WrapTextI(const T *buf, const int len,
+                                          FTPoint position, int renderMode,
+                                          FTBBox *bounds)
+{
+    FTUnicodeStringItr<T> breakItr(buf);          // points to the last break character
+    FTUnicodeStringItr<T> lineStart(buf);         // points to the line start
+    float nextStart = 0.0;     // total width of the current line
+    float breakWidth = 0.0;    // width of the line up to the last word break
+    float currentWidth = 0.0;  // width of all characters on the current line
+    float prevWidth;           // width of all characters but the current glyph
+    float wordLength = 0.0;    // length of the block since the last break char
+    int charCount = 0;         // number of characters so far on the line
+    int breakCharCount = 0;    // number of characters before the breakItr
+    float glyphWidth, advance;
+    FTBBox glyphBounds;
+
+    // Reset the pen position
+    pen.Y(0);
+
+    // If we have bounds mark them invalid
+    if(bounds)
+    {
+        bounds->Invalidate();
+    }
+
+    // Scan the input for all characters that need output
+    FTUnicodeStringItr<T> prevItr(buf);
+    for (FTUnicodeStringItr<T> itr(buf); *itr; prevItr = itr++, charCount++)
+    {
+        // Find the width of the current glyph
+        glyphBounds = currentFont->BBox(itr.getBufferFromHere(), 1);
+        glyphWidth = glyphBounds.Upper().Xf() - glyphBounds.Lower().Xf();
+
+        advance = currentFont->Advance(itr.getBufferFromHere(), 1);
+        prevWidth = currentWidth;
+        // Compute the width of all glyphs up to the end of buf[i]
+        currentWidth = nextStart + glyphWidth;
+        // Compute the position of the next glyph
+        nextStart += advance;
+
+        // See if the current character is a space, a break or a regular character
+        if((currentWidth > lineLength) || (*itr == '\n'))
+        {
+            // A non whitespace character has exceeded the line length.  Or a
+            // newline character has forced a line break.  Output the last
+            // line and start a new line after the break character.
+            // If we have not yet found a break, break on the last character
+            if(breakItr == lineStart || (*itr == '\n'))
+            {
+                // Break on the previous character
+                breakItr = prevItr;
+                breakCharCount = charCount - 1;
+                breakWidth = prevWidth;
+                // None of the previous words will be carried to the next line
+                wordLength = 0;
+                // If the current character is a newline discard its advance
+                if(*itr == '\n') advance = 0;
+            }
+
+            float remainingWidth = lineLength - breakWidth;
+
+            // Render the current substring
+            FTUnicodeStringItr<T> breakChar = breakItr;
+            // move past the break character and don't count it on the next line either
+            ++breakChar; --charCount;
+            // If the break character is a newline do not render it
+            if(*breakChar == '\n')
+            {
+                ++breakChar; --charCount;
+            }
+
+            OutputWrapped(lineStart.getBufferFromHere(), breakCharCount,
+                          //breakItr.getBufferFromHere() - lineStart.getBufferFromHere(),
+                          position, renderMode, remainingWidth, bounds);
+
+            // Store the start of the next line
+            lineStart = breakChar;
+            // TODO: Is Height() the right value here?
+            pen -= FTPoint(0, currentFont->LineHeight() * lineSpacing);
+            // The current width is the width since the last break
+            nextStart = wordLength + advance;
+            wordLength += advance;
+            currentWidth = wordLength + advance;
+            // Reset the safe break for the next line
+            breakItr = lineStart;
+            charCount -= breakCharCount;
+        }
+        else if(iswspace(*itr))
+        {
+            // This is the last word break position
+            wordLength = 0;
+            breakItr = itr;
+            breakCharCount = charCount;
+
+            // Check to see if this is the first whitespace character in a run
+            if(buf == itr.getBufferFromHere() || !iswspace(*prevItr))
+            {
+                // Record the width of the start of the block
+                breakWidth = currentWidth;
+            }
+        }
+        else
+        {
+            wordLength += advance;
+        }
+    }
+
+    float remainingWidth = lineLength - currentWidth;
+    // Render any remaining text on the last line
+    // Disable justification for the last row
+    if(alignment == FTGL::ALIGN_JUSTIFY)
+    {
+        alignment = FTGL::ALIGN_LEFT;
+        OutputWrapped(lineStart.getBufferFromHere(), -1, position, renderMode,
+                      remainingWidth, bounds);
+        alignment = FTGL::ALIGN_JUSTIFY;
+    }
+    else
+    {
+        OutputWrapped(lineStart.getBufferFromHere(), -1, position, renderMode,
+                      remainingWidth, bounds);
+    }
+}
+
+
+void FTSimpleLayoutImpl::WrapText(const char *buf, const int len,
+                                  FTPoint position, int renderMode,
+                                  FTBBox *bounds)
+{
+    WrapTextI(buf, len, position, renderMode, bounds);
+}
+
+
+void FTSimpleLayoutImpl::WrapText(const wchar_t* buf, const int len,
+                                  FTPoint position, int renderMode,
+                                  FTBBox *bounds)
+{
+    WrapTextI(buf, len, position, renderMode, bounds);
+}
+
+
+template <typename T>
+inline void FTSimpleLayoutImpl::OutputWrappedI(const T *buf, const int len,
+                                               FTPoint position, int renderMode,
+                                               const float remaining,
+                                               FTBBox *bounds)
+{
+    float distributeWidth = 0.0;
+    // Align the text according as specified by Alignment
+    switch (alignment)
+    {
+        case FTGL::ALIGN_LEFT:
+            pen.X(0);
+            break;
+        case FTGL::ALIGN_CENTER:
+            pen.X(remaining / 2);
+            break;
+        case FTGL::ALIGN_RIGHT:
+            pen.X(remaining);
+            break;
+        case FTGL::ALIGN_JUSTIFY:
+            pen.X(0);
+            distributeWidth = remaining;
+            break;
+    }
+
+    // If we have bounds expand them by the line's bounds, otherwise render
+    // the line.
+    if(bounds)
+    {
+        FTBBox temp = currentFont->BBox(buf, len);
+
+        // Add the extra space to the upper x dimension
+        temp = FTBBox(temp.Lower() + pen,
+                      temp.Upper() + pen + FTPoint(distributeWidth, 0));
+
+        // See if this is the first area to be added to the bounds
+        if(bounds->IsValid())
+        {
+            *bounds |= temp;
+        }
+        else
+        {
+            *bounds = temp;
+        }
+    }
+    else
+    {
+        RenderSpace(buf, len, position, renderMode, distributeWidth);
+    }
+}
+
+
+void FTSimpleLayoutImpl::OutputWrapped(const char *buf, const int len,
+                                       FTPoint position, int renderMode,
+                                       const float remaining, FTBBox *bounds)
+{
+    OutputWrappedI(buf, len, position, renderMode, remaining, bounds);
+}
+
+
+void FTSimpleLayoutImpl::OutputWrapped(const wchar_t *buf, const int len,
+                                       FTPoint position, int renderMode,
+                                       const float remaining, FTBBox *bounds)
+{
+    OutputWrappedI(buf, len, position, renderMode, remaining, bounds);
+}
+
+
+template <typename T>
+inline void FTSimpleLayoutImpl::RenderSpaceI(const T *string, const int len,
+                                             FTPoint position, int renderMode,
+                                             const float extraSpace)
+{
+    float space = 0.0;
+
+    // If there is space to distribute, count the number of spaces
+    if(extraSpace > 0.0)
+    {
+        int numSpaces = 0;
+
+        // Count the number of space blocks in the input
+        FTUnicodeStringItr<T> prevItr(string), itr(string);
+        for(int i = 0; ((len < 0) && *itr) || ((len >= 0) && (i <= len));
+            ++i, prevItr = itr++)
+        {
+            // If this is the end of a space block, increment the counter
+            if((i > 0) && !iswspace(*itr) && iswspace(*prevItr))
+            {
+                numSpaces++;
+            }
+        }
+
+        space = extraSpace/numSpaces;
+    }
+
+    // Output all characters of the string
+    FTUnicodeStringItr<T> prevItr(string), itr(string);
+    for(int i = 0; ((len < 0) && *itr) || ((len >= 0) && (i <= len));
+        ++i, prevItr = itr++)
+    {
+        // If this is the end of a space block, distribute the extra space
+        // inside it
+        if((i > 0) && !iswspace(*itr) && iswspace(*prevItr))
+        {
+            pen += FTPoint(space, 0);
+        }
+
+        pen = currentFont->Render(itr.getBufferFromHere(), 1, pen, FTPoint(), renderMode);
+    }
+}
+
+
+void FTSimpleLayoutImpl::RenderSpace(const char *string, const int len,
+                                     FTPoint position, int renderMode,
+                                     const float extraSpace)
+{
+    RenderSpaceI(string, len, position, renderMode, extraSpace);
+}
+
+
+void FTSimpleLayoutImpl::RenderSpace(const wchar_t *string, const int len,
+                                     FTPoint position, int renderMode,
+                                     const float extraSpace)
+{
+    RenderSpaceI(string, len, position, renderMode, extraSpace);
+}
+
diff --git a/src/ext/ftgl/FTLayout/FTSimpleLayoutImpl.h b/src/ext/ftgl/FTLayout/FTSimpleLayoutImpl.h
new file mode 100644
index 0000000..96a074d
--- /dev/null
+++ b/src/ext/ftgl/FTLayout/FTSimpleLayoutImpl.h
@@ -0,0 +1,225 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __FTSimpleLayoutImpl__
+#define __FTSimpleLayoutImpl__
+
+#include "FTLayoutImpl.h"
+
+
+class FTFont;
+
+class FTSimpleLayoutImpl : public FTLayoutImpl
+{
+    friend class FTSimpleLayout;
+
+    protected:
+        FTSimpleLayoutImpl();
+
+        virtual ~FTSimpleLayoutImpl() {};
+
+        virtual FTBBox BBox(const char* string, const int len,
+                            FTPoint position);
+
+        virtual FTBBox BBox(const wchar_t* string, const int len,
+                            FTPoint position);
+
+        virtual void Render(const char *string, const int len,
+                            FTPoint position, int renderMode);
+
+        virtual void Render(const wchar_t *string, const int len,
+                            FTPoint position, int renderMode);
+
+        /**
+         * Render a string of characters and distribute extra space amongst
+         * the whitespace regions of the string.
+         *
+         * @param string   A buffer of wchar_t characters to output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered.
+         * @param position TODO
+         * @param renderMode Render mode to display
+         * @param extraSpace The amount of extra space to distribute amongst
+         *                   the characters.
+         */
+        virtual void RenderSpace(const char *string, const int len,
+                                 FTPoint position, int renderMode,
+                                 const float extraSpace);
+
+        /**
+         * Render a string of characters and distribute extra space amongst
+         * the whitespace regions of the string.
+         *
+         * @param string   A buffer of wchar_t characters to output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered.
+         * @param position TODO
+         * @param renderMode Render mode to display
+         * @param extraSpace The amount of extra space to distribute amongst
+         *                   the characters.
+         */
+        virtual void RenderSpace(const wchar_t *string, const int len,
+                                 FTPoint position, int renderMode,
+                                 const float extraSpace);
+
+    private:
+        /**
+         * Either render a string of characters and wrap lines
+         * longer than a threshold or compute the bounds
+         * of a string of characters when wrapped.  The functionality
+         * of this method is exposed by the BBoxWrapped and
+         * RenderWrapped methods.
+         *
+         * @param buf  A char string to output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered.
+         * @param position TODO
+         * @param renderMode  Render mode to display
+         * @param bounds      A pointer to a bounds object.  If non null
+         *                    the bounds of the text when laid out
+         *                    will be stored in bounds.  If null the
+         *                    text will be rendered.
+         */
+        virtual void WrapText(const char *buf, const int len,
+                              FTPoint position, int renderMode,
+                              FTBBox *bounds);
+
+        /**
+         * Either render a string of characters and wrap lines
+         * longer than a threshold or compute the bounds
+         * of a string of characters when wrapped.  The functionality
+         * of this method is exposed by the BBoxWrapped and
+         * RenderWrapped methods.
+         *
+         * @param buf  A wchar_t style string to output.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered.
+         * @param position TODO
+         * @param renderMode  Render mode to display
+         * @param bounds      A pointer to a bounds object.  If non null
+         *                    the bounds of the text when laid out
+         *                    will be stored in bounds.  If null the
+         *                    text will be rendered.
+         */
+        virtual void WrapText(const wchar_t *buf, const int len,
+                              FTPoint position, int renderMode,
+                              FTBBox *bounds);
+
+        /**
+         * A helper method used by WrapText to either output the text or
+         * compute it's bounds.
+         *
+         * @param buf      A pointer to an array of character data.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered.
+         * @param position TODO
+         * @param renderMode  Render mode to display
+         * @param RemainingWidth The amount of extra space left on the line.
+         * @param bounds     A pointer to a bounds object.  If non null the
+         *                   bounds will be initialized or expanded by the
+         *                   bounds of the line.  If null the text will be
+         *                   rendered.  If the bounds are invalid (lower > upper)
+         *                   they will be initialized.  Otherwise they
+         *                   will be expanded.
+         */
+        void OutputWrapped(const char *buf, const int len,
+                           FTPoint position, int renderMode,
+                           const float RemainingWidth, FTBBox *bounds);
+
+        /**
+         * A helper method used by WrapText to either output the text or
+         * compute it's bounds.
+         *
+         * @param buf      A pointer to an array of character data.
+         * @param len  The length of the string. If < 0 then all characters
+         *             will be displayed until a null character is encountered.
+         * @param position TODO
+         * @param renderMode  Render mode to display
+         * @param RemainingWidth The amount of extra space left on the line.
+         * @param bounds     A pointer to a bounds object.  If non null the
+         *                   bounds will be initialized or expanded by the
+         *                   bounds of the line.  If null the text will be
+         *                   rendered.  If the bounds are invalid (lower > upper)
+         *                   they will be initialized.  Otherwise they
+         *                   will be expanded.
+         */
+        void OutputWrapped(const wchar_t *buf, const int len,
+                           FTPoint position, int renderMode,
+                           const float RemainingWidth, FTBBox *bounds);
+
+        /**
+         * The font to use for rendering the text.  The font is
+         * referenced by this but will not be disposed of when this
+         * is deleted.
+         */
+        FTFont *currentFont;
+
+        /**
+         * The maximum line length for formatting text.
+         */
+        float lineLength;
+
+        /**
+         * The text alignment mode used to distribute
+         * space within a line or rendered text.
+         */
+        FTGL::TextAlignment alignment;
+
+        /**
+         * The height of each line of text expressed as
+         * a percentage of the font's line height.
+         */
+        float lineSpacing;
+
+        /* Internal generic BBox() implementation */
+        template <typename T>
+        inline FTBBox BBoxI(const T* string, const int len, FTPoint position);
+
+        /* Internal generic Render() implementation */
+        template <typename T>
+        inline void RenderI(const T* string, const int len,
+                            FTPoint position, int renderMode);
+
+        /* Internal generic RenderSpace() implementation */
+        template <typename T>
+        inline void RenderSpaceI(const T* string, const int len,
+                                 FTPoint position, int renderMode,
+                                 const float extraSpace);
+
+        /* Internal generic WrapText() implementation */
+        template <typename T>
+        void WrapTextI(const T* buf, const int len, FTPoint position,
+                       int renderMode, FTBBox *bounds);
+
+        /* Internal generic OutputWrapped() implementation */
+        template <typename T>
+        void OutputWrappedI(const T* buf, const int len, FTPoint position,
+                            int renderMode, const float RemainingWidth,
+                            FTBBox *bounds);
+};
+
+#endif  //  __FTSimpleLayoutImpl__
+
diff --git a/src/ext/ftgl/FTLibrary.cpp b/src/ext/ftgl/FTLibrary.cpp
new file mode 100644
index 0000000..66074c3
--- /dev/null
+++ b/src/ext/ftgl/FTLibrary.cpp
@@ -0,0 +1,91 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTLibrary.h"
+
+
+const FTLibrary&  FTLibrary::Instance()
+{
+    static FTLibrary ftlib;
+    return ftlib;
+}
+
+
+FTLibrary::~FTLibrary()
+{
+    if(library != 0)
+    {
+        FT_Done_FreeType(*library);
+
+        delete library;
+        library= 0;
+    }
+
+//  if(manager != 0)
+//  {
+//      FTC_Manager_Done(manager);
+//
+//      delete manager;
+//      manager= 0;
+//  }
+}
+
+
+FTLibrary::FTLibrary()
+:   library(0),
+    err(0)
+{
+    Initialise();
+}
+
+
+bool FTLibrary::Initialise()
+{
+    if(library != 0)
+        return true;
+
+    library = new FT_Library;
+
+    err = FT_Init_FreeType(library);
+    if(err)
+    {
+        delete library;
+        library = 0;
+        return false;
+    }
+
+//  FTC_Manager* manager;
+//
+//  if(FTC_Manager_New(lib, 0, 0, 0, my_face_requester, 0, manager)
+//  {
+//      delete manager;
+//      manager= 0;
+//      return false;
+//  }
+
+    return true;
+}
diff --git a/src/ext/ftgl/FTLibrary.h b/src/ext/ftgl/FTLibrary.h
new file mode 100644
index 0000000..951fecc
--- /dev/null
+++ b/src/ext/ftgl/FTLibrary.h
@@ -0,0 +1,122 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTLibrary__
+#define     __FTLibrary__
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+//#include FT_CACHE_H
+
+#include "FTGL/ftgl.h"
+
+
+/**
+ * FTLibrary class is the global accessor for the Freetype library.
+ *
+ * This class encapsulates the Freetype Library. This is a singleton class
+ * and ensures that only one FT_Library is in existence at any one time.
+ * All constructors are private therefore clients cannot create or
+ * instantiate this class themselves and must access it's methods via the
+ * static <code>FTLibrary::Instance()</code> function.
+ *
+ * Just because this class returns a valid <code>FTLibrary</code> object
+ * doesn't mean that the Freetype Library has been successfully initialised.
+ * Clients should check for errors. You can initialse the library AND check
+ * for errors using the following code...
+ * <code>err = FTLibrary::Instance().Error();</code>
+ *
+ * @see "Freetype 2 Documentation"
+ *
+ */
+class FTLibrary
+{
+    public:
+        /**
+         * Global acces point to the single FTLibrary object.
+         *
+         * @return  The global <code>FTLibrary</code> object.
+         */
+        static const FTLibrary& Instance();
+
+        /**
+         * Gets a pointer to the native Freetype library.
+         *
+         * @return A handle to a FreeType library instance.
+         */
+        const FT_Library* const GetLibrary() const { return library; }
+
+        /**
+         * Queries the library for errors.
+         *
+         * @return  The current error code.
+         */
+        FT_Error Error() const { return err; }
+
+        /**
+         * Destructor
+         *
+         * Disposes of the Freetype library
+         */
+        ~FTLibrary();
+
+    private:
+        /**
+         * Default constructors.
+         *
+         * Made private to stop clients creating there own FTLibrary
+         * objects.
+         */
+        FTLibrary();
+        FTLibrary(const FT_Library&){}
+        FTLibrary& operator=(const FT_Library&) { return *this; }
+
+        /**
+         * Initialises the Freetype library
+         *
+         * Even though this function indicates success via the return value,
+         * clients can't see this so must check the error codes. This function
+         * is only ever called by the default c_stor
+         *
+         * @return  <code>true</code> if the Freetype library was
+         *          successfully initialised, <code>false</code>
+         *          otherwise.
+         */
+        bool Initialise();
+
+        /**
+         * Freetype library handle.
+         */
+        FT_Library* library;
+//      FTC_Manager* manager;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+
+};
+
+#endif  //  __FTLibrary__
diff --git a/src/ext/ftgl/FTList.h b/src/ext/ftgl/FTList.h
new file mode 100644
index 0000000..1440667
--- /dev/null
+++ b/src/ext/ftgl/FTList.h
@@ -0,0 +1,137 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef    __FTList__
+#define    __FTList__
+
+#include "FTGL/ftgl.h"
+
+/**
+* Provides a non-STL alternative to the STL list
+ */
+template <typename FT_LIST_ITEM_TYPE>
+class FTList
+{
+    public:
+        typedef FT_LIST_ITEM_TYPE value_type;
+        typedef value_type& reference;
+        typedef const value_type& const_reference;
+        typedef size_t size_type;
+
+        /**
+         * Constructor
+         */
+        FTList()
+        :   listSize(0),
+            tail(0)
+        {
+            tail = NULL;
+            head = new Node;
+        }
+
+        /**
+         * Destructor
+         */
+        ~FTList()
+        {
+            Node* next;
+
+            for(Node *walk = head; walk; walk = next)
+            {
+                next = walk->next;
+                delete walk;
+            }
+        }
+
+        /**
+         * Get the number of items in the list
+         */
+        size_type size() const
+        {
+            return listSize;
+        }
+
+        /**
+         * Add an item to the end of the list
+         */
+        void push_back(const value_type& item)
+        {
+            Node* node = new Node(item);
+
+            if(head->next == NULL)
+            {
+                head->next = node;
+            }
+
+            if(tail)
+            {
+                tail->next = node;
+            }
+            tail = node;
+            ++listSize;
+        }
+
+        /**
+         * Get the item at the front of the list
+         */
+        reference front() const
+        {
+            return head->next->payload;
+        }
+
+        /**
+         * Get the item at the end of the list
+         */
+        reference back() const
+        {
+            return tail->payload;
+        }
+
+    private:
+        struct Node
+        {
+            Node()
+            : next(NULL)
+            {}
+
+            Node(const value_type& item)
+            : next(NULL)
+            {
+                payload = item;
+            }
+
+            Node* next;
+
+            value_type payload;
+        };
+
+        size_type listSize;
+
+        Node* head;
+        Node* tail;
+};
+
+#endif // __FTList__
+
diff --git a/src/ext/ftgl/FTPoint.cpp b/src/ext/ftgl/FTPoint.cpp
new file mode 100644
index 0000000..cc02e5a
--- /dev/null
+++ b/src/ext/ftgl/FTPoint.cpp
@@ -0,0 +1,58 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include <math.h>
+
+#include "FTGL/ftgl.h"
+
+bool operator == (const FTPoint &a, const FTPoint &b)
+{
+    return((a.values[0] == b.values[0]) && (a.values[1] == b.values[1]) && (a.values[2] == b.values[2]));
+}
+
+
+bool operator != (const FTPoint &a, const FTPoint &b)
+{
+    return((a.values[0] != b.values[0]) || (a.values[1] != b.values[1]) || (a.values[2] != b.values[2]));
+}
+
+
+FTPoint FTPoint::Normalise()
+{
+    double norm = sqrt(values[0] * values[0]
+                       + values[1] * values[1]
+                       + values[2] * values[2]);
+    if(norm == 0.0)
+    {
+        return *this;
+    }
+
+    FTPoint temp(values[0] / norm, values[1] / norm, values[2] / norm);
+    return temp;
+}
+
diff --git a/src/ext/ftgl/FTSize.cpp b/src/ext/ftgl/FTSize.cpp
new file mode 100644
index 0000000..49f1596
--- /dev/null
+++ b/src/ext/ftgl/FTSize.cpp
@@ -0,0 +1,123 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTSize.h"
+
+
+FTSize::FTSize()
+:   ftFace(0),
+    ftSize(0),
+    size(0),
+    xResolution(0),
+    yResolution(0),
+    err(0)
+{}
+
+
+FTSize::~FTSize()
+{}
+
+
+bool FTSize::CharSize(FT_Face* face, unsigned int pointSize, unsigned int xRes, unsigned int yRes)
+{
+    if(size != pointSize || xResolution != xRes || yResolution != yRes)
+    {
+        err = FT_Set_Char_Size(*face, 0L, pointSize * 64, xResolution, yResolution);
+
+        if(!err)
+        {
+            ftFace = face;
+            size = pointSize;
+            xResolution = xRes;
+            yResolution = yRes;
+            ftSize = (*ftFace)->size;
+        }
+    }
+
+    return !err;
+}
+
+
+unsigned int FTSize::CharSize() const
+{
+    return size;
+}
+
+
+float FTSize::Ascender() const
+{
+    return ftSize == 0 ? 0.0f : static_cast<float>(ftSize->metrics.ascender) / 64.0f;
+}
+
+
+float FTSize::Descender() const
+{
+    return ftSize == 0 ? 0.0f : static_cast<float>(ftSize->metrics.descender) / 64.0f;
+}
+
+
+float FTSize::Height() const
+{
+    if(0 == ftSize)
+    {
+        return 0.0f;
+    }
+
+    if(FT_IS_SCALABLE((*ftFace)))
+    {
+        return ((*ftFace)->bbox.yMax - (*ftFace)->bbox.yMin) * ((float)ftSize->metrics.y_ppem / (float)(*ftFace)->units_per_EM);
+    }
+    else
+    {
+        return static_cast<float>(ftSize->metrics.height) / 64.0f;
+    }
+}
+
+
+float FTSize::Width() const
+{
+    if(0 == ftSize)
+    {
+        return 0.0f;
+    }
+
+    if(FT_IS_SCALABLE((*ftFace)))
+    {
+        return ((*ftFace)->bbox.xMax - (*ftFace)->bbox.xMin) * (static_cast<float>(ftSize->metrics.x_ppem) / static_cast<float>((*ftFace)->units_per_EM));
+    }
+    else
+    {
+        return static_cast<float>(ftSize->metrics.max_advance) / 64.0f;
+    }
+}
+
+
+float FTSize::Underline() const
+{
+    return 0.0f;
+}
+
diff --git a/src/ext/ftgl/FTSize.h b/src/ext/ftgl/FTSize.h
new file mode 100644
index 0000000..4ba2666
--- /dev/null
+++ b/src/ext/ftgl/FTSize.h
@@ -0,0 +1,164 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTSize__
+#define     __FTSize__
+
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+
+#include "FTGL/ftgl.h"
+
+
+
+/**
+ * FTSize class provides an abstraction layer for the Freetype Size.
+ *
+ * @see "Freetype 2 Documentation"
+ *
+ */
+class FTSize
+{
+    public:
+        /**
+         * Default Constructor
+         */
+         FTSize();
+
+        /**
+         * Destructor
+         */
+        virtual ~FTSize();
+
+        /**
+         * Sets the char size for the current face.
+         *
+         * This doesn't guarantee that the size was set correctly. Clients
+         * should check errors. If an error does occur the size object isn't modified.
+         *
+         * @param face           Parent face for this size object
+         * @param point_size     the face size in points (1/72 inch)
+         * @param x_resolution   the horizontal resolution of the target device.
+         * @param y_resolution   the vertical resolution of the target device.
+         * @return          <code>true</code> if the size has been set. Clients should check Error() for more information if this function returns false()
+         */
+        bool CharSize(FT_Face* face, unsigned int point_size,
+                      unsigned int x_resolution, unsigned int y_resolution);
+
+        /**
+         * get the char size for the current face.
+         *
+         * @return The char size in points
+         */
+        unsigned int CharSize() const;
+
+        /**
+         * Gets the global ascender height for the face in pixels.
+         *
+         * @return  Ascender height
+         */
+        float Ascender() const;
+
+        /**
+         * Gets the global descender height for the face in pixels.
+         *
+         * @return  Ascender height
+         */
+        float Descender() const;
+
+        /**
+         * Gets the global face height for the face.
+         *
+         * If the face is scalable this returns the height of the global
+         * bounding box which ensures that any glyph will be less than or
+         * equal to this height. If the font isn't scalable there is no
+         * guarantee that glyphs will not be taller than this value.
+         *
+         * @return  height in pixels.
+         */
+        float Height() const;
+
+        /**
+         * Gets the global face width for the face.
+         *
+         * If the face is scalable this returns the width of the global
+         * bounding box which ensures that any glyph will be less than or
+         * equal to this width. If the font isn't scalable this value is
+         * the max_advance for the face.
+         *
+         * @return  width in pixels.
+         */
+        float Width() const;
+
+        /**
+         * Gets the underline position for the face.
+         *
+         * @return  underline position in pixels
+         */
+        float Underline() const;
+
+        /**
+         * Queries for errors.
+         *
+         * @return  The current error code.
+         */
+        FT_Error Error() const { return err; }
+
+    private:
+        /**
+         * The current Freetype face that this FTSize object relates to.
+         */
+        FT_Face* ftFace;
+
+        /**
+         *  The Freetype size.
+         */
+        FT_Size ftSize;
+
+        /**
+         *  The size in points.
+         */
+        unsigned int size;
+
+        /**
+         *  The horizontal resolution.
+         */
+        unsigned int xResolution;
+
+        /**
+         *  The vertical resolution.
+         */
+        unsigned int yResolution;
+
+        /**
+         * Current error code. Zero means no error.
+         */
+        FT_Error err;
+
+};
+
+#endif  //  __FTSize__
+
diff --git a/src/ext/ftgl/FTUnicode.h b/src/ext/ftgl/FTUnicode.h
new file mode 100644
index 0000000..6c74100
--- /dev/null
+++ b/src/ext/ftgl/FTUnicode.h
@@ -0,0 +1,237 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2008 Daniel Remenak <dtremenak at users.sourceforge.net>
+ *
+ * Portions derived from ConvertUTF.c Copyright (C) 2001-2004 Unicode, Inc
+ *   Unicode, Inc. hereby grants the right to freely use the information
+ *   supplied in this file in the creation of products supporting the
+ *   Unicode Standard, and to make copies of this file in any form
+ *   for internal or external distribution as long as this notice
+ *   remains attached.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef    __FTUnicode__
+#define    __FTUnicode__
+
+/**
+ * Provides a way to easily walk multibyte unicode strings in the various
+ * Unicode encodings (UTF-8, UTF-16, UTF-32, UCS-2, and UCS-4).  Encodings
+ * with elements larger than one byte must already be in the correct endian
+ * order for the current architecture.
+ */
+template <typename T>
+class FTUnicodeStringItr
+{
+public:
+    /**
+     * Constructor.  Also reads the first character and stores it.
+     *
+     * @param string  The buffer to iterate.  No copy is made.
+     */
+    FTUnicodeStringItr(const T* string) : curPos(string), nextPos(string)
+    {
+        (*this)++;
+    };
+
+    /**
+     * Pre-increment operator.  Reads the next unicode character and sets
+     * the state appropriately.
+     * Note - not protected against overruns.
+     */
+    FTUnicodeStringItr& operator++()
+    {
+        curPos = nextPos;
+        // unicode handling
+        switch (sizeof(T))
+        {
+            case 1: // UTF-8
+                // get this character
+                readUTF8(); break;
+            case 2: // UTF-16
+                readUTF16(); break;
+            case 4: // UTF-32
+                // fall through
+            default: // error condition really, but give it a shot anyway
+                curChar = *nextPos++;
+        }
+        return *this;
+    }
+
+    /**
+     * Post-increment operator.  Reads the next character and sets
+     * the state appropriately.
+     * Note - not protected against overruns.
+     */
+    FTUnicodeStringItr operator++(int)
+    {
+        FTUnicodeStringItr temp = *this;
+        ++*this;
+        return temp;
+    }
+
+    /**
+     * Equality operator.  Two FTUnicodeStringItrs are considered equal
+     * if they have the same current buffer and buffer position.
+     */
+    bool operator==(const FTUnicodeStringItr& right) const
+    {
+        if (curPos == right.getBufferFromHere())
+            return true;
+        return false;
+    }
+
+    /**
+     * Dereference operator.
+     *
+     * @return  The unicode codepoint of the character currently pointed
+     * to by the FTUnicodeStringItr.
+     */
+    unsigned int operator*() const
+    {
+        return curChar;
+    }
+
+    /**
+     * Buffer-fetching getter.  You can use this to retreive the buffer
+     * starting at the currently-iterated character for functions which
+     * require a Unicode string as input.
+     */
+    const T* getBufferFromHere() const { return curPos; }
+
+private:
+    /**
+     * Helper function for reading a single UTF8 character from the string.
+     * Updates internal state appropriately.
+     */
+    void readUTF8();
+
+    /**
+     * Helper function for reading a single UTF16 character from the string.
+     * Updates internal state appropriately.
+     */
+    void readUTF16();
+
+    /**
+     * The buffer position of the first element in the current character.
+     */
+    const T* curPos;
+
+    /**
+     * The character stored at the current buffer position (prefetched on
+     * increment, so there's no penalty for dereferencing more than once).
+     */
+    unsigned int curChar;
+
+    /**
+     * The buffer position of the first element in the next character.
+     */
+    const T* nextPos;
+
+    // unicode magic numbers
+    static const char utf8bytes[256];
+    static const unsigned long offsetsFromUTF8[6];
+    static const unsigned long highSurrogateStart;
+    static const unsigned long highSurrogateEnd;
+    static const unsigned long lowSurrogateStart;
+    static const unsigned long lowSurrogateEnd;
+    static const unsigned long highSurrogateShift;
+    static const unsigned long lowSurrogateBase;
+};
+
+/* The first character in a UTF8 sequence indicates how many bytes
+ * to read (among other things) */
+template <typename T>
+const char FTUnicodeStringItr<T>::utf8bytes[256] = {
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,5,5,5,5,6,6,6,6
+};
+
+/* Magic values subtracted from a buffer value during UTF8 conversion.
+ * This table contains as many values as there might be trailing bytes
+ * in a UTF-8 sequence. */
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
+  0x03C82080UL, 0xFA082080UL, 0x82082080UL };
+
+// get a UTF8 character; leave the tracking pointer at the start of the
+// next character
+// not protected against invalid UTF8
+template <typename T>
+inline void FTUnicodeStringItr<T>::readUTF8()
+{
+    unsigned int ch = 0;
+    unsigned int extraBytesToRead = utf8bytes[(unsigned char)(*nextPos)];
+    // falls through
+    switch (extraBytesToRead)
+    {
+          case 6: ch += *nextPos++; ch <<= 6; /* remember, illegal UTF-8 */
+          case 5: ch += *nextPos++; ch <<= 6; /* remember, illegal UTF-8 */
+          case 4: ch += *nextPos++; ch <<= 6;
+          case 3: ch += *nextPos++; ch <<= 6;
+          case 2: ch += *nextPos++; ch <<= 6;
+          case 1: ch += *nextPos++;
+    }
+    ch -= offsetsFromUTF8[extraBytesToRead-1];
+    curChar = ch;
+}
+
+// Magic numbers for UTF-16 conversions
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::highSurrogateStart = 0xD800;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::highSurrogateEnd = 0xDBFF;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::lowSurrogateStart = 0xDC00;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::lowSurrogateEnd = 0xDFFF;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::highSurrogateShift = 10;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::lowSurrogateBase = 0x0010000UL;
+
+template <typename T>
+inline void FTUnicodeStringItr<T>::readUTF16()
+{
+    unsigned int ch = *nextPos++;
+    // if we have the first half of the surrogate pair
+    if (ch >= highSurrogateStart && ch <= highSurrogateEnd)
+    {
+        unsigned int ch2 = *curPos;
+        // complete the surrogate pair
+        if (ch2 >= lowSurrogateStart && ch2 <= lowSurrogateEnd)
+        {
+            ch = ((ch - highSurrogateStart) << highSurrogateShift)
+                + (ch2 - lowSurrogateStart) + lowSurrogateBase;
+            ++nextPos;
+        }
+    }
+    curChar = ch;
+}
+
+#endif
diff --git a/src/ext/ftgl/FTVector.h b/src/ext/ftgl/FTVector.h
new file mode 100644
index 0000000..ceac72a
--- /dev/null
+++ b/src/ext/ftgl/FTVector.h
@@ -0,0 +1,215 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef    __FTVector__
+#define    __FTVector__
+
+#include "FTGL/ftgl.h"
+
+/**
+ * Provides a non-STL alternative to the STL vector
+ */
+template <typename FT_VECTOR_ITEM_TYPE>
+class FTVector
+{
+    public:
+        typedef FT_VECTOR_ITEM_TYPE value_type;
+        typedef value_type& reference;
+        typedef const value_type& const_reference;
+        typedef value_type* iterator;
+        typedef const value_type* const_iterator;
+        typedef size_t size_type;
+
+        FTVector()
+        {
+            Capacity = Size = 0;
+            Items = 0;
+        }
+
+
+        virtual ~FTVector()
+        {
+            clear();
+        }
+
+        FTVector& operator =(const FTVector& v)
+        {
+            reserve(v.capacity());
+
+            iterator ptr = begin();
+            const_iterator vbegin = v.begin();
+            const_iterator vend = v.end();
+
+            while(vbegin != vend)
+            {
+                *ptr++ = *vbegin++;
+            }
+
+            Size = v.size();
+            return *this;
+        }
+
+        size_type size() const
+        {
+            return Size;
+        }
+
+        size_type capacity() const
+        {
+            return Capacity;
+        }
+
+        iterator begin()
+        {
+            return Items;
+        }
+
+        const_iterator begin() const
+        {
+            return Items;
+        }
+
+        iterator end()
+        {
+            return begin() + size();
+        }
+
+        const_iterator end() const
+        {
+            return begin() + size();
+        }
+
+        bool empty() const
+        {
+            return size() == 0;
+        }
+
+        reference operator [](size_type pos)
+        {
+            return(*(begin() + pos));
+        }
+
+        const_reference operator [](size_type pos) const
+        {
+            return *(begin() + pos);
+        }
+
+        void clear()
+        {
+            if(Capacity)
+            {
+                delete [] Items;
+                Capacity = Size = 0;
+                Items = 0;
+            }
+        }
+
+        void reserve(size_type n)
+        {
+            if(capacity() < n)
+            {
+                expand(n);
+            }
+        }
+
+        void push_back(const value_type& x)
+        {
+            if(size() == capacity())
+            {
+                expand();
+            }
+
+           (*this)[size()] = x;
+            ++Size;
+        }
+
+        void resize(size_type n, value_type x)
+        {
+            if(n == size())
+            {
+                return;
+            }
+
+            reserve(n);
+            iterator ibegin, iend;
+
+            if(n >= Size)
+            {
+                ibegin = this->end();
+                iend = this->begin() + n;
+            }
+            else
+            {
+                ibegin = this->begin() + n;
+                iend = this->end();
+            }
+
+            while(ibegin != iend)
+            {
+                *ibegin++ = x;
+            }
+
+            Size = n;
+        }
+
+
+    private:
+        void expand(size_type capacity_hint = 0)
+        {
+            size_type new_capacity = (capacity() == 0) ? 256 : capacity() * 2;
+            if(capacity_hint)
+            {
+                while(new_capacity < capacity_hint)
+                {
+                    new_capacity *= 2;
+                }
+            }
+
+            value_type *new_items = new value_type[new_capacity];
+
+            iterator ibegin = this->begin();
+            iterator iend = this->end();
+            value_type *ptr = new_items;
+
+            while(ibegin != iend)
+            {
+                *ptr++ = *ibegin++;
+            }
+
+            if(Capacity)
+            {
+                delete [] Items;
+            }
+
+            Items = new_items;
+            Capacity = new_capacity;
+        }
+
+        size_type Capacity;
+        size_type Size;
+        value_type* Items;
+};
+
+#endif  //  __FTVector__
diff --git a/src/ext/ftgl/FTVectoriser.cpp b/src/ext/ftgl/FTVectoriser.cpp
new file mode 100644
index 0000000..ea5c571
--- /dev/null
+++ b/src/ext/ftgl/FTVectoriser.cpp
@@ -0,0 +1,328 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Éric Beets <ericbeets at free.fr>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include "config.h"
+
+#include "FTInternals.h"
+#include "FTVectoriser.h"
+
+#ifndef CALLBACK
+#define CALLBACK
+#endif
+
+#if defined __APPLE_CC__ && __APPLE_CC__ < 5465
+    typedef GLvoid (*GLUTesselatorFunction) (...);
+#elif defined WIN32 && !defined __CYGWIN__
+    typedef GLvoid (CALLBACK *GLUTesselatorFunction) ();
+#else
+    typedef GLvoid (*GLUTesselatorFunction) ();
+#endif
+
+
+void CALLBACK ftglError(GLenum errCode, FTMesh* mesh)
+{
+    mesh->Error(errCode);
+}
+
+
+void CALLBACK ftglVertex(void* data, FTMesh* mesh)
+{
+    FTGL_DOUBLE* vertex = static_cast<FTGL_DOUBLE*>(data);
+    mesh->AddPoint(vertex[0], vertex[1], vertex[2]);
+}
+
+
+void CALLBACK ftglCombine(FTGL_DOUBLE coords[3], void* vertex_data[4], GLfloat weight[4], void** outData, FTMesh* mesh)
+{
+    const FTGL_DOUBLE* vertex = static_cast<const FTGL_DOUBLE*>(coords);
+    *outData = const_cast<FTGL_DOUBLE*>(mesh->Combine(vertex[0], vertex[1], vertex[2]));
+}
+
+void CALLBACK ftglBegin(GLenum type, FTMesh* mesh)
+{
+    mesh->Begin(type);
+}
+
+
+void CALLBACK ftglEnd(FTMesh* mesh)
+{
+    mesh->End();
+}
+
+
+FTMesh::FTMesh()
+: currentTesselation(0),
+    err(0)
+{
+    tesselationList.reserve(16);
+}
+
+
+FTMesh::~FTMesh()
+{
+    for(size_t t = 0; t < tesselationList.size(); ++t)
+    {
+        delete tesselationList[t];
+    }
+
+    tesselationList.clear();
+}
+
+
+void FTMesh::AddPoint(const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
+{
+    currentTesselation->AddPoint(x, y, z);
+}
+
+
+const FTGL_DOUBLE* FTMesh::Combine(const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
+{
+    tempPointList.push_back(FTPoint(x, y,z));
+    return static_cast<const FTGL_DOUBLE*>(tempPointList.back());
+}
+
+
+void FTMesh::Begin(GLenum meshType)
+{
+    currentTesselation = new FTTesselation(meshType);
+}
+
+
+void FTMesh::End()
+{
+    tesselationList.push_back(currentTesselation);
+}
+
+
+const FTTesselation* const FTMesh::Tesselation(size_t index) const
+{
+    return (index < tesselationList.size()) ? tesselationList[index] : NULL;
+}
+
+
+FTVectoriser::FTVectoriser(const FT_GlyphSlot glyph)
+:   contourList(0),
+    mesh(0),
+    ftContourCount(0),
+    contourFlag(0)
+{
+    if(glyph)
+    {
+        outline = glyph->outline;
+
+        ftContourCount = outline.n_contours;
+        contourList = 0;
+        contourFlag = outline.flags;
+
+        ProcessContours();
+    }
+}
+
+
+FTVectoriser::~FTVectoriser()
+{
+    for(size_t c = 0; c < ContourCount(); ++c)
+    {
+        delete contourList[c];
+    }
+
+    delete [] contourList;
+    delete mesh;
+}
+
+
+void FTVectoriser::ProcessContours()
+{
+    short contourLength = 0;
+    short startIndex = 0;
+    short endIndex = 0;
+
+    contourList = new FTContour*[ftContourCount];
+
+    for(int i = 0; i < ftContourCount; ++i)
+    {
+        FT_Vector* pointList = &outline.points[startIndex];
+        char* tagList = &outline.tags[startIndex];
+
+        endIndex = outline.contours[i];
+        contourLength =  (endIndex - startIndex) + 1;
+
+        FTContour* contour = new FTContour(pointList, tagList, contourLength);
+
+        contourList[i] = contour;
+
+        startIndex = endIndex + 1;
+    }
+
+    // Compute each contour's parity. FIXME: see if FT_Outline_Get_Orientation
+    // can do it for us.
+    for(int i = 0; i < ftContourCount; i++)
+    {
+        FTContour *c1 = contourList[i];
+
+        // 1. Find the leftmost point.
+        FTPoint leftmost(65536.0, 0.0);
+
+        for(size_t n = 0; n < c1->PointCount(); n++)
+        {
+            FTPoint p = c1->Point(n);
+            if(p.X() < leftmost.X())
+            {
+                leftmost = p;
+            }
+        }
+
+        // 2. Count how many other contours we cross when going further to
+        // the left.
+        int parity = 0;
+
+        for(int j = 0; j < ftContourCount; j++)
+        {
+            if(j == i)
+            {
+                continue;
+            }
+
+            FTContour *c2 = contourList[j];
+
+            for(size_t n = 0; n < c2->PointCount(); n++)
+            {
+                FTPoint p1 = c2->Point(n);
+                FTPoint p2 = c2->Point((n + 1) % c2->PointCount());
+
+                /* FIXME: combinations of >= > <= and < do not seem stable */
+                if((p1.Y() < leftmost.Y() && p2.Y() < leftmost.Y())
+                    || (p1.Y() >= leftmost.Y() && p2.Y() >= leftmost.Y())
+                    || (p1.X() > leftmost.X() && p2.X() > leftmost.X()))
+                {
+                    continue;
+                }
+                else if(p1.X() < leftmost.X() && p2.X() < leftmost.X())
+                {
+                    parity++;
+                }
+                else
+                {
+                    FTPoint a = p1 - leftmost;
+                    FTPoint b = p2 - leftmost;
+                    if(b.X() * a.Y() > b.Y() * a.X())
+                    {
+                        parity++;
+                    }
+                }
+            }
+        }
+
+        // 3. Make sure the glyph has the proper parity.
+        c1->SetParity(parity);
+    }
+}
+
+
+size_t FTVectoriser::PointCount()
+{
+    size_t s = 0;
+    for(size_t c = 0; c < ContourCount(); ++c)
+    {
+        s += contourList[c]->PointCount();
+    }
+
+    return s;
+}
+
+
+const FTContour* const FTVectoriser::Contour(size_t index) const
+{
+    return (index < ContourCount()) ? contourList[index] : NULL;
+}
+
+
+void FTVectoriser::MakeMesh(FTGL_DOUBLE zNormal, int outsetType, float outsetSize)
+{
+    if(mesh)
+    {
+        delete mesh;
+    }
+
+    mesh = new FTMesh;
+
+    GLUtesselator* tobj = gluNewTess();
+
+    gluTessCallback(tobj, GLU_TESS_BEGIN_DATA,     (GLUTesselatorFunction)ftglBegin);
+    gluTessCallback(tobj, GLU_TESS_VERTEX_DATA,    (GLUTesselatorFunction)ftglVertex);
+    gluTessCallback(tobj, GLU_TESS_COMBINE_DATA,   (GLUTesselatorFunction)ftglCombine);
+    gluTessCallback(tobj, GLU_TESS_END_DATA,       (GLUTesselatorFunction)ftglEnd);
+    gluTessCallback(tobj, GLU_TESS_ERROR_DATA,     (GLUTesselatorFunction)ftglError);
+
+    if(contourFlag & ft_outline_even_odd_fill) // ft_outline_reverse_fill
+    {
+        gluTessProperty(tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD);
+    }
+    else
+    {
+        gluTessProperty(tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NONZERO);
+    }
+
+
+    gluTessProperty(tobj, GLU_TESS_TOLERANCE, 0);
+    gluTessNormal(tobj, 0.0f, 0.0f, zNormal);
+    gluTessBeginPolygon(tobj, mesh);
+
+        for(size_t c = 0; c < ContourCount(); ++c)
+        {
+            /* Build the */
+            switch(outsetType)
+            {
+                case 1 : contourList[c]->buildFrontOutset(outsetSize); break;
+                case 2 : contourList[c]->buildBackOutset(outsetSize); break;
+            }
+            const FTContour* contour = contourList[c];
+
+
+            gluTessBeginContour(tobj);
+                for(size_t p = 0; p < contour->PointCount(); ++p)
+                {
+                    const FTGL_DOUBLE* d;
+                    switch(outsetType)
+                    {
+                        case 1: d = contour->FrontPoint(p); break;
+                        case 2: d = contour->BackPoint(p); break;
+                        case 0: default: d = contour->Point(p); break;
+                    }
+                    // XXX: gluTessVertex doesn't modify the data but does not
+                    // specify "const" in its prototype, so we cannot cast to
+                    // a const type.
+                    gluTessVertex(tobj, (GLdouble *)d, (GLvoid *)d);
+                }
+
+            gluTessEndContour(tobj);
+        }
+    gluTessEndPolygon(tobj);
+
+    gluDeleteTess(tobj);
+}
+
diff --git a/src/ext/ftgl/FTVectoriser.h b/src/ext/ftgl/FTVectoriser.h
new file mode 100644
index 0000000..942aea1
--- /dev/null
+++ b/src/ext/ftgl/FTVectoriser.h
@@ -0,0 +1,313 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl at opengl.geek.nz>
+ * Copyright (c) 2008 Sam Hocevar <sam at zoy.org>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef     __FTVectoriser__
+#define     __FTVectoriser__
+
+#include "FTGL/ftgl.h"
+
+#include "FTContour.h"
+#include "FTList.h"
+#include "FTVector.h"
+
+
+#ifndef CALLBACK
+#define CALLBACK
+#endif
+
+
+/**
+ * FTTesselation captures points that are output by OpenGL's gluTesselator.
+ */
+class FTTesselation
+{
+    public:
+        /**
+         * Default constructor
+         */
+        FTTesselation(GLenum m)
+        : meshType(m)
+        {
+            pointList.reserve(128);
+        }
+
+        /**
+         *  Destructor
+         */
+        ~FTTesselation()
+        {
+            pointList.clear();
+        }
+
+        /**
+         * Add a point to the mesh.
+         */
+        void AddPoint(const FTGL_DOUBLE x, const FTGL_DOUBLE y,
+                      const FTGL_DOUBLE z)
+        {
+            pointList.push_back(FTPoint(x, y, z));
+        }
+
+        /**
+         * The number of points in this mesh
+         */
+        size_t PointCount() const { return pointList.size(); }
+
+        /**
+         *
+         */
+        const FTPoint& Point(unsigned int index) const
+        { return pointList[index]; }
+
+        /**
+         * Return the OpenGL polygon type.
+         */
+        GLenum PolygonType() const { return meshType; }
+
+    private:
+        /**
+         * Points generated by gluTesselator.
+         */
+        typedef FTVector<FTPoint> PointVector;
+        PointVector pointList;
+
+        /**
+         * OpenGL primitive type from gluTesselator.
+         */
+        GLenum meshType;
+};
+
+
+/**
+ * FTMesh is a container of FTTesselation's that make up a polygon glyph
+ */
+class FTMesh
+{
+        typedef FTVector<FTTesselation*> TesselationVector;
+        typedef FTList<FTPoint> PointList;
+
+    public:
+        /**
+         * Default constructor
+         */
+        FTMesh();
+
+        /**
+         *  Destructor
+         */
+        ~FTMesh();
+
+        /**
+         * Add a point to the mesh
+         */
+        void AddPoint(const FTGL_DOUBLE x, const FTGL_DOUBLE y,
+                      const FTGL_DOUBLE z);
+
+        /**
+         *  Create a combine point for the gluTesselator
+         */
+        const FTGL_DOUBLE* Combine(const FTGL_DOUBLE x, const FTGL_DOUBLE y,
+                                   const FTGL_DOUBLE z);
+
+        /**
+         * Begin a new polygon
+         */
+        void Begin(GLenum meshType);
+
+        /**
+         * End a polygon
+         */
+        void End();
+
+        /**
+         * Record a gluTesselation error
+         */
+        void Error(GLenum e) { err = e; }
+
+        /**
+         * The number of tesselations in the mesh
+         */
+        size_t TesselationCount() const { return tesselationList.size(); }
+
+        /**
+         * Get a tesselation by index
+         */
+        const FTTesselation* const Tesselation(size_t index) const;
+
+        /**
+         * Return the temporary point list. For testing only.
+         */
+        const PointList& TempPointList() const { return tempPointList; }
+
+        /**
+         * Get the GL ERROR returned by the glu tesselator
+         */
+        GLenum Error() const { return err; }
+
+    private:
+        /**
+         * The current sub mesh that we are constructing.
+         */
+        FTTesselation* currentTesselation;
+
+        /**
+         * Holds each sub mesh that comprises this glyph.
+         */
+        TesselationVector tesselationList;
+
+        /**
+         * Holds extra points created by gluTesselator. See ftglCombine.
+         */
+        PointList tempPointList;
+
+        /**
+         * GL ERROR returned by the glu tesselator
+         */
+        GLenum err;
+
+};
+
+const FTGL_DOUBLE FTGL_FRONT_FACING = 1.0;
+const FTGL_DOUBLE FTGL_BACK_FACING = -1.0;
+
+/**
+ * FTVectoriser class is a helper class that converts font outlines into
+ * point data.
+ *
+ * @see FTExtrudeGlyph
+ * @see FTOutlineGlyph
+ * @see FTPolygonGlyph
+ * @see FTContour
+ * @see FTPoint
+ *
+ */
+class FTVectoriser
+{
+    public:
+        /**
+         * Constructor
+         *
+         * @param glyph The freetype glyph to be processed
+         */
+        FTVectoriser(const FT_GlyphSlot glyph);
+
+        /**
+         *  Destructor
+         */
+        virtual ~FTVectoriser();
+
+        /**
+         * Build an FTMesh from the vector outline data.
+         *
+         * @param zNormal   The direction of the z axis of the normal
+         *                  for this mesh
+         * FIXME: change the following for a constant
+         * @param outsetType Specify the outset type contour
+         *  0 : Original
+         *  1 : Front
+         *  2 : Back
+         * @param outsetSize Specify the outset size contour
+         */
+        void MakeMesh(FTGL_DOUBLE zNormal = FTGL_FRONT_FACING, int outsetType = 0, float outsetSize = 0.0f);
+
+        /**
+         * Get the current mesh.
+         */
+        const FTMesh* const GetMesh() const { return mesh; }
+
+        /**
+         * Get the total count of points in this outline
+         *
+         * @return the number of points
+         */
+        size_t PointCount();
+
+        /**
+         * Get the count of contours in this outline
+         *
+         * @return the number of contours
+         */
+        size_t ContourCount() const { return ftContourCount; }
+
+        /**
+         * Return a contour at index
+         *
+         * @return the number of contours
+         */
+         const FTContour* const Contour(size_t index) const;
+
+        /**
+         * Get the number of points in a specific contour in this outline
+         *
+         * @param c     The contour index
+         * @return      the number of points in contour[c]
+         */
+        size_t ContourSize(int c) const { return contourList[c]->PointCount(); }
+
+        /**
+         * Get the flag for the tesselation rule for this outline
+         *
+         * @return The contour flag
+         */
+        int ContourFlag() const { return contourFlag; }
+
+    private:
+        /**
+         * Process the freetype outline data into contours of points
+         *
+         * @param front front outset distance
+         * @param back back outset distance
+         */
+        void ProcessContours();
+
+        /**
+         * The list of contours in the glyph
+         */
+        FTContour** contourList;
+
+        /**
+         * A Mesh for tesselations
+         */
+        FTMesh* mesh;
+
+        /**
+         * The number of contours reported by Freetype
+         */
+        short ftContourCount;
+
+        /**
+         * A flag indicating the tesselation rule for the glyph
+         */
+        int contourFlag;
+
+        /**
+         * A Freetype outline
+         */
+        FT_Outline outline;
+};
+
+
+#endif  //  __FTVectoriser__
diff --git a/src/ext/ftgl/config.h b/src/ext/ftgl/config.h
new file mode 100644
index 0000000..aa8570b
--- /dev/null
+++ b/src/ext/ftgl/config.h
@@ -0,0 +1,7 @@
+/* In rgl, we don't run the FTGL configure script, and we don't have 
+   RTTI.  It appears as though the configure script is not needed for the 
+   subset we use (except we need config.h, hence this file), and we can 
+   use static_casts in place of dynamic_casts, hence the define below.
+*/
+
+#define dynamic_cast static_cast
diff --git a/src/fps.cpp b/src/fps.cpp
new file mode 100644
index 0000000..84ce790
--- /dev/null
+++ b/src/fps.cpp
@@ -0,0 +1,43 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: fps.cpp 1115 2014-07-18 13:51:22Z murdoch $
+
+#include "fps.h"
+
+#include "glgui.h"
+
+#include <cstdio>
+
+using namespace rgl;
+
+void FPS::init(double time)
+{
+  lastTime = time;
+  framecnt = 0;
+  buffer[0] = '0';
+  buffer[1] = '\0';
+}
+
+void FPS::render(double t, RenderContext* ctx)
+{
+  if (lastTime + 1.0f < t ) {
+    lastTime = t;
+    sprintf(buffer, "FPS %d", framecnt);
+    framecnt = 0;
+  }
+
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  glOrtho(-1.0f,1.0f,-1.0f,1.0f,-1.0f,1.0f);
+
+  glColor3f(1.0f,1.0f,1.0f);
+  glRasterPos2f( 1.0f, -0.9f);
+
+  if (ctx->font)
+    ctx->font->draw(buffer, strlen(buffer), -1, 0.0, *ctx);
+
+  framecnt++;
+}
diff --git a/src/fps.h b/src/fps.h
new file mode 100644
index 0000000..092816a
--- /dev/null
+++ b/src/fps.h
@@ -0,0 +1,32 @@
+#ifndef RGL_FPS_H
+#define RGL_FPS_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: fps.h 976 2013-10-04 15:06:19Z murdoch $
+
+#include "scene.h"
+
+namespace rgl {
+
+//
+// FPS COUNTER
+//
+
+class FPS
+{
+private:
+  double lastTime;
+  int   framecnt;
+  char  buffer[12];
+public:
+  inline FPS() { };
+  void init(double t);
+  void render(double t, RenderContext* ctx);
+};
+
+} // namespace rgl
+
+#endif // RGL_FPS_H
+
diff --git a/src/ftgl.cpp b/src/ftgl.cpp
new file mode 100644
index 0000000..889b369
--- /dev/null
+++ b/src/ftgl.cpp
@@ -0,0 +1,17 @@
+
+#ifdef HAVE_FREETYPE
+
+#include "FTBuffer.cpp"
+#include "FTCharmap.cpp"
+#include "FTFace.cpp"
+#include "FTFont/FTFont.cpp"
+#include "FTFont/FTBufferFont.cpp"
+#include "FTFont/FTPixmapFont.cpp"
+#include "FTGlyphContainer.cpp"
+#include "FTGlyph/FTGlyph.cpp"
+#include "FTGlyph/FTPixmapGlyph.cpp"
+#include "FTGlyph/FTBufferGlyph.cpp"
+#include "FTLibrary.cpp"
+#include "FTSize.cpp"
+
+#endif
diff --git a/src/geom.cpp b/src/geom.cpp
new file mode 100644
index 0000000..af4e90a
--- /dev/null
+++ b/src/geom.cpp
@@ -0,0 +1,195 @@
+#include "geom.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   AABox
+//
+
+AABox::AABox()
+{
+  invalidate();
+}
+
+void AABox::invalidate(void)
+{
+  vmax = Vertex( -FLT_MAX, -FLT_MAX, -FLT_MAX );
+  vmin = Vertex(  FLT_MAX,  FLT_MAX,  FLT_MAX );
+}
+
+void AABox::operator += (const Vertex& v)
+{
+  if (!ISNAN(v.x)) {
+    vmin.x = getMin(vmin.x, v.x);
+    vmax.x = getMax(vmax.x, v.x);   
+  }
+  if (!ISNAN(v.y)) {
+    vmin.y = getMin(vmin.y, v.y);
+    vmax.y = getMax(vmax.y, v.y);   
+  }
+  if (!ISNAN(v.z)) {
+    vmin.z = getMin(vmin.z, v.z);
+    vmax.z = getMax(vmax.z, v.z);
+  }
+}
+
+void AABox::operator += (const AABox& aabox)
+{
+  if (aabox.isValid()) {
+    *this += aabox.vmin;
+    *this += aabox.vmax;
+  }
+}
+
+void AABox::operator += (const Sphere& sphere)
+{
+  *this += sphere.center - Vertex(sphere.radius,sphere.radius,sphere.radius);
+  *this += sphere.center + Vertex(sphere.radius,sphere.radius,sphere.radius);
+}
+
+bool AABox::operator < (const AABox& that) const
+{
+  return true;
+}
+
+bool AABox::isValid(void) const
+{
+  return ((vmax.x >= vmin.x) && (vmax.y >= vmin.y) && (vmax.z >= vmin.z)) ? true : false;
+}
+
+Vertex AABox::getCenter(void) const
+{
+  return Vertex( (vmax + vmin) * 0.5f );
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Sphere
+//
+
+Sphere::Sphere(const AABox& bbox)
+{
+  Vertex hdiagonal( (bbox.vmax - bbox.vmin) * 0.5f );
+
+  center = bbox.getCenter();
+  radius = hdiagonal.getLength();
+}
+
+Sphere::Sphere(const AABox& bbox, const Vertex& s)
+{
+  Vertex hdiagonal( ((bbox.vmax - bbox.vmin) * 0.5f).scale(s) );
+  center = bbox.getCenter();
+  radius = hdiagonal.getLength();
+}
+
+Sphere::Sphere(const float in_radius)
+: center(0.0f, 0.0f, 0.0f), radius(in_radius)
+{
+}
+
+Sphere::Sphere(const Vertex& in_center, const float in_radius)
+: center(in_center), radius(in_radius)
+{
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Frustum
+//
+
+//
+// setup frustum to enclose the space given by a bounding sphere, 
+// field-of-view angle and window size.
+//
+// window size is used to provide aspect ratio.
+//
+// 
+
+void Frustum::enclose(float sphere_radius, float fovangle, int width, int height)
+{
+  float s=0.5, t=1.0;
+  
+  if (fovangle != 0.0) {
+    float fovradians = math::deg2rad(fovangle/2.0f);
+
+    s = math::sin(fovradians);
+    t = math::tan(fovradians);
+
+    ortho = false;
+  } else {
+    ortho = true;
+  }
+
+  distance = sphere_radius / s;
+
+  znear = distance - sphere_radius;
+  zfar  = znear + sphere_radius*2.0f;
+
+  float hlen = t * znear;
+
+  // hold aspect ratio 1:1
+
+  float hwidth, hheight;
+
+  bool inside = false;
+
+  if (inside) {
+
+    // inside bounding sphere: fit to max(winsize)
+
+    if (width >= height) {
+      hwidth  = hlen;
+      hheight = hlen * ( (float)height ) /  ( (float)width );
+    } else {
+      hwidth  = hlen * ( (float)width  ) / ( (float)height );
+      hheight = hlen;
+    }
+  } else {
+
+    // outside(in front of) bounding sphere: fit to min(winsize)
+
+    if (width >= height) {
+      hwidth  = hlen * ( (float)width ) / ( (float)height );
+      hheight = hlen;
+    } else {
+      hwidth  = hlen;
+      hheight = hlen * ( (float)height ) / ( (float)width );
+    }
+
+  } 
+
+  left   = -hwidth;
+  right  =  hwidth;
+  bottom = -hheight;
+  top    =  hheight;
+}
+
+Matrix4x4 Frustum::getMatrix()
+{
+  double data[16];
+  memset(data, 0, sizeof(data));
+  if (ortho) {
+    data[0] = 2/(right - left);
+    data[5] = 2/(top - bottom);
+    data[10] = -2/(zfar - znear);
+    data[12] = -(right + left)/(right - left);
+    data[13] = -(top + bottom)/(top - bottom);
+    data[14] = -(zfar + znear)/(zfar - znear);
+    data[15] = 1;
+  } else {
+    data[0] = 2*znear/(right - left);
+    data[5] = 2*znear/(top - bottom);
+    data[8] = (right + left)/(right - left);
+    data[9] = (top + bottom)/(top - bottom);
+    data[10] = -(zfar + znear)/(zfar - znear);
+    data[11] = -1;
+    data[14] = -2*zfar*znear/(zfar - znear);
+  }
+  return Matrix4x4(data);
+}
+   
diff --git a/src/geom.h b/src/geom.h
new file mode 100644
index 0000000..4bea373
--- /dev/null
+++ b/src/geom.h
@@ -0,0 +1,65 @@
+#ifndef GEOM_H
+#define GEOM_H
+
+#include "rglmath.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   AABox (axis-aligned box)
+//
+
+class Sphere;
+
+class AABox {
+public:
+  AABox();
+  AABox(const AABox& that)
+   : vmin(that.vmin), vmax(that.vmax)
+  { }
+  void invalidate(void);
+  bool isValid(void) const;
+  void operator += (const AABox& aabox);
+  void operator += (const Sphere& sphere);
+  void operator += (const Vertex& vertex);
+  bool operator < (const AABox& aabox) const;
+  Vertex getCenter(void) const;
+  Vertex vmin, vmax;
+};
+
+
+//
+// CLASS
+//   Sphere
+//
+
+class Sphere {
+public:
+  Sphere() : center(0,0,0), radius(1) {};
+  Sphere(const Vertex& center, const float radius);
+  Sphere(const float radius);
+  Sphere(const AABox& aabox);
+  Sphere(const AABox& aabox, const Vertex& scale);
+  Vertex center;
+  float radius;
+};
+
+
+//
+// CLASS
+//   Frustum
+//
+
+class Frustum {
+public:
+  Frustum() : ortho(false) {};
+  void enclose(float sphere_radius, float fovangle, int win_width, int win_height);
+  Matrix4x4 getMatrix();
+  float left, right, bottom, top, znear, zfar, distance;
+  bool ortho;
+};
+
+} // namespace rgl
+
+#endif // GEOM_H
diff --git a/src/gl2ps.c b/src/gl2ps.c
new file mode 100644
index 0000000..c467e14
--- /dev/null
+++ b/src/gl2ps.c
@@ -0,0 +1,6139 @@
+/*
+ * GL2PS, an OpenGL to PostScript Printing Library
+ * Copyright (C) 1999-2012 C. Geuzaine
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of either:
+ *
+ * a) the GNU Library General Public License as published by the Free
+ * Software Foundation, either version 2 of the License, or (at your
+ * option) any later version; or
+ *
+ * b) the GL2PS License as published by Christophe Geuzaine, either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
+ * the GNU Library General Public License or the GL2PS License for
+ * more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library in the file named "COPYING.LGPL";
+ * if not, write to the Free Software Foundation, Inc., 51 Franklin
+ * Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * You should have received a copy of the GL2PS License with this
+ * library in the file named "COPYING.GL2PS"; if not, I will be glad
+ * to provide one.
+ *
+ * For the latest info about gl2ps and a full list of contributors,
+ * see http://www.geuz.org/gl2ps/.
+ *
+ * Please report all bugs and problems to <gl2ps at geuz.org>.
+ */
+
+#include "gl2ps.h"
+
+#include <math.h>
+#include <string.h>
+#include <sys/types.h>
+#include <stdarg.h>
+#include <time.h>
+#include <float.h>
+
+#if defined(GL2PS_HAVE_ZLIB)
+#include <zlib.h>
+#endif
+
+#if defined(GL2PS_HAVE_LIBPNG)
+#include <png.h>
+#endif
+
+/*********************************************************************
+ *
+ * Private definitions, data structures and prototypes
+ *
+ *********************************************************************/
+
+/* Magic numbers (assuming that the order of magnitude of window
+   coordinates is 10^3) */
+
+#define GL2PS_EPSILON       5.0e-3F
+#define GL2PS_ZSCALE        1000.0F
+#define GL2PS_ZOFFSET       5.0e-2F
+#define GL2PS_ZOFFSET_LARGE 20.0F
+#define GL2PS_ZERO(arg)     (fabs(arg) < 1.e-20)
+
+/* Primitive types */
+
+#define GL2PS_NO_TYPE          -1
+#define GL2PS_TEXT             1
+#define GL2PS_POINT            2
+#define GL2PS_LINE             3
+#define GL2PS_QUADRANGLE       4
+#define GL2PS_TRIANGLE         5
+#define GL2PS_PIXMAP           6
+#define GL2PS_IMAGEMAP         7
+#define GL2PS_IMAGEMAP_WRITTEN 8
+#define GL2PS_IMAGEMAP_VISIBLE 9
+#define GL2PS_SPECIAL          10
+
+/* BSP tree primitive comparison */
+
+#define GL2PS_COINCIDENT  1
+#define GL2PS_IN_FRONT_OF 2
+#define GL2PS_IN_BACK_OF  3
+#define GL2PS_SPANNING    4
+
+/* 2D BSP tree primitive comparison */
+
+#define GL2PS_POINT_COINCIDENT 0
+#define GL2PS_POINT_INFRONT    1
+#define GL2PS_POINT_BACK       2
+
+/* Internal feedback buffer pass-through tokens */
+
+#define GL2PS_BEGIN_OFFSET_TOKEN   1
+#define GL2PS_END_OFFSET_TOKEN     2
+#define GL2PS_BEGIN_BOUNDARY_TOKEN 3
+#define GL2PS_END_BOUNDARY_TOKEN   4
+#define GL2PS_BEGIN_STIPPLE_TOKEN  5
+#define GL2PS_END_STIPPLE_TOKEN    6
+#define GL2PS_POINT_SIZE_TOKEN     7
+#define GL2PS_LINE_WIDTH_TOKEN     8
+#define GL2PS_BEGIN_BLEND_TOKEN    9
+#define GL2PS_END_BLEND_TOKEN      10
+#define GL2PS_SRC_BLEND_TOKEN      11
+#define GL2PS_DST_BLEND_TOKEN      12
+#define GL2PS_IMAGEMAP_TOKEN       13
+#define GL2PS_DRAW_PIXELS_TOKEN    14
+#define GL2PS_TEXT_TOKEN           15
+
+typedef enum {
+  T_UNDEFINED    = -1,
+  T_CONST_COLOR  = 1,
+  T_VAR_COLOR    = 1<<1,
+  T_ALPHA_1      = 1<<2,
+  T_ALPHA_LESS_1 = 1<<3,
+  T_VAR_ALPHA    = 1<<4
+} GL2PS_TRIANGLE_PROPERTY;
+
+typedef GLfloat GL2PSxyz[3];
+typedef GLfloat GL2PSplane[4];
+
+typedef struct _GL2PSbsptree2d GL2PSbsptree2d;
+
+struct _GL2PSbsptree2d {
+  GL2PSplane plane;
+  GL2PSbsptree2d *front, *back;
+};
+
+typedef struct {
+  GLint nmax, size, incr, n;
+  char *array;
+} GL2PSlist;
+
+typedef struct _GL2PSbsptree GL2PSbsptree;
+
+struct _GL2PSbsptree {
+  GL2PSplane plane;
+  GL2PSlist *primitives;
+  GL2PSbsptree *front, *back;
+};
+
+typedef struct {
+  GL2PSxyz xyz;
+  GL2PSrgba rgba;
+} GL2PSvertex;
+
+typedef struct {
+  GL2PSvertex vertex[3];
+  int prop;
+} GL2PStriangle;
+
+typedef struct {
+  GLshort fontsize;
+  char *str, *fontname;
+  /* Note: for a 'special' string, 'alignment' holds the format
+     (PostScript, PDF, etc.) of the special string */
+  GLint alignment;
+  GLfloat angle;
+} GL2PSstring;
+
+typedef struct {
+  GLsizei width, height;
+  /* Note: for an imagemap, 'type' indicates if it has already been
+     written to the file or not, and 'format' indicates if it is
+     visible or not */
+  GLenum format, type;
+  GLfloat zoom_x, zoom_y;
+  GLfloat *pixels;
+} GL2PSimage;
+
+typedef struct _GL2PSimagemap GL2PSimagemap;
+
+struct _GL2PSimagemap {
+  GL2PSimage *image;
+  GL2PSimagemap *next;
+};
+
+typedef struct {
+  GLshort type, numverts;
+  GLushort pattern;
+  char boundary, offset, culled;
+  GLint factor;
+  GLfloat width;
+  GL2PSvertex *verts;
+  union {
+    GL2PSstring *text;
+    GL2PSimage *image;
+  } data;
+} GL2PSprimitive;
+
+typedef struct {
+#if defined(GL2PS_HAVE_ZLIB)
+  Bytef *dest, *src, *start;
+  uLongf destLen, srcLen;
+#else
+  int dummy;
+#endif
+} GL2PScompress;
+
+typedef struct{
+  GL2PSlist* ptrlist;
+  int gsno, fontno, imno, shno, maskshno, trgroupno;
+  int gsobjno, fontobjno, imobjno, shobjno, maskshobjno, trgroupobjno;
+} GL2PSpdfgroup;
+
+typedef struct {
+  /* General */
+  GLint format, sort, options, colorsize, colormode, buffersize;
+  char *title, *producer, *filename;
+  GLboolean boundary, blending;
+  GLfloat *feedback, offset[2], lastlinewidth;
+  GLint viewport[4], blendfunc[2], lastfactor;
+  GL2PSrgba *colormap, lastrgba, threshold, bgcolor;
+  GLushort lastpattern;
+  GL2PSvertex lastvertex;
+  GL2PSlist *primitives, *auxprimitives;
+  FILE *stream;
+  GL2PScompress *compress;
+  GLboolean header;
+
+  /* BSP-specific */
+  GLint maxbestroot;
+
+  /* Occlusion culling-specific */
+  GLboolean zerosurfacearea;
+  GL2PSbsptree2d *imagetree;
+  GL2PSprimitive *primitivetoadd;
+
+  /* PDF-specific */
+  int streamlength;
+  GL2PSlist *pdfprimlist, *pdfgrouplist;
+  int *xreflist;
+  int objects_stack; /* available objects */
+  int extgs_stack; /* graphics state object number */
+  int font_stack; /* font object number */
+  int im_stack; /* image object number */
+  int trgroupobjects_stack; /* xobject numbers */
+  int shader_stack; /* shader object numbers */
+  int mshader_stack; /* mask shader object numbers */
+
+  /* for image map list */
+  GL2PSimagemap *imagemap_head;
+  GL2PSimagemap *imagemap_tail;
+} GL2PScontext;
+
+typedef struct {
+  void  (*printHeader)(void);
+  void  (*printFooter)(void);
+  void  (*beginViewport)(GLint viewport[4]);
+  GLint (*endViewport)(void);
+  void  (*printPrimitive)(void *data);
+  void  (*printFinalPrimitive)(void);
+  const char *file_extension;
+  const char *description;
+} GL2PSbackend;
+
+/* The gl2ps context. gl2ps is not thread safe (we should create a
+   local GL2PScontext during gl2psBeginPage) */
+
+static GL2PScontext *gl2ps = NULL;
+
+/* Need to forward-declare this one */
+
+static GLint gl2psPrintPrimitives(void);
+
+/*********************************************************************
+ *
+ * Utility routines
+ *
+ *********************************************************************/
+
+static void gl2psMsg(GLint level, const char *fmt, ...)
+{
+/*  Avoid R check complaints:  GL2PS_SILENT is always set
+  va_list args;
+
+  if(!(gl2ps->options & GL2PS_SILENT)){
+    switch(level){
+    case GL2PS_INFO : fprintf(stderr, "GL2PS info: "); break;
+    case GL2PS_WARNING : fprintf(stderr, "GL2PS warning: "); break;
+    case GL2PS_ERROR : fprintf(stderr, "GL2PS error: "); break;
+    }
+    va_start(args, fmt);
+    vfprintf(stderr, fmt, args);
+    va_end(args);
+    fprintf(stderr, "\n");
+  }
+*/
+
+  /* if(level == GL2PS_ERROR) exit(1); */
+}
+
+static void *gl2psMalloc(size_t size)
+{
+  void *ptr;
+
+  if(!size) return NULL;
+  ptr = malloc(size);
+  if(!ptr){
+    gl2psMsg(GL2PS_ERROR, "Couldn't allocate requested memory");
+    return NULL;
+  }
+  return ptr;
+}
+
+static void *gl2psRealloc(void *ptr, size_t size)
+{
+  void *orig = ptr;
+  if(!size) return NULL;
+  ptr = realloc(orig, size);
+  if(!ptr){
+    gl2psMsg(GL2PS_ERROR, "Couldn't reallocate requested memory");
+    free(orig);
+    return NULL;
+  }
+  return ptr;
+}
+
+static void gl2psFree(void *ptr)
+{
+  if(!ptr) return;
+  free(ptr);
+}
+
+static int gl2psWriteBigEndian(unsigned long data, int bytes)
+{
+  int i;
+  int size = sizeof(unsigned long);
+  for(i = 1; i <= bytes; ++i){
+    fputc(0xff & (data >> (size - i) * 8), gl2ps->stream);
+  }
+  return bytes;
+}
+
+/* zlib compression helper routines */
+
+#if defined(GL2PS_HAVE_ZLIB)
+
+static void gl2psSetupCompress(void)
+{
+  gl2ps->compress = (GL2PScompress*)gl2psMalloc(sizeof(GL2PScompress));
+  gl2ps->compress->src = NULL;
+  gl2ps->compress->start = NULL;
+  gl2ps->compress->dest = NULL;
+  gl2ps->compress->srcLen = 0;
+  gl2ps->compress->destLen = 0;
+}
+
+static void gl2psFreeCompress(void)
+{
+  if(!gl2ps->compress)
+    return;
+  gl2psFree(gl2ps->compress->start);
+  gl2psFree(gl2ps->compress->dest);
+  gl2ps->compress->src = NULL;
+  gl2ps->compress->start = NULL;
+  gl2ps->compress->dest = NULL;
+  gl2ps->compress->srcLen = 0;
+  gl2ps->compress->destLen = 0;
+}
+
+static int gl2psAllocCompress(unsigned int srcsize)
+{
+  gl2psFreeCompress();
+
+  if(!gl2ps->compress || !srcsize)
+    return GL2PS_ERROR;
+
+  gl2ps->compress->srcLen = srcsize;
+  gl2ps->compress->destLen = (int)ceil(1.001 * gl2ps->compress->srcLen + 12);
+  gl2ps->compress->src = (Bytef*)gl2psMalloc(gl2ps->compress->srcLen);
+  gl2ps->compress->start = gl2ps->compress->src;
+  gl2ps->compress->dest = (Bytef*)gl2psMalloc(gl2ps->compress->destLen);
+
+  return GL2PS_SUCCESS;
+}
+
+static void *gl2psReallocCompress(unsigned int srcsize)
+{
+  if(!gl2ps->compress || !srcsize)
+    return NULL;
+
+  if(srcsize < gl2ps->compress->srcLen)
+    return gl2ps->compress->start;
+
+  gl2ps->compress->srcLen = srcsize;
+  gl2ps->compress->destLen = (int)ceil(1.001 * gl2ps->compress->srcLen + 12);
+  gl2ps->compress->src = (Bytef*)gl2psRealloc(gl2ps->compress->src,
+                                              gl2ps->compress->srcLen);
+  gl2ps->compress->start = gl2ps->compress->src;
+  gl2ps->compress->dest = (Bytef*)gl2psRealloc(gl2ps->compress->dest,
+                                               gl2ps->compress->destLen);
+
+  return gl2ps->compress->start;
+}
+
+static int gl2psWriteBigEndianCompress(unsigned long data, int bytes)
+{
+  int i;
+  int size = sizeof(unsigned long);
+  for(i = 1; i <= bytes; ++i){
+    *gl2ps->compress->src = (Bytef)(0xff & (data >> (size-i) * 8));
+    ++gl2ps->compress->src;
+  }
+  return bytes;
+}
+
+static int gl2psDeflate(void)
+{
+  /* For compatibility with older zlib versions, we use compress(...)
+     instead of compress2(..., Z_BEST_COMPRESSION) */
+  return compress(gl2ps->compress->dest, &gl2ps->compress->destLen,
+                  gl2ps->compress->start, gl2ps->compress->srcLen);
+}
+
+#endif
+
+static int gl2psPrintf(const char* fmt, ...)
+{
+  int ret;
+  va_list args;
+
+#if defined(GL2PS_HAVE_ZLIB)
+  static char buf[1024];
+  char *bufptr = buf;
+  GLboolean freebuf = GL_FALSE;
+  unsigned int oldsize = 0;
+#if !defined(GL2PS_HAVE_NO_VSNPRINTF)
+  /* Try writing the string to a 1024 byte buffer. If it is too small to fit,
+     keep trying larger sizes until it does. */
+  size_t bufsize = sizeof(buf);
+#endif
+  if(gl2ps->options & GL2PS_COMPRESS){
+    va_start(args, fmt);
+#if defined(GL2PS_HAVE_NO_VSNPRINTF)
+    ret = vsprintf(buf, fmt, args);
+#else
+    ret = vsnprintf(bufptr, bufsize, fmt, args);
+#endif
+    va_end(args);
+#if !defined(GL2PS_HAVE_NO_VSNPRINTF)
+    while(ret >= (bufsize - 1) || ret < 0){
+      /* Too big. Allocate a new buffer. */
+      bufsize *= 2;
+      if(freebuf == GL_TRUE) gl2psFree(bufptr);
+      bufptr = (char *)gl2psMalloc(bufsize);
+      freebuf = GL_TRUE;
+      va_start(args, fmt);
+      ret = vsnprintf(bufptr, bufsize, fmt, args);
+      va_end(args);
+    }
+#endif
+    oldsize = gl2ps->compress->srcLen;
+    gl2ps->compress->start = (Bytef*)gl2psReallocCompress(oldsize + ret);
+    memcpy(gl2ps->compress->start + oldsize, bufptr, ret);
+    if(freebuf == GL_TRUE) gl2psFree(bufptr);
+    ret = 0;
+  }
+  else{
+#endif
+    va_start(args, fmt);
+    ret = vfprintf(gl2ps->stream, fmt, args);
+    va_end(args);
+#if defined(GL2PS_HAVE_ZLIB)
+  }
+#endif
+  return ret;
+}
+
+static void gl2psPrintGzipHeader(void)
+{
+#if defined(GL2PS_HAVE_ZLIB)
+  char tmp[10] = {'\x1f', '\x8b', /* magic numbers: 0x1f, 0x8b */
+                  8, /* compression method: Z_DEFLATED */
+                  0, /* flags */
+                  0, 0, 0, 0, /* time */
+                  2, /* extra flags: max compression */
+                  '\x03'}; /* OS code: 0x03 (Unix) */
+
+  if(gl2ps->options & GL2PS_COMPRESS){
+    gl2psSetupCompress();
+    /* add the gzip file header */
+    fwrite(tmp, 10, 1, gl2ps->stream);
+  }
+#endif
+}
+
+static void gl2psPrintGzipFooter(void)
+{
+#if defined(GL2PS_HAVE_ZLIB)
+  int n;
+  uLong crc, len;
+  char tmp[8];
+
+  if(gl2ps->options & GL2PS_COMPRESS){
+    if(Z_OK != gl2psDeflate()){
+      gl2psMsg(GL2PS_ERROR, "Zlib deflate error");
+    }
+    else{
+      /* determine the length of the header in the zlib stream */
+      n = 2; /* CMF+FLG */
+      if(gl2ps->compress->dest[1] & (1<<5)){
+        n += 4; /* DICTID */
+      }
+      /* write the data, without the zlib header and footer */
+      fwrite(gl2ps->compress->dest+n, gl2ps->compress->destLen-(n+4),
+             1, gl2ps->stream);
+      /* add the gzip file footer */
+      crc = crc32(0L, gl2ps->compress->start, gl2ps->compress->srcLen);
+      for(n = 0; n < 4; ++n){
+        tmp[n] = (char)(crc & 0xff);
+        crc >>= 8;
+      }
+      len = gl2ps->compress->srcLen;
+      for(n = 4; n < 8; ++n){
+        tmp[n] = (char)(len & 0xff);
+        len >>= 8;
+      }
+      fwrite(tmp, 8, 1, gl2ps->stream);
+    }
+    gl2psFreeCompress();
+    gl2psFree(gl2ps->compress);
+    gl2ps->compress = NULL;
+  }
+#endif
+}
+
+/* The list handling routines */
+
+static void gl2psListRealloc(GL2PSlist *list, GLint n)
+{
+  if(!list){
+    gl2psMsg(GL2PS_ERROR, "Cannot reallocate NULL list");
+    return;
+  }
+  if(n <= 0) return;
+  if(!list->array){
+    list->nmax = n;
+    list->array = (char*)gl2psMalloc(list->nmax * list->size);
+  }
+  else{
+    if(n > list->nmax){
+      list->nmax = ((n - 1) / list->incr + 1) * list->incr;
+      list->array = (char*)gl2psRealloc(list->array,
+                                        list->nmax * list->size);
+    }
+  }
+}
+
+static GL2PSlist *gl2psListCreate(GLint n, GLint incr, GLint size)
+{
+  GL2PSlist *list;
+
+  if(n < 0) n = 0;
+  if(incr <= 0) incr = 1;
+  list = (GL2PSlist*)gl2psMalloc(sizeof(GL2PSlist));
+  list->nmax = 0;
+  list->incr = incr;
+  list->size = size;
+  list->n = 0;
+  list->array = NULL;
+  gl2psListRealloc(list, n);
+  return list;
+}
+
+static void gl2psListReset(GL2PSlist *list)
+{
+  if(!list) return;
+  list->n = 0;
+}
+
+static void gl2psListDelete(GL2PSlist *list)
+{
+  if(!list) return;
+  gl2psFree(list->array);
+  gl2psFree(list);
+}
+
+static void gl2psListAdd(GL2PSlist *list, void *data)
+{
+  if(!list){
+    gl2psMsg(GL2PS_ERROR, "Cannot add into unallocated list");
+    return;
+  }
+  list->n++;
+  gl2psListRealloc(list, list->n);
+  memcpy(&list->array[(list->n - 1) * list->size], data, list->size);
+}
+
+static int gl2psListNbr(GL2PSlist *list)
+{
+  if(!list)
+    return 0;
+  return list->n;
+}
+
+static void *gl2psListPointer(GL2PSlist *list, GLint idx)
+{
+  if(!list){
+    gl2psMsg(GL2PS_ERROR, "Cannot point into unallocated list");
+    return NULL;
+  }
+  if((idx < 0) || (idx >= list->n)){
+    gl2psMsg(GL2PS_ERROR, "Wrong list index in gl2psListPointer");
+    return NULL;
+  }
+  return &list->array[idx * list->size];
+}
+
+static void gl2psListSort(GL2PSlist *list,
+                          int (*fcmp)(const void *a, const void *b))
+{
+  if(!list)
+    return;
+  qsort(list->array, list->n, list->size, fcmp);
+}
+
+static void gl2psListAction(GL2PSlist *list, void (*action)(void *data))
+{
+  GLint i;
+
+  for(i = 0; i < gl2psListNbr(list); i++){
+    (*action)(gl2psListPointer(list, i));
+  }
+}
+
+static void gl2psListActionInverse(GL2PSlist *list, void (*action)(void *data))
+{
+  GLint i;
+
+  for(i = gl2psListNbr(list); i > 0; i--){
+    (*action)(gl2psListPointer(list, i-1));
+  }
+}
+
+#if defined(GL2PS_HAVE_LIBPNG)
+
+static void gl2psListRead(GL2PSlist *list, int index, void *data)
+{
+  if((index < 0) || (index >= list->n))
+    gl2psMsg(GL2PS_ERROR, "Wrong list index in gl2psListRead");
+  memcpy(data, &list->array[index * list->size], list->size);
+}
+
+static void gl2psEncodeBase64Block(unsigned char in[3], unsigned char out[4], int len)
+{
+  static const char cb64[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+  out[0] = cb64[ in[0] >> 2 ];
+  out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
+  out[2] = (len > 1) ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=';
+  out[3] = (len > 2) ? cb64[ in[2] & 0x3f ] : '=';
+}
+
+static void gl2psListEncodeBase64(GL2PSlist *list)
+{
+  unsigned char *buffer, in[3], out[4];
+  int i, n, index, len;
+
+  n = list->n * list->size;
+  buffer = (unsigned char*)gl2psMalloc(n * sizeof(unsigned char));
+  memcpy(buffer, list->array, n * sizeof(unsigned char));
+  gl2psListReset(list);
+
+  index = 0;
+  while(index < n) {
+    len = 0;
+    for(i = 0; i < 3; i++) {
+      if(index < n){
+        in[i] = buffer[index];
+        len++;
+      }
+      else{
+        in[i] = 0;
+      }
+      index++;
+    }
+    if(len) {
+      gl2psEncodeBase64Block(in, out, len);
+      for(i = 0; i < 4; i++)
+        gl2psListAdd(list, &out[i]);
+    }
+  }
+  gl2psFree(buffer);
+}
+
+#endif
+
+/* Helpers for rgba colors */
+
+static GLboolean gl2psSameColor(GL2PSrgba rgba1, GL2PSrgba rgba2)
+{
+  if(!GL2PS_ZERO(rgba1[0] - rgba2[0]) ||
+     !GL2PS_ZERO(rgba1[1] - rgba2[1]) ||
+     !GL2PS_ZERO(rgba1[2] - rgba2[2]))
+    return GL_FALSE;
+  return GL_TRUE;
+}
+
+static GLboolean gl2psVertsSameColor(const GL2PSprimitive *prim)
+{
+  int i;
+
+  for(i = 1; i < prim->numverts; i++){
+    if(!gl2psSameColor(prim->verts[0].rgba, prim->verts[i].rgba)){
+      return GL_FALSE;
+    }
+  }
+  return GL_TRUE;
+}
+
+static GLboolean gl2psSameColorThreshold(int n, GL2PSrgba rgba[],
+                                         GL2PSrgba threshold)
+{
+  int i;
+
+  if(n < 2) return GL_TRUE;
+
+  for(i = 1; i < n; i++){
+    if(fabs(rgba[0][0] - rgba[i][0]) > threshold[0] ||
+       fabs(rgba[0][1] - rgba[i][1]) > threshold[1] ||
+       fabs(rgba[0][2] - rgba[i][2]) > threshold[2])
+      return GL_FALSE;
+  }
+
+  return GL_TRUE;
+}
+
+static void gl2psSetLastColor(GL2PSrgba rgba)
+{
+  int i;
+  for(i = 0; i < 3; ++i){
+    gl2ps->lastrgba[i] = rgba[i];
+  }
+}
+
+static GLfloat gl2psGetRGB(GL2PSimage *im, GLuint x, GLuint y,
+                           GLfloat *red, GLfloat *green, GLfloat *blue)
+{
+
+  GLsizei width = im->width;
+  GLsizei height = im->height;
+  GLfloat *pixels = im->pixels;
+  GLfloat *pimag;
+
+  /* OpenGL image is from down to up, PS image is up to down */
+  switch(im->format){
+  case GL_RGBA:
+    pimag = pixels + 4 * (width * (height - 1 - y) + x);
+    break;
+  case GL_RGB:
+  default:
+    pimag = pixels + 3 * (width * (height - 1 - y) + x);
+    break;
+  }
+  *red = *pimag; pimag++;
+  *green = *pimag; pimag++;
+  *blue = *pimag; pimag++;
+
+  return (im->format == GL_RGBA) ? *pimag : 1.0F;
+}
+
+/* Helper routines for pixmaps */
+
+static GL2PSimage *gl2psCopyPixmap(GL2PSimage *im)
+{
+  int size;
+  GL2PSimage *image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage));
+
+  image->width = im->width;
+  image->height = im->height;
+  image->format = im->format;
+  image->type = im->type;
+  image->zoom_x = im->zoom_x;
+  image->zoom_y = im->zoom_y;
+
+  switch(image->format){
+  case GL_RGBA:
+    size = image->height * image->width * 4 * sizeof(GLfloat);
+    break;
+  case GL_RGB:
+  default:
+    size = image->height * image->width * 3 * sizeof(GLfloat);
+    break;
+  }
+
+  image->pixels = (GLfloat*)gl2psMalloc(size);
+  memcpy(image->pixels, im->pixels, size);
+
+  return image;
+}
+
+static void gl2psFreePixmap(GL2PSimage *im)
+{
+  if(!im)
+    return;
+  gl2psFree(im->pixels);
+  gl2psFree(im);
+}
+
+#if defined(GL2PS_HAVE_LIBPNG)
+
+#if !defined(png_jmpbuf)
+#  define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
+#endif
+
+static void gl2psUserWritePNG(png_structp png_ptr, png_bytep data, png_size_t length)
+{
+  unsigned int i;
+  GL2PSlist *png = (GL2PSlist*)png_get_io_ptr(png_ptr);
+  for(i = 0; i < length; i++)
+    gl2psListAdd(png, &data[i]);
+}
+
+static void gl2psUserFlushPNG(png_structp png_ptr)
+{
+  (void) png_ptr;  /* not used */
+}
+
+static void gl2psConvertPixmapToPNG(GL2PSimage *pixmap, GL2PSlist *png)
+{
+  png_structp png_ptr;
+  png_infop info_ptr;
+  unsigned char *row_data;
+  GLfloat dr, dg, db;
+  int row, col;
+
+  if(!(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL)))
+    return;
+
+  if(!(info_ptr = png_create_info_struct(png_ptr))){
+    png_destroy_write_struct(&png_ptr, NULL);
+    return;
+  }
+
+  if(setjmp(png_jmpbuf(png_ptr))) {
+    png_destroy_write_struct(&png_ptr, &info_ptr);
+    return;
+  }
+
+  png_set_write_fn(png_ptr, (void *)png, gl2psUserWritePNG, gl2psUserFlushPNG);
+  png_set_compression_level(png_ptr, Z_DEFAULT_COMPRESSION);
+  png_set_IHDR(png_ptr, info_ptr, pixmap->width, pixmap->height, 8,
+               PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE,
+               PNG_FILTER_TYPE_BASE);
+  png_write_info(png_ptr, info_ptr);
+
+  row_data = (unsigned char*)gl2psMalloc(3 * pixmap->width * sizeof(unsigned char));
+  for(row = 0; row < pixmap->height; row++){
+    for(col = 0; col < pixmap->width; col++){
+      gl2psGetRGB(pixmap, col, row, &dr, &dg, &db);
+      row_data[3*col] = (unsigned char)(255. * dr);
+      row_data[3*col+1] = (unsigned char)(255. * dg);
+      row_data[3*col+2] = (unsigned char)(255. * db);
+    }
+    png_write_row(png_ptr, (png_bytep)row_data);
+  }
+  gl2psFree(row_data);
+
+  png_write_end(png_ptr, info_ptr);
+  png_destroy_write_struct(&png_ptr, &info_ptr);
+}
+
+#endif
+
+/* Helper routines for text strings */
+
+static GLint gl2psAddText(GLint type, const char *str, const char *fontname,
+                          GLshort fontsize, GLint alignment, GLfloat angle,
+                          GL2PSrgba color)
+{
+  GLfloat pos[4];
+  GL2PSprimitive *prim;
+  GLboolean valid;
+
+  if(!gl2ps || !str || !fontname) return GL2PS_UNINITIALIZED;
+
+  if(gl2ps->options & GL2PS_NO_TEXT) return GL2PS_SUCCESS;
+
+  glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid);
+  if(GL_FALSE == valid) return GL2PS_SUCCESS; /* the primitive is culled */
+
+  glGetFloatv(GL_CURRENT_RASTER_POSITION, pos);
+
+  prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+  prim->type = type;
+  prim->boundary = 0;
+  prim->numverts = 1;
+  prim->verts = (GL2PSvertex*)gl2psMalloc(sizeof(GL2PSvertex));
+  prim->verts[0].xyz[0] = pos[0];
+  prim->verts[0].xyz[1] = pos[1];
+  prim->verts[0].xyz[2] = pos[2];
+  prim->culled = 0;
+  prim->offset = 0;
+  prim->pattern = 0;
+  prim->factor = 0;
+  prim->width = 1;
+  if (color)
+    memcpy(prim->verts[0].rgba, color, 4 * sizeof(float));
+  else
+    glGetFloatv(GL_CURRENT_RASTER_COLOR, prim->verts[0].rgba);
+  prim->data.text = (GL2PSstring*)gl2psMalloc(sizeof(GL2PSstring));
+  prim->data.text->str = (char*)gl2psMalloc((strlen(str)+1)*sizeof(char));
+  strcpy(prim->data.text->str, str);
+  prim->data.text->fontname = (char*)gl2psMalloc((strlen(fontname)+1)*sizeof(char));
+  strcpy(prim->data.text->fontname, fontname);
+  prim->data.text->fontsize = fontsize;
+  prim->data.text->alignment = alignment;
+  prim->data.text->angle = angle;
+
+  gl2psListAdd(gl2ps->auxprimitives, &prim);
+  glPassThrough(GL2PS_TEXT_TOKEN);
+
+  return GL2PS_SUCCESS;
+}
+
+static GL2PSstring *gl2psCopyText(GL2PSstring *t)
+{
+  GL2PSstring *text = (GL2PSstring*)gl2psMalloc(sizeof(GL2PSstring));
+  text->str = (char*)gl2psMalloc((strlen(t->str)+1)*sizeof(char));
+  strcpy(text->str, t->str);
+  text->fontname = (char*)gl2psMalloc((strlen(t->fontname)+1)*sizeof(char));
+  strcpy(text->fontname, t->fontname);
+  text->fontsize = t->fontsize;
+  text->alignment = t->alignment;
+  text->angle = t->angle;
+
+  return text;
+}
+
+static void gl2psFreeText(GL2PSstring *text)
+{
+  if(!text)
+    return;
+  gl2psFree(text->str);
+  gl2psFree(text->fontname);
+  gl2psFree(text);
+}
+
+/* Helpers for blending modes */
+
+static GLboolean gl2psSupportedBlendMode(GLenum sfactor, GLenum dfactor)
+{
+  /* returns TRUE if gl2ps supports the argument combination: only two
+     blending modes have been implemented so far */
+
+  if( (sfactor == GL_SRC_ALPHA && dfactor == GL_ONE_MINUS_SRC_ALPHA) ||
+      (sfactor == GL_ONE && dfactor == GL_ZERO) )
+    return GL_TRUE;
+  return GL_FALSE;
+}
+
+static void gl2psAdaptVertexForBlending(GL2PSvertex *v)
+{
+  /* Transforms vertex depending on the actual blending function -
+     currently the vertex v is considered as source vertex and his
+     alpha value is changed to 1.0 if source blending GL_ONE is
+     active. This might be extended in the future */
+
+  if(!v || !gl2ps)
+    return;
+
+  if(gl2ps->options & GL2PS_NO_BLENDING || !gl2ps->blending){
+    v->rgba[3] = 1.0F;
+    return;
+  }
+
+  switch(gl2ps->blendfunc[0]){
+  case GL_ONE:
+    v->rgba[3] = 1.0F;
+    break;
+  default:
+    break;
+  }
+}
+
+static void gl2psAssignTriangleProperties(GL2PStriangle *t)
+{
+  /* int i; */
+
+  t->prop = T_VAR_COLOR;
+
+  /* Uncommenting the following lines activates an even more fine
+     grained distinction between triangle types - please don't delete,
+     a remarkable amount of PDF handling code inside this file depends
+     on it if activated */
+  /*
+  t->prop = T_CONST_COLOR;
+  for(i = 0; i < 3; ++i){
+    if(!GL2PS_ZERO(t->vertex[0].rgba[i] - t->vertex[1].rgba[i]) ||
+       !GL2PS_ZERO(t->vertex[1].rgba[i] - t->vertex[2].rgba[i])){
+      t->prop = T_VAR_COLOR;
+      break;
+    }
+  }
+  */
+
+  if(!GL2PS_ZERO(t->vertex[0].rgba[3] - t->vertex[1].rgba[3]) ||
+     !GL2PS_ZERO(t->vertex[1].rgba[3] - t->vertex[2].rgba[3])){
+    t->prop |= T_VAR_ALPHA;
+  }
+  else{
+    if(t->vertex[0].rgba[3] < 1)
+      t->prop |= T_ALPHA_LESS_1;
+    else
+      t->prop |= T_ALPHA_1;
+  }
+}
+
+static void gl2psFillTriangleFromPrimitive(GL2PStriangle *t, GL2PSprimitive *p,
+                                           GLboolean assignprops)
+{
+  t->vertex[0] = p->verts[0];
+  t->vertex[1] = p->verts[1];
+  t->vertex[2] = p->verts[2];
+  if(GL_TRUE == assignprops)
+    gl2psAssignTriangleProperties(t);
+}
+
+static void gl2psInitTriangle(GL2PStriangle *t)
+{
+  int i;
+  GL2PSvertex vertex = { {-1.0F, -1.0F, -1.0F}, {-1.0F, -1.0F, -1.0F, -1.0F} };
+  for(i = 0; i < 3; i++)
+    t->vertex[i] = vertex;
+  t->prop = T_UNDEFINED;
+}
+
+/* Miscellaneous helper routines */
+
+static GL2PSprimitive *gl2psCopyPrimitive(GL2PSprimitive *p)
+{
+  GL2PSprimitive *prim;
+
+  if(!p){
+    gl2psMsg(GL2PS_ERROR, "Trying to copy an empty primitive");
+    return NULL;
+  }
+
+  prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+
+  prim->type = p->type;
+  prim->numverts = p->numverts;
+  prim->boundary = p->boundary;
+  prim->offset = p->offset;
+  prim->pattern = p->pattern;
+  prim->factor = p->factor;
+  prim->culled = p->culled;
+  prim->width = p->width;
+  prim->verts = (GL2PSvertex*)gl2psMalloc(p->numverts*sizeof(GL2PSvertex));
+  memcpy(prim->verts, p->verts, p->numverts * sizeof(GL2PSvertex));
+
+  switch(prim->type){
+  case GL2PS_PIXMAP :
+    prim->data.image = gl2psCopyPixmap(p->data.image);
+    break;
+  case GL2PS_TEXT :
+  case GL2PS_SPECIAL :
+    prim->data.text = gl2psCopyText(p->data.text);
+    break;
+  default:
+    break;
+  }
+
+  return prim;
+}
+
+static GLboolean gl2psSamePosition(GL2PSxyz p1, GL2PSxyz p2)
+{
+  if(!GL2PS_ZERO(p1[0] - p2[0]) ||
+     !GL2PS_ZERO(p1[1] - p2[1]) ||
+     !GL2PS_ZERO(p1[2] - p2[2]))
+    return GL_FALSE;
+  return GL_TRUE;
+}
+
+/*********************************************************************
+ *
+ * 3D sorting routines
+ *
+ *********************************************************************/
+
+static GLfloat gl2psComparePointPlane(GL2PSxyz point, GL2PSplane plane)
+{
+  return (plane[0] * point[0] +
+          plane[1] * point[1] +
+          plane[2] * point[2] +
+          plane[3]);
+}
+
+static GLfloat gl2psPsca(GLfloat *a, GLfloat *b)
+{
+  return (a[0]*b[0] + a[1]*b[1] + a[2]*b[2]);
+}
+
+static void gl2psPvec(GLfloat *a, GLfloat *b, GLfloat *c)
+{
+  c[0] = a[1]*b[2] - a[2]*b[1];
+  c[1] = a[2]*b[0] - a[0]*b[2];
+  c[2] = a[0]*b[1] - a[1]*b[0];
+}
+
+static GLfloat gl2psNorm(GLfloat *a)
+{
+  return (GLfloat)sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]);
+}
+
+static void gl2psGetNormal(GLfloat *a, GLfloat *b, GLfloat *c)
+{
+  GLfloat norm;
+
+  gl2psPvec(a, b, c);
+  if(!GL2PS_ZERO(norm = gl2psNorm(c))){
+    c[0] = c[0] / norm;
+    c[1] = c[1] / norm;
+    c[2] = c[2] / norm;
+  }
+  else{
+    /* The plane is still wrong despite our tests in gl2psGetPlane.
+       Let's return a dummy value for now (this is a hack: we should
+       do more intelligent tests in GetPlane) */
+    c[0] = c[1] = 0.0F;
+    c[2] = 1.0F;
+  }
+}
+
+static void gl2psGetPlane(GL2PSprimitive *prim, GL2PSplane plane)
+{
+  GL2PSxyz v = {0.0F, 0.0F, 0.0F}, w = {0.0F, 0.0F, 0.0F};
+
+  switch(prim->type){
+  case GL2PS_TRIANGLE :
+  case GL2PS_QUADRANGLE :
+    v[0] = prim->verts[1].xyz[0] - prim->verts[0].xyz[0];
+    v[1] = prim->verts[1].xyz[1] - prim->verts[0].xyz[1];
+    v[2] = prim->verts[1].xyz[2] - prim->verts[0].xyz[2];
+    w[0] = prim->verts[2].xyz[0] - prim->verts[0].xyz[0];
+    w[1] = prim->verts[2].xyz[1] - prim->verts[0].xyz[1];
+    w[2] = prim->verts[2].xyz[2] - prim->verts[0].xyz[2];
+    if((GL2PS_ZERO(v[0]) && GL2PS_ZERO(v[1]) && GL2PS_ZERO(v[2])) ||
+       (GL2PS_ZERO(w[0]) && GL2PS_ZERO(w[1]) && GL2PS_ZERO(w[2]))){
+      plane[0] = plane[1] = 0.0F;
+      plane[2] = 1.0F;
+      plane[3] = -prim->verts[0].xyz[2];
+    }
+    else{
+      gl2psGetNormal(v, w, plane);
+      plane[3] =
+        - plane[0] * prim->verts[0].xyz[0]
+        - plane[1] * prim->verts[0].xyz[1]
+        - plane[2] * prim->verts[0].xyz[2];
+    }
+    break;
+  case GL2PS_LINE :
+    v[0] = prim->verts[1].xyz[0] - prim->verts[0].xyz[0];
+    v[1] = prim->verts[1].xyz[1] - prim->verts[0].xyz[1];
+    v[2] = prim->verts[1].xyz[2] - prim->verts[0].xyz[2];
+    if(GL2PS_ZERO(v[0]) && GL2PS_ZERO(v[1]) && GL2PS_ZERO(v[2])){
+      plane[0] = plane[1] = 0.0F;
+      plane[2] = 1.0F;
+      plane[3] = -prim->verts[0].xyz[2];
+    }
+    else{
+      if(GL2PS_ZERO(v[0]))      w[0] = 1.0F;
+      else if(GL2PS_ZERO(v[1])) w[1] = 1.0F;
+      else                      w[2] = 1.0F;
+      gl2psGetNormal(v, w, plane);
+      plane[3] =
+        - plane[0] * prim->verts[0].xyz[0]
+        - plane[1] * prim->verts[0].xyz[1]
+        - plane[2] * prim->verts[0].xyz[2];
+    }
+    break;
+  case GL2PS_POINT :
+  case GL2PS_PIXMAP :
+  case GL2PS_TEXT :
+  case GL2PS_SPECIAL :
+  case GL2PS_IMAGEMAP:
+    plane[0] = plane[1] = 0.0F;
+    plane[2] = 1.0F;
+    plane[3] = -prim->verts[0].xyz[2];
+    break;
+  default :
+    gl2psMsg(GL2PS_ERROR, "Unknown primitive type in BSP tree");
+    plane[0] = plane[1] = plane[3] = 0.0F;
+    plane[2] = 1.0F;
+    break;
+  }
+}
+
+static void gl2psCutEdge(GL2PSvertex *a, GL2PSvertex *b, GL2PSplane plane,
+                         GL2PSvertex *c)
+{
+  GL2PSxyz v;
+  GLfloat sect, psca;
+
+  v[0] = b->xyz[0] - a->xyz[0];
+  v[1] = b->xyz[1] - a->xyz[1];
+  v[2] = b->xyz[2] - a->xyz[2];
+
+  if(!GL2PS_ZERO(psca = gl2psPsca(plane, v)))
+    sect = -gl2psComparePointPlane(a->xyz, plane) / psca;
+  else
+    sect = 0.0F;
+
+  c->xyz[0] = a->xyz[0] + v[0] * sect;
+  c->xyz[1] = a->xyz[1] + v[1] * sect;
+  c->xyz[2] = a->xyz[2] + v[2] * sect;
+
+  c->rgba[0] = (1 - sect) * a->rgba[0] + sect * b->rgba[0];
+  c->rgba[1] = (1 - sect) * a->rgba[1] + sect * b->rgba[1];
+  c->rgba[2] = (1 - sect) * a->rgba[2] + sect * b->rgba[2];
+  c->rgba[3] = (1 - sect) * a->rgba[3] + sect * b->rgba[3];
+}
+
+static void gl2psCreateSplitPrimitive(GL2PSprimitive *parent, GL2PSplane plane,
+                                      GL2PSprimitive *child, GLshort numverts,
+                                      GLshort *index0, GLshort *index1)
+{
+  GLshort i;
+
+  if(parent->type == GL2PS_IMAGEMAP){
+    child->type = GL2PS_IMAGEMAP;
+    child->data.image = parent->data.image;
+  }
+  else{
+    if(numverts > 4){
+      gl2psMsg(GL2PS_WARNING, "%d vertices in polygon", numverts);
+      numverts = 4;
+    }
+    switch(numverts){
+    case 1 : child->type = GL2PS_POINT; break;
+    case 2 : child->type = GL2PS_LINE; break;
+    case 3 : child->type = GL2PS_TRIANGLE; break;
+    case 4 : child->type = GL2PS_QUADRANGLE; break;
+    default: child->type = GL2PS_NO_TYPE; break;
+    }
+  }
+
+  child->boundary = 0; /* FIXME: not done! */
+  child->culled = parent->culled;
+  child->offset = parent->offset;
+  child->pattern = parent->pattern;
+  child->factor = parent->factor;
+  child->width = parent->width;
+  child->numverts = numverts;
+  child->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex));
+
+  for(i = 0; i < numverts; i++){
+    if(index1[i] < 0){
+      child->verts[i] = parent->verts[index0[i]];
+    }
+    else{
+      gl2psCutEdge(&parent->verts[index0[i]], &parent->verts[index1[i]],
+                   plane, &child->verts[i]);
+    }
+  }
+}
+
+static void gl2psAddIndex(GLshort *index0, GLshort *index1, GLshort *nb,
+                          GLshort i, GLshort j)
+{
+  GLint k;
+
+  for(k = 0; k < *nb; k++){
+    if((index0[k] == i && index1[k] == j) ||
+       (index1[k] == i && index0[k] == j)) return;
+  }
+  index0[*nb] = i;
+  index1[*nb] = j;
+  (*nb)++;
+}
+
+static GLshort gl2psGetIndex(GLshort i, GLshort num)
+{
+  return (i < num - 1) ? i + 1 : 0;
+}
+
+static GLint gl2psTestSplitPrimitive(GL2PSprimitive *prim, GL2PSplane plane)
+{
+  GLint type = GL2PS_COINCIDENT;
+  GLshort i, j;
+  GLfloat d[5];
+
+  for(i = 0; i < prim->numverts; i++){
+    d[i] = gl2psComparePointPlane(prim->verts[i].xyz, plane);
+  }
+
+  if(prim->numverts < 2){
+    return 0;
+  }
+  else{
+    for(i = 0; i < prim->numverts; i++){
+      j = gl2psGetIndex(i, prim->numverts);
+      if(d[j] > GL2PS_EPSILON){
+        if(type == GL2PS_COINCIDENT)      type = GL2PS_IN_BACK_OF;
+        else if(type != GL2PS_IN_BACK_OF) return 1;
+        if(d[i] < -GL2PS_EPSILON)         return 1;
+      }
+      else if(d[j] < -GL2PS_EPSILON){
+        if(type == GL2PS_COINCIDENT)       type = GL2PS_IN_FRONT_OF;
+        else if(type != GL2PS_IN_FRONT_OF) return 1;
+        if(d[i] > GL2PS_EPSILON)           return 1;
+      }
+    }
+  }
+  return 0;
+}
+
+static GLint gl2psSplitPrimitive(GL2PSprimitive *prim, GL2PSplane plane,
+                                 GL2PSprimitive **front, GL2PSprimitive **back)
+{
+  GLshort i, j, in = 0, out = 0, in0[5], in1[5], out0[5], out1[5];
+  GLint type;
+  GLfloat d[5];
+
+  type = GL2PS_COINCIDENT;
+
+  for(i = 0; i < prim->numverts; i++){
+    d[i] = gl2psComparePointPlane(prim->verts[i].xyz, plane);
+  }
+
+  switch(prim->type){
+  case GL2PS_POINT :
+    if(d[0] > GL2PS_EPSILON)       type = GL2PS_IN_BACK_OF;
+    else if(d[0] < -GL2PS_EPSILON) type = GL2PS_IN_FRONT_OF;
+    else                           type = GL2PS_COINCIDENT;
+    break;
+  default :
+    for(i = 0; i < prim->numverts; i++){
+      j = gl2psGetIndex(i, prim->numverts);
+      if(d[j] > GL2PS_EPSILON){
+        if(type == GL2PS_COINCIDENT)      type = GL2PS_IN_BACK_OF;
+        else if(type != GL2PS_IN_BACK_OF) type = GL2PS_SPANNING;
+        if(d[i] < -GL2PS_EPSILON){
+          gl2psAddIndex(in0, in1, &in, i, j);
+          gl2psAddIndex(out0, out1, &out, i, j);
+          type = GL2PS_SPANNING;
+        }
+        gl2psAddIndex(out0, out1, &out, j, -1);
+      }
+      else if(d[j] < -GL2PS_EPSILON){
+        if(type == GL2PS_COINCIDENT)       type = GL2PS_IN_FRONT_OF;
+        else if(type != GL2PS_IN_FRONT_OF) type = GL2PS_SPANNING;
+        if(d[i] > GL2PS_EPSILON){
+          gl2psAddIndex(in0, in1, &in, i, j);
+          gl2psAddIndex(out0, out1, &out, i, j);
+          type = GL2PS_SPANNING;
+        }
+        gl2psAddIndex(in0, in1, &in, j, -1);
+      }
+      else{
+        gl2psAddIndex(in0, in1, &in, j, -1);
+        gl2psAddIndex(out0, out1, &out, j, -1);
+      }
+    }
+    break;
+  }
+
+  if(type == GL2PS_SPANNING){
+    *back = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+    *front = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+    gl2psCreateSplitPrimitive(prim, plane, *back, out, out0, out1);
+    gl2psCreateSplitPrimitive(prim, plane, *front, in, in0, in1);
+  }
+
+  return type;
+}
+
+static void gl2psDivideQuad(GL2PSprimitive *quad,
+                            GL2PSprimitive **t1, GL2PSprimitive **t2)
+{
+  *t1 = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+  *t2 = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+  (*t1)->type = (*t2)->type = GL2PS_TRIANGLE;
+  (*t1)->numverts = (*t2)->numverts = 3;
+  (*t1)->culled = (*t2)->culled = quad->culled;
+  (*t1)->offset = (*t2)->offset = quad->offset;
+  (*t1)->pattern = (*t2)->pattern = quad->pattern;
+  (*t1)->factor = (*t2)->factor = quad->factor;
+  (*t1)->width = (*t2)->width = quad->width;
+  (*t1)->verts = (GL2PSvertex*)gl2psMalloc(3 * sizeof(GL2PSvertex));
+  (*t2)->verts = (GL2PSvertex*)gl2psMalloc(3 * sizeof(GL2PSvertex));
+  (*t1)->verts[0] = quad->verts[0];
+  (*t1)->verts[1] = quad->verts[1];
+  (*t1)->verts[2] = quad->verts[2];
+  (*t1)->boundary = ((quad->boundary & 1) ? 1 : 0) | ((quad->boundary & 2) ? 2 : 0);
+  (*t2)->verts[0] = quad->verts[0];
+  (*t2)->verts[1] = quad->verts[2];
+  (*t2)->verts[2] = quad->verts[3];
+  (*t2)->boundary = ((quad->boundary & 4) ? 2 : 0) | ((quad->boundary & 8) ? 4 : 0);
+}
+
+static int gl2psCompareDepth(const void *a, const void *b)
+{
+  const GL2PSprimitive *q, *w;
+  GLfloat dq = 0.0F, dw = 0.0F, diff;
+  int i;
+
+  q = *(const GL2PSprimitive* const*)a;
+  w = *(const GL2PSprimitive* const*)b;
+
+  for(i = 0; i < q->numverts; i++){
+    dq += q->verts[i].xyz[2];
+  }
+  dq /= (GLfloat)q->numverts;
+
+  for(i = 0; i < w->numverts; i++){
+    dw += w->verts[i].xyz[2];
+  }
+  dw /= (GLfloat)w->numverts;
+
+  diff = dq - dw;
+  if(diff > 0.){
+    return -1;
+  }
+  else if(diff < 0.){
+    return 1;
+  }
+  else{
+    return 0;
+  }
+}
+
+static int gl2psTrianglesFirst(const void *a, const void *b)
+{
+  const GL2PSprimitive *q, *w;
+
+  q = *(const GL2PSprimitive* const*)a;
+  w = *(const GL2PSprimitive* const*)b;
+  return (q->type < w->type ? 1 : -1);
+}
+
+static GLint gl2psFindRoot(GL2PSlist *primitives, GL2PSprimitive **root)
+{
+  GLint i, j, count, best = 1000000, idx = 0;
+  GL2PSprimitive *prim1, *prim2;
+  GL2PSplane plane;
+  GLint maxp;
+
+  if(!gl2psListNbr(primitives)){
+    gl2psMsg(GL2PS_ERROR, "Cannot fint root in empty primitive list");
+    return 0;
+  }
+
+  *root = *(GL2PSprimitive**)gl2psListPointer(primitives, 0);
+
+  if(gl2ps->options & GL2PS_BEST_ROOT){
+    maxp = gl2psListNbr(primitives);
+    if(maxp > gl2ps->maxbestroot){
+      maxp = gl2ps->maxbestroot;
+    }
+    for(i = 0; i < maxp; i++){
+      prim1 = *(GL2PSprimitive**)gl2psListPointer(primitives, i);
+      gl2psGetPlane(prim1, plane);
+      count = 0;
+      for(j = 0; j < gl2psListNbr(primitives); j++){
+        if(j != i){
+          prim2 = *(GL2PSprimitive**)gl2psListPointer(primitives, j);
+          count += gl2psTestSplitPrimitive(prim2, plane);
+        }
+        if(count > best) break;
+      }
+      if(count < best){
+        best = count;
+        idx = i;
+        *root = prim1;
+        if(!count) return idx;
+      }
+    }
+    /* if(index) gl2psMsg(GL2PS_INFO, "GL2PS_BEST_ROOT was worth it: %d", index); */
+    return idx;
+  }
+  else{
+    return 0;
+  }
+}
+
+static void gl2psFreeImagemap(GL2PSimagemap *list)
+{
+  GL2PSimagemap *next;
+  while(list != NULL){
+    next = list->next;
+    gl2psFree(list->image->pixels);
+    gl2psFree(list->image);
+    gl2psFree(list);
+    list = next;
+  }
+}
+
+static void gl2psFreePrimitive(void *data)
+{
+  GL2PSprimitive *q;
+
+  q = *(GL2PSprimitive**)data;
+  gl2psFree(q->verts);
+  if(q->type == GL2PS_TEXT || q->type == GL2PS_SPECIAL){
+    gl2psFreeText(q->data.text);
+  }
+  else if(q->type == GL2PS_PIXMAP){
+    gl2psFreePixmap(q->data.image);
+  }
+  gl2psFree(q);
+}
+
+static void gl2psAddPrimitiveInList(GL2PSprimitive *prim, GL2PSlist *list)
+{
+  GL2PSprimitive *t1, *t2;
+
+  if(prim->type != GL2PS_QUADRANGLE){
+    gl2psListAdd(list, &prim);
+  }
+  else{
+    gl2psDivideQuad(prim, &t1, &t2);
+    gl2psListAdd(list, &t1);
+    gl2psListAdd(list, &t2);
+    gl2psFreePrimitive(&prim);
+  }
+
+}
+
+static void gl2psFreeBspTree(GL2PSbsptree **tree)
+{
+  if(*tree){
+    if((*tree)->back) gl2psFreeBspTree(&(*tree)->back);
+    if((*tree)->primitives){
+      gl2psListAction((*tree)->primitives, gl2psFreePrimitive);
+      gl2psListDelete((*tree)->primitives);
+    }
+    if((*tree)->front) gl2psFreeBspTree(&(*tree)->front);
+    gl2psFree(*tree);
+    *tree = NULL;
+  }
+}
+
+static GLboolean gl2psGreater(GLfloat f1, GLfloat f2)
+{
+  if(f1 > f2) return GL_TRUE;
+  else return GL_FALSE;
+}
+
+static GLboolean gl2psLess(GLfloat f1, GLfloat f2)
+{
+  if(f1 < f2) return GL_TRUE;
+  else return GL_FALSE;
+}
+
+static void gl2psBuildBspTree(GL2PSbsptree *tree, GL2PSlist *primitives)
+{
+  GL2PSprimitive *prim, *frontprim = NULL, *backprim = NULL;
+  GL2PSlist *frontlist, *backlist;
+  GLint i, idx;
+
+  tree->front = NULL;
+  tree->back = NULL;
+  tree->primitives = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+  idx = gl2psFindRoot(primitives, &prim);
+  gl2psGetPlane(prim, tree->plane);
+  gl2psAddPrimitiveInList(prim, tree->primitives);
+
+  frontlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+  backlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+
+  for(i = 0; i < gl2psListNbr(primitives); i++){
+    if(i != idx){
+      prim = *(GL2PSprimitive**)gl2psListPointer(primitives,i);
+      switch(gl2psSplitPrimitive(prim, tree->plane, &frontprim, &backprim)){
+      case GL2PS_COINCIDENT:
+        gl2psAddPrimitiveInList(prim, tree->primitives);
+        break;
+      case GL2PS_IN_BACK_OF:
+        gl2psAddPrimitiveInList(prim, backlist);
+        break;
+      case GL2PS_IN_FRONT_OF:
+        gl2psAddPrimitiveInList(prim, frontlist);
+        break;
+      case GL2PS_SPANNING:
+        gl2psAddPrimitiveInList(backprim, backlist);
+        gl2psAddPrimitiveInList(frontprim, frontlist);
+        gl2psFreePrimitive(&prim);
+        break;
+      }
+    }
+  }
+
+  if(gl2psListNbr(tree->primitives)){
+    gl2psListSort(tree->primitives, gl2psTrianglesFirst);
+  }
+
+  if(gl2psListNbr(frontlist)){
+    gl2psListSort(frontlist, gl2psTrianglesFirst);
+    tree->front = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree));
+    gl2psBuildBspTree(tree->front, frontlist);
+  }
+  else{
+    gl2psListDelete(frontlist);
+  }
+
+  if(gl2psListNbr(backlist)){
+    gl2psListSort(backlist, gl2psTrianglesFirst);
+    tree->back = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree));
+    gl2psBuildBspTree(tree->back, backlist);
+  }
+  else{
+    gl2psListDelete(backlist);
+  }
+
+  gl2psListDelete(primitives);
+}
+
+static void gl2psTraverseBspTree(GL2PSbsptree *tree, GL2PSxyz eye, GLfloat epsilon,
+                                 GLboolean (*compare)(GLfloat f1, GLfloat f2),
+                                 void (*action)(void *data), int inverse)
+{
+  GLfloat result;
+
+  if(!tree) return;
+
+  result = gl2psComparePointPlane(eye, tree->plane);
+
+  if(GL_TRUE == compare(result, epsilon)){
+    gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse);
+    if(inverse){
+      gl2psListActionInverse(tree->primitives, action);
+    }
+    else{
+      gl2psListAction(tree->primitives, action);
+    }
+    gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse);
+  }
+  else if(GL_TRUE == compare(-epsilon, result)){
+    gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse);
+    if(inverse){
+      gl2psListActionInverse(tree->primitives, action);
+    }
+    else{
+      gl2psListAction(tree->primitives, action);
+    }
+    gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse);
+  }
+  else{
+    gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse);
+    gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse);
+  }
+}
+
+static void gl2psRescaleAndOffset(void)
+{
+  GL2PSprimitive *prim;
+  GLfloat minZ, maxZ, rangeZ, scaleZ;
+  GLfloat factor, units, area, dZ, dZdX, dZdY, maxdZ;
+  int i, j;
+
+  if(!gl2psListNbr(gl2ps->primitives))
+    return;
+
+  /* get z-buffer range */
+  prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, 0);
+  minZ = maxZ = prim->verts[0].xyz[2];
+  for(i = 1; i < prim->numverts; i++){
+    if(prim->verts[i].xyz[2] < minZ) minZ = prim->verts[i].xyz[2];
+    if(prim->verts[i].xyz[2] > maxZ) maxZ = prim->verts[i].xyz[2];
+  }
+  for(i = 1; i < gl2psListNbr(gl2ps->primitives); i++){
+    prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, i);
+    for(j = 0; j < prim->numverts; j++){
+      if(prim->verts[j].xyz[2] < minZ) minZ = prim->verts[j].xyz[2];
+      if(prim->verts[j].xyz[2] > maxZ) maxZ = prim->verts[j].xyz[2];
+    }
+  }
+  rangeZ = (maxZ - minZ);
+
+  /* rescale z-buffer coordinate in [0,GL2PS_ZSCALE], to make it of
+     the same order of magnitude as the x and y coordinates */
+  scaleZ = GL2PS_ZERO(rangeZ) ? GL2PS_ZSCALE : (GL2PS_ZSCALE / rangeZ);
+  /* avoid precision loss (we use floats!) */
+  if(scaleZ > 100000.F) scaleZ = 100000.F;
+
+  /* apply offsets */
+  for(i = 0; i < gl2psListNbr(gl2ps->primitives); i++){
+    prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, i);
+    for(j = 0; j < prim->numverts; j++){
+      prim->verts[j].xyz[2] = (prim->verts[j].xyz[2] - minZ) * scaleZ;
+    }
+    if((gl2ps->options & GL2PS_SIMPLE_LINE_OFFSET) &&
+       (prim->type == GL2PS_LINE)){
+      if(gl2ps->sort == GL2PS_SIMPLE_SORT){
+        prim->verts[0].xyz[2] -= GL2PS_ZOFFSET_LARGE;
+        prim->verts[1].xyz[2] -= GL2PS_ZOFFSET_LARGE;
+      }
+      else{
+        prim->verts[0].xyz[2] -= GL2PS_ZOFFSET;
+        prim->verts[1].xyz[2] -= GL2PS_ZOFFSET;
+      }
+    }
+    else if(prim->offset && (prim->type == GL2PS_TRIANGLE)){
+      factor = gl2ps->offset[0];
+      units = gl2ps->offset[1];
+      area =
+        (prim->verts[1].xyz[0] - prim->verts[0].xyz[0]) *
+        (prim->verts[2].xyz[1] - prim->verts[1].xyz[1]) -
+        (prim->verts[2].xyz[0] - prim->verts[1].xyz[0]) *
+        (prim->verts[1].xyz[1] - prim->verts[0].xyz[1]);
+      if(!GL2PS_ZERO(area)){
+        dZdX =
+          ((prim->verts[2].xyz[1] - prim->verts[1].xyz[1]) *
+           (prim->verts[1].xyz[2] - prim->verts[0].xyz[2]) -
+           (prim->verts[1].xyz[1] - prim->verts[0].xyz[1]) *
+           (prim->verts[2].xyz[2] - prim->verts[1].xyz[2])) / area;
+        dZdY =
+          ((prim->verts[1].xyz[0] - prim->verts[0].xyz[0]) *
+           (prim->verts[2].xyz[2] - prim->verts[1].xyz[2]) -
+           (prim->verts[2].xyz[0] - prim->verts[1].xyz[0]) *
+           (prim->verts[1].xyz[2] - prim->verts[0].xyz[2])) / area;
+        maxdZ = (GLfloat)sqrt(dZdX * dZdX + dZdY * dZdY);
+      }
+      else{
+        maxdZ = 0.0F;
+      }
+      dZ = factor * maxdZ + units;
+      prim->verts[0].xyz[2] += dZ;
+      prim->verts[1].xyz[2] += dZ;
+      prim->verts[2].xyz[2] += dZ;
+    }
+  }
+}
+
+/*********************************************************************
+ *
+ * 2D sorting routines (for occlusion culling)
+ *
+ *********************************************************************/
+
+static GLint gl2psGetPlaneFromPoints(GL2PSxyz a, GL2PSxyz b, GL2PSplane plane)
+{
+  GLfloat n;
+
+  plane[0] = b[1] - a[1];
+  plane[1] = a[0] - b[0];
+  n = (GLfloat)sqrt(plane[0]*plane[0] + plane[1]*plane[1]);
+  plane[2] = 0.0F;
+  if(!GL2PS_ZERO(n)){
+    plane[0] /= n;
+    plane[1] /= n;
+    plane[3] = -plane[0]*a[0]-plane[1]*a[1];
+    return 1;
+  }
+  else{
+    plane[0] = -1.0F;
+    plane[1] = 0.0F;
+    plane[3] = a[0];
+    return 0;
+  }
+}
+
+static void gl2psFreeBspImageTree(GL2PSbsptree2d **tree)
+{
+  if(*tree){
+    if((*tree)->back)  gl2psFreeBspImageTree(&(*tree)->back);
+    if((*tree)->front) gl2psFreeBspImageTree(&(*tree)->front);
+    gl2psFree(*tree);
+    *tree = NULL;
+  }
+}
+
+static GLint gl2psCheckPoint(GL2PSxyz point, GL2PSplane plane)
+{
+  GLfloat pt_dis;
+
+  pt_dis = gl2psComparePointPlane(point, plane);
+  if(pt_dis > GL2PS_EPSILON)        return GL2PS_POINT_INFRONT;
+  else if(pt_dis < -GL2PS_EPSILON)  return GL2PS_POINT_BACK;
+  else                              return GL2PS_POINT_COINCIDENT;
+}
+
+static void gl2psAddPlanesInBspTreeImage(GL2PSprimitive *prim,
+                                         GL2PSbsptree2d **tree)
+{
+  GLint ret = 0;
+  GLint i;
+  GLint offset = 0;
+  GL2PSbsptree2d *head = NULL, *cur = NULL;
+
+  if((*tree == NULL) && (prim->numverts > 2)){
+    /* don't cull if transparent
+    for(i = 0; i < prim->numverts - 1; i++)
+      if(prim->verts[i].rgba[3] < 1.0F) return;
+    */
+    head = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d));
+    for(i = 0; i < prim->numverts-1; i++){
+      if(!gl2psGetPlaneFromPoints(prim->verts[i].xyz,
+                                  prim->verts[i+1].xyz,
+                                  head->plane)){
+        if(prim->numverts-i > 3){
+          offset++;
+        }
+        else{
+          gl2psFree(head);
+          return;
+        }
+      }
+      else{
+        break;
+      }
+    }
+    head->back = NULL;
+    head->front = NULL;
+    for(i = 2+offset; i < prim->numverts; i++){
+      ret = gl2psCheckPoint(prim->verts[i].xyz, head->plane);
+      if(ret != GL2PS_POINT_COINCIDENT) break;
+    }
+    switch(ret){
+    case GL2PS_POINT_INFRONT :
+      cur = head;
+      for(i = 1+offset; i < prim->numverts-1; i++){
+        if(cur->front == NULL){
+          cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d));
+        }
+        if(gl2psGetPlaneFromPoints(prim->verts[i].xyz,
+                                   prim->verts[i+1].xyz,
+                                   cur->front->plane)){
+          cur = cur->front;
+          cur->front = NULL;
+          cur->back = NULL;
+        }
+      }
+      if(cur->front == NULL){
+        cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d));
+      }
+      if(gl2psGetPlaneFromPoints(prim->verts[i].xyz,
+                                 prim->verts[offset].xyz,
+                                 cur->front->plane)){
+        cur->front->front = NULL;
+        cur->front->back = NULL;
+      }
+      else{
+        gl2psFree(cur->front);
+        cur->front = NULL;
+      }
+      break;
+    case GL2PS_POINT_BACK :
+      for(i = 0; i < 4; i++){
+        head->plane[i] = -head->plane[i];
+      }
+      cur = head;
+      for(i = 1+offset; i < prim->numverts-1; i++){
+        if(cur->front == NULL){
+          cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d));
+        }
+        if(gl2psGetPlaneFromPoints(prim->verts[i+1].xyz,
+                                   prim->verts[i].xyz,
+                                   cur->front->plane)){
+          cur = cur->front;
+          cur->front = NULL;
+          cur->back = NULL;
+        }
+      }
+      if(cur->front == NULL){
+        cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d));
+      }
+      if(gl2psGetPlaneFromPoints(prim->verts[offset].xyz,
+                                 prim->verts[i].xyz,
+                                 cur->front->plane)){
+        cur->front->front = NULL;
+        cur->front->back = NULL;
+      }
+      else{
+        gl2psFree(cur->front);
+        cur->front = NULL;
+      }
+      break;
+    default:
+      gl2psFree(head);
+      return;
+    }
+    (*tree) = head;
+  }
+}
+
+static GLint gl2psCheckPrimitive(GL2PSprimitive *prim, GL2PSplane plane)
+{
+  GLint i;
+  GLint pos;
+
+  pos = gl2psCheckPoint(prim->verts[0].xyz, plane);
+  for(i = 1; i < prim->numverts; i++){
+    pos |= gl2psCheckPoint(prim->verts[i].xyz, plane);
+    if(pos == (GL2PS_POINT_INFRONT | GL2PS_POINT_BACK)) return GL2PS_SPANNING;
+  }
+  if(pos & GL2PS_POINT_INFRONT)   return GL2PS_IN_FRONT_OF;
+  else if(pos & GL2PS_POINT_BACK) return GL2PS_IN_BACK_OF;
+  else                            return GL2PS_COINCIDENT;
+}
+
+static GL2PSprimitive *gl2psCreateSplitPrimitive2D(GL2PSprimitive *parent,
+                                                   GLshort numverts,
+                                                   GL2PSvertex *vertx)
+{
+  GLint i;
+  GL2PSprimitive *child = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+
+  if(parent->type == GL2PS_IMAGEMAP){
+    child->type = GL2PS_IMAGEMAP;
+    child->data.image = parent->data.image;
+  }
+  else {
+    switch(numverts){
+    case 1 : child->type = GL2PS_POINT; break;
+    case 2 : child->type = GL2PS_LINE; break;
+    case 3 : child->type = GL2PS_TRIANGLE; break;
+    case 4 : child->type = GL2PS_QUADRANGLE; break;
+    default: child->type = GL2PS_NO_TYPE; break; /* FIXME */
+    }
+  }
+  child->boundary = 0; /* FIXME: not done! */
+  child->culled = parent->culled;
+  child->offset = parent->offset;
+  child->pattern = parent->pattern;
+  child->factor = parent->factor;
+  child->width = parent->width;
+  child->numverts = numverts;
+  child->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex));
+  for(i = 0; i < numverts; i++){
+    child->verts[i] = vertx[i];
+  }
+  return child;
+}
+
+static void gl2psSplitPrimitive2D(GL2PSprimitive *prim,
+                                  GL2PSplane plane,
+                                  GL2PSprimitive **front,
+                                  GL2PSprimitive **back)
+{
+  /* cur will hold the position of the current vertex
+     prev will hold the position of the previous vertex
+     prev0 will hold the position of the vertex number 0
+     v1 and v2 represent the current and previous vertices, respectively
+     flag is set if the current vertex should be checked against the plane */
+  GLint cur = -1, prev = -1, i, v1 = 0, v2 = 0, flag = 1, prev0 = -1;
+
+  /* list of vertices that will go in front and back primitive */
+  GL2PSvertex *front_list = NULL, *back_list = NULL;
+
+  /* number of vertices in front and back list */
+  GLshort front_count = 0, back_count = 0;
+
+  for(i = 0; i <= prim->numverts; i++){
+    v1 = i;
+    if(v1 == prim->numverts){
+      if(prim->numverts < 3) break;
+      v1 = 0;
+      v2 = prim->numverts - 1;
+      cur = prev0;
+    }
+    else if(flag){
+      cur = gl2psCheckPoint(prim->verts[v1].xyz, plane);
+      if(i == 0){
+        prev0 = cur;
+      }
+    }
+    if(((prev == -1) || (prev == cur) || (prev == 0) || (cur == 0)) &&
+       (i < prim->numverts)){
+      if(cur == GL2PS_POINT_INFRONT){
+        front_count++;
+        front_list = (GL2PSvertex*)gl2psRealloc(front_list,
+                                                sizeof(GL2PSvertex)*front_count);
+        front_list[front_count-1] = prim->verts[v1];
+      }
+      else if(cur == GL2PS_POINT_BACK){
+        back_count++;
+        back_list = (GL2PSvertex*)gl2psRealloc(back_list,
+                                               sizeof(GL2PSvertex)*back_count);
+        back_list[back_count-1] = prim->verts[v1];
+      }
+      else{
+        front_count++;
+        front_list = (GL2PSvertex*)gl2psRealloc(front_list,
+                                                sizeof(GL2PSvertex)*front_count);
+        front_list[front_count-1] = prim->verts[v1];
+        back_count++;
+        back_list = (GL2PSvertex*)gl2psRealloc(back_list,
+                                               sizeof(GL2PSvertex)*back_count);
+        back_list[back_count-1] = prim->verts[v1];
+      }
+      flag = 1;
+    }
+    else if((prev != cur) && (cur != 0) && (prev != 0)){
+      if(v1 != 0){
+        v2 = v1-1;
+        i--;
+      }
+      front_count++;
+      front_list = (GL2PSvertex*)gl2psRealloc(front_list,
+                                              sizeof(GL2PSvertex)*front_count);
+      gl2psCutEdge(&prim->verts[v2], &prim->verts[v1],
+                   plane, &front_list[front_count-1]);
+      back_count++;
+      back_list = (GL2PSvertex*)gl2psRealloc(back_list,
+                                             sizeof(GL2PSvertex)*back_count);
+      back_list[back_count-1] = front_list[front_count-1];
+      flag = 0;
+    }
+    prev = cur;
+  }
+  *front = gl2psCreateSplitPrimitive2D(prim, front_count, front_list);
+  *back = gl2psCreateSplitPrimitive2D(prim, back_count, back_list);
+  gl2psFree(front_list);
+  gl2psFree(back_list);
+}
+
+static GLint gl2psAddInBspImageTree(GL2PSprimitive *prim, GL2PSbsptree2d **tree)
+{
+  GLint ret = 0;
+  GL2PSprimitive *frontprim = NULL, *backprim = NULL;
+
+  /* FIXME: until we consider the actual extent of text strings and
+     pixmaps, never cull them. Otherwise the whole string/pixmap gets
+     culled as soon as the reference point is hidden */
+  if(prim->type == GL2PS_PIXMAP ||
+     prim->type == GL2PS_TEXT ||
+     prim->type == GL2PS_SPECIAL){
+    return 1;
+  }
+
+  if(*tree == NULL){
+    if((prim->type != GL2PS_IMAGEMAP) && (GL_FALSE == gl2ps->zerosurfacearea)){
+      gl2psAddPlanesInBspTreeImage(gl2ps->primitivetoadd, tree);
+    }
+    return 1;
+  }
+  else{
+    switch(gl2psCheckPrimitive(prim, (*tree)->plane)){
+    case GL2PS_IN_BACK_OF: return gl2psAddInBspImageTree(prim, &(*tree)->back);
+    case GL2PS_IN_FRONT_OF:
+      if((*tree)->front != NULL) return gl2psAddInBspImageTree(prim, &(*tree)->front);
+      else                       return 0;
+    case GL2PS_SPANNING:
+      gl2psSplitPrimitive2D(prim, (*tree)->plane, &frontprim, &backprim);
+      ret = gl2psAddInBspImageTree(backprim, &(*tree)->back);
+      if((*tree)->front != NULL){
+        if(gl2psAddInBspImageTree(frontprim, &(*tree)->front)){
+          ret = 1;
+        }
+      }
+      gl2psFree(frontprim->verts);
+      gl2psFree(frontprim);
+      gl2psFree(backprim->verts);
+      gl2psFree(backprim);
+      return ret;
+    case GL2PS_COINCIDENT:
+      if((*tree)->back != NULL){
+        gl2ps->zerosurfacearea = GL_TRUE;
+        ret = gl2psAddInBspImageTree(prim, &(*tree)->back);
+        gl2ps->zerosurfacearea = GL_FALSE;
+        if(ret) return ret;
+      }
+      if((*tree)->front != NULL){
+        gl2ps->zerosurfacearea = GL_TRUE;
+        ret = gl2psAddInBspImageTree(prim, &(*tree)->front);
+        gl2ps->zerosurfacearea = GL_FALSE;
+        if(ret) return ret;
+      }
+      if(prim->type == GL2PS_LINE) return 1;
+      else                         return 0;
+    }
+  }
+  return 0;
+}
+
+static void gl2psAddInImageTree(void *data)
+{
+  GL2PSprimitive *prim = *(GL2PSprimitive **)data;
+  gl2ps->primitivetoadd = prim;
+  if(prim->type == GL2PS_IMAGEMAP && prim->data.image->format == GL2PS_IMAGEMAP_VISIBLE){
+    prim->culled = 1;
+  }
+  else if(!gl2psAddInBspImageTree(prim, &gl2ps->imagetree)){
+    prim->culled = 1;
+  }
+  else if(prim->type == GL2PS_IMAGEMAP){
+    prim->data.image->format = GL2PS_IMAGEMAP_VISIBLE;
+  }
+}
+
+/* Boundary construction */
+
+static void gl2psAddBoundaryInList(GL2PSprimitive *prim, GL2PSlist *list)
+{
+  GL2PSprimitive *b;
+  GLshort i;
+  GL2PSxyz c;
+
+  c[0] = c[1] = c[2] = 0.0F;
+  for(i = 0; i < prim->numverts; i++){
+    c[0] += prim->verts[i].xyz[0];
+    c[1] += prim->verts[i].xyz[1];
+  }
+  c[0] /= prim->numverts;
+  c[1] /= prim->numverts;
+
+  for(i = 0; i < prim->numverts; i++){
+    if(prim->boundary & (GLint)pow(2., i)){
+      b = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+      b->type = GL2PS_LINE;
+      b->offset = prim->offset;
+      b->pattern = prim->pattern;
+      b->factor = prim->factor;
+      b->culled = prim->culled;
+      b->width = prim->width;
+      b->boundary = 0;
+      b->numverts = 2;
+      b->verts = (GL2PSvertex*)gl2psMalloc(2 * sizeof(GL2PSvertex));
+
+#if 0 /* FIXME: need to work on boundary offset... */
+      v[0] = c[0] - prim->verts[i].xyz[0];
+      v[1] = c[1] - prim->verts[i].xyz[1];
+      v[2] = 0.0F;
+      norm = gl2psNorm(v);
+      v[0] /= norm;
+      v[1] /= norm;
+      b->verts[0].xyz[0] = prim->verts[i].xyz[0] +0.1*v[0];
+      b->verts[0].xyz[1] = prim->verts[i].xyz[1] +0.1*v[1];
+      b->verts[0].xyz[2] = prim->verts[i].xyz[2];
+      v[0] = c[0] - prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0];
+      v[1] = c[1] - prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1];
+      norm = gl2psNorm(v);
+      v[0] /= norm;
+      v[1] /= norm;
+      b->verts[1].xyz[0] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0] +0.1*v[0];
+      b->verts[1].xyz[1] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1] +0.1*v[1];
+      b->verts[1].xyz[2] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[2];
+#else
+      b->verts[0].xyz[0] = prim->verts[i].xyz[0];
+      b->verts[0].xyz[1] = prim->verts[i].xyz[1];
+      b->verts[0].xyz[2] = prim->verts[i].xyz[2];
+      b->verts[1].xyz[0] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0];
+      b->verts[1].xyz[1] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1];
+      b->verts[1].xyz[2] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[2];
+#endif
+
+      b->verts[0].rgba[0] = 0.0F;
+      b->verts[0].rgba[1] = 0.0F;
+      b->verts[0].rgba[2] = 0.0F;
+      b->verts[0].rgba[3] = 0.0F;
+      b->verts[1].rgba[0] = 0.0F;
+      b->verts[1].rgba[1] = 0.0F;
+      b->verts[1].rgba[2] = 0.0F;
+      b->verts[1].rgba[3] = 0.0F;
+      gl2psListAdd(list, &b);
+    }
+  }
+
+}
+
+static void gl2psBuildPolygonBoundary(GL2PSbsptree *tree)
+{
+  GLint i;
+  GL2PSprimitive *prim;
+
+  if(!tree) return;
+  gl2psBuildPolygonBoundary(tree->back);
+  for(i = 0; i < gl2psListNbr(tree->primitives); i++){
+    prim = *(GL2PSprimitive**)gl2psListPointer(tree->primitives, i);
+    if(prim->boundary) gl2psAddBoundaryInList(prim, tree->primitives);
+  }
+  gl2psBuildPolygonBoundary(tree->front);
+}
+
+/*********************************************************************
+ *
+ * Feedback buffer parser
+ *
+ *********************************************************************/
+
+static void gl2psAddPolyPrimitive(GLshort type, GLshort numverts,
+                                  GL2PSvertex *verts, GLint offset,
+                                  GLushort pattern, GLint factor,
+                                  GLfloat width, char boundary)
+{
+  GL2PSprimitive *prim;
+
+  prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+  prim->type = type;
+  prim->numverts = numverts;
+  prim->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex));
+  memcpy(prim->verts, verts, numverts * sizeof(GL2PSvertex));
+  prim->boundary = boundary;
+  prim->offset = offset;
+  prim->pattern = pattern;
+  prim->factor = factor;
+  prim->width = width;
+  prim->culled = 0;
+
+  /* FIXME: here we should have an option to split stretched
+     tris/quads to enhance SIMPLE_SORT */
+
+  gl2psListAdd(gl2ps->primitives, &prim);
+}
+
+static GLint gl2psGetVertex(GL2PSvertex *v, GLfloat *p)
+{
+  GLint i;
+
+  v->xyz[0] = p[0];
+  v->xyz[1] = p[1];
+  v->xyz[2] = p[2];
+
+  if(gl2ps->colormode == GL_COLOR_INDEX && gl2ps->colorsize > 0){
+    i = (GLint)(p[3] + 0.5);
+    v->rgba[0] = gl2ps->colormap[i][0];
+    v->rgba[1] = gl2ps->colormap[i][1];
+    v->rgba[2] = gl2ps->colormap[i][2];
+    v->rgba[3] = gl2ps->colormap[i][3];
+    return 4;
+  }
+  else{
+    v->rgba[0] = p[3];
+    v->rgba[1] = p[4];
+    v->rgba[2] = p[5];
+    v->rgba[3] = p[6];
+    return 7;
+  }
+}
+
+static void gl2psParseFeedbackBuffer(GLint used)
+{
+  char flag;
+  GLushort pattern = 0;
+  GLboolean boundary;
+  GLint i, sizeoffloat, count, v, vtot, offset = 0, factor = 0, auxindex = 0;
+  GLfloat lwidth = 1.0F, psize = 1.0F;
+  GLfloat *current;
+  GL2PSvertex vertices[3];
+  GL2PSprimitive *prim;
+  GL2PSimagemap *node;
+
+  current = gl2ps->feedback;
+  boundary = gl2ps->boundary = GL_FALSE;
+
+  while(used > 0){
+
+    if(GL_TRUE == boundary) gl2ps->boundary = GL_TRUE;
+
+    switch((GLint)*current){
+    case GL_POINT_TOKEN :
+      current ++;
+      used --;
+      i = gl2psGetVertex(&vertices[0], current);
+      current += i;
+      used    -= i;
+      gl2psAddPolyPrimitive(GL2PS_POINT, 1, vertices, 0,
+                            pattern, factor, psize, 0);
+      break;
+    case GL_LINE_TOKEN :
+    case GL_LINE_RESET_TOKEN :
+      current ++;
+      used --;
+      i = gl2psGetVertex(&vertices[0], current);
+      current += i;
+      used    -= i;
+      i = gl2psGetVertex(&vertices[1], current);
+      current += i;
+      used    -= i;
+      gl2psAddPolyPrimitive(GL2PS_LINE, 2, vertices, 0,
+                            pattern, factor, lwidth, 0);
+      break;
+    case GL_POLYGON_TOKEN :
+      count = (GLint)current[1];
+      current += 2;
+      used -= 2;
+      v = vtot = 0;
+      while(count > 0 && used > 0){
+        i = gl2psGetVertex(&vertices[v], current);
+        gl2psAdaptVertexForBlending(&vertices[v]);
+        current += i;
+        used    -= i;
+        count --;
+        vtot++;
+        if(v == 2){
+          if(GL_TRUE == boundary){
+            if(!count && vtot == 2) flag = 1|2|4;
+            else if(!count) flag = 2|4;
+            else if(vtot == 2) flag = 1|2;
+            else flag = 2;
+          }
+          else
+            flag = 0;
+          gl2psAddPolyPrimitive(GL2PS_TRIANGLE, 3, vertices, offset,
+                                pattern, factor, 1, flag);
+          vertices[1] = vertices[2];
+        }
+        else
+          v ++;
+      }
+      break;
+    case GL_BITMAP_TOKEN :
+    case GL_DRAW_PIXEL_TOKEN :
+    case GL_COPY_PIXEL_TOKEN :
+      current ++;
+      used --;
+      i = gl2psGetVertex(&vertices[0], current);
+      current += i;
+      used    -= i;
+      break;
+    case GL_PASS_THROUGH_TOKEN :
+      switch((GLint)current[1]){
+      case GL2PS_BEGIN_OFFSET_TOKEN : offset = 1; break;
+      case GL2PS_END_OFFSET_TOKEN : offset = 0; break;
+      case GL2PS_BEGIN_BOUNDARY_TOKEN : boundary = GL_TRUE; break;
+      case GL2PS_END_BOUNDARY_TOKEN : boundary = GL_FALSE; break;
+      case GL2PS_END_STIPPLE_TOKEN : pattern = factor = 0; break;
+      case GL2PS_BEGIN_BLEND_TOKEN : gl2ps->blending = GL_TRUE; break;
+      case GL2PS_END_BLEND_TOKEN : gl2ps->blending = GL_FALSE; break;
+      case GL2PS_BEGIN_STIPPLE_TOKEN :
+        current += 2;
+        used -= 2;
+        pattern = (GLushort)current[1];
+        current += 2;
+        used -= 2;
+        factor = (GLint)current[1];
+        break;
+      case GL2PS_SRC_BLEND_TOKEN :
+        current += 2;
+        used -= 2;
+        gl2ps->blendfunc[0] = (GLint)current[1];
+        break;
+      case GL2PS_DST_BLEND_TOKEN :
+        current += 2;
+        used -= 2;
+        gl2ps->blendfunc[1] = (GLint)current[1];
+        break;
+      case GL2PS_POINT_SIZE_TOKEN :
+        current += 2;
+        used -= 2;
+        psize = current[1];
+        break;
+      case GL2PS_LINE_WIDTH_TOKEN :
+        current += 2;
+        used -= 2;
+        lwidth = current[1];
+        break;
+      case GL2PS_IMAGEMAP_TOKEN :
+        prim = (GL2PSprimitive *)gl2psMalloc(sizeof(GL2PSprimitive));
+        prim->type = GL2PS_IMAGEMAP;
+        prim->boundary = 0;
+        prim->numverts = 4;
+        prim->verts = (GL2PSvertex *)gl2psMalloc(4 * sizeof(GL2PSvertex));
+        prim->culled = 0;
+        prim->offset = 0;
+        prim->pattern = 0;
+        prim->factor = 0;
+        prim->width = 1;
+
+        node = (GL2PSimagemap*)gl2psMalloc(sizeof(GL2PSimagemap));
+        node->image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage));
+        node->image->type = 0;
+        node->image->format = 0;
+        node->image->zoom_x = 1.0F;
+        node->image->zoom_y = 1.0F;
+        node->next = NULL;
+
+        if(gl2ps->imagemap_head == NULL)
+          gl2ps->imagemap_head = node;
+        else
+          gl2ps->imagemap_tail->next = node;
+        gl2ps->imagemap_tail = node;
+        prim->data.image = node->image;
+
+        current += 2; used -= 2;
+        i = gl2psGetVertex(&prim->verts[0], &current[1]);
+        current += i; used -= i;
+
+        node->image->width = (GLint)current[2];
+        current += 2; used -= 2;
+        node->image->height = (GLint)current[2];
+        prim->verts[0].xyz[0] = prim->verts[0].xyz[0] - (int)(node->image->width / 2) + 0.5F;
+        prim->verts[0].xyz[1] = prim->verts[0].xyz[1] - (int)(node->image->height / 2) + 0.5F;
+        for(i = 1; i < 4; i++){
+          for(v = 0; v < 3; v++){
+            prim->verts[i].xyz[v] = prim->verts[0].xyz[v];
+            prim->verts[i].rgba[v] = prim->verts[0].rgba[v];
+          }
+          prim->verts[i].rgba[v] = prim->verts[0].rgba[v];
+        }
+        prim->verts[1].xyz[0] = prim->verts[1].xyz[0] + node->image->width;
+        prim->verts[2].xyz[0] = prim->verts[1].xyz[0];
+        prim->verts[2].xyz[1] = prim->verts[2].xyz[1] + node->image->height;
+        prim->verts[3].xyz[1] = prim->verts[2].xyz[1];
+
+        sizeoffloat = sizeof(GLfloat);
+        v = 2 * sizeoffloat;
+        vtot = node->image->height + node->image->height *
+          ((node->image->width - 1) / 8);
+        node->image->pixels = (GLfloat*)gl2psMalloc(v + vtot);
+        node->image->pixels[0] = prim->verts[0].xyz[0];
+        node->image->pixels[1] = prim->verts[0].xyz[1];
+
+        for(i = 0; i < vtot; i += sizeoffloat){
+          current += 2; used -= 2;
+          if((vtot - i) >= 4)
+            memcpy(&(((char*)(node->image->pixels))[i + v]), &(current[2]), sizeoffloat);
+          else
+            memcpy(&(((char*)(node->image->pixels))[i + v]), &(current[2]), vtot - i);
+        }
+        current++; used--;
+        gl2psListAdd(gl2ps->primitives, &prim);
+        break;
+      case GL2PS_DRAW_PIXELS_TOKEN :
+      case GL2PS_TEXT_TOKEN :
+        if(auxindex < gl2psListNbr(gl2ps->auxprimitives))
+          gl2psListAdd(gl2ps->primitives,
+                       gl2psListPointer(gl2ps->auxprimitives, auxindex++));
+        else
+          gl2psMsg(GL2PS_ERROR, "Wrong number of auxiliary tokens in buffer");
+        break;
+      }
+      current += 2;
+      used -= 2;
+      break;
+    default :
+      gl2psMsg(GL2PS_WARNING, "Unknown token in buffer");
+      current ++;
+      used --;
+      break;
+    }
+  }
+
+  gl2psListReset(gl2ps->auxprimitives);
+}
+
+/*********************************************************************
+ *
+ * PostScript routines
+ *
+ *********************************************************************/
+
+static void gl2psWriteByte(unsigned char byte)
+{
+  unsigned char h = byte / 16;
+  unsigned char l = byte % 16;
+  gl2psPrintf("%x%x", h, l);
+}
+
+static void gl2psPrintPostScriptPixmap(GLfloat x, GLfloat y, GL2PSimage *im)
+{
+  GLuint nbhex, nbyte, nrgb, nbits;
+  GLuint row, col, ibyte, icase;
+  GLfloat dr, dg, db, fgrey;
+  unsigned char red = 0, green = 0, blue = 0, b, grey;
+  GLuint width = (GLuint)im->width;
+  GLuint height = (GLuint)im->height;
+
+  /* FIXME: should we define an option for these? Or just keep the
+     8-bit per component case? */
+  int greyscale = 0; /* set to 1 to output greyscale image */
+  int nbit = 8; /* number of bits per color compoment (2, 4 or 8) */
+
+  if((width <= 0) || (height <= 0)) return;
+
+  gl2psPrintf("gsave\n");
+  gl2psPrintf("%.2f %.2f translate\n", x, y);
+  gl2psPrintf("%.2f %.2f scale\n", width * im->zoom_x, height * im->zoom_y);
+
+  if(greyscale){ /* greyscale */
+    gl2psPrintf("/picstr %d string def\n", width);
+    gl2psPrintf("%d %d %d\n", width, height, 8);
+    gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height);
+    gl2psPrintf("{ currentfile picstr readhexstring pop }\n");
+    gl2psPrintf("image\n");
+    for(row = 0; row < height; row++){
+      for(col = 0; col < width; col++){
+        gl2psGetRGB(im, col, row, &dr, &dg, &db);
+        fgrey = (0.30F * dr + 0.59F * dg + 0.11F * db);
+        grey = (unsigned char)(255. * fgrey);
+        gl2psWriteByte(grey);
+      }
+      gl2psPrintf("\n");
+    }
+    nbhex = width * height * 2;
+    gl2psPrintf("%%%% nbhex digit          :%d\n", nbhex);
+  }
+  else if(nbit == 2){ /* color, 2 bits for r and g and b; rgbs following each other */
+    nrgb = width  * 3;
+    nbits = nrgb * nbit;
+    nbyte = nbits / 8;
+    if((nbyte * 8) != nbits) nbyte++;
+    gl2psPrintf("/rgbstr %d string def\n", nbyte);
+    gl2psPrintf("%d %d %d\n", width, height, nbit);
+    gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height);
+    gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n");
+    gl2psPrintf("false 3\n");
+    gl2psPrintf("colorimage\n");
+    for(row = 0; row < height; row++){
+      icase = 1;
+      col = 0;
+      b = 0;
+      for(ibyte = 0; ibyte < nbyte; ibyte++){
+        if(icase == 1) {
+          if(col < width) {
+            gl2psGetRGB(im, col, row, &dr, &dg, &db);
+          }
+          else {
+            dr = dg = db = 0;
+          }
+          col++;
+          red = (unsigned char)(3. * dr);
+          green = (unsigned char)(3. * dg);
+          blue = (unsigned char)(3. * db);
+          b = red;
+          b = (b<<2) + green;
+          b = (b<<2) + blue;
+          if(col < width) {
+            gl2psGetRGB(im, col, row, &dr, &dg, &db);
+          }
+          else {
+            dr = dg = db = 0;
+          }
+          col++;
+          red = (unsigned char)(3. * dr);
+          green = (unsigned char)(3. * dg);
+          blue = (unsigned char)(3. * db);
+          b = (b<<2) + red;
+          gl2psWriteByte(b);
+          b = 0;
+          icase++;
+        }
+        else if(icase == 2) {
+          b = green;
+          b = (b<<2) + blue;
+          if(col < width) {
+            gl2psGetRGB(im, col, row, &dr, &dg, &db);
+          }
+          else {
+            dr = dg = db = 0;
+          }
+          col++;
+          red = (unsigned char)(3. * dr);
+          green = (unsigned char)(3. * dg);
+          blue = (unsigned char)(3. * db);
+          b = (b<<2) + red;
+          b = (b<<2) + green;
+          gl2psWriteByte(b);
+          b = 0;
+          icase++;
+        }
+        else if(icase == 3) {
+          b = blue;
+          if(col < width) {
+            gl2psGetRGB(im, col, row, &dr, &dg, &db);
+          }
+          else {
+            dr = dg = db = 0;
+          }
+          col++;
+          red = (unsigned char)(3. * dr);
+          green = (unsigned char)(3. * dg);
+          blue = (unsigned char)(3. * db);
+          b = (b<<2) + red;
+          b = (b<<2) + green;
+          b = (b<<2) + blue;
+          gl2psWriteByte(b);
+          b = 0;
+          icase = 1;
+        }
+      }
+      gl2psPrintf("\n");
+    }
+  }
+  else if(nbit == 4){ /* color, 4 bits for r and g and b; rgbs following each other */
+    nrgb = width  * 3;
+    nbits = nrgb * nbit;
+    nbyte = nbits / 8;
+    if((nbyte * 8) != nbits) nbyte++;
+    gl2psPrintf("/rgbstr %d string def\n", nbyte);
+    gl2psPrintf("%d %d %d\n", width, height, nbit);
+    gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height);
+    gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n");
+    gl2psPrintf("false 3\n");
+    gl2psPrintf("colorimage\n");
+    for(row = 0; row < height; row++){
+      col = 0;
+      icase = 1;
+      for(ibyte = 0; ibyte < nbyte; ibyte++){
+        if(icase == 1) {
+          if(col < width) {
+            gl2psGetRGB(im, col, row, &dr, &dg, &db);
+          }
+          else {
+            dr = dg = db = 0;
+          }
+          col++;
+          red = (unsigned char)(15. * dr);
+          green = (unsigned char)(15. * dg);
+          gl2psPrintf("%x%x", red, green);
+          icase++;
+        }
+        else if(icase == 2) {
+          blue = (unsigned char)(15. * db);
+          if(col < width) {
+            gl2psGetRGB(im, col, row, &dr, &dg, &db);
+          }
+          else {
+            dr = dg = db = 0;
+          }
+          col++;
+          red = (unsigned char)(15. * dr);
+          gl2psPrintf("%x%x", blue, red);
+          icase++;
+        }
+        else if(icase == 3) {
+          green = (unsigned char)(15. * dg);
+          blue = (unsigned char)(15. * db);
+          gl2psPrintf("%x%x", green, blue);
+          icase = 1;
+        }
+      }
+      gl2psPrintf("\n");
+    }
+  }
+  else{ /* 8 bit for r and g and b */
+    nbyte = width * 3;
+    gl2psPrintf("/rgbstr %d string def\n", nbyte);
+    gl2psPrintf("%d %d %d\n", width, height, 8);
+    gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height);
+    gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n");
+    gl2psPrintf("false 3\n");
+    gl2psPrintf("colorimage\n");
+    for(row = 0; row < height; row++){
+      for(col = 0; col < width; col++){
+        gl2psGetRGB(im, col, row, &dr, &dg, &db);
+        red = (unsigned char)(255. * dr);
+        gl2psWriteByte(red);
+        green = (unsigned char)(255. * dg);
+        gl2psWriteByte(green);
+        blue = (unsigned char)(255. * db);
+        gl2psWriteByte(blue);
+      }
+      gl2psPrintf("\n");
+    }
+  }
+
+  gl2psPrintf("grestore\n");
+}
+
+static void gl2psPrintPostScriptImagemap(GLfloat x, GLfloat y,
+                                         GLsizei width, GLsizei height,
+                                         const unsigned char *imagemap){
+  int i, size;
+
+  if((width <= 0) || (height <= 0)) return;
+
+  size = height + height * (width - 1) / 8;
+
+  gl2psPrintf("gsave\n");
+  gl2psPrintf("%.2f %.2f translate\n", x, y);
+  gl2psPrintf("%d %d scale\n%d %d\ntrue\n", width, height,width, height);
+  gl2psPrintf("[ %d 0 0 -%d 0 %d ] {<", width, height);
+  for(i = 0; i < size; i++){
+    gl2psWriteByte(*imagemap);
+    imagemap++;
+  }
+  gl2psPrintf(">} imagemask\ngrestore\n");
+}
+
+static void gl2psPrintPostScriptHeader(void)
+{
+  time_t now;
+
+  /* Since compression is not part of the PostScript standard,
+     compressed PostScript files are just gzipped PostScript files
+     ("ps.gz" or "eps.gz") */
+  gl2psPrintGzipHeader();
+
+  time(&now);
+
+  if(gl2ps->format == GL2PS_PS){
+    gl2psPrintf("%%!PS-Adobe-3.0\n");
+  }
+  else{
+    gl2psPrintf("%%!PS-Adobe-3.0 EPSF-3.0\n");
+  }
+
+  gl2psPrintf("%%%%Title: %s\n"
+              "%%%%Creator: GL2PS %d.%d.%d%s, %s\n"
+              "%%%%For: %s\n"
+              "%%%%CreationDate: %s"
+              "%%%%LanguageLevel: 3\n"
+              "%%%%DocumentData: Clean7Bit\n"
+              "%%%%Pages: 1\n",
+              gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION,
+              GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT,
+              gl2ps->producer, ctime(&now));
+
+  if(gl2ps->format == GL2PS_PS){
+    gl2psPrintf("%%%%Orientation: %s\n"
+                "%%%%DocumentMedia: Default %d %d 0 () ()\n",
+                (gl2ps->options & GL2PS_LANDSCAPE) ? "Landscape" : "Portrait",
+                (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[3] :
+                (int)gl2ps->viewport[2],
+                (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[2] :
+                (int)gl2ps->viewport[3]);
+  }
+
+  gl2psPrintf("%%%%BoundingBox: %d %d %d %d\n"
+              "%%%%EndComments\n",
+              (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[1] :
+              (int)gl2ps->viewport[0],
+              (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[0] :
+              (int)gl2ps->viewport[1],
+              (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[3] :
+              (int)gl2ps->viewport[2],
+              (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[2] :
+              (int)gl2ps->viewport[3]);
+
+  /* RGB color: r g b C (replace C by G in output to change from rgb to gray)
+     Grayscale: r g b G
+     Font choose: size fontname FC
+     Text string: (string) x y size fontname S??
+     Rotated text string: (string) angle x y size fontname S??R
+     Point primitive: x y size P
+     Line width: width W
+     Line start: x y LS
+     Line joining last point: x y L
+     Line end: x y LE
+     Flat-shaded triangle: x3 y3 x2 y2 x1 y1 T
+     Smooth-shaded triangle: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 ST */
+
+  gl2psPrintf("%%%%BeginProlog\n"
+              "/gl2psdict 64 dict def gl2psdict begin\n"
+              "0 setlinecap 0 setlinejoin\n"
+              "/tryPS3shading %s def %% set to false to force subdivision\n"
+              "/rThreshold %g def %% red component subdivision threshold\n"
+              "/gThreshold %g def %% green component subdivision threshold\n"
+              "/bThreshold %g def %% blue component subdivision threshold\n",
+              (gl2ps->options & GL2PS_NO_PS3_SHADING) ? "false" : "true",
+              gl2ps->threshold[0], gl2ps->threshold[1], gl2ps->threshold[2]);
+
+  gl2psPrintf("/BD { bind def } bind def\n"
+              "/C  { setrgbcolor } BD\n"
+              "/G  { 0.082 mul exch 0.6094 mul add exch 0.3086 mul add neg 1.0 add setgray } BD\n"
+              "/W  { setlinewidth } BD\n");
+
+  gl2psPrintf("/FC { findfont exch /SH exch def SH scalefont setfont } BD\n"
+              "/SW { dup stringwidth pop } BD\n"
+              "/S  { FC moveto show } BD\n"
+              "/SBC{ FC moveto SW -2 div 0 rmoveto show } BD\n"
+              "/SBR{ FC moveto SW neg 0 rmoveto show } BD\n"
+              "/SCL{ FC moveto 0 SH -2 div rmoveto show } BD\n"
+              "/SCC{ FC moveto SW -2 div SH -2 div rmoveto show } BD\n"
+              "/SCR{ FC moveto SW neg SH -2 div rmoveto show } BD\n"
+              "/STL{ FC moveto 0 SH neg rmoveto show } BD\n"
+              "/STC{ FC moveto SW -2 div SH neg rmoveto show } BD\n"
+              "/STR{ FC moveto SW neg SH neg rmoveto show } BD\n");
+
+  /* rotated text routines: same nameanem with R appended */
+
+  gl2psPrintf("/FCT { FC translate 0 0 } BD\n"
+              "/SR  { gsave FCT moveto rotate show grestore } BD\n"
+              "/SBCR{ gsave FCT moveto rotate SW -2 div 0 rmoveto show grestore } BD\n"
+              "/SBRR{ gsave FCT moveto rotate SW neg 0 rmoveto show grestore } BD\n"
+              "/SCLR{ gsave FCT moveto rotate 0 SH -2 div rmoveto show grestore} BD\n");
+  gl2psPrintf("/SCCR{ gsave FCT moveto rotate SW -2 div SH -2 div rmoveto show grestore} BD\n"
+              "/SCRR{ gsave FCT moveto rotate SW neg SH -2 div rmoveto show grestore} BD\n"
+              "/STLR{ gsave FCT moveto rotate 0 SH neg rmoveto show grestore } BD\n"
+              "/STCR{ gsave FCT moveto rotate SW -2 div SH neg rmoveto show grestore } BD\n"
+              "/STRR{ gsave FCT moveto rotate SW neg SH neg rmoveto show grestore } BD\n");
+
+  gl2psPrintf("/P  { newpath 0.0 360.0 arc closepath fill } BD\n"
+              "/LS { newpath moveto } BD\n"
+              "/L  { lineto } BD\n"
+              "/LE { lineto stroke } BD\n"
+              "/T  { newpath moveto lineto lineto closepath fill } BD\n");
+
+  /* Smooth-shaded triangle with PostScript level 3 shfill operator:
+        x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STshfill */
+
+  gl2psPrintf("/STshfill {\n"
+              "      /b1 exch def /g1 exch def /r1 exch def /y1 exch def /x1 exch def\n"
+              "      /b2 exch def /g2 exch def /r2 exch def /y2 exch def /x2 exch def\n"
+              "      /b3 exch def /g3 exch def /r3 exch def /y3 exch def /x3 exch def\n"
+              "      gsave << /ShadingType 4 /ColorSpace [/DeviceRGB]\n"
+              "      /DataSource [ 0 x1 y1 r1 g1 b1 0 x2 y2 r2 g2 b2 0 x3 y3 r3 g3 b3 ] >>\n"
+              "      shfill grestore } BD\n");
+
+  /* Flat-shaded triangle with middle color:
+        x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 Tm */
+
+  gl2psPrintf(/* stack : x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 */
+              "/Tm { 3 -1 roll 8 -1 roll 13 -1 roll add add 3 div\n" /* r = (r1+r2+r3)/3 */
+              /* stack : x3 y3 g3 b3 x2 y2 g2 b2 x1 y1 g1 b1 r */
+              "      3 -1 roll 7 -1 roll 11 -1 roll add add 3 div\n" /* g = (g1+g2+g3)/3 */
+              /* stack : x3 y3 b3 x2 y2 b2 x1 y1 b1 r g b */
+              "      3 -1 roll 6 -1 roll 9 -1 roll add add 3 div" /* b = (b1+b2+b3)/3 */
+              /* stack : x3 y3 x2 y2 x1 y1 r g b */
+              " C T } BD\n");
+
+  /* Split triangle in four sub-triangles (at sides middle points) and call the
+     STnoshfill procedure on each, interpolating the colors in RGB space:
+        x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STsplit
+     (in procedure comments key: (Vi) = xi yi ri gi bi) */
+
+  gl2psPrintf("/STsplit {\n"
+              "      4 index 15 index add 0.5 mul\n" /* x13 = (x1+x3)/2 */
+              "      4 index 15 index add 0.5 mul\n" /* y13 = (y1+y3)/2 */
+              "      4 index 15 index add 0.5 mul\n" /* r13 = (r1+r3)/2 */
+              "      4 index 15 index add 0.5 mul\n" /* g13 = (g1+g3)/2 */
+              "      4 index 15 index add 0.5 mul\n" /* b13 = (b1+b3)/2 */
+              "      5 copy 5 copy 25 15 roll\n");
+
+  /* at his point, stack = (V3) (V13) (V13) (V13) (V2) (V1) */
+
+  gl2psPrintf("      9 index 30 index add 0.5 mul\n" /* x23 = (x2+x3)/2 */
+              "      9 index 30 index add 0.5 mul\n" /* y23 = (y2+y3)/2 */
+              "      9 index 30 index add 0.5 mul\n" /* r23 = (r2+r3)/2 */
+              "      9 index 30 index add 0.5 mul\n" /* g23 = (g2+g3)/2 */
+              "      9 index 30 index add 0.5 mul\n" /* b23 = (b2+b3)/2 */
+              "      5 copy 5 copy 35 5 roll 25 5 roll 15 5 roll\n");
+
+  /* stack = (V3) (V13) (V23) (V13) (V23) (V13) (V23) (V2) (V1) */
+
+  gl2psPrintf("      4 index 10 index add 0.5 mul\n" /* x12 = (x1+x2)/2 */
+              "      4 index 10 index add 0.5 mul\n" /* y12 = (y1+y2)/2 */
+              "      4 index 10 index add 0.5 mul\n" /* r12 = (r1+r2)/2 */
+              "      4 index 10 index add 0.5 mul\n" /* g12 = (g1+g2)/2 */
+              "      4 index 10 index add 0.5 mul\n" /* b12 = (b1+b2)/2 */
+              "      5 copy 5 copy 40 5 roll 25 5 roll 15 5 roll 25 5 roll\n");
+
+  /* stack = (V3) (V13) (V23) (V13) (V12) (V23) (V13) (V1) (V12) (V23) (V12) (V2) */
+
+  gl2psPrintf("      STnoshfill STnoshfill STnoshfill STnoshfill } BD\n");
+
+  /* Gouraud shaded triangle using recursive subdivision until the difference
+     between corner colors does not exceed the thresholds:
+        x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STnoshfill  */
+
+  gl2psPrintf("/STnoshfill {\n"
+              "      2 index 8 index sub abs rThreshold gt\n" /* |r1-r2|>rth */
+              "      { STsplit }\n"
+              "      { 1 index 7 index sub abs gThreshold gt\n" /* |g1-g2|>gth */
+              "        { STsplit }\n"
+              "        { dup 6 index sub abs bThreshold gt\n" /* |b1-b2|>bth */
+              "          { STsplit }\n"
+              "          { 2 index 13 index sub abs rThreshold gt\n" /* |r1-r3|>rht */
+              "            { STsplit }\n"
+              "            { 1 index 12 index sub abs gThreshold gt\n" /* |g1-g3|>gth */
+              "              { STsplit }\n"
+              "              { dup 11 index sub abs bThreshold gt\n" /* |b1-b3|>bth */
+              "                { STsplit }\n"
+              "                { 7 index 13 index sub abs rThreshold gt\n"); /* |r2-r3|>rht */
+  gl2psPrintf("                  { STsplit }\n"
+              "                  { 6 index 12 index sub abs gThreshold gt\n" /* |g2-g3|>gth */
+              "                    { STsplit }\n"
+              "                    { 5 index 11 index sub abs bThreshold gt\n" /* |b2-b3|>bth */
+              "                      { STsplit }\n"
+              "                      { Tm }\n" /* all colors sufficiently similar */
+              "                      ifelse }\n"
+              "                    ifelse }\n"
+              "                  ifelse }\n"
+              "                ifelse }\n"
+              "              ifelse }\n"
+              "            ifelse }\n"
+              "          ifelse }\n"
+              "        ifelse }\n"
+              "      ifelse } BD\n");
+
+  gl2psPrintf("tryPS3shading\n"
+              "{ /shfill where\n"
+              "  { /ST { STshfill } BD }\n"
+              "  { /ST { STnoshfill } BD }\n"
+              "  ifelse }\n"
+              "{ /ST { STnoshfill } BD }\n"
+              "ifelse\n");
+
+  gl2psPrintf("end\n"
+              "%%%%EndProlog\n"
+              "%%%%BeginSetup\n"
+              "/DeviceRGB setcolorspace\n"
+              "gl2psdict begin\n"
+              "%%%%EndSetup\n"
+              "%%%%Page: 1 1\n"
+              "%%%%BeginPageSetup\n");
+
+  if(gl2ps->options & GL2PS_LANDSCAPE){
+    gl2psPrintf("%d 0 translate 90 rotate\n",
+                (int)gl2ps->viewport[3]);
+  }
+
+  gl2psPrintf("%%%%EndPageSetup\n"
+              "mark\n"
+              "gsave\n"
+              "1.0 1.0 scale\n");
+
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    gl2psPrintf("%g %g %g C\n"
+                "newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n"
+                "closepath fill\n",
+                gl2ps->bgcolor[0], gl2ps->bgcolor[1], gl2ps->bgcolor[2],
+                (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2],
+                (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3],
+                (int)gl2ps->viewport[0], (int)gl2ps->viewport[3]);
+  }
+}
+
+static void gl2psPrintPostScriptColor(GL2PSrgba rgba)
+{
+  if(!gl2psSameColor(gl2ps->lastrgba, rgba)){
+    gl2psSetLastColor(rgba);
+    gl2psPrintf("%g %g %g C\n", rgba[0], rgba[1], rgba[2]);
+  }
+}
+
+static void gl2psResetPostScriptColor(void)
+{
+  gl2ps->lastrgba[0] = gl2ps->lastrgba[1] = gl2ps->lastrgba[2] = -1.;
+}
+
+static void gl2psEndPostScriptLine(void)
+{
+  int i;
+  if(gl2ps->lastvertex.rgba[0] >= 0.){
+    gl2psPrintf("%g %g LE\n", gl2ps->lastvertex.xyz[0], gl2ps->lastvertex.xyz[1]);
+    for(i = 0; i < 3; i++)
+      gl2ps->lastvertex.xyz[i] = -1.;
+    for(i = 0; i < 4; i++)
+      gl2ps->lastvertex.rgba[i] = -1.;
+  }
+}
+
+static void gl2psParseStipplePattern(GLushort pattern, GLint factor,
+                                     int *nb, int array[10])
+{
+  int i, n;
+  int on[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+  int off[8] = {0, 0, 0, 0, 0, 0, 0, 0};
+  char tmp[16];
+
+  /* extract the 16 bits from the OpenGL stipple pattern */
+  for(n = 15; n >= 0; n--){
+    tmp[n] = (char)(pattern & 0x01);
+    pattern >>= 1;
+  }
+  /* compute the on/off pixel sequence */
+  n = 0;
+  for(i = 0; i < 8; i++){
+    while(n < 16 && !tmp[n]){ off[i]++; n++; }
+    while(n < 16 && tmp[n]){ on[i]++; n++; }
+    if(n >= 15){ i++; break; }
+  }
+
+  /* store the on/off array from right to left, starting with off
+     pixels. The PostScript specification allows for at most 11
+     elements in the on/off array, so we limit ourselves to 5 on/off
+     couples (our longest possible array is thus [on4 off4 on3 off3
+     on2 off2 on1 off1 on0 off0]) */
+  *nb = 0;
+  for(n = i - 1; n >= 0; n--){
+    array[(*nb)++] = factor * on[n];
+    array[(*nb)++] = factor * off[n];
+    if(*nb == 10) break;
+  }
+}
+
+static int gl2psPrintPostScriptDash(GLushort pattern, GLint factor, const char *str)
+{
+  int len = 0, i, n, array[10];
+
+  if(pattern == gl2ps->lastpattern && factor == gl2ps->lastfactor)
+    return 0;
+
+  gl2ps->lastpattern = pattern;
+  gl2ps->lastfactor = factor;
+
+  if(!pattern || !factor){
+    /* solid line */
+    len += gl2psPrintf("[] 0 %s\n", str);
+  }
+  else{
+    gl2psParseStipplePattern(pattern, factor, &n, array);
+    len += gl2psPrintf("[");
+    for(i = 0; i < n; i++){
+      if(i) len += gl2psPrintf(" ");
+      len += gl2psPrintf("%d", array[i]);
+    }
+    len += gl2psPrintf("] 0 %s\n", str);
+  }
+
+  return len;
+}
+
+static void gl2psPrintPostScriptPrimitive(void *data)
+{
+  int newline;
+  GL2PSprimitive *prim;
+
+  prim = *(GL2PSprimitive**)data;
+
+  if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return;
+
+  /* Every effort is made to draw lines as connected segments (i.e.,
+     using a single PostScript path): this is the only way to get nice
+     line joins and to not restart the stippling for every line
+     segment. So if the primitive to print is not a line we must first
+     finish the current line (if any): */
+  if(prim->type != GL2PS_LINE) gl2psEndPostScriptLine();
+
+  switch(prim->type){
+  case GL2PS_POINT :
+    gl2psPrintPostScriptColor(prim->verts[0].rgba);
+    gl2psPrintf("%g %g %g P\n",
+                prim->verts[0].xyz[0], prim->verts[0].xyz[1], 0.5 * prim->width);
+    break;
+  case GL2PS_LINE :
+    if(!gl2psSamePosition(gl2ps->lastvertex.xyz, prim->verts[0].xyz) ||
+       !gl2psSameColor(gl2ps->lastrgba, prim->verts[0].rgba) ||
+       gl2ps->lastlinewidth != prim->width ||
+       gl2ps->lastpattern != prim->pattern ||
+       gl2ps->lastfactor != prim->factor){
+      /* End the current line if the new segment does not start where
+         the last one ended, or if the color, the width or the
+         stippling have changed (multi-stroking lines with changing
+         colors is necessary until we use /shfill for lines;
+         unfortunately this means that at the moment we can screw up
+         line stippling for smooth-shaded lines) */
+      gl2psEndPostScriptLine();
+      newline = 1;
+    }
+    else{
+      newline = 0;
+    }
+    if(gl2ps->lastlinewidth != prim->width){
+      gl2ps->lastlinewidth = prim->width;
+      gl2psPrintf("%g W\n", gl2ps->lastlinewidth);
+    }
+    gl2psPrintPostScriptDash(prim->pattern, prim->factor, "setdash");
+    gl2psPrintPostScriptColor(prim->verts[0].rgba);
+    gl2psPrintf("%g %g %s\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1],
+                newline ? "LS" : "L");
+    gl2ps->lastvertex = prim->verts[1];
+    break;
+  case GL2PS_TRIANGLE :
+    if(!gl2psVertsSameColor(prim)){
+      gl2psResetPostScriptColor();
+      gl2psPrintf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g ST\n",
+                  prim->verts[2].xyz[0], prim->verts[2].xyz[1],
+                  prim->verts[2].rgba[0], prim->verts[2].rgba[1],
+                  prim->verts[2].rgba[2], prim->verts[1].xyz[0],
+                  prim->verts[1].xyz[1], prim->verts[1].rgba[0],
+                  prim->verts[1].rgba[1], prim->verts[1].rgba[2],
+                  prim->verts[0].xyz[0], prim->verts[0].xyz[1],
+                  prim->verts[0].rgba[0], prim->verts[0].rgba[1],
+                  prim->verts[0].rgba[2]);
+    }
+    else{
+      gl2psPrintPostScriptColor(prim->verts[0].rgba);
+      gl2psPrintf("%g %g %g %g %g %g T\n",
+                  prim->verts[2].xyz[0], prim->verts[2].xyz[1],
+                  prim->verts[1].xyz[0], prim->verts[1].xyz[1],
+                  prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+    }
+    break;
+  case GL2PS_QUADRANGLE :
+    gl2psMsg(GL2PS_WARNING, "There should not be any quad left to print");
+    break;
+  case GL2PS_PIXMAP :
+    gl2psPrintPostScriptPixmap(prim->verts[0].xyz[0], prim->verts[0].xyz[1],
+                               prim->data.image);
+    break;
+  case GL2PS_IMAGEMAP :
+    if(prim->data.image->type != GL2PS_IMAGEMAP_WRITTEN){
+      gl2psPrintPostScriptColor(prim->verts[0].rgba);
+      gl2psPrintPostScriptImagemap(prim->data.image->pixels[0],
+                                   prim->data.image->pixels[1],
+                                   prim->data.image->width, prim->data.image->height,
+                                   (const unsigned char*)(&(prim->data.image->pixels[2])));
+      prim->data.image->type = GL2PS_IMAGEMAP_WRITTEN;
+    }
+    break;
+  case GL2PS_TEXT :
+    gl2psPrintPostScriptColor(prim->verts[0].rgba);
+    gl2psPrintf("(%s) ", prim->data.text->str);
+    if(prim->data.text->angle)
+      gl2psPrintf("%g ", prim->data.text->angle);
+    gl2psPrintf("%g %g %d /%s ",
+                prim->verts[0].xyz[0], prim->verts[0].xyz[1],
+                prim->data.text->fontsize, prim->data.text->fontname);
+    switch(prim->data.text->alignment){
+    case GL2PS_TEXT_C:
+      gl2psPrintf(prim->data.text->angle ? "SCCR\n" : "SCC\n");
+      break;
+    case GL2PS_TEXT_CL:
+      gl2psPrintf(prim->data.text->angle ? "SCLR\n" : "SCL\n");
+      break;
+    case GL2PS_TEXT_CR:
+      gl2psPrintf(prim->data.text->angle ? "SCRR\n" : "SCR\n");
+      break;
+    case GL2PS_TEXT_B:
+      gl2psPrintf(prim->data.text->angle ? "SBCR\n" : "SBC\n");
+      break;
+    case GL2PS_TEXT_BR:
+      gl2psPrintf(prim->data.text->angle ? "SBRR\n" : "SBR\n");
+      break;
+    case GL2PS_TEXT_T:
+      gl2psPrintf(prim->data.text->angle ? "STCR\n" : "STC\n");
+      break;
+    case GL2PS_TEXT_TL:
+      gl2psPrintf(prim->data.text->angle ? "STLR\n" : "STL\n");
+      break;
+    case GL2PS_TEXT_TR:
+      gl2psPrintf(prim->data.text->angle ? "STRR\n" : "STR\n");
+      break;
+    case GL2PS_TEXT_BL:
+    default:
+      gl2psPrintf(prim->data.text->angle ? "SR\n" : "S\n");
+      break;
+    }
+    break;
+  case GL2PS_SPECIAL :
+    /* alignment contains the format for which the special output text
+       is intended */
+    if(prim->data.text->alignment == GL2PS_PS ||
+       prim->data.text->alignment == GL2PS_EPS)
+      gl2psPrintf("%s\n", prim->data.text->str);
+    break;
+  default :
+    break;
+  }
+}
+
+static void gl2psPrintPostScriptFooter(void)
+{
+  gl2psPrintf("grestore\n"
+              "showpage\n"
+              "cleartomark\n"
+              "%%%%PageTrailer\n"
+              "%%%%Trailer\n"
+              "end\n"
+              "%%%%EOF\n");
+
+  gl2psPrintGzipFooter();
+}
+
+static void gl2psPrintPostScriptBeginViewport(GLint viewport[4])
+{
+  GLint idx;
+  GLfloat rgba[4];
+  int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3];
+
+  glRenderMode(GL_FEEDBACK);
+
+  if(gl2ps->header){
+    gl2psPrintPostScriptHeader();
+    gl2ps->header = GL_FALSE;
+  }
+
+  gl2psPrintf("gsave\n"
+              "1.0 1.0 scale\n");
+
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){
+      glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba);
+    }
+    else{
+      glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx);
+      rgba[0] = gl2ps->colormap[idx][0];
+      rgba[1] = gl2ps->colormap[idx][1];
+      rgba[2] = gl2ps->colormap[idx][2];
+      rgba[3] = 1.0F;
+    }
+    gl2psPrintf("%g %g %g C\n"
+                "newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n"
+                "closepath fill\n",
+                rgba[0], rgba[1], rgba[2],
+                x, y, x+w, y, x+w, y+h, x, y+h);
+  }
+
+  gl2psPrintf("newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n"
+              "closepath clip\n",
+              x, y, x+w, y, x+w, y+h, x, y+h);
+
+}
+
+static GLint gl2psPrintPostScriptEndViewport(void)
+{
+  GLint res;
+
+  res = gl2psPrintPrimitives();
+  gl2psPrintf("grestore\n");
+  return res;
+}
+
+static void gl2psPrintPostScriptFinalPrimitive(void)
+{
+  /* End any remaining line, if any */
+  gl2psEndPostScriptLine();
+}
+
+/* definition of the PostScript and Encapsulated PostScript backends */
+
+static GL2PSbackend gl2psPS = {
+  gl2psPrintPostScriptHeader,
+  gl2psPrintPostScriptFooter,
+  gl2psPrintPostScriptBeginViewport,
+  gl2psPrintPostScriptEndViewport,
+  gl2psPrintPostScriptPrimitive,
+  gl2psPrintPostScriptFinalPrimitive,
+  "ps",
+  "Postscript"
+};
+
+static GL2PSbackend gl2psEPS = {
+  gl2psPrintPostScriptHeader,
+  gl2psPrintPostScriptFooter,
+  gl2psPrintPostScriptBeginViewport,
+  gl2psPrintPostScriptEndViewport,
+  gl2psPrintPostScriptPrimitive,
+  gl2psPrintPostScriptFinalPrimitive,
+  "eps",
+  "Encapsulated Postscript"
+};
+
+/*********************************************************************
+ *
+ * LaTeX routines
+ *
+ *********************************************************************/
+
+static void gl2psPrintTeXHeader(void)
+{
+  char name[256];
+  time_t now;
+  int i;
+
+  if(gl2ps->filename && strlen(gl2ps->filename) < 256){
+    for(i = (int)strlen(gl2ps->filename) - 1; i >= 0; i--){
+      if(gl2ps->filename[i] == '.'){
+        strncpy(name, gl2ps->filename, i);
+        name[i] = '\0';
+        break;
+      }
+    }
+    if(i <= 0) strcpy(name, gl2ps->filename);
+  }
+  else{
+    strcpy(name, "untitled");
+  }
+
+  time(&now);
+
+  fprintf(gl2ps->stream,
+          "%% Title: %s\n"
+          "%% Creator: GL2PS %d.%d.%d%s, %s\n"
+          "%% For: %s\n"
+          "%% CreationDate: %s",
+          gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION,
+          GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT,
+          gl2ps->producer, ctime(&now));
+
+  fprintf(gl2ps->stream,
+          "\\setlength{\\unitlength}{1pt}\n"
+          "\\begin{picture}(0,0)\n"
+          "\\includegraphics{%s}\n"
+          "\\end{picture}%%\n"
+          "%s\\begin{picture}(%d,%d)(0,0)\n",
+          name, (gl2ps->options & GL2PS_LANDSCAPE) ? "\\rotatebox{90}{" : "",
+          (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]);
+}
+
+static void gl2psPrintTeXPrimitive(void *data)
+{
+  GL2PSprimitive *prim;
+
+  prim = *(GL2PSprimitive**)data;
+
+  switch(prim->type){
+  case GL2PS_TEXT :
+    fprintf(gl2ps->stream, "\\fontsize{%d}{0}\n\\selectfont",
+            prim->data.text->fontsize);
+    fprintf(gl2ps->stream, "\\put(%g,%g)",
+            prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+    if(prim->data.text->angle)
+      fprintf(gl2ps->stream, "{\\rotatebox{%g}", prim->data.text->angle);
+    fprintf(gl2ps->stream, "{\\makebox(0,0)");
+    switch(prim->data.text->alignment){
+    case GL2PS_TEXT_C:
+      fprintf(gl2ps->stream, "{");
+      break;
+    case GL2PS_TEXT_CL:
+      fprintf(gl2ps->stream, "[l]{");
+      break;
+    case GL2PS_TEXT_CR:
+      fprintf(gl2ps->stream, "[r]{");
+      break;
+    case GL2PS_TEXT_B:
+      fprintf(gl2ps->stream, "[b]{");
+      break;
+    case GL2PS_TEXT_BR:
+      fprintf(gl2ps->stream, "[br]{");
+      break;
+    case GL2PS_TEXT_T:
+      fprintf(gl2ps->stream, "[t]{");
+      break;
+    case GL2PS_TEXT_TL:
+      fprintf(gl2ps->stream, "[tl]{");
+      break;
+    case GL2PS_TEXT_TR:
+      fprintf(gl2ps->stream, "[tr]{");
+      break;
+    case GL2PS_TEXT_BL:
+    default:
+      fprintf(gl2ps->stream, "[bl]{");
+      break;
+    }
+    fprintf(gl2ps->stream, "\\textcolor[rgb]{%g,%g,%g}{{%s}}",
+            prim->verts[0].rgba[0], prim->verts[0].rgba[1], prim->verts[0].rgba[2],
+            prim->data.text->str);
+    if(prim->data.text->angle)
+      fprintf(gl2ps->stream, "}");
+    fprintf(gl2ps->stream, "}}\n");
+    break;
+  case GL2PS_SPECIAL :
+    /* alignment contains the format for which the special output text
+       is intended */
+    if (prim->data.text->alignment == GL2PS_TEX)
+      fprintf(gl2ps->stream, "%s\n", prim->data.text->str);
+    break;
+  default :
+    break;
+  }
+}
+
+static void gl2psPrintTeXFooter(void)
+{
+  fprintf(gl2ps->stream, "\\end{picture}%s\n",
+          (gl2ps->options & GL2PS_LANDSCAPE) ? "}" : "");
+}
+
+static void gl2psPrintTeXBeginViewport(GLint viewport[4])
+{
+  (void) viewport;  /* not used */
+  glRenderMode(GL_FEEDBACK);
+
+  if(gl2ps->header){
+    gl2psPrintTeXHeader();
+    gl2ps->header = GL_FALSE;
+  }
+}
+
+static GLint gl2psPrintTeXEndViewport(void)
+{
+  return gl2psPrintPrimitives();
+}
+
+static void gl2psPrintTeXFinalPrimitive(void)
+{
+}
+
+/* definition of the LaTeX backend */
+
+static GL2PSbackend gl2psTEX = {
+  gl2psPrintTeXHeader,
+  gl2psPrintTeXFooter,
+  gl2psPrintTeXBeginViewport,
+  gl2psPrintTeXEndViewport,
+  gl2psPrintTeXPrimitive,
+  gl2psPrintTeXFinalPrimitive,
+  "tex",
+  "LaTeX text"
+};
+
+/*********************************************************************
+ *
+ * PDF routines
+ *
+ *********************************************************************/
+
+static int gl2psPrintPDFCompressorType(void)
+{
+#if defined(GL2PS_HAVE_ZLIB)
+  if(gl2ps->options & GL2PS_COMPRESS){
+    return fprintf(gl2ps->stream, "/Filter [/FlateDecode]\n");
+  }
+#endif
+  return 0;
+}
+
+static int gl2psPrintPDFStrokeColor(GL2PSrgba rgba)
+{
+  int i, offs = 0;
+
+  gl2psSetLastColor(rgba);
+  for(i = 0; i < 3; ++i){
+    if(GL2PS_ZERO(rgba[i]))
+      offs += gl2psPrintf("%.0f ", 0.);
+    else if(rgba[i] < 1e-4 || rgba[i] > 1e6) /* avoid %e formatting */
+      offs += gl2psPrintf("%f ", rgba[i]);
+    else
+      offs += gl2psPrintf("%g ", rgba[i]);
+  }
+  offs += gl2psPrintf("RG\n");
+  return offs;
+}
+
+static int gl2psPrintPDFFillColor(GL2PSrgba rgba)
+{
+  int i, offs = 0;
+
+  for(i = 0; i < 3; ++i){
+    if(GL2PS_ZERO(rgba[i]))
+      offs += gl2psPrintf("%.0f ", 0.);
+    else if(rgba[i] < 1e-4 || rgba[i] > 1e6) /* avoid %e formatting */
+      offs += gl2psPrintf("%f ", rgba[i]);
+    else
+      offs += gl2psPrintf("%g ", rgba[i]);
+  }
+  offs += gl2psPrintf("rg\n");
+  return offs;
+}
+
+static int gl2psPrintPDFLineWidth(GLfloat lw)
+{
+  if(GL2PS_ZERO(lw))
+    return gl2psPrintf("%.0f w\n", 0.);
+  else if(lw < 1e-4 || lw > 1e6) /* avoid %e formatting */
+    return gl2psPrintf("%f w\n", lw);
+  else
+    return gl2psPrintf("%g w\n", lw);
+}
+
+static void gl2psPutPDFText(GL2PSstring *text, int cnt, GLfloat x, GLfloat y)
+{
+  GLfloat rad, crad, srad;
+
+  if(text->angle == 0.0F){
+    gl2ps->streamlength += gl2psPrintf
+      ("BT\n"
+       "/F%d %d Tf\n"
+       "%f %f Td\n"
+       "(%s) Tj\n"
+       "ET\n",
+       cnt, text->fontsize, x, y, text->str);
+  }
+  else{
+    rad = (GLfloat)(3.141593F * text->angle / 180.0F);
+    srad = (GLfloat)sin(rad);
+    crad = (GLfloat)cos(rad);
+    gl2ps->streamlength += gl2psPrintf
+      ("BT\n"
+       "/F%d %d Tf\n"
+       "%f %f %f %f %f %f Tm\n"
+       "(%s) Tj\n"
+       "ET\n",
+       cnt, text->fontsize, crad, srad, -srad, crad, x, y, text->str);
+  }
+}
+
+static void gl2psPutPDFSpecial(GL2PSstring *text)
+{
+  gl2ps->streamlength += gl2psPrintf("%s\n", text->str);
+}
+
+static void gl2psPutPDFImage(GL2PSimage *image, int cnt, GLfloat x, GLfloat y)
+{
+  gl2ps->streamlength += gl2psPrintf
+    ("q\n"
+     "%d 0 0 %d %f %f cm\n"
+     "/Im%d Do\n"
+     "Q\n",
+     (int)image->width, (int)image->height, x, y, cnt);
+}
+
+static void gl2psPDFstacksInit(void)
+{
+  gl2ps->objects_stack = 7 /* FIXED_XREF_ENTRIES */ + 1;
+  gl2ps->extgs_stack = 0;
+  gl2ps->font_stack = 0;
+  gl2ps->im_stack = 0;
+  gl2ps->trgroupobjects_stack = 0;
+  gl2ps->shader_stack = 0;
+  gl2ps->mshader_stack = 0;
+}
+
+static void gl2psPDFgroupObjectInit(GL2PSpdfgroup *gro)
+{
+  if(!gro)
+    return;
+
+  gro->ptrlist = NULL;
+  gro->fontno = gro->gsno = gro->imno = gro->maskshno = gro->shno
+    = gro->trgroupno = gro->fontobjno = gro->imobjno = gro->shobjno
+    = gro->maskshobjno = gro->gsobjno = gro->trgroupobjno = -1;
+}
+
+/* Build up group objects and assign name and object numbers */
+
+static void gl2psPDFgroupListInit(void)
+{
+  int i;
+  GL2PSprimitive *p = NULL;
+  GL2PSpdfgroup gro;
+  int lasttype = GL2PS_NO_TYPE;
+  GL2PSrgba lastrgba = {-1.0F, -1.0F, -1.0F, -1.0F};
+  GLushort lastpattern = 0;
+  GLint lastfactor = 0;
+  GLfloat lastwidth = 1;
+  GL2PStriangle lastt, tmpt;
+  int lastTriangleWasNotSimpleWithSameColor = 0;
+
+  if(!gl2ps->pdfprimlist)
+    return;
+
+  gl2ps->pdfgrouplist = gl2psListCreate(500, 500, sizeof(GL2PSpdfgroup));
+  gl2psInitTriangle(&lastt);
+
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfprimlist); ++i){
+    p = *(GL2PSprimitive**)gl2psListPointer(gl2ps->pdfprimlist, i);
+    switch(p->type){
+    case GL2PS_PIXMAP:
+      gl2psPDFgroupObjectInit(&gro);
+      gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+      gro.imno = gl2ps->im_stack++;
+      gl2psListAdd(gro.ptrlist, &p);
+      gl2psListAdd(gl2ps->pdfgrouplist, &gro);
+      break;
+    case GL2PS_TEXT:
+      gl2psPDFgroupObjectInit(&gro);
+      gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+      gro.fontno = gl2ps->font_stack++;
+      gl2psListAdd(gro.ptrlist, &p);
+      gl2psListAdd(gl2ps->pdfgrouplist, &gro);
+      break;
+    case GL2PS_LINE:
+      if(lasttype != p->type || lastwidth != p->width ||
+         lastpattern != p->pattern || lastfactor != p->factor ||
+         !gl2psSameColor(p->verts[0].rgba, lastrgba)){
+        gl2psPDFgroupObjectInit(&gro);
+        gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+        gl2psListAdd(gro.ptrlist, &p);
+        gl2psListAdd(gl2ps->pdfgrouplist, &gro);
+      }
+      else{
+        gl2psListAdd(gro.ptrlist, &p);
+      }
+      lastpattern = p->pattern;
+      lastfactor = p->factor;
+      lastwidth = p->width;
+      lastrgba[0] = p->verts[0].rgba[0];
+      lastrgba[1] = p->verts[0].rgba[1];
+      lastrgba[2] = p->verts[0].rgba[2];
+      break;
+    case GL2PS_POINT:
+      if(lasttype != p->type || lastwidth != p->width ||
+         !gl2psSameColor(p->verts[0].rgba, lastrgba)){
+        gl2psPDFgroupObjectInit(&gro);
+        gro.ptrlist = gl2psListCreate(1,2,sizeof(GL2PSprimitive*));
+        gl2psListAdd(gro.ptrlist, &p);
+        gl2psListAdd(gl2ps->pdfgrouplist, &gro);
+      }
+      else{
+        gl2psListAdd(gro.ptrlist, &p);
+      }
+      lastwidth = p->width;
+      lastrgba[0] = p->verts[0].rgba[0];
+      lastrgba[1] = p->verts[0].rgba[1];
+      lastrgba[2] = p->verts[0].rgba[2];
+      break;
+    case GL2PS_TRIANGLE:
+      gl2psFillTriangleFromPrimitive(&tmpt, p, GL_TRUE);
+      lastTriangleWasNotSimpleWithSameColor =
+        !(tmpt.prop & T_CONST_COLOR && tmpt.prop & T_ALPHA_1) ||
+        !gl2psSameColor(tmpt.vertex[0].rgba, lastt.vertex[0].rgba);
+      if(lasttype == p->type && tmpt.prop == lastt.prop &&
+         lastTriangleWasNotSimpleWithSameColor){
+        /* TODO Check here for last alpha */
+        gl2psListAdd(gro.ptrlist, &p);
+      }
+      else{
+        gl2psPDFgroupObjectInit(&gro);
+        gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+        gl2psListAdd(gro.ptrlist, &p);
+        gl2psListAdd(gl2ps->pdfgrouplist, &gro);
+      }
+      lastt = tmpt;
+      break;
+    case GL2PS_SPECIAL:
+      gl2psPDFgroupObjectInit(&gro);
+      gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*));
+      gl2psListAdd(gro.ptrlist, &p);
+      gl2psListAdd(gl2ps->pdfgrouplist, &gro);
+      break;
+    default:
+      break;
+    }
+    lasttype = p->type;
+  }
+}
+
+static void gl2psSortOutTrianglePDFgroup(GL2PSpdfgroup *gro)
+{
+  GL2PStriangle t;
+  GL2PSprimitive *prim = NULL;
+
+  if(!gro)
+    return;
+
+  if(!gl2psListNbr(gro->ptrlist))
+    return;
+
+  prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0);
+
+  if(prim->type != GL2PS_TRIANGLE)
+    return;
+
+  gl2psFillTriangleFromPrimitive(&t, prim, GL_TRUE);
+
+  if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_LESS_1){
+    gro->gsno = gl2ps->extgs_stack++;
+    gro->gsobjno = gl2ps->objects_stack ++;
+  }
+  else if(t.prop & T_CONST_COLOR && t.prop & T_VAR_ALPHA){
+    gro->gsno = gl2ps->extgs_stack++;
+    gro->gsobjno = gl2ps->objects_stack++;
+    gro->trgroupno = gl2ps->trgroupobjects_stack++;
+    gro->trgroupobjno = gl2ps->objects_stack++;
+    gro->maskshno = gl2ps->mshader_stack++;
+    gro->maskshobjno = gl2ps->objects_stack++;
+  }
+  else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_1){
+    gro->shno = gl2ps->shader_stack++;
+    gro->shobjno = gl2ps->objects_stack++;
+  }
+  else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_LESS_1){
+    gro->gsno = gl2ps->extgs_stack++;
+    gro->gsobjno = gl2ps->objects_stack++;
+    gro->shno = gl2ps->shader_stack++;
+    gro->shobjno = gl2ps->objects_stack++;
+  }
+  else if(t.prop & T_VAR_COLOR && t.prop & T_VAR_ALPHA){
+    gro->gsno = gl2ps->extgs_stack++;
+    gro->gsobjno = gl2ps->objects_stack++;
+    gro->shno = gl2ps->shader_stack++;
+    gro->shobjno = gl2ps->objects_stack++;
+    gro->trgroupno = gl2ps->trgroupobjects_stack++;
+    gro->trgroupobjno = gl2ps->objects_stack++;
+    gro->maskshno = gl2ps->mshader_stack++;
+    gro->maskshobjno = gl2ps->objects_stack++;
+  }
+}
+
+/* Main stream data */
+
+static void gl2psPDFgroupListWriteMainStream(void)
+{
+  int i, j, lastel;
+  GL2PSprimitive *prim = NULL, *prev = NULL;
+  GL2PSpdfgroup *gro;
+  GL2PStriangle t;
+
+  if(!gl2ps->pdfgrouplist)
+    return;
+
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i);
+
+    lastel = gl2psListNbr(gro->ptrlist) - 1;
+    if(lastel < 0)
+      continue;
+
+    prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0);
+
+    switch(prim->type){
+    case GL2PS_POINT:
+      gl2ps->streamlength += gl2psPrintf("1 J\n");
+      gl2ps->streamlength += gl2psPrintPDFLineWidth(prim->width);
+      gl2ps->streamlength += gl2psPrintPDFStrokeColor(prim->verts[0].rgba);
+      for(j = 0; j <= lastel; ++j){
+        prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+        gl2ps->streamlength +=
+          gl2psPrintf("%f %f m %f %f l\n",
+                      prim->verts[0].xyz[0], prim->verts[0].xyz[1],
+                      prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+      }
+      gl2ps->streamlength += gl2psPrintf("S\n");
+      gl2ps->streamlength += gl2psPrintf("0 J\n");
+      break;
+    case GL2PS_LINE:
+      /* We try to use as few paths as possible to draw lines, in
+         order to get nice stippling even when the individual segments
+         are smaller than the stipple */
+      gl2ps->streamlength += gl2psPrintPDFLineWidth(prim->width);
+      gl2ps->streamlength += gl2psPrintPDFStrokeColor(prim->verts[0].rgba);
+      gl2ps->streamlength += gl2psPrintPostScriptDash(prim->pattern, prim->factor, "d");
+      /* start new path */
+      gl2ps->streamlength +=
+        gl2psPrintf("%f %f m\n",
+                    prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+
+      for(j = 1; j <= lastel; ++j){
+        prev = prim;
+        prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+        if(!gl2psSamePosition(prim->verts[0].xyz, prev->verts[1].xyz)){
+          /* the starting point of the new segment does not match the
+             end point of the previous line, so we end the current
+             path and start a new one */
+          gl2ps->streamlength +=
+            gl2psPrintf("%f %f l\n",
+                        prev->verts[1].xyz[0], prev->verts[1].xyz[1]);
+          gl2ps->streamlength +=
+            gl2psPrintf("%f %f m\n",
+                        prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+        }
+        else{
+          /* the two segements are connected, so we just append to the
+             current path */
+          gl2ps->streamlength +=
+            gl2psPrintf("%f %f l\n",
+                        prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+        }
+      }
+      /* end last path */
+      gl2ps->streamlength +=
+        gl2psPrintf("%f %f l\n",
+                    prim->verts[1].xyz[0], prim->verts[1].xyz[1]);
+      gl2ps->streamlength += gl2psPrintf("S\n");
+      break;
+    case GL2PS_TRIANGLE:
+      gl2psFillTriangleFromPrimitive(&t, prim, GL_TRUE);
+      gl2psSortOutTrianglePDFgroup(gro);
+
+      /* No alpha and const color: Simple PDF draw orders  */
+      if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_1){
+        gl2ps->streamlength += gl2psPrintPDFFillColor(t.vertex[0].rgba);
+        for(j = 0; j <= lastel; ++j){
+          prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+          gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE);
+          gl2ps->streamlength
+            += gl2psPrintf("%f %f m\n"
+                           "%f %f l\n"
+                           "%f %f l\n"
+                           "h f\n",
+                           t.vertex[0].xyz[0], t.vertex[0].xyz[1],
+                           t.vertex[1].xyz[0], t.vertex[1].xyz[1],
+                           t.vertex[2].xyz[0], t.vertex[2].xyz[1]);
+        }
+      }
+      /* Const alpha < 1 and const color: Simple PDF draw orders
+         and an extra extended Graphics State for the alpha const */
+      else if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_LESS_1){
+        gl2ps->streamlength += gl2psPrintf("q\n"
+                                           "/GS%d gs\n",
+                                           gro->gsno);
+        gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba);
+        for(j = 0; j <= lastel; ++j){
+          prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+          gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE);
+          gl2ps->streamlength
+            += gl2psPrintf("%f %f m\n"
+                           "%f %f l\n"
+                           "%f %f l\n"
+                           "h f\n",
+                           t.vertex[0].xyz[0], t.vertex[0].xyz[1],
+                           t.vertex[1].xyz[0], t.vertex[1].xyz[1],
+                           t.vertex[2].xyz[0], t.vertex[2].xyz[1]);
+        }
+        gl2ps->streamlength += gl2psPrintf("Q\n");
+      }
+      /* Variable alpha and const color: Simple PDF draw orders
+         and an extra extended Graphics State + Xobject + Shader
+         object for the alpha mask */
+      else if(t.prop & T_CONST_COLOR && t.prop & T_VAR_ALPHA){
+        gl2ps->streamlength += gl2psPrintf("q\n"
+                                           "/GS%d gs\n"
+                                           "/TrG%d Do\n",
+                                           gro->gsno, gro->trgroupno);
+        gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba);
+        for(j = 0; j <= lastel; ++j){
+          prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+          gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE);
+          gl2ps->streamlength
+            += gl2psPrintf("%f %f m\n"
+                           "%f %f l\n"
+                           "%f %f l\n"
+                           "h f\n",
+                           t.vertex[0].xyz[0], t.vertex[0].xyz[1],
+                           t.vertex[1].xyz[0], t.vertex[1].xyz[1],
+                           t.vertex[2].xyz[0], t.vertex[2].xyz[1]);
+        }
+        gl2ps->streamlength += gl2psPrintf("Q\n");
+      }
+      /* Variable color and no alpha: Shader Object for the colored
+         triangle(s) */
+      else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_1){
+        gl2ps->streamlength += gl2psPrintf("/Sh%d sh\n", gro->shno);
+      }
+      /* Variable color and const alpha < 1: Shader Object for the
+         colored triangle(s) and an extra extended Graphics State
+         for the alpha const */
+      else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_LESS_1){
+        gl2ps->streamlength += gl2psPrintf("q\n"
+                                           "/GS%d gs\n"
+                                           "/Sh%d sh\n"
+                                           "Q\n",
+                                           gro->gsno, gro->shno);
+      }
+      /* Variable alpha and color: Shader Object for the colored
+         triangle(s) and an extra extended Graphics State
+         + Xobject + Shader object for the alpha mask */
+      else if(t.prop & T_VAR_COLOR && t.prop & T_VAR_ALPHA){
+        gl2ps->streamlength += gl2psPrintf("q\n"
+                                           "/GS%d gs\n"
+                                           "/TrG%d Do\n"
+                                           "/Sh%d sh\n"
+                                           "Q\n",
+                                           gro->gsno, gro->trgroupno, gro->shno);
+      }
+      break;
+    case GL2PS_PIXMAP:
+      for(j = 0; j <= lastel; ++j){
+        prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+        gl2psPutPDFImage(prim->data.image, gro->imno, prim->verts[0].xyz[0],
+                         prim->verts[0].xyz[1]);
+      }
+      break;
+    case GL2PS_TEXT:
+      for(j = 0; j <= lastel; ++j){
+        prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+        gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba);
+        gl2psPutPDFText(prim->data.text, gro->fontno, prim->verts[0].xyz[0],
+                        prim->verts[0].xyz[1]);
+      }
+      break;
+    case GL2PS_SPECIAL:
+      for(j = 0; j <= lastel; ++j){
+        prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+        gl2psPutPDFSpecial(prim->data.text);
+      }
+    default:
+      break;
+    }
+  }
+}
+
+/* Graphics State names */
+
+static int gl2psPDFgroupListWriteGStateResources(void)
+{
+  GL2PSpdfgroup *gro;
+  int offs = 0;
+  int i;
+
+  offs += fprintf(gl2ps->stream,
+                  "/ExtGState\n"
+                  "<<\n"
+                  "/GSa 7 0 R\n");
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i);
+    if(gro->gsno >= 0)
+      offs += fprintf(gl2ps->stream, "/GS%d %d 0 R\n", gro->gsno, gro->gsobjno);
+  }
+  offs += fprintf(gl2ps->stream, ">>\n");
+  return offs;
+}
+
+/* Main Shader names */
+
+static int gl2psPDFgroupListWriteShaderResources(void)
+{
+  GL2PSpdfgroup *gro;
+  int offs = 0;
+  int i;
+
+  offs += fprintf(gl2ps->stream,
+                  "/Shading\n"
+                  "<<\n");
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i);
+    if(gro->shno >= 0)
+      offs += fprintf(gl2ps->stream, "/Sh%d %d 0 R\n", gro->shno, gro->shobjno);
+    if(gro->maskshno >= 0)
+      offs += fprintf(gl2ps->stream, "/TrSh%d %d 0 R\n", gro->maskshno, gro->maskshobjno);
+  }
+  offs += fprintf(gl2ps->stream,">>\n");
+  return offs;
+}
+
+/* Images & Mask Shader XObject names */
+
+static int gl2psPDFgroupListWriteXObjectResources(void)
+{
+  int i;
+  GL2PSprimitive *p = NULL;
+  GL2PSpdfgroup *gro;
+  int offs = 0;
+
+  offs += fprintf(gl2ps->stream,
+                  "/XObject\n"
+                  "<<\n");
+
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i);
+    if(!gl2psListNbr(gro->ptrlist))
+      continue;
+    p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0);
+    switch(p->type){
+    case GL2PS_PIXMAP:
+      gro->imobjno = gl2ps->objects_stack++;
+      if(GL_RGBA == p->data.image->format)  /* reserve one object for image mask */
+        gl2ps->objects_stack++;
+      offs += fprintf(gl2ps->stream, "/Im%d %d 0 R\n", gro->imno, gro->imobjno);
+    case GL2PS_TRIANGLE:
+      if(gro->trgroupno >=0)
+        offs += fprintf(gl2ps->stream, "/TrG%d %d 0 R\n", gro->trgroupno, gro->trgroupobjno);
+      break;
+    default:
+      break;
+    }
+  }
+  offs += fprintf(gl2ps->stream,">>\n");
+  return offs;
+}
+
+/* Font names */
+
+static int gl2psPDFgroupListWriteFontResources(void)
+{
+  int i;
+  GL2PSpdfgroup *gro;
+  int offs = 0;
+
+  offs += fprintf(gl2ps->stream, "/Font\n<<\n");
+
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i);
+    if(gro->fontno < 0)
+      continue;
+    gro->fontobjno = gl2ps->objects_stack++;
+    offs += fprintf(gl2ps->stream, "/F%d %d 0 R\n", gro->fontno, gro->fontobjno);
+  }
+  offs += fprintf(gl2ps->stream, ">>\n");
+
+  return offs;
+}
+
+static void gl2psPDFgroupListDelete(void)
+{
+  int i;
+  GL2PSpdfgroup *gro = NULL;
+
+  if(!gl2ps->pdfgrouplist)
+    return;
+
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist,i);
+    gl2psListDelete(gro->ptrlist);
+  }
+
+  gl2psListDelete(gl2ps->pdfgrouplist);
+  gl2ps->pdfgrouplist = NULL;
+}
+
+/* Print 1st PDF object - file info */
+
+static int gl2psPrintPDFInfo(void)
+{
+  int offs;
+  time_t now;
+  struct tm *newtime;
+
+  time(&now);
+  newtime = gmtime(&now);
+
+  offs = fprintf(gl2ps->stream,
+                 "1 0 obj\n"
+                 "<<\n"
+                 "/Title (%s)\n"
+                 "/Creator (GL2PS %d.%d.%d%s, %s)\n"
+                 "/Producer (%s)\n",
+                 gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION,
+                 GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT,
+                 gl2ps->producer);
+
+  if(!newtime){
+    offs += fprintf(gl2ps->stream,
+                    ">>\n"
+                    "endobj\n");
+    return offs;
+  }
+
+  offs += fprintf(gl2ps->stream,
+                  "/CreationDate (D:%d%02d%02d%02d%02d%02d)\n"
+                  ">>\n"
+                  "endobj\n",
+                  newtime->tm_year+1900,
+                  newtime->tm_mon+1,
+                  newtime->tm_mday,
+                  newtime->tm_hour,
+                  newtime->tm_min,
+                  newtime->tm_sec);
+  return offs;
+}
+
+/* Create catalog and page structure - 2nd and 3th PDF object */
+
+static int gl2psPrintPDFCatalog(void)
+{
+  return fprintf(gl2ps->stream,
+                 "2 0 obj\n"
+                 "<<\n"
+                 "/Type /Catalog\n"
+                 "/Pages 3 0 R\n"
+                 ">>\n"
+                 "endobj\n");
+}
+
+static int gl2psPrintPDFPages(void)
+{
+  return fprintf(gl2ps->stream,
+                 "3 0 obj\n"
+                 "<<\n"
+                 "/Type /Pages\n"
+                 "/Kids [6 0 R]\n"
+                 "/Count 1\n"
+                 ">>\n"
+                 "endobj\n");
+}
+
+/* Open stream for data - graphical objects, fonts etc. PDF object 4 */
+
+static int gl2psOpenPDFDataStream(void)
+{
+  int offs = 0;
+
+  offs += fprintf(gl2ps->stream,
+                  "4 0 obj\n"
+                  "<<\n"
+                  "/Length 5 0 R\n" );
+  offs += gl2psPrintPDFCompressorType();
+  offs += fprintf(gl2ps->stream,
+                  ">>\n"
+                  "stream\n");
+  return offs;
+}
+
+/* Stream setup - Graphics state, fill background if allowed */
+
+static int gl2psOpenPDFDataStreamWritePreface(void)
+{
+  int offs;
+
+  offs = gl2psPrintf("/GSa gs\n");
+
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    offs += gl2psPrintPDFFillColor(gl2ps->bgcolor);
+    offs += gl2psPrintf("%d %d %d %d re\n",
+                        (int)gl2ps->viewport[0], (int)gl2ps->viewport[1],
+                        (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]);
+    offs += gl2psPrintf("f\n");
+  }
+  return offs;
+}
+
+/* Use the functions above to create the first part of the PDF*/
+
+static void gl2psPrintPDFHeader(void)
+{
+  int offs = 0;
+  gl2ps->pdfprimlist = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*));
+  gl2psPDFstacksInit();
+
+  gl2ps->xreflist = (int*)gl2psMalloc(sizeof(int) * gl2ps->objects_stack);
+
+#if defined(GL2PS_HAVE_ZLIB)
+  if(gl2ps->options & GL2PS_COMPRESS){
+    gl2psSetupCompress();
+  }
+#endif
+  gl2ps->xreflist[0] = 0;
+  offs += fprintf(gl2ps->stream, "%%PDF-1.4\n");
+  gl2ps->xreflist[1] = offs;
+
+  offs += gl2psPrintPDFInfo();
+  gl2ps->xreflist[2] = offs;
+
+  offs += gl2psPrintPDFCatalog();
+  gl2ps->xreflist[3] = offs;
+
+  offs += gl2psPrintPDFPages();
+  gl2ps->xreflist[4] = offs;
+
+  offs += gl2psOpenPDFDataStream();
+  gl2ps->xreflist[5] = offs; /* finished in gl2psPrintPDFFooter */
+  gl2ps->streamlength = gl2psOpenPDFDataStreamWritePreface();
+}
+
+/* The central primitive drawing */
+
+static void gl2psPrintPDFPrimitive(void *data)
+{
+  GL2PSprimitive *prim = *(GL2PSprimitive**)data;
+
+  if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled)
+    return;
+
+  prim = gl2psCopyPrimitive(prim); /* deep copy */
+  gl2psListAdd(gl2ps->pdfprimlist, &prim);
+}
+
+/* close stream and ... */
+
+static int gl2psClosePDFDataStream(void)
+{
+  int offs = 0;
+
+#if defined(GL2PS_HAVE_ZLIB)
+  if(gl2ps->options & GL2PS_COMPRESS){
+    if(Z_OK != gl2psDeflate())
+      gl2psMsg(GL2PS_ERROR, "Zlib deflate error");
+    else
+      fwrite(gl2ps->compress->dest, gl2ps->compress->destLen, 1, gl2ps->stream);
+    gl2ps->streamlength += gl2ps->compress->destLen;
+
+    offs += gl2ps->streamlength;
+    gl2psFreeCompress();
+  }
+#endif
+
+  offs += fprintf(gl2ps->stream,
+                  "endstream\n"
+                  "endobj\n");
+  return offs;
+}
+
+/* ... write the now known length object */
+
+static int gl2psPrintPDFDataStreamLength(int val)
+{
+  return fprintf(gl2ps->stream,
+                 "5 0 obj\n"
+                 "%d\n"
+                 "endobj\n", val);
+}
+
+/* Put the info created before in PDF objects */
+
+static int gl2psPrintPDFOpenPage(void)
+{
+  int offs;
+
+  /* Write fixed part */
+
+  offs = fprintf(gl2ps->stream,
+                 "6 0 obj\n"
+                 "<<\n"
+                 "/Type /Page\n"
+                 "/Parent 3 0 R\n"
+                 "/MediaBox [%d %d %d %d]\n",
+                 (int)gl2ps->viewport[0], (int)gl2ps->viewport[1],
+                 (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]);
+
+  if(gl2ps->options & GL2PS_LANDSCAPE)
+    offs += fprintf(gl2ps->stream, "/Rotate -90\n");
+
+  offs += fprintf(gl2ps->stream,
+                  "/Contents 4 0 R\n"
+                  "/Resources\n"
+                  "<<\n"
+                  "/ProcSet [/PDF /Text /ImageB /ImageC]  %%/ImageI\n");
+
+  return offs;
+
+  /* End fixed part, proceeds in gl2psPDFgroupListWriteVariableResources() */
+}
+
+static int gl2psPDFgroupListWriteVariableResources(void)
+{
+  int offs = 0;
+
+  /* a) Graphics States for shader alpha masks*/
+  offs += gl2psPDFgroupListWriteGStateResources();
+
+  /* b) Shader and shader masks */
+  offs += gl2psPDFgroupListWriteShaderResources();
+
+  /* c) XObjects (Images & Shader Masks) */
+  offs += gl2psPDFgroupListWriteXObjectResources();
+
+  /* d) Fonts */
+  offs += gl2psPDFgroupListWriteFontResources();
+
+  /* End resources and page */
+  offs += fprintf(gl2ps->stream,
+                  ">>\n"
+                  ">>\n"
+                  "endobj\n");
+  return offs;
+}
+
+/* Standard Graphics State */
+
+static int gl2psPrintPDFGSObject(void)
+{
+  return fprintf(gl2ps->stream,
+                 "7 0 obj\n"
+                 "<<\n"
+                 "/Type /ExtGState\n"
+                 "/SA false\n"
+                 "/SM 0.02\n"
+                 "/OP false\n"
+                 "/op false\n"
+                 "/OPM 0\n"
+                 "/BG2 /Default\n"
+                 "/UCR2 /Default\n"
+                 "/TR2 /Default\n"
+                 ">>\n"
+                 "endobj\n");
+}
+
+/* Put vertex' edge flag (8bit) and coordinates (32bit) in shader stream */
+
+static int gl2psPrintPDFShaderStreamDataCoord(GL2PSvertex *vertex,
+                                              int (*action)(unsigned long data, int size),
+                                              GLfloat dx, GLfloat dy,
+                                              GLfloat xmin, GLfloat ymin)
+{
+  int offs = 0;
+  unsigned long imap;
+  GLfloat diff;
+  double dmax = ~1UL;
+  char edgeflag = 0;
+
+  /* FIXME: temp bux fix for 64 bit archs: */
+  if(sizeof(unsigned long) == 8) dmax = dmax - 2048.;
+
+  offs += (*action)(edgeflag, 1);
+
+  /* The Shader stream in PDF requires to be in a 'big-endian'
+     order */
+
+  if(GL2PS_ZERO(dx * dy)){
+    offs += (*action)(0, 4);
+    offs += (*action)(0, 4);
+  }
+  else{
+    diff = (vertex->xyz[0] - xmin) / dx;
+    if(diff > 1)
+      diff = 1.0F;
+    else if(diff < 0)
+      diff = 0.0F;
+    imap = (unsigned long)(diff * dmax);
+    offs += (*action)(imap, 4);
+
+    diff = (vertex->xyz[1] - ymin) / dy;
+    if(diff > 1)
+      diff = 1.0F;
+    else if(diff < 0)
+      diff = 0.0F;
+    imap = (unsigned long)(diff * dmax);
+    offs += (*action)(imap, 4);
+  }
+
+  return offs;
+}
+
+/* Put vertex' rgb value (8bit for every component) in shader stream */
+
+static int gl2psPrintPDFShaderStreamDataRGB(GL2PSvertex *vertex,
+                                            int (*action)(unsigned long data, int size))
+{
+  int offs = 0;
+  unsigned long imap;
+  double dmax = ~1UL;
+
+  /* FIXME: temp bux fix for 64 bit archs: */
+  if(sizeof(unsigned long) == 8) dmax = dmax - 2048.;
+
+  imap = (unsigned long)((vertex->rgba[0]) * dmax);
+  offs += (*action)(imap, 1);
+
+  imap = (unsigned long)((vertex->rgba[1]) * dmax);
+  offs += (*action)(imap, 1);
+
+  imap = (unsigned long)((vertex->rgba[2]) * dmax);
+  offs += (*action)(imap, 1);
+
+  return offs;
+}
+
+/* Put vertex' alpha (8/16bit) in shader stream */
+
+static int gl2psPrintPDFShaderStreamDataAlpha(GL2PSvertex *vertex,
+                                              int (*action)(unsigned long data, int size),
+                                              int sigbyte)
+{
+  int offs = 0;
+  unsigned long imap;
+  double dmax = ~1UL;
+
+  /* FIXME: temp bux fix for 64 bit archs: */
+  if(sizeof(unsigned long) == 8) dmax = dmax - 2048.;
+
+  if(sigbyte != 8 && sigbyte != 16)
+    sigbyte = 8;
+
+  sigbyte /= 8;
+
+  imap = (unsigned long)((vertex->rgba[3]) * dmax);
+
+  offs += (*action)(imap, sigbyte);
+
+  return offs;
+}
+
+/* Put a triangles raw data in shader stream */
+
+static int gl2psPrintPDFShaderStreamData(GL2PStriangle *triangle,
+                                         GLfloat dx, GLfloat dy,
+                                         GLfloat xmin, GLfloat ymin,
+                                         int (*action)(unsigned long data, int size),
+                                         int gray)
+{
+  int i, offs = 0;
+  GL2PSvertex v;
+
+  if(gray && gray != 8 && gray != 16)
+    gray = 8;
+
+  for(i = 0; i < 3; ++i){
+    offs += gl2psPrintPDFShaderStreamDataCoord(&triangle->vertex[i], action,
+                                               dx, dy, xmin, ymin);
+    if(gray){
+      v = triangle->vertex[i];
+      offs += gl2psPrintPDFShaderStreamDataAlpha(&v, action, gray);
+    }
+    else{
+      offs += gl2psPrintPDFShaderStreamDataRGB(&triangle->vertex[i], action);
+    }
+  }
+
+  return offs;
+}
+
+static void gl2psPDFRectHull(GLfloat *xmin, GLfloat *xmax,
+                             GLfloat *ymin, GLfloat *ymax,
+                             GL2PStriangle *triangles, int cnt)
+{
+  int i, j;
+
+  *xmin = triangles[0].vertex[0].xyz[0];
+  *xmax = triangles[0].vertex[0].xyz[0];
+  *ymin = triangles[0].vertex[0].xyz[1];
+  *ymax = triangles[0].vertex[0].xyz[1];
+
+  for(i = 0; i < cnt; ++i){
+    for(j = 0; j < 3; ++j){
+      if(*xmin > triangles[i].vertex[j].xyz[0])
+        *xmin = triangles[i].vertex[j].xyz[0];
+      if(*xmax < triangles[i].vertex[j].xyz[0])
+        *xmax = triangles[i].vertex[j].xyz[0];
+      if(*ymin > triangles[i].vertex[j].xyz[1])
+        *ymin = triangles[i].vertex[j].xyz[1];
+      if(*ymax < triangles[i].vertex[j].xyz[1])
+        *ymax = triangles[i].vertex[j].xyz[1];
+    }
+  }
+}
+
+/* Writes shaded triangle
+   gray == 0 means write RGB triangles
+   gray == 8             8bit-grayscale (for alpha masks)
+   gray == 16            16bit-grayscale (for alpha masks) */
+
+static int gl2psPrintPDFShader(int obj, GL2PStriangle *triangles,
+                               int size, int gray)
+{
+  int i, offs = 0, vertexbytes, done = 0;
+  GLfloat xmin, xmax, ymin, ymax;
+
+  switch(gray){
+  case 0:
+    vertexbytes = 1+4+4+1+1+1;
+    break;
+  case 8:
+    vertexbytes = 1+4+4+1;
+    break;
+  case 16:
+    vertexbytes = 1+4+4+2;
+    break;
+  default:
+    gray = 8;
+    vertexbytes = 1+4+4+1;
+    break;
+  }
+
+  gl2psPDFRectHull(&xmin, &xmax, &ymin, &ymax, triangles, size);
+
+  offs += fprintf(gl2ps->stream,
+                  "%d 0 obj\n"
+                  "<< "
+                  "/ShadingType 4 "
+                  "/ColorSpace %s "
+                  "/BitsPerCoordinate 32 "
+                  "/BitsPerComponent %d "
+                  "/BitsPerFlag 8 "
+                  "/Decode [%f %f %f %f 0 1 %s] ",
+                  obj,
+                  (gray) ? "/DeviceGray" : "/DeviceRGB",
+                  (gray) ? gray : 8,
+                  xmin, xmax, ymin, ymax,
+                  (gray) ? "" : "0 1 0 1");
+
+#if defined(GL2PS_HAVE_ZLIB)
+  if(gl2ps->options & GL2PS_COMPRESS){
+    gl2psAllocCompress(vertexbytes * size * 3);
+
+    for(i = 0; i < size; ++i)
+      gl2psPrintPDFShaderStreamData(&triangles[i],
+                                    xmax-xmin, ymax-ymin, xmin, ymin,
+                                    gl2psWriteBigEndianCompress, gray);
+
+    if(Z_OK == gl2psDeflate() && 23 + gl2ps->compress->destLen < gl2ps->compress->srcLen){
+      offs += gl2psPrintPDFCompressorType();
+      offs += fprintf(gl2ps->stream,
+                      "/Length %d "
+                      ">>\n"
+                      "stream\n",
+                      (int)gl2ps->compress->destLen);
+      offs += gl2ps->compress->destLen * fwrite(gl2ps->compress->dest,
+                                                gl2ps->compress->destLen,
+                                                1, gl2ps->stream);
+      done = 1;
+    }
+    gl2psFreeCompress();
+  }
+#endif
+
+  if(!done){
+    /* no compression, or too long after compression, or compress error
+       -> write non-compressed entry */
+    offs += fprintf(gl2ps->stream,
+                    "/Length %d "
+                    ">>\n"
+                    "stream\n",
+                    vertexbytes * 3 * size);
+    for(i = 0; i < size; ++i)
+      offs += gl2psPrintPDFShaderStreamData(&triangles[i],
+                                            xmax-xmin, ymax-ymin, xmin, ymin,
+                                            gl2psWriteBigEndian, gray);
+  }
+
+  offs += fprintf(gl2ps->stream,
+                  "\nendstream\n"
+                  "endobj\n");
+
+  return offs;
+}
+
+/* Writes a XObject for a shaded triangle mask */
+
+static int gl2psPrintPDFShaderMask(int obj, int childobj)
+{
+  int offs = 0, len;
+
+  offs += fprintf(gl2ps->stream,
+                  "%d 0 obj\n"
+                  "<<\n"
+                  "/Type /XObject\n"
+                  "/Subtype /Form\n"
+                  "/BBox [ %d %d %d %d ]\n"
+                  "/Group \n<<\n/S /Transparency /CS /DeviceRGB\n"
+                  ">>\n",
+                  obj,
+                  (int)gl2ps->viewport[0], (int)gl2ps->viewport[1],
+                  (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]);
+
+  len = (childobj>0)
+    ? strlen("/TrSh sh\n") + (int)log10((double)childobj)+1
+    : strlen("/TrSh0 sh\n");
+
+  offs += fprintf(gl2ps->stream,
+                  "/Length %d\n"
+                  ">>\n"
+                  "stream\n",
+                  len);
+  offs += fprintf(gl2ps->stream,
+                  "/TrSh%d sh\n",
+                  childobj);
+  offs += fprintf(gl2ps->stream,
+                  "endstream\n"
+                  "endobj\n");
+
+  return offs;
+}
+
+/* Writes a Extended graphics state for a shaded triangle mask if
+   simplealpha ist true the childobj argument is ignored and a /ca
+   statement will be written instead */
+
+static int gl2psPrintPDFShaderExtGS(int obj, int childobj)
+{
+  int offs = 0;
+
+  offs += fprintf(gl2ps->stream,
+                  "%d 0 obj\n"
+                  "<<\n",
+                  obj);
+
+  offs += fprintf(gl2ps->stream,
+                  "/SMask << /S /Alpha /G %d 0 R >> ",
+                  childobj);
+
+  offs += fprintf(gl2ps->stream,
+                  ">>\n"
+                  "endobj\n");
+  return offs;
+}
+
+/* a simple graphics state */
+
+static int gl2psPrintPDFShaderSimpleExtGS(int obj, GLfloat alpha)
+{
+  int offs = 0;
+
+  offs += fprintf(gl2ps->stream,
+                  "%d 0 obj\n"
+                  "<<\n"
+                  "/ca %g"
+                  ">>\n"
+                  "endobj\n",
+                  obj, alpha);
+  return offs;
+}
+
+/* Similar groups of functions for pixmaps and text */
+
+static int gl2psPrintPDFPixmapStreamData(GL2PSimage *im,
+                                         int (*action)(unsigned long data, int size),
+                                         int gray)
+{
+  int x, y, shift;
+  GLfloat r, g, b, a;
+
+  if(im->format != GL_RGBA && gray)
+    return 0;
+
+  if(gray && gray != 8 && gray != 16)
+    gray = 8;
+
+  gray /= 8;
+
+  shift = (sizeof(unsigned long) - 1) * 8;
+
+  for(y = 0; y < im->height; ++y){
+    for(x = 0; x < im->width; ++x){
+      a = gl2psGetRGB(im, x, y, &r, &g, &b);
+      if(im->format == GL_RGBA && gray){
+        (*action)((unsigned long)(a * 255) << shift, gray);
+      }
+      else{
+        (*action)((unsigned long)(r * 255) << shift, 1);
+        (*action)((unsigned long)(g * 255) << shift, 1);
+        (*action)((unsigned long)(b * 255) << shift, 1);
+      }
+    }
+  }
+
+  switch(gray){
+  case 0: return 3 * im->width * im->height;
+  case 1: return im->width * im->height;
+  case 2: return 2 * im->width * im->height;
+  default: return 3 * im->width * im->height;
+  }
+}
+
+static int gl2psPrintPDFPixmap(int obj, int childobj, GL2PSimage *im, int gray)
+{
+  int offs = 0, done = 0, sigbytes = 3;
+
+  if(gray && gray !=8 && gray != 16)
+    gray = 8;
+
+  if(gray)
+    sigbytes = gray / 8;
+
+  offs += fprintf(gl2ps->stream,
+                  "%d 0 obj\n"
+                  "<<\n"
+                  "/Type /XObject\n"
+                  "/Subtype /Image\n"
+                  "/Width %d\n"
+                  "/Height %d\n"
+                  "/ColorSpace %s \n"
+                  "/BitsPerComponent 8\n",
+                  obj,
+                  (int)im->width, (int)im->height,
+                  (gray) ? "/DeviceGray" : "/DeviceRGB" );
+  if(GL_RGBA == im->format && gray == 0){
+    offs += fprintf(gl2ps->stream,
+                    "/SMask %d 0 R\n",
+                    childobj);
+  }
+
+#if defined(GL2PS_HAVE_ZLIB)
+  if(gl2ps->options & GL2PS_COMPRESS){
+    gl2psAllocCompress((int)(im->width * im->height * sigbytes));
+
+    gl2psPrintPDFPixmapStreamData(im, gl2psWriteBigEndianCompress, gray);
+
+    if(Z_OK == gl2psDeflate() && 23 + gl2ps->compress->destLen < gl2ps->compress->srcLen){
+      offs += gl2psPrintPDFCompressorType();
+      offs += fprintf(gl2ps->stream,
+                      "/Length %d "
+                      ">>\n"
+                      "stream\n",
+                      (int)gl2ps->compress->destLen);
+      offs += gl2ps->compress->destLen * fwrite(gl2ps->compress->dest, gl2ps->compress->destLen,
+                                                1, gl2ps->stream);
+      done = 1;
+    }
+    gl2psFreeCompress();
+  }
+#endif
+
+  if(!done){
+    /* no compression, or too long after compression, or compress error
+       -> write non-compressed entry */
+    offs += fprintf(gl2ps->stream,
+                    "/Length %d "
+                    ">>\n"
+                    "stream\n",
+                    (int)(im->width * im->height * sigbytes));
+    offs += gl2psPrintPDFPixmapStreamData(im, gl2psWriteBigEndian, gray);
+  }
+
+  offs += fprintf(gl2ps->stream,
+                  "\nendstream\n"
+                  "endobj\n");
+
+  return offs;
+}
+
+static int gl2psPrintPDFText(int obj, GL2PSstring *s, int fontnumber)
+{
+  int offs = 0;
+
+  offs += fprintf(gl2ps->stream,
+                  "%d 0 obj\n"
+                  "<<\n"
+                  "/Type /Font\n"
+                  "/Subtype /Type1\n"
+                  "/Name /F%d\n"
+                  "/BaseFont /%s\n"
+                  "/Encoding /MacRomanEncoding\n"
+                  ">>\n"
+                  "endobj\n",
+                  obj, fontnumber, s->fontname);
+  return offs;
+}
+
+/* Write the physical objects */
+
+static int gl2psPDFgroupListWriteObjects(int entryoffs)
+{
+  int i,j;
+  GL2PSprimitive *p = NULL;
+  GL2PSpdfgroup *gro;
+  int offs = entryoffs;
+  GL2PStriangle *triangles;
+  int size = 0;
+
+  if(!gl2ps->pdfgrouplist)
+    return offs;
+
+  for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){
+    gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i);
+    if(!gl2psListNbr(gro->ptrlist))
+      continue;
+    p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0);
+    switch(p->type){
+    case GL2PS_POINT:
+      break;
+    case GL2PS_LINE:
+      break;
+    case GL2PS_TRIANGLE:
+      size = gl2psListNbr(gro->ptrlist);
+      triangles = (GL2PStriangle*)gl2psMalloc(sizeof(GL2PStriangle) * size);
+      for(j = 0; j < size; ++j){
+        p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j);
+        gl2psFillTriangleFromPrimitive(&triangles[j], p, GL_TRUE);
+      }
+      if(triangles[0].prop & T_VAR_COLOR){
+        gl2ps->xreflist[gro->shobjno] = offs;
+        offs += gl2psPrintPDFShader(gro->shobjno, triangles, size, 0);
+      }
+      if(triangles[0].prop & T_ALPHA_LESS_1){
+        gl2ps->xreflist[gro->gsobjno] = offs;
+        offs += gl2psPrintPDFShaderSimpleExtGS(gro->gsobjno, triangles[0].vertex[0].rgba[3]);
+      }
+      if(triangles[0].prop & T_VAR_ALPHA){
+        gl2ps->xreflist[gro->gsobjno] = offs;
+        offs += gl2psPrintPDFShaderExtGS(gro->gsobjno, gro->trgroupobjno);
+        gl2ps->xreflist[gro->trgroupobjno] = offs;
+        offs += gl2psPrintPDFShaderMask(gro->trgroupobjno, gro->maskshno);
+        gl2ps->xreflist[gro->maskshobjno] = offs;
+        offs += gl2psPrintPDFShader(gro->maskshobjno, triangles, size, 8);
+      }
+      gl2psFree(triangles);
+      break;
+    case GL2PS_PIXMAP:
+      gl2ps->xreflist[gro->imobjno] = offs;
+      offs += gl2psPrintPDFPixmap(gro->imobjno, gro->imobjno+1, p->data.image, 0);
+      if(p->data.image->format == GL_RGBA){
+        gl2ps->xreflist[gro->imobjno+1] = offs;
+        offs += gl2psPrintPDFPixmap(gro->imobjno+1, -1, p->data.image, 8);
+      }
+      break;
+    case GL2PS_TEXT:
+      gl2ps->xreflist[gro->fontobjno] = offs;
+      offs += gl2psPrintPDFText(gro->fontobjno,p->data.text,gro->fontno);
+      break;
+    case GL2PS_SPECIAL :
+      /* alignment contains the format for which the special output text
+         is intended */
+      if(p->data.text->alignment == GL2PS_PDF)
+        offs += fprintf(gl2ps->stream, "%s\n", p->data.text->str);
+      break;
+    default:
+      break;
+    }
+  }
+  return offs;
+}
+
+/* All variable data has been written at this point and all required
+   functioninality has been gathered, so we can write now file footer
+   with cross reference table and trailer */
+
+static void gl2psPrintPDFFooter(void)
+{
+  int i, offs;
+
+  gl2psPDFgroupListInit();
+  gl2psPDFgroupListWriteMainStream();
+
+  offs = gl2ps->xreflist[5] + gl2ps->streamlength;
+  offs += gl2psClosePDFDataStream();
+  gl2ps->xreflist[5] = offs;
+
+  offs += gl2psPrintPDFDataStreamLength(gl2ps->streamlength);
+  gl2ps->xreflist[6] = offs;
+  gl2ps->streamlength = 0;
+
+  offs += gl2psPrintPDFOpenPage();
+  offs += gl2psPDFgroupListWriteVariableResources();
+  gl2ps->xreflist = (int*)gl2psRealloc(gl2ps->xreflist,
+                                       sizeof(int) * (gl2ps->objects_stack + 1));
+  gl2ps->xreflist[7] = offs;
+
+  offs += gl2psPrintPDFGSObject();
+  gl2ps->xreflist[8] = offs;
+
+  gl2ps->xreflist[gl2ps->objects_stack] =
+    gl2psPDFgroupListWriteObjects(gl2ps->xreflist[8]);
+
+  /* Start cross reference table. The file has to been opened in
+     binary mode to preserve the 20 digit string length! */
+  fprintf(gl2ps->stream,
+          "xref\n"
+          "0 %d\n"
+          "%010d 65535 f \n", gl2ps->objects_stack, 0);
+
+  for(i = 1; i < gl2ps->objects_stack; ++i)
+    fprintf(gl2ps->stream, "%010d 00000 n \n", gl2ps->xreflist[i]);
+
+  fprintf(gl2ps->stream,
+          "trailer\n"
+          "<<\n"
+          "/Size %d\n"
+          "/Info 1 0 R\n"
+          "/Root 2 0 R\n"
+          ">>\n"
+          "startxref\n%d\n"
+          "%%%%EOF\n",
+          gl2ps->objects_stack, gl2ps->xreflist[gl2ps->objects_stack]);
+
+  /* Free auxiliary lists and arrays */
+  gl2psFree(gl2ps->xreflist);
+  gl2psListAction(gl2ps->pdfprimlist, gl2psFreePrimitive);
+  gl2psListDelete(gl2ps->pdfprimlist);
+  gl2psPDFgroupListDelete();
+
+#if defined(GL2PS_HAVE_ZLIB)
+  if(gl2ps->options & GL2PS_COMPRESS){
+    gl2psFreeCompress();
+    gl2psFree(gl2ps->compress);
+    gl2ps->compress = NULL;
+  }
+#endif
+}
+
+/* PDF begin viewport */
+
+static void gl2psPrintPDFBeginViewport(GLint viewport[4])
+{
+  int offs = 0;
+  GLint idx;
+  GLfloat rgba[4];
+  int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3];
+
+  glRenderMode(GL_FEEDBACK);
+
+  if(gl2ps->header){
+    gl2psPrintPDFHeader();
+    gl2ps->header = GL_FALSE;
+  }
+
+  offs += gl2psPrintf("q\n");
+
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){
+      glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba);
+    }
+    else{
+      glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx);
+      rgba[0] = gl2ps->colormap[idx][0];
+      rgba[1] = gl2ps->colormap[idx][1];
+      rgba[2] = gl2ps->colormap[idx][2];
+      rgba[3] = 1.0F;
+    }
+    offs += gl2psPrintPDFFillColor(rgba);
+    offs += gl2psPrintf("%d %d %d %d re\n"
+                        "W\n"
+                        "f\n",
+                        x, y, w, h);
+  }
+  else{
+    offs += gl2psPrintf("%d %d %d %d re\n"
+                        "W\n"
+                        "n\n",
+                        x, y, w, h);
+  }
+
+  gl2ps->streamlength += offs;
+}
+
+static GLint gl2psPrintPDFEndViewport(void)
+{
+  GLint res;
+
+  res = gl2psPrintPrimitives();
+  gl2ps->streamlength += gl2psPrintf("Q\n");
+  return res;
+}
+
+static void gl2psPrintPDFFinalPrimitive(void)
+{
+}
+
+/* definition of the PDF backend */
+
+static GL2PSbackend gl2psPDF = {
+  gl2psPrintPDFHeader,
+  gl2psPrintPDFFooter,
+  gl2psPrintPDFBeginViewport,
+  gl2psPrintPDFEndViewport,
+  gl2psPrintPDFPrimitive,
+  gl2psPrintPDFFinalPrimitive,
+  "pdf",
+  "Portable Document Format"
+};
+
+/*********************************************************************
+ *
+ * SVG routines
+ *
+ *********************************************************************/
+
+static void gl2psSVGGetCoordsAndColors(int n, GL2PSvertex *verts,
+                                       GL2PSxyz *xyz, GL2PSrgba *rgba)
+{
+  int i, j;
+
+  for(i = 0; i < n; i++){
+    xyz[i][0] = verts[i].xyz[0];
+    xyz[i][1] = gl2ps->viewport[3] - verts[i].xyz[1];
+    xyz[i][2] = 0.0F;
+    for(j = 0; j < 4; j++)
+      rgba[i][j] = verts[i].rgba[j];
+  }
+}
+
+static void gl2psSVGGetColorString(GL2PSrgba rgba, char str[32])
+{
+  int r = (int)(255. * rgba[0]);
+  int g = (int)(255. * rgba[1]);
+  int b = (int)(255. * rgba[2]);
+  int rc = (r < 0) ? 0 : (r > 255) ? 255 : r;
+  int gc = (g < 0) ? 0 : (g > 255) ? 255 : g;
+  int bc = (b < 0) ? 0 : (b > 255) ? 255 : b;
+  sprintf(str, "#%2.2x%2.2x%2.2x", rc, gc, bc);
+}
+
+static void gl2psPrintSVGHeader(void)
+{
+  int x, y, width, height;
+  char col[32];
+  time_t now;
+
+  time(&now);
+
+  if (gl2ps->options & GL2PS_LANDSCAPE){
+    x = (int)gl2ps->viewport[1];
+    y = (int)gl2ps->viewport[0];
+    width = (int)gl2ps->viewport[3];
+    height = (int)gl2ps->viewport[2];
+  }
+  else{
+    x = (int)gl2ps->viewport[0];
+    y = (int)gl2ps->viewport[1];
+    width = (int)gl2ps->viewport[2];
+    height = (int)gl2ps->viewport[3];
+  }
+
+  /* Compressed SVG files (.svgz) are simply gzipped SVG files */
+  gl2psPrintGzipHeader();
+
+  gl2psPrintf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n");
+  gl2psPrintf("<svg xmlns=\"http://www.w3.org/2000/svg\"\n");
+  gl2psPrintf("     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
+              "     width=\"%dpx\" height=\"%dpx\" viewBox=\"%d %d %d %d\">\n",
+              width, height, x, y, width, height);
+  gl2psPrintf("<title>%s</title>\n", gl2ps->title);
+  gl2psPrintf("<desc>\n");
+  gl2psPrintf("Creator: GL2PS %d.%d.%d%s, %s\n"
+              "For: %s\n"
+              "CreationDate: %s",
+              GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION,
+              GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer, ctime(&now));
+  gl2psPrintf("</desc>\n");
+  gl2psPrintf("<defs>\n");
+  gl2psPrintf("</defs>\n");
+
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    gl2psSVGGetColorString(gl2ps->bgcolor, col);
+    gl2psPrintf("<polygon fill=\"%s\" points=\"%d,%d %d,%d %d,%d %d,%d\"/>\n", col,
+                (int)gl2ps->viewport[0], (int)gl2ps->viewport[1],
+                (int)gl2ps->viewport[2], (int)gl2ps->viewport[1],
+                (int)gl2ps->viewport[2], (int)gl2ps->viewport[3],
+                (int)gl2ps->viewport[0], (int)gl2ps->viewport[3]);
+  }
+
+  /* group all the primitives and disable antialiasing */
+  gl2psPrintf("<g shape-rendering=\"crispEdges\">\n");
+}
+
+static void gl2psPrintSVGSmoothTriangle(GL2PSxyz xyz[3], GL2PSrgba rgba[3])
+{
+  int i;
+  GL2PSxyz xyz2[3];
+  GL2PSrgba rgba2[3];
+  char col[32];
+
+  /* Apparently there is no easy way to do Gouraud shading in SVG
+     without explicitly pre-defining gradients, so for now we just do
+     recursive subdivision */
+
+  if(gl2psSameColorThreshold(3, rgba, gl2ps->threshold)){
+    gl2psSVGGetColorString(rgba[0], col);
+    gl2psPrintf("<polygon fill=\"%s\" ", col);
+    if(rgba[0][3] < 1.0F) gl2psPrintf("fill-opacity=\"%g\" ", rgba[0][3]);
+    gl2psPrintf("points=\"%g,%g %g,%g %g,%g\"/>\n", xyz[0][0], xyz[0][1],
+                xyz[1][0], xyz[1][1], xyz[2][0], xyz[2][1]);
+  }
+  else{
+    /* subdivide into 4 subtriangles */
+    for(i = 0; i < 3; i++){
+      xyz2[0][i] = xyz[0][i];
+      xyz2[1][i] = 0.5F * (xyz[0][i] + xyz[1][i]);
+      xyz2[2][i] = 0.5F * (xyz[0][i] + xyz[2][i]);
+    }
+    for(i = 0; i < 4; i++){
+      rgba2[0][i] = rgba[0][i];
+      rgba2[1][i] = 0.5F * (rgba[0][i] + rgba[1][i]);
+      rgba2[2][i] = 0.5F * (rgba[0][i] + rgba[2][i]);
+    }
+    gl2psPrintSVGSmoothTriangle(xyz2, rgba2);
+    for(i = 0; i < 3; i++){
+      xyz2[0][i] = 0.5F * (xyz[0][i] + xyz[1][i]);
+      xyz2[1][i] = xyz[1][i];
+      xyz2[2][i] = 0.5F * (xyz[1][i] + xyz[2][i]);
+    }
+    for(i = 0; i < 4; i++){
+      rgba2[0][i] = 0.5F * (rgba[0][i] + rgba[1][i]);
+      rgba2[1][i] = rgba[1][i];
+      rgba2[2][i] = 0.5F * (rgba[1][i] + rgba[2][i]);
+    }
+    gl2psPrintSVGSmoothTriangle(xyz2, rgba2);
+    for(i = 0; i < 3; i++){
+      xyz2[0][i] = 0.5F * (xyz[0][i] + xyz[2][i]);
+      xyz2[1][i] = xyz[2][i];
+      xyz2[2][i] = 0.5F * (xyz[1][i] + xyz[2][i]);
+    }
+    for(i = 0; i < 4; i++){
+      rgba2[0][i] = 0.5F * (rgba[0][i] + rgba[2][i]);
+      rgba2[1][i] = rgba[2][i];
+      rgba2[2][i] = 0.5F * (rgba[1][i] + rgba[2][i]);
+    }
+    gl2psPrintSVGSmoothTriangle(xyz2, rgba2);
+    for(i = 0; i < 3; i++){
+      xyz2[0][i] = 0.5F * (xyz[0][i] + xyz[1][i]);
+      xyz2[1][i] = 0.5F * (xyz[1][i] + xyz[2][i]);
+      xyz2[2][i] = 0.5F * (xyz[0][i] + xyz[2][i]);
+    }
+    for(i = 0; i < 4; i++){
+      rgba2[0][i] = 0.5F * (rgba[0][i] + rgba[1][i]);
+      rgba2[1][i] = 0.5F * (rgba[1][i] + rgba[2][i]);
+      rgba2[2][i] = 0.5F * (rgba[0][i] + rgba[2][i]);
+    }
+    gl2psPrintSVGSmoothTriangle(xyz2, rgba2);
+  }
+}
+
+static void gl2psPrintSVGDash(GLushort pattern, GLint factor)
+{
+  int i, n, array[10];
+
+  if(!pattern || !factor) return; /* solid line */
+
+  gl2psParseStipplePattern(pattern, factor, &n, array);
+  gl2psPrintf("stroke-dasharray=\"");
+  for(i = 0; i < n; i++){
+    if(i) gl2psPrintf(",");
+    gl2psPrintf("%d", array[i]);
+  }
+  gl2psPrintf("\" ");
+}
+
+static void gl2psEndSVGLine(void)
+{
+  int i;
+  if(gl2ps->lastvertex.rgba[0] >= 0.){
+    gl2psPrintf("%g,%g\"/>\n", gl2ps->lastvertex.xyz[0],
+                gl2ps->viewport[3] - gl2ps->lastvertex.xyz[1]);
+    for(i = 0; i < 3; i++)
+      gl2ps->lastvertex.xyz[i] = -1.;
+    for(i = 0; i < 4; i++)
+      gl2ps->lastvertex.rgba[i] = -1.;
+  }
+}
+
+static void gl2psPrintSVGPixmap(GLfloat x, GLfloat y, GL2PSimage *pixmap)
+{
+#if defined(GL2PS_HAVE_LIBPNG)
+  GL2PSlist *png;
+  unsigned char c;
+  int i;
+
+  /* The only image types supported by the SVG standard are JPEG, PNG
+     and SVG. Here we choose PNG, and since we want to embed the image
+     directly in the SVG stream (and not link to an external image
+     file), we need to encode the pixmap into PNG in memory, then
+     encode it into base64. */
+
+  png = gl2psListCreate(pixmap->width * pixmap->height * 3, 1000,
+                        sizeof(unsigned char));
+  gl2psConvertPixmapToPNG(pixmap, png);
+  gl2psListEncodeBase64(png);
+  gl2psPrintf("<image x=\"%g\" y=\"%g\" width=\"%d\" height=\"%d\"\n",
+              x, y - pixmap->height, pixmap->width, pixmap->height);
+  gl2psPrintf("xlink:href=\"data:image/png;base64,");
+  for(i = 0; i < gl2psListNbr(png); i++){
+    gl2psListRead(png, i, &c);
+    gl2psPrintf("%c", c);
+  }
+  gl2psPrintf("\"/>\n");
+  gl2psListDelete(png);
+#else
+  (void) x; (void) y; (void) pixmap;  /* not used */
+  gl2psMsg(GL2PS_WARNING, "GL2PS must be compiled with PNG support in "
+           "order to embed images in SVG streams");
+#endif
+}
+
+static void gl2psPrintSVGPrimitive(void *data)
+{
+  GL2PSprimitive *prim;
+  GL2PSxyz xyz[4];
+  GL2PSrgba rgba[4];
+  char col[32];
+  int newline;
+
+  prim = *(GL2PSprimitive**)data;
+
+  if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return;
+
+  /* We try to draw connected lines as a single path to get nice line
+     joins and correct stippling. So if the primitive to print is not
+     a line we must first finish the current line (if any): */
+  if(prim->type != GL2PS_LINE) gl2psEndSVGLine();
+
+  gl2psSVGGetCoordsAndColors(prim->numverts, prim->verts, xyz, rgba);
+
+  switch(prim->type){
+  case GL2PS_POINT :
+    gl2psSVGGetColorString(rgba[0], col);
+    gl2psPrintf("<circle fill=\"%s\" ", col);
+    if(rgba[0][3] < 1.0F) gl2psPrintf("fill-opacity=\"%g\" ", rgba[0][3]);
+    gl2psPrintf("cx=\"%g\" cy=\"%g\" r=\"%g\"/>\n",
+                xyz[0][0], xyz[0][1], 0.5 * prim->width);
+    break;
+  case GL2PS_LINE :
+    if(!gl2psSamePosition(gl2ps->lastvertex.xyz, prim->verts[0].xyz) ||
+       !gl2psSameColor(gl2ps->lastrgba, prim->verts[0].rgba) ||
+       gl2ps->lastlinewidth != prim->width ||
+       gl2ps->lastpattern != prim->pattern ||
+       gl2ps->lastfactor != prim->factor){
+      /* End the current line if the new segment does not start where
+         the last one ended, or if the color, the width or the
+         stippling have changed (we will need to use multi-point
+         gradients for smooth-shaded lines) */
+      gl2psEndSVGLine();
+      newline = 1;
+    }
+    else{
+      newline = 0;
+    }
+    gl2ps->lastvertex = prim->verts[1];
+    gl2psSetLastColor(prim->verts[0].rgba);
+    gl2ps->lastlinewidth = prim->width;
+    gl2ps->lastpattern = prim->pattern;
+    gl2ps->lastfactor = prim->factor;
+    if(newline){
+      gl2psSVGGetColorString(rgba[0], col);
+      gl2psPrintf("<polyline fill=\"none\" stroke=\"%s\" stroke-width=\"%g\" ",
+                  col, prim->width);
+      if(rgba[0][3] < 1.0F) gl2psPrintf("stroke-opacity=\"%g\" ", rgba[0][3]);
+      gl2psPrintSVGDash(prim->pattern, prim->factor);
+      gl2psPrintf("points=\"%g,%g ", xyz[0][0], xyz[0][1]);
+    }
+    else{
+      gl2psPrintf("%g,%g ", xyz[0][0], xyz[0][1]);
+    }
+    break;
+  case GL2PS_TRIANGLE :
+    gl2psPrintSVGSmoothTriangle(xyz, rgba);
+    break;
+  case GL2PS_QUADRANGLE :
+    gl2psMsg(GL2PS_WARNING, "There should not be any quad left to print");
+    break;
+  case GL2PS_PIXMAP :
+    gl2psPrintSVGPixmap(xyz[0][0], xyz[0][1], prim->data.image);
+    break;
+  case GL2PS_TEXT :
+    gl2psSVGGetColorString(prim->verts[0].rgba, col);
+    gl2psPrintf("<text fill=\"%s\" x=\"%g\" y=\"%g\" font-size=\"%d\" ",
+                col, xyz[0][0], xyz[0][1], prim->data.text->fontsize);
+    if(prim->data.text->angle)
+      gl2psPrintf("transform=\"rotate(%g, %g, %g)\" ",
+                  -prim->data.text->angle, xyz[0][0], xyz[0][1]);
+    switch(prim->data.text->alignment){
+    case GL2PS_TEXT_C:
+      gl2psPrintf("text-anchor=\"middle\" baseline-shift=\"%d\" ",
+                  -prim->data.text->fontsize / 2);
+      break;
+    case GL2PS_TEXT_CL:
+      gl2psPrintf("text-anchor=\"start\" baseline-shift=\"%d\" ",
+                  -prim->data.text->fontsize / 2);
+      break;
+    case GL2PS_TEXT_CR:
+      gl2psPrintf("text-anchor=\"end\" baseline-shift=\"%d\" ",
+                  -prim->data.text->fontsize / 2);
+      break;
+    case GL2PS_TEXT_B:
+      gl2psPrintf("text-anchor=\"middle\" baseline-shift=\"0\" ");
+      break;
+    case GL2PS_TEXT_BR:
+      gl2psPrintf("text-anchor=\"end\" baseline-shift=\"0\" ");
+      break;
+    case GL2PS_TEXT_T:
+      gl2psPrintf("text-anchor=\"middle\" baseline-shift=\"%d\" ",
+                  -prim->data.text->fontsize);
+      break;
+    case GL2PS_TEXT_TL:
+      gl2psPrintf("text-anchor=\"start\" baseline-shift=\"%d\" ",
+                  -prim->data.text->fontsize);
+      break;
+    case GL2PS_TEXT_TR:
+      gl2psPrintf("text-anchor=\"end\" baseline-shift=\"%d\" ",
+                  -prim->data.text->fontsize);
+      break;
+    case GL2PS_TEXT_BL:
+    default: /* same as GL2PS_TEXT_BL */
+      gl2psPrintf("text-anchor=\"start\" baseline-shift=\"0\" ");
+      break;
+    }
+    if(!strcmp(prim->data.text->fontname, "Times-Roman"))
+      gl2psPrintf("font-family=\"Times\">");
+    else if(!strcmp(prim->data.text->fontname, "Times-Bold"))
+      gl2psPrintf("font-family=\"Times\" font-weight=\"bold\">");
+    else if(!strcmp(prim->data.text->fontname, "Times-Italic"))
+      gl2psPrintf("font-family=\"Times\" font-style=\"italic\">");
+    else if(!strcmp(prim->data.text->fontname, "Times-BoldItalic"))
+      gl2psPrintf("font-family=\"Times\" font-style=\"italic\" font-weight=\"bold\">");
+    else if(!strcmp(prim->data.text->fontname, "Helvetica-Bold"))
+      gl2psPrintf("font-family=\"Helvetica\" font-weight=\"bold\">");
+    else if(!strcmp(prim->data.text->fontname, "Helvetica-Oblique"))
+      gl2psPrintf("font-family=\"Helvetica\" font-style=\"oblique\">");
+    else if(!strcmp(prim->data.text->fontname, "Helvetica-BoldOblique"))
+      gl2psPrintf("font-family=\"Helvetica\" font-style=\"oblique\" font-weight=\"bold\">");
+    else if(!strcmp(prim->data.text->fontname, "Courier-Bold"))
+      gl2psPrintf("font-family=\"Courier\" font-weight=\"bold\">");
+    else if(!strcmp(prim->data.text->fontname, "Courier-Oblique"))
+      gl2psPrintf("font-family=\"Courier\" font-style=\"oblique\">");
+    else if(!strcmp(prim->data.text->fontname, "Courier-BoldOblique"))
+      gl2psPrintf("font-family=\"Courier\" font-style=\"oblique\" font-weight=\"bold\">");
+    else
+      gl2psPrintf("font-family=\"%s\">", prim->data.text->fontname);
+    gl2psPrintf("%s</text>\n", prim->data.text->str);
+    break;
+  case GL2PS_SPECIAL :
+    /* alignment contains the format for which the special output text
+       is intended */
+    if(prim->data.text->alignment == GL2PS_SVG)
+      gl2psPrintf("%s\n", prim->data.text->str);
+    break;
+  default :
+    break;
+  }
+}
+
+static void gl2psPrintSVGFooter(void)
+{
+  gl2psPrintf("</g>\n");
+  gl2psPrintf("</svg>\n");
+
+  gl2psPrintGzipFooter();
+}
+
+static void gl2psPrintSVGBeginViewport(GLint viewport[4])
+{
+  GLint idx;
+  char col[32];
+  GLfloat rgba[4];
+  int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3];
+
+  glRenderMode(GL_FEEDBACK);
+
+  if(gl2ps->header){
+    gl2psPrintSVGHeader();
+    gl2ps->header = GL_FALSE;
+  }
+
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){
+      glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba);
+    }
+    else{
+      glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx);
+      rgba[0] = gl2ps->colormap[idx][0];
+      rgba[1] = gl2ps->colormap[idx][1];
+      rgba[2] = gl2ps->colormap[idx][2];
+      rgba[3] = 1.0F;
+    }
+    gl2psSVGGetColorString(rgba, col);
+    gl2psPrintf("<polygon fill=\"%s\" points=\"%d,%d %d,%d %d,%d %d,%d\"/>\n", col,
+                x, gl2ps->viewport[3] - y,
+                x + w, gl2ps->viewport[3] - y,
+                x + w, gl2ps->viewport[3] - (y + h),
+                x, gl2ps->viewport[3] - (y + h));
+  }
+
+  gl2psPrintf("<clipPath id=\"cp%d%d%d%d\">\n", x, y, w, h);
+  gl2psPrintf("  <polygon points=\"%d,%d %d,%d %d,%d %d,%d\"/>\n",
+              x, gl2ps->viewport[3] - y,
+              x + w, gl2ps->viewport[3] - y,
+              x + w, gl2ps->viewport[3] - (y + h),
+              x, gl2ps->viewport[3] - (y + h));
+  gl2psPrintf("</clipPath>\n");
+  gl2psPrintf("<g clip-path=\"url(#cp%d%d%d%d)\">\n", x, y, w, h);
+}
+
+static GLint gl2psPrintSVGEndViewport(void)
+{
+  GLint res;
+
+  res = gl2psPrintPrimitives();
+  gl2psPrintf("</g>\n");
+  return res;
+}
+
+static void gl2psPrintSVGFinalPrimitive(void)
+{
+  /* End any remaining line, if any */
+  gl2psEndSVGLine();
+}
+
+/* definition of the SVG backend */
+
+static GL2PSbackend gl2psSVG = {
+  gl2psPrintSVGHeader,
+  gl2psPrintSVGFooter,
+  gl2psPrintSVGBeginViewport,
+  gl2psPrintSVGEndViewport,
+  gl2psPrintSVGPrimitive,
+  gl2psPrintSVGFinalPrimitive,
+  "svg",
+  "Scalable Vector Graphics"
+};
+
+/*********************************************************************
+ *
+ * PGF routines
+ *
+ *********************************************************************/
+
+static void gl2psPrintPGFColor(GL2PSrgba rgba)
+{
+  if(!gl2psSameColor(gl2ps->lastrgba, rgba)){
+    gl2psSetLastColor(rgba);
+    fprintf(gl2ps->stream, "\\color[rgb]{%f,%f,%f}\n", rgba[0], rgba[1], rgba[2]);
+  }
+}
+
+static void gl2psPrintPGFHeader(void)
+{
+  time_t now;
+
+  time(&now);
+
+  fprintf(gl2ps->stream,
+          "%% Title: %s\n"
+          "%% Creator: GL2PS %d.%d.%d%s, %s\n"
+          "%% For: %s\n"
+          "%% CreationDate: %s",
+          gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION,
+          GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT,
+          gl2ps->producer, ctime(&now));
+
+  fprintf(gl2ps->stream, "\\begin{pgfpicture}\n");
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    gl2psPrintPGFColor(gl2ps->bgcolor);
+    fprintf(gl2ps->stream,
+            "\\pgfpathrectanglecorners{"
+            "\\pgfpoint{%dpt}{%dpt}}{\\pgfpoint{%dpt}{%dpt}}\n"
+            "\\pgfusepath{fill}\n",
+            (int)gl2ps->viewport[0], (int)gl2ps->viewport[1],
+            (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]);
+  }
+}
+
+static void gl2psPrintPGFDash(GLushort pattern, GLint factor)
+{
+  int i, n, array[10];
+
+  if(pattern == gl2ps->lastpattern && factor == gl2ps->lastfactor)
+    return;
+
+  gl2ps->lastpattern = pattern;
+  gl2ps->lastfactor = factor;
+
+  if(!pattern || !factor){
+    /* solid line */
+    fprintf(gl2ps->stream, "\\pgfsetdash{}{0pt}\n");
+  }
+  else{
+    gl2psParseStipplePattern(pattern, factor, &n, array);
+    fprintf(gl2ps->stream, "\\pgfsetdash{");
+    for(i = 0; i < n; i++) fprintf(gl2ps->stream, "{%dpt}", array[i]);
+    fprintf(gl2ps->stream, "}{0pt}\n");
+  }
+}
+
+static const char *gl2psPGFTextAlignment(int align)
+{
+  switch(align){
+  case GL2PS_TEXT_C  : return "center";
+  case GL2PS_TEXT_CL : return "west";
+  case GL2PS_TEXT_CR : return "east";
+  case GL2PS_TEXT_B  : return "south";
+  case GL2PS_TEXT_BR : return "south east";
+  case GL2PS_TEXT_T  : return "north";
+  case GL2PS_TEXT_TL : return "north west";
+  case GL2PS_TEXT_TR : return "north east";
+  case GL2PS_TEXT_BL :
+  default            : return "south west";
+  }
+}
+
+static void gl2psPrintPGFPrimitive(void *data)
+{
+  GL2PSprimitive *prim;
+
+  prim = *(GL2PSprimitive**)data;
+
+  switch(prim->type){
+  case GL2PS_POINT :
+    /* Points in openGL are rectangular */
+    gl2psPrintPGFColor(prim->verts[0].rgba);
+    fprintf(gl2ps->stream,
+            "\\pgfpathrectangle{\\pgfpoint{%fpt}{%fpt}}"
+            "{\\pgfpoint{%fpt}{%fpt}}\n\\pgfusepath{fill}\n",
+            prim->verts[0].xyz[0]-0.5*prim->width,
+            prim->verts[0].xyz[1]-0.5*prim->width,
+            prim->width,prim->width);
+    break;
+  case GL2PS_LINE :
+    gl2psPrintPGFColor(prim->verts[0].rgba);
+    if(gl2ps->lastlinewidth != prim->width){
+      gl2ps->lastlinewidth = prim->width;
+      fprintf(gl2ps->stream, "\\pgfsetlinewidth{%fpt}\n", gl2ps->lastlinewidth);
+    }
+    gl2psPrintPGFDash(prim->pattern, prim->factor);
+    fprintf(gl2ps->stream,
+            "\\pgfpathmoveto{\\pgfpoint{%fpt}{%fpt}}\n"
+            "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n"
+            "\\pgfusepath{stroke}\n",
+            prim->verts[1].xyz[0], prim->verts[1].xyz[1],
+            prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+    break;
+  case GL2PS_TRIANGLE :
+    if(gl2ps->lastlinewidth != 0){
+      gl2ps->lastlinewidth = 0;
+      fprintf(gl2ps->stream, "\\pgfsetlinewidth{0.01pt}\n");
+    }
+    gl2psPrintPGFColor(prim->verts[0].rgba);
+    fprintf(gl2ps->stream,
+            "\\pgfpathmoveto{\\pgfpoint{%fpt}{%fpt}}\n"
+            "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n"
+            "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n"
+            "\\pgfpathclose\n"
+            "\\pgfusepath{fill,stroke}\n",
+            prim->verts[2].xyz[0], prim->verts[2].xyz[1],
+            prim->verts[1].xyz[0], prim->verts[1].xyz[1],
+            prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+    break;
+  case GL2PS_TEXT :
+    fprintf(gl2ps->stream, "{\n\\pgftransformshift{\\pgfpoint{%fpt}{%fpt}}\n",
+            prim->verts[0].xyz[0], prim->verts[0].xyz[1]);
+
+    if(prim->data.text->angle)
+      fprintf(gl2ps->stream, "\\pgftransformrotate{%f}{", prim->data.text->angle);
+
+    fprintf(gl2ps->stream, "\\pgfnode{rectangle}{%s}{\\fontsize{%d}{0}\\selectfont",
+            gl2psPGFTextAlignment(prim->data.text->alignment),
+            prim->data.text->fontsize);
+
+    fprintf(gl2ps->stream, "\\textcolor[rgb]{%g,%g,%g}{{%s}}",
+            prim->verts[0].rgba[0], prim->verts[0].rgba[1],
+            prim->verts[0].rgba[2], prim->data.text->str);
+
+    fprintf(gl2ps->stream, "}{}{\\pgfusepath{discard}}}\n");
+    break;
+  case GL2PS_SPECIAL :
+    /* alignment contains the format for which the special output text
+       is intended */
+    if (prim->data.text->alignment == GL2PS_PGF)
+      fprintf(gl2ps->stream, "%s\n", prim->data.text->str);
+    break;
+  default :
+    break;
+  }
+}
+
+static void gl2psPrintPGFFooter(void)
+{
+  fprintf(gl2ps->stream, "\\end{pgfpicture}\n");
+}
+
+static void gl2psPrintPGFBeginViewport(GLint viewport[4])
+{
+  GLint idx;
+  GLfloat rgba[4];
+  int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3];
+
+  glRenderMode(GL_FEEDBACK);
+
+  if(gl2ps->header){
+    gl2psPrintPGFHeader();
+    gl2ps->header = GL_FALSE;
+  }
+
+  fprintf(gl2ps->stream, "\\begin{pgfscope}\n");
+  if(gl2ps->options & GL2PS_DRAW_BACKGROUND){
+    if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){
+      glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba);
+    }
+    else{
+      glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx);
+      rgba[0] = gl2ps->colormap[idx][0];
+      rgba[1] = gl2ps->colormap[idx][1];
+      rgba[2] = gl2ps->colormap[idx][2];
+      rgba[3] = 1.0F;
+    }
+    gl2psPrintPGFColor(rgba);
+    fprintf(gl2ps->stream,
+            "\\pgfpathrectangle{\\pgfpoint{%dpt}{%dpt}}"
+            "{\\pgfpoint{%dpt}{%dpt}}\n"
+            "\\pgfusepath{fill}\n",
+            x, y, w, h);
+  }
+
+  fprintf(gl2ps->stream,
+          "\\pgfpathrectangle{\\pgfpoint{%dpt}{%dpt}}"
+          "{\\pgfpoint{%dpt}{%dpt}}\n"
+          "\\pgfusepath{clip}\n",
+          x, y, w, h);
+}
+
+static GLint gl2psPrintPGFEndViewport(void)
+{
+  GLint res;
+  res = gl2psPrintPrimitives();
+  fprintf(gl2ps->stream, "\\end{pgfscope}\n");
+  return res;
+}
+
+static void gl2psPrintPGFFinalPrimitive(void)
+{
+}
+
+/* definition of the PGF backend */
+
+static GL2PSbackend gl2psPGF = {
+  gl2psPrintPGFHeader,
+  gl2psPrintPGFFooter,
+  gl2psPrintPGFBeginViewport,
+  gl2psPrintPGFEndViewport,
+  gl2psPrintPGFPrimitive,
+  gl2psPrintPGFFinalPrimitive,
+  "tex",
+  "PGF Latex Graphics"
+};
+
+/*********************************************************************
+ *
+ * General primitive printing routine
+ *
+ *********************************************************************/
+
+/* Warning: the ordering of the backends must match the format
+   #defines in gl2ps.h */
+
+static GL2PSbackend *gl2psbackends[] = {
+  &gl2psPS,  /* 0 */
+  &gl2psEPS, /* 1 */
+  &gl2psTEX, /* 2 */
+  &gl2psPDF, /* 3 */
+  &gl2psSVG, /* 4 */
+  &gl2psPGF  /* 5 */
+};
+
+static void gl2psComputeTightBoundingBox(void *data)
+{
+  GL2PSprimitive *prim;
+  int i;
+
+  prim = *(GL2PSprimitive**)data;
+
+  for(i = 0; i < prim->numverts; i++){
+    if(prim->verts[i].xyz[0] < gl2ps->viewport[0])
+      gl2ps->viewport[0] = (GLint)prim->verts[i].xyz[0];
+    if(prim->verts[i].xyz[0] > gl2ps->viewport[2])
+      gl2ps->viewport[2] = (GLint)(prim->verts[i].xyz[0] + 0.5F);
+    if(prim->verts[i].xyz[1] < gl2ps->viewport[1])
+      gl2ps->viewport[1] = (GLint)prim->verts[i].xyz[1];
+    if(prim->verts[i].xyz[1] > gl2ps->viewport[3])
+      gl2ps->viewport[3] = (GLint)(prim->verts[i].xyz[1] + 0.5F);
+  }
+}
+
+static GLint gl2psPrintPrimitives(void)
+{
+  GL2PSbsptree *root;
+  GL2PSxyz eye = {0.0F, 0.0F, 100.0F * GL2PS_ZSCALE};
+  GLint used;
+
+  used = glRenderMode(GL_RENDER);
+
+  if(used < 0){
+    gl2psMsg(GL2PS_INFO, "OpenGL feedback buffer overflow");
+    return GL2PS_OVERFLOW;
+  }
+
+  if(used > 0)
+    gl2psParseFeedbackBuffer(used);
+
+  gl2psRescaleAndOffset();
+
+  if(gl2ps->header){
+    if(gl2psListNbr(gl2ps->primitives) &&
+       (gl2ps->options & GL2PS_TIGHT_BOUNDING_BOX)){
+      gl2ps->viewport[0] = gl2ps->viewport[1] = 100000;
+      gl2ps->viewport[2] = gl2ps->viewport[3] = -100000;
+      gl2psListAction(gl2ps->primitives, gl2psComputeTightBoundingBox);
+    }
+    (gl2psbackends[gl2ps->format]->printHeader)();
+    gl2ps->header = GL_FALSE;
+  }
+
+  if(!gl2psListNbr(gl2ps->primitives)){
+    /* empty feedback buffer and/or nothing else to print */
+    return GL2PS_NO_FEEDBACK;
+  }
+
+  switch(gl2ps->sort){
+  case GL2PS_NO_SORT :
+    gl2psListAction(gl2ps->primitives, gl2psbackends[gl2ps->format]->printPrimitive);
+    gl2psListAction(gl2ps->primitives, gl2psFreePrimitive);
+    /* reset the primitive list, waiting for the next viewport */
+    gl2psListReset(gl2ps->primitives);
+    break;
+  case GL2PS_SIMPLE_SORT :
+    gl2psListSort(gl2ps->primitives, gl2psCompareDepth);
+    if(gl2ps->options & GL2PS_OCCLUSION_CULL){
+      gl2psListActionInverse(gl2ps->primitives, gl2psAddInImageTree);
+      gl2psFreeBspImageTree(&gl2ps->imagetree);
+    }
+    gl2psListAction(gl2ps->primitives, gl2psbackends[gl2ps->format]->printPrimitive);
+    gl2psListAction(gl2ps->primitives, gl2psFreePrimitive);
+    /* reset the primitive list, waiting for the next viewport */
+    gl2psListReset(gl2ps->primitives);
+    break;
+  case GL2PS_BSP_SORT :
+    root = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree));
+    gl2psBuildBspTree(root, gl2ps->primitives);
+    if(GL_TRUE == gl2ps->boundary) gl2psBuildPolygonBoundary(root);
+    if(gl2ps->options & GL2PS_OCCLUSION_CULL){
+      gl2psTraverseBspTree(root, eye, -GL2PS_EPSILON, gl2psLess,
+                           gl2psAddInImageTree, 1);
+      gl2psFreeBspImageTree(&gl2ps->imagetree);
+    }
+    gl2psTraverseBspTree(root, eye, GL2PS_EPSILON, gl2psGreater,
+                         gl2psbackends[gl2ps->format]->printPrimitive, 0);
+    gl2psFreeBspTree(&root);
+    /* reallocate the primitive list (it's been deleted by
+       gl2psBuildBspTree) in case there is another viewport */
+    gl2ps->primitives = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*));
+    break;
+  }
+  gl2psbackends[gl2ps->format]->printFinalPrimitive();
+
+  return GL2PS_SUCCESS;
+}
+
+/*********************************************************************
+ *
+ * Public routines
+ *
+ *********************************************************************/
+
+GL2PSDLL_API GLint gl2psBeginPage(const char *title, const char *producer,
+                                  GLint viewport[4], GLint format, GLint sort,
+                                  GLint options, GLint colormode,
+                                  GLint colorsize, GL2PSrgba *colormap,
+                                  GLint nr, GLint ng, GLint nb, GLint buffersize,
+                                  FILE *stream, const char *filename)
+{
+  GLint idx;
+  int i;
+
+  if(gl2ps){
+    gl2psMsg(GL2PS_ERROR, "gl2psBeginPage called in wrong program state");
+    return GL2PS_ERROR;
+  }
+
+  gl2ps = (GL2PScontext*)gl2psMalloc(sizeof(GL2PScontext));
+
+  if(format >= 0 && format < (GLint)(sizeof(gl2psbackends) / sizeof(gl2psbackends[0]))){
+    gl2ps->format = format;
+  }
+  else {
+    gl2psMsg(GL2PS_ERROR, "Unknown output format: %d", format);
+    gl2psFree(gl2ps);
+    gl2ps = NULL;
+    return GL2PS_ERROR;
+  }
+
+  switch(sort){
+  case GL2PS_NO_SORT :
+  case GL2PS_SIMPLE_SORT :
+  case GL2PS_BSP_SORT :
+    gl2ps->sort = sort;
+    break;
+  default :
+    gl2psMsg(GL2PS_ERROR, "Unknown sorting algorithm: %d", sort);
+    gl2psFree(gl2ps);
+    gl2ps = NULL;
+    return GL2PS_ERROR;
+  }
+
+  if(stream){
+    gl2ps->stream = stream;
+  }
+  else{
+    gl2psMsg(GL2PS_ERROR, "Bad file pointer");
+    gl2psFree(gl2ps);
+    gl2ps = NULL;
+    return GL2PS_ERROR;
+  }
+
+  gl2ps->header = GL_TRUE;
+  gl2ps->maxbestroot = 10;
+  gl2ps->options = options;
+  gl2ps->compress = NULL;
+  gl2ps->imagemap_head = NULL;
+  gl2ps->imagemap_tail = NULL;
+
+  if(gl2ps->options & GL2PS_USE_CURRENT_VIEWPORT){
+    glGetIntegerv(GL_VIEWPORT, gl2ps->viewport);
+  }
+  else{
+    for(i = 0; i < 4; i++){
+      gl2ps->viewport[i] = viewport[i];
+    }
+  }
+
+  if(!gl2ps->viewport[2] || !gl2ps->viewport[3]){
+    gl2psMsg(GL2PS_ERROR, "Incorrect viewport (x=%d, y=%d, width=%d, height=%d)",
+             gl2ps->viewport[0], gl2ps->viewport[1],
+             gl2ps->viewport[2], gl2ps->viewport[3]);
+    gl2psFree(gl2ps);
+    gl2ps = NULL;
+    return GL2PS_ERROR;
+  }
+
+  gl2ps->threshold[0] = nr ? 1.0F / (GLfloat)nr : 0.064F;
+  gl2ps->threshold[1] = ng ? 1.0F / (GLfloat)ng : 0.034F;
+  gl2ps->threshold[2] = nb ? 1.0F / (GLfloat)nb : 0.100F;
+  gl2ps->colormode = colormode;
+  gl2ps->buffersize = buffersize > 0 ? buffersize : 2048 * 2048;
+  for(i = 0; i < 3; i++){
+    gl2ps->lastvertex.xyz[i] = -1.0F;
+  }
+  for(i = 0; i < 4; i++){
+    gl2ps->lastvertex.rgba[i] = -1.0F;
+    gl2ps->lastrgba[i] = -1.0F;
+  }
+  gl2ps->lastlinewidth = -1.0F;
+  gl2ps->lastpattern = 0;
+  gl2ps->lastfactor = 0;
+  gl2ps->imagetree = NULL;
+  gl2ps->primitivetoadd = NULL;
+  gl2ps->zerosurfacearea = GL_FALSE;
+  gl2ps->pdfprimlist = NULL;
+  gl2ps->pdfgrouplist = NULL;
+  gl2ps->xreflist = NULL;
+
+  /* get default blending mode from current OpenGL state (enabled by
+     default for SVG) */
+  gl2ps->blending = (gl2ps->format == GL2PS_SVG) ? GL_TRUE : glIsEnabled(GL_BLEND);
+  glGetIntegerv(GL_BLEND_SRC, &gl2ps->blendfunc[0]);
+  glGetIntegerv(GL_BLEND_DST, &gl2ps->blendfunc[1]);
+
+  if(gl2ps->colormode == GL_RGBA){
+    gl2ps->colorsize = 0;
+    gl2ps->colormap = NULL;
+    glGetFloatv(GL_COLOR_CLEAR_VALUE, gl2ps->bgcolor);
+  }
+  else if(gl2ps->colormode == GL_COLOR_INDEX){
+    if(!colorsize || !colormap){
+      gl2psMsg(GL2PS_ERROR, "Missing colormap for GL_COLOR_INDEX rendering");
+      gl2psFree(gl2ps);
+      gl2ps = NULL;
+      return GL2PS_ERROR;
+    }
+    gl2ps->colorsize = colorsize;
+    gl2ps->colormap = (GL2PSrgba*)gl2psMalloc(gl2ps->colorsize * sizeof(GL2PSrgba));
+    memcpy(gl2ps->colormap, colormap, gl2ps->colorsize * sizeof(GL2PSrgba));
+    glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx);
+    gl2ps->bgcolor[0] = gl2ps->colormap[idx][0];
+    gl2ps->bgcolor[1] = gl2ps->colormap[idx][1];
+    gl2ps->bgcolor[2] = gl2ps->colormap[idx][2];
+    gl2ps->bgcolor[3] = 1.0F;
+  }
+  else{
+    gl2psMsg(GL2PS_ERROR, "Unknown color mode in gl2psBeginPage");
+    gl2psFree(gl2ps);
+    gl2ps = NULL;
+    return GL2PS_ERROR;
+  }
+
+  if(!title){
+    gl2ps->title = (char*)gl2psMalloc(sizeof(char));
+    gl2ps->title[0] = '\0';
+  }
+  else{
+    gl2ps->title = (char*)gl2psMalloc((strlen(title)+1)*sizeof(char));
+    strcpy(gl2ps->title, title);
+  }
+
+  if(!producer){
+    gl2ps->producer = (char*)gl2psMalloc(sizeof(char));
+    gl2ps->producer[0] = '\0';
+  }
+  else{
+    gl2ps->producer = (char*)gl2psMalloc((strlen(producer)+1)*sizeof(char));
+    strcpy(gl2ps->producer, producer);
+  }
+
+  if(!filename){
+    gl2ps->filename = (char*)gl2psMalloc(sizeof(char));
+    gl2ps->filename[0] = '\0';
+  }
+  else{
+    gl2ps->filename = (char*)gl2psMalloc((strlen(filename)+1)*sizeof(char));
+    strcpy(gl2ps->filename, filename);
+  }
+
+  gl2ps->primitives = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*));
+  gl2ps->auxprimitives = gl2psListCreate(100, 100, sizeof(GL2PSprimitive*));
+  gl2ps->feedback = (GLfloat*)gl2psMalloc(gl2ps->buffersize * sizeof(GLfloat));
+  glFeedbackBuffer(gl2ps->buffersize, GL_3D_COLOR, gl2ps->feedback);
+  glRenderMode(GL_FEEDBACK);
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psEndPage(void)
+{
+  GLint res;
+
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  res = gl2psPrintPrimitives();
+
+  if(res != GL2PS_OVERFLOW)
+    (gl2psbackends[gl2ps->format]->printFooter)();
+
+  fflush(gl2ps->stream);
+
+  gl2psListDelete(gl2ps->primitives);
+  gl2psListDelete(gl2ps->auxprimitives);
+  gl2psFreeImagemap(gl2ps->imagemap_head);
+  gl2psFree(gl2ps->colormap);
+  gl2psFree(gl2ps->title);
+  gl2psFree(gl2ps->producer);
+  gl2psFree(gl2ps->filename);
+  gl2psFree(gl2ps->feedback);
+  gl2psFree(gl2ps);
+  gl2ps = NULL;
+
+  return res;
+}
+
+GL2PSDLL_API GLint gl2psBeginViewport(GLint viewport[4])
+{
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  (gl2psbackends[gl2ps->format]->beginViewport)(viewport);
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psEndViewport(void)
+{
+  GLint res;
+
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  res = (gl2psbackends[gl2ps->format]->endViewport)();
+
+  /* reset last used colors, line widths */
+  gl2ps->lastlinewidth = -1.0F;
+
+  return res;
+}
+
+GL2PSDLL_API GLint gl2psTextOptColor(const char *str, const char *fontname,
+                                     GLshort fontsize, GLint alignment, GLfloat angle,
+                                     GL2PSrgba color)
+{
+  return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, alignment, angle,
+                      color);
+}
+
+GL2PSDLL_API GLint gl2psTextOpt(const char *str, const char *fontname,
+                                GLshort fontsize, GLint alignment, GLfloat angle)
+{
+  return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, alignment, angle, NULL);
+}
+
+GL2PSDLL_API GLint gl2psText(const char *str, const char *fontname, GLshort fontsize)
+{
+  return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, GL2PS_TEXT_BL, 0.0F,
+                      NULL);
+}
+
+GL2PSDLL_API GLint gl2psSpecial(GLint format, const char *str)
+{
+  return gl2psAddText(GL2PS_SPECIAL, str, "", 0, format, 0.0F, NULL);
+}
+
+GL2PSDLL_API GLint gl2psDrawPixels(GLsizei width, GLsizei height,
+                                   GLint xorig, GLint yorig,
+                                   GLenum format, GLenum type,
+                                   const void *pixels)
+{
+  int size, i;
+  const GLfloat *piv;
+  GLfloat pos[4], zoom_x, zoom_y;
+  GL2PSprimitive *prim;
+  GLboolean valid;
+
+  if(!gl2ps || !pixels) return GL2PS_UNINITIALIZED;
+
+  if((width <= 0) || (height <= 0)) return GL2PS_ERROR;
+
+  if(gl2ps->options & GL2PS_NO_PIXMAP) return GL2PS_SUCCESS;
+
+  if((format != GL_RGB && format != GL_RGBA) || type != GL_FLOAT){
+    gl2psMsg(GL2PS_ERROR, "gl2psDrawPixels only implemented for "
+             "GL_RGB/GL_RGBA, GL_FLOAT pixels");
+    return GL2PS_ERROR;
+  }
+
+  glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid);
+  if(GL_FALSE == valid) return GL2PS_SUCCESS; /* the primitive is culled */
+
+  glGetFloatv(GL_CURRENT_RASTER_POSITION, pos);
+  glGetFloatv(GL_ZOOM_X, &zoom_x);
+  glGetFloatv(GL_ZOOM_Y, &zoom_y);
+
+  prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive));
+  prim->type = GL2PS_PIXMAP;
+  prim->boundary = 0;
+  prim->numverts = 1;
+  prim->verts = (GL2PSvertex*)gl2psMalloc(sizeof(GL2PSvertex));
+  prim->verts[0].xyz[0] = pos[0] + xorig;
+  prim->verts[0].xyz[1] = pos[1] + yorig;
+  prim->verts[0].xyz[2] = pos[2];
+  prim->culled = 0;
+  prim->offset = 0;
+  prim->pattern = 0;
+  prim->factor = 0;
+  prim->width = 1;
+  glGetFloatv(GL_CURRENT_RASTER_COLOR, prim->verts[0].rgba);
+  prim->data.image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage));
+  prim->data.image->width = width;
+  prim->data.image->height = height;
+  prim->data.image->zoom_x = zoom_x;
+  prim->data.image->zoom_y = zoom_y;
+  prim->data.image->format = format;
+  prim->data.image->type = type;
+
+  switch(format){
+  case GL_RGBA:
+    if(gl2ps->options & GL2PS_NO_BLENDING || !gl2ps->blending){
+      /* special case: blending turned off */
+      prim->data.image->format = GL_RGB;
+      size = height * width * 3;
+      prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat));
+      piv = (const GLfloat*)pixels;
+      for(i = 0; i < size; ++i, ++piv){
+        prim->data.image->pixels[i] = *piv;
+        if(!((i + 1) % 3))
+          ++piv;
+      }
+    }
+    else{
+      size = height * width * 4;
+      prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat));
+      memcpy(prim->data.image->pixels, pixels, size * sizeof(GLfloat));
+    }
+    break;
+  case GL_RGB:
+  default:
+    size = height * width * 3;
+    prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat));
+    memcpy(prim->data.image->pixels, pixels, size * sizeof(GLfloat));
+    break;
+  }
+
+  gl2psListAdd(gl2ps->auxprimitives, &prim);
+  glPassThrough(GL2PS_DRAW_PIXELS_TOKEN);
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psDrawImageMap(GLsizei width, GLsizei height,
+                                     const GLfloat position[3],
+                                     const unsigned char *imagemap){
+  int size, i;
+  int sizeoffloat = sizeof(GLfloat);
+
+  if(!gl2ps || !imagemap) return GL2PS_UNINITIALIZED;
+
+  if((width <= 0) || (height <= 0)) return GL2PS_ERROR;
+
+  size = height + height * ((width - 1) / 8);
+  glPassThrough(GL2PS_IMAGEMAP_TOKEN);
+  glBegin(GL_POINTS);
+  glVertex3f(position[0], position[1],position[2]);
+  glEnd();
+  glPassThrough((GLfloat)width);
+  glPassThrough((GLfloat)height);
+  for(i = 0; i < size; i += sizeoffloat){
+    const float *value = (const float*)imagemap;
+    glPassThrough(*value);
+    imagemap += sizeoffloat;
+  }
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psEnable(GLint mode)
+{
+  GLint tmp;
+
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  switch(mode){
+  case GL2PS_POLYGON_OFFSET_FILL :
+    glPassThrough(GL2PS_BEGIN_OFFSET_TOKEN);
+    glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &gl2ps->offset[0]);
+    glGetFloatv(GL_POLYGON_OFFSET_UNITS, &gl2ps->offset[1]);
+    break;
+  case GL2PS_POLYGON_BOUNDARY :
+    glPassThrough(GL2PS_BEGIN_BOUNDARY_TOKEN);
+    break;
+  case GL2PS_LINE_STIPPLE :
+    glPassThrough(GL2PS_BEGIN_STIPPLE_TOKEN);
+    glGetIntegerv(GL_LINE_STIPPLE_PATTERN, &tmp);
+    glPassThrough((GLfloat)tmp);
+    glGetIntegerv(GL_LINE_STIPPLE_REPEAT, &tmp);
+    glPassThrough((GLfloat)tmp);
+    break;
+  case GL2PS_BLEND :
+    glPassThrough(GL2PS_BEGIN_BLEND_TOKEN);
+    break;
+  default :
+    gl2psMsg(GL2PS_WARNING, "Unknown mode in gl2psEnable: %d", mode);
+    return GL2PS_WARNING;
+  }
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psDisable(GLint mode)
+{
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  switch(mode){
+  case GL2PS_POLYGON_OFFSET_FILL :
+    glPassThrough(GL2PS_END_OFFSET_TOKEN);
+    break;
+  case GL2PS_POLYGON_BOUNDARY :
+    glPassThrough(GL2PS_END_BOUNDARY_TOKEN);
+    break;
+  case GL2PS_LINE_STIPPLE :
+    glPassThrough(GL2PS_END_STIPPLE_TOKEN);
+    break;
+  case GL2PS_BLEND :
+    glPassThrough(GL2PS_END_BLEND_TOKEN);
+    break;
+  default :
+    gl2psMsg(GL2PS_WARNING, "Unknown mode in gl2psDisable: %d", mode);
+    return GL2PS_WARNING;
+  }
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psPointSize(GLfloat value)
+{
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  glPassThrough(GL2PS_POINT_SIZE_TOKEN);
+  glPassThrough(value);
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psLineWidth(GLfloat value)
+{
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  glPassThrough(GL2PS_LINE_WIDTH_TOKEN);
+  glPassThrough(value);
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psBlendFunc(GLenum sfactor, GLenum dfactor)
+{
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  if(GL_FALSE == gl2psSupportedBlendMode(sfactor, dfactor))
+    return GL2PS_WARNING;
+
+  glPassThrough(GL2PS_SRC_BLEND_TOKEN);
+  glPassThrough((GLfloat)sfactor);
+  glPassThrough(GL2PS_DST_BLEND_TOKEN);
+  glPassThrough((GLfloat)dfactor);
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psSetOptions(GLint options)
+{
+  if(!gl2ps) return GL2PS_UNINITIALIZED;
+
+  gl2ps->options = options;
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API GLint gl2psGetOptions(GLint *options)
+{
+  if(!gl2ps) {
+    *options = 0;
+    return GL2PS_UNINITIALIZED;
+  }
+
+  *options = gl2ps->options;
+
+  return GL2PS_SUCCESS;
+}
+
+GL2PSDLL_API const char *gl2psGetFileExtension(GLint format)
+{
+  if(format >= 0 && format < (GLint)(sizeof(gl2psbackends) / sizeof(gl2psbackends[0])))
+    return gl2psbackends[format]->file_extension;
+  else
+    return "Unknown format";
+}
+
+GL2PSDLL_API const char *gl2psGetFormatDescription(GLint format)
+{
+  if(format >= 0 && format < (GLint)(sizeof(gl2psbackends) / sizeof(gl2psbackends[0])))
+    return gl2psbackends[format]->description;
+  else
+    return "Unknown format";
+}
+
+GL2PSDLL_API GLint gl2psGetFileFormat()
+{
+  return gl2ps->format;
+}
diff --git a/src/gl2ps.h b/src/gl2ps.h
new file mode 100644
index 0000000..978c2f1
--- /dev/null
+++ b/src/gl2ps.h
@@ -0,0 +1,207 @@
+/*
+ * GL2PS, an OpenGL to PostScript Printing Library
+ * Copyright (C) 1999-2012 C. Geuzaine
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of either:
+ *
+ * a) the GNU Library General Public License as published by the Free
+ * Software Foundation, either version 2 of the License, or (at your
+ * option) any later version; or
+ *
+ * b) the GL2PS License as published by Christophe Geuzaine, either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
+ * the GNU Library General Public License or the GL2PS License for
+ * more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with this library in the file named "COPYING.LGPL";
+ * if not, write to the Free Software Foundation, Inc., 51 Franklin
+ * Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * You should have received a copy of the GL2PS License with this
+ * library in the file named "COPYING.GL2PS"; if not, I will be glad
+ * to provide one.
+ *
+ * For the latest info about gl2ps and a full list of contributors,
+ * see http://www.geuz.org/gl2ps/.
+ *
+ * Please report all bugs and problems to <gl2ps at geuz.org>.
+ */
+
+#ifndef __GL2PS_H__
+#define __GL2PS_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+
+/* Define GL2PSDLL at compile time to build a Windows DLL */
+
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
+#  if defined(_MSC_VER)
+#    pragma warning(disable:4115)
+#    pragma warning(disable:4996)
+#  endif
+#  include <windows.h>
+#  if defined(GL2PSDLL)
+#    if defined(GL2PSDLL_EXPORTS)
+#      define GL2PSDLL_API __declspec(dllexport)
+#    else
+#      define GL2PSDLL_API __declspec(dllimport)
+#    endif
+#  else
+#    define GL2PSDLL_API
+#  endif
+#else
+#  define GL2PSDLL_API
+#endif
+
+#if defined(__APPLE__) || defined(HAVE_OPENGL_GL_H)
+#  include <OpenGL/gl.h>
+#else
+#  include <GL/gl.h>
+#endif
+
+/* Support for compressed PostScript/PDF/SVG and for embedded PNG
+   images in SVG */
+
+#if defined(HAVE_ZLIB) || defined(HAVE_LIBZ)
+#  define GL2PS_HAVE_ZLIB
+#  if defined(HAVE_LIBPNG) || defined(HAVE_PNG)
+#    define GL2PS_HAVE_LIBPNG
+#  endif
+#endif
+
+#if defined(HAVE_NO_VSNPRINTF)
+#  define GL2PS_HAVE_NO_VSNPRINTF
+#endif
+
+/* Version number */
+
+#define GL2PS_MAJOR_VERSION 1
+#define GL2PS_MINOR_VERSION 3
+#define GL2PS_PATCH_VERSION 8
+#define GL2PS_EXTRA_VERSION ""
+
+#define GL2PS_VERSION (GL2PS_MAJOR_VERSION + \
+                       0.01 * GL2PS_MINOR_VERSION + \
+                       0.0001 * GL2PS_PATCH_VERSION)
+
+#define GL2PS_COPYRIGHT "(C) 1999-2012 C. Geuzaine"
+
+/* Output file formats (the values and the ordering are important!) */
+
+#define GL2PS_PS  0
+#define GL2PS_EPS 1
+#define GL2PS_TEX 2
+#define GL2PS_PDF 3
+#define GL2PS_SVG 4
+#define GL2PS_PGF 5
+
+/* Sorting algorithms */
+
+#define GL2PS_NO_SORT     1
+#define GL2PS_SIMPLE_SORT 2
+#define GL2PS_BSP_SORT    3
+
+/* Message levels and error codes */
+
+#define GL2PS_SUCCESS       0
+#define GL2PS_INFO          1
+#define GL2PS_WARNING       2
+#define GL2PS_ERROR         3
+#define GL2PS_NO_FEEDBACK   4
+#define GL2PS_OVERFLOW      5
+#define GL2PS_UNINITIALIZED 6
+
+/* Options for gl2psBeginPage */
+
+#define GL2PS_NONE                 0
+#define GL2PS_DRAW_BACKGROUND      (1<<0)
+#define GL2PS_SIMPLE_LINE_OFFSET   (1<<1)
+#define GL2PS_SILENT               (1<<2)
+#define GL2PS_BEST_ROOT            (1<<3)
+#define GL2PS_OCCLUSION_CULL       (1<<4)
+#define GL2PS_NO_TEXT              (1<<5)
+#define GL2PS_LANDSCAPE            (1<<6)
+#define GL2PS_NO_PS3_SHADING       (1<<7)
+#define GL2PS_NO_PIXMAP            (1<<8)
+#define GL2PS_USE_CURRENT_VIEWPORT (1<<9)
+#define GL2PS_COMPRESS             (1<<10)
+#define GL2PS_NO_BLENDING          (1<<11)
+#define GL2PS_TIGHT_BOUNDING_BOX   (1<<12)
+
+/* Arguments for gl2psEnable/gl2psDisable */
+
+#define GL2PS_POLYGON_OFFSET_FILL 1
+#define GL2PS_POLYGON_BOUNDARY    2
+#define GL2PS_LINE_STIPPLE        3
+#define GL2PS_BLEND               4
+
+/* Text alignment (o=raster position; default mode is BL):
+   +---+ +---+ +---+ +---+ +---+ +---+ +-o-+ o---+ +---o
+   | o | o   | |   o |   | |   | |   | |   | |   | |   |
+   +---+ +---+ +---+ +-o-+ o---+ +---o +---+ +---+ +---+
+    C     CL    CR    B     BL    BR    T     TL    TR */
+
+#define GL2PS_TEXT_C  1
+#define GL2PS_TEXT_CL 2
+#define GL2PS_TEXT_CR 3
+#define GL2PS_TEXT_B  4
+#define GL2PS_TEXT_BL 5
+#define GL2PS_TEXT_BR 6
+#define GL2PS_TEXT_T  7
+#define GL2PS_TEXT_TL 8
+#define GL2PS_TEXT_TR 9
+
+typedef GLfloat GL2PSrgba[4];
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+GL2PSDLL_API GLint gl2psBeginPage(const char *title, const char *producer,
+                                  GLint viewport[4], GLint format, GLint sort,
+                                  GLint options, GLint colormode,
+                                  GLint colorsize, GL2PSrgba *colormap,
+                                  GLint nr, GLint ng, GLint nb, GLint buffersize,
+                                  FILE *stream, const char *filename);
+GL2PSDLL_API GLint gl2psEndPage(void);
+GL2PSDLL_API GLint gl2psSetOptions(GLint options);
+GL2PSDLL_API GLint gl2psGetOptions(GLint *options);
+GL2PSDLL_API GLint gl2psBeginViewport(GLint viewport[4]);
+GL2PSDLL_API GLint gl2psEndViewport(void);
+GL2PSDLL_API GLint gl2psText(const char *str, const char *fontname,
+                             GLshort fontsize);
+GL2PSDLL_API GLint gl2psTextOpt(const char *str, const char *fontname,
+                                GLshort fontsize, GLint align, GLfloat angle);
+GL2PSDLL_API GLint gl2psTextOptColor(const char *str, const char *fontname,
+                                     GLshort fontsize, GLint align, GLfloat angle,
+                                     GL2PSrgba color);
+GL2PSDLL_API GLint gl2psSpecial(GLint format, const char *str);
+GL2PSDLL_API GLint gl2psDrawPixels(GLsizei width, GLsizei height,
+                                   GLint xorig, GLint yorig,
+                                   GLenum format, GLenum type, const void *pixels);
+GL2PSDLL_API GLint gl2psEnable(GLint mode);
+GL2PSDLL_API GLint gl2psDisable(GLint mode);
+GL2PSDLL_API GLint gl2psPointSize(GLfloat value);
+GL2PSDLL_API GLint gl2psLineWidth(GLfloat value);
+GL2PSDLL_API GLint gl2psBlendFunc(GLenum sfactor, GLenum dfactor);
+
+/* undocumented */
+GL2PSDLL_API GLint gl2psDrawImageMap(GLsizei width, GLsizei height,
+                                     const GLfloat position[3],
+                                     const unsigned char *imagemap);
+GL2PSDLL_API const char *gl2psGetFileExtension(GLint format);
+GL2PSDLL_API const char *gl2psGetFormatDescription(GLint format);
+GL2PSDLL_API GLint gl2psGetFileFormat();
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* __GL2PS_H__ */
diff --git a/src/glErrors.cpp b/src/glErrors.cpp
new file mode 100644
index 0000000..b113964
--- /dev/null
+++ b/src/glErrors.cpp
@@ -0,0 +1,38 @@
+// 
+// This file is part of RGL.
+//
+
+#include "opengl.h"
+#include "R.h"
+#include "platform.h"
+
+namespace rgl {
+int SaveErrnum = GL_NO_ERROR;
+}
+
+using namespace rgl;
+
+static const char * SaveFile;
+static int SaveLine;
+
+void saveGLerror(const char * file, int line)
+{
+  GLenum errnum;
+  if (SaveErrnum == GL_NO_ERROR && (errnum = glGetError()) != GL_NO_ERROR) {
+    SaveErrnum = errnum;
+    SaveFile = file;
+    SaveLine = line;
+  }
+}
+
+void checkGLerror(const char * file, int line)
+{
+  saveGLerror(file, line);
+  if (SaveErrnum != GL_NO_ERROR) {
+    int err = SaveErrnum;
+    SaveErrnum = GL_NO_ERROR;
+    while (glGetError() != GL_NO_ERROR) {} /* clear other errors, if any */
+    error("OpenGL error at %s:%d: %s", SaveFile, SaveLine, gluErrorString(err));
+  }
+}
+
diff --git a/src/glgui.cpp b/src/glgui.cpp
new file mode 100644
index 0000000..2ff8836
--- /dev/null
+++ b/src/glgui.cpp
@@ -0,0 +1,193 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: glgui.cpp 1366 2015-10-05 15:25:06Z murdoch $
+
+#include <cstdio>
+#ifdef HAVE_FREETYPE
+#include "FTGL/ftgl.h"
+#include "R.h"
+#endif
+#include "types.h"
+#include "glgui.h"
+#include "gl2ps.h"
+#include "opengl.h"
+#include "RenderContext.h"
+#include "subscene.h"
+#include "platform.h"
+
+using namespace rgl;
+
+//
+// CLASS
+//   GLFont
+//
+
+GLboolean GLFont::justify(double width, double height, double adjx, double adjy, const RenderContext& rc) {
+  GLdouble pos[4], pos2[4];
+  double basex = 0.0, basey = 0.0, scaling = 1.0;
+  GLboolean valid;
+  gl2ps_centering = GL2PS_TEXT_BL;
+  
+  if (adjx > 0) {
+
+    if (rc.gl2psActive > GL2PS_NONE) scaling = GL2PS_SCALING;
+     
+    if ( adjx > 0.25 && rc.gl2psActive == GL2PS_POSITIONAL) {
+      if (adjx < 0.75) {
+        basex = 0.5;
+        gl2ps_centering = GL2PS_TEXT_B;
+      } else {
+        basex = 1.0;
+        gl2ps_centering = GL2PS_TEXT_BR;
+      }
+    }
+  }  
+
+  if ((adjx != basex) || (adjy != basey)) {
+    glGetDoublev(GL_CURRENT_RASTER_POSITION, pos);    
+    pos[0] = pos[0] - scaling*width*(adjx-basex); 
+    pos[1] = pos[1] - scaling*height*(adjy-basey);
+    GLint pviewport[4] = {rc.subscene->pviewport.x, 
+                          rc.subscene->pviewport.y, 
+                          rc.subscene->pviewport.width, 
+                          rc.subscene->pviewport.height};
+    GLdouble modelMatrix[16], projMatrix[16];
+    rc.subscene->modelMatrix.getData(modelMatrix);
+    rc.subscene->projMatrix.getData(projMatrix);
+    gluUnProject( pos[0], pos[1], pos[2], modelMatrix, projMatrix, pviewport, pos2, pos2 + 1, pos2 + 2);
+    glRasterPos3dv(pos2);
+  }
+  
+  glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid);
+  return valid;
+}
+
+//
+// CLASS
+//   GLBitmapFont
+//
+
+GLBitmapFont::~GLBitmapFont() {
+    delete [] widths;
+    if (nglyph) glDeleteLists(listBase+GL_BITMAP_FONT_FIRST_GLYPH, nglyph);
+}
+
+double GLBitmapFont::width(const char* text) {
+  double result = 0.0;
+  for(int i=0; text[i]; i++) {
+    char c;
+    if ((int)(text[i]) >= (int)firstGlyph && (c = text[i] - firstGlyph) < (int)nglyph)
+      result += widths[(int)c];
+  }
+  return result;
+}
+
+double GLBitmapFont::width(const wchar_t* text) {
+  double result = 0.0;
+  for(int i=0; text[i]; i++) {
+    wchar_t c;
+    if (text[i] >= firstGlyph && (c = text[i] - firstGlyph) < nglyph)
+      result += widths[c];  
+  }    
+  return result;
+}
+  
+double GLBitmapFont::height() {
+  return ascent;
+}
+
+bool GLBitmapFont::valid(const char* text) {
+  for (int i=0; text[i]; i++)
+    if ((int)text[i] < (int)firstGlyph || (int)text[i] - (int)firstGlyph >= (int)nglyph)
+      return false;
+  return true;
+}
+
+void GLBitmapFont::draw(const char* text, int length, 
+                        double adjx, double adjy, const RenderContext& rc) {
+    
+  if (justify(width(text), height(), adjx, adjy, rc)) {
+    if (rc.gl2psActive == GL2PS_NONE) {
+      glListBase(listBase);
+      glCallLists(length, GL_UNSIGNED_BYTE, text);
+    } else
+      gl2psTextOpt(text, GL2PS_FONT, GL2PS_FONTSIZE*cex, gl2ps_centering, 0.0);
+  }
+}
+
+void GLBitmapFont::draw(const wchar_t* text, int length, 
+                        double adjx, double adjy, const RenderContext& rc) {
+  
+  if (justify(width(text), height(), adjx, adjy, rc)) {
+    GLenum type = sizeof(wchar_t) == 4 ? GL_UNSIGNED_INT :
+                  sizeof(wchar_t) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE ;
+    if (rc.gl2psActive == GL2PS_NONE) {
+      glListBase(listBase);
+      glCallLists(length, type, text);
+    }
+  // gl2ps doesn't support wchar_t?  Should convert?
+  }
+}
+
+#ifdef HAVE_FREETYPE
+
+GLFTFont::GLFTFont(const char* in_family, int in_style, double in_cex, const char* in_fontname) 
+: GLFont(in_family, in_style, in_cex, in_fontname, true)
+{
+  font=new FTGLPixmapFont(fontname);
+  if (font->Error()) { 
+    errmsg = "Cannot create Freetype font";
+    delete font;
+    font = NULL;
+  } else {
+    unsigned int size = 16*cex + 0.5;
+    if (size<1) { size=1; }
+    if (!font->FaceSize(size)) {
+      errmsg = "Cannot create Freetype font of requested size";
+      delete font;
+      font = NULL;
+    }
+  }
+/*  font->CharMap(ft_encoding_unicode);
+  if (font->Error()) {
+    error("Cannot set unicode encoding."); 
+  }*/
+
+}
+
+GLFTFont::~GLFTFont()
+{
+  if (font) delete font;
+}
+
+double GLFTFont::width(const char* text) {
+  return font->Advance(text);
+}
+
+double GLFTFont::width(const wchar_t* text) {
+  return font->Advance(text);
+}
+  
+double GLFTFont::height() {
+  return font->Ascender();
+}
+
+void GLFTFont::draw(const char* text, int length, double adjx, double adjy, const RenderContext& rc) {
+  
+  if ( justify( width(text), height(), adjx, adjy, rc ) ) {
+    if (rc.gl2psActive == GL2PS_NONE)
+      font->Render(text);
+    else
+      gl2psTextOpt(text, GL2PS_FONT, GL2PS_FONTSIZE*cex, gl2ps_centering, 0.0);
+  }
+}
+
+void GLFTFont::draw(const wchar_t* text, int length, double adjx, double adjy, const RenderContext& rc) {
+  if ( justify( width(text), height(), adjx, adjy, rc ) ) {
+    if (rc.gl2psActive == GL2PS_NONE) 
+      font->Render(text);
+  }      
+}
+      
+#endif
diff --git a/src/glgui.h b/src/glgui.h
new file mode 100644
index 0000000..a06db27
--- /dev/null
+++ b/src/glgui.h
@@ -0,0 +1,173 @@
+#ifndef GL_GUI_H
+#define GL_GUI_H
+
+// C++ header
+// This file is part of rgl
+//
+// $Id: glgui.h 1115 2014-07-18 13:51:22Z murdoch $
+
+#include "opengl.h"
+#include <vector>
+#ifdef HAVE_FREETYPE
+#include "FTGL/ftgl.h"
+#endif
+
+#include "RenderContext.h"
+
+namespace rgl {
+
+// CLASS
+//   GLFont
+//
+
+class GLFont
+{
+public:
+  GLFont(const char* in_family, int in_style, double in_cex, 
+         const char* in_fontname, bool in_useFreeType):
+  style(in_style), cex(in_cex), useFreeType(in_useFreeType) 
+  {
+    family = new char[strlen(in_family) + 1];
+    memcpy(family, in_family, strlen(in_family) + 1);
+    fontname = new char[strlen(in_fontname) + 1];
+    memcpy(fontname, in_fontname, strlen(in_fontname) + 1);    
+  };
+  
+  virtual ~GLFont()
+  {
+    delete [] family;
+    delete [] fontname;
+  }
+  
+  virtual void draw(const char* text, int length, double adjx, double adjy, const RenderContext& rc) = 0;
+  virtual void draw(const wchar_t* text, int length, double adjx, double adjy, const RenderContext& rc) = 0;
+  virtual double width(const char* text) = 0;
+  virtual double width(const wchar_t* text) = 0;
+  virtual double height() = 0;
+  virtual bool valid(const char* text) { return true; };
+  // justify returns false if justification puts the text outside the viewport
+  GLboolean justify(double width, double height, double adjx, double adjy, const RenderContext& rc);
+  char* family;
+  int style;
+  double cex;
+  char* fontname;
+  bool useFreeType;
+  int gl2ps_centering;
+private:
+  GLFont(const GLFont &);
+  GLFont &operator=(const GLFont &);
+};
+
+#define GL_BITMAP_FONT_FIRST_GLYPH  32
+#define GL_BITMAP_FONT_LAST_GLYPH   127
+#define GL_BITMAP_FONT_COUNT       (GL_BITMAP_FONT_LAST_GLYPH-GL_BITMAP_FONT_FIRST_GLYPH+1)
+
+#define GL2PS_FONT 	"Helvetica"
+#define GL2PS_FONTSIZE 	12
+#define GL2PS_SCALING   0.8
+
+#define GL2PS_NONE	 0
+#define GL2PS_LEFT_ONLY	 1
+#define GL2PS_POSITIONAL 2
+
+//
+// CLASS
+//   GLBitmapFont
+//
+
+class GLBitmapFont : public GLFont
+{
+public:
+  // Most initialization of this object is done by the system-specific driver
+  GLBitmapFont(const char* in_family, int in_style, double in_cex, const char* in_fontname): 
+    GLFont(in_family, in_style, in_cex, in_fontname, false) {};
+  ~GLBitmapFont();
+
+  void draw(const char* text, int length, double adjx, double adjy, const RenderContext& rc);
+  void draw(const wchar_t* text, int length, double adjx, double adjy, const RenderContext& rc); 
+  double width(const char* text);
+  double width(const wchar_t* text);
+  double height();
+  bool valid(const char* text);
+  
+  GLuint listBase;
+  GLuint firstGlyph;
+  GLuint nglyph;
+  unsigned int* widths;
+  unsigned int ascent;
+};
+
+//
+// CLASS
+//   GLFTFont
+//
+
+class GLFTFont : public GLFont
+{
+public:
+  GLFTFont(const char* in_family, int in_style, double in_cex, const char* in_fontname);
+  
+  ~GLFTFont();
+#ifdef HAVE_FREETYPE
+  void draw(const char* text, int length, double adjx, double adjy, const RenderContext& rc);
+  void draw(const wchar_t* text, int length, double adjx, double adjy, const RenderContext& rc);
+  double width(const char* text);
+  double width(const wchar_t* text);
+  double height();
+  
+  FTFont *font;
+  const char *errmsg;
+#endif
+};
+
+//
+// CLASS
+//   NULLFont
+//
+
+class NULLFont : public GLFont
+{
+public:
+  NULLFont(const char* in_family, int in_style, double in_cex): 
+    GLFont(in_family, in_style, in_cex, "NULL", false) {};
+
+  void draw(const char* text, int length, double adjx, double adjy, const RenderContext& rc) {};
+  void draw(const wchar_t* text, int length, double adjx, double adjy, const RenderContext& rc) {}; 
+  double width(const char* text) {return 0.0;};
+  double width(const wchar_t* text) {return 0.0;};
+  double height() {return 0.0;};
+  
+};
+
+/**
+ * FontArray
+ **/
+typedef std::vector<GLFont*> FontArray;
+
+/* The macros below are taken from the R internationalization code, which
+   is marked
+
+   Copyright (C) 1995-1999, 2000-2007 Free Software Foundation, Inc.
+*/   
+/* Pathname support.
+   ISSLASH(C)           tests whether C is a directory separator character.
+   IS_ABSOLUTE_PATH(P)  tests whether P is an absolute path.  If it is not,
+                        it may be concatenated to a directory pathname.
+ */
+#if defined _WIN32 || defined __WIN32__ || defined __CYGWIN__ || defined __EMX__ || defined __DJGPP__
+  /* Win32, Cygwin, OS/2, DOS */
+# define ISSLASH(C) ((C) == '/' || (C) == '\\')
+# define HAS_DEVICE(P) \
+    ((((P)[0] >= 'A' && (P)[0] <= 'Z') || ((P)[0] >= 'a' && (P)[0] <= 'z')) \
+     && (P)[1] == ':')
+# define IS_ABSOLUTE_PATH(P) (ISSLASH ((P)[0]) || HAS_DEVICE (P))
+#else
+  /* Unix */
+# define ISSLASH(C) ((C) == '/')
+# define IS_ABSOLUTE_PATH(P) ISSLASH ((P)[0])
+#endif
+
+} // namespace rgl
+
+#endif /* GL_GUI_H */
+
diff --git a/src/gui.cpp b/src/gui.cpp
new file mode 100644
index 0000000..7819a26
--- /dev/null
+++ b/src/gui.cpp
@@ -0,0 +1,312 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: gui.cpp 1137 2014-09-24 19:03:24Z murdoch $
+// ---------------------------------------------------------------------------
+#include "gui.h"
+#include "lib.h"
+#include "R.h"
+
+using namespace rgl;
+
+// ---------------------------------------------------------------------------
+// WindowImpl common code
+// ---------------------------------------------------------------------------
+void WindowImpl::getFonts(FontArray& outfonts, int nfonts, char** family, int* style, 
+                          double* cex, bool useFreeType)
+{
+  GLFont* font;
+  outfonts.resize(nfonts);
+  for (int i = 0; i < nfonts; i++) {
+    font = getFont(*(family++), *(style++), *(cex++), useFreeType);
+    outfonts[i] = font;
+  }  
+}
+
+// ---------------------------------------------------------------------------
+// View Implementation
+// ---------------------------------------------------------------------------
+View::View()
+: baseX(0)
+, baseY(0)
+, width(0)
+, height(0)
+, flags(0)
+, windowImpl(0)
+{ }
+// ---------------------------------------------------------------------------
+View::View(int inBaseX, int inBaseY, int inWidth, int inHeight, int inFlags)
+: baseX(inBaseX)
+, baseY(inBaseY)
+, width(inWidth)
+, height(inHeight)
+, flags(inFlags)
+, windowImpl(0)
+{
+}
+// ---------------------------------------------------------------------------
+View::~View()
+{
+  if ((windowImpl) && (flags & WINDOW_IMPL_OWNER)) {
+    windowImpl->unbind();
+    windowImpl->destroy();
+    windowImpl = 0;
+  }
+}
+// ---------------------------------------------------------------------------
+void View::setSize(int inWidth, int inHeight)
+{
+  if ((windowImpl) && (flags & WINDOW_IMPL_OWNER)) {
+    int left, top, right, bottom;
+    windowImpl->getWindowRect(&left, &top, &right, &bottom);
+    windowImpl->setWindowRect(left, top, left+inWidth, top+inHeight);
+  } else
+    resize(inWidth, inHeight);
+}
+// ---------------------------------------------------------------------------
+void View::setLocation(int inBaseX, int inBaseY)
+{
+  if ((windowImpl) && (flags & WINDOW_IMPL_OWNER)) {
+    int left, top, right, bottom;
+    windowImpl->getWindowRect(&left, &top, &right, &bottom);
+    windowImpl->setWindowRect(inBaseX, inBaseY, inBaseX + left-right, inBaseY + bottom-top);
+  } else
+    relocate(inBaseX, inBaseY);
+}
+// ---------------------------------------------------------------------------
+void View::update(void)
+{
+  if (windowImpl)
+    windowImpl->update();
+}
+// ---------------------------------------------------------------------------
+void View::setWindowImpl(WindowImpl* inWindowImpl)
+{
+  windowImpl = inWindowImpl;
+}
+// ---------------------------------------------------------------------------
+void View::show(void)
+{
+}
+// ---------------------------------------------------------------------------
+void View::hide(void)
+{
+}
+// ---------------------------------------------------------------------------
+void View::paint(void)
+{
+}
+// ---------------------------------------------------------------------------
+void View::resize(int inWidth, int inHeight)
+{
+  width  = inWidth;
+  height = inHeight;
+}
+// ---------------------------------------------------------------------------
+void View::relocate(int inBaseX, int inBaseY)
+{
+  baseX = inBaseX;
+  baseY = inBaseY;
+}
+// ---------------------------------------------------------------------------
+void View::keyPress(int code)
+{
+}
+// ---------------------------------------------------------------------------
+void View::keyRelease(int code)
+{
+}
+// ---------------------------------------------------------------------------
+void View::buttonPress(int button, int mouseX, int mouseY)
+{
+}
+// ---------------------------------------------------------------------------
+void View::buttonRelease(int button, int mouseX, int mouseY)
+{
+}
+// ---------------------------------------------------------------------------
+void View::mouseMove(int mouseX, int mouseY)
+{
+}
+// ---------------------------------------------------------------------------
+void View::wheelRotate(int direction)
+{
+}
+// ---------------------------------------------------------------------------
+void View::captureLost()
+{
+}
+// ---------------------------------------------------------------------------
+// Window Implementation
+// ---------------------------------------------------------------------------
+Window::Window(View* in_child, GUIFactory* factory)
+: View(0,0,in_child->width, in_child->height,WINDOW_IMPL_OWNER)
+, child(in_child)
+, title("untitled")
+{
+  skipRedraw = false;  
+  windowImpl = factory->createWindowImpl(this);
+  if (child)
+    child->setWindowImpl(windowImpl);
+}
+// ---------------------------------------------------------------------------
+Window::~Window()
+{
+  if (child) {
+    delete child;
+  }
+  fireNotifyDisposed();  
+}
+// ---------------------------------------------------------------------------
+void Window::setWindowImpl(WindowImpl* impl)
+{
+  View::setWindowImpl(impl);
+
+  if (child)
+    child->setWindowImpl(impl);
+}
+// ---------------------------------------------------------------------------
+void Window::setTitle(const char* in_title)
+{
+  if (windowImpl)
+    windowImpl->setTitle(in_title);
+}
+// ---------------------------------------------------------------------------
+void Window::update(void)
+{
+  windowImpl->update();
+}
+// ---------------------------------------------------------------------------
+void Window::setVisibility(bool state)
+{
+  if (state)
+    windowImpl->show();
+  else
+    windowImpl->hide();
+}
+// ---------------------------------------------------------------------------
+void Window::bringToTop(int stay)
+{
+  windowImpl->bringToTop(stay);
+}
+// ---------------------------------------------------------------------------
+void Window::getWindowRect(int *left, int *top, int *width, int *height)
+{
+  windowImpl->getWindowRect(left, top, width, height);
+}
+// ---------------------------------------------------------------------------
+void Window::setWindowRect(int left, int top, int width, int height)
+{
+  windowImpl->setWindowRect(left, top, width, height);
+}
+
+// ---------------------------------------------------------------------------
+
+int Window::getSkipRedraw(void)
+{
+  return (int)skipRedraw;
+}
+// ---------------------------------------------------------------------------
+void Window::setSkipRedraw(int in_skipRedraw)
+{
+  skipRedraw = (bool)in_skipRedraw;
+  if (!skipRedraw) update();
+}
+// ---------------------------------------------------------------------------
+void Window::show(void)
+{
+  if (child)
+    child->show();
+}
+// ---------------------------------------------------------------------------
+void Window::hide(void)
+{
+  if (child)
+    child->hide();
+}
+// ---------------------------------------------------------------------------
+void Window::resize(int in_width, int in_height)
+{
+  if (child)
+    child->resize(in_width,in_height);
+}
+// ---------------------------------------------------------------------------
+void Window::paint(void)
+{
+  if (child)
+    child->paint();
+}
+// ---------------------------------------------------------------------------
+void Window::notifyDestroy(void)
+{
+  if (child) {
+    delete child;
+    child = NULL;
+  }
+  fireNotifyDisposed();
+}
+// ---------------------------------------------------------------------------
+void Window::buttonPress(int button, int mouseX, int mouseY)
+{
+  if (child)
+    child->buttonPress(button, mouseX, mouseY);
+}
+// ---------------------------------------------------------------------------
+void Window::buttonRelease(int button, int mouseX, int mouseY)
+{
+  if (child)
+    child->buttonRelease(button, mouseX, mouseY);
+}
+// ---------------------------------------------------------------------------
+void Window::mouseMove(int mouseX, int mouseY)
+{
+  if (child)
+    child->mouseMove(mouseX, mouseY);
+}
+// ---------------------------------------------------------------------------
+void Window::keyPress(int code)
+{
+  if (child)
+    child->keyPress(code);
+}
+// ---------------------------------------------------------------------------
+void Window::wheelRotate(int dir)
+{
+  if (child)
+    child->wheelRotate(dir);
+}
+// ---------------------------------------------------------------------------
+void Window::on_close()
+{
+  windowImpl->destroy();
+}
+// ---------------------------------------------------------------------------
+void Window::getFonts(FontArray& outfonts, int nfonts, char** family, int* style, 
+                      double* cex, bool useFreeType)
+{
+  windowImpl->getFonts(outfonts, nfonts, family, style, cex, useFreeType);
+}
+// ---------------------------------------------------------------------------
+
+int WindowImpl::getAntialias()
+{
+  if (beginGL()) {
+    int result;      
+    glGetIntegerv(GL_SAMPLES, &result);
+    endGL();
+    CHECKGLERROR;
+    return result;
+  }
+  return 1;
+}
+
+int WindowImpl::getMaxClipPlanes()
+{
+  int result;
+  glGetError();
+  glGetIntegerv(GL_MAX_CLIP_PLANES, &result);
+  if (glGetError() == GL_NO_ERROR)
+    return result;
+  else
+    return 6;
+}
diff --git a/src/gui.h b/src/gui.h
new file mode 100644
index 0000000..b4513fd
--- /dev/null
+++ b/src/gui.h
@@ -0,0 +1,219 @@
+#ifndef RGL_GUI_H
+#define RGL_GUI_H
+// ---------------------------------------------------------------------------
+// C++ header file
+// This file is part of RGL
+//
+// $Id: gui.h 1137 2014-09-24 19:03:24Z murdoch $
+// ---------------------------------------------------------------------------
+#include "types.h"
+#include "glgui.h"
+#include "Disposable.h"
+
+namespace rgl {
+
+// ---------------------------------------------------------------------------
+enum {
+  GUI_ButtonLeft = 1,
+  GUI_ButtonRight,
+  GUI_ButtonMiddle
+};
+// ---------------------------------------------------------------------------
+enum {
+  GUI_WheelForward = 1,
+  GUI_WheelBackward
+};
+// ---------------------------------------------------------------------------
+enum {
+  GUI_KeyF1  = 128,
+  GUI_KeyF2,
+  GUI_KeyF3,
+  GUI_KeyF4,
+  GUI_KeyF5,
+  GUI_KeyF6,
+  GUI_KeyF7,
+  GUI_KeyF8,
+  GUI_KeyF9,
+  GUI_KeyF10,
+  GUI_KeyF11,
+  GUI_KeyF12,
+  GUI_KeyReturn,
+  GUI_KeyUp,
+  GUI_KeyDown,
+  GUI_KeyLeft,
+  GUI_KeyRight,
+  GUI_KeyInsert,
+  GUI_KeyESC
+};
+// ---------------------------------------------------------------------------
+//
+// IMPLEMENTATION INTERFACE
+//
+// ---------------------------------------------------------------------------
+class View;
+class Window;
+// ---------------------------------------------------------------------------
+class WindowImpl
+{
+public:
+  inline WindowImpl(Window* in_window)
+  : window(in_window)
+  { 
+    fonts.resize(1);
+  }
+
+  virtual ~WindowImpl() { }
+
+  inline  void unbind() { window = 0; }
+  virtual void setTitle(const char* title) = 0;
+  virtual void setWindowRect(int left, int top, int right, int bottom) = 0;
+  virtual void getWindowRect(int *left, int *top, int *right, int *bottom) = 0;
+  virtual void show(void) = 0;
+  virtual void hide(void) = 0;
+  virtual void update(void) = 0;
+
+  virtual void bringToTop(int stay) = 0;
+
+  /// @doc notifyDestroy will be called on success
+  virtual void destroy(void) = 0;
+  virtual bool beginGL(void) = 0;
+  virtual void endGL(void) = 0;
+  virtual void swap(void) = 0;
+  virtual void captureMouse(View* captureView) = 0;
+  virtual void releaseMouse(void) = 0;
+  virtual GLFont* getFont(const char* family, int style, double cex, 
+                          bool useFreeType) = 0;
+  void getFonts(FontArray& outfonts, int nfonts, char** family, int* style, double* cex, 
+                bool useFreeType);
+  virtual int getAntialias();
+  virtual int getMaxClipPlanes();
+  // OpenGL support (FIXME: remove)
+  FontArray fonts;
+protected:
+  Window*      window;
+};
+// ---------------------------------------------------------------------------
+//
+// GUIFactory to be used in ABSTRACT GUI TOOLKIT
+//
+// ---------------------------------------------------------------------------
+class GUIFactory
+{
+public:
+  virtual ~GUIFactory() { }    
+  virtual WindowImpl* createWindowImpl(Window*) = 0;
+};
+// ---------------------------------------------------------------------------
+//
+// implementation specific
+//
+rgl::GUIFactory* getGUIFactory(bool useNULLDevice);
+// ---------------------------------------------------------------------------
+//
+// ABSTRACT GUI TOOLKIT
+//
+// ---------------------------------------------------------------------------
+//
+// view flags
+//
+// ---------------------------------------------------------------------------
+#define WINDOW_IMPL_OWNER   (1<<0)
+// ---------------------------------------------------------------------------
+class View 
+{
+public:
+  View();
+  View(int basex, int basey, int width, int height, int flags);
+  virtual ~View();
+
+// services:
+
+  virtual void setSize(int width, int height);
+  virtual void setLocation(int basex, int basey);
+  virtual void update(void);
+
+// event handlers:
+
+  virtual void show(void);
+  virtual void hide(void);
+  virtual void paint(void);
+  virtual void relocate(int baseX, int baseY);
+  virtual void resize(int inWidth, int inHeight);
+  virtual void keyPress(int code);
+  virtual void keyRelease(int code);
+  virtual void buttonPress(int button, int mouseX, int mouseY);
+  virtual void buttonRelease(int button, int mouseX, int mouseY);
+  virtual void wheelRotate(int direction);
+  virtual void mouseMove(int mouseX, int mouseY);
+  virtual void captureLost();
+
+// protected services:
+
+  virtual void setWindowImpl(WindowImpl* impl);
+
+// data:
+
+  int baseX, baseY;
+  int width, height;
+  int flags;
+
+  WindowImpl* windowImpl;
+
+  friend class Window;
+};
+// ---------------------------------------------------------------------------
+class Window : public View, public Disposable
+{
+public:
+
+  Window(View* child=NULL, GUIFactory* factory=rgl::getGUIFactory(0) );
+  ~Window();
+
+// overloaded view methods:
+  void setWindowImpl(WindowImpl* windowImpl);
+
+// services:
+  void setTitle(const char* title);
+  void setVisibility(bool state);
+  void update(void);
+  int getSkipRedraw(void);
+  void setSkipRedraw(int in_skipRedraw);
+
+/**
+ * Close the window. 
+ **/
+public:
+  void close() { if (windowImpl) windowImpl->destroy(); else dispose(); }
+
+// protected:
+
+// event handlers:
+  void show();
+  void hide();
+  void resize(int width, int height);
+  void paint();
+  void on_close();
+  void notifyDestroy();
+  void buttonPress(int button, int mouseX, int mouseY);
+  void buttonRelease(int button, int mouseX, int mouseY);
+  void mouseMove(int mouseX, int mouseY);
+  void keyPress(int code);
+  void wheelRotate(int dir);
+
+  void bringToTop(int stay);
+  void setWindowRect(int left, int top, int right, int bottom);
+  void getWindowRect(int *left, int *top, int *right, int *bottom);
+  void getFonts(FontArray& outfonts, int nfonts, char** family, int* style, double* cex,
+                bool useFreeType);
+
+// data:
+  View* child;
+  const char* title;
+  bool skipRedraw;  
+};
+// ---------------------------------------------------------------------------
+
+} // namespace rgl
+
+#endif // RGL_GUI_H 
+
diff --git a/src/init.cpp b/src/init.cpp
new file mode 100644
index 0000000..dac688b
--- /dev/null
+++ b/src/init.cpp
@@ -0,0 +1,254 @@
+#include "lib.h"
+#include "DeviceManager.h"
+#include "init.h"
+#include "api.h"
+
+/* libfreetype 2.6 defines a conflicting TYPEOF macro */
+
+#ifdef TYPEOF
+# undef TYPEOF
+#endif
+
+#include <R_ext/Visibility.h>
+#include <R_ext/Rdynload.h>
+#include "R.h"
+
+using namespace rgl;
+
+//
+// FUNCTION
+//   rgl_init
+//
+
+//
+// GLOBAL: deviceManager pointer
+//
+
+namespace rgl{
+
+DeviceManager* deviceManager = NULL;
+
+int gInitValue;
+void* gHandle;
+SEXP rglNamespace;
+
+//
+// FUNCTION
+//   rgl_init
+//
+// PARAMETERS
+//   ioptions - platform-specific options.
+//     Windows:
+//     [0]  multiple-document-interface console handle (MDI)
+//          or 0 (SDI)
+//     MacOSX:
+//     [0]  Formerly indicator of presence (1) or absence (0) of Carbon/Cocoa, now unused
+//
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+SEXP rgl_init(SEXP initValue, SEXP useNULL, SEXP in_namespace)
+{
+  int success = 0;
+  bool useNULLDevice = asLogical(useNULL);
+
+  gInitValue = 0;
+  gHandle = NULL;
+  rglNamespace = in_namespace;
+  
+  if ( isNumeric(initValue) ) {
+    gInitValue =  asInteger(initValue);
+  }
+  else if ( TYPEOF(initValue) == EXTPTRSXP ) {
+    gHandle = R_ExternalPtrAddr(initValue);
+  }
+  else if ( !isNull(initValue) )
+  {
+    return ScalarInteger( 0 );
+  }  
+  if ( init(useNULLDevice) ) {
+    deviceManager = new DeviceManager(useNULLDevice);
+    success = 1;
+  }
+
+  return(ScalarInteger(success));
+}
+
+#define FUNDEF(name, n)  {#name, (DL_FUNC) &name, n}
+
+#undef CHECK_ARGS
+
+#ifdef CHECK_ARGS
+  R_NativePrimitiveArgType aI[1] = {INTSXP};  
+  R_NativePrimitiveArgType aL[1] = {LGLSXP}; 
+  R_NativePrimitiveArgType aII[2] = {INTSXP, INTSXP}; 
+  R_NativePrimitiveArgType aLI[2] = {LGLSXP, INTSXP}; 
+  R_NativePrimitiveArgType aLL[2] = {LGLSXP, LGLSXP}; 
+  R_NativePrimitiveArgType aIII[3] = {INTSXP, INTSXP, INTSXP};  
+  R_NativePrimitiveArgType aIIS[3] = {INTSXP, INTSXP, STRSXP}; 
+  R_NativePrimitiveArgType aIID[3] = {INTSXP, INTSXP, REALSXP};
+  R_NativePrimitiveArgType aLII[3] = {LGLSXP, INTSXP, INTSXP}; 
+  R_NativePrimitiveArgType aLIS[3] = {LGLSXP, INTSXP, STRSXP}; 
+  R_NativePrimitiveArgType aLID[3] = {LGLSXP, INTSXP, REALSXP}; 
+  R_NativePrimitiveArgType aIIDD[4] = {INTSXP, INTSXP, REALSXP, REALSXP}; 
+  R_NativePrimitiveArgType aLISD[4] = {LGLSXP, INTSXP, STRSXP, REALSXP}; 
+  R_NativePrimitiveArgType aIISI[4] = {INTSXP, INTSXP, STRSXP, INTSXP};
+  R_NativePrimitiveArgType aLIDD[4] = {LGLSXP, INTSXP, REALSXP, REALSXP}; 
+  R_NativePrimitiveArgType aIIIID[5] = {INTSXP, INTSXP, INTSXP, INTSXP, REALSXP}; 
+  R_NativePrimitiveArgType aIIIIS[5] = {INTSXP, INTSXP, INTSXP, INTSXP, STRSXP}; 
+  R_NativePrimitiveArgType aLIIIS[5] = {LGLSXP, INTSXP, INTSXP, INTSXP, STRSXP}; 
+  R_NativePrimitiveArgType aLIIID[5] = {LGLSXP, INTSXP, INTSXP, INTSXP, REALSXP}; 
+  R_NativePrimitiveArgType aLIISD[5] = {LGLSXP, INTSXP, INTSXP, STRSXP, REALSXP}; 
+  R_NativePrimitiveArgType aLIIIF[5] = {LGLSXP, INTSXP, INTSXP, INTSXP, SINGLESXP}; 
+  R_NativePrimitiveArgType aLIDDD[5] = {LGLSXP, INTSXP, REALSXP, REALSXP, REALSXP};
+  R_NativePrimitiveArgType aIIDDD[5] = {INTSXP, INTSXP, REALSXP, REALSXP, REALSXP};
+  R_NativePrimitiveArgType aIIDDID[6] = {INTSXP, INTSXP, REALSXP, REALSXP, INTSXP, REALSXP};
+  R_NativePrimitiveArgType aLIDDDDI[7] = {LGLSXP, INTSXP, REALSXP, REALSXP, REALSXP, REALSXP, INTSXP};
+  
+  R_NativePrimitiveArgType aLIDDSDSDS[9] = {LGLSXP, INTSXP, REALSXP, REALSXP, STRSXP, REALSXP,
+                                             STRSXP, REALSXP, STRSXP}; 
+  R_NativePrimitiveArgType aIIDSDISIDI[10] = {INTSXP, INTSXP, REALSXP, STRSXP, REALSXP, INTSXP,
+                                             STRSXP, INTSXP, REALSXP, INTSXP}; 
+  R_NativePrimitiveArgType aIIDDDDDDDDIII[13] = {INTSXP, INTSXP, REALSXP, REALSXP, REALSXP, REALSXP,
+                                             REALSXP, REALSXP, REALSXP, REALSXP, INTSXP, INTSXP, INTSXP}; 
+
+ static const R_CMethodDef CEntries[] = { 
+   {"rgl_dev_open", 		(DL_FUNC) &rgl_dev_open, 2, aLL},
+   {"rgl_dev_close", 		(DL_FUNC) &rgl_dev_close, 1, aL},
+   {"rgl_dev_setcurrent", 	(DL_FUNC) &rgl_dev_setcurrent, 2, aLI},
+   {"rgl_snapshot", 		(DL_FUNC) &rgl_snapshot, 3, aLIS},
+   {"rgl_postscript", 		(DL_FUNC) &rgl_postscript, 3, aLIS},
+   {"rgl_material", 		(DL_FUNC) &rgl_material, 4, aLISD},
+   {"rgl_getmaterial", 		(DL_FUNC) &rgl_getmaterial, 5, aLIISD},
+   {"rgl_getcolorcount", 	(DL_FUNC) &rgl_getcolorcount, 1, aI},
+   {"rgl_dev_bringtotop", 	(DL_FUNC) &rgl_dev_bringtotop, 2, aLL},
+   {"rgl_clear", 		(DL_FUNC) &rgl_clear, 2, aLI},  
+   {"rgl_pop", 			(DL_FUNC) &rgl_pop, 2, aLI},  
+   {"rgl_id_count", 		(DL_FUNC) &rgl_id_count, 3, aIII},  
+   {"rgl_ids", 			(DL_FUNC) &rgl_ids, 4, aIISI},  
+   {"rgl_viewpoint", 		(DL_FUNC) &rgl_viewpoint, 3, aLID},    
+   {"rgl_getObserver", 	        (DL_FUNC) &rgl_getObserver, 2, aID},
+   {"rgl_setObserver", 	        (DL_FUNC) &rgl_setObserver, 2, aID},
+   {"rgl_attrib_count", 	(DL_FUNC) &rgl_attrib_count, 3, aIII}, 
+   {"rgl_attrib", 		(DL_FUNC) &rgl_attrib, 5, aIIIID}, 
+   {"rgl_text_attrib", 		(DL_FUNC) &rgl_text_attrib, 5, aIIIIS}, 
+   {"rgl_bg", 			(DL_FUNC) &rgl_bg, 2, aLI},
+   {"rgl_bbox", 		(DL_FUNC) &rgl_bbox, 9, aLIDDSDSDS}, 
+   {"rgl_light",		(DL_FUNC) &rgl_light, 3, aIID},
+   {"rgl_pixels",		(DL_FUNC) &rgl_pixels, 5, aLIIIF},
+   {"rgl_planes",		(DL_FUNC) &rgl_planes, 4, aIIDD},
+   {"rgl_clipplanes", 		(DL_FUNC) &rgl_planes, 4, aIIDD},
+   {"rgl_abclines",		(DL_FUNC) &rgl_abclines, 4, aIIDD},
+   {"rgl_primitive",		(DL_FUNC) &rgl_primitive, 5, aIIDDD},
+   {"rgl_surface", 		(DL_FUNC) &rgl_surface, 13, aIIDDDDDDDDIII},
+   {"rgl_spheres",		(DL_FUNC) &rgl_spheres, 4, aIIDD},
+   {"rgl_texts",		(DL_FUNC) &rgl_texts, 10, aIIDSDISIDI},
+   {"rgl_sprites",  		(DL_FUNC) &rgl_sprites, 6, aIIDDID},
+   {"rgl_newsubscene",		(DL_FUNC) &rgl_newsubscene, 4, aIIII},
+   {"rgl_setsubscene",		(DL_FUNC) &rgl_setsubscene, 1, aI},
+   {"rgl_getsubsceneid",	(DL_FUNC) &rgl_getsubsceneid, 2, aII},
+   {"rgl_getsubsceneparent",    (DL_FUNC) &rgl_getsubsceneparent, 1, aI},
+   {"rgl_getsubscenechildcount",(DL_FUNC) &rgl_getsubscenechildcount, 2, aII},
+   {"rgl_getsubscenechildren",  (DL_FUNC) &rgl_getsubscenechildren, 2, aII},
+   {"rgl_gc", 			(DL_FUNC) &rgl_gc, 2, aII},
+   {"rgl_setEmbeddings",        (DL_FUNC) &rgl_setEmbeddings, 2, aII},
+   {"rgl_getEmbeddings",        (DL_FUNC) &rgl_getEmbeddings, 2, aII},
+   {"rgl_addtosubscene", 	(DL_FUNC) &rgl_addtosubscene, 3, aIII},
+   {"rgl_delfromsubscene",	(DL_FUNC) &rgl_delfromsubscene, 3, aIII},
+   {"rgl_user2window",		(DL_FUNC) &rgl_user2window, 7, aLIDDDDI},
+   {"rgl_window2user", 		(DL_FUNC) &rgl_window2user, 7, aLIDDDDI},
+   {"rgl_selectstate", 		(DL_FUNC) &rgl_selectstate, 3, aLID},
+   {"rgl_setselectstate",	(DL_FUNC) &rgl_setselectstate, 2, aLI},
+   {"rgl_quit",			(DL_FUNC) &rgl_quit, 1, aL},
+   
+   {NULL, NULL, 0}
+ };
+
+#else  // don't CHECK_ARGS
+
+ static const R_CMethodDef CEntries[] = { 
+   FUNDEF(rgl_dev_open, 2),
+   FUNDEF(rgl_dev_close, 1),
+   FUNDEF(rgl_dev_setcurrent, 2),
+   FUNDEF(rgl_snapshot, 3),
+   FUNDEF(rgl_postscript, 3),
+   FUNDEF(rgl_material, 4),
+   FUNDEF(rgl_getmaterial, 5),
+   FUNDEF(rgl_getcolorcount, 1),
+   FUNDEF(rgl_dev_bringtotop, 2),
+   FUNDEF(rgl_clear, 2), 
+   FUNDEF(rgl_pop, 2), 
+   FUNDEF(rgl_id_count, 3), 
+   FUNDEF(rgl_ids, 4), 
+   FUNDEF(rgl_viewpoint, 3), 
+   FUNDEF(rgl_getObserver, 2),
+   FUNDEF(rgl_setObserver, 2),
+   FUNDEF(rgl_attrib_count, 3), 
+   FUNDEF(rgl_attrib, 5), 
+   FUNDEF(rgl_text_attrib, 5), 
+   FUNDEF(rgl_bg, 2),
+   FUNDEF(rgl_bbox, 9), 
+   FUNDEF(rgl_light, 3),
+   FUNDEF(rgl_pixels, 5),
+   FUNDEF(rgl_planes, 4),
+   FUNDEF(rgl_clipplanes, 4),
+   FUNDEF(rgl_abclines, 4),
+   FUNDEF(rgl_primitive, 5),
+   FUNDEF(rgl_surface, 13),
+   FUNDEF(rgl_spheres, 4),
+   FUNDEF(rgl_texts, 10),
+   FUNDEF(rgl_sprites, 6),
+   FUNDEF(rgl_newsubscene, 4),
+   FUNDEF(rgl_setsubscene, 1),
+   FUNDEF(rgl_getsubsceneid, 2),
+   FUNDEF(rgl_getsubsceneparent, 1),
+   FUNDEF(rgl_getsubscenechildcount, 2),
+   FUNDEF(rgl_getsubscenechildren, 2),
+   FUNDEF(rgl_gc, 2),
+   FUNDEF(rgl_setEmbeddings, 2),
+   FUNDEF(rgl_getEmbeddings, 2),
+   FUNDEF(rgl_addtosubscene, 3),
+   FUNDEF(rgl_delfromsubscene, 3),
+   FUNDEF(rgl_user2window, 7),
+   FUNDEF(rgl_window2user, 7),
+   FUNDEF(rgl_selectstate, 3),
+   FUNDEF(rgl_setselectstate, 2),
+   FUNDEF(rgl_quit, 1),
+   
+   {NULL, NULL, 0}
+ };
+ 
+ #endif // CHECK_ARGS
+
+ static const R_CallMethodDef CallEntries[]  = {
+   FUNDEF(rgl_init, 3),
+   FUNDEF(rgl_dev_getcurrent, 0),
+   FUNDEF(rgl_dev_list, 0),
+   FUNDEF(rgl_par3d, 3),
+   FUNDEF(rgl_setMouseCallbacks, 4),
+   FUNDEF(rgl_setWheelCallback, 1),
+   FUNDEF(rgl_getMouseCallbacks, 1),
+   FUNDEF(rgl_getWheelCallback, 0),
+
+   {NULL, NULL, 0}
+ };
+
+ static const R_ExternalMethodDef ExtEntries[] = {
+   {NULL, NULL, 0}
+ };
+ 
+void attribute_visible R_init_rgl(DllInfo *dll) 
+{
+  R_registerRoutines(dll, CEntries, CallEntries, NULL, ExtEntries);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+// ---------------------------------------------------------------------------
+} // namespace rgl
+// ---------------------------------------------------------------------------
+
diff --git a/src/init.h b/src/init.h
new file mode 100644
index 0000000..d72b6d8
--- /dev/null
+++ b/src/init.h
@@ -0,0 +1,30 @@
+#ifndef RGL_INIT_H
+#define RGL_INIT_H
+
+#include "R.h"
+#include <Rdefines.h> 
+#include <Rinternals.h> 
+
+namespace rgl {
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+// RGL initialization
+//
+*/
+
+/* library service */
+
+SEXP rgl_init          (SEXP initValue, SEXP onlyNULL, SEXP in_namespace);
+
+#ifdef __cplusplus
+}
+#endif
+
+} // namespace rgl
+
+#endif /* RGL_INIT_H */
+
diff --git a/src/lib.h b/src/lib.h
new file mode 100644
index 0000000..0d31591
--- /dev/null
+++ b/src/lib.h
@@ -0,0 +1,20 @@
+#ifndef RGL_LIB_H
+#define RGL_LIB_H
+// ---------------------------------------------------------------------------
+// $Id: lib.h 1115 2014-07-18 13:51:22Z murdoch $
+// ---------------------------------------------------------------------------
+
+namespace rgl {
+
+// ---------------------------------------------------------------------------
+bool init(bool onlyNULLDevice);
+const char * GUIFactoryName(bool useNULLDevice);    
+void quit();
+void printMessage(const char* string);
+double getTime();
+// ---------------------------------------------------------------------------
+
+} // namespace rgl
+
+#endif // RGL_LIB_H
+
diff --git a/src/opengl.h b/src/opengl.h
new file mode 100644
index 0000000..554ace7
--- /dev/null
+++ b/src/opengl.h
@@ -0,0 +1,29 @@
+#ifndef RGL_OPENGL_H
+#define RGL_OPENGL_H
+// ---------------------------------------------------------------------------
+// Using OpenGL and GLU
+//
+// $Id: opengl.h 1115 2014-07-18 13:51:22Z murdoch $
+// ---------------------------------------------------------------------------
+#include "config.h"
+// ---------------------------------------------------------------------------
+#ifdef RGL_OSX
+#include <OpenGL/gl.h>
+#include <OpenGL/glu.h>
+#endif
+// ---------------------------------------------------------------------------
+#ifdef RGL_W32
+#include <windows.h>
+#include <GL/gl.h>
+#include <GL/glu.h>
+#include <GLsdk/GL/glext.h>
+#include <GLsdk/GL/wglext.h>
+#endif
+// ---------------------------------------------------------------------------
+#ifdef RGL_X11
+#include <GL/gl.h>
+#include <GL/glu.h>
+#endif
+// ---------------------------------------------------------------------------
+#endif // RGL_OPENGL_H
+ 
diff --git a/src/par3d.cpp b/src/par3d.cpp
new file mode 100644
index 0000000..88beb01
--- /dev/null
+++ b/src/par3d.cpp
@@ -0,0 +1,757 @@
+/* Avoid conflict with Rinternals.h */
+// #undef DEBUG
+
+#include "R.h"
+#include "Rversion.h"
+
+#include "DeviceManager.h"
+#include "rglview.h"
+
+#include "api.h"
+
+/* These defines are not in the installed version of R */
+
+#define _  
+#define streql(s, t)	(!strcmp((s), (t)))
+
+#include <Rdefines.h>
+#include <Rinternals.h>
+
+namespace rgl {
+void getObserver(double* ddata, Subscene* subscene);
+void setObserver(bool automatic, double* ddata, RGLView* rglview, Subscene* subscene);
+}
+
+using namespace rgl;
+
+/* These two are currently exposed, because observer3d uses them. */
+void rgl::getObserver(double* ddata, Subscene* subscene)
+{
+  UserViewpoint* userviewpoint = subscene->getUserViewpoint();
+  Vertex res = userviewpoint->getObserver();
+  ddata[0] = res.x;
+  ddata[1] = res.y;
+  ddata[2] = res.z;
+}   
+
+void rgl::setObserver(bool automatic, double* ddata, RGLView* rglview, Subscene* subscene)
+{
+    UserViewpoint* userviewpoint = subscene->getUserViewpoint();
+    userviewpoint->setObserver(automatic, Vertex(ddata[0], ddata[1], ddata[2]));
+    rglview->update();
+}
+
+/* These functions used to be in api.h and api.c, but are only accessed from par3d, so
+   have been made static */
+   
+static void getZoom(double* zoom, Subscene* subscene)
+{
+    UserViewpoint* userviewpoint = subscene->getUserViewpoint();
+    *zoom = userviewpoint->getZoom();
+    CHECKGLERROR;
+}
+
+static void setZoom(double* zoom, RGLView* rglview, Subscene* subscene)
+{
+    UserViewpoint* userviewpoint = subscene->getUserViewpoint();
+    userviewpoint->setZoom( *zoom );
+    rglview->update();
+    CHECKGLERROR;
+}
+
+static void getFOV(double* fov, Subscene* subscene)
+{
+    UserViewpoint* userviewpoint = subscene->getUserViewpoint();
+    *fov = userviewpoint->getFOV();
+    CHECKGLERROR;
+}
+
+static void setFOV(double* fov, RGLView* rglview, Subscene* sub)
+{
+  UserViewpoint* userviewpoint = sub->getUserViewpoint();
+  userviewpoint->setFOV(*fov);
+  rglview->update();
+  CHECKGLERROR;
+}
+
+static void getIgnoreExtent(int* ignoreExtent, Device* device)
+{
+    *ignoreExtent = device->getIgnoreExtent();
+    CHECKGLERROR;
+}
+
+static void setIgnoreExtent(int* ignoreExtent, Device* device)
+{
+  device->setIgnoreExtent(*ignoreExtent);
+  CHECKGLERROR;
+}
+
+static void getSkipRedraw(int* skipRedraw, Device* device)
+{
+    *skipRedraw = device->getSkipRedraw();
+    CHECKGLERROR;
+}
+
+static void setSkipRedraw(int* skipRedraw, Device* device)
+{
+  device->setSkipRedraw(*skipRedraw);
+  CHECKGLERROR;
+}
+
+static void getMouseMode(int *button, int* mode, RGLView* rglview)
+{
+    *mode = static_cast<int>( rglview->getMouseMode(*button) );
+    CHECKGLERROR;
+}
+
+static void setMouseMode(int* button, int* mode, RGLView* rglview)
+{
+  rglview->setMouseMode(*button, (MouseModeID)(*mode));
+
+  CHECKGLERROR;
+}
+
+static void getWheelMode(int* mode, RGLView* rglview)
+{
+    *mode = static_cast<int>( rglview->getWheelMode() );
+    CHECKGLERROR;
+}
+
+static void setWheelMode(int* mode, RGLView* rglview)
+{
+  rglview->setWheelMode((WheelModeID)(*mode));
+
+  CHECKGLERROR;
+}
+
+static void getUserMatrix(double* userMatrix, Subscene* subscene)
+{
+    subscene->getUserMatrix(userMatrix);
+
+    CHECKGLERROR;
+
+}
+
+static void setUserMatrix(double* userMatrix, RGLView* rglview, Subscene* subscene)
+{
+  subscene->setUserMatrix(userMatrix);
+  rglview->update();
+  CHECKGLERROR;
+}
+
+static void getPosition(double* position, Subscene* subscene)
+{
+  subscene->getPosition(position);
+  CHECKGLERROR;
+}
+
+static void setPosition(double* position, RGLView* rglview, Subscene* subscene)
+{
+    subscene->setPosition(position);
+    rglview->update()
+
+    CHECKGLERROR;
+}
+
+static void getScale(double* scale, Subscene* subscene)
+{
+    subscene->getScale(scale);
+}
+
+static void setScale(double* scale, RGLView* rglview, Subscene* subscene)
+{
+
+  subscene->setScale(scale);
+  rglview->update();
+  
+  CHECKGLERROR;
+}
+
+static void setViewport(double* viewport, Device* device, RGLView* rglview, Subscene* subscene)
+{
+  Embedding embedding;
+  
+  while ((embedding = subscene->getEmbedding(0)) == EMBED_INHERIT)
+    subscene = subscene->getParent();
+
+  int left, top, right, bottom;
+  double x, y, width, height;
+  if (embedding == EMBED_REPLACE) {
+    device->getWindowRect(&left, &top, &right, &bottom);
+    width = right - left;
+    height = bottom - top;
+    bottom = 0;
+    left = 0;
+  } else {
+    left = subscene->getParent()->pviewport.x;
+    bottom = subscene->getParent()->pviewport.y;
+    width = subscene->getParent()->pviewport.width;
+    height = subscene->getParent()->pviewport.height;
+  }
+  x = (viewport[0]-left)/width;
+  y = (viewport[1]-bottom)/height;
+  width = viewport[2]/width;
+  height = viewport[3]/height;
+  subscene->setViewport(x, y, width, height);
+  rglview->update();
+}	
+
+static void getViewport(int* viewport, Subscene* subscene)
+{      
+      viewport[0] = subscene->pviewport.x;
+      viewport[1] = subscene->pviewport.y;
+      viewport[2] = subscene->pviewport.width;
+      viewport[3] = subscene->pviewport.height;
+      CHECKGLERROR;
+}
+
+static void getWindowRect(int* rect, Device* device)
+{
+     device->getWindowRect(rect, rect+1, rect+2, rect+3);
+     CHECKGLERROR;
+}
+
+static void setWindowRect(int* rect, Device* dev)
+{
+    dev->setWindowRect(rect[0], rect[1], rect[2], rect[3]);
+    CHECKGLERROR;
+}
+
+static void getBoundingbox(double* bboxvec, Subscene* subscene)
+{
+      const AABox& bbox = subscene->getBoundingBox();
+      bboxvec[0] = bbox.vmin.x;
+      bboxvec[1] = bbox.vmax.x;
+      bboxvec[2] = bbox.vmin.y;
+      bboxvec[3] = bbox.vmax.y;
+      bboxvec[4] = bbox.vmin.z;
+      bboxvec[5] = bbox.vmax.z;
+
+      CHECKGLERROR;
+}
+
+/* font access functions.  These are only used from par3d */
+
+static char* getFamily(RGLView* rglview)
+{
+    const char* f = rglview->getFontFamily();
+    char* result;
+    result = R_alloc(strlen(f)+1, 1);
+    strcpy(result, f);
+    CHECKGLERROR;
+    return result;
+}
+
+static bool setFamily(const char *family, RGLView* rglview)
+{
+  rglview->setFontFamily(family);
+  CHECKGLERROR;
+  return true;
+}
+
+static int getFont(RGLView* rglview)
+{
+    int result = rglview->getFontStyle();
+    CHECKGLERROR;
+    return result;
+}
+
+static bool setFont(int font, RGLView* rglview)
+{
+  rglview->setFontStyle(font);
+  CHECKGLERROR;
+  return true;
+}
+
+static double getCex(RGLView* rglview)
+{
+    double result = rglview->getFontCex();
+    CHECKGLERROR;  
+    return result;
+}
+
+static bool setCex(double cex, RGLView* rglview)
+{
+  rglview->setFontCex(cex);
+  CHECKGLERROR;
+  return true;
+}
+
+static int getUseFreeType(RGLView* rglview)
+{
+    int result = (int) rglview->getFontUseFreeType();
+    CHECKGLERROR;  
+    return result;
+}
+
+static bool setUseFreeType(bool useFreeType, RGLView* rglview)
+{
+  rglview->setFontUseFreeType(useFreeType);
+  CHECKGLERROR;
+  return true;
+}
+
+static char* getFontname(RGLView* rglview)
+{
+  char* result = NULL;
+
+  const char* f = rglview->getFontname();
+  result = R_alloc(strlen(f)+1, 1);
+  strcpy(result, f);
+  CHECKGLERROR;
+  return result;
+}
+
+static int getAntialias(RGLView* rglview)
+{
+    return rglview->windowImpl->getAntialias();
+}
+
+static int getMaxClipPlanes(RGLView* rglview)
+{
+  return rglview->windowImpl->getMaxClipPlanes();
+}  
+
+
+/* par3d implementation based on R's par implementation
+ *
+ *  Main functions:
+ *	par3d(.)	
+ *	Specify(.)	[ par(what = value) ]
+ *	Query(.)	[ par(what) ]
+ */
+
+static void par_error(const char *what)
+{
+    error(_("invalid value specified for rgl parameter \"%s\""),  what);
+}
+
+static void lengthCheck(const char *what, SEXP v, int n)
+{
+    if (length(v) != n)
+	error(_("parameter \"%s\" has the wrong length"), what);
+}
+
+static void dimCheck(const char *what, SEXP v, int r, int c)
+{
+    SEXP dim = coerceVector(getAttrib(v, R_DimSymbol), INTSXP);
+    if (length(dim) != 2 || INTEGER(dim)[0] != r || INTEGER(dim)[1] != c)
+    	error(_("parameter \"%s\" has the wrong dimension"), what);
+}
+
+#ifdef UNUSED
+static void nonnegIntCheck(int x, const char *s)
+{
+    if (x == NA_INTEGER || x < 0)
+	par_error(s);
+}
+
+static void posIntCheck(int x, const char *s)
+{
+    if (x == NA_INTEGER || x <= 0)
+	par_error(s);
+}
+
+static void naIntCheck(int x, const char *s)
+{
+    if (x == NA_INTEGER)
+	par_error(s);
+}
+#endif
+
+static void posRealCheck(double x, const char *s)
+{
+    if (!R_FINITE(x) || x <= 0)
+	par_error(s);
+}
+
+#ifdef UNUSED
+static void nonnegRealCheck(double x, const char *s)
+{
+    if (!R_FINITE(x) || x < 0)
+	par_error(s);
+}
+
+static void naRealCheck(double x, const char *s)
+{
+    if (!R_FINITE(x))
+	par_error(s);
+}
+#endif
+
+static void BoundsCheck(double x, double a, double b, const char *s)
+{
+/* Check if   a <= x <= b */
+    if (!R_FINITE(x) || (R_FINITE(a) && x < a) || (R_FINITE(b) && x > b))
+	par_error(s);
+}
+
+/* These modes must match the definitions of mmTRACKBALL etc in rglview.h ! */ 
+
+namespace rgl {
+const char* mouseModes[] = {"none", "trackball", "xAxis", "yAxis", "zAxis", "polar", "selecting", "zoom", "fov", "user"};
+const char* wheelModes[] = {"none", "push", "pull", "user"};
+const char* viewportlabels[] = {"x", "y", "width", "height"};
+}
+
+#define mmLAST 10
+#define wmLAST  4
+
+/* At R 2.6.0, the type of the first arg to psmatch changed to const char *.  Conditionally cast 
+   to char * if we're in an old version */
+#if defined(R_VERSION) && R_VERSION < R_Version(2, 6, 0)
+#define OLDCAST (char *)
+#else
+#define OLDCAST
+#endif
+
+
+static void Specify(Device* dev, RGLView* rglview, Subscene* sub, const char *what, SEXP value)
+{
+ 
+ /* Do NOT forget to update  ../R/par3d.R */
+ /* if you  ADD a NEW  par !! 
+
+ */
+    SEXP x;
+    double v;
+    int iv;
+    int success = 1;
+
+    if (streql(what, "FOV")) {
+    	lengthCheck(what, value, 1);	v = asReal(value);
+	BoundsCheck(v, 0.0, 179.0, what);
+	setFOV(&v, rglview, sub);
+    }
+    else if (streql(what, "ignoreExtent")) {
+    	lengthCheck(what, value, 1);	iv = asLogical(value);
+    	setIgnoreExtent(&iv, dev);
+    }    
+    else if (streql(what, "mouseMode")) {
+    	value = coerceVector(value, STRSXP);
+	if (length(value) > 4) par_error(what);   
+        for (int i=1; i<=3 && i <= length(value); i++) {
+            if (STRING_ELT(value, i-1) != NA_STRING) {
+		success = 0;
+		/* check exact first, then partial */
+		for (int mode = 0; mode < mmLAST; mode++) {
+		    if (psmatch(OLDCAST mouseModes[mode], CHAR(STRING_ELT(value, i-1)), (Rboolean)TRUE)) {
+			setMouseMode(&i, &mode, rglview);
+			success = 1;
+			break;
+		    }
+		}
+		if (!success) {
+		    for (int mode = 0; mode < mmLAST; mode++) {
+			if (psmatch(OLDCAST mouseModes[mode], CHAR(STRING_ELT(value, i-1)), (Rboolean)FALSE)) {
+			    setMouseMode(&i, &mode, rglview);
+			    success = 1;
+			    break;
+			}
+		    }		
+		}
+		if (!success) par_error(what);
+	    }
+   	}
+	if (length(value) == 4) {
+	    if (STRING_ELT(value, 3) != NA_STRING) {
+		success = 0;
+		for (int mode = 0; mode < wmLAST; mode++) {
+		    if (psmatch(OLDCAST wheelModes[mode], CHAR(STRING_ELT(value, 3)), (Rboolean)TRUE)) {
+			setWheelMode(&mode, rglview);
+			success = 1;
+			break;
+		    }
+		}
+		if (!success) {
+		    for (int mode = 0; mode < wmLAST; mode++) {
+			if (psmatch(OLDCAST wheelModes[mode], CHAR(STRING_ELT(value, 3)), (Rboolean)FALSE)) {
+			    setWheelMode(&mode, rglview);
+			    success = 1;
+			    break;
+			}
+		    }
+		}
+		if (!success) par_error(what);
+	    }
+	}
+    }
+    else if (streql(what, "listeners")) {
+        x = coerceVector(value, INTSXP);
+        sub->setMouseListeners(length(x), INTEGER(x));
+    }
+    else if (streql(what, "skipRedraw")) {
+    	lengthCheck(what, value, 1);	iv = asLogical(value);
+    	setSkipRedraw(&iv, dev);
+    }
+    else if (streql(what, "userMatrix")) {
+	dimCheck(what, value, 4, 4);
+	x = coerceVector(value, REALSXP);
+	
+	setUserMatrix(REAL(x), rglview, sub);
+    }
+    else if (streql(what, "scale")) {
+	lengthCheck(what, value, 3);
+	x = coerceVector(value, REALSXP);
+	
+	setScale(REAL(x), rglview, sub);
+    }
+    else if (streql(what, "viewport")) {
+	lengthCheck(what, value, 4);
+	x = coerceVector(value, REALSXP);
+	setViewport(REAL(x), dev, rglview, sub);
+    }
+    else if (streql(what, "zoom")) {
+    	lengthCheck(what, value, 1);	v = asReal(value);
+	posRealCheck(v, what);
+	setZoom(&v, rglview, sub);
+    }
+    else if (streql(what, ".position")) {
+	lengthCheck(what, value, 2);
+	x = coerceVector(value, REALSXP);
+	
+	setPosition(REAL(x), rglview, sub);
+    }
+    else if (streql(what, "windowRect")) {
+        lengthCheck(what, value, 4);
+        x = coerceVector(value, INTSXP);
+        
+        setWindowRect(INTEGER(x), dev);
+    }    
+    else if (streql(what, "family")) {
+      lengthCheck(what, value, 1);
+      x = coerceVector(value, STRSXP);
+      if (!setFamily(CHAR(STRING_ELT(x, 0)), rglview)) success = 0;
+    }
+    else if (streql(what, "font")) {
+      lengthCheck(what, value, 1);
+      x=coerceVector(value, INTSXP);
+      if (INTEGER(x)[0] < 1 || INTEGER(x)[0] > 5) { par_error(what); }
+      if (!setFont(INTEGER(x)[0], rglview)) success = 0;
+    }
+    else if (streql(what, "cex")) {
+      lengthCheck(what, value, 1);
+      x=coerceVector(value, REALSXP);
+      if (REAL(x)[0] <= 0) { par_error(what); }
+      if (!setCex(REAL(x)[0],rglview)) success = 0;
+    }
+    else if (streql(what, "useFreeType")) {
+      lengthCheck(what, value, 1);
+      x=coerceVector(value, LGLSXP);
+#ifndef HAVE_FREETYPE
+      if (LOGICAL(x)[0])
+          warning("FreeType not supported in this build");
+#endif
+      if (!setUseFreeType(LOGICAL(x)[0], rglview)) success = 0;
+    }
+    
+     else warning(_("parameter \"%s\" cannot be set"), what);
+ 
+    if (!success) par_error(what);
+    
+    return;
+} 
+ 
+ 
+ /* Do NOT forget to update  ../R/par3d.R */
+ /* if you  ADD a NEW  par !! */
+ 
+ 
+static SEXP Query(Device* dev, RGLView* rglview, Subscene* sub, const char *what)
+{
+    SEXP value, names;
+    int i, mode, success = 1;
+    char* buf;
+
+    value = R_NilValue;
+    
+    if (streql(what, "FOV")) {
+	value = allocVector(REALSXP, 1);
+	getFOV(REAL(value), sub);
+    }
+    else if (streql(what, "ignoreExtent")) {
+    	value = allocVector(LGLSXP, 1);
+    	getIgnoreExtent(LOGICAL(value), dev);
+    }    
+    else if (streql(what, "modelMatrix")) {
+	value = allocMatrix(REALSXP, 4, 4);
+	sub->modelMatrix.getData(REAL(value));
+    }
+    else if (streql(what, "mouseMode")) {
+    	PROTECT(value = allocVector(STRSXP, 4));
+    	for (i=1; i<4; i++) {
+	    getMouseMode(&i, &mode, rglview); 
+	    if (mode < 0 || mode > mmLAST) mode = 0;
+	    SET_STRING_ELT(value, i-1, mkChar(mouseModes[mode]));
+    	};    
+	getWheelMode(&mode, rglview);
+	if (mode < 0 || mode > mmLAST) mode = 0;
+	SET_STRING_ELT(value, 3, mkChar(wheelModes[mode]));
+	
+    	PROTECT(names = allocVector(STRSXP, 4));
+    	SET_STRING_ELT(names, 0, mkChar("left"));
+    	SET_STRING_ELT(names, 1, mkChar("right"));  
+    	SET_STRING_ELT(names, 2, mkChar("middle"));
+	SET_STRING_ELT(names, 3, mkChar("wheel"));
+    	UNPROTECT(2);
+    	value = namesgets(value, names);
+    }
+    else if (streql(what, "observer")) {
+        value = allocVector(REALSXP, 3);
+        rgl::getObserver(REAL(value), sub);
+    }
+    else if (streql(what, "projMatrix")) {
+	value = allocMatrix(REALSXP, 4, 4);
+	sub->projMatrix.getData(REAL(value));    
+    }
+    else if (streql(what, "listeners")) {
+        value = allocVector(INTSXP, sub->mouseListeners.size());
+        sub->getMouseListeners(length(value), INTEGER(value));
+    }
+    else if (streql(what, "skipRedraw")) {
+    	value = allocVector(LGLSXP, 1);
+    	getSkipRedraw(LOGICAL(value), dev);
+    }
+    else if (streql(what, "userMatrix")) {
+	value = allocMatrix(REALSXP, 4, 4);
+	getUserMatrix(REAL(value), sub);
+    }
+    else if (streql(what, "scale")) {
+        value = allocVector(REALSXP, 3);
+        getScale(REAL(value), sub);
+    }
+    else if (streql(what, "viewport")) {
+	PROTECT(value = allocVector(INTSXP, 4));
+	getViewport(INTEGER(value), sub);
+	PROTECT(names = allocVector(STRSXP, 4));
+	for (i=0; i<4; i++)
+	  SET_STRING_ELT(names, i, mkChar(viewportlabels[i]));
+	value = namesgets(value, names);
+	UNPROTECT(2);
+    }
+    else if (streql(what, "zoom")) {
+	value = allocVector(REALSXP, 1);
+	getZoom(REAL(value), sub);
+    }
+    else if (streql(what, "bbox")) {
+      value = allocVector(REALSXP, 6);
+      getBoundingbox(REAL(value), sub);
+    }
+    else if (streql(what, ".position")) {
+      value = allocVector(REALSXP, 2);
+      getPosition(REAL(value), sub);
+    }
+    else if (streql(what, "windowRect")) {
+      value = allocVector(INTSXP, 4);
+      getWindowRect(INTEGER(value), dev);
+    }
+    else if (streql(what, "family")) {
+      buf = getFamily(rglview);
+      if (buf) {
+        value = mkString(buf);
+      } 
+    }
+    else if (streql(what, "font")) {
+      value = allocVector(INTSXP, 1);
+      INTEGER(value)[0] = getFont(rglview);
+      success = INTEGER(value)[0] >= 0;
+    }
+    else if (streql(what, "cex")) {
+      value = allocVector(REALSXP, 1);
+      REAL(value)[0] = getCex(rglview);
+      success = REAL(value)[0] >= 0;
+    }    
+    else if (streql(what, "useFreeType")) {
+      int useFreeType = getUseFreeType(rglview);
+      value = allocVector(LGLSXP, 1);
+      if (useFreeType < 0) {
+        LOGICAL(value)[0] = false;
+        success = 0;
+      } else {
+        LOGICAL(value)[0] = (bool)useFreeType;
+      }
+    }    
+    else if (streql(what, "fontname")) {
+      buf = getFontname(rglview);
+      if (buf) {
+        value = mkString(buf);
+      } 
+    }
+    else if (streql(what, "antialias")) {
+      value = allocVector(INTSXP, 1);
+      INTEGER(value)[0] = getAntialias(rglview);
+    }
+    else if (streql(what, "maxClipPlanes")) {
+	value = allocVector(INTSXP, 1);
+	INTEGER(value)[0] = getMaxClipPlanes(rglview);
+    }
+  	
+    if (! success) error(_("unknown error getting rgl parameter \"%s\""),  what);
+
+    return value;
+}
+
+namespace rgl {
+extern DeviceManager* deviceManager;
+}
+  
+SEXP rgl::rgl_par3d(SEXP device, SEXP subscene, SEXP args)
+{
+    Device* dev;
+    
+    if (!deviceManager || !(dev = deviceManager->getDevice(asInteger(device))))
+    	error(_("rgl device %d cannot be found"), asInteger(device));
+    	
+    RGLView* rglview = dev->getRGLView();
+    Scene* scene = rglview->getScene();
+    Subscene* sub = scene->getSubscene(asInteger(subscene));
+    
+    if (!sub)
+    	error(_("rgl subscene %d cannot be found"), asInteger(subscene));
+    
+    SEXP value;
+    int nargs;
+    
+    nargs = length(args);
+    if (isNewList(args)) {
+	SEXP oldnames, newnames, tag, val;
+	int i;
+	PROTECT(newnames = allocVector(STRSXP, nargs));
+	PROTECT(value = allocVector(VECSXP, nargs));
+	oldnames = getAttrib(args, R_NamesSymbol);
+	for (i = 0 ; i < nargs ; i++) {
+	    if (oldnames != R_NilValue)
+		tag = STRING_ELT(oldnames, i);
+	    else
+		tag = R_NilValue;
+	    val = VECTOR_ELT(args, i);
+	    if (tag != R_NilValue && CHAR(tag)[0]) {
+		SET_VECTOR_ELT(value, i, Query(dev, rglview, sub, CHAR(tag)));
+		SET_STRING_ELT(newnames, i, tag);
+		Specify(dev, rglview, sub, CHAR(tag), val);
+		CHECKGLERROR;
+	    }
+	    else if (isString(val) && length(val) > 0) {
+		tag = STRING_ELT(val, 0);
+		if (tag != R_NilValue && CHAR(tag)[0]) {
+		    SET_VECTOR_ELT(value, i, Query(dev, rglview, sub, CHAR(tag)));
+		    SET_STRING_ELT(newnames, i, tag);
+		    CHECKGLERROR;
+		}
+	    }
+	    else {
+		SET_VECTOR_ELT(value, i, R_NilValue);
+		SET_STRING_ELT(newnames, i, R_BlankString);
+	    }
+	}
+	setAttrib(value, R_NamesSymbol, newnames);
+	UNPROTECT(2);
+    }
+    else {
+    	error(_("invalid parameter passed to par3d()"));
+    	return R_NilValue/* -Wall */;
+    }
+    return value;
+}
+
+
diff --git a/src/pixmap.cpp b/src/pixmap.cpp
new file mode 100644
index 0000000..e16b8d1
--- /dev/null
+++ b/src/pixmap.cpp
@@ -0,0 +1,157 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: pixmap.cpp 1436 2016-01-01 15:18:43Z murdoch $
+
+#include "pixmap.h"
+using namespace std;
+
+#include "lib.h"
+
+// PNG FORMAT IMPLEMENTATION
+
+using namespace rgl;
+
+#ifdef HAVE_PNG_H
+#include "pngpixmap.h"
+namespace rgl {
+PNGPixmapFormat png;
+}
+#endif
+
+// PIXMAP FORMAT TABLE
+
+PixmapFormat* rgl::pixmapFormat[PIXMAP_FILEFORMAT_LAST] =
+{
+  
+// PNG FORMAT
+  
+#ifdef HAVE_PNG_H
+  &png,
+#else
+  NULL,
+#endif
+
+
+};
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Pixmap
+//
+
+Pixmap::Pixmap()
+{
+  typeID = INVALID;
+  width = 0;
+  height = 0;
+  bits_per_channel = 0;
+  data = NULL;
+  bytesperrow = 0;
+}
+
+Pixmap::~Pixmap()
+{
+  if (data)
+    delete[] data;
+}
+
+bool Pixmap::init(PixmapTypeID in_typeID, int in_width, int in_height, int in_bits_per_channel) 
+{
+  if (data)
+    delete data;
+  
+  typeID = in_typeID;
+  width  = in_width;
+  height = in_height;
+  bits_per_channel = in_bits_per_channel;
+  
+  int channels;
+
+  if (typeID == RGB24)
+    channels = 3;
+  else if (typeID == RGBA32)
+    channels = 4;
+  else if (typeID == GRAY8)
+    channels = 1;
+  else
+    return false;
+
+  bytesperrow = ( (channels * bits_per_channel) >> 3 ) * width;
+
+  data = new unsigned char [ bytesperrow * height ];
+  
+  if (data)
+    return true;
+  else
+    return false;
+}
+
+void Pixmap::clear()
+{
+  if (data) 
+    memset(data, 0, bytesperrow * height);
+}
+
+bool Pixmap::load(const char* filename)
+{
+  bool success = false;
+
+  std::FILE* file = NULL;
+
+  file = fopen(filename, "rb");
+  if (!file) {
+    char buffer[256];
+    sprintf(buffer, "Pixmap load: unable to open file '%s' for reading", filename);
+    printMessage(buffer);
+    return false;
+  }
+
+  bool support = false;
+
+  for(int i=0;i<PIXMAP_FILEFORMAT_LAST;i++) {
+
+    PixmapFormat* format;
+
+    format = pixmapFormat[i];
+
+    if ( (format) && (format->checkSignature(file) ) ) {
+      support = true;
+      success = format->load(file, this);
+      break;
+    }
+  }
+
+  if (!support) {
+    printMessage("Pixmap load: file format unsupported");
+  }
+  
+  if (!success) {
+    printMessage("Pixmap load: failed");
+  }
+
+  fclose(file);
+  
+  return success;
+}
+
+
+bool Pixmap::save(PixmapFormat* format, const char* filename)
+{
+  std::FILE* file = NULL;
+
+  file = fopen(filename, "wb");
+  if (!file) {
+    char buffer[256];
+    sprintf(buffer, "Pixmap save: unable to open file '%s' for writing", filename);
+    printMessage(buffer);
+    return false;
+  }
+  
+  bool success = format->save(file, this);
+
+  fclose(file);
+
+  return success;
+}
diff --git a/src/pixmap.h b/src/pixmap.h
new file mode 100644
index 0000000..9c6189a
--- /dev/null
+++ b/src/pixmap.h
@@ -0,0 +1,54 @@
+#ifndef PIXMAP_H
+#define PIXMAP_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: pixmap.h 1158 2014-11-11 17:27:21Z murdoch $
+
+#include <cstdio>
+#include "opengl.h"
+
+namespace rgl {
+
+class PixmapFormat;
+  
+enum PixmapTypeID { INVALID=0, RGB24, RGB32, RGBA32, GRAY8 };
+
+enum PixmapFileFormatID {
+PIXMAP_FILEFORMAT_PNG = 0,
+PIXMAP_FILEFORMAT_LAST
+};
+
+class Pixmap {
+public:
+  
+  Pixmap();
+  ~Pixmap();
+  bool init(PixmapTypeID typeID, int width, int height, int bits_per_channel);
+  bool load(const char* filename);
+  bool save(PixmapFormat* format, const char* filename);
+  void clear();
+  PixmapTypeID typeID;
+  unsigned int width;
+  unsigned int height;
+  unsigned int bits_per_channel;
+  unsigned int bytesperrow;
+  unsigned char *data;
+};
+
+
+class PixmapFormat {
+public:
+  virtual ~PixmapFormat() { }  
+  virtual bool checkSignature(std::FILE* file) = 0;
+  virtual bool load(std::FILE* file, Pixmap* pixmap) = 0;
+  virtual bool save(std::FILE* file, Pixmap* pixmap) = 0;
+};
+
+
+extern PixmapFormat* pixmapFormat[PIXMAP_FILEFORMAT_LAST];
+
+} // namespace rgl
+
+#endif /* PIXMAP_H */
diff --git a/src/platform.cpp b/src/platform.cpp
new file mode 100644
index 0000000..08ac0e8
--- /dev/null
+++ b/src/platform.cpp
@@ -0,0 +1,77 @@
+// C++ source
+// This file is part of RGL.
+//
+
+#include "platform.h"
+
+/*  MacOSX */
+
+#ifdef RGL_OSX
+
+#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9
+  // pre-Mavericks code
+#else
+  // Mavericks and later
+  
+#include <GLKit/GLKMathUtils.h> 
+#include <GLKit/GLKVector3.h>
+#include <GLKit/GLKMatrix4.h>
+  
+GLint gluProject(GLdouble  objX,  GLdouble  objY,  GLdouble  objZ,  
+                 const GLdouble *  model,  const GLdouble *  proj,  
+                 const GLint *  view,  GLdouble*  winX,  GLdouble*  winY,  
+                 GLdouble*  winZ) 
+{
+  int glkview[] = {view[0], view[1], view[2], view[3]};
+  GLKVector3 result =
+  GLKMathProject(GLKVector3Make(objX, objY, objZ),
+                 GLKMatrix4Make(model[0],model[1],model[2],model[3],
+                 		model[4],model[5],model[6],model[7],
+                 		model[8],model[9],model[10],model[11],
+                 		model[12],model[13],model[14],model[15]),
+                 GLKMatrix4Make(proj[0],proj[1],proj[2],proj[3],
+                 		proj[4],proj[5],proj[6],proj[7],
+                 		proj[8],proj[9],proj[10],proj[11],
+                 		proj[12],proj[13],proj[14],proj[15]),
+                 glkview                 
+                 );
+  *winX = result.x;
+  *winY = result.y;
+  *winZ = result.z;
+  return GLU_TRUE;
+}   
+
+GLint gluUnProject(GLdouble  winX,  GLdouble  winY,  GLdouble  winZ,  
+                   const GLdouble *  model,  const GLdouble *  proj,  
+                   const GLint *  view,  GLdouble*  objX,  GLdouble*  objY,  
+                   GLdouble*  objZ)
+{
+  int glkview[] = {view[0], view[1], view[2], view[3]};
+  bool success;
+  GLKVector3 result =
+  GLKMathUnproject(GLKVector3Make(winX, winY, winZ),
+                 GLKMatrix4Make(model[0],model[1],model[2],model[3],
+                 		model[4],model[5],model[6],model[7],
+                 		model[8],model[9],model[10],model[11],
+                 		model[12],model[13],model[14],model[15]),
+                 GLKMatrix4Make(proj[0],proj[1],proj[2],proj[3],
+                 		proj[4],proj[5],proj[6],proj[7],
+                 		proj[8],proj[9],proj[10],proj[11],
+                 		proj[12],proj[13],proj[14],proj[15]),
+                 glkview,
+                 &success
+                 );
+  *objX = result.x;
+  *objY = result.y;
+  *objZ = result.z;
+  return success ? GLU_TRUE : GLU_FALSE;
+}               
+
+const GLubyte * gluErrorString(GLenum  error)
+{
+  return (GLubyte*)"glu Error";
+}
+                      
+#endif /* Mavericks */
+
+#endif /* RGL_OSX */
diff --git a/src/platform.h b/src/platform.h
new file mode 100644
index 0000000..21c52a4
--- /dev/null
+++ b/src/platform.h
@@ -0,0 +1,45 @@
+#ifndef PLATFORM_H
+#define PLATFORM_H
+
+/* These are some platform-specific definitions, currently to support MacOSX */
+
+#include "opengl.h"
+
+/*  MacOSX */
+
+#ifdef RGL_OSX
+
+#include <Availability.h>
+
+#ifndef __MAC_10_9
+#define __MAC_10_9 1090
+#endif
+
+#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9
+  // pre-Mavericks code
+#else
+  // Mavericks and later  
+  
+#define MODERN_OPENGL
+  
+#define gluProject rgl_gluProject
+#define gluUnProject rgl_gluUnProject
+#define gluErrorString rgl_gluErrorString
+  
+GLint gluProject(GLdouble  objX,  GLdouble  objY,  GLdouble  objZ,  
+                 const GLdouble *  model,  const GLdouble *  proj,  
+                 const GLint *  view,  GLdouble*  winX,  GLdouble*  winY,  
+                 GLdouble*  winZ);
+                 
+GLint gluUnProject(GLdouble  winX,  GLdouble  winY,  GLdouble  winZ,  
+                   const GLdouble *  model,  const GLdouble *  proj,  
+                   const GLint *  view,  GLdouble*  objX,  GLdouble*  objY,  
+                   GLdouble*  objZ);
+                   
+const GLubyte * gluErrorString(GLenum  error);
+                 
+#endif /* Mavericks */
+
+#endif /* RGL_OSX */
+
+#endif /* PLATFORM_H */
diff --git a/src/pngpixmap.h b/src/pngpixmap.h
new file mode 100644
index 0000000..0072bd3
--- /dev/null
+++ b/src/pngpixmap.h
@@ -0,0 +1,414 @@
+#include "lib.h"
+#include "types.h"
+#include <png.h>
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: pngpixmap.h 1197 2014-12-20 19:07:08Z murdoch $
+
+namespace rgl {
+
+class PNGPixmapFormat : public PixmapFormat {
+public:
+  PNGPixmapFormat()
+  {
+  }
+
+  bool checkSignature(std::FILE* fd)
+  {
+    unsigned char buf[8];
+
+    if (fread(buf, 1, 8, fd) < 8)
+      return false;
+    fseek(fd, 0, SEEK_SET);
+
+    return !png_sig_cmp(buf, 0, 8);
+  }
+
+  bool load(std::FILE* fd, Pixmap* pixmap)
+  {
+    Load load(fd, pixmap);
+
+    if (load.init()) {
+      bool success;
+      success = load.process();
+      if (!success)
+        printMessage("pixmap png loader: process failed");
+      return success;
+    } else {
+      printMessage("pixmap png loader: init failed");
+      return false;
+    }
+  }
+
+  bool save(std::FILE* fd, Pixmap* pixmap)
+  {
+    Save save(fd, pixmap);
+
+    if (save.init())
+      return save.process();
+    else
+      return false;
+  }
+
+private:
+
+  //
+  // CLASS
+  //   Load
+  //
+
+  class Load {
+  public:
+
+    Load(std::FILE* _file, Pixmap* _pixmap)
+    {
+      file     = _file;
+      pixmap   = _pixmap;
+      png_ptr  = NULL;
+      info_ptr = NULL;
+      finish   = false;
+      error    = false;
+    }
+
+    bool init(void) 
+    {
+      bool success = false;
+
+      png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, (png_voidp)this, error_callback, warning_callback);
+
+      if (png_ptr) {
+        info_ptr = png_create_info_struct(png_ptr);
+        if (info_ptr) {
+          png_set_progressive_read_fn(png_ptr, (void *)this, info_callback, row_callback, end_callback);
+          success = true;
+        } 
+      } 
+      
+      return success;
+    }
+
+    bool process()
+    {
+      while ((!feof(file)) && (!error)) {
+        int size = fread(buffer,1,sizeof(buffer),file);
+        if (ferror(file)) {
+          printError("file read error");
+          return false;
+        }
+        png_process_data(png_ptr, info_ptr, buffer, size);
+      }
+
+      return finish;
+    }
+
+    ~Load() 
+    {
+      if (png_ptr)
+        png_destroy_read_struct(&png_ptr, (info_ptr) ? &info_ptr : NULL, (png_infopp)NULL);
+    }
+
+  private:
+
+    static void printError(const char* error_msg) {
+      char buf[256];
+      sprintf(buf, "PNG Pixmap Loader Error: %s", error_msg);
+      printMessage(buf);
+    }
+
+    static void printWarning(const char* warning_msg) {
+      char buf[256];
+      sprintf(buf, "PNG Pixmap Loader Warning: %s", warning_msg);
+      printMessage(buf);
+    }
+
+
+    static void error_callback(png_structp png_ptr, png_const_charp error_msg) {
+
+//      Load* load = (Load*) png_get_error_ptr(png_ptr);
+      printError( (const char*) error_msg );
+
+    }
+
+    static void warning_callback(png_structp png_ptr, png_const_charp warning_msg) {
+
+//      Load* load = (Load*) png_get_error_ptr(png_ptr);
+      printWarning( (const char*) warning_msg );
+
+    }
+
+
+    static void info_callback(png_structp png_ptr, png_infop info) 
+    {
+      char buffer[256];
+      Load* load = (Load*) png_get_progressive_ptr(png_ptr);
+
+      png_uint_32 width, height;
+      int  bit_depth, color_type, interlace_type, compression_type, filter_type;
+
+      png_get_IHDR(load->png_ptr, load->info_ptr, &width, &height,
+       &bit_depth, &color_type, &interlace_type,
+       &compression_type, &filter_type);
+
+
+      char* color_type_name;
+
+      switch(color_type) {
+        case PNG_COLOR_TYPE_RGB:
+          color_type_name = (char*)"RGB";
+          break;
+        case PNG_COLOR_TYPE_GRAY:
+          color_type_name = (char*)"GRAY";
+          break;
+        case PNG_COLOR_TYPE_PALETTE:
+          color_type_name = (char*)"INDEX";
+          break;
+        case PNG_COLOR_TYPE_RGB_ALPHA:
+          color_type_name = (char*)"RGBALPHA";
+          break;
+        case PNG_COLOR_TYPE_GRAY_ALPHA:
+          color_type_name = (char*)"GRAYALPHA";
+          break;
+        default:
+          color_type_name = (char*)"unknown";
+          break;
+      };
+
+      const char* interlace_string = (interlace_type == PNG_INTERLACE_ADAM7) ? "adam7 interlace " : "";
+
+      if (bit_depth == 16)
+        png_set_strip_16(png_ptr);
+      else if (bit_depth < 8  && color_type == PNG_COLOR_TYPE_GRAY)
+        png_set_expand_gray_1_2_4_to_8(png_ptr);
+      else if (bit_depth != 8)  /* this should never happen with current formats... */
+        goto unsupported;
+      
+      if (interlace_type == PNG_INTERLACE_ADAM7)
+        goto unsupported;
+
+      PixmapTypeID typeID;
+
+      switch(color_type) {
+        case PNG_COLOR_TYPE_RGB:
+          typeID = RGB24;
+          goto init;
+        case PNG_COLOR_TYPE_GRAY:
+          typeID = GRAY8;
+          goto init;
+        case PNG_COLOR_TYPE_RGB_ALPHA:
+          typeID = RGBA32;
+          goto init;        
+        case PNG_COLOR_TYPE_PALETTE:
+          png_set_palette_to_rgb(png_ptr);
+          typeID = RGB24;
+          goto init;
+        case PNG_COLOR_TYPE_GRAY_ALPHA:
+          png_set_gray_to_rgb(png_ptr);
+          typeID = RGBA32;
+          goto init;
+        default:
+          goto unsupported;
+          break;
+      };
+
+init:
+      if (typeID == RGB24 && png_get_valid(png_ptr, info, PNG_INFO_tRNS)) {
+        png_set_tRNS_to_alpha(png_ptr);
+        typeID = RGBA32;
+      }
+      
+      load->pixmap->init(typeID, width,height,bit_depth);
+
+      png_read_update_info(load->png_ptr,load->info_ptr);
+      return;
+
+unsupported:
+      sprintf(buffer,"%s%s format unsupported: %lux%lu (%d bits per channel)", 
+              interlace_string, color_type_name, 
+              (long unsigned int)width, (long unsigned int)height, bit_depth);
+      printMessage(buffer);
+      load->error = true;
+      png_read_update_info(load->png_ptr,load->info_ptr);
+      return;
+
+
+      /* Do any setup here, including setting any of
+         the transformations mentioned in the Reading
+         PNG files section.  For now, you _must_ call
+         either png_start_read_image() or
+         png_read_update_info() after all the
+         transformations are set (even if you don't set
+         any).  You may start getting rows before
+         png_process_data() returns, so this is your
+         last chance to prepare for that.
+       */
+    }
+    static void row_callback(png_structp png_ptr, png_bytep new_row, png_uint_32 row_num, int pass)
+    {
+      Load* load = (Load*) png_get_progressive_ptr(png_ptr);
+
+      void* rowptr = load->pixmap->data + load->pixmap->bytesperrow * (load->pixmap->height-1-row_num);
+
+      memcpy(rowptr, new_row, load->pixmap->bytesperrow);
+    }
+
+    static void end_callback(png_structp png_ptr, png_infop info)
+    {
+      Load* load = (Load*) png_get_progressive_ptr(png_ptr);
+
+      load->finish = true;
+    /* This function is called after the whole image
+       has been read, including any chunks after the
+       image (up to and including the IEND).  You
+       will usually have the same info chunk as you
+       had in the header, although some data may have
+       been added to the comments and time fields.
+
+       Most people won't do much here, perhaps setting
+       a flag that marks the image as finished.
+     */
+    }
+
+/*
+    static void end_callback(void) {
+  }
+ */
+
+    typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
+
+    std::FILE* file;
+    Pixmap* pixmap;
+
+    png_structp png_ptr;
+    png_infop info_ptr;
+    unsigned char buffer[4096];
+    bool error;
+    bool finish;
+
+  };
+
+
+  //
+  // CLASS
+  //   Save
+  //
+
+  class Save {
+  public:
+    Save(std::FILE* in_file, Pixmap* in_pixmap)
+    {
+      file     = in_file;
+      pixmap   = in_pixmap;
+      png_ptr  = NULL;
+      info_ptr = NULL;
+    }
+
+    bool init(void)
+    {
+      bool success = false;
+
+      png_ptr = png_create_write_struct (PNG_LIBPNG_VER_STRING, (png_voidp)this, error_callback, warning_callback);
+      
+      if (png_ptr) {
+        info_ptr = png_create_info_struct(png_ptr);
+        if (info_ptr) {
+          png_init_io(png_ptr, file);
+          success = true;
+        }
+      }
+
+      return success;
+    }
+
+    bool process(void)
+    {
+      if (setjmp(png_jmpbuf(png_ptr))) {
+        printError("an error occured");
+        png_destroy_write_struct(&png_ptr, &info_ptr);
+        return false;
+      }
+
+      png_set_filter(png_ptr, 0, PNG_FILTER_NONE);
+
+      
+      const int color_type = PNG_COLOR_TYPE_RGB;
+      const int interlace_type = PNG_INTERLACE_NONE;
+      const int compression_type = PNG_COMPRESSION_TYPE_DEFAULT;
+      const int filter_type = PNG_FILTER_TYPE_DEFAULT;
+
+      png_set_IHDR(png_ptr, info_ptr, 
+        pixmap->width, 
+        pixmap->height, pixmap->bits_per_channel, 
+        color_type, interlace_type, compression_type, filter_type);
+
+      png_text text[1];
+
+      text[0].key  = (png_charp)"Software";
+      text[0].text = (png_charp)"R/RGL package/libpng";
+      text[0].compression = PNG_TEXT_COMPRESSION_NONE;
+
+      png_set_text(png_ptr, info_ptr, text, sizeof(text)/sizeof(png_text) );
+      
+      png_write_info(png_ptr, info_ptr);
+
+      png_bytep rowptr = (png_bytep) ( ((u8*)pixmap->data) + (pixmap->height - 1) * pixmap->bytesperrow );
+
+      for(unsigned int i=0;i<pixmap->height;i++) {
+        png_write_row(png_ptr, rowptr);
+        rowptr -= pixmap->bytesperrow;
+      }
+
+      png_write_end(png_ptr, info_ptr);
+
+      return true;
+    }
+
+    ~Save()
+    {
+      if (png_ptr)
+        png_destroy_write_struct(&png_ptr, (info_ptr) ? &info_ptr : NULL);
+
+    }
+
+  private:
+
+    static void printError(const char* error_msg) {
+      char buf[256];
+      sprintf(buf, "PNG Pixmap Saver Error: %s", error_msg);
+      printMessage(buf);
+    }
+
+    static void printWarning(const char* warning_msg) {
+      char buf[256];
+      sprintf(buf, "PNG Pixmap Saver Warning: %s", warning_msg);
+      printMessage(buf);
+    }
+
+
+    static void error_callback(png_structp png_ptr, png_const_charp error_msg) {
+
+//      Save* save = (Save*) png_get_error_ptr(png_ptr);
+      printError( (const char*) error_msg );
+
+    }
+
+    static void warning_callback(png_structp png_ptr, png_const_charp warning_msg) {
+
+//      Save* save = (Save*) png_get_error_ptr(png_ptr);
+      printWarning( (const char*) warning_msg );
+
+    }
+
+
+    std::FILE* file;
+    Pixmap* pixmap;
+
+    png_structp png_ptr;
+    png_infop info_ptr;
+
+  };
+
+};
+
+} // namespace rgl
diff --git a/src/pragma.h b/src/pragma.h
new file mode 100644
index 0000000..7f2dc84
--- /dev/null
+++ b/src/pragma.h
@@ -0,0 +1,52 @@
+#ifndef RGL_PRAGMA_H
+#define RGL_PRAGMA_H
+
+/**
+ * compiler- and platform-specific pragma's
+ **/
+
+//
+// ---[ Borland C++ ]---------------------------------------------------------
+//
+#ifdef __BCPLUSPLUS__
+#define _RWSTD_NO_EXCEPTIONS
+
+#define ARCH_X86
+
+#endif
+
+//
+// ---[ Microsoft Visual C++ ]------------------------------------------------
+//
+#ifdef _MSC_VER 
+
+
+#pragma warning(disable:4530)
+/**
+ * remove warnings on truncated 'debug information' to 255 characters
+ **/
+#pragma warning(disable:4786)
+
+/**
+ * remove warnings " 'this' : used in base member initializer list "
+ **/
+#pragma warning(disable:4355) 
+
+#ifdef _M_IX86
+#define ARCH_X86
+#endif
+
+#endif
+
+//
+// ---[ GCC ]-----------------------------------------------------------------
+//
+#ifdef __GNUC__
+
+#ifdef _X86_
+#define ARCH_X86
+#endif
+
+#endif
+
+#endif // RGL_PRAGMA_H
diff --git a/src/pretty.c b/src/pretty.c
new file mode 100644
index 0000000..55be9bf
--- /dev/null
+++ b/src/pretty.c
@@ -0,0 +1,216 @@
+/* This file is taken from the R sources, r61744 of src/appl/pretty.c, with minimal changes */
+
+#include "pretty.h"
+#include <math.h>
+#include <float.h>
+#include <R_ext/Applic.h>
+#include <Rmath.h>
+
+/*
+ *  R : A Computer Language for Statistical Data Analysis
+ *  Copyright (C) 1995-2012  The R Core Team
+ *
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, a copy is available at
+ *  http://www.r-project.org/Licenses/
+ */
+
+/* Pretty Intervals
+ * ----------------
+ * Constructs m "pretty" values which cover the given interval	*lo <= *up
+ *	m ~= *ndiv + 1	(i.e., ndiv := approximate number of INTERVALS)
+ *
+ * It is not quite clear what should happen for	 *lo = *up;
+ * S itself behaves quite funilly, then.
+ *
+ * In my opinion, a proper 'pretty' should always ensure
+ * *lo < *up, and hence *ndiv >=1 in the result.
+ * However, in S and here, we allow  *lo == *up, and *ndiv = 0.
+ * Note however, that we are NOT COMPATIBLE to S. [Martin M.]
+ *
+ * NEW (0.63.2): ns, nu are double (==> no danger of integer overflow)
+ *
+ * We determine
+ * if the interval (up - lo) is ``small'' [<==>	 i_small == TRUE, below].
+ * For the ``i_small'' situation, there is a parameter  shrink_sml,
+ * the factor by which the "scale" is shrunk.		~~~~~~~~~~
+ * It is advisable to set it to some (smaller) integer power of 2,
+ * since this enables exact floating point division.
+ */
+ 
+/* Leave out all the R includes that we can 
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#ifdef ENABLE_NLS
+#include <libintl.h>
+#define _(String) gettext (String)
+#else
+#define _(String) (String)
+#endif
+
+#include <math.h>
+#include <float.h>
+#include <R_ext/Applic.h>
+#include <Rmath.h>
+#include <R_ext/Error.h>
+#ifdef DEBUGpr
+# include <R_ext/Print.h>
+#endif
+
+#ifdef HAVE_VISIBILITY_ATTRIBUTE
+# define attribute_hidden __attribute__ ((visibility ("hidden")))
+#else
+# define attribute_hidden
+#endif
+
+*/
+
+/* non-API, used by rgl */
+double R_pretty0(double *lo, double *up, int *ndiv, int min_n,
+	       double shrink_sml, double high_u_fact[],
+	       int eps_correction, int return_bounds)
+{
+/* From version 0.65 on, we had rounding_eps := 1e-5, before, r..eps = 0
+ * 1e-7 is consistent with seq.default() */
+#define rounding_eps 1e-7
+
+#define h  high_u_fact[0]
+#define h5 high_u_fact[1]
+
+    double dx, cell, unit, base, U;
+    double ns, nu;
+    int k;
+    Rboolean i_small;
+
+    dx = *up - *lo;
+    /* cell := "scale"	here */
+    if(dx == 0 && *up == 0) { /*  up == lo == 0	 */
+	cell = 1;
+	i_small = TRUE;
+    } else {
+	cell = fmax2(fabs(*lo),fabs(*up));
+	/* U = upper bound on cell/unit */
+	U = (1 + (h5 >= 1.5*h+.5)) ? 1/(1+h) : 1.5/(1+h5);
+	/* added times 3, as several calculations here */
+	i_small = dx < cell * U * imax2(1,*ndiv) * DBL_EPSILON *3;
+    }
+
+    /*OLD: cell = FLT_EPSILON+ dx / *ndiv; FLT_EPSILON = 1.192e-07 */
+    if(i_small) {
+        if(cell > 10)
+	    cell = 9 + cell/10;
+	cell *= shrink_sml;
+	if(min_n > 1) cell /= min_n;
+    } else {
+	cell = dx;
+	if(*ndiv > 1) cell /= *ndiv;
+    }
+
+    if(cell < 20*DBL_MIN) {
+      /* warning(_("Internal(pretty()): very small range.. corrected")); */
+      cell = 20*DBL_MIN;
+    } else if(cell * 10 > DBL_MAX) {
+      /* warning(_("Internal(pretty()): very large range.. corrected")); */
+      cell = .1*DBL_MAX;
+    }
+    base = pow(10., floor(log10(cell))); /* base <= cell < 10*base */
+
+    /* unit : from { 1,2,5,10 } * base
+     *	 such that |u - cell| is small,
+     * favoring larger (if h > 1, else smaller)  u  values;
+     * favor '5' more than '2'  if h5 > h  (default h5 = .5 + 1.5 h) */
+    unit = base;
+    if((U = 2*base)-cell <  h*(cell-unit)) { unit = U;
+    if((U = 5*base)-cell < h5*(cell-unit)) { unit = U;
+    if((U =10*base)-cell <  h*(cell-unit)) unit = U; }}
+    /* Result: c := cell,  u := unit,  b := base
+     *	c in [	1,	      (2+ h) /(1+h) ] b ==> u=  b
+     *	c in ( (2+ h)/(1+h),  (5+2h5)/(1+h5)] b ==> u= 2b
+     *	c in ( (5+2h)/(1+h), (10+5h) /(1+h) ] b ==> u= 5b
+     *	c in ((10+5h)/(1+h),	         10 ) b ==> u=10b
+     *
+     *	===>	2/5 *(2+h)/(1+h)  <=  c/u  <=  (2+h)/(1+h)	*/
+
+    ns = floor(*lo/unit+rounding_eps);
+    nu = ceil (*up/unit-rounding_eps);
+#ifdef DEBUGpr
+    REprintf("pretty(lo=%g,up=%g,ndiv=%d,min_n=%d,shrink=%g,high_u=(%g,%g),"
+	     "eps=%d)\n\t dx=%g; is.small:%d. ==> cell=%g; unit=%g\n",
+	     *lo, *up, *ndiv, min_n, shrink_sml, h, h5,
+	      eps_correction,	dx, (int)i_small, cell, unit);
+#endif
+    if(eps_correction && (eps_correction > 1 || !i_small)) {
+        if(*lo) *lo *= (1- DBL_EPSILON); else *lo = -DBL_MIN;
+        if(*up) *up *= (1+ DBL_EPSILON); else *up = +DBL_MIN;
+    }
+
+#ifdef DEBUGpr
+    if(ns*unit > *lo)
+	REprintf("\t ns= %.0f -- while(ns*unit > *lo) ns--;\n", ns);
+#endif
+    while(ns*unit > *lo + rounding_eps*unit) ns--;
+
+#ifdef DEBUGpr
+    if(nu*unit < *up)
+	REprintf("\t nu= %.0f -- while(nu*unit < *up) nu++;\n", nu);
+#endif
+    while(nu*unit < *up - rounding_eps*unit) nu++;
+
+    k = (int)(0.5 + nu - ns);
+    if(k < min_n) {
+	/* ensure that	nu - ns	 == min_n */
+#ifdef DEBUGpr
+	REprintf("\tnu-ns=%.0f-%.0f=%d SMALL -> ensure nu-ns= min_n=%d\n",
+		 nu,ns, k, min_n);
+#endif
+	k = min_n - k;
+	if(ns >= 0.) {
+	    nu += k/2;
+	    ns -= k/2 + k%2;/* ==> nu-ns = old(nu-ns) + min_n -k = min_n */
+	} else {
+	    ns -= k/2;
+	    nu += k/2 + k%2;
+	}
+	*ndiv = min_n;
+    }
+    else {
+	*ndiv = k;
+    }
+    if(return_bounds) { /* if()'s to ensure that result covers original range */
+        if(ns * unit < *lo) *lo = ns * unit;
+        if(nu * unit > *up) *up = nu * unit;
+    } else {
+        *lo = ns;
+	*up = nu;
+    }
+#ifdef DEBUGpr
+    REprintf("\t ns=%.0f ==> lo=%g\n", ns, *lo);
+    REprintf("\t nu=%.0f ==> up=%g  ==> ndiv = %d\n", nu, *up, *ndiv);
+#endif
+    return unit;
+#undef h
+#undef h5
+}
+
+/*
+attribute_hidden
+void R_pretty(double *lo, double *up, int *ndiv, int *min_n,
+	      double *shrink_sml, double *high_u_fact, int *eps_correction)
+{
+    R_pretty0(lo, up, ndiv,
+	    *min_n, *shrink_sml, high_u_fact, *eps_correction, 1);
+}
+*/
diff --git a/src/pretty.h b/src/pretty.h
new file mode 100644
index 0000000..fdacfb8
--- /dev/null
+++ b/src/pretty.h
@@ -0,0 +1,17 @@
+#ifndef RGL_PRETTY_H
+#define RGL_PRETTY_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+double R_pretty0(double *lo, double *up, int *ndiv, int min_n,
+	       double shrink_sml, double high_u_fact[],
+	       int eps_correction, int return_bounds);
+	       
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* RGL_API_H */
+	       
diff --git a/src/render.cpp b/src/render.cpp
new file mode 100644
index 0000000..f0263fc
--- /dev/null
+++ b/src/render.cpp
@@ -0,0 +1,139 @@
+#include "render.h"
+
+#include "opengl.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  SECTION: MATERIAL
+//
+//////////////////////////////////////////////////////////////////////////////
+
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   VertexArray
+//
+
+VertexArray::VertexArray()
+{
+  arrayptr = NULL;
+}
+
+VertexArray::~VertexArray()
+{
+  if (arrayptr)
+    delete[] arrayptr;
+}
+
+void VertexArray::alloc(int nvertex)
+{
+  if (arrayptr)
+    delete[] arrayptr;
+
+  arrayptr = new float [nvertex*3];
+}
+
+void VertexArray::copy(int nvertex, double* vertices)
+{
+  for(int i=0;i<nvertex;i++) {
+    arrayptr[i*3+0] = (float) vertices[i*3+0];
+    arrayptr[i*3+1] = (float) vertices[i*3+1];
+    arrayptr[i*3+2] = (float) vertices[i*3+2];
+  }
+}
+
+void VertexArray::setVertex(int index, double* v) {
+  arrayptr[index*3+0] = (float) v[0];
+  arrayptr[index*3+1] = (float) v[1];
+  arrayptr[index*3+2] = (float) v[2];
+}
+
+void VertexArray::beginUse() {
+  glEnableClientState(GL_VERTEX_ARRAY);
+  glVertexPointer(3, GL_FLOAT, 0, (const GLvoid*) arrayptr );
+}
+
+void VertexArray::endUse() {
+  glDisableClientState(GL_VERTEX_ARRAY);
+}
+
+Vertex VertexArray::getNormal(int iv1, int iv2, int iv3)
+{
+  Vertex normal;
+
+  Vertex& v1 = (*this)[iv1];
+  Vertex& v2 = (*this)[iv2];
+  Vertex& v3 = (*this)[iv3];
+
+  Vertex a(v3-v2), b(v1-v2);
+
+  normal = a.cross(b);
+
+  normal.normalize();
+
+  return normal;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   NormalArray
+//
+
+void NormalArray::beginUse() {
+  glEnableClientState(GL_NORMAL_ARRAY);
+  glNormalPointer(GL_FLOAT, 0, (const GLvoid*) arrayptr );
+}
+
+void NormalArray::endUse() {
+  glDisableClientState(GL_NORMAL_ARRAY);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   TexCoordArray
+//
+
+TexCoordArray::TexCoordArray()
+{
+  arrayptr = NULL;
+  nvertex = 0;
+}
+
+TexCoordArray::~TexCoordArray()
+{
+  if (arrayptr)
+    delete[] arrayptr;
+}
+
+void TexCoordArray::alloc(int in_nvertex)
+{
+  if (arrayptr) {
+    delete[] arrayptr;
+    arrayptr = NULL;
+  }
+  nvertex = in_nvertex;
+  if (nvertex)
+    arrayptr = new float[2*nvertex];
+}
+
+TexCoord& TexCoordArray::operator [] (int index) {
+  return (TexCoord&) arrayptr[index*2];
+}
+
+void TexCoordArray::beginUse() {
+  if (arrayptr) {
+    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+    glTexCoordPointer(2, GL_FLOAT, 0, (const GLvoid*) arrayptr );
+  }
+}
+
+void TexCoordArray::endUse() {
+  if (arrayptr)
+    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
+}
diff --git a/src/render.h b/src/render.h
new file mode 100644
index 0000000..62edab8
--- /dev/null
+++ b/src/render.h
@@ -0,0 +1,79 @@
+#ifndef RENDER_H
+#define RENDER_H
+
+#include "RenderContext.h"
+
+#include "types.h"
+
+namespace rgl {
+
+//
+// CLASS
+//   VertexArray
+//
+
+/**
+ * VertexArray
+ **/
+class VertexArray
+{
+public:
+
+  VertexArray();
+  ~VertexArray();
+
+  void alloc(int nvertex);
+  void copy(int nvertex, double* vertices);
+  void beginUse();
+  void endUse();
+  Vertex& operator[](int index);
+  void setVertex(int index, double* v);
+
+  Vertex getNormal(int v1, int v2, int v3);
+
+protected:
+  float* arrayptr;
+};
+
+inline Vertex& VertexArray::operator[](int index) {
+  return (Vertex&) arrayptr[index*3];
+}
+
+/**
+ * NormalArray
+ **/
+class NormalArray : public VertexArray 
+{
+public:
+  void beginUse();
+  void endUse();
+};
+
+struct TexCoord
+{
+  float s,t;
+};
+
+/**
+ * TexCoordArray
+ **/
+class TexCoordArray 
+{
+public:
+  TexCoordArray();
+  ~TexCoordArray();
+
+  void alloc(int in_nvertex);
+  void beginUse();
+  void endUse();
+  TexCoord& operator[](int index);
+  int size() { return nvertex; };
+
+private:
+  int nvertex;
+  float* arrayptr;
+};
+
+} // namespace rgl
+
+#endif // RENDER_H
diff --git a/src/rgl-win.def b/src/rgl-win.def
new file mode 100644
index 0000000..0a866b7
--- /dev/null
+++ b/src/rgl-win.def
@@ -0,0 +1,3 @@
+LIBRARY rgl.dll
+EXPORTS
+  R_init_rgl
\ No newline at end of file
diff --git a/src/rglmath.cpp b/src/rglmath.cpp
new file mode 100644
index 0000000..2bc9255
--- /dev/null
+++ b/src/rglmath.cpp
@@ -0,0 +1,334 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: rglmath.cpp 1137 2014-09-24 19:03:24Z murdoch $
+
+#include "rglmath.h"
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Vertex
+//
+
+void Vec3::normalize()
+{
+  float len = this->getLength();
+  if (len != 0.0f) {
+    float f = 1.0f/len;
+    x *= f;
+    y *= f;
+    z *= f;
+  }
+}
+
+Vec3 Vec3::cross(Vec3 op2) const
+{
+  Vec3 v;
+  v.x = y * op2.z - z * op2.y;
+  v.y = z * op2.x - x * op2.z;
+  v.z = x * op2.y - y * op2.x;
+  return v;
+}
+
+float Vec3::angle(const Vec3& that) const
+{
+  float dot;
+  dot = x*that.x + y*that.y + z*that.z;
+  return math::rad2deg(math::acos( dot/(this->getLength() * that.getLength())));
+
+}
+
+Vec3 Vec3::operator * (float s)
+{
+  Vec3 v;
+
+  v.x = x*s;
+  v.y = y*s;
+  v.z = z*s;
+
+  return v;
+}
+
+float Vec3::operator * (Vec3 v)
+{
+  return (x*v.x + y*v.y + z*v.z);
+}
+
+Vec3 Vec3::operator - (Vec3 op2) const 
+{
+  Vec3 v;
+
+  v.x = x - op2.x;
+  v.y = y - op2.y;
+  v.z = z - op2.z;
+
+  return v;
+}
+
+void Vec3::operator += (Vec3 op2) 
+{
+  x += op2.x;
+  y += op2.y;
+  z += op2.z;
+}
+
+Vec3 Vec3::scale(const Vec3& op2) const
+{
+  Vec3 t(*this);
+  t.x *= op2.x;
+  t.y *= op2.y;
+  t.z *= op2.z;
+  return t;
+}
+
+Vec3 Vertex::operator + (Vec3 op2) const
+{
+  Vec3 t(*this);
+
+  t += op2;
+
+  return t;
+}
+
+void Vec3::rotateX(float degree)
+{
+  Vec3 t(*this);
+
+  float rad = math::deg2rad(degree);
+  float s = math::sin(rad);
+  float c = math::cos(rad);
+
+  y = c*t.y + -s*t.z;
+  z = s*t.y +  c*t.z;
+}
+
+void Vec3::rotateY(float degree)
+{
+  Vec3 t(*this);
+
+  float rad = math::deg2rad(degree);
+  float s = math::sin(rad);
+  float c = math::cos(rad);
+
+  x =  c*t.x + s*t.z;
+  z = -s*t.x + c*t.z;
+}
+
+bool Vec3::missing() const
+{
+  return ISNAN(x) || ISNAN(y) || ISNAN(z);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Vec4
+//
+
+Vec4::Vec4(const float in_x, const float in_y, const float in_z, const float in_w)
+{
+  x = in_x;
+  y = in_y;
+  z = in_z;
+  w = in_w;
+}
+
+float Vec4::operator * (const Vec4& v) const
+{
+  return (x*v.x + y*v.y + z*v.z + w*v.w);
+}
+
+Vec4 Vec4::operator * (const float s) const
+{
+  Vec4 r;
+
+  r.x = x*s;
+  r.y = y*s;
+  r.z = z*s;
+  r.w = w*s;
+
+  return r;
+}
+
+Vec4 Vec4::operator + (const Vec4& v) const
+{
+  return Vec4(x+v.x, y+v.y, z+v.z, w+v.w);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Matrix4x4
+//
+
+Matrix4x4::Matrix4x4()
+{
+}
+
+Matrix4x4::Matrix4x4(const Matrix4x4& src)
+{
+  for(int i=0;i<16;i++)
+    data[i] = src.data[i];
+}
+
+Matrix4x4::Matrix4x4(const double* from) {
+  loadData(from);
+}
+
+void Matrix4x4::loadData(const double* from) {
+  for(int i=0;i<16;i++)
+    data[i] = (float) from[i];
+}
+
+void Matrix4x4::loadData(const float* from) {
+  for(int i=0;i<16;i++)
+    data[i] = from[i];
+}
+
+void Matrix4x4::loadData(const Matrix4x4& from) {
+  loadData(from.data);
+}
+
+Vec3 Matrix4x4::operator * (const Vec3 v) const {
+  Vec3 r;
+  const float v_w = 1.0f;
+
+  r.x = val(0,0) * v.x + val(0,1) * v.y + val(0,2) * v.z + val(0,3) * v_w;
+  r.y = val(1,0) * v.x + val(1,1) * v.y + val(1,2) * v.z + val(1,3) * v_w;
+  r.z = val(2,0) * v.x + val(2,1) * v.y + val(2,2) * v.z + val(2,3) * v_w;
+
+  return r;
+}
+
+Vec4 Matrix4x4::operator*(const Vec4& v) const {
+
+  Vec4 r;
+
+  r.x = val(0,0) * v.x + val(0,1) * v.y + val(0,2) * v.z + val(0,3) * v.w;
+  r.y = val(1,0) * v.x + val(1,1) * v.y + val(1,2) * v.z + val(1,3) * v.w;
+  r.z = val(2,0) * v.x + val(2,1) * v.y + val(2,2) * v.z + val(2,3) * v.w;
+  r.w = val(3,0) * v.x + val(3,1) * v.y + val(3,2) * v.z + val(3,3) * v.w;
+
+  return r;
+}
+
+bool Vec4::missing() const
+{
+  return ISNAN(x) || ISNAN(y) || ISNAN(z) || ISNAN(w);
+}
+
+
+
+Matrix4x4 Matrix4x4::operator * (const Matrix4x4& op2) const {
+
+  Matrix4x4 r;
+
+  for(int i=0;i<4;i++)
+    for(int j=0;j<4;j++) {
+      float tmp = 0;
+
+      for(int k=0;k<4;k++)
+        tmp += val(i, k) * op2.val(k, j);
+
+      r.ref(i,j) = tmp;
+    }
+
+  return r;
+}
+
+Vec4 Matrix4x4::getRow(int row) {
+  Vec4 r;
+  
+  r.x = val(row, 0);
+  r.y = val(row, 1);
+  r.z = val(row, 2);
+  r.w = val(row, 3);
+  
+  return r;
+}
+
+void Matrix4x4::setIdentity(void) {
+  for(int i=0;i<16;i++)
+    data[i] = 0.0f;
+  ref(0,0) = 1.0f;
+  ref(1,1) = 1.0f;
+  ref(2,2) = 1.0f;
+  ref(3,3) = 1.0f;
+}
+
+void Matrix4x4::setRotate(const int axis, const float degree) {
+  float rad = math::deg2rad(degree);
+  float s   = math::sin(rad);
+  float c   = math::cos(rad);
+  setIdentity();
+  switch(axis) {
+    case 0:
+      ref(1,1) = c;
+      ref(1,2) = -s;
+      ref(2,1) = s;
+      ref(2,2) = c;
+      break;
+    case 1:
+      ref(0,0) = c;
+      ref(0,2) = s;
+      ref(2,0) = -s;
+      ref(2,2) = c;
+      break;
+    case 2:
+      ref(0,0) = c;
+      ref(0,1) = -s;
+      ref(1,0) = s;
+      ref(1,1) = c;
+      break;
+  }
+}
+
+void Matrix4x4::transpose() {
+  for (int i = 0; i < 3; i++)
+    for (int j = i+1; j < 4; j++) {
+      float temp = val(i,j);
+      ref(i,j) = val(j,i);
+      ref(j,i) = temp;
+    }
+}
+
+void Matrix4x4::getData(double* dest)
+{
+	for(int i=0;i<16;i++)
+    	dest[i] = data[i];
+}
+
+Matrix4x4 Matrix4x4::scaleMatrix(double sx, double sy, double sz)
+{
+  Matrix4x4 result;
+  result.setIdentity();
+  result.ref(0,0) = sx;
+  result.ref(1,1) = sy;
+  result.ref(2,2) = sz;
+  return result;
+}
+
+Matrix4x4 Matrix4x4::translationMatrix(double x, double y, double z)
+{
+  Matrix4x4 result;
+  result.setIdentity();
+  result.ref(0,3) = x;
+  result.ref(1,3) = y;
+  result.ref(2,3) = z;
+  return result;
+}
+
+Vertex PolarCoord::vector() const { 
+  float t = math::deg2rad(theta);
+  float p = math::deg2rad(phi);
+  return Vertex (
+    math::cos(p) * math::sin(t),
+    math::sin(p),
+    math::cos(p) * math::cos(t)
+  );
+}
+
diff --git a/src/rglmath.h b/src/rglmath.h
new file mode 100644
index 0000000..7fb2297
--- /dev/null
+++ b/src/rglmath.h
@@ -0,0 +1,232 @@
+#ifndef RGL_MATH_H
+#define RGL_MATH_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: rglmath.h 1137 2014-09-24 19:03:24Z murdoch $
+
+#include <cmath>
+#include <cfloat>
+
+using namespace std;
+
+#include "types.h"
+
+#ifndef M_PI
+#define M_PI      3.1415926535897932384626433832795
+#endif
+
+namespace rgl {
+
+namespace math {
+
+  // template-based math functions with default 'double' implementation using math.h
+
+  template<typename T> inline T acos(T x) { return static_cast<T>( ::acos( static_cast<double>(x) ) ); }
+  template<typename T> inline T asin(T x) { return static_cast<T>( ::asin( static_cast<double>(x) ) ); }
+  template<typename T> inline T atan(T x) { return static_cast<T>( ::atan( static_cast<double>(x) ) ); }
+  template<typename T> inline T atan2(T x, T y) { return static_cast<T>( ::atan2( static_cast<double>(x), static_cast<double>(y) ) ); }
+  template<typename T> inline T cos(T x) { return static_cast<T>( ::cos( static_cast<double>(x) ) ); }
+  template<typename T> inline T sin(T x) { return static_cast<T>( ::sin( static_cast<double>(x) ) ); }
+#ifdef HAVE_SINF
+  template<> inline float sin(float rad) { return ::sinf(rad); }
+#endif
+  template<typename T> inline T tan(T x) { return static_cast<T>( ::tan( static_cast<double>(x) ) ); }
+  // template<typename T> inline T acosh(T x) { return static_cast<T>( ::acosh( static_cast<double>(x) ) ); }
+  // template<typename T> inline T asinh(T x) { return static_cast<T>( ::asinh( static_cast<double>(x) ) ); }
+  // template<typename T> inline T atanh(T x) { return static_cast<T>( ::atanh( static_cast<double>(x) ) ); }
+  // template<typename T> inline T cosh(T x) { return static_cast<T>( ::cosh( static_cast<double>(x) ) ); }
+  // template<typename T> inline T sinh(T x) { return static_cast<T>( ::sinh( static_cast<double>(x) ) ); }
+  // template<typename T> inline T tanh(T x) { return static_cast<T>( ::tanh( static_cast<double>(x) ) ); }
+  template<typename T> inline T exp(T x) { return static_cast<T>( ::exp( static_cast<double>(x) ) ); }
+//  template<typename T> inline T exp2(T x) { return static_cast<T>( ::exp2( static_cast<double>(x) ) ); }
+//  template<typename T> inline T expm1(T x) { return static_cast<T>( ::expm1( static_cast<double>(x) ) ); }
+  template<typename T> inline T log(T x) { return static_cast<T>( ::log( static_cast<double>(x) ) ); }
+  template<typename T> inline T log10(T x) { return static_cast<T>( ::log10( static_cast<double>(x) ) ); }
+//  template<typename T> inline T log2(T x) { return static_cast<T>( ::log2( static_cast<double>(x) ) ); }
+  template<typename T> inline T log1p(T x) { return static_cast<T>( ::log1p( static_cast<double>(x) ) ); }
+  template<typename T> inline T logb(T x) { return static_cast<T>( ::logb( static_cast<double>(x) ) ); }
+  template<typename T> inline T modf(T x, T* y) { double i; double r = ::modf( static_cast<double>(x), &i ); *y = static_cast<T>(i); return static_cast<T>(r); }
+  template<> inline double modf(double x, double* y) { return ::modf(x,y); }
+  //template<> inline float  modf(float x, float* y) { return ::modff(x,y); }
+  template<typename T> inline T ldexp(T x, int y) { return static_cast<T>( ::ldexp(static_cast<double>(x),y) ); }
+//  template<typename T> inline T frexp(T x, int* y) { return static_cast<T>( ::frexp( static_cast<double>(x),n) ); }
+  template<typename T> inline int ilogb(T x) { return ::ilogb( static_cast<double>(x) ); }
+  template<typename T> inline T scalbn(T x, int n) { return static_cast<T>( ::scalbn( static_cast<double>(x),n ) ); }
+  template<typename T> inline T fabs(T x) { return static_cast<T>( ::fabs( static_cast<double>(x) ) ); }
+  template<typename T> inline T cbrt(T x) { return static_cast<T>( ::cbrt( static_cast<double>(x) ) ); }
+//  template<typename T> inline T hypot(T x) { return static_cast<T>( ::hypot( static_cast<double>(x) ) ); }
+  template<typename T> inline T pow(T x, T y) { return static_cast<T>( ::pow( static_cast<double>(x), static_cast<double>(y) ) ); }
+  template<typename T> inline T sqrt(T x) { return static_cast<T>( ::sqrt( static_cast<double>(x) ) ); }
+  template<typename T> inline T erf(T x) { return static_cast<T>( ::erf( static_cast<double>(x) ) ); }
+  template<typename T> inline T erfc(T x) { return static_cast<T>( ::erfc( static_cast<double>(x) ) ); }
+  template<typename T> inline T lgamma(T x) { return static_cast<T>( ::lgamma( static_cast<double>(x) ) ); }
+//  template<typename T> inline T tgamma(T x) { return static_cast<T>( ::tgamma( static_cast<double>(x) ) ); }
+  template<typename T> inline T ceil(T x) { return static_cast<T>( ::ceil( static_cast<double>(x) ) ); }
+  template<typename T> inline T floor(T x) { return static_cast<T>( ::floor( static_cast<double>(x) ) ); }
+//  template<typename T> inline T nearbyint(T x) { return static_cast<T>( ::nearbyint( static_cast<double>(x) ) ); }
+  template<typename T> inline T rint(T x) { return static_cast<T>( ::rint( static_cast<double>(x) ) ); }
+//  template<typename T> inline long int lrint(T x) { return ( ::lrint( static_cast<double>(x) ) ); }
+//  template<typename T> inline long long int llrint(T x) { return ::llrint( static_cast<double>(x) ); }
+//  template<typename T> inline T round(T x) { return static_cast<T>( ::round( static_cast<double>(x) ) ); }
+
+  template<class T> inline T pi() { return static_cast<T>( M_PI ); }  
+  template<class T> inline T deg2rad(T deg) { return ( pi<T>() / T(180.0) ) * deg; }
+  template<class T> inline T rad2deg(T rad) { return rad / ( pi<T>() / T(180.0) ); }
+
+}
+
+
+// inline float deg2radf(float deg) { return ((float)(PI/180.0)) * deg; }
+// inline float rad2degf(float rad) { return rad / ((float)(PI/180.0)); }
+
+// inline float deg2radf(float deg) { return deg2rad<float>(deg); }
+// inline float rad2degf(float rad) { return rad2deg<float>(rad); }
+
+
+struct Vec3
+{
+
+  float x,y,z;
+  
+  Vec3() : x(0),y(0),z(0) { }
+  Vec3(float in_x,float in_y, float in_z) : x(in_x), y(in_y), z(in_z) { }
+  Vec3(const Vec3& that) : x(that.x), y(that.y), z(that.z) { }
+  inline float getLength() const
+  {
+    return math::sqrt( x*x + y*y + z*z );
+  }
+  void normalize();
+  Vec3 cross(Vec3 op2) const;
+  float angle(const Vec3& op2) const;
+  float operator * (Vec3 op2);
+  Vec3 operator * (float value);
+  Vec3 operator+(Vec3 op2) const;
+  Vec3 operator-(Vec3 op2) const;
+  Vec3 scale(const Vec3& op2) const;
+  void   operator+=(Vec3 op2);
+  void   rotateX(float degree);
+  void   rotateY(float degree);
+  bool   missing() const;  /* Any components missing */
+
+  static inline Vec3& asVec3(float* ptr) {
+    return *( reinterpret_cast<Vec3*>( ptr ) );
+  }
+};
+
+template<>
+inline void copy(double* from, Vec3* to, int size)
+{
+  copy(from, (float*) to, size*3);
+}
+
+typedef Vec3    Vertex;
+typedef Vertex  Vertex3;
+typedef Vertex3 Normal;
+
+
+struct Vec4
+{
+  
+  float x,y,z,w;
+
+  Vec4(const Normal& n, float in_w=0.0f) : x(n.x), y(n.y), z(n.z), w(in_w) {};
+  Vec4() {};
+  Vec4(const float x, const float y, const float z, const float w=1.0f);
+  float operator * (const Vec4& op2) const;
+  Vec4 operator * (const float value) const;
+  Vec4 operator + (const Vec4& op2) const;
+  bool   missing() const;  /* Any components missing */
+
+  static inline Vec4& asVec4(float* ptr) {
+    return *( reinterpret_cast<Vec4*>( ptr ) );
+  }
+};
+
+class Matrix4x4
+{
+public:
+  Matrix4x4();
+  Matrix4x4(const Matrix4x4& src);
+  Matrix4x4(const double*);
+  Vec3 operator*(const Vec3 op2) const;
+  Vec4 operator*(const Vec4& op2) const;
+  Matrix4x4 operator*(const Matrix4x4& op2) const;
+  Vec4 getRow(int row);
+  void setIdentity(void);
+  void setRotate(const int axis, const float degree);
+  void getData(double* dest);
+  void loadData(const double* from);
+  void loadData(const float* from);
+  void loadData(const Matrix4x4& from);
+  void transpose();
+  static Matrix4x4 scaleMatrix(double sx, double sy, double sz); 
+  static Matrix4x4 translationMatrix(double x, double y, double z);
+private:
+  inline float  val(int row, int column) const { return data[4*column+row]; }
+  inline float& ref(int row, int column) { return data[4*column+row]; }
+  float data[16];
+};
+
+
+//
+// CLASS
+//   RectSize
+//
+
+struct RectSize
+{
+  RectSize() : width(0), height(0) {};
+  RectSize(int in_width, int in_height) : width(in_width), height(in_height) {};
+  int width;
+  int height;
+};
+
+struct Rect2
+{
+  Rect2(int in_x, int in_y, int in_w, int in_h)
+  : x(in_x)
+  , y(in_y)
+  , width(in_w)
+  , height(in_h) 
+  { }
+  int x, y;
+  int width, height;
+};
+
+struct Rect2d
+{
+  Rect2d(double in_x, double in_y, double in_w, double in_h)
+  : x(in_x)
+  , y(in_y)
+  , width(in_w)
+  , height(in_h) 
+  { }
+  double x, y;
+  double width, height;
+};
+
+
+//
+// CLASS
+//   PolarCoord
+//
+
+struct PolarCoord
+{
+  PolarCoord(float in_theta=0.0f, float in_phi=0.0f) : theta(in_theta), phi(in_phi) {};
+  PolarCoord(const PolarCoord& src) : theta(src.theta), phi(src.phi) {};
+  PolarCoord operator + (const PolarCoord& op2) const { return PolarCoord(theta+op2.theta, phi+op2.phi); }
+  PolarCoord operator - (const PolarCoord& op2) const { return PolarCoord(theta-op2.theta, phi-op2.phi); }  
+  Vec3 vector() const;
+  float theta;
+  float phi;
+};
+
+
+typedef Vec4 Vertex4;
+
+} // namespace rgl
+
+#endif /* MATH_H */
diff --git a/src/rglview.cpp b/src/rglview.cpp
new file mode 100644
index 0000000..444391e
--- /dev/null
+++ b/src/rglview.cpp
@@ -0,0 +1,1027 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: rglview.cpp 1442 2016-01-04 13:08:15Z murdoch $
+
+
+
+#ifdef __sun
+#include <locale.h>
+#else
+#include <locale>
+#endif
+#include <cstdio>
+#include "rglview.h"
+#include "opengl.h"
+#include "lib.h"
+#include "rglmath.h"
+#include "pixmap.h"
+#include "fps.h"
+#include "select.h"
+#include "gl2ps.h"
+
+#include "R.h"		// for error()
+
+using namespace rgl;
+
+//
+// CAMERA config
+//
+
+#define ZOOM_MIN  0.0001f
+#define ZOOM_MAX  10000.0f
+
+RGLView::RGLView(Scene* in_scene)
+ : View(0,0,256,256,0), dragBase(0.0f,0.0f),dragCurrent(0.0f,0.0f), autoUpdate(false)
+{
+  scene = in_scene;
+  drag  = 0;
+  flags = 0;
+  selectState = msNONE;
+
+  setDefaultMouseFunc();
+  renderContext.rect.x = 0;
+  renderContext.rect.y = 0; // size is set elsewhere
+  
+  for (int i=0; i<3; i++) {
+    beginCallback[i] = NULL;
+    updateCallback[i] = NULL;
+    endCallback[i] = NULL;
+    cleanupCallback[i] = NULL;
+    for (int j=0; j<3; j++) 
+      userData[3*i + j] = NULL;
+  }
+}
+
+RGLView::~RGLView()
+{
+  for (int i=0; i<3; i++) 
+    if (cleanupCallback[i]) 
+      (*cleanupCallback[i])(userData + 3*i);
+}
+
+void RGLView::show()
+{
+  fps.init( getTime() );
+}
+
+void RGLView::hide()
+{
+  autoUpdate=false;
+}
+
+
+void RGLView::setWindowImpl(WindowImpl* impl) {
+  View::setWindowImpl(impl);
+
+#if defined HAVE_FREETYPE
+  renderContext.font = impl->getFont("sans", 1, 1, true);
+#else
+  renderContext.font = impl->fonts[0];
+#endif
+}
+
+Scene* RGLView::getScene() {
+  return scene;
+}
+
+void RGLView::resize(int in_width, int in_height) {
+
+  View::resize(in_width, in_height);
+
+  renderContext.rect.width = in_width;
+  renderContext.rect.height = in_height;
+  
+  update();
+
+  if (drag) captureLost();
+}
+
+void RGLView::paint(void) {
+
+  double last = renderContext.time;
+  double t    = getTime();
+
+  double dt   = (last != 0.0f) ? last - t : 0.0f;
+  
+  renderContext.time = t;
+  renderContext.deltaTime = dt;
+  
+  /* This doesn't do any actual plotting, but it calculates matrices etc. */
+  scene->update(&renderContext);
+
+  /* This section does the OpenGL plotting */
+  if (windowImpl->beginGL()) {
+    SAVEGLERROR;  
+    scene->render(&renderContext);
+    glViewport(0,0, width, height);
+    if (selectState == msCHANGING)
+      select.render(mousePosition);
+    if (flags & FSHOWFPS && selectState == msNONE)
+      fps.render(renderContext.time, &renderContext );
+
+    glFinish();
+    windowImpl->endGL();
+    
+    SAVEGLERROR;
+  }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// user input
+//
+
+// NB:  This code has to deal with three conflicting descriptions of pixel locations.
+//      The calls to buttonPress, buttonRelease, etc. are given in OS window-relative
+//      coordinates, which count mouseX from the left, mouseY down from the top.
+//      These are translated into the OpenGL convention which counts Y up from the bottom,
+//      or subscene-relative coordinates, up from the bottom of the viewport.
+//      We use RGLView::translateCoords to go from OS window-relative to OpenGL window-relative,
+//      and Subscene::translateCoords to go from OpenGL window-relative to viewport-relative.
+
+void RGLView::keyPress(int key)
+{
+  switch(key) {
+    case GUI_KeyF1:
+      flags ^= FSHOWFPS;
+      windowImpl->update();
+      break;
+    case GUI_KeyESC:
+      selectState = msABORT;
+      break;
+  }
+}
+
+void RGLView::buttonPress(int button, int mouseX, int mouseY)
+{
+    ModelViewpoint* modelviewpoint = scene->getCurrentSubscene()->getModelViewpoint();
+      if ( modelviewpoint->isInteractive() ) {
+	if (!drag) {
+	  translateCoords(&mouseX, &mouseY);
+	  Subscene* subscene = scene->whichSubscene(mouseX, mouseY);
+	  subscene->translateCoords(&mouseX, &mouseY);
+	  drag = button;
+	  activeSubscene = subscene->getObjID();
+	  vwidth = subscene->pviewport.width;
+	  vheight = subscene->pviewport.height;
+	  windowImpl->captureMouse(this);	  
+	  (this->*ButtonBeginFunc[button-1])(mouseX, mouseY);
+	}
+      }
+}
+
+
+void RGLView::buttonRelease(int button, int mouseX, int mouseY)
+{
+  	if (drag == button) {
+	    windowImpl->releaseMouse();
+	    drag = 0;
+	    (this->*ButtonEndFunc[button-1])();
+	    activeSubscene = 0;
+ 	}
+}
+
+void RGLView::mouseMove(int mouseX, int mouseY)
+{
+    if (drag) {
+        translateCoords(&mouseX, &mouseY);
+    	Subscene* subscene = scene->getSubscene(activeSubscene);
+    	if (!subscene) { /* it may have been killed */
+    	  buttonRelease(drag, mouseX, mouseY);
+    	  return;
+    	}
+    	subscene->translateCoords(&mouseX, &mouseY);
+
+	vwidth = subscene->pviewport.width; /* These may have changed */
+	vheight = subscene->pviewport.height;    	  
+    	
+  	mouseX = clamp(mouseX, 0, vwidth-1);
+  	mouseY = clamp(mouseY, 0, vheight-1);
+
+  	(this->*ButtonUpdateFunc[drag-1])(mouseX,mouseY);
+    }
+}
+
+void RGLView::wheelRotate(int dir)
+{
+  (this->*WheelRotateFunc)(dir);
+}
+
+void RGLView::captureLost()
+{
+  if (drag) {
+    (this->*ButtonEndFunc[drag-1])();
+    drag = 0;
+  }
+}
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// INTERACTIVE FEATURE
+//   adjustDirection
+//
+
+//
+// FUNCTION
+//   screenToPolar
+//
+// DESCRIPTION
+//   screen space is the same as in OpenGL, starting 0,0 at left/bottom(!) of viewport
+//
+
+static PolarCoord screenToPolar(int width, int height, int mouseX, int mouseY) {
+
+  float cubelen, cx,cy,dx,dy,r;
+
+  cubelen = (float) getMin(width,height);
+  r   = cubelen * 0.5f;
+
+  cx  = ((float)width)  * 0.5f;
+  cy  = ((float)height) * 0.5f;
+  dx  = ((float)mouseX) - cx;
+  dy  = ((float)mouseY) - cy;
+
+  //
+  // dx,dy = distance to center in pixels
+  //
+
+  dx = clamp(dx, -r,r);
+  dy = clamp(dy, -r,r);
+
+  //
+  // sin theta = dx / r
+  // sin phi   = dy / r
+  //
+  // phi   = arc sin ( sin theta )
+  // theta = arc sin ( sin phi   )
+  //
+
+  return PolarCoord(
+
+    math::rad2deg( math::asin( dx/r ) ),
+    math::rad2deg( math::asin( dy/r ) )
+    
+  );
+
+}
+
+static Vertex screenToVector(int width, int height, int mouseX, int mouseY) {
+
+    float radius = (float) getMax(width, height) * 0.5f;
+
+    float cx = ((float)width) * 0.5f;
+    float cy = ((float)height) * 0.5f;
+    float x  = (((float)mouseX) - cx)/radius;
+    float y  = (((float)mouseY) - cy)/radius;
+
+    // Make unit vector
+
+    float len = sqrt(x*x + y*y);
+    if (len > 1.0e-6) {
+        x = x/len;
+        y = y/len;
+    }
+    // Find length to first edge
+
+    float maxlen = math::sqrt(2.0f);
+
+    // zero length is vertical, max length is horizontal
+    float angle = (maxlen - len)/maxlen*math::pi<float>()/2.0f;
+
+    float z = math::sin(angle);
+
+    // renorm to unit length
+
+    len = math::sqrt(1.0f - z*z);
+    x = x*len;
+    y = y*len;
+
+    return Vertex(x, y, z);
+}
+
+void RGLView::trackballBegin(int mouseX, int mouseY)
+{
+    rotBase = screenToVector(vwidth,vheight,mouseX,mouseY);
+}
+
+void RGLView::trackballUpdate(int mouseX, int mouseY)
+{
+    	Subscene* subscene = scene->getSubscene(activeSubscene);
+    	if (!subscene) return;
+
+  	rotCurrent = screenToVector(vwidth,vheight,mouseX,mouseY);
+	if (windowImpl->beginGL()) {
+            for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+                Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+                if (sub) {
+                    ModelViewpoint* modelviewpoint = sub->getModelViewpoint();
+	            modelviewpoint->updateMouseMatrix(rotBase,rotCurrent);
+                }
+            }
+	    windowImpl->endGL();
+
+	    View::update();
+	}
+}
+
+void RGLView::trackballEnd()
+{
+    Subscene* subscene = scene->getSubscene(activeSubscene);
+    if (!subscene) return;
+    for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+        Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+        if (sub) {   
+            ModelViewpoint* modelviewpoint = sub->getModelViewpoint();
+            modelviewpoint->mergeMouseMatrix();
+        }
+    }
+}
+
+void RGLView::oneAxisBegin(int mouseX, int mouseY)
+{
+	rotBase = screenToVector(vwidth,vheight,mouseX,height/2);
+}
+
+void RGLView::oneAxisUpdate(int mouseX, int mouseY)
+{
+    	Subscene* subscene = scene->getSubscene(activeSubscene);
+    	if (!subscene) return;
+
+  	rotCurrent = screenToVector(vwidth,vheight,mouseX,height/2);
+
+	if (windowImpl->beginGL()) {
+            for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+                Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+                if (sub) {
+                    ModelViewpoint* modelviewpoint = sub->getModelViewpoint();
+	            modelviewpoint->mouseOneAxis(rotBase,rotCurrent,axis[drag-1]);
+                }
+            }
+	    windowImpl->endGL();
+
+	    View::update();
+	}
+}
+
+void RGLView::polarBegin(int mouseX, int mouseY)
+{
+    	Subscene* subscene = scene->getSubscene(activeSubscene);
+    	if (!subscene) return;
+
+	ModelViewpoint* modelviewpoint = subscene->getModelViewpoint();
+
+  	camBase = modelviewpoint->getPosition();
+
+	dragBase = screenToPolar(vwidth,vheight,mouseX,mouseY);
+
+}
+
+void RGLView::polarUpdate(int mouseX, int mouseY)
+{
+  Subscene* subscene = scene->getSubscene(activeSubscene);
+  if (!subscene) return;
+
+  dragCurrent = screenToPolar(vwidth,vheight,mouseX,mouseY);
+
+  PolarCoord newpos = camBase - ( dragCurrent - dragBase );
+
+  newpos.phi = clamp( newpos.phi, -90.0f, 90.0f );
+  for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+    Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+    if (sub) {   
+      ModelViewpoint* modelviewpoint = sub->getModelViewpoint();
+      modelviewpoint->setPosition( newpos );
+    }
+  }
+  View::update();
+}
+
+void RGLView::polarEnd()
+{
+
+ //    Viewpoint* viewpoint = scene->getViewpoint();
+ //    viewpoint->mergeMouseMatrix();
+
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// INTERACTIVE FEATURE
+//   adjustFOV
+//
+
+
+void RGLView::adjustFOVBegin(int mouseX, int mouseY)
+{
+  fovBaseY = mouseY;
+}
+
+
+void RGLView::adjustFOVUpdate(int mouseX, int mouseY)
+{
+  Subscene* subscene = scene->getSubscene(activeSubscene);
+  if (!subscene) return;
+
+  int dy = mouseY - fovBaseY;
+
+  float py = -((float)dy/(float)vheight) * 180.0f;
+
+  for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+    Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+    if (sub) {
+      UserViewpoint* userviewpoint = sub->getUserViewpoint();
+      userviewpoint->setFOV( userviewpoint->getFOV() + py );
+    }
+  }
+
+  View::update();
+
+  fovBaseY = mouseY;
+}
+
+
+void RGLView::adjustFOVEnd()
+{
+}
+
+void RGLView::wheelRotatePull(int dir)
+{
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+  for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+    Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+    if (sub) {
+      UserViewpoint* userviewpoint = sub->getUserViewpoint();
+      float zoom = userviewpoint->getZoom();
+
+#define ZOOM_STEP  1.05f 
+#define ZOOM_PIXELLOGSTEP 0.02f
+  
+      switch(dir)
+      {
+        case GUI_WheelForward:
+          zoom *= ZOOM_STEP;
+          break;
+        case GUI_WheelBackward:
+          zoom /= ZOOM_STEP;
+          break;
+      }
+
+      zoom = clamp( zoom , ZOOM_MIN, ZOOM_MAX);
+      userviewpoint->setZoom(zoom);
+    }
+  }
+  View::update();
+}
+
+void RGLView::wheelRotatePush(int dir)
+{
+  switch (dir)
+  {
+    case GUI_WheelForward:
+      wheelRotatePull(GUI_WheelBackward);
+      break;
+    case GUI_WheelBackward:
+      wheelRotatePull(GUI_WheelForward);
+      break;
+  }
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// INTERACTIVE FEATURE
+//   user callback
+//
+
+
+void RGLView::userBegin(int mouseX, int mouseY)
+{
+  int ind = drag - 1;
+  activeButton = drag;
+  if (beginCallback[ind]) {
+    busy = true;
+    (*beginCallback[ind])(userData[3*ind+0], mouseX, vheight-mouseY);
+    busy = false;
+  }
+}
+
+
+void RGLView::userUpdate(int mouseX, int mouseY)
+{
+  int ind = activeButton - 1;
+  if (!busy && updateCallback[ind]) {
+    busy = true;
+    (*updateCallback[ind])(userData[3*ind+1], mouseX, vheight-mouseY);
+    busy = false;
+  }
+}
+
+void RGLView::userEnd()
+{
+  int ind = activeButton - 1;
+  if (endCallback[ind])
+    (*endCallback[ind])(userData[3*ind+2]);
+}
+
+void RGLView::userWheel(int dir)
+{
+  if (wheelCallback)
+    (*wheelCallback)(wheelData, dir);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// INTERACTIVE FEATURE
+//   adjustZoom
+//
+
+
+void RGLView::adjustZoomBegin(int mouseX, int mouseY)
+{
+  zoomBaseY = mouseY;
+}
+
+
+void RGLView::adjustZoomUpdate(int mouseX, int mouseY)
+{
+  Subscene* subscene = scene->getSubscene(activeSubscene);
+  if (!subscene) return;
+
+  int dy = mouseY - zoomBaseY;
+  
+  for (unsigned int i = 0; i < subscene->mouseListeners.size(); i++) {
+    Subscene* sub = scene->getSubscene(subscene->mouseListeners[i]);
+    if (sub) {
+      UserViewpoint* userviewpoint = sub->getUserViewpoint();
+
+      float zoom = clamp ( userviewpoint->getZoom() * exp(dy*ZOOM_PIXELLOGSTEP), ZOOM_MIN, ZOOM_MAX);
+      userviewpoint->setZoom(zoom);
+    }
+  }
+  View::update();
+
+  zoomBaseY = mouseY;
+}
+
+
+void RGLView::adjustZoomEnd()
+{
+}
+
+//
+// snapshot
+//
+
+bool RGLView::snapshot(PixmapFileFormatID formatID, const char* filename)
+{
+  bool success = false;
+
+  if ( (formatID < PIXMAP_FILEFORMAT_LAST) && (pixmapFormat[formatID])) { 
+    // alloc pixmap memory
+    Pixmap snapshot;
+   
+    if (snapshot.init(RGB24, width, height, 8)) {
+      if ( windowImpl->beginGL() ) {
+        // read front buffer
+
+        glPushAttrib(GL_PIXEL_MODE_BIT);
+
+        glReadBuffer(GL_FRONT);
+        glPixelStorei(GL_PACK_ALIGNMENT, 1);
+        glReadPixels(0,0,width,height,GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*) snapshot.data);
+
+        glPopAttrib();
+  
+        windowImpl->endGL();
+      } else
+        snapshot.clear();
+      
+      success = snapshot.save( pixmapFormat[formatID], filename );
+      
+    } else error("unable to create pixmap");
+    	
+  } else error("pixmap save format not supported in this build");
+
+  return success;
+}
+
+bool RGLView::pixels( int* ll, int* size, int component, double* result )
+{
+  bool success = false;
+  GLenum format[] = {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA, 
+                      GL_DEPTH_COMPONENT, GL_LUMINANCE};   
+  if ( windowImpl->beginGL() ) {
+    /*
+     * Some OSX systems appear to have a glReadPixels 
+     * bug causing segfaults when reading the depth component.  
+     * Read those column by column.
+     */
+    bool bycolumn = format[component] == GL_DEPTH_COMPONENT;
+    int n = bycolumn ? size[1] : size[0]*size[1];
+    GLfloat* buffer = (GLfloat*) R_alloc(n, sizeof(GLfloat));
+  	
+    glEnable(GL_DEPTH_TEST);
+    glDepthMask(GL_TRUE);
+  
+    // read front buffer
+
+    glPushAttrib(GL_PIXEL_MODE_BIT);
+ 
+    glReadBuffer(GL_FRONT);
+    glPixelStorei(GL_PACK_ALIGNMENT, 1);
+    
+    if (bycolumn) {
+      for(int ix=0; ix<size[0]; ++ix){
+        glReadPixels(ix+ll[0],ll[1],1,size[1],format[component], GL_FLOAT, (GLvoid*) buffer);
+        for(int iy=0; iy<size[1]; ++iy) {
+          result[ix + iy*size[0]] = buffer[iy];
+        }
+      }	
+    } else {	
+      glReadPixels(ll[0],ll[1],size[0],size[1],format[component], GL_FLOAT, (GLvoid*) buffer);
+      for (int i=0; i<n; i++)
+        result[i] = buffer[i];
+    }
+    glPopAttrib();
+    success = true;
+
+    windowImpl->endGL();
+  }
+
+  return success;
+}
+
+void RGLView::setMouseMode(int button, MouseModeID mode)
+{
+	int index = button-1;
+    	mouseMode[index] = mode;
+	switch (mode) {
+	    case mmTRACKBALL:
+	    	ButtonBeginFunc[index] = &RGLView::trackballBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::trackballUpdate;
+	    	ButtonEndFunc[index] = &RGLView::trackballEnd;
+	    	break;
+	    case mmXAXIS:
+	    case mmYAXIS:
+	    case mmZAXIS:
+	    	ButtonBeginFunc[index] = &RGLView::oneAxisBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::oneAxisUpdate;
+	    	ButtonEndFunc[index] = &RGLView::trackballEnd; // No need for separate function
+	    	if (mode == mmXAXIS)      axis[index] = Vertex(1,0,0);
+	    	else if (mode == mmYAXIS) axis[index] = Vertex(0,1,0);
+	    	else                      axis[index] = Vertex(0,0,1);
+	    	break;	    	
+	    case mmPOLAR:
+ 	    	ButtonBeginFunc[index] = &RGLView::polarBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::polarUpdate;
+	    	ButtonEndFunc[index] = &RGLView::polarEnd;
+	    	break;
+	    case mmSELECTING:
+ 	    	ButtonBeginFunc[index] = &RGLView::mouseSelectionBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::mouseSelectionUpdate;
+	    	ButtonEndFunc[index] = &RGLView::mouseSelectionEnd;
+	    	break;
+	    case mmZOOM:
+ 	    	ButtonBeginFunc[index] = &RGLView::adjustZoomBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::adjustZoomUpdate;
+	    	ButtonEndFunc[index] = &RGLView::adjustZoomEnd;
+	    	break;
+	    case mmFOV:
+ 	    	ButtonBeginFunc[index] = &RGLView::adjustFOVBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::adjustFOVUpdate;
+	    	ButtonEndFunc[index] = &RGLView::adjustFOVEnd;
+	    	break;
+	    case mmUSER:
+ 	    	ButtonBeginFunc[index] = &RGLView::userBegin;
+	    	ButtonUpdateFunc[index] = &RGLView::userUpdate;
+	    	ButtonEndFunc[index] = &RGLView::userEnd;
+	    	break;	    	
+	}
+}
+
+void RGLView::setMouseCallbacks(int button, userControlPtr begin, userControlPtr update, 
+                                userControlEndPtr end, userCleanupPtr cleanup, void** user)
+{
+  if (drag) captureLost();
+  int ind = button - 1;
+  if (cleanupCallback[ind])
+    (*cleanupCallback[ind])(userData + 3*ind);
+  beginCallback[ind] = begin;
+  updateCallback[ind] = update;
+  endCallback[ind] = end;
+  cleanupCallback[ind] = cleanup;
+  userData[3*ind + 0] = *(user++);
+  userData[3*ind + 1] = *(user++);
+  userData[3*ind + 2] = *user;
+  setMouseMode(button, mmUSER);
+}
+
+void RGLView::getMouseCallbacks(int button, userControlPtr *begin, userControlPtr *update, 
+                                            userControlEndPtr *end, userCleanupPtr *cleanup, void** user)
+{
+  int ind = button - 1;
+  *begin = beginCallback[ind];
+  *update = updateCallback[ind];
+  *end = endCallback[ind];
+  *cleanup = cleanupCallback[ind];
+  *(user++) = userData[3*ind + 0];
+  *(user++) = userData[3*ind + 1];
+  *(user++) = userData[3*ind + 2];
+} 
+
+MouseModeID RGLView::getMouseMode(int button)
+{
+    return mouseMode[button-1];
+}
+
+void RGLView::setWheelMode(WheelModeID mode)
+{
+  wheelMode = mode;
+  switch (mode) {
+    case wmPULL:
+      WheelRotateFunc = &RGLView::wheelRotatePull;
+      break;
+    case wmPUSH:
+      WheelRotateFunc = &RGLView::wheelRotatePush;
+      break;
+    case wmUSER:
+      WheelRotateFunc = &RGLView::userWheel;
+      break;
+  }
+}
+
+WheelModeID RGLView::getWheelMode()
+{
+  return wheelMode;
+}
+
+void RGLView::setWheelCallback(userWheelPtr wheel, void* user)
+{
+  wheelCallback = wheel;
+  wheelData = user;
+  setWheelMode(wmUSER);  
+}
+
+void RGLView::getWheelCallback(userWheelPtr *wheel, void** user)
+{
+  *wheel = wheelCallback;
+  *user = wheelData;
+}
+
+MouseSelectionID RGLView::getSelectState()
+{
+    	return selectState;
+}
+
+void RGLView::setSelectState(MouseSelectionID state)
+{
+    	selectState = state;
+}
+
+double* RGLView::getMousePosition()
+{
+    	return mousePosition;
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// INTERACTIVE FEATURE
+//   mouseSelection
+//
+void RGLView::mouseSelectionBegin(int mouseX,int mouseY)
+{
+	if (selectState == msABORT) return;
+	
+	mousePosition[0] = (float)mouseX/(float)vwidth;
+	mousePosition[1] = (float)mouseY/(float)vheight;
+	mousePosition[2] = mousePosition[0];
+	mousePosition[3] = mousePosition[1];
+	selectState = msCHANGING;
+}
+
+void RGLView::mouseSelectionUpdate(int mouseX,int mouseY)
+{
+	mousePosition[2] = (float)mouseX/(float)vwidth;
+	mousePosition[3] = (float)mouseY/(float)vheight;
+	View::update();
+}
+
+void RGLView::mouseSelectionEnd()
+{
+	if (selectState == msABORT) return;
+	
+	selectState = msDONE;
+	View::update();
+}
+
+void RGLView::getUserMatrix(double* dest)
+{
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+
+  ModelViewpoint* modelviewpoint = subscene->getModelViewpoint();
+
+  modelviewpoint->getUserMatrix(dest);
+}
+
+void RGLView::setUserMatrix(double* src)
+{
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+  subscene->setUserMatrix(src);  	   
+  View::update();
+}
+
+void RGLView::getScale(double* dest)
+{
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+    
+  ModelViewpoint* modelviewpoint = subscene->getModelViewpoint();
+	
+  modelviewpoint->getScale(dest);
+}
+
+void RGLView::setScale(double* src)
+{
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+    
+  subscene->setScale(src);
+
+  View::update();
+}
+
+void RGLView::setDefaultFont(const char* family, int style, double cex, bool useFreeType)
+{
+    GLFont* font = View::windowImpl->getFont(family, style, cex, useFreeType);
+    if (!font)
+	error("font not available");
+    renderContext.font = font;
+}
+  
+const char* RGLView::getFontFamily() const 
+{
+  if (!renderContext.font)
+    error("font not available");
+      
+  return renderContext.font->family;
+}
+
+void RGLView::setFontFamily(const char *family)
+{
+  setDefaultFont(family, getFontStyle(), getFontCex(), getFontUseFreeType());
+}
+
+int RGLView::getFontStyle() const 
+{
+  if (!renderContext.font)
+    error("font not available");
+  return renderContext.font->style;
+}
+
+void RGLView::setFontStyle(int style)
+{
+  setDefaultFont(getFontFamily(), style, getFontCex(), getFontUseFreeType());
+}
+
+double RGLView::getFontCex() const 
+{
+  if (!renderContext.font)
+    error("font not available");
+  return renderContext.font->cex;
+}
+
+void RGLView::setFontCex(double cex)
+{
+  setDefaultFont(getFontFamily(), getFontStyle(), cex, getFontUseFreeType());
+}
+
+const char* RGLView::getFontname() const 
+{
+  if (!renderContext.font)
+    error("font not available");
+  return renderContext.font->fontname;
+}
+
+bool RGLView::getFontUseFreeType() const
+{
+  if (!renderContext.font)
+    error("font not available");
+  return renderContext.font->useFreeType;
+}
+
+void RGLView::setFontUseFreeType(bool useFreeType)
+{
+  setDefaultFont(getFontFamily(), getFontStyle(), getFontCex(), useFreeType);
+}
+
+void RGLView::getPosition(double* dest)
+{    
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+    
+  ModelViewpoint* modelviewpoint = subscene->getModelViewpoint();
+  modelviewpoint->getPosition(dest);
+}
+
+void RGLView::setPosition(double* src)
+{
+  Subscene* subscene = NULL;
+  if (activeSubscene) 
+    subscene = scene->getSubscene(activeSubscene);
+  if (!subscene)
+    subscene = scene->getCurrentSubscene();
+    
+  ModelViewpoint* modelviewpoint = subscene->getModelViewpoint();
+
+  modelviewpoint->setPosition(src);
+}
+
+
+void RGLView::setDefaultMouseFunc()
+{
+    setMouseMode(1, mmPOLAR);
+    setMouseMode(2, mmFOV);
+    setMouseMode(3, mmZOOM);
+    setWheelMode(wmPULL);
+}
+
+bool RGLView::postscript(int formatID, const char* filename, bool drawText)
+{
+  bool success = false;
+
+  std::FILE *fp = fopen(filename, "wb");  
+  char *oldlocale = setlocale(LC_NUMERIC, "C");
+  
+  GLint buffsize = 0, state = GL2PS_OVERFLOW;
+  GLint vp[4];
+  GLint options = GL2PS_SILENT | GL2PS_SIMPLE_LINE_OFFSET | GL2PS_NO_BLENDING |
+                  GL2PS_OCCLUSION_CULL | GL2PS_BEST_ROOT;
+
+  if (!drawText) options |= GL2PS_NO_TEXT;
+  
+  if (windowImpl->beginGL()) {
+  
+    glGetIntegerv(GL_VIEWPORT, vp);
+ 
+    while( state == GL2PS_OVERFLOW ){ 
+      buffsize += 1024*1024;
+      gl2psBeginPage ( filename, "Generated by rgl", vp,
+                   formatID, GL2PS_BSP_SORT, options,
+                   GL_RGBA, 0, NULL, 0, 0, 0, buffsize,
+                   fp, filename );
+
+    
+      if ( drawText ) {
+        // signal gl2ps for text
+        scene->invalidateDisplaylists();
+        if (formatID == GL2PS_PS || formatID == GL2PS_EPS || 
+            formatID == GL2PS_TEX || formatID == GL2PS_PGF)
+      	  renderContext.gl2psActive = GL2PS_POSITIONAL;  
+        else
+          renderContext.gl2psActive = GL2PS_LEFT_ONLY;
+      }
+    
+      // redraw:
+    
+      scene->render(&renderContext);
+      glFinish();
+ 
+      if ( drawText ) {
+        scene->invalidateDisplaylists();
+        renderContext.gl2psActive = GL2PS_NONE;   
+      }
+      success = true;
+
+      state = gl2psEndPage();
+    }
+  
+    windowImpl->endGL();
+  }
+  setlocale(LC_NUMERIC, oldlocale);
+  
+  fclose(fp);
+
+  return success;
+}
diff --git a/src/rglview.h b/src/rglview.h
new file mode 100644
index 0000000..b94ad5a
--- /dev/null
+++ b/src/rglview.h
@@ -0,0 +1,203 @@
+#ifndef RGLVIEW_H
+#define RGLVIEW_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: rglview.h 1436 2016-01-01 15:18:43Z murdoch $
+
+
+#include "scene.h"
+#include "gui.h"
+#include "fps.h"
+#include "select.h"
+#include "pixmap.h"
+
+namespace rgl {
+
+enum MouseModeID {mmTRACKBALL = 1, mmXAXIS, mmYAXIS, mmZAXIS, mmPOLAR, 
+                  mmSELECTING, mmZOOM, mmFOV, mmUSER};
+enum MouseSelectionID {msNONE=1, msCHANGING, msDONE, msABORT};
+
+enum WheelModeID {wmPUSH = 1, wmPULL, wmUSER};
+
+typedef void (*userControlPtr)(void *userData, int mouseX, int mouseY);
+typedef void (*userControlEndPtr)(void *userData);
+typedef void (*userCleanupPtr)(void **userData);
+typedef void (*userWheelPtr)(void *userData, int dir);
+
+class RGLView : public View
+{
+public:
+  RGLView(Scene* scene);
+  ~RGLView();
+  bool snapshot(PixmapFileFormatID formatID, const char* filename);
+  bool pixels(int* ll, int* size, int component, double* result);
+  bool postscript(int format, const char* filename, bool drawText);
+// event handler:
+  void show(void);
+  void hide(void);
+  void paint(void);
+  void resize(int width, int height);
+  void buttonPress(int button, int mouseX, int mouseY);
+  void buttonRelease(int button, int mouseX, int mouseY);
+  void mouseMove(int mouseX, int mouseY);
+  void wheelRotate(int dir);
+  void captureLost();
+  void keyPress(int code);
+  Scene* getScene();
+
+  MouseModeID getMouseMode(int button);
+  void        setMouseMode(int button, MouseModeID mode);
+  void        setMouseCallbacks(int button, userControlPtr begin, userControlPtr update, 
+                                            userControlEndPtr end, userCleanupPtr cleanup, void** user);
+  void        getMouseCallbacks(int button, userControlPtr *begin, userControlPtr *update, 
+                                            userControlEndPtr *end, userCleanupPtr *cleanup, void** user);
+  WheelModeID getWheelMode();
+  void        setWheelMode(WheelModeID mode);
+  void        setWheelCallback(userWheelPtr wheel, void* user);
+  void        getWheelCallback(userWheelPtr *wheel, void** user);
+  
+  MouseSelectionID getSelectState();
+  void        setSelectState(MouseSelectionID state);
+  double*     getMousePosition();
+  void        getUserMatrix(double* dest);
+  void        setUserMatrix(double* src);
+  void        getScale(double* dest);
+  void        setScale(double* src);
+  const char* getFontFamily() const;
+  void        setFontFamily(const char *family);
+  int         getFontStyle() const;
+  void        setFontStyle(int style);
+  double      getFontCex() const;
+  void        setFontCex(double cex);
+  bool        getFontUseFreeType() const;
+  void        setFontUseFreeType(bool useFreeType);
+  void	      setDefaultFont(const char *family, int style, double cex, bool useFreeType);
+  const char* getFontname() const;
+  
+  /* NB:  these functions do not maintain consistency with userMatrix */
+  
+  void        getPosition(double* dest);
+  void 	      setPosition(double* src);
+
+protected:
+
+  void setWindowImpl(WindowImpl* impl);
+
+
+private:
+  typedef void (RGLView::*viewControlPtr)(int mouseX,int mouseY);
+  typedef void (RGLView::*viewControlEndPtr)();
+  typedef void (RGLView::*viewWheelPtr)(int dir);
+    
+
+  viewControlPtr ButtonBeginFunc[3], ButtonUpdateFunc[3];
+  viewControlEndPtr ButtonEndFunc[3];
+  viewWheelPtr WheelRotateFunc;
+
+  void setDefaultMouseFunc();
+
+//
+// DRAG USER-INPUT
+//
+
+  int drag, activeSubscene;
+  int vwidth, vheight;      /* width and height of active subscene */
+  
+// Translate from OS window-relative coordinates (relative to top left corner) to
+// OpenGL window relative (relative to bottom left corner)
+  void translateCoords(int* mouseX, int* mouseY) const { *mouseY = height - *mouseY; }
+
+// o DRAG FEATURE: adjustDirection
+
+  void polarBegin(int mouseX, int mouseY);
+  void polarUpdate(int mouseX, int mouseY);
+  void polarEnd();
+
+  void trackballBegin(int mouseX, int mouseY);
+  void trackballUpdate(int mouseX, int mouseY);
+  void trackballEnd();
+  
+  void oneAxisBegin(int mouseX, int mouseY);
+  void oneAxisUpdate(int mouseX, int mouseY);  
+
+  void wheelRotatePull(int dir);
+  void wheelRotatePush(int dir);
+  
+  PolarCoord camBase, dragBase, dragCurrent;
+  Vertex rotBase, rotCurrent, axis[3];
+
+
+// o DRAG FEATURE: adjustZoom
+
+  void adjustZoomBegin(int mouseX, int mouseY);
+  void adjustZoomUpdate(int mouseX, int mouseY);
+  void adjustZoomEnd();
+
+  int zoomBaseY;
+
+// o DRAG FEATURE: adjustFOV (field of view)
+
+  void adjustFOVBegin(int mouseX, int mouseY);
+  void adjustFOVUpdate(int mouseX, int mouseY);
+  void adjustFOVEnd();
+
+  int fovBaseY;
+  
+// o DRAG FEATURE: user supplied callback
+
+  void userBegin(int mouseX, int mouseY);
+  void userUpdate(int mouseX, int mouseY);
+  void userEnd();
+  
+  void userWheel(int dir);
+  
+  void* userData[9];
+  userControlPtr beginCallback[3], updateCallback[3];
+  userControlEndPtr endCallback[3];
+  userCleanupPtr cleanupCallback[3];
+  int activeButton;
+  bool busy;
+  
+  void* wheelData;
+  userWheelPtr wheelCallback;
+
+// o DRAG FEATURE: mouseSelection
+  void mouseSelectionBegin(int mouseX,int mouseY);
+  void mouseSelectionUpdate(int mouseX,int mouseY);
+  void mouseSelectionEnd();
+
+//
+// RENDER SYSTEM
+//
+  
+// o LAYERS
+  
+  Scene*  scene;
+  FPS     fps;
+  SELECT  select;
+
+// o CONTEXT
+  
+  RenderContext renderContext;
+
+  bool autoUpdate;
+
+  enum {
+    FSHOWFPS    = 1<<0,
+    FAUTOUPDATE = 1<<1
+  };
+
+  int  flags;
+
+  MouseModeID mouseMode[3];
+  MouseSelectionID selectState;
+  double  mousePosition[4];
+
+  WheelModeID wheelMode;
+};
+
+} // namespace rgl
+
+#endif /* RGLVIEW_H */
diff --git a/src/scene.cpp b/src/scene.cpp
new file mode 100644
index 0000000..dede580
--- /dev/null
+++ b/src/scene.cpp
@@ -0,0 +1,299 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: scene.cpp 1415 2015-11-26 20:31:02Z murdoch $
+
+#include "gl2ps.h"
+#include "scene.h"
+#include "rglmath.h"
+#include "render.h"
+#include "geom.h"
+#include <map>
+#include <algorithm>
+#include <functional>
+#include "R.h"
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Scene
+//
+
+ObjID SceneNode::nextID = 1;
+
+Scene::Scene()
+: rootSubscene(EMBED_REPLACE, EMBED_REPLACE, EMBED_REPLACE, false),
+  doIgnoreExtent(false)
+{
+  nodes.reserve(6);
+  nodes.push_back( currentSubscene = &rootSubscene );
+ 
+  add( new UserViewpoint );
+  add( new ModelViewpoint );
+  add( new Background );
+  add( new Light );
+}
+
+Scene::~Scene()
+{
+  clear(SHAPE);
+  clear(LIGHT);
+  clear(BBOXDECO);
+
+}
+
+UserViewpoint* Scene::getUserViewpoint() 
+{
+  return currentSubscene->getUserViewpoint();
+}
+
+ModelViewpoint* Scene::getModelViewpoint() 
+{
+  return currentSubscene->getModelViewpoint();
+}
+
+bool Scene::clear(TypeID type)
+{
+  std::vector<SceneNode*>::iterator iter;
+  for (iter = nodes.begin(); iter != nodes.end();) {
+    if ((*iter)->getTypeID() == type) {
+      SceneNode* node = (*iter);
+      int id = node->getObjID();
+      if (id == rootSubscene.getObjID()) 
+        ++iter;
+      else {
+        hide(node->getObjID());
+        delete node;
+        iter = nodes.erase(iter);
+      }
+    } else
+      ++iter;
+  }
+  SAVEGLERROR;
+  return true;
+}
+
+bool Scene::add(SceneNode* node)
+{
+  nodes.push_back( node );
+  return currentSubscene->add(node);
+}  
+
+bool Scene::pop(TypeID type, int id)
+{
+  std::vector<SceneNode*>::iterator iter;
+  
+  if (id == 0) {  
+    for (iter = nodes.end(); iter != nodes.begin();) {
+      --iter;
+      if ((*iter)->getTypeID() == type) {
+        id = (*iter)->getObjID();
+        break;
+      }
+    }
+    if (!id) return false;
+  }
+  iter = std::find_if(nodes.begin(), nodes.end(), 
+		      std::bind2nd(std::ptr_fun(&sameID), id));
+  if (iter != nodes.end()) {
+    SceneNode* node = *iter;  
+    if (node == &rootSubscene) 
+      return true;
+    hide((*iter)->getObjID());
+    nodes.erase(iter);
+    delete node;
+
+    return true;
+  }
+  
+  return false;
+}
+
+void Scene::hide(int id)
+{
+  std::vector<SceneNode*>::iterator inode;
+  SceneNode* node = get_scenenode(id);
+  if (node) {
+    TypeID type = node->getTypeID();
+    for (inode = nodes.begin(); inode != nodes.end(); ++inode) {
+      if ((*inode)->getTypeID() == SUBSCENE) {
+        Subscene* subscene = static_cast<Subscene*>((*inode));
+        switch (type) {
+          case SUBSCENE: currentSubscene = subscene->hideSubscene(id, currentSubscene);
+            break;
+          case SHAPE: subscene->hideShape(id);
+            break;
+          case LIGHT: subscene->hideLight(id);
+            break;
+          case BBOXDECO: subscene->hideBBoxDeco(id);
+            break;
+          case BACKGROUND: subscene->hideBackground(id);
+            break;
+          case USERVIEWPOINT:
+          case MODELVIEWPOINT:
+            subscene->hideViewpoint(id);
+            break;
+          default: error("hiding type %d not implemented", type);
+        }
+      }
+    }
+  }
+}
+
+int Scene::get_id_count(TypeID type)
+{
+  int count = 0;
+  for (std::vector<SceneNode*>::iterator iter = nodes.begin();
+       iter != nodes.end(); ++iter) 
+    if (type == (*iter)->getTypeID())
+      count++;
+   
+  return count;
+}
+
+void Scene::get_ids(TypeID type, int* ids, char** types)
+{
+  char buffer[20];
+  for (std::vector<SceneNode*>::iterator iter = nodes.begin(); iter != nodes.end(); ++ iter) {
+    if (type == (*iter)->getTypeID()) {
+      *ids++ = (*iter)->getObjID();
+      buffer[19] = 0;
+      (*iter)->getTypeName(buffer, 20); 
+      *types = R_alloc(strlen(buffer)+1, 1);
+      strcpy(*types, buffer);        
+      types++;
+    }
+  }
+}  
+
+SceneNode* Scene::get_scenenode(int id) 
+{
+  for (std::vector<SceneNode*>::iterator iter = nodes.begin(); iter != nodes.end(); ++iter) 
+    if (id == (*iter)->getObjID())
+      return *iter;
+  return NULL;
+}
+
+SceneNode* Scene::get_scenenode(TypeID type, int id)
+{
+  SceneNode* node = get_scenenode(id);
+  if (node && node->getTypeID() == type)
+    return node;
+  else
+    return NULL;
+}
+Shape* Scene::get_shape(int id)
+{
+  return (Shape*)get_scenenode(SHAPE, id);
+}
+
+Background* Scene::get_background(int id)
+{
+  return (Background*)get_scenenode(BACKGROUND, id);
+}
+
+BBoxDeco* Scene::get_bboxdeco(int id)
+{
+  return (BBoxDeco*)get_scenenode(BBOXDECO, id);
+}
+  
+Subscene* Scene::getSubscene(int id)
+{
+  return (Subscene*)get_scenenode(SUBSCENE, id);
+}
+
+Subscene* Scene::whichSubscene(int id)
+{
+  Subscene* result = rootSubscene.whichSubscene(id);
+  if (!result) result = &rootSubscene;
+  return result;
+}
+
+Subscene* Scene::whichSubscene(int mouseX, int mouseY)
+{
+  Subscene* result = rootSubscene.whichSubscene(mouseX, mouseY);
+  if (!result) result = &rootSubscene;
+  return result;
+}
+
+void Scene::setCurrentSubscene(Subscene* subscene)
+{
+  currentSubscene = subscene;
+}
+
+void Scene::setupLightModel()
+{
+  Color global_ambient(0.0f,0.0f,0.0f,1.0f);
+
+  glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient.data );
+  glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE );
+  glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE );
+  SAVEGLERROR;  
+}
+  
+void Scene::update(RenderContext* renderContext)
+{
+  rootSubscene.update(renderContext);
+}
+
+void Scene::render(RenderContext* renderContext)
+{
+
+  //
+  // CLEAR BUFFERS
+  //
+
+  GLbitfield clearFlags = GL_COLOR_BUFFER_BIT;
+  rootSubscene.get_background()->material.colors.getColor(0).useClearColor();  
+
+  SAVEGLERROR;
+
+  // Depth Buffer
+
+  glClearDepth(1.0);
+  glDepthFunc(GL_LESS);
+  glDepthMask(GL_TRUE);
+  // mask and func will be reset by material
+
+  // if ( unsortedShapes.size() )
+    clearFlags  |= GL_DEPTH_BUFFER_BIT;
+
+  // The subscenes use the scissor test to limit where they draw, but we want to clear everything here
+  // clear
+  glDisable(GL_SCISSOR_TEST);																																																																																																																																																																															
+  glClear(clearFlags);  
+  glEnable(GL_SCISSOR_TEST);
+
+  // userMatrix and scale might change the length of normals.  If this slows us
+  // down, we should test for that instead of just enabling GL_NORMALIZE
+  
+  glEnable(GL_NORMALIZE);
+
+  setupLightModel();
+  
+  SAVEGLERROR;
+
+  //
+  // RENDER MODEL
+  //
+
+  rootSubscene.render(renderContext);
+}
+
+
+// ---------------------------------------------------------------------------
+void Scene::invalidateDisplaylists()
+{
+  std::vector<SceneNode*>::iterator iter;
+  for (iter = nodes.begin(); iter != nodes.end(); ++iter) {
+    if ((*iter)->getTypeID() == SHAPE)
+      ((Shape*)(*iter))->invalidateDisplaylist();
+  }
+}
+
+bool rgl::sameID(SceneNode* node, int id)
+{ 
+  return node->getObjID() == id; 
+}
diff --git a/src/scene.h b/src/scene.h
new file mode 100644
index 0000000..20e6cce
--- /dev/null
+++ b/src/scene.h
@@ -0,0 +1,157 @@
+#ifndef SCENE_H
+#define SCENE_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: scene.h 1415 2015-11-26 20:31:02Z murdoch $
+
+#include <vector>
+#include "types.h"
+#include "subscene.h"
+
+namespace rgl {
+
+class Scene {
+public:
+  Scene();
+  ~Scene();
+
+  // ---[ client services ]---------------------------------------------------
+
+  /**
+   * remove all nodes of the given type.  This is always recursive through subscenes.
+   **/
+  bool clear(TypeID type);
+  
+  /**
+   * add node to current subscene
+   **/
+  bool add(SceneNode* node);
+  
+  /**
+   * remove specified node of given type, or last-added if id==0
+   **/
+  bool pop(TypeID stackTypeID, int id);
+  
+  /**
+   * hide specified node in all subscenes
+   **/
+  void hide(int id);
+  
+  /**
+   * get information about stacks
+   */
+  int get_id_count(TypeID type);
+  void get_ids(TypeID type, int* ids, char** types);
+  
+  /**
+   * get a SceneNode by id
+   */
+   
+  SceneNode* get_scenenode(int id);
+  SceneNode* get_scenenode(TypeID type, int id);
+  
+  /**
+   * get information about particular shapes
+   **/
+  Shape* get_shape(int id);
+  
+  /**
+   * get information about particular lights
+   **/
+  Light* get_light(int id);
+  
+  /**
+   * get a background
+   */
+  Background* get_background(int id);
+  
+  /**
+   * get the bbox
+   */
+  BBoxDeco* get_bboxdeco(int id);
+  
+  /**
+   * get subscene
+   */
+  Subscene* getSubscene(int id);  /* get subscene by its id */
+  Subscene* whichSubscene(int id); /* get subscene holding this id */
+  Subscene* whichSubscene(int mouseX, int mouseY); /* get subscene by mouse coords */
+  /* coordinates are window-relative */
+
+  /** 
+   * set/get the current subscene
+   **/
+  void setCurrentSubscene(Subscene* subscene);
+  Subscene* getCurrentSubscene() const { return currentSubscene; }
+  const Subscene* getRootSubscene() const { return &rootSubscene; }
+  
+  // ---[ grouping component ]-----------------------------------------------
+  
+  /**
+   * obtain subscene's axis-aligned bounding box. 
+   **/
+  const AABox& getBoundingBox() const { return currentSubscene->getBoundingBox(); }
+  
+  // ---[ Renderable interface ]---------------------------------------------
+  
+  /**
+   * update matrices etc.
+   */
+  void update(RenderContext* renderContext);
+  
+  /**
+   * do OpenGL plotting
+   */
+  void render(RenderContext* renderContext);
+
+  // ---[ bindable component ]-----------------------------------------------
+  
+  /**
+   * obtain bounded viewpoint
+   **/
+  UserViewpoint* getUserViewpoint();
+  ModelViewpoint* getModelViewpoint();
+  
+  /**
+   * Get and set flag to ignore elements in bounding box
+   **/
+  
+  int getIgnoreExtent(void) const { return doIgnoreExtent; }
+  void setIgnoreExtent(int in_ignoreExtent) { doIgnoreExtent = in_ignoreExtent; }
+  
+  /**
+   * invalidate display lists so objects will be rendered again
+   **/
+  void invalidateDisplaylists();
+
+  Subscene rootSubscene;  
+
+private:
+
+  // Whether objects created in this scene should affect the bounding box or not
+  
+  bool doIgnoreExtent;
+
+  void setupLightModel();
+
+  // --- [ Subscenes ]-------------------------------------------------------
+
+  Subscene* currentSubscene;
+
+  // ---[ nodes ]-----------------------------------------------------------
+  
+  /**
+   * list of scene nodes.  The scene owns them, the subscenes display a subset.
+   **/
+  std::vector<SceneNode*> nodes;
+
+  void deleteAll(std::vector<SceneNode*> list);
+
+};
+
+} // namespace rgl
+
+#endif /* SCENE_H */
+
diff --git a/src/select.cpp b/src/select.cpp
new file mode 100644
index 0000000..27ef09c
--- /dev/null
+++ b/src/select.cpp
@@ -0,0 +1,35 @@
+// C++ source
+// This file is part of RGL.
+//
+// $Id: select.cpp 976 2013-10-04 15:06:19Z murdoch $
+
+#include "select.h"
+
+#include <cstdio>
+
+using namespace rgl;
+
+void SELECT::render(double* position)
+{
+  double llx, lly, urx, ury;
+  llx = *position;
+  lly = *(position+1);
+  urx = *(position+2);
+  ury = *(position+3);
+
+  glMatrixMode(GL_MODELVIEW);
+  glLoadIdentity();
+  glMatrixMode(GL_PROJECTION);
+  glLoadIdentity();
+  glOrtho(0.0f,1.0f,0.0f,1.0f,0.0f,1.0f);
+
+  glColor3f(0.5f,0.5f,0.5f);
+  glLineWidth(2.0);
+
+  glBegin(GL_LINE_LOOP);
+  	glVertex2f(llx, lly);
+  	glVertex2f(llx,	ury);
+  	glVertex2f(urx, ury);
+  	glVertex2f(urx, lly);
+  glEnd();
+}
diff --git a/src/select.h b/src/select.h
new file mode 100644
index 0000000..807613f
--- /dev/null
+++ b/src/select.h
@@ -0,0 +1,27 @@
+#ifndef PLX_SELECT_H
+#define PLX_SELECT_H
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: select.h 976 2013-10-04 15:06:19Z murdoch $
+
+#include "scene.h"
+
+namespace rgl {
+
+//
+// Mouse selection rectangle
+//
+
+class SELECT
+{
+public:
+  inline SELECT() { };
+  void render(double* position);
+};
+
+} // namespace rgl
+
+#endif // PLX_SELECT_H
+
diff --git a/src/subscene.cpp b/src/subscene.cpp
new file mode 100644
index 0000000..045ab86
--- /dev/null
+++ b/src/subscene.cpp
@@ -0,0 +1,1016 @@
+#include "subscene.h"
+#include "gl2ps.h"
+#include "R.h"
+#include <algorithm>
+#include <functional>
+
+using namespace rgl;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// CLASS
+//   Subscene
+//
+
+Subscene::Subscene(Embedding in_viewport, Embedding in_projection, Embedding in_model,
+                   bool in_ignoreExtent)
+ : SceneNode(SUBSCENE), parent(NULL), do_viewport(in_viewport), do_projection(in_projection),
+   do_model(in_model), viewport(0.,0.,1.,1.),Zrow(), Wrow(),
+   pviewport(0,0,1024,1024), ignoreExtent(in_ignoreExtent)
+{
+  userviewpoint = NULL;
+  modelviewpoint = NULL;
+  bboxdeco   = NULL;
+  background = NULL;
+  bboxChanges = false;
+  data_bbox.invalidate();
+  modelMatrix.setIdentity();
+  projMatrix.setIdentity(); 
+  mouseListeners.push_back(getObjID());
+}
+
+Subscene::~Subscene() 
+{
+  for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end(); ++ i ) 
+    delete (*i);
+}
+
+bool Subscene::add(SceneNode* node)
+{
+  bool success = false;
+  switch( node->getTypeID() )
+  {
+    case SHAPE:
+      {
+        Shape* shape = (Shape*) node;
+        addShape(shape);
+
+        success = true;
+      }
+      break;
+    case LIGHT:
+      {
+	Light* light = (Light*) node;
+	  addLight(light);
+	  
+	  success = true;
+      }
+      break;
+    case USERVIEWPOINT:
+      {
+        userviewpoint = (UserViewpoint*) node;
+        success = true;
+      }
+      break;
+    case MODELVIEWPOINT:
+      {
+        modelviewpoint = (ModelViewpoint*) node;
+        success = true;
+      }
+      break;
+    case SUBSCENE:
+      {
+	Subscene* subscene = static_cast<Subscene*>(node);
+	if (subscene->parent)
+	  error("Subscene %d is already a child of subscene %d.", subscene->getObjID(),
+	        subscene->parent->getObjID());
+	addSubscene(subscene);
+	success = true;
+      }
+      break;
+    case BACKGROUND:
+      {
+        Background* background = static_cast<Background*>(node);
+        addBackground(background);
+        success = true;
+      }
+      break;
+    case BBOXDECO:
+      { 
+        BBoxDeco* bboxdeco = static_cast<BBoxDeco*>(node);
+        addBBoxDeco(bboxdeco);
+        success = true;
+      }
+      break;
+    default:
+      break;
+  }
+  return success;
+}
+
+void Subscene::addBackground(Background* newbackground)
+{
+  background = newbackground;
+}
+
+void Subscene::addBBoxDeco(BBoxDeco* newbboxdeco)
+{
+  bboxdeco = newbboxdeco;
+}
+
+void Subscene::addShape(Shape* shape)
+{
+  if (!shape->getIgnoreExtent()) 
+    addBBox(shape->getBoundingBox(), shape->getBBoxChanges());
+
+  shapes.push_back(shape);
+  
+  if ( shape->isBlended() ) {
+    zsortShapes.push_back(shape);
+  } else if ( shape->isClipPlane() ) {
+    clipPlanes.push_back(static_cast<ClipPlaneSet*>(shape));
+    shrinkBBox();
+  } else
+    unsortedShapes.push_back(shape);
+}
+
+void Subscene::addBBox(const AABox& bbox, bool changes)
+{
+  data_bbox += bbox;
+  bboxChanges |= changes;
+  intersectClipplanes();
+  if (parent && !ignoreExtent) 
+    parent->addBBox(data_bbox, changes);
+}
+  
+void Subscene::addLight(Light* light)
+{
+  lights.push_back(light);
+}
+
+void Subscene::addSubscene(Subscene* subscene)
+{
+  subscenes.push_back(subscene);
+  subscene->parent = this;
+  subscene->newEmbedding();
+  if (!subscene->getIgnoreExtent()) 
+    addBBox(subscene->getBoundingBox(), subscene->bboxChanges);
+}
+
+void Subscene::hideShape(int id)
+{
+  std::vector<Shape*>::iterator ishape 
+     = std::find_if(shapes.begin(), shapes.end(), 
+       std::bind2nd(std::ptr_fun(&sameID), id));
+  if (ishape == shapes.end()) return;
+        
+  Shape* shape = *ishape;
+  shapes.erase(ishape);
+  if ( shape->isBlended() )
+    zsortShapes.erase(std::find_if(zsortShapes.begin(), zsortShapes.end(),
+                                   std::bind2nd(std::ptr_fun(&sameID), id)));
+  else if ( shape->isClipPlane() )
+    clipPlanes.erase(std::find_if(clipPlanes.begin(), clipPlanes.end(),
+                     std::bind2nd(std::ptr_fun(&sameID), id)));
+  else
+    unsortedShapes.erase(std::find_if(unsortedShapes.begin(), unsortedShapes.end(),
+                         std::bind2nd(std::ptr_fun(&sameID), id)));
+      
+  shrinkBBox();
+}
+
+void Subscene::hideLight(int id)
+{
+  std::vector<Light*>::iterator ilight = std::find_if(lights.begin(), lights.end(),
+                            std::bind2nd(std::ptr_fun(&sameID), id));
+  if (ilight != lights.end()) {
+    lights.erase(ilight);
+  }
+}
+
+void Subscene::hideBBoxDeco(int id)
+{
+  if (bboxdeco && sameID(bboxdeco, id))
+    bboxdeco = NULL;
+}
+
+void Subscene::hideBackground(int id)
+{
+  if (background && sameID(background, id)) {
+    if (parent)
+      background = NULL;
+    else
+      background = new( Background );  /* The root must always have a background */
+  }
+}
+
+Subscene* Subscene::hideSubscene(int id, Subscene* current)
+{
+  for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end(); ++ i) {
+    if (sameID(*i, id)) {
+      if ((*i)->getSubscene(current->getObjID()))
+        current = (*i)->parent;  
+      (*i)->parent = NULL;
+      subscenes.erase(i);
+      shrinkBBox();
+      return current;
+    } 
+  }
+  return current;
+}
+
+void Subscene::hideViewpoint(int id)
+{
+  if (userviewpoint && sameID(userviewpoint, id)) {
+    if (parent)            /* the root needs a viewpoint */
+      userviewpoint = NULL;
+  } else if (modelviewpoint && sameID(modelviewpoint, id)) {
+    if (parent)            /* the root needs a viewpoint */
+      modelviewpoint = NULL;
+  } 
+}
+
+Subscene* Subscene::getSubscene(int id)
+{
+  if (id == getObjID()) return this;
+    
+  for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end() ; ++ i ) {
+    Subscene* subscene = (*i)->getSubscene(id);
+    if (subscene) return subscene;
+  }
+  
+  return NULL;
+}
+
+Subscene* Subscene::whichSubscene(int id)
+{
+  for (std::vector<Shape*>::iterator i = shapes.begin(); i != shapes.end() ; ++ i ) {
+    if ((*i)->getObjID() == id)
+      return this;
+  }
+  for (std::vector<Light*>::iterator i = lights.begin(); i != lights.end() ; ++ i ) {
+    if ((*i)->getObjID() == id)
+      return this;
+  }
+  if (bboxdeco && bboxdeco->getObjID() == id)
+    return this;
+  for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end(); ++ i ) {
+    if ((*i)->getObjID() == id)
+      return this;
+  }
+  if (userviewpoint && userviewpoint->getObjID() == id)
+    return this;
+  if (modelviewpoint && modelviewpoint->getObjID() == id)
+    return this;
+  if (background && background->getObjID() == id)
+    return this;
+  for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end() ; ++ i ) {
+    Subscene* result = (*i)->whichSubscene(id);
+    if (result) 
+      return result;
+  }
+  return NULL;
+}
+
+Subscene* Subscene::whichSubscene(int mouseX, int mouseY)
+{
+  Subscene* result = NULL;
+  Subscene* sub;
+  for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end() ; ++ i ) {
+    result = (sub = (*i)->whichSubscene(mouseX, mouseY)) ? sub : result;
+  }  
+  if (!result && pviewport.x <= mouseX && mouseX < pviewport.x + pviewport.width 
+              && pviewport.y <= mouseY && mouseY < pviewport.y + pviewport.height)
+    result = this;
+  return result;
+}
+
+int Subscene::getAttributeCount(AABox& bbox, AttribID attrib)
+{
+  switch (attrib) {
+    case IDS:	   
+    case TYPES:    return shapes.size();
+  }
+  return SceneNode::getAttributeCount(bbox, attrib);
+}
+
+void Subscene::getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result)
+{
+  int n = getAttributeCount(bbox, attrib);
+  int ind = 0;
+
+  if (first + count < n) n = first + count;
+  if (first < n) {
+    switch(attrib) {
+      case IDS:
+        for (std::vector<Shape*>::iterator i = shapes.begin(); i != shapes.end() ; ++ i ) {
+      	  if ( first <= ind  && ind < n )  
+            *result++ = (*i)->getObjID();
+          ind++;
+        }
+        return;
+    }  
+    SceneNode::getAttribute(bbox, attrib, first, count, result);
+  }
+}
+
+String Subscene::getTextAttribute(AABox& bbox, AttribID attrib, int index)
+{
+  int n = getAttributeCount(bbox, attrib);
+  if (index < n && attrib == TYPES) {
+    char* buffer = R_alloc(20, 1);    
+    shapes[index]->getTypeName(buffer, 20);
+    return String(strlen(buffer), buffer);
+  } else
+    return SceneNode::getTextAttribute(bbox, attrib, index);
+}
+
+void Subscene::renderClipplanes(RenderContext* renderContext)
+{
+  std::vector<ClipPlaneSet*>::iterator iter;
+  
+  ClipPlaneSet::num_planes = 0;
+	
+  for (iter = clipPlanes.begin() ; iter != clipPlanes.end() ; ++iter ) {
+    ClipPlaneSet* plane = *iter;
+    plane->render(renderContext);
+    SAVEGLERROR;
+  }
+}
+
+void Subscene::disableClipplanes(RenderContext* renderContext)
+{
+  std::vector<ClipPlaneSet*>::iterator iter;
+	
+  for (iter = clipPlanes.begin() ; iter != clipPlanes.end() ; ++iter ) {
+    ClipPlaneSet* plane = *iter;
+    plane->enable(false);
+    SAVEGLERROR;
+  }
+}
+ 
+int Subscene::get_id_count(TypeID type, bool recursive)
+{
+  int result = 0;
+  if (recursive)
+    for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end(); ++ i ) 
+      result += (*i)->get_id_count(type, recursive);
+  switch (type) {
+    case SHAPE: {
+      result += shapes.size();
+      break;
+    }
+    case LIGHT: {
+      result += lights.size();
+      break;
+    }
+    case BBOXDECO: {
+      result += bboxdeco ? 1 : 0;
+      break;
+    }
+    case SUBSCENE: {
+      result += subscenes.size();
+      break;
+    }
+    case USERVIEWPOINT: {    
+      result += do_projection > EMBED_INHERIT ? 1 : 0;
+      break;
+    }
+    case MODELVIEWPOINT: {    
+      result += do_model > EMBED_INHERIT ? 1 : 0;
+      break;
+    }
+    case BACKGROUND: {
+      result += background ? 1 : 0;
+      break;
+    }
+  }
+  return result;
+}
+    
+int Subscene::get_ids(TypeID type, int* ids, char** types, bool recursive)
+{
+  char buffer[20];
+  int count = 0;
+  switch(type) {
+  case SHAPE: 
+    for (std::vector<Shape*>::iterator i = shapes.begin(); i != shapes.end() ; ++ i ) {
+      *ids++ = (*i)->getObjID();
+      buffer[19] = 0;
+      (*i)->getTypeName(buffer, 20);
+      *types = R_alloc(strlen(buffer)+1, 1);
+      strcpy(*types, buffer);
+      types++;
+      count++;
+    }
+    break;
+  case LIGHT: 
+    for (std::vector<Light*>::iterator i = lights.begin(); i != lights.end() ; ++ i ) {
+      *ids++ = (*i)->getObjID();
+      *types = R_alloc(strlen("light")+1, 1);
+      strcpy(*types, "light");
+      types++;
+      count++;
+    }
+    break;
+  case BBOXDECO: 
+    if (bboxdeco) {
+      *ids++ = bboxdeco->getObjID();
+      *types = R_alloc(strlen("bboxdeco")+1, 1);
+      strcpy(*types, "bboxdeco");
+      types++;
+      count++;
+    }
+    break;
+  case SUBSCENE: 
+    for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end(); ++ i ) {
+      *ids++ = (*i)->getObjID();
+      *types = R_alloc(strlen("subscene")+1, 1);
+      strcpy(*types, "subscene");
+      types++;
+      count++;
+    }
+    break;
+  case USERVIEWPOINT:
+    if (userviewpoint) {
+      *ids++ = userviewpoint->getObjID();
+      *types = R_alloc(strlen("userviewpoint")+1, 1);
+      strcpy(*types, "userviewpoint");
+      types++;
+      count++;
+    }
+    break;
+  case MODELVIEWPOINT:
+    if (modelviewpoint) {
+      *ids++ = modelviewpoint->getObjID();
+      *types = R_alloc(strlen("modelviewpoint")+1, 1);
+      strcpy(*types, "modelviewpoint");
+      types++;
+      count++;
+    }
+    break;
+  case BACKGROUND:
+    if (background) {
+      *ids++ = background->getObjID();
+      *types = R_alloc(strlen("background")+1, 1);
+      strcpy(*types, "background");
+      types++;
+      count++;
+    }
+    break;
+  }
+  if (recursive)
+    for (std::vector<Subscene*>::iterator i = subscenes.begin(); i != subscenes.end(); ++ i ) {
+      int newcount = (*i)->get_ids(type, ids, types, true);
+      ids += newcount;
+      types += newcount;
+      count += newcount;
+    }
+  return count;
+}
+
+Background* Subscene::get_background()
+{
+  if (background) return background;
+  else if (parent) return parent->get_background();
+  else return NULL;
+}
+
+Background* Subscene::get_background(int id)
+{
+  Background* background = get_background();
+  if (background && background->getObjID() == id)
+    return background;
+  
+  std::vector<Subscene*>::const_iterator iter;
+  for(iter = subscenes.begin(); iter != subscenes.end(); ++iter) {
+    background = (*iter)->get_background(id);
+    if (background) return background;
+  }
+  return NULL;
+}  
+
+BBoxDeco* Subscene::get_bboxdeco()
+{
+  if (bboxdeco) return bboxdeco;
+  else if (parent) return parent->get_bboxdeco();
+  else return NULL;
+}
+
+BBoxDeco* Subscene::get_bboxdeco(int id)
+{
+  BBoxDeco* bboxdeco = get_bboxdeco();
+  if (bboxdeco && bboxdeco->getObjID() == id)
+    return bboxdeco;
+  
+  std::vector<Subscene*>::const_iterator iter;
+  for(iter = subscenes.begin(); iter != subscenes.end(); ++iter) {
+    bboxdeco = (*iter)->get_bboxdeco(id);
+    if (bboxdeco) return bboxdeco;
+  }
+  return NULL;
+}  
+
+
+UserViewpoint* Subscene::getUserViewpoint()
+{
+  if (userviewpoint && do_projection > EMBED_INHERIT)
+    return userviewpoint;
+  else if (parent) return parent->getUserViewpoint();
+  else error("must have a user viewpoint");
+}
+
+ModelViewpoint* Subscene::getModelViewpoint()
+{
+  if (modelviewpoint && do_model > EMBED_INHERIT)
+    return modelviewpoint;
+  else if (parent) return parent->getModelViewpoint();
+  else error("must have a model viewpoint");
+}
+
+void Subscene::update(RenderContext* renderContext)
+{
+  GLdouble saveprojection[16];
+  
+
+  renderContext->subscene = this;
+  
+  setupViewport(renderContext);
+  if (bboxChanges) 
+    calcDataBBox();
+  
+  Sphere total_bsphere;
+
+  if (data_bbox.isValid()) {
+    
+    // 
+    // GET DATA VOLUME SPHERE
+    //
+
+    total_bsphere = Sphere( (bboxdeco) ? bboxdeco->getBoundingBox(data_bbox) : data_bbox, getModelViewpoint()->scale );
+    if (total_bsphere.radius <= 0.0)
+      total_bsphere.radius = 1.0;
+
+  } else {
+    total_bsphere = Sphere( Vertex(0,0,0), 1 );
+  }
+  
+  // Now get the matrices.  First we compute the projection matrix.  If we're inheriting,
+  // just use the parent.
+  
+  if (do_projection > EMBED_INHERIT) {
+    projMatrix.getData(saveprojection);
+    setupProjMatrix(renderContext, total_bsphere);
+  } else
+    projMatrix = parent->projMatrix;
+  
+  // Now the model matrix.  Since this depends on both the viewpoint and the model
+  // transformations, we don't bother using the parent one, we reconstruct in
+  // every subscene.
+  
+  if (do_projection > EMBED_INHERIT || do_model > EMBED_INHERIT)
+    setupModelViewMatrix(renderContext, total_bsphere.center);
+  else
+    modelMatrix = parent->modelMatrix;
+    
+  // update subscenes
+    
+  std::vector<Subscene*>::const_iterator iter;
+  for(iter = subscenes.begin(); iter != subscenes.end(); ++iter) 
+    (*iter)->update(renderContext);
+    
+}
+
+void Subscene::render(RenderContext* renderContext)
+{
+  renderContext->subscene = this;
+  
+  glViewport(pviewport.x, pviewport.y, pviewport.width, pviewport.height);
+  glScissor(pviewport.x, pviewport.y, pviewport.width, pviewport.height);
+  SAVEGLERROR;
+  
+  if (background) {
+    GLbitfield clearFlags = background->getClearFlags(renderContext);
+
+    // clear
+    glDepthMask(GL_TRUE);
+    glClear(clearFlags);
+  }
+  SAVEGLERROR;
+  
+  // Now render the current scene.  First we set the projection matrix, then the modelview matrix.
+  
+  double mat[16];
+  projMatrix.getData(mat);
+  glMatrixMode(GL_PROJECTION);
+  glLoadMatrixd(mat);  
+  SAVEGLERROR; 
+  
+  modelMatrix.getData(mat);
+  glMatrixMode(GL_MODELVIEW);  
+  glLoadMatrixd(mat);
+  SAVEGLERROR;
+  
+  setupLights(renderContext);
+  
+  if (background) {
+    //
+    // RENDER BACKGROUND
+    //
+
+    // DISABLE Z-BUFFER TEST
+    glDisable(GL_DEPTH_TEST);
+
+    // DISABLE Z-BUFFER FOR WRITING
+    glDepthMask(GL_FALSE);
+  
+    background->render(renderContext);
+    SAVEGLERROR;
+  }
+  
+  //
+  // RENDER MODEL
+  //
+
+  // if (data_bbox.isValid() ) {
+
+    //
+    // RENDER SOLID SHAPES
+    //
+
+    // ENABLE Z-BUFFER TEST 
+    glEnable(GL_DEPTH_TEST);
+
+    // ENABLE Z-BUFFER FOR WRITING
+    glDepthMask(GL_TRUE);
+
+    // DISABLE BLENDING
+    glDisable(GL_BLEND);
+    
+    // CLIP PLANES
+    renderClipplanes(renderContext);
+    
+    //
+    // RENDER BBOX DECO
+    //
+
+    if (bboxdeco) 
+      bboxdeco->render(renderContext);  // This changes the modelview/projection/viewport
+
+    SAVEGLERROR;
+
+    renderUnsorted(renderContext);
+
+// #define NO_BLEND
+
+#ifndef NO_BLEND
+    //
+    // RENDER BLENDED SHAPES
+    //
+    // render shapes in bounding-box sorted order according to z value
+    //
+
+    // DISABLE Z-BUFFER FOR WRITING
+    glDepthMask(GL_FALSE);
+    
+    SAVEGLERROR;
+    
+    // SETUP BLENDING
+    if (renderContext->gl2psActive == GL2PS_NONE) 
+      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+    else
+      gl2psBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
+
+    SAVEGLERROR;
+    
+    // ENABLE BLENDING
+    glEnable(GL_BLEND);
+
+    SAVEGLERROR;
+
+    //
+    // GET THE TRANSFORMATION
+    //
+
+    Matrix4x4 M(modelMatrix);    
+    Matrix4x4 P(projMatrix);
+    P = P*M;
+    
+    Zrow = P.getRow(2);
+    Wrow = P.getRow(3);
+    
+    renderZsort(renderContext);
+#endif    
+
+    /* Reset flag(s) now that scene has been rendered */
+    getModelViewpoint()->scaleChanged = false;
+
+    /* Reset clipplanes */
+    disableClipplanes(renderContext);
+    SAVEGLERROR;
+  // }
+  
+  // Render subscenes
+    
+  std::vector<Subscene*>::const_iterator iter;
+  for(iter = subscenes.begin(); iter != subscenes.end(); ++iter) 
+    (*iter)->render(renderContext);
+}
+
+void Subscene::calcDataBBox()
+{
+  data_bbox.invalidate();
+  
+  std::vector<Subscene*>::const_iterator subiter;
+  bboxChanges = false;
+  
+  for(subiter = subscenes.begin(); subiter != subscenes.end(); ++subiter) {
+    Subscene* subscene = *subiter;
+    if (!subscene->getIgnoreExtent()) {
+      subscene->calcDataBBox();
+      data_bbox += subscene->getBoundingBox();
+      bboxChanges |= subscene->bboxChanges;
+    }
+  }
+      
+  std::vector<Shape*>::const_iterator iter;
+  for(iter = shapes.begin(); iter != shapes.end(); ++iter) {
+    Shape* shape = *iter;
+
+    if (!shape->getIgnoreExtent()) {
+      data_bbox += shape->getBoundingBox(this);
+      bboxChanges |= shape->getBBoxChanges();
+    }
+  }
+  intersectClipplanes(); 
+}
+
+void Subscene::intersectClipplanes(void) 
+{
+  std::vector<ClipPlaneSet*>::iterator iter;
+  for (iter = clipPlanes.begin() ; iter != clipPlanes.end() ; ++iter ) {
+      ClipPlaneSet* plane = *iter;
+      plane->intersectBBox(data_bbox);
+      SAVEGLERROR;
+  }
+}
+
+/* Call this when adding a clipplane that can shrink things */
+void Subscene::shrinkBBox(void)
+{
+  if (parent) parent->shrinkBBox();
+  else {
+      calcDataBBox();
+  }
+}
+// ---------------------------------------------------------------------------
+void Subscene::setIgnoreExtent(int in_ignoreExtent)
+{
+  ignoreExtent = (bool)in_ignoreExtent;
+}
+
+void Subscene::setupViewport(RenderContext* rctx)
+{
+  Rect2 rect(0,0,0,0);
+  if (do_viewport == EMBED_REPLACE) {
+    rect.x = rctx->rect.x + viewport.x*rctx->rect.width;
+    rect.y = rctx->rect.y + viewport.y*rctx->rect.height;
+    rect.width = rctx->rect.width*viewport.width;
+    rect.height = rctx->rect.height*viewport.height;
+  } else {
+    rect.x = parent->pviewport.x + viewport.x*parent->pviewport.width;
+    rect.y = parent->pviewport.y + viewport.y*parent->pviewport.height;
+    rect.width = parent->pviewport.width*viewport.width;
+    rect.height = parent->pviewport.height*viewport.height;
+  }
+  pviewport = rect;
+}
+
+void Subscene::setupProjMatrix(RenderContext* rctx, const Sphere& viewSphere)
+{
+  if (do_projection == EMBED_REPLACE) 
+    projMatrix.setIdentity();
+
+  getUserViewpoint()->setupFrustum(rctx, viewSphere);   
+}
+
+// The ModelView matrix has components of the user view (the translation at the start)
+// and also the model transformations.  The former comes from the userViewpoint,
+// the latter from the modelViewpoint, possibly after applying the same from the parents.
+// We always reconstruct from scratch rather than trying to use the matrix in place.
+
+void Subscene::setupModelViewMatrix(RenderContext* rctx, Vertex center)
+{
+  modelMatrix.setIdentity();
+  getUserViewpoint()->setupViewer(rctx);
+  setupModelMatrix(rctx, center);
+}
+
+void Subscene::setupModelMatrix(RenderContext* rctx, Vertex center)
+{
+  /* The recursive call below will set the active subscene
+     modelMatrix, not the inherited one. */
+     
+  if (do_model < EMBED_REPLACE && parent)
+    parent->setupModelMatrix(rctx, center);
+    
+  if (do_model > EMBED_INHERIT)
+    getModelViewpoint()->setupTransformation(rctx, center);
+  
+}
+
+void Subscene::disableLights(RenderContext* rctx)
+{
+    
+  //
+  // disable lights; setup will enable them
+  //
+
+  for (int i=0;i<8;i++)
+    glDisable(GL_LIGHT0 + i);  
+}  
+
+void Subscene::setupLights(RenderContext* rctx) 
+{  
+  int nlights = 0;
+  bool anyviewpoint = false;
+  std::vector<Light*>::const_iterator iter;
+  
+  disableLights(rctx);
+
+  for(iter = lights.begin(); iter != lights.end() ; ++iter ) {
+
+    Light* light = *iter;
+    light->id = GL_LIGHT0 + (nlights++);
+    if (!light->viewpoint)
+      light->setup(rctx);
+    else
+      anyviewpoint = true;
+  }
+
+  SAVEGLERROR;
+
+  if (anyviewpoint) {
+    //
+    // viewpoint lights
+    //
+
+    glMatrixMode(GL_MODELVIEW);
+    glPushMatrix();
+    glLoadIdentity();
+
+    for(iter = lights.begin(); iter != lights.end() ; ++iter ) {
+
+      Light* light = *iter;
+
+      if (light->viewpoint)
+        light->setup(rctx);
+    }
+    glPopMatrix();
+  }
+  SAVEGLERROR;
+
+}
+
+void Subscene::renderUnsorted(RenderContext* renderContext)
+{
+  std::vector<Shape*>::iterator iter;
+
+  for (iter = unsortedShapes.begin() ; iter != unsortedShapes.end() ; ++iter ) {
+    Shape* shape = *iter;
+    shape->render(renderContext);
+    SAVEGLERROR;
+  }
+}
+    
+void Subscene::renderZsort(RenderContext* renderContext)
+{  
+  std::vector<Shape*>::iterator iter;
+  std::multimap<float, ShapeItem*> distanceMap;
+  int index = 0;
+
+  for (iter = zsortShapes.begin() ; iter != zsortShapes.end() ; ++iter ) {
+    Shape* shape = *iter;
+    shape->renderBegin(renderContext);
+    for (int j = 0; j < shape->getElementCount(); j++) {
+	ShapeItem* item = new ShapeItem(shape, j);
+	float distance = getDistance( shape->getElementCenter(j) );
+      distanceMap.insert( std::pair<const float,ShapeItem*>(-distance, item) );
+      index++;
+    }
+  }
+
+  {
+    Shape* prev = NULL;
+    std::multimap<float,ShapeItem*>::iterator iter;
+    for (iter = distanceMap.begin() ; iter != distanceMap.end() ; ++ iter ) {
+      ShapeItem* item = iter->second;
+      Shape* shape = item->shape;
+      if (shape != prev) {
+        if (prev) prev->drawEnd(renderContext);
+        shape->drawBegin(renderContext);
+        prev = shape;
+      }
+      shape->drawElement(renderContext, item->itemnum);
+      delete item;
+    }
+    if (prev) prev->drawEnd(renderContext);
+  }
+}
+
+const AABox& Subscene::getBoundingBox()
+{ 
+  if (bboxChanges) 
+      calcDataBBox();
+  return data_bbox; 
+}
+
+void Subscene::newEmbedding()
+{
+  if (parent) {
+    if (do_projection == EMBED_REPLACE && !userviewpoint)
+      add(new UserViewpoint(*(parent->getUserViewpoint())));
+    else if (do_projection == EMBED_MODIFY && !userviewpoint)
+      add(new UserViewpoint(0.0, 1.0)); /* should be like an identity */
+    
+    if (do_model == EMBED_REPLACE && !modelviewpoint)
+      add(new ModelViewpoint(*(parent->getModelViewpoint())));
+    else if (do_model == EMBED_MODIFY && !modelviewpoint)
+      add(new ModelViewpoint(PolarCoord(0.0, 0.0), Vec3(1.0, 1.0, 1.0), 
+                             parent->getModelViewpoint()->isInteractive()));
+  }
+}
+
+void Subscene::setEmbedding(int which, Embedding value)
+{
+  switch(which) {
+    case 0: do_viewport = value; break;
+    case 1: do_projection = value; break;
+    case 2: do_model = value; 
+  }
+  newEmbedding();
+}
+
+Embedding Subscene::getEmbedding(int which)
+{
+  switch(which) {
+    case 0: return do_viewport;
+    case 1: return do_projection;
+    default: return do_model;
+  }
+}
+
+void Subscene::getUserMatrix(double* dest)
+{
+  ModelViewpoint* modelviewpoint = getModelViewpoint();
+  modelviewpoint->getUserMatrix(dest);
+}
+
+void Subscene::setUserMatrix(double* src)
+{
+  ModelViewpoint* modelviewpoint = getModelViewpoint();
+  modelviewpoint->setUserMatrix(src);
+}
+
+void Subscene::getScale(double* dest)
+{
+  ModelViewpoint* modelviewpoint = getModelViewpoint();
+  modelviewpoint->getScale(dest);
+}
+
+void Subscene::setScale(double* src)
+{
+  ModelViewpoint* modelviewpoint = getModelViewpoint();
+  modelviewpoint->setScale(src);
+}
+
+void Subscene::getPosition(double* dest)
+{
+  ModelViewpoint* modelviewpoint = getModelViewpoint();
+  modelviewpoint->getPosition(dest);
+}
+
+void Subscene::setPosition(double* src)
+{
+  ModelViewpoint* modelviewpoint = getModelViewpoint();
+  modelviewpoint->setPosition(src);
+}
+
+void Subscene::setViewport(double x, double y, double width, double height)
+{
+  viewport.x = x;
+  viewport.y = y;
+  viewport.width = width;
+  viewport.height = height;
+}
+
+void Subscene::setMouseListeners(unsigned int n, int* ids)
+{
+  mouseListeners.clear();
+  for (unsigned int i = 0; i < n; i++)
+    mouseListeners.push_back(ids[i]);
+}
+
+void Subscene::getMouseListeners(unsigned int max, int* ids)
+{
+  max = max > mouseListeners.size() ? mouseListeners.size() : max;  
+  for (unsigned int i = 0; i < max; i++)
+    ids[i] = mouseListeners[i];
+}
+
+float Subscene::getDistance(const Vertex& v) const
+{
+  Vertex4 vec = Vertex4(v, 1.0f);
+
+  return (Zrow*vec) / (Wrow*vec);
+}
diff --git a/src/subscene.h b/src/subscene.h
new file mode 100644
index 0000000..7c8277e
--- /dev/null
+++ b/src/subscene.h
@@ -0,0 +1,234 @@
+#ifndef SUBSCENE_H
+#define SUBSCENE_H
+
+#include "Shape.h"
+#include "ClipPlane.h"
+#include "Viewpoint.h"
+#include "Background.h"
+#include "BBoxDeco.h"
+#include "Light.h"
+#include <map>
+
+namespace rgl {
+
+enum Embedding { EMBED_INHERIT=1, EMBED_MODIFY, EMBED_REPLACE };
+
+class Subscene : public SceneNode {
+  /* Subscenes do their own projection.  They can inherit, modify or replace the
+     viewport, projection and model matrices.  The root viewport always replaces them,
+     since it doesn't have anything to inherit.
+  */
+private:
+
+  void setupViewport(RenderContext* rctx);
+  void setupProjMatrix(RenderContext* rctx, const Sphere& viewSphere);
+  void setupModelMatrix(RenderContext* rctx, Vertex center);
+  void setupModelViewMatrix(RenderContext* rctx, Vertex center);
+  
+  void disableLights(RenderContext* rctx);
+  void setupLights(RenderContext* rctx);
+  
+  void newEmbedding();
+
+  /* These lists contain pointers to lights and shapes, but don't actually manage them:  the Scene does that. */
+  std::vector<Light*> lights;
+  std::vector<Shape*> shapes;
+  std::vector<Shape*> unsortedShapes;
+  std::vector<Shape*> zsortShapes;
+  std::vector<ClipPlaneSet*> clipPlanes;  
+
+  /* Subscenes form a tree; this is the parent subscene.  The root has a NULL parent. */
+  Subscene* parent;
+  /* Here are the children */
+  std::vector<Subscene*> subscenes;
+  
+  UserViewpoint* userviewpoint;
+  ModelViewpoint* modelviewpoint;
+  /**
+   * bounded background
+   **/
+  Background* background;
+  /**
+   * bounded decorator
+   **/
+  BBoxDeco*  bboxdeco;  
+  
+  /** 
+   * How is this subscene embedded in its parent?
+   **/
+  Embedding do_viewport, do_projection, do_model;
+  
+  /**
+   * This viewport on the (0,0) to (1,1) scale
+   **/
+  Rect2d viewport;
+public:
+  Subscene(Embedding in_viewport, Embedding in_projection, Embedding in_model,
+           bool in_ignoreExtent);
+  virtual ~Subscene( );
+
+  bool add(SceneNode* node);
+  void addBackground(Background* newbackground);
+  void addBBoxDeco(BBoxDeco* bboxdeco);
+  void addShape(Shape* shape);
+  void addLight(Light* light);
+  void addSubscene(Subscene* subscene);
+  void addBBox(const AABox& bbox, bool changes);
+  void intersectClipplanes(void);
+  
+  /**
+   * hide shape or light or bboxdeco
+   **/
+   
+  void hideShape(int id);
+  void hideLight(int id);
+  void hideBBoxDeco(int id);
+  void hideBackground(int id);
+  Subscene* hideSubscene(int id, Subscene* current);
+  void hideViewpoint(int id);
+
+  /**
+   * recursive search for subscene; could return self, or NULL if not found
+   **/
+  Subscene* getSubscene(int id);
+  Subscene* whichSubscene(int id); /* which subscene holds this */
+  Subscene* whichSubscene(int mouseX, int mouseY); /* coordinates are pixels within the window */
+  
+  /**
+   * get parent, or NULL for the root
+   **/  
+  Subscene* getParent() const { return parent; }
+
+  /**
+   * get children
+   **/
+  int getChildCount() const { return subscenes.size(); }
+  Subscene* getChild(int which) const { return subscenes[which]; }
+  
+  /**
+   * obtain bounding box
+   **/
+  const AABox& getBoundingBox() const { return data_bbox; }
+    
+  /**
+   * get the bbox
+   */
+  BBoxDeco* get_bboxdeco();
+  
+   /**
+   * get a bbox
+   */
+  BBoxDeco* get_bboxdeco(int id);
+  
+  /**
+   * get the background
+   */
+  Background* get_background() const { return background; }
+  
+  /** 
+   * get a background
+   */
+  Background* get_background(int id);
+  
+  /**
+   * obtain subscene's axis-aligned bounding box. 
+   **/
+  const AABox& getBoundingBox();
+
+ /**
+   * get information about stacks
+   */
+  int get_id_count(TypeID type, bool recursive);
+  int get_ids(TypeID type, int* ids, char** types, bool recursive);
+
+  virtual int getAttributeCount(AABox& bbox, AttribID attrib);
+  
+  virtual void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result);
+  virtual String getTextAttribute(AABox& bbox, AttribID attrib, int index);
+
+  /* Update matrices etc. in preparation for rendering */
+  void update(RenderContext* renderContext);
+  
+  /* Do the OpenGL rendering */
+  void render(RenderContext* renderContext);
+
+  void renderClipplanes(RenderContext* renderContext);
+  void disableClipplanes(RenderContext* renderContext);
+  
+  void renderUnsorted(RenderContext* renderContext);
+  void renderZsort(RenderContext* renderContext);
+  
+  /**
+   * Get and set flag to ignore elements in bounding box
+   **/
+  
+  int getIgnoreExtent(void) const { return (int) ignoreExtent; }
+  void setIgnoreExtent(int in_ignoreExtent);
+  
+  void setEmbedding(int which, Embedding value);  /* which is 0=viewport, 1=projection, 2=model */
+  Embedding getEmbedding(int which);
+  
+  void setUserMatrix(double* src);
+  void setScale(double* src);
+  void setViewport(double x, double y, double width, double height); /* Sets relative (i.e. [0,1]x[0,1]) viewport size */
+  void setPosition(double* src);
+  
+  void getUserMatrix(double* dest);
+  void getScale(double* dest);
+  void getPosition(double* dest);
+  
+  void setMouseListeners(unsigned int n, int* ids);
+  void getMouseListeners(unsigned int max, int* ids);
+  
+  float getDistance(const Vertex& v) const;
+
+// Translate from OpenGL window-relative coordinates (relative to bottom left corner of window) to
+// viewport relative (relative to bottom left corner of viewport)
+  void translateCoords(int* mouseX, int* mouseY) const { *mouseX = *mouseX - pviewport.x; *mouseY = *mouseY - pviewport.y; }
+  
+  
+  UserViewpoint* getUserViewpoint();
+  ModelViewpoint* getModelViewpoint();
+
+  virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "subscene", buflen); };
+  
+  Background* get_background(); 
+  
+  /* This vector lists other subscenes that will be controlled
+     by mouse actions on this one.  We do it by ID rather
+     than pointer so we can detect when any are invalid.  
+     Initially only the subscene itself is in the list. */
+     
+  std::vector<int> mouseListeners;
+  
+  // These are set after rendering the scene
+  Vec4 Zrow;
+  Vec4 Wrow;
+  Matrix4x4 modelMatrix, projMatrix;
+  Rect2 pviewport;  // viewport in pixels
+    
+private:
+    
+  /**
+   * compute bounding-box
+   **/
+  void calcDataBBox();
+  
+  /**
+   * shrink bounding-box when something has been removed
+   **/
+
+  void shrinkBBox();
+  
+  /**
+   * bounding box of subscene
+   **/
+  AABox data_bbox;
+  
+  bool ignoreExtent;
+  bool bboxChanges;
+};
+
+} // namespace rgl
+
+#endif // SUBSCENE_H
diff --git a/src/types.h b/src/types.h
new file mode 100644
index 0000000..6fa1f99
--- /dev/null
+++ b/src/types.h
@@ -0,0 +1,162 @@
+#ifndef RGL_TYPES_H
+#define RGL_TYPES_H
+
+#include <cstring>
+#include "pragma.h"
+
+// C++ header file
+// This file is part of RGL
+//
+// $Id: types.h 991 2013-11-20 20:26:13Z murdoch $
+
+namespace rgl {
+
+//
+//
+// constants
+//
+//
+
+
+#ifndef NULL
+#define NULL    0UL
+#endif
+
+
+
+//
+//
+// fundamental data types
+//
+//
+
+
+
+typedef unsigned char u8;
+typedef long          u32;
+
+
+
+//
+// memory management objects
+//
+
+
+class AutoDestroy
+{
+public:
+  AutoDestroy() { refcount = 0; }
+  virtual ~AutoDestroy() { }
+  void ref() { refcount++; }
+  void unref() { if ( !(--refcount) ) delete this; }
+private:
+  int refcount;
+};
+
+template<class T>
+class Ref
+{
+public:
+  Ref() : ptr(NULL) { }
+  Ref(T* in_ptr) : ptr(in_ptr) { if (ptr) ptr->ref(); }
+  Ref(const Ref& ref) : ptr(ref.ptr) { if (ptr) ptr->ref(); }
+  ~Ref() { if (ptr) ptr->unref(); }
+  Ref& operator = (T* in_ptr) { if (ptr) ptr->unref(); ptr = in_ptr; if (ptr) ptr->ref(); return *this; }
+  T* operator -> () { return ptr; }
+  operator bool () { return (ptr) ? true : false; }
+private:
+  T* ptr;
+};
+
+//
+// CLASS
+//  DestroyHandler
+//
+
+class DestroyHandler
+{
+public:
+  virtual ~DestroyHandler();    
+  virtual void notifyDestroy(void* userdata) = 0;
+};
+
+//
+// mem copy
+//
+
+template<class A, class B>
+inline void copy(A* from, B* to, int size)
+{
+  memcpy( (void*) to, (const void*) from, size*sizeof(A) );
+	}
+
+//
+// TEMPLATE
+//   ARRAY
+//
+
+template<class T>
+struct ARRAY
+{
+  int _size;
+  T*  ptr;
+  inline int size()
+  { return _size; }
+  inline ARRAY(int in_size) : _size(in_size), ptr(new T [_size])
+  { }
+  template<class SRC>
+  inline ARRAY(int in_size, SRC* src) : _size(in_size), ptr(new T [_size])
+  { copy(src, ptr,_size); }
+  inline ~ARRAY()
+  { delete [] ptr; }
+  inline T& get(int index)
+  { return ptr[index]; }
+  inline T& getRecycled(int index)
+  { return ptr[index%_size]; };
+};
+
+//
+// cast-copy doubles to floats
+//
+
+template<>
+inline void copy(double* from, float* to, int size)
+{
+  while(size--) {
+    *to = (float) *from;
+    from++; to++;
+  }
+}
+
+/**
+ * get most significant bit
+ * @param x unsigned value
+ * @return bit position between 1..32 or 0 if value was 0
+ **/
+inline int msb(unsigned int x) {
+  if (x) {
+    int bit = sizeof(int)*8;
+    unsigned int mask = 1<<((sizeof(int)*8)-1);
+    while ( !(x & mask) ) {
+      --bit; mask >>= 1;
+    }
+    return bit;
+  } else
+    return 0;
+}
+
+
+// template<class T> T getMax(T a, T b) { return (a > b) ? a : b; }
+// template<class T> T getMin(T a, T b) { return (a < b) ? a : b; }
+
+inline int   getMin(int a, int b)     { return (a <= b) ? a : b; }
+inline float getMin(float a, float b) { return (a <= b) ? a : b; }
+inline int   getMax(int a, int b)     { return (a >= b) ? a : b; }
+inline float getMax(float a, float b) { return (a >= b) ? a : b; }
+inline float clamp(float v, float floor, float ceil) { return (v<floor) ? floor : ( (v>ceil) ? ceil : v ); }
+inline int   clamp(int   v, int   floor, int   ceil) { return (v<floor) ? floor : ( (v>ceil) ? ceil : v ); }
+
+} // namespace rgl
+
+#endif /* RGL_TYPES_H */
+
diff --git a/src/win32gui.cpp b/src/win32gui.cpp
new file mode 100644
index 0000000..5871aa7
--- /dev/null
+++ b/src/win32gui.cpp
@@ -0,0 +1,781 @@
+#include "config.h"
+#ifdef RGL_W32
+// C++ source
+// This file is part of RGL.
+//
+// $Id: win32gui.cpp 1115 2014-07-18 13:51:22Z murdoch $
+
+#include "win32gui.h"
+
+#include "lib.h"
+#include "glgui.h"
+
+#include <winuser.h>
+#include <shlobj.h>
+#include "assert.h"
+#include "R.h"
+#include <Rinternals.h>
+
+#include <ctype.h>
+
+namespace rgl {
+
+extern int     gInitValue;
+extern HANDLE  gHandle;
+extern SEXP    rglNamespace;
+static WNDPROC gDefWindowProc;
+static HWND    gMDIClientHandle = 0;
+static HWND    gMDIFrameHandle  = 0;
+
+// describe requirements
+static const PIXELFORMATDESCRIPTOR pfd = {
+  sizeof(PIXELFORMATDESCRIPTOR),    // size of this pfd
+  1,                                // version number
+  0
+  | PFD_DRAW_TO_WINDOW              // support window
+  | PFD_SUPPORT_OPENGL              // support OpenGL
+  | PFD_GENERIC_FORMAT              // generic format
+  | PFD_DOUBLEBUFFER                // double buffered
+  ,
+  PFD_TYPE_RGBA,                    // RGBA type
+  16,                               // 16-bit color depth
+  0, 0, 0, 0, 0, 0,                 // color bits ignored
+  1,                                // alpha buffer
+  0,                                // shift bit ignored
+  0,                                // no accumulation buffer
+  0, 0, 0, 0,                       // accum bits ignored
+  16,                               // 16-bit z-buffer
+  0,                                // no stencil buffer
+  0,                                // no auxiliary buffer
+  PFD_MAIN_PLANE,                   // main layer
+  0,                                // reserved
+  0, 0, 0                           // layer masks ignored
+};
+
+// ---------------------------------------------------------------------------
+//
+// translate keycode
+//
+// ---------------------------------------------------------------------------
+static int translate_key(int wParam) 
+{
+  if ( (wParam >= VK_F1) && (wParam <= VK_F12) ) {
+    return ( GUI_KeyF1 + (wParam - VK_F1) );
+  } else {
+    switch(wParam) {
+      case VK_UP:
+        return GUI_KeyUp;
+      case VK_DOWN:
+        return GUI_KeyDown;
+      case VK_LEFT:
+        return GUI_KeyLeft;
+      case VK_RIGHT:
+        return GUI_KeyRight;
+      case VK_INSERT:
+        return GUI_KeyInsert;
+      case VK_ESCAPE:
+      	return GUI_KeyESC;
+      default:
+        return 0;
+    }
+  }
+}
+// ---------------------------------------------------------------------------
+class Win32WindowImpl : public WindowImpl
+{ 
+public:
+  Win32WindowImpl(Window* in_window);
+  ~Win32WindowImpl();
+  void setTitle(const char* title);
+  void setWindowRect(int left, int top, int right, int bottom);
+  void getWindowRect(int *left, int *top, int *right, int *bottom);
+  void show();
+  void hide();
+  int  isTopmost(HWND handle);
+  void bringToTop(int stay);
+  void update();
+  void destroy();
+  void captureMouse(View* pView);
+  void releaseMouse();
+  GLFont* getFont(const char* family, int style, double cex, 
+                  bool useFreeType);
+
+private:
+  LRESULT processMessage(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
+  static bool registerClass();
+  static void unregisterClass();
+  static LRESULT CALLBACK delegateWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
+  static LRESULT CALLBACK windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
+  static ATOM classAtom;
+  HWND  windowHandle;
+  View* captureView;
+  bool  painting;               // window is currently busy painting
+  bool  autoUpdate;             // update/refresh automatically
+  bool  refreshMenu;		// need to tell Windows to update the menu
+#if defined(WGL_ARB_pixel_format) && !defined(WGL_WGLEXT_PROTOTYPES)
+  PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
+#endif
+  friend class Win32GUIFactory;
+
+public:
+  bool beginGL();
+  void endGL();
+  void swap();
+private:
+  bool initGL();
+  void shutdownGL();
+  GLBitmapFont* initGLBitmapFont(u8 firstGlyph, u8 lastGlyph);
+  HDC   dcHandle;               // temporary variable setup by lock
+  HGLRC glrcHandle;
+};
+
+} // namespace rgl
+
+using namespace rgl;
+// ----------------------------------------------------------------------------
+// constructor
+// ----------------------------------------------------------------------------
+Win32WindowImpl::Win32WindowImpl(Window* in_window)
+: WindowImpl(in_window)
+{
+  windowHandle = NULL;
+  captureView = NULL;
+
+  dcHandle = NULL;
+  glrcHandle = NULL;
+
+  painting = false;
+  autoUpdate = false;
+  refreshMenu = false;
+}
+
+Win32WindowImpl::~Win32WindowImpl()
+{
+  beginGL();
+  for (unsigned int i=0; i < fonts.size(); i++) {
+    delete fonts[i];
+  }
+  endGL();
+}
+
+void Win32WindowImpl::setTitle(const char* title)
+{
+  SetWindowText(windowHandle, title);
+}
+
+void Win32WindowImpl::setWindowRect(int left, int top, int right, int bottom)
+{
+  if (windowHandle) {
+    RECT rect;
+    
+    rect.left = left;
+    rect.top = top;
+    rect.right = right;
+    rect.bottom = bottom;
+    
+    // Specification gives the desired client coordinates; expand to include the frame
+    AdjustWindowRectEx(&rect, GetWindowLong(windowHandle, GWL_STYLE), FALSE,
+                              GetWindowLong(windowHandle, GWL_EXSTYLE)); 
+    MoveWindow(windowHandle, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top, TRUE);
+  }
+}
+
+void Win32WindowImpl::getWindowRect(int *left, int *top, int *right, int *bottom)
+{
+  if (windowHandle) {
+    RECT rect;
+    GetClientRect(windowHandle, &rect);
+    ClientToScreen(windowHandle, (LPPOINT)&rect.left);
+    ClientToScreen(windowHandle, (LPPOINT)&rect.right);
+    // Rect is now in screen coordinates; convert to parent client area coordinates 
+    // for MDI
+    HWND parent = GetParent(windowHandle);
+    if (parent) {
+      ScreenToClient(parent, (LPPOINT)&rect.left);
+      ScreenToClient(parent, (LPPOINT)&rect.right);
+    }
+    *left = rect.left;
+    *top = rect.top;
+    *right = rect.right;
+    *bottom = rect.bottom;
+  }
+}
+
+void Win32WindowImpl::show()
+{
+  if (windowHandle) {
+    // ShowWindow is required in SDI to show the window once 
+    // (otherwise to update takes place)
+    ShowWindow(windowHandle, SW_SHOW);
+    SetWindowPos(
+      windowHandle
+     ,HWND_TOP
+     ,0,0,0,0
+     ,SWP_SHOWWINDOW|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOSIZE
+    );
+    update();
+  } else
+    printMessage("window not bound");
+}
+
+void Win32WindowImpl::hide()
+{
+  if (windowHandle) {
+    ShowWindow(windowHandle, SW_HIDE);
+  }
+}
+
+int Win32WindowImpl::isTopmost(HWND handle)
+{
+  return GetWindowLong(handle, GWL_EXSTYLE) & WS_EX_TOPMOST;
+}
+
+void Win32WindowImpl::bringToTop(int stay) /* stay=0 for regular, 1 for topmost, 2 for toggle */
+{
+  if (windowHandle) {
+    SetForegroundWindow(windowHandle); /* needed in Rterm */
+    BringWindowToTop(windowHandle);    /* needed in Rgui --mdi */
+
+    if (stay == 2) 
+      stay = !isTopmost(windowHandle);
+
+    if (stay) 
+      SetWindowPos(
+        windowHandle
+      , HWND_TOPMOST
+      , 0, 0, 0, 0
+      , SWP_NOMOVE | SWP_NOSIZE
+      );
+    else 
+      SetWindowPos(windowHandle
+      , HWND_NOTOPMOST
+      , 0, 0, 0, 0
+      , SWP_NOMOVE | SWP_NOSIZE
+      );
+  } else
+    printMessage("window not bound");
+}
+
+void Win32WindowImpl::update()
+{
+  InvalidateRect(windowHandle, NULL, false);
+  SAVEGLERROR;
+  UpdateWindow(windowHandle);
+  SAVEGLERROR;
+}
+
+void Win32WindowImpl::destroy()
+{
+  if (gHandle) SendMessage(gMDIClientHandle, WM_MDIDESTROY, (WPARAM) windowHandle, 0);
+  else DestroyWindow(windowHandle);
+}
+
+bool Win32WindowImpl::beginGL()
+{
+  dcHandle = GetDC(windowHandle);
+  if (wglMakeCurrent( dcHandle, glrcHandle )) return true;
+  else return false;
+}
+
+void Win32WindowImpl::endGL()
+{
+  ReleaseDC(windowHandle, dcHandle);
+}
+
+void Win32WindowImpl::swap()
+{
+  dcHandle = GetDC(windowHandle);
+  SwapBuffers(dcHandle);
+  ReleaseDC(windowHandle, dcHandle);
+}
+
+void Win32WindowImpl::captureMouse(View* inCaptureView)
+{
+  captureView = inCaptureView;
+  SetCapture(windowHandle);
+}
+
+void Win32WindowImpl::releaseMouse(void)
+{
+  captureView = NULL;
+  ReleaseCapture();
+}
+
+bool Win32WindowImpl::initGL () {
+  bool success = false;
+  // obtain a device context for the window
+  dcHandle = GetDC(windowHandle);
+  if (dcHandle) {
+    int  iPixelFormat;
+#ifdef WGL_ARB_pixel_format
+    // Setup antialiasing based on "rgl.antialias" option
+    int aa;
+    SEXP rgl_aa = GetOption(install("rgl.antialias"),R_BaseEnv);
+    if (isNull(rgl_aa)) aa = RGL_ANTIALIAS;
+    else aa = asInteger(rgl_aa);
+    
+    if (aa > 0) {
+      float fAttributes[] = { 0, 0 };
+      int iAttributes[] = {
+        WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
+        WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
+        WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB,
+        WGL_COLOR_BITS_ARB,     24,
+        WGL_ALPHA_BITS_ARB,     8,
+        WGL_DEPTH_BITS_ARB,     16,
+        WGL_STENCIL_BITS_ARB,   0,
+        WGL_DOUBLE_BUFFER_ARB,  GL_TRUE,
+        WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
+        WGL_SAMPLES_ARB,        aa,
+        0, 0 };
+      UINT numFormats = 0;
+      if (!wglChoosePixelFormatARB || !wglChoosePixelFormatARB(dcHandle, iAttributes, fAttributes, 1, &iPixelFormat, &numFormats) || numFormats < 1) {
+        iPixelFormat = ChoosePixelFormat(dcHandle, &pfd);
+      }
+    } else
+#endif
+    // get the device context's best, available pixel format match
+    iPixelFormat = ChoosePixelFormat(dcHandle, &pfd);
+    if (iPixelFormat != 0) {
+      // make that match the device context's current pixel format
+      SetPixelFormat(dcHandle, iPixelFormat, &pfd);
+      // create GL context
+      if ( ( glrcHandle = wglCreateContext( dcHandle ) ) )
+          success = true;
+      else
+        printMessage("wglCreateContext failed");
+    }
+    else
+      printMessage("iPixelFormat == 0!");
+    ReleaseDC(windowHandle,dcHandle);
+  }
+
+  return success;
+}
+
+void Win32WindowImpl::shutdownGL() 
+{
+  dcHandle = GetDC(windowHandle);
+  wglMakeCurrent(NULL,NULL);
+  ReleaseDC(windowHandle, dcHandle);
+  wglDeleteContext(glrcHandle);
+}
+
+GLFont* Win32WindowImpl::getFont(const char* family, int style, double cex, 
+                                 bool useFreeType)
+{
+  for (unsigned int i=0; i < fonts.size(); i++) {
+    if (fonts[i]->cex == cex && fonts[i]->style == style && !strcmp(fonts[i]->family, family)
+     && fonts[i]->useFreeType == useFreeType)
+      return fonts[i];
+  }
+  
+  if (!useFreeType) {
+    // Not found, so create it.  This is based on code from graphapp gdraw.c
+    if (strcmp(family, "NA") && beginGL()) {  // User passes NA_character_ for default, looks like "NA" here
+      
+      SEXP Rfontname = VECTOR_ELT(PROTECT(eval(lang2(install("windowsFonts"), 
+                                          ScalarString(mkChar(family))), rglNamespace)),
+                                          0);
+      if (isString(Rfontname)) {
+        const char* fontname = CHAR(STRING_ELT(Rfontname, 0)); 
+        GLBitmapFont* font = new GLBitmapFont(family, style, cex, fontname);
+        HFONT hf;
+        LOGFONT lf;
+    
+        double size = 12*cex + 0.5;
+    
+        lf.lfHeight = -MulDiv(size, GetDeviceCaps(dcHandle, LOGPIXELSY), 72);
+  
+        lf.lfWidth = 0 ;
+        lf.lfEscapement = lf.lfOrientation = 0;
+        lf.lfWeight = FW_NORMAL;
+        lf.lfItalic = lf.lfUnderline = lf.lfStrikeOut = 0;
+        if ((! strcmp(fontname, "Symbol")) || (! strcmp(fontname, "Wingdings")))
+          lf.lfCharSet = SYMBOL_CHARSET;
+        else
+          lf.lfCharSet = DEFAULT_CHARSET;
+        lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
+        lf.lfQuality = DEFAULT_QUALITY;
+        lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
+        if ((strlen(fontname) > 1) && (fontname[0] == 'T') && (fontname[1] == 'T')) {
+          const char *pf;
+          lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
+          for (pf = &fontname[2]; isspace(*pf) ; pf++);
+          strncpy(lf.lfFaceName, pf, LF_FACESIZE-1);
+        }
+        else {
+          lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
+          strncpy(lf.lfFaceName, fontname, LF_FACESIZE-1);
+        }
+        if (style == 2 || style == 4) lf.lfWeight = FW_BOLD;
+        if (style == 3 || style == 4) lf.lfItalic = 1;
+      
+        if ((hf = CreateFontIndirect(&lf))) {
+          SelectObject (dcHandle, hf );
+          font->nglyph     = GL_BITMAP_FONT_LAST_GLYPH - GL_BITMAP_FONT_FIRST_GLYPH + 1;
+          font->widths     = new unsigned int [font->nglyph];
+          GLuint listBase = glGenLists(font->nglyph);
+          font->firstGlyph = GL_BITMAP_FONT_FIRST_GLYPH;
+          font->listBase   = listBase - font->firstGlyph;
+          GetCharWidth32( dcHandle, font->firstGlyph, GL_BITMAP_FONT_LAST_GLYPH,  (LPINT) font->widths );
+          {
+            TEXTMETRIC tm;
+            GetTextMetrics( dcHandle, &tm);
+            font->ascent = tm.tmAscent;
+          }
+          wglUseFontBitmaps(dcHandle, font->firstGlyph, font->nglyph, listBase);
+          DeleteObject( hf );
+          endGL();  
+          fonts.push_back(font);
+          UNPROTECT(1);
+          return font;
+        } 
+        delete font;
+        endGL();
+      }
+      UNPROTECT(1);
+    }
+  } else { // useFreeType
+#ifdef HAVE_FREETYPE
+    char fontname_absolute[MAX_PATH+1] = "";
+    int len=0;
+    SEXP Rfontname = VECTOR_ELT(PROTECT(eval(lang2(install("rglFonts"), 
+                                          ScalarString(mkChar(family))), rglNamespace)),
+                                          0);
+    if (isString(Rfontname) && length(Rfontname) >= style) {
+      const char* fontname = CHAR(STRING_ELT(Rfontname, style-1)); 
+      if (!IS_ABSOLUTE_PATH(fontname)) {
+        LPITEMIDLIST pidlFonts;
+        assert(SUCCEEDED(SHGetSpecialFolderLocation(0, CSIDL_FONTS, &pidlFonts))
+            && SUCCEEDED(SHGetPathFromIDList(pidlFonts, fontname_absolute)) );
+        len = strlen(fontname_absolute);
+        if (len && fontname_absolute[len-1] != '\\') {
+          strcat(fontname_absolute, "\\");
+          len++;
+        }
+      }
+      assert(len + strlen(fontname) <= MAX_PATH);
+      strcat(fontname_absolute, fontname);  
+      GLFTFont* font=new GLFTFont(family, style, cex, fontname_absolute);
+      if (font->font) {
+        fonts.push_back(font);
+        UNPROTECT(1);
+        return font;
+      } else {
+        warning(font->errmsg);
+        delete font;
+      }
+    }
+    UNPROTECT(1);
+#endif
+  }
+  if (strcmp(family, fonts[0]->family)) warning("font family \"%s\" not found, using \"%s\"", 
+                                         family, fonts[0]->family);
+  else if (style != fonts[0]->style) warning("\"%s\" family only supports font %d", 
+                                        fonts[0]->family, fonts[0]->style);
+  else if (cex != fonts[0]->cex) warning("\"%s\" family only supports cex = %g",
+  					fonts[0]->family, fonts[0]->cex);
+  else if (useFreeType) warning("FreeType font not available");
+  return fonts[0];
+}
+
+GLBitmapFont* Win32WindowImpl::initGLBitmapFont(u8 firstGlyph, u8 lastGlyph) 
+{
+  GLBitmapFont* font = NULL; 
+  if (beginGL()) {
+    font = new GLBitmapFont("bitmap", 1, 1, "System");
+    SelectObject (dcHandle, GetStockObject (SYSTEM_FONT) );
+    font->nglyph     = lastGlyph-firstGlyph+1;
+    font->widths     = new unsigned int [font->nglyph];
+    GLuint listBase = glGenLists(font->nglyph);
+    font->firstGlyph = firstGlyph;
+    font->listBase   = listBase - firstGlyph;
+    GetCharWidth32( dcHandle, font->firstGlyph, lastGlyph,  (LPINT) font->widths );
+    {  
+      TEXTMETRIC tm;
+      GetTextMetrics( dcHandle, &tm);
+      font->ascent = tm.tmAscent;
+    }    
+    wglUseFontBitmaps(dcHandle, font->firstGlyph, font->nglyph, listBase);
+    endGL();
+  }
+  return font;
+}
+
+LRESULT Win32WindowImpl::processMessage(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
+  LRESULT returnValue = 0;
+  switch(message) {
+    case WM_CREATE:
+      windowHandle = hwnd;
+      initGL();
+      fonts[0] = initGLBitmapFont(GL_BITMAP_FONT_FIRST_GLYPH, GL_BITMAP_FONT_LAST_GLYPH);
+      if (gHandle) {
+        refreshMenu = true;
+      }
+      break;
+    case WM_SHOWWINDOW:
+      if ( ( (BOOL) wParam ) == TRUE ) {
+        window->show();
+        autoUpdate = true;
+      }
+      else {
+        window->hide();
+        autoUpdate = false;
+      }
+      break;
+    case WM_PAINT: // Warning:  don't put Rprintf calls in paint/render/draw methods, or you get a permanent loop!
+      if (!painting) {
+        painting = true;
+        if (refreshMenu) {
+          SendMessage(gMDIClientHandle, WM_MDIREFRESHMENU, 0, 0);    
+          DrawMenuBar(gMDIFrameHandle);
+          refreshMenu = false;
+        }        
+        if (!window->skipRedraw) {
+          window->paint();
+          swap();
+        }  
+        ValidateRect(hwnd, NULL);
+        painting = false;
+      }
+      break;
+    case WM_SIZE:
+      window->resize(LOWORD(lParam), HIWORD(lParam));
+      if (gHandle)
+        return gDefWindowProc(hwnd,message,wParam,lParam);
+      else
+        break;
+    case WM_CLOSE:
+      window->on_close();
+      break;
+    case WM_KEYDOWN:
+      if (int keycode = translate_key(wParam) ) {
+        window->keyPress(keycode);
+      } else
+        return -1;
+    case WM_CHAR:
+      window->keyPress( (int) ( (char) wParam ) );
+      break;
+    case WM_LBUTTONDOWN:
+      ( (captureView) ? captureView : window ) -> buttonPress(GUI_ButtonLeft, (short) LOWORD(lParam), (short) HIWORD(lParam) );
+      break;
+    case WM_LBUTTONUP:
+      ( (captureView) ? captureView : window ) -> buttonRelease(GUI_ButtonLeft, (short) LOWORD(lParam), (short) HIWORD(lParam));
+      break;
+    case WM_RBUTTONDOWN:
+      ( (captureView) ? captureView : window ) -> buttonPress(GUI_ButtonRight,(short) LOWORD(lParam), (short) HIWORD(lParam) );
+      break;
+    case WM_RBUTTONUP:
+      ( (captureView) ? captureView : window ) -> buttonRelease(GUI_ButtonRight,(short) LOWORD(lParam), (short) HIWORD(lParam) );
+      break;
+    case WM_MBUTTONDOWN:
+      ( (captureView) ? captureView : window )
+       -> buttonPress(GUI_ButtonMiddle, (short) LOWORD(lParam), (short) HIWORD(lParam) );
+      break;
+    case WM_MBUTTONUP:
+      ( (captureView) ? captureView : window ) -> buttonRelease(GUI_ButtonMiddle, (short) LOWORD(lParam), (short) HIWORD(lParam) );
+      break;
+#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)
+    case WM_MOUSEWHEEL:
+      {
+        int dir = ( (short) HIWORD(wParam)  > 0 ) ?  GUI_WheelForward : GUI_WheelBackward;
+        ( (captureView) ? captureView : window ) -> wheelRotate(dir);
+        break;
+      }
+#endif
+    case WM_MOUSEMOVE:
+      ( (captureView) ? captureView : window ) -> mouseMove( ( (short) LOWORD(lParam) ), ( (short) HIWORD(lParam) ) );
+      break;
+    case WM_CAPTURECHANGED:
+      if (captureView) {
+        captureView->captureLost();
+        captureView = NULL;
+      }
+      break;
+    case WM_DESTROY:
+      shutdownGL();
+#if defined (WIN64) || defined(_MSC_VER) 
+	  SetWindowLongPtr(hwnd, GWLP_USERDATA, (long)NULL);
+#else
+      SetWindowLong(hwnd, GWL_USERDATA, (LONG) NULL );
+#endif
+      if (window)
+        window->notifyDestroy();
+      delete this;
+      break;
+    default:
+      return gDefWindowProc(hwnd,message,wParam,lParam);
+  }
+  return returnValue;
+}
+    
+// static 
+LRESULT CALLBACK Win32WindowImpl::delegateWindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
+#if defined (WIN64) || defined(_MSC_VER) 
+  Win32WindowImpl* windowImpl = (Win32WindowImpl*) GetWindowLongPtr(hwnd, GWLP_USERDATA);
+#else
+  Win32WindowImpl* windowImpl = (Win32WindowImpl*) GetWindowLong(hwnd, GWL_USERDATA);
+#endif
+  return windowImpl->processMessage(hwnd, message, wParam, lParam);
+}
+
+// static 
+LRESULT CALLBACK Win32WindowImpl::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
+  if (message == WM_CREATE) {
+    Win32WindowImpl* windowImpl;
+    LPCREATESTRUCT pCreateStruct = reinterpret_cast<LPCREATESTRUCT>(lParam);        
+    if (gHandle) {
+      LPMDICREATESTRUCT pMDICreateStruct = reinterpret_cast<LPMDICREATESTRUCT>(pCreateStruct->lpCreateParams);
+      windowImpl = reinterpret_cast<Win32WindowImpl*>( pMDICreateStruct->lParam );
+    } else {
+      windowImpl = reinterpret_cast<Win32WindowImpl*>( pCreateStruct->lpCreateParams );
+    }
+    if (windowImpl) {
+#if defined (WIN64) || defined(_MSC_VER) 
+      SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)windowImpl );
+      SetWindowLongPtr(hwnd, GWLP_WNDPROC, (LONG_PTR) delegateWindowProc );
+#else
+      SetWindowLong(hwnd, GWL_USERDATA, (long) windowImpl );
+      SetWindowLong(hwnd, GWL_WNDPROC, (long) delegateWindowProc );
+#endif
+      return windowImpl->processMessage(hwnd, message, wParam, lParam);
+    }
+  } 
+  return gDefWindowProc(hwnd, message, wParam, lParam); 
+}
+
+// static 
+bool Win32WindowImpl::registerClass() {
+  WNDCLASSEX wcex;
+  ZeroMemory( &wcex, sizeof(WNDCLASSEX) );
+  wcex.cbSize = sizeof(WNDCLASSEX);
+  wcex.style          = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
+  wcex.lpfnWndProc    = (WNDPROC) windowProc;
+  wcex.hIcon          = LoadIcon(NULL, IDI_APPLICATION);
+  wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
+  wcex.lpszClassName  = "RGLDevice";
+  classAtom = RegisterClassEx(&wcex);
+  return (classAtom) ? true : false;
+}
+
+// static 
+void Win32WindowImpl::unregisterClass(void) {
+  if (classAtom)
+    UnregisterClass(MAKEINTATOM(classAtom), NULL );
+}
+
+// static 
+ATOM Win32WindowImpl::classAtom = (ATOM) NULL;
+
+// ---------------------------------------------------------------------------
+//
+// Win32GUIFactory class
+//
+// ---------------------------------------------------------------------------
+
+
+Win32GUIFactory::Win32GUIFactory()
+#if defined(WGL_ARB_pixel_format) && !defined(WGL_WGLEXT_PROTOTYPES)
+: wglChoosePixelFormatARB(NULL)
+#endif
+{
+  if (gInitValue) {
+    // we must be running in pre-2.6.0 R
+    gHandle = reinterpret_cast<HANDLE>(gInitValue);
+  }
+  if (gHandle) {
+    // the handle is given for the console window, so that
+    // client and frame windows can be derived
+    HWND consoleHandle = reinterpret_cast<HWND>(gHandle);
+    gMDIClientHandle = GetParent(consoleHandle);
+    gMDIFrameHandle  = GetParent(gMDIClientHandle);
+    gDefWindowProc   = &DefMDIChildProc;
+  } else
+    gDefWindowProc   = &DefWindowProc;
+  if ( !Win32WindowImpl::registerClass() )
+    error("window class registration failed");
+
+#if defined(WGL_ARB_pixel_format) && !defined(WGL_WGLEXT_PROTOTYPES)
+  HANDLE saveHandle = gHandle;
+  gHandle = NULL; /* call below fails for MDI windows */
+  // wglGetProcAddress needs to be called within valid GL context, we need to create dummy window here
+  HWND windowHandle = CreateWindow(MAKEINTATOM(Win32WindowImpl::classAtom), "", WS_POPUP | WS_DISABLED, 0, 0, 10, 10, NULL, NULL, NULL, NULL);
+  if (windowHandle) {
+    HDC dcHandle = GetDC(windowHandle);
+    if (dcHandle) {
+      int iPixelFormat = ChoosePixelFormat(dcHandle, &pfd);
+      if (iPixelFormat != 0) {
+        SetPixelFormat(dcHandle, iPixelFormat, &pfd);
+        HGLRC glrcHandle = wglCreateContext(dcHandle);
+        if (glrcHandle) {
+          wglMakeCurrent(dcHandle, glrcHandle);
+          wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
+          wglMakeCurrent(NULL, NULL);
+          wglDeleteContext(glrcHandle);
+        }
+      }
+      ReleaseDC(windowHandle, dcHandle);
+    }
+    DestroyWindow(windowHandle);
+  }
+  gHandle = saveHandle;
+#endif
+}
+// ---------------------------------------------------------------------------
+Win32GUIFactory::~Win32GUIFactory() {
+  Win32WindowImpl::unregisterClass();
+}
+// ---------------------------------------------------------------------------
+
+WindowImpl* Win32GUIFactory::createWindowImpl(Window* in_window)
+{
+  Win32WindowImpl* impl = new Win32WindowImpl(in_window);
+#if defined(WGL_ARB_pixel_format) && !defined(WGL_WGLEXT_PROTOTYPES)
+  impl->wglChoosePixelFormatARB = wglChoosePixelFormatARB;
+#endif  
+
+  RECT size;
+
+  size.left = 0;
+  size.right = in_window->width-1;
+  size.top  = 0;
+  size.bottom = in_window->height-1;
+
+  AdjustWindowRect(
+    &size
+  , WS_OVERLAPPEDWINDOW // WS_CAPTION|WS_SYSMENU|WS_THICKFRAME|WS_MINIMIZEBOX|WS_MAXIMIZEBOX
+  , false // no menu
+  );
+
+  HWND success = 0;
+  
+  if (gHandle) {
+    success = CreateMDIWindow(
+      MAKEINTATOM(Win32WindowImpl::classAtom)
+    , in_window->title
+    , MDIS_ALLCHILDSTYLES|WS_OVERLAPPEDWINDOW
+    , CW_USEDEFAULT, 0
+    , size.right- size.left+1, size.bottom - size.top+1
+    , gMDIClientHandle, NULL // GetModuleHandle(NULL)
+    , reinterpret_cast<LPARAM>(impl)
+    );
+  } else {
+    success = CreateWindow(
+      MAKEINTATOM(Win32WindowImpl::classAtom)
+    , in_window->title
+    , WS_OVERLAPPEDWINDOW
+    , CW_USEDEFAULT, 0
+    , size.right- size.left+1, size.bottom - size.top+1
+    , NULL, NULL, NULL
+    , reinterpret_cast<LPVOID>(impl)
+    );
+  }
+  if (!success)
+    error("window creation failed");
+
+  return impl;
+}
+// ---------------------------------------------------------------------------
+#endif // RGL_W32
+
diff --git a/src/win32gui.h b/src/win32gui.h
new file mode 100644
index 0000000..85f566c
--- /dev/null
+++ b/src/win32gui.h
@@ -0,0 +1,28 @@
+#ifndef RGL_W32_GUI_H
+#define RGL_W32_GUI_H
+// ---------------------------------------------------------------------------
+// $Id: win32gui.h 1115 2014-07-18 13:51:22Z murdoch $
+// ---------------------------------------------------------------------------
+#include "gui.h"
+// ---------------------------------------------------------------------------
+#include <windows.h>
+
+namespace rgl {
+
+// ---------------------------------------------------------------------------
+class Win32GUIFactory : public GUIFactory
+{
+public:
+  Win32GUIFactory();
+  virtual ~Win32GUIFactory();
+  WindowImpl* createWindowImpl(Window* window);
+#ifndef WGL_WGLEXT_PROTOTYPES
+  PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
+#endif
+};
+// ---------------------------------------------------------------------------
+
+} // namespace rgl
+
+#endif // RGL_W32_GUI_H
+
diff --git a/src/win32lib.cpp b/src/win32lib.cpp
new file mode 100644
index 0000000..29aaa5e
--- /dev/null
+++ b/src/win32lib.cpp
@@ -0,0 +1,71 @@
+#include "config.h"
+#ifdef RGL_W32
+// ---------------------------------------------------------------------------
+// W32 Library Implementation
+// $Id: win32lib.cpp 1115 2014-07-18 13:51:22Z murdoch $
+// ---------------------------------------------------------------------------
+#include "lib.h"
+#include "win32gui.h"
+#include "NULLgui.h"
+#include <windows.h>
+#include "assert.h"
+#include "R.h"
+
+using namespace rgl;
+
+// ---------------------------------------------------------------------------
+// GUI Factory
+// ---------------------------------------------------------------------------
+Win32GUIFactory* gpWin32GUIFactory = NULL;
+NULLGUIFactory* gpNULLGUIFactory = NULL;
+// ---------------------------------------------------------------------------
+GUIFactory* rgl::getGUIFactory(bool useNULLDevice)
+{
+  if (useNULLDevice)
+    return (GUIFactory*) gpNULLGUIFactory;
+  else if (gpWin32GUIFactory)
+    return (GUIFactory*) gpWin32GUIFactory;
+  else
+    error("wgl device not initialized");
+}
+// ---------------------------------------------------------------------------
+const char * rgl::GUIFactoryName(bool useNULLDevice)
+{
+  return useNULLDevice ? "null" : "wgl";
+}
+// ---------------------------------------------------------------------------
+// printMessage
+// ---------------------------------------------------------------------------
+void rgl::printMessage( const char* string ) {
+  warning("RGL: %s\n", string);
+}
+// ---------------------------------------------------------------------------
+// getTime
+// ---------------------------------------------------------------------------
+double rgl::getTime() {
+  return ( (double) ::GetTickCount() ) * ( 1.0 / 1000.0 );
+}
+// ---------------------------------------------------------------------------
+// init
+// ---------------------------------------------------------------------------
+bool rgl::init(bool useNULLDevice)
+{
+  if (!useNULLDevice)
+    gpWin32GUIFactory = new Win32GUIFactory();  
+  gpNULLGUIFactory = new NULLGUIFactory();
+  return true;
+}
+// ---------------------------------------------------------------------------
+// quit
+// ---------------------------------------------------------------------------
+void rgl::quit()
+{
+  assert(gpWin32GUIFactory != NULL && gpNULLGUIFactory != NULL);
+  delete gpWin32GUIFactory;
+  delete gpNULLGUIFactory;
+  gpWin32GUIFactory = NULL;
+  gpNULLGUIFactory = NULL;
+}
+// ---------------------------------------------------------------------------
+#endif // RGL_W32
+
diff --git a/src/x11gui.cpp b/src/x11gui.cpp
new file mode 100644
index 0000000..deb96b1
--- /dev/null
+++ b/src/x11gui.cpp
@@ -0,0 +1,703 @@
+#include "config.h"
+#ifdef RGL_X11
+// ---------------------------------------------------------------------------
+// C++ source
+// This file is part of RGL.
+//
+// $Id: x11gui.cpp 1197 2014-12-20 19:07:08Z murdoch $
+
+// Uncomment for verbose output on stderr:
+// #define RGL_X11_DEBUG
+
+// ---------------------------------------------------------------------------
+#include <X11/keysym.h>
+#include <cstdio>
+#include <Rinternals.h>
+#include "x11gui.h"
+#include "lib.h"
+#include "R.h"
+
+namespace rgl {
+
+// ---------------------------------------------------------------------------
+extern SEXP    rglNamespace;    
+// ---------------------------------------------------------------------------
+
+class X11WindowImpl : public WindowImpl
+{
+public:
+  X11WindowImpl(rgl::Window* in_window
+  , X11GUIFactory* in_factory
+  , ::Window in_xwindow
+  , XVisualInfo* invisualinfo
+  );
+  virtual ~X11WindowImpl();
+  void setTitle(const char* title);
+  void setWindowRect(int left, int top, int right, int bottom);
+  void getWindowRect(int *left, int *top, int *right, int *bottom);
+  void show();
+  void hide();
+  void bringToTop(int stay);
+  void update();
+  void destroy();
+  bool beginGL();
+  void endGL();
+  void swap();
+  void captureMouse(View* captureview);
+  void releaseMouse();
+  GLFont* getFont(const char* family, int style, double cex, 
+                  bool useFreeType);
+
+private:
+  void initGL();
+  GLBitmapFont* initGLFont();
+  void shutdownGL();
+  static int translate_key(KeySym keysym);
+  void on_init();
+  void on_shutdown();
+  void on_paint();
+  void processEvent(XEvent& ev); 
+  X11GUIFactory* factory;
+  ::Window       xwindow;
+  ::GLXContext   glxctx;
+  friend class X11GUIFactory;
+  XVisualInfo* xvisualinfo;
+};
+
+} // namespace rgl
+
+using namespace rgl;
+// ---------------------------------------------------------------------------
+// X11WindowImpl Implementation
+// ---------------------------------------------------------------------------
+X11WindowImpl::X11WindowImpl(Window* w, X11GUIFactory* f, ::Window in_xwindow, XVisualInfo* invisualinfo)
+: WindowImpl(w)
+, factory(f)
+, xwindow(in_xwindow)
+, xvisualinfo(invisualinfo)
+{
+  on_init();
+}
+// ---------------------------------------------------------------------------
+X11WindowImpl::~X11WindowImpl()
+{
+  if (xwindow != 0)
+    destroy();
+  // free XVisualInfo structure
+  if (xvisualinfo) {
+    XFree(xvisualinfo);
+    xvisualinfo = 0;
+  }    
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::setTitle(const char* title)
+{
+  XStoreName(factory->xdisplay,xwindow,title);
+  factory->flushX();
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::setWindowRect(int left, int top, int right, int bottom) 
+{
+  ::Window root, child, parent, *children;
+  int x, y;
+  unsigned int nchildren;
+  XQueryTree(factory->xdisplay, xwindow, &root, &parent, &children, &nchildren);
+  XTranslateCoordinates(factory->xdisplay, xwindow, parent, 0, 0, &x, &y, &child);
+  // The weird calculation below (subtracting twice (x,y)) compensates for the diff
+  // between coordinates of the rgl window within the parent window.
+  // There's probably a smarter way to do this...
+  XMoveWindow(factory->xdisplay, xwindow, left-2*x, top-2*y);
+  XResizeWindow(factory->xdisplay, xwindow, right-left, bottom-top);
+  factory->flushX();
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::getWindowRect(int *left, int *top, int *right, int *bottom)
+{
+  ::Window root, child;
+  int x, y;
+  unsigned int width, height, border_width, depth;
+  do {
+    factory->flushX();
+    factory->processEvents();
+  } while (XEventsQueued(factory->xdisplay, QueuedAfterFlush));
+  XGetGeometry(factory->xdisplay, xwindow, &root, &x, &y, &width, &height, &border_width, &depth);
+  XTranslateCoordinates(factory->xdisplay, xwindow, root, x, y, left, top, &child);
+  XTranslateCoordinates(factory->xdisplay, xwindow, root, x+width, y+height, right, bottom, &child);
+}
+
+// ---------------------------------------------------------------------------
+static Bool IsMapNotify(Display* d, XEvent* ev, XPointer arg)
+{
+  ::Window w = (::Window) arg;
+  return ( (ev->xany.window == w) && (ev->type == MapNotify) );
+}
+void X11WindowImpl::show()
+{
+  XMapWindow(factory->xdisplay, xwindow);
+  XEvent ev;
+  XIfEvent(factory->xdisplay, &ev, IsMapNotify, (XPointer) xwindow );
+  factory->processEvents();
+  factory->flushX();
+  update();
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::hide()
+{
+  XUnmapWindow(factory->xdisplay, xwindow);
+  factory->flushX();
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::bringToTop(int stay)
+{
+  XRaiseWindow(factory->xdisplay, xwindow);
+  factory->processEvents();
+  factory->flushX();
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::on_paint()
+{
+  if (window) {
+    if (window->skipRedraw) return;
+    window->paint();
+    SAVEGLERROR;
+  }  
+  swap();
+  SAVEGLERROR;
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::update()
+{
+  on_paint();
+  SAVEGLERROR;
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::destroy()
+{
+  if (xwindow != 0) 
+  {
+    on_shutdown();
+    XDestroyWindow(factory->xdisplay, xwindow);
+    factory->flushX();
+    factory->notifyDelete(xwindow); /* Why didn't this happen in the lines above, from the DestroyNotify event? */
+    xwindow = 0;
+    if (window)
+        window->notifyDestroy();
+    delete this;
+  }
+}
+// ---------------------------------------------------------------------------
+bool X11WindowImpl::beginGL()
+{
+    if ( glXMakeCurrent(factory->xdisplay, xwindow, glxctx) == False ) {
+      printMessage("ERROR: can't bind glx context to window");
+      return false;
+    }
+    else return true;
+
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::endGL()
+{
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::swap()
+{
+  glXSwapBuffers(factory->xdisplay, xwindow);
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::captureMouse(View* captureview)
+{
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::releaseMouse()
+{
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::processEvent(XEvent& ev)
+{
+  char   keybuffer[8];
+  KeySym keysym;
+  XComposeStatus compose;
+  int    keycode;
+  ::Window root, child;
+  int    rootx, rooty, winx, winy;
+  unsigned int  mask;
+  
+  switch(ev.type) {
+    case ButtonPress:
+      switch(ev.xbutton.button) {
+        case 1:
+          if (window)
+            window->buttonPress( GUI_ButtonLeft, ev.xbutton.x, ev.xbutton.y );
+          break;
+        case 2:
+          if (window)
+            window->buttonPress( GUI_ButtonMiddle, ev.xbutton.x, ev.xbutton.y );
+          break;
+        case 3:
+          if (window)
+            window->buttonPress( GUI_ButtonRight, ev.xbutton.x, ev.xbutton.y );
+          break;
+        case 4:
+          if (window)
+            window->wheelRotate( GUI_WheelForward );
+          break;
+        case 5:
+          if (window)
+            window->wheelRotate( GUI_WheelBackward );
+          break;
+      }
+      break;
+    case ButtonRelease:
+      switch(ev.xbutton.button) {
+        case 1:
+          if (window)
+            window->buttonRelease( GUI_ButtonLeft, ev.xbutton.x, ev.xbutton.y );
+          break;
+        case 2:
+          if (window)
+            window->buttonRelease( GUI_ButtonMiddle, ev.xbutton.x, ev.xbutton.y );
+          break;
+        case 3:
+          if (window)
+            window->buttonRelease( GUI_ButtonRight, ev.xbutton.x, ev.xbutton.y );
+          break;
+      }
+      break;
+    case KeyPress:
+      XLookupString(&ev.xkey, keybuffer, sizeof(keybuffer), &keysym, &compose);
+      keycode = translate_key(keysym);
+      if (keycode)
+        if (window)
+          window->keyPress(keycode);
+      break;
+    case KeyRelease:
+      XLookupString(&ev.xkey, keybuffer, sizeof(keybuffer), &keysym, &compose);
+      keycode = translate_key(keysym);
+      if (keycode)
+        if (window)
+          window->keyRelease(keycode);
+      break;
+    case MappingNotify:
+      XRefreshKeyboardMapping(&ev.xmapping);
+      break;
+    case MotionNotify:
+      if( XQueryPointer(factory->xdisplay, xwindow, &root, &child, &rootx, &rooty, &winx, &winy, &mask) == True )
+        if (window)
+          window->mouseMove( winx, winy );
+      break;
+    case Expose:
+      if (ev.xexpose.count == 0) {
+        if (window) {
+          if (window->skipRedraw) break;
+          window->paint();
+        }  
+        swap();
+      }
+      break;
+    case ConfigureNotify:
+      if (window)
+        window->resize( ev.xconfigure.width, ev.xconfigure.height );
+      break;
+    case MapNotify:
+      if (window)
+        window->show();
+      break;
+    case UnmapNotify:
+      if (window)
+        window->hide();
+      break;
+    case ClientMessage:
+      if ( ( (::Atom) ev.xclient.data.l[0] ) == factory->atoms[GUI_X11_ATOM_WM_DELETE])
+        if (window)
+          window->on_close();
+      break;
+    case DestroyNotify:
+      factory->notifyDelete(xwindow);
+      xwindow = 0;
+      if (window)
+        window->notifyDestroy();
+      delete this;
+      break;
+  }
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::initGL()
+{  
+  glxctx = glXCreateContext(factory->xdisplay, xvisualinfo, NULL, True);
+  if (!glxctx)
+    factory->throw_error("unable to create GLX Context"); 
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::shutdownGL()
+{
+  // destroy GL context
+  
+  if (glxctx) {
+    glXMakeCurrent(factory->xdisplay, None, NULL);
+    glXDestroyContext(factory->xdisplay, glxctx);
+    glxctx = NULL;
+  }
+}
+// ---------------------------------------------------------------------------
+GLFont* X11WindowImpl::getFont(const char* family, int style, double cex, 
+                                 bool useFreeType)
+{
+  for (unsigned int i=0; i < fonts.size(); i++) {
+    if (fonts[i]->cex == cex && fonts[i]->style == style && !strcmp(fonts[i]->family, family)
+     && fonts[i]->useFreeType == useFreeType)
+      return fonts[i];
+  }
+  
+  if (useFreeType) {
+#ifdef HAVE_FREETYPE
+    SEXP Rfontname = VECTOR_ELT(PROTECT(eval(lang2(install("rglFonts"), 
+                                          ScalarString(mkChar(family))), rglNamespace)),
+                                          0);
+    if (isString(Rfontname) && length(Rfontname) >= style) {
+      const char* fontname = CHAR(STRING_ELT(Rfontname, style-1)); 
+      GLFTFont* font=new GLFTFont(family, style, cex, fontname);
+      if (font->font) {
+        fonts.push_back(font);
+        UNPROTECT(1);
+        return font;
+      } else {
+        warning(font->errmsg);
+        delete font;
+      }
+    }
+    UNPROTECT(1);
+#endif
+  }
+  if (strcmp(family, fonts[0]->family)) warning("font family \"%s\" not found, using \"%s\"", 
+                                         family, fonts[0]->family);
+  else if (style != fonts[0]->style) warning("\"%s\" family only supports font %d", 
+                                        fonts[0]->family, fonts[0]->style);
+  else if (cex != fonts[0]->cex) warning("\"%s\" family only supports cex = %g",
+  					fonts[0]->family, fonts[0]->cex);
+  else if (useFreeType) warning("FreeType font not available");
+  return fonts[0];
+}
+
+GLBitmapFont* X11WindowImpl::initGLFont()
+{
+  GLBitmapFont* font = NULL; 
+  if (beginGL()) {
+    font = new GLBitmapFont("bitmap", 1, 1, "fixed");  
+    font->nglyph     = GL_BITMAP_FONT_COUNT;
+    font->firstGlyph = GL_BITMAP_FONT_FIRST_GLYPH;
+    GLuint listBase = glGenLists(font->nglyph);
+    font->listBase   = listBase - font->firstGlyph;
+    glXUseXFont(factory->xfont->fid, font->firstGlyph, font->nglyph, listBase);
+
+    font->widths = new unsigned int[font->nglyph];
+
+    for(unsigned int i=0;i<font->nglyph;i++)
+      font->widths[i] = 9;
+    font->ascent = factory->xfont->ascent;
+    endGL();  // Should this be added?
+  }
+  return font;
+}
+// ---------------------------------------------------------------------------
+void X11WindowImpl::on_init()
+{
+  initGL();
+  fonts[0] = initGLFont();
+}
+
+void X11WindowImpl::on_shutdown()
+{
+  shutdownGL();
+}
+// ---------------------------------------------------------------------------
+//
+// FUNCTION
+//   translate_key
+//
+// translates X11 KeySym keycode to GUI_Key code
+//
+// ---------------------------------------------------------------------------
+int X11WindowImpl::translate_key(KeySym keysym)
+{
+  if ( (keysym >= XK_space) && (keysym <= XK_asciitilde) )
+    return (int) keysym;
+  else if ((keysym >= XK_F1) && (keysym <= XK_F12))
+    return GUI_KeyF1 + keysym - XK_F1;
+  else {
+    switch(keysym)
+    {
+      case XK_Return:
+        return GUI_KeyReturn;
+      case XK_Escape:
+        return GUI_KeyESC;
+      default:
+        return 0;
+    }
+  }
+    
+}
+
+// ---------------------------------------------------------------------------
+// X11GUIFactory Implementation
+// ---------------------------------------------------------------------------
+// throw error
+// ---------------------------------------------------------------------------
+void X11GUIFactory::throw_error(const char* string)
+{
+  printMessage(string);
+  disconnect();
+}
+// ---------------------------------------------------------------------------
+// ---------------------------------------------------------------------------
+static int error_code; 
+
+static void ConvertError(Display *dsp)
+{
+  char buff[1000];
+  XGetErrorText(dsp, error_code, buff, 1000);
+  error("X11 protocol error: %s", buff);
+}
+
+static int X11SaveErr(Display *dsp, XErrorEvent *event)
+{
+  error_code = event->error_code;
+  return 0;
+}
+
+X11GUIFactory::X11GUIFactory(const char* displayname)
+: xdisplay(0)
+, xfont(0)
+{
+  // Open one display connection for all RGL X11 devices
+  xdisplay = XOpenDisplay(displayname);
+  if (xdisplay == 0) {
+    throw_error("unable to open X11 display"); return;
+  }
+/*  XSynchronize(xdisplay, True); */
+
+  // Load System font
+  xfont = XLoadQueryFont(xdisplay,"fixed");
+ 
+  // Obtain display atoms
+  static char* atom_names[GUI_X11_ATOM_LAST] = {
+    const_cast<char*>("WM_DELETE_WINDOW")
+  };
+  Status s = XInternAtoms(xdisplay, atom_names, sizeof(atom_names)/sizeof(char*), True, atoms);
+
+  if (!s)
+    printMessage("some atoms not available");
+ 
+  // Query glx extension
+   
+  if ( glXQueryExtension(xdisplay, &errorBase, &eventBase) == False ) {
+    throw_error("GLX extension missing on server"); return;
+  }
+  
+}
+// ---------------------------------------------------------------------------
+X11GUIFactory::~X11GUIFactory()
+{
+  disconnect();
+}
+// ---------------------------------------------------------------------------
+void X11GUIFactory::disconnect()
+{
+  // process pending XDestroyNotify events
+  if (xdisplay) {
+    XSync(xdisplay, False);
+    processEvents();
+  }
+
+  // free xfont
+  if (xfont) {
+    XUnloadFont(xdisplay, xfont->fid);
+    xfont = 0;
+  }
+  
+  // disconnect from X server
+  if (xdisplay) {
+    XCloseDisplay(xdisplay);
+    xdisplay = 0;
+  }
+}
+// ---------------------------------------------------------------------------
+void X11GUIFactory::flushX()
+{
+  XSync(xdisplay, False);
+  glXWaitX();
+}
+// ---------------------------------------------------------------------------
+void X11GUIFactory::processEvents()
+{
+  for(;;) {
+    int nevents = XEventsQueued(xdisplay, QueuedAfterReading);
+
+    if (nevents == 0)
+      return;
+    
+    while(nevents--) {
+      
+      XEvent ev;
+      XNextEvent(xdisplay,&ev);
+
+      X11WindowImpl* impl = windowMap[ev.xany.window];
+
+      if (impl)
+        impl->processEvent(ev);
+#ifdef RGL_X11_DEBUG
+      else
+        fprintf(stderr,"unknown window id %lx(code %lx)\n"
+        , static_cast<long>(ev.xany.window)
+        , static_cast<long>(ev.type) 
+        );
+#endif        
+    }
+  } 
+}
+// ---------------------------------------------------------------------------
+WindowImpl* X11GUIFactory::createWindowImpl(Window* window)
+{
+  X11WindowImpl* impl = NULL;
+  XVisualInfo* xvisualinfo;
+
+  // Choose GLX visual
+  
+  static int attribList[] =
+  {
+    GLX_RGBA,
+    GLX_DOUBLEBUFFER,
+    GLX_RED_SIZE, 1,
+    GLX_GREEN_SIZE, 1,
+    GLX_BLUE_SIZE, 1,
+    GLX_ALPHA_SIZE, 0,
+    GLX_DEPTH_SIZE, 1,
+    None, None, // Space for optional AA settings
+    None, None,
+    None
+  };
+
+#ifdef GLX_SAMPLE_BUFFERS
+  // Setup antialiasing based on "rgl.antialias" option
+  int aa;
+  SEXP rgl_aa = GetOption(install("rgl.antialias"),R_BaseEnv);
+  if (isNull(rgl_aa)) aa = RGL_ANTIALIAS;
+  else aa = asInteger(rgl_aa);
+  
+  if(aa > 0) {
+    attribList[12] = GLX_SAMPLE_BUFFERS;
+    attribList[13] = 1;
+    attribList[14] = GLX_SAMPLES;
+    attribList[15] = aa;
+  }
+#endif
+
+  xvisualinfo = glXChooseVisual( xdisplay, DefaultScreen(xdisplay), attribList );
+#ifdef GLX_SAMPLE_BUFFERS
+  // Try to set up visual without MSAA if it failed
+  if (xvisualinfo == 0 && aa > 0) {
+    attribList[12] = None;
+    xvisualinfo = glXChooseVisual( xdisplay, DefaultScreen(xdisplay), attribList );
+  }
+#endif
+  if (xvisualinfo == 0) {
+    throw_error("no suitable visual available"); 
+  }
+    
+  // create X11 window
+
+  // We don't want a border, but MacOSX Xvfb requires one.  
+  unsigned long valuemask=CWEventMask|CWColormap|CWBorderPixel;
+    
+  XSetWindowAttributes attrib;
+  XErrorHandler old_handler;
+  
+  attrib.event_mask = 
+      ButtonMotionMask 
+    | PointerMotionHintMask
+    | VisibilityChangeMask 
+    | ExposureMask
+    | StructureNotifyMask 
+    | ButtonPressMask 
+    | KeyPressMask
+    | KeyReleaseMask
+    | ButtonReleaseMask;
+
+
+  ::Window xparent = RootWindow(xdisplay, DefaultScreen(xdisplay));
+
+  attrib.colormap = XCreateColormap(xdisplay, xparent, xvisualinfo->visual, AllocNone);
+  attrib.border_pixel = 0;
+  
+  /* Work around problems with Xvfb on MacOSX:  temporarily catch protocol errors and convert
+     to R errors */
+  error_code = 0;
+  old_handler = XSetErrorHandler(X11SaveErr);
+  
+  ::Window xwindow = XCreateWindow(
+    xdisplay, xparent,
+    0, 0, 256, 256, 0, 
+    xvisualinfo->depth,
+    InputOutput,
+    xvisualinfo->visual, 
+    valuemask,
+    &attrib
+  );
+  XSync(xdisplay, False);
+
+  /* set WM_CLASS on window */
+  XClassHint *classHint = XAllocClassHint();
+  if (classHint) {
+      classHint->res_name = const_cast<char*>("rgl");
+      classHint->res_class = const_cast<char*>("R_x11");
+      XSetClassHint(xdisplay, xwindow, classHint);
+      XFree(classHint);
+  }
+
+  XSetErrorHandler(old_handler);
+  
+  if (error_code) ConvertError(xdisplay);  /* will not return */
+  
+  if (!xwindow)
+    return NULL;
+
+  // set window manager protocols
+
+  int n = 0;
+
+  ::Atom proto_atoms[GUI_X11_ATOM_LAST];
+  
+  if (atoms[GUI_X11_ATOM_WM_DELETE]) {
+    proto_atoms[n] = atoms[GUI_X11_ATOM_WM_DELETE];
+    n++;
+  }
+  
+  if (n)
+    XSetWMProtocols(xdisplay,xwindow,proto_atoms,n);
+
+  // create window implementation instance
+  
+  impl = new X11WindowImpl(window, this, xwindow, xvisualinfo);
+
+  // register instance
+  
+  windowMap[xwindow] = impl;
+  
+  // flush X requests
+  
+  flushX();
+  
+  return (WindowImpl*) impl;
+}
+// ---------------------------------------------------------------------------
+void X11GUIFactory::notifyDelete(::Window xwindowid)
+{
+#ifdef RGL_X11_DEBUG
+  fprintf(stderr,"notifyDelete %lx\n", xwindowid);
+#endif
+  // remove window from map
+  windowMap.erase(xwindowid);
+}
+// ---------------------------------------------------------------------------
+#endif // RGL_X11_H
+
diff --git a/src/x11gui.h b/src/x11gui.h
new file mode 100644
index 0000000..66567b4
--- /dev/null
+++ b/src/x11gui.h
@@ -0,0 +1,68 @@
+#ifndef X11_GUI_H
+#define X11_GUI_H
+// ---------------------------------------------------------------------------
+// C++ header file
+// This file is part of RGL
+//
+// $Id: x11gui.h 1115 2014-07-18 13:51:22Z murdoch $
+// ---------------------------------------------------------------------------
+#include <X11/Xlib.h>
+#include <GL/glx.h>
+#include <map>
+#include "gui.h"
+
+namespace rgl {
+
+// ---------------------------------------------------------------------------
+class X11WindowImpl;
+enum {
+  GUI_X11_ATOM_WM_DELETE = 0,
+  GUI_X11_ATOM_LAST
+};
+// ---------------------------------------------------------------------------
+class X11GUIFactory : public GUIFactory
+{
+public:
+  X11GUIFactory (const char* displayname);
+  virtual ~X11GUIFactory ();
+  WindowImpl* createWindowImpl(Window* window);
+  inline bool isConnected() { return (xdisplay) ? true : false; }
+  inline int  getFD()     { return ConnectionNumber(xdisplay); }
+  
+  void notifyDelete(::Window xwindowid);
+  
+  // implementation services:
+  
+  void processEvents();
+  void flushX();
+  
+  // display specific:
+  
+  Display* xdisplay;
+  
+  ::Atom atoms[GUI_X11_ATOM_LAST];
+  
+  // GLX specific
+  int errorBase, eventBase;
+  
+  // Font specific
+  XFontStruct* xfont;
+  
+  void throw_error(const char* string);
+private:
+
+  void connect(const char* displayname);
+  void disconnect();
+
+  // administrative data:
+
+  typedef std::map< XID , X11WindowImpl*> WindowMap;
+  
+  WindowMap windowMap;
+};
+// ---------------------------------------------------------------------------
+
+} // namespace rgl
+
+#endif // X11_GUI_H
+
diff --git a/src/x11lib.cpp b/src/x11lib.cpp
new file mode 100644
index 0000000..a278b93
--- /dev/null
+++ b/src/x11lib.cpp
@@ -0,0 +1,138 @@
+#include "config.h"
+#ifdef RGL_X11
+// C++ source
+// This file is part of RGL.
+//
+// $Id: x11lib.cpp 1115 2014-07-18 13:51:22Z murdoch $
+
+#include "R.h"
+#include "lib.h"
+
+#include "NULLgui.h"
+//
+// ===[ GUI IMPLEMENTATION ]=================================================
+//
+
+#include "x11gui.h"
+
+using namespace rgl;
+
+namespace rgl {
+X11GUIFactory* gpX11GUIFactory = NULL;
+NULLGUIFactory* gpNULLGUIFactory = NULL;
+}
+
+GUIFactory* rgl::getGUIFactory(bool useNULLDevice)
+{
+  if (useNULLDevice)
+    return (GUIFactory*) gpNULLGUIFactory;
+  else if (gpX11GUIFactory)
+    return (GUIFactory*) gpX11GUIFactory;
+  else
+    error("glX device not initialized");  
+}
+// ---------------------------------------------------------------------------
+const char * rgl::GUIFactoryName(bool useNULLDevice)
+{
+  return useNULLDevice ? "null" : "glX";
+}
+
+//
+// ===[ R INTEGRATION ]=======================================================
+//
+
+#include "R.h"
+#include <R_ext/eventloop.h>
+
+static InputHandler* R_handler = NULL;
+
+static void R_rgl_eventHandler(void * userData)
+{
+  gpX11GUIFactory->processEvents();
+}
+
+static void set_R_handler()
+{
+  // add R input handler (R_ext/eventloop.h)
+  // approach taken from GtkDevice ... good work guys!
+  
+  R_handler = ::addInputHandler(R_InputHandlers, gpX11GUIFactory->getFD(), R_rgl_eventHandler, XActivity);
+
+  // seek end of node
+  
+  while(R_handler->next)
+    R_handler = R_handler->next;
+}
+
+static void unset_R_handler()
+{
+  if (R_handler) {
+    ::removeInputHandler(&R_InputHandlers, R_handler);
+    R_handler = NULL;
+  }
+}
+
+//
+// ===[ LIB INIT / QUIT ]=====================================================
+//
+
+bool rgl::init(bool useNULLDevice)
+{
+  bool success = false;
+
+  // construct GUI Factory
+  
+  gpNULLGUIFactory = new NULLGUIFactory();
+ 
+  if (useNULLDevice) {
+    success = true;
+  } else {
+    gpX11GUIFactory = new X11GUIFactory(NULL);
+    if ( gpX11GUIFactory->isConnected() ) {
+      set_R_handler();
+      success = true;
+    }
+  }
+  return success;
+}
+
+void rgl::quit()
+{
+  unset_R_handler();
+  delete gpX11GUIFactory;
+  delete gpNULLGUIFactory;
+  gpX11GUIFactory = 0;
+  gpNULLGUIFactory = 0;
+}
+
+//
+// ===[ LIB SERVICES ]=======================================================
+//
+
+//
+// printMessage
+//
+
+void rgl::printMessage( const char* string ) {
+  warning("RGL: %s\n", string);
+}
+
+//
+// getTime
+//
+
+#include <sys/time.h>
+#include <unistd.h>
+
+double rgl::getTime() {
+  struct ::timeval t;
+  gettimeofday(&t,NULL);
+  return ( (double) t.tv_sec ) * 1000.0 + ( ( (double) t.tv_usec ) / 1000.0 ); 
+}
+
+// ---------------------------------------------------------------------------
+
+
+
+#endif // RGL_X11
+
diff --git a/tests/demos.R b/tests/demos.R
new file mode 100644
index 0000000..dd0da19
--- /dev/null
+++ b/tests/demos.R
@@ -0,0 +1,8 @@
+library(rgl)
+
+# regression :  this failed for headless tests
+par3d(userMatrix = diag(4))
+
+for(demo in demo(package="rgl")$results[,"Item"]) 
+  if (!(demo %in% c("rgl", "lsystem")))
+    demo(demo, package="rgl", character.only=TRUE)
diff --git a/vignettes/WebGL.Rmd b/vignettes/WebGL.Rmd
new file mode 100644
index 0000000..07367b2
--- /dev/null
+++ b/vignettes/WebGL.Rmd
@@ -0,0 +1,434 @@
+---
+title: "User Interaction in WebGL"
+author: "Duncan Murdoch"
+date: "`r format(Sys.time(), '%B %d, %Y')`"
+output:
+  rmarkdown::html_vignette:
+    toc: yes
+    fig_width: 5
+    fig_height: 5
+vignette: >
+  %\VignetteIndexEntry{User Interaction in WebGL} 
+  %\VignetteEngine{knitr::rmarkdown}
+---
+
+
+```{r setup, echo=FALSE, results="asis"}
+source("setup.R")
+set.seed(123)
+```
+
+## Introduction
+
+This document describes how to embed `rgl` scenes in HTML documents
+and use embedded Javascript to 
+control a WebGL display in an HTML document.  For more 
+general information, see [rgl Overview](rgl.html).
+
+We assume that the HTML document is produced from R markdown
+source using `knitr` or `rmarkdown`.  This format mixes
+text with Markdown markup with chunks of R code.
+
+There are two ways to embed an `rgl` scene in the document.  The
+older one is to use the chunk option `webgl = TRUE`.  With that
+option, whatever `rgl` scene is active at the end of the chunk
+will be embedded.  See the `r linkfn("setupKnitr", pkg="rgl")` 
+help page for chunk options.  
+
+The second way is to use a call to `r linkfn("rglwidget",
+pkg="rglwidget")` from the `rglwidget` package.  Each call to
+this function will insert a scene into the document.  Do not set
+`webgl = TRUE`.  
+
+## Browser support
+
+Most browsers now support WebGL, but it may be disabled by
+default.  See http://get.webgl.org for help on a number of
+different browsers.  
+
+If you are using the internal browser in RStudio, support varies
+by version.  I believe it is enabled by default in Windows
+versions, but not in all Mac OSX versions.  You can run this
+command:
+ 
+    defaults write org.rstudio.RStudio WebKitWebGLEnabled -bool YES
+
+to enable it.  I do not have much experience with RStudio in
+Linux, but it does seem that WebGL is enabled there.
+
+
+Both methods make use of functions from the `rglwidget` package,
+so you will need to install it.  The second method is easier for
+me to maintain, so it is likely to receive more support in the 
+future, but for now both methods are supported, and there
+are examples of both in this document.
+
+## Examples
+
+We start with two simple examples.  The next section gives 
+reference information.
+
+Consider the simple plot of the iris data.  We
+insert a code chunk and call the `r linkfn("rglwidget",pkg="rglwidget")` 
+function with optional argument `elementId`.  This allows later
+Javascript code to refer to the image.
+```{r plot3d}
+library(rgl)
+library(rglwidget)
+with(iris, plot3d(Sepal.Length, Sepal.Width, Petal.Length, 
+                  type="s", col=as.numeric(Species)))
+subid <- currentSubscene3d()
+rglwidget(elementId="plot3drgl")
+```
+We might like a button on the web page to cause a change to the
+display, e.g. a rotation of the plot.  First we add buttons, with
+the "onclick" event set to a function described below:
+
+    <button type="button" onclick="rotate(10)">Forward</button>
+    <button type="button" onclick="rotate(-10)">Backward</button>
+
+which produces these buttons: 
+<button type="button" onclick="rotate(10)">Forward</button>
+<button type="button" onclick="rotate(-10)">Backward</button>
+
+We stored the subscene number that is currently active in
+`subid` in the code chunk above, and use it as `r rinline("subid")`
+in the script below.  `knitr` substitutes the value
+`r subid` when it processes the document.
+
+The `rotate()` function uses the Javascript function `document.getElementById` to retrieve the `<div>` component
+of the web page containing the scene.  It will have a
+component named `rglinstance` which contains information about the scene that we can modify:
+
+    <script type="text/javascript">
+    var rotate = function(angle) {
+      var rgl = document.getElementById("plot3drgl").rglinstance;
+      rgl.getObj(`r rinline("subid",
+                           script=TRUE)`).par3d.userMatrix.rotate(angle, 0,1,0);
+      rgl.drawScene();
+    };
+    </script>
+    
+<script type="text/javascript">
+var rotate = function(angle) {
+  var rgl = document.getElementById("plot3drgl").rglinstance;
+  rgl.getObj(`r subid`).par3d.userMatrix.rotate(angle, 0,1,0);
+  rgl.drawScene();
+};
+</script>
+
+If we had used `webGL=TRUE` in the chunk header,
+the `knitr` WebGL support create a global object with a name of the form `<chunkname>rgl`.  For example,  if the code chunk
+was named `plot3d`, the object
+would be called `plot3drgl`, and this code would work:
+
+    <script type="text/javascript">
+    var rotate = function(angle) {
+      plot3drgl.getObj(`r rinline("subid",
+                           script=TRUE)`).par3d.userMatrix.rotate(angle, 0,1,0);
+      plot3drgl.drawScene();
+    };
+    </script>
+    
+
+## Autogenerated controls
+
+We can also change the contents of the plot using `r indexfns("toggleButton")`.
+For example, we can redo the previous plot, but with the
+three species as separate "spheres" objects and buttons to
+toggle them:
+```{r toggle, webgl = TRUE, rgl.newwindow = TRUE}
+sphereid <- with(subset(iris, Species == "setosa"), 
+     spheres3d(Sepal.Length, Sepal.Width, Petal.Length, 
+                  col=as.numeric(Species),
+                  radius = 0.211))
+with(subset(iris, Species == "versicolor"), 
+     spheres3d(Sepal.Length, Sepal.Width, Petal.Length, 
+               col=as.numeric(Species),
+     	       radius = 0.211))
+with(subset(iris, Species == "virginica"), 
+     spheres3d(Sepal.Length, Sepal.Width, Petal.Length, 
+               col=as.numeric(Species),
+     	       radius = 0.211))
+aspect3d(1,1,1)
+axesid <- decorate3d()
+subid <- currentSubscene3d()
+```
+
+```{r results="asis"}
+toggleButton(sphereid, label = "setosa", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+1, label = "versicolor", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+2, label = "virginica", prefix = "toggle", subscene = subid)
+```
+
+Note that we need to use `results="asis"` for the button code.  
+Normally we would also use `echo=FALSE`, though I didn't do so above;
+then the buttons will end up side-by-side.  We also add another button
+to toggle the axes:
+
+```{r results="asis", echo=FALSE}
+toggleButton(sphereid, label = "setosa", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+1, label = "versicolor", prefix = "toggle", subscene = subid)
+toggleButton(sphereid+2, label = "virginica", prefix = "toggle", subscene = subid)
+toggleButton(axesid, label="axes", prefix = "toggle", subscene = subid)
+```
+
+An alternate control to achieve the same thing is `r indexfns("subsetSlider")`.  Here we also illustrate the 
+`r indexfns("elementId2Prefix")` bridge to allow an `r indexfns("rglwidget")`
+to be controlled by the old-style slider.
+
+```{r slider}
+rglwidget(elementId = "slider")
+```
+```{r results="asis"}
+elementId2Prefix("slider")
+subsetSlider(subsets = list(setosa = sphereid, 
+                  versicolor = sphereid + 1, 
+                  virginica = sphereid + 2, 
+                  all = sphereid + 0:2),
+             prefixes = "slider", subscenes = subid,
+             init = 3)
+```
+
+There are several other functions to generate the Javascript
+code for controls.  `r indexfns("par3dinterpSetter")` generates
+a function that approximates the result of `r linkfn("par3dinterp")`.
+`r indexfns("propertySetter")` is a more general function to set
+the value of properties of the scene.  Both generate Javascript
+functions, but not the controls to use them; for that, use
+`r indexfns("propertySlider")` or your own custom code.
+
+For example, the following code (similar to the `r linkfn("play3d")`
+example) rotates the scene in a complex way.
+```{r userMatrix, webgl=TRUE}
+```
+```{r results="asis"}
+M <- r3dDefaults$userMatrix
+fn <- par3dinterp(time = (0:2)*0.75, userMatrix = list(M,
+                                     rotate3d(M, pi/2, 1, 0, 0),
+                                     rotate3d(M, pi/2, 0, 1, 0) ) )
+propertySlider(setter = par3dinterpSetter(fn, 0, 1.5, steps=15, 
+					   prefix = "userMatrix", 
+					   subscene = subid),
+	       step = 0.01)
+```
+Some things to note:  The generated Javascript slider has 150 increments,
+so that motion appears smooth.  However, storing 150 `userMatrix` values
+would take up a lot of space, so we use interpolation
+in the Javascript code.  However, the Javascript code can only do 
+linear interpolation, not the more complex spline-based SO(3)
+interpolation done by `r linkfn("par3dinterp")`.  Because of this,
+we need to output 15 steps from `r linkfn("par3dinterpSetter")`
+so that the distortions of linear interpolation are not visible.  
+
+Another function that auto-generates Javascript code is 
+`r indexfns("clipplaneSlider")`.  This function allows the user to control
+the location of a clipping plane by moving a slider.  Both it 
+and `r linkfn("par3dinterpSetter")` are implemented
+using the more general `r indexfns("propertySlider")`, which 
+allows control of multiple objects in multiple scenes, but which 
+does require knowledge of the internal representation of the scene
+in its Javascript implementation.
+
+
+Less general than `r linkfn("propertySetter")` is
+`r indexfns("vertexSetter")`.  This function sets attributes
+of individual vertices in a scene.  For example, to set the
+x-coordinate of the closest point in the setosa group, and modify
+its colour from black to white,
+
+```{r vertex, webgl=TRUE}
+```
+
+```{r results="asis"}
+setosa <- subset(iris, Species == "setosa")
+which <- which.min(setosa$Sepal.Width)
+init <- setosa$Sepal.Length[which]
+propertySlider(
+	vertexSetter(values = matrix(c(init,8,0,1,0,1,0,1), nrow=2),
+	             attributes=c("x", "r", "g", "b"), 
+		     vertices = which, objid = sphereid, 
+		     prefix = "vertex"), 
+	step=0.01)
+```
+	     
+
+A related function is `r indexfns("ageSetter")`, though it uses
+a very different specification of the attributes.
+It is used when the slider controls the "age" of the scene, 
+and attributes of vertices change with their age. 
+
+Rather than giving an example, we will illustrate
+the very similar function `r indexfns("ageControl", pkg = "rglwidget")` from the `rglwidgets` package, embedded in a 
+`r indexfns("playwidget", pkg = "rglwidget")`.  We will
+show a point moving along a curve.  In the original scene
+we need to specify multiple colours so that the
+colour is not fixed, and can be controlled by the slider.  We
+also give two `ageControl` calls in a list;
+
+```{r}
+time <- 0:500
+xyz <- cbind(cos(time/20), sin(time/10), time)
+lineid <- plot3d(xyz, type="l", col = c("black", "black"))["data"]
+sphereid <- spheres3d(xyz[1, , drop=FALSE], radius = 8, col = "red")
+rglwidget(elementId = "ageExample")
+```
+```{r}
+playwidget("ageExample", list(
+  ageControl(births = time, ages = c(0, 0, 50),
+		colors = c("gray", "red", "gray"), objids = lineid),
+	ageControl(births = 0, ages = time,
+		vertices = xyz, objids = sphereid)),
+  start = 0, stop = max(time) + 20, rate = 50,
+  components = c("Reverse", "Play", "Slower", "Faster",
+                 "Reset", "Slider", "Label"),
+  loop = TRUE)
+```
+
+The final function of this type is `r indexfns("matrixSetter")`, for setting
+up multiple controls to modify a matrix, typically `userMatrix`. This is used
+when complex manipulation of a matrix requires several controls.
+
+## User defined mouse controls
+
+`rgl` allows user defined mouse controls.  For these to work
+within WebGL, you will need to write a Javascript version as
+well as the R version.  This isn't easy:  R provides a lot
+of support functions which are not easily available in Javascript.
+
+TODO:  give an example here.
+
+## Reference for `rglClass`
+
+NB:  This section has not been updated recently, and is 
+not current.
+
+In writing the `writeWebGL()` function, I haven't tried to prevent access to 
+anything.  On the other hand, I haven't provided access to
+everything.  The parts documented here should remain relatively stable
+(unless indicated otherwise).  Users may also consult the source
+to `writeWebGL`, but should be aware that anything that isn't documented
+here is subject to change without notice.  
+
+`r indexclass("rglClass")`
+
+As documented in `r linkfn("writeWebGL")`, the call
+```{r eval=FALSE}
+writeWebGL(..., prefix = "<prefix>")
+```
+will create a global object on the output page with name 
+`<prefix>rgl` and Javascript class `rglClass`. 
+This class has a large number of properties and methods, some of which are designed
+to be available for use by other code on the web page. 
+
+Most of the properties are stored as Javascript `Array` objects, indexed
+by the `rgl` id of the subscene to which they apply.  There 
+are also Javascript methods attached to the `rglClass` class.
+
+### Methods
+
+`r indexmethods("drawScene")`
+
+After any change that will affect the display, code should
+call `<prefix>rgl.drawScene()` to redraw the scene.
+
+`r indexmethods(c("inSubscene", "addToSubscene", "delFromSubscene"))`
+
+These methods each take two arguments:  `id` and `subscene`,
+which should be the `rgl` ids of an object and a subscene.
+`inSubscene` tests whether `id` is already included in the 
+subscene, and the others 
+add it or delete it from the subscene.
+
+`r indexmethods(c("getSubsceneEntries"))`
+
+This function takes a subscene id as argument, and returns an `Array`
+containing all of the ids displayed in that subscene.
+
+`r indexmethods(c("setSubsceneEntries"))`
+
+This takes an `Array` of ids and a subscene id as arguments, and sets
+the contents of the subscene to the ids.
+
+### Properties
+
+`r indexproperties(c("FOV", "listeners", "userMatrix", "zoom"))`
+
+These correspond to the 
+`r linkfn("par3d")` properties with the same names.  
+
+- `FOV` and `zoom` are arrays of numbers. 
+- `userMatrix` is an array
+of `CanvasMatrix4` objects (documented in the file 
+`system.file("WebGL/CanvasMatrix.src.js")`.
+- Each `listeners` item is itself an array of subscene ids that "listen"
+to mouse actions, i.e. `listeners[19]` would contain all
+subscene ids that respond to mouse actions in subscene 19.
+
+`r indexproperties("viewport")`
+
+This property also corresponds to the
+`r linkfn("par3d")` property, but should be considered to be 
+read-only.
+
+`r indexproperties(c("drawFns", "clipFns"))`
+
+These two arrays contain the code to display 
+each object in the scene.  The functions in the
+`drawFns` array are called for each object
+each time it is displayed.  The `clipFns` functions
+are called when objects being clipped are drawn.
+
+`r indexproperties(c("values", "offsets"))`
+
+Most of the data about each object in a scene is contained in
+the `values` property.  This is an array, indexed by object
+id. The individual entries are numeric arrays.  Though they
+are singly-indexed, the entries are meant to be interpreted
+as matrices stored by row.  The first 3 columns are generally
+the coordinates of a vertex, and remaining columns correspond
+to other values from `r linkfn("rgl.attrib")`.  
+
+The `offsets` property gives the (0-based) offset of the first 
+column for a particular attribute in a named object.  Not all 
+columns will be present in every object; if not
+present, the corresponding `offsets` entry will be `-1`.
+The entries are
+
+Name | Meaning
+-----|--------
+vofs | Offset to 3 columns of vertex data in XYZ order
+cofs | Offset to 4 columns of colour data in RGBA order
+nofs | Offset to 3 columns of normal data
+radofs | Offset to 1 column of sphere radius data
+oofs | Offset to 2 columns of text or sprite origin data
+tofs | Offset to 2 columns of texture coordinates
+stride | Total number of columns in `values`
+
+For example, to find the blue colour entry for vertex 
+`i` in an object, one would first check if `offsets["cofs"]` was
+`-1`, indicating that no colour information was present.  If
+not, the entry could be found using
+```
+values[offsets["stride"]*(i-1) + offsets["cofs"] + 2]
+```
+This assumes `i` is specified using 1-based vertex counting
+as in R, and writes `values` and `offsets` instead of the
+fully specified `<prefix>rgl.values` and `<prefix>rgl.offsets`
+for clarity.
+
+Changes to `values` need to be pushed to the graphics system
+to be reflected in the scene; see the calls to `gl.bindBuffer` and
+`gl.bufferData` in the source to `r linkfn("propertySlider")`
+for details.
+
+
+## Index 
+
+The following functions and `rglClass` properties and methods are described in this document:<br>
+
+```{r echo=FALSE, results="asis"}
+writeIndex(cols = 5)
+```
+
+
diff --git a/vignettes/rgl.Rmd b/vignettes/rgl.Rmd
new file mode 100644
index 0000000..197d311
--- /dev/null
+++ b/vignettes/rgl.Rmd
@@ -0,0 +1,596 @@
+---
+title: "rgl Overview"
+author: "Duncan Murdoch"
+date: "`r format(Sys.time(), '%B %d, %Y')`"
+output:
+  rmarkdown::html_vignette:
+    toc: yes
+    fig_width: 5
+    fig_height: 5
+vignette: >
+  %\VignetteIndexEntry{rgl Overview} 
+  %\VignetteEngine{knitr::rmarkdown}
+---
+
+```{r setup, echo=FALSE, results="asis"}
+source("setup.R")
+knitr::opts_chunk$set(rgl.newwindow = TRUE)
+set.seed(123)
+```
+
+
+
+## Introduction
+
+The `rgl` package is used to produce interactive 3-D plots.  It contains
+high-level graphics commands modelled loosely after classic R graphics,
+but working in three dimensions.  It also contains low level structure
+inspired by (but incompatible with) the `grid` package.
+
+This document gives an overview.  See the help pages for details.
+
+### About this document
+
+This document was written in R Markdown, using the `knitr` package
+for production.  It corresponds to rgl version 
+`r packageVersion("rgl")`.
+
+Most of the highlighted function names are HTML links.
+The internal links should work in any browser; the links to
+help topics should work if you view the vignette from
+within the R help system.
+
+The document includes WebGL figures.  To view these, you must have
+Javascript and WebGL enabled in your browser.  Some older browsers
+may not support this -- see http://get.webgl.org for tests
+and links to a discussion.
+
+The WebGL figures were produced using the `rglwidget`
+package, version `r packageVersion("rglwidget")`.
+
+
+## Basics and High Level Functions
+
+The `r indexfns("plot3d")` function
+plots points within an rgl window.  It is similar to the classic 
+`r linkfn("plot", pkg="graphics")` function,
+but works in 3 dimensions.
+
+For example
+```{r echo=1}
+with(iris, plot3d(Sepal.Length, Sepal.Width, Petal.Length, 
+                  type="s", col=as.numeric(Species)))
+rglwidget()
+```
+can be used to plot three columns of the `iris` data.  
+Allowed plot types include `"p", "l", "h", "s"`,
+meaning points, lines, segments from z=0, and spheres.  There's
+a lot of flexibility in specifying the coordinates; the 
+`r linkfn("xyz.coords", pkg = "grDevices")` function
+from the `grDevices` package is used for this.
+
+You can use your mouse to manipulate the plot.  The default is that
+if you click and hold with the left mouse button, you can rotate 
+the plot by dragging it.  The right mouse button is used to resize
+it, and the middle button changes the perspective in the point of view.
+
+If you call `r linkfn("plot3d")` again, it will overwrite the current plot.
+To open a new graphics window, use `r linkfn("open3d")`.
+ 
+The other high level function is `r indexfns("persp3d")` to draw surfaces.
+It is
+similar to the classic `r linkfn("persp", pkg = "graphics")`
+function, but with greater flexibility.
+First, any of `x`, `y` or `z`
+can be specified using matrices, not just `z`.  This allows parametric
+surfaces to be plotted. 
+An even simpler specification is possible:  `x` may be a function,
+in which case `persp3d` will work out the grid itself.  See 
+`r linkfn("persp3d.function", text="?persp3d.function", pkg="rgl")`
+for details.  For example, the `MASS` package estimates
+Gamma parameters using maximum likelihood in a 
+`r linkfn("fitdistr", text="?MASS::fitdistr", pkg="MASS")` example.
+Here we show the log likelihood surface. 
+```{r persp3d, webgl=TRUE, fig.height=3, fig.width=6}
+library(MASS)
+# from the fitdistr example
+set.seed(123)
+x <- rgamma(100, shape = 5, rate = 0.1)
+fit <- fitdistr(x, dgamma, list(shape = 1, rate = 0.1), lower = 0.001)
+loglik <- function(shape, rate) sum(dgamma(x, shape=shape, rate=rate, 
+                                           log=TRUE))
+loglik <- Vectorize(loglik)
+xlim <- fit$estimate[1]+4*fit$sd[1]*c(-1,1)
+ylim <- fit$estimate[2]+4*fit$sd[2]*c(-1,1)
+
+mfrow3d(1, 2, sharedMouse = TRUE)
+persp3d(loglik, 
+        xlim = xlim, ylim = ylim,
+        n = 30)
+zlim <- fit$loglik + c(-qchisq(0.99, 2)/2, 0)
+next3d()
+persp3d(loglik, 
+        xlim = xlim, ylim = ylim, zlim = zlim,
+        n = 30)
+```
+ On the left, the whole surface over a range of the parameters; on the right, only the 
+parts of the surface with log likelihood values near the maximum.
+
+Note:  this example used the `knitr` hook functions 
+(see `r linkfn("setupKnitr")`) to insert the
+scene into this vignette; the previous example used the `rglwidget`
+function from the package of the same name.  We generally
+recommend the newer `r linkfn("rglwidget", pkg="rglwidget")` approach.
+
+## Adding Graphical Elements
+
+### Primitive shapes
+
+Just as we have `r linkfn("points", pkg="graphics")` and 
+`r linkfn("lines", pkg="graphics")` in classic graphics, there are a number
+of low level functions in `rgl` to add graphical elements to the
+currently active plot.  The "primitive" shapes are those that are 
+native to OpenGL:
+
+----------------------------- | -----------
+`r indexfns("points3d")`:     | adds points
+`r indexfns("lines3d")`:      | adds lines
+`r indexfns("segments3d")`:   | adds line segments
+`r indexfns("triangles3d")`:  | adds triangles
+`r indexfns("quads3d")`:      | adds quadrilaterals
+
+Each of the above functions takes arguments `x`, `y` and `z`, again
+using `r linkfn("xyz.coords", pkg="grDevices")` for flexibility.
+They group successive entries
+as necessary.  For example, the `r linkfn("triangles3d")` function takes each
+successive triple of points as the vertices of a triangle.
+
+You can use these functions to annotate the current graph, or to 
+construct a figure from scratch.
+
+### Constructed shapes
+
+`rgl` also has a number of objects which it constructs
+from the primitives.
+
+----------------------------- | -----------
+`r indexfns(c("text3d", "texts3d"))`: | adds text
+`r indexfns("abclines3d")`:   | adds straight lines to plot (like `abline`)
+`r indexfns("planes3d")`:     | adds planes to plot
+`r indexfns("clipplanes3d")`: | add clipping planes to plot
+`r indexfns(c("sprites3d", "particles3d"))`: | add sprites (fixed shapes or images) to plot
+`r indexfns("spheres3d")`:    | adds spheres
+`r indexfns(c("surface3d", "terrain3d"))`:    | a surface (as used in `r linkfn("persp3d")`)
+
+### Axes and other "decorations"
+
+The following low-level functions control the look of the graph:
+
+------------------------------------ | -----------
+`r indexfns(c("axes3d", "axis3d"))`: | add axes to plot
+`r indexfns(c("box3d", "bbox3d"))`:               | add box around plot
+`r indexfns("title3d")`:             | add title to plot
+`r indexfns("mtext3d")`:             | add marginal text to plot
+`r indexfns("decorate3d")`:          | add multiple "decorations" (scales, etc.) to plot
+`r indexfns("aspect3d")`:            | set the aspect ratios for the plot
+`r indexfns(c("bg3d", "bgplot3d"))`: | set the background of the scene
+`r indexfns("show2d")`:              | show a 2D plot or image in a 3D scene
+`r indexfns("legend3d")`:            | set a legend for the scene
+`r indexfns("grid3d")`:              | add a reference grid to a graph
+
+For example, to plot three random triangles, one could use
+```{r webgl=TRUE, fig.width=3, fig.height=3}
+triangles3d(cbind(x=rnorm(9), y=rnorm(9), z=rnorm(9)), col = "green")
+decorate3d()
+bg3d("lightgray")
+aspect3d(1,1,1)
+```
+
+Besides the `*3d` functions mentioned above, there are even lower-level
+functions 
+`r indexfns(c("rgl.primitive", "rgl.points", "rgl.linestrips", "rgl.lines", "rgl.triangles",
+"rgl.quads", "rgl.texts", "rgl.abclines", "rgl.planes", "rgl.bg",
+"rgl.clipplanes", "rgl.bbox", "rgl.spheres", "rgl.sprites", "rgl.surface"))`.  
+You should avoid using these functions, which do not
+work well with the higher level `*3d` functions.  See the 
+`r linkfn("r3d", text="?r3d", pkg="rgl")` help
+topic for details.
+
+## Controlling the Look of the Scene
+
+### Lighting
+
+In most scenes, objects are "lit", meaning that their appearance
+depends on their position and orientation relative to lights
+in the scene.  The lights themselves don't normally show up,
+but their effect on the objects does.
+
+Use the `r indexfns("light3d")` function to 
+specify the position and characteristics of a light.
+Lights may be infinitely distant, or may be embedded
+within the scene.  Their characteristics include 
+`ambient`, `diffuse`, and `specular` components, all
+defaulting to white.  The `ambient` component appears
+the same from any direction.  The `diffuse` component 
+depends on the angle between the surface and the light, 
+while the `specular` component also takes the viewer's
+position into account.
+
+The `r indexfns("rgl.light")` function is a lower-level
+function with different defaults; users should normally
+use `r linkfn("light3d")`.
+
+### Materials
+
+The mental model used in `rgl` is that the objects being shown
+in scenes are physical objects in space, with material properties
+that affect how light reflects from them (or is emitted by them).
+These are mainly controlled by the `r indexfns("material3d")` function,
+or by arguments to other functions that are passed to it.
+
+The material properties that can be set by calls to `material3d` are
+described in detail in the 
+`r linkfn("material3d", text="?material3d", pkg="rgl")` help page.
+Here we give an overview.
+
+Property  | Default | Meaning 
+--------- | ------- | ------------------
+color     | white   | vector of surface colors to apply to successive vertices for diffuse light
+alpha     | 1       | transparency:  0 is invisible, 1 is opaque
+lit       | TRUE    | whether lighting calculations should be done
+ambient   | black   | color in ambient  light
+specular  | white   | color in specular light
+emission  | black   | color emitted by the surface
+shininess | 50      | controls the specular lighting:  high values look shiny
+smooth    | TRUE    | whether shading should be interpolated between vertices
+texture   | NULL    | optional path to a "texture" bitmap to be displayed on the surface
+front, back | fill  | should polygons be filled, or outlined? 
+size      | 3       | size of points in pixels
+lwd       | 1       | width of lines in pixels
+
+Other properties include 
+"texmipmap", "texmagfilter", "texminfilter", "texenvmap", "fog", 
+"point\_antialias", "line\_antialias", "depth\_mask", and "depth\_test"; 
+see the help page for details.
+
+There is also an `r indexfns("rgl.material")` function that works
+at a lower level; users should normally avoid it.
+
+### par3d:  Miscellaneous graphical parameters
+
+The `r indexfns("par3d")` function, modelled after the classic
+graphics `r linkfn("par", pkg="graphics")` function, sets or reads 
+a variety of different `rgl` internal
+parameters.  Some parameters are completely read-only; others are
+fixed at the time the window is opened, and others may be changed 
+at any time.
+
+Name        |  Changeable?     | Description
+----------- | ----- | -----------
+antialias   | fixed | Amount of hardware antialiasing 
+cex         |       | Default size for text
+family      |       | Device-independent font family name; see `r linkfn("text3d", text="?text3d", pkg="rgl")`
+font        |       | Integer font number
+useFreeType |       | Should FreeType fonts be used if available?
+fontname    | read-only | System-dependent font name set by `r indexfns("rglFonts")`
+FOV         |       | Field of view, in degrees.  Zero means isometric perspective
+ignoreExtent |      | Should `rgl` ignore the size of new objects when computing the bounding box?
+skipRedraw   |      | Should `rgl` suppress updates to the display? 
+maxClipPlanes | read-only | How many clip planes can be defined?
+modelMatrix | read-only | The OpenGL ModelView matrix; partly set by `r indexfns("view3d")` or the obsolete `r indexfns("rgl.viewpoint")`
+projMatrix  | read-only | The OpenGL Projection matrix
+bbox        | read-only | Current bounding-box of the scene
+viewport    |       | Dimensions in pixels of the scene within the window
+windowRect  |           | Dimensions in pixels of the window on the whole screen
+listeners   |           | Which subscenes respond to mouse actions in the current one
+mouseMode   |       | What the mouse buttons do.  See `r linkfn("mouseMode", '<code>"mouseMode"</code>')`
+observer    | read-only | The position of the observer; set by `r indexfns("observer3d")`
+scale       |           | Rescaling for each coordinate; see `r linkfn("aspect3d")`
+zoom        |           | Magnification of the scene
+
+### Default settings
+
+The `r indexfns("r3dDefaults")` list and the `r indexfns("getr3dDefaults")` 
+function control defaults in new windows opened by `r linkfn("open3d")`.  
+The function looks for the variable in the user's global environment,
+and if not found there, finds the one in the `rgl` namespace.  This
+allows the user to override the default settings for new windows.
+
+Once found, the `r3dDefaults` list provides initial values for `r linkfn("par3d")` parameters, as well as defaults for `r linkfn("material3d")` and `r linkfn("bg3d")` in components `"material"`
+and `"bg"` respectively.
+
+
+## Meshes:  Constructing Shapes 
+
+`rgl` includes a number of functions to construct and display 
+various solid shapes.  These generate objects of class `"shape3d"`,
+`"mesh3d"` or `"shapelist3d"`.  The details of the classes are 
+described below.  We start with functions to generate them.
+
+### Specific solids
+
+These functions generate specific shapes.  Optional arguments allow
+attributes such as colour or transformations to be specified.
+
+------------------------------------ | -----------
+`r indexfns(c("tetrahedron3d", "cube3d", "octahedron3d", "dodecahedron3d", "icosahedron3d"))`: | Platonic solids
+`r indexfns(c("cuboctahedron3d", "oh3d"))`:             | other solids
+
+```{r results="hide",webgl=TRUE}
+open3d()
+cols <- rainbow(7)
+layout3d(matrix(1:16, 4,4), heights=c(1,3,1,3))
+text3d(0,0,0,"tetrahedron3d"); next3d()
+shade3d(tetrahedron3d(col=cols[1])); next3d()
+text3d(0,0,0,"cube3d"); next3d()
+shade3d(cube3d(col=cols[2])); next3d()
+text3d(0,0,0,"octahedron3d"); next3d()
+shade3d(octahedron3d(col=cols[3])); next3d()
+text3d(0,0,0,"dodecahedron3d"); next3d()
+shade3d(dodecahedron3d(col=cols[4])); next3d()
+text3d(0,0,0,"icosahedron3d"); next3d()
+shade3d(icosahedron3d(col=cols[5])); next3d()
+text3d(0,0,0,"cuboctahedron3d"); next3d()
+shade3d(cuboctahedron3d(col=cols[6])); next3d()
+text3d(0,0,0,"oh3d"); next3d()
+shade3d(oh3d(col=cols[7]))
+```
+
+### Generating new shapes 
+
+These functions generate new shapes:
+
+------------------------------------ | -----------
+`r indexfns("cylinder3d")`: | generate a tube or cylinder
+`r indexfns("polygon3d")`:  | generate a flat polygon by triangulation
+`r indexfns("extrude3d")`:  | generate an "extrusion" of a polygon
+`r indexfns("turn3d")`:     | generate a solid of rotation
+`r indexfns("ellipse3d")`:  | generate an ellipsoid in various ways
+`r indexfns(c("tmesh3d", "qmesh3d"))`:  | generate a shape from vertices and faces
+`r indexfns("shapelist3d")`: | generate a shape by combining other shapes
+
+A related function is `r indexfns("triangulate")`, which takes a
+two dimensional polygon and divides it up into triangles using the 
+"ear-clipping" algorithm.
+
+### The underlying class structure for shapes
+
+`"shape3d"` is the basic abstract type.  Objects of this class can be
+displayed by `r indexfns("shade3d")` (which shades faces), 
+`r indexfns("wire3d")` (which draws edges), or `r indexfns("dot3d")`
+(which draws points at each vertex.)  Note that `wire3d` and `dot3d`
+only work within R; in HTML output from `r linkfn("writeWebGL")` only
+`shade3d` is supported.
+
+`"mesh3d"` is a descendant type.  Objects of this type contain the following 
+fields:
+
+Field        | Meaning
+------------ | ---------------
+vb           | A 4 by n matrix of vertices in homogeneous coordinates.  Each column is a point.
+it           | (optional) A 3 by t matrix of vertex indices.  Each column is a triangle.
+ib           | (optional) A 4 by q matrix of vertex indices.  Each column is a quadrilateral.
+material     | (optional) A list of material properties.
+normals      | (optional) A matrix of the same shape as vb, containing normal vectors at each vertex.
+texcoords    | (optional) A 2 by n matrix of texture coordinates corresponding to each vertex.
+
+### Manipulating shapes
+
+The final set of functions manipulate and modify mesh objects:
+
+------------------------------------ | -----------
+`r indexfns("addNormals")`: | add normal vectors to make a shape look smooth
+`r indexfns("subdivision3d")`: | add extra vertices to make it look even smoother
+
+## Multi-figure Layouts
+
+`rgl` has several functions to support displaying multiple different
+"subscenes" in the same window.  The high level functions are
+
+------------------------------------ | -----------
+`r indexfns("mfrow3d")`:  | Multiple figures (like `r linkfn("par", text = 'par("mfrow")', pkg="graphics")`
+`r indexfns("layout3d")`: | Multiple figures (like `r linkfn("layout", pkg="graphics")`)
+`r indexfns("next3d")`:   | Move to the next figure (like `r linkfn("plot.new", pkg="graphics")` or `r linkfn("frame", pkg="graphics")`)
+`r indexfns("subsceneList")`: | List all the subscenes in the current layout
+`r indexfns("clearSubsceneList")` | Clear the current list and revert to the previous one
+
+There are also lower level functions.
+
+------------------------------------ | -----------
+`r indexfns("newSubscene3d")`:     | Create a new subscene, with fine control over what is inherited from the parent
+`r indexfns("currentSubscene3d")`: | Report on the active subscene
+`r indexfns("subsceneInfo")`:      | Get information on current subscene
+`r indexfns("useSubscene3d")`:     | Make a different subscene active
+`r indexfns(c("addToSubscene3d", "delFromSubscene3d"))`: | Add objects to a subscene, or delete them
+`r indexfns("gc3d")`:              | Do "garbage collection":  delete objects that are not displayed in any subscene
+
+
+## Utility Functions
+
+
+### User interaction
+
+By default, `rgl` detects and handles mouse clicks within your scene,
+and uses these to control its appearance.  You can find out the current
+handlers using the following code:
+```{r}
+par3d("mouseMode")
+```
+The labels `c("left", "right", "middle")` refer to the buttons on
+a three button mouse, or simulations of them on other mice.  `"wheel"` 
+refers to the mouse wheel.
+
+The button actions generally correspond to click and drag operations.
+Possible values for `r indexfns("mouseMode", '<code>"mouseMode"</code>')` for buttons or the wheel are as follows:
+
+--------       | ---------
+`"none"`       | No action
+`"trackball"`  | The mouse acts as a virtual trackball. Clicking and dragging rotates the scene
+`"xAxis"`, `"yAxis"`, `"zAxis"`      | Like `"trackball"`, but restricted to rotation about one axis
+`"polar"`      | The mouse affects rotations by controlling polar coordinates directly
+`"selecting"`  | The mouse is being used by the `r linkfn("select3d")` function
+`"zoom"`       | The mouse zooms the display
+`"fov"`        | The mouse affects perspective by changing the field of view
+`"pull"`       | Rotating the mouse wheel towards the user "pulls the scene closer"
+`"push"`       | The same rotation "pushes the scene away"
+`"user"`       | A user action set by `r indexfns(c("rgl.setMouseCallbacks", "rgl.setWheelCallback"))`.  Use `r indexfns("rgl.getMouseCallbacks")` and `r indexfns("rgl.getWheelCallback")` to retrieve
+
+The following functions make use of the mouse for selection within a 
+scene.
+
+---------------------------- | -----------
+`r indexfns("identify3d")`   | like the classic graphics `r linkfn("identify", pkg="graphics")` function
+`r indexfns("select3d")`     | returns a function that tests whether a coordinate was selected
+`r indexfns("selectpoints3d")` | selects from specific objects
+
+The `r indexfns("rgl.select3d")` function is an obsolete version of
+`select3d`, and `r indexfns("rgl.select")` is a low-level support
+function.
+
+### Animations
+
+`rgl` has several functions that can be used to construct
+animations.  These are based on functions that update the
+scene according to the current real-world time, and repeated
+calls to those.  The functions are:
+
+---------------------- | -------------
+`r indexfns("play3d")` | Repeatedly call the update function 
+`r indexfns("spin3d")` | Update the display by rotating at a constant rate
+`r indexfns("par3dinterp")` | Compute new values of some `r linkfn("par3d")` parameters by interpolation over time
+
+See the `r linkfn("movie3d")` function for a way to output an animation
+to a file on disk.  
+Animations are not currently supported 
+in the HTML written by `r linkfn("writeWebGL")`, though the
+`rglwidget::playwidget` function provides equivalent functionality.
+
+### Exporting and importing scenes
+
+`rgl` contains several functions to write scenes to disk for use
+by other software, or to read them in.
+
+In order from highest fidelity to lowest, the functions are:
+
+----------- | -------------
+`r indexfns("scene3d")`    | Save a scene to an R variable, which can be saved and reloaded
+`r indexfns("writeWebGL")` | Write HTML and Javascript to display a scene in a web browser.  (See also [User Interaction in WebGL](WebGL.html).)
+`r indexfns("writePLY")`   | Write PLY files (commonly used in 3D printing)
+`r indexfns(c("readOBJ", "writeOBJ"))`   | Read or write OBJ files (commonly used in 3D graphics)
+`r indexfns(c("readSTL", "writeSTL"))`   | Read or write STL files (also common in 3D printing)
+`r indexfns("rgl.useNULL")`  | A helper function for setting a NULL device
+
+See the help page `r linkfn("rgl.useNULL", pkg="rgl")` for instructions on how
+to use `rgl` on a "headless" system.
+
+There are also functions to save snapshots or other recordings of a scene,
+without any 3D information being saved:
+
+------------ | -------------
+`r indexfns("snapshot3d")` | Save a PNG file bitmap of the scene
+`r indexfns("rgl.postscript")` | Save a Postscript, LaTeX, PDF, SVG or PGF vector rendering of the scene
+`r indexfns("movie3d")`    | Save a series of bitmaps to be assembled into a movie
+`r indexfns("rgl.pixels")` | Obtain pixel-level information about the scene in an R variable
+`r indexfns("rgl.Sweave")` | Driver function for inserting a snapshot into a Sweave document.
+`r indexfns(c("hook_rgl", "hook_webgl"))` | `knitr` hook functions for inserting images into a document.
+`r indexfns("setupKnitr")` | Function to set up `knitr` hooks
+
+The `r indexfns("rgl.snapshot")` function is identical to `snapshot3d`.
+The functions `r indexfns(c("rgl.Sweave.off", "Sweave.snapshot"))` are 
+involved in Sweave processing and not normally called by users.
+
+### Working with WebGL scenes
+
+There are currently two schemes for exporting a scene to a web page.
+Both require the `rglwidget` package and use the same underlying
+code.
+
+The recommended approach works with the `htmlwidgets` framework
+(see http://www.htmlwidgets.org/).  In an R Markdown document
+in `knitr`, use the chunk option `webgl=TRUE`, or the 
+`rglwidget::rglwidget()` function.  More details are given in the vignette 
+[User Interaction in WebGL](WebGL.html).
+
+The older approach uses the `writeWebGL` function to export a scene 
+to HTML and Javascript code.  
+The functions below write HTML and Javascript for working with the 
+exported scene.  
+
+------------------------------------ | -------------
+`r indexfns("propertySlider")`       | insert a slider to make changes to a scene
+`r indexfns("clipplaneSlider")`      | insert a slider to control a clipping plane
+`r indexfns("subsetSlider")`         | insert a slider to control which objects are displayed
+`r indexfns("toggleButton")`         | insert a button to toggle some items
+`r indexfns("propertySetter")`       | function to modify properties
+`r indexfns("subsetSetter")`         | function to choose subsets
+`r indexfns("ageSetter")`            | function to "age" vertices
+`r indexfns("par3dinterpSetter")`    | function like `r linkfn("par3dinterp")`
+`r indexfns("vertexSetter")`         | function to modify individual vertices
+`r indexfns("matrixSetter")`         | function to modify matrices
+
+### Working with the scene
+
+`rgl` maintains internal structures for all the scenes it displays.
+The following functions allow users to find information about them
+and manipulate them.
+
+------------------------------------ | -----------
+`r indexfns("open3d")`               | open a new window
+`r indexfns("rgl.close")`            | close the current window
+`r indexfns("rgl.bringtotop")`       | bring the current window to the top
+`r indexfns("rgl.cur")`              | id of the active device
+`r indexfns("rgl.dev.list")`         | ids of all active devices
+`r indexfns("rgl.set")`              | set a particular device to be active
+`r indexfns("rgl.ids")`              | ids and types of all current objects
+`r indexfns(c("rgl.attrib", "rgl.attrib.count"))`: | attributes of objects in the scene
+`r indexfns(c("pop3d", "rgl.pop"))`     | delete an object from the scene
+`r indexfns(c("clear3d", "rgl.clear"))`            | delete all objects of certain classes
+`r indexfns("rgl.projection")`        | return information about the current projection
+`r indexfns(c("rgl.user2window", "rgl.window2user"))` | convert between coordinates in the current projection
+
+In addition to these, there are some other related functions which
+should rarely be called by users: `r indexfns(c("rgl.init", "rgl.open", "rgl.quit"))`.  
+
+
+### Working with 3-D vectors
+
+Most `rgl` functions work internally with "homogeneous" coordinates.
+In this system, 3-D points are represented with 4 coordinates, generally
+called (x, y, z, w).  The corresponding Euclidean point is
+(x/w, y/w, z/w), if w is nonzero; zero values of w correspond to 
+"points at infinity".  The advantage of this system is that
+affine transformations including translations and perspective shifts
+become linear transformations, with multiplication by a 4 by 4 matrix.
+
+`rgl` has the following functions to work with homogeneous coordinates:
+
+------------------------------------ | -----------
+`r indexfns(c("asEuclidean", "asHomogeneous"))`: | convert between homogeneous and Euclidean coordinates
+`r indexfns(c("rotate3d", "scale3d", "translate3d"))`:  | apply a transformation
+`r indexfns("transform3d")`:  | apply a general transformation
+`r indexfns(c("rotationMatrix", "scaleMatrix", "translationMatrix"))`:  | compute the transformation matrix
+`r indexfns("identityMatrix")` | return a 4 x 4 identity matrix
+
+There is also a function `r indexfns("GramSchmidt")`, mainly for internal
+use:  it does a Gram-Schmidt orthogonalization of a 3x3 matrix,
+with some specializations for its use in `r linkfn("cylinder3d")`.
+
+## Warning:  Work in Progress!
+
+This vignette is in a preliminary form.  Many aspects of the rgl
+package are not described, or do not have examples.  There may
+even be functions that are missed completely, if the following
+list is not empty:
+```{r echo=FALSE}
+setdiff(ls("package:rgl"), documentedfns)
+```
+
+## Index of Functions
+
+The following functions and constants are described in this document:<br>
+
+```{r echo=FALSE, results="asis"}
+writeIndex(cols = 5)
+```
+
+
diff --git a/vignettes/setup.R b/vignettes/setup.R
new file mode 100644
index 0000000..6900676
--- /dev/null
+++ b/vignettes/setup.R
@@ -0,0 +1,76 @@
+options(rgl.useNULL=TRUE)
+library(rgl)
+library(rglwidget)
+
+if (requireNamespace("rmarkdown") && !rmarkdown::pandoc_available("1.13.1"))
+  warning("These vignettes assume pandoc version 1.13.1; older versions may give poor formatting.")
+
+setupKnitr()
+
+documentedfns <- c()
+
+indexfns <- function(fns, text = paste0("`", fns, "`"), show = TRUE, pkg = NA) {
+  documentedfns <<- c(documentedfns, fns)
+  anchors <- paste0('<a name="', fns, '">',
+                    if (show) linkfn(fns, text, pkg = pkg),
+                    '</a>')
+  paste(anchors, collapse=if (show) ", " else "")
+}
+
+indexclass <-
+  indexproperties <- function(fns, text = paste0("`", fns, "`"), show = TRUE) {
+    documentedfns <<- c(documentedfns, fns)
+    anchors <- paste0('<a name="', fns, '">',
+                      if (show) text,
+                      '</a>')
+    paste(anchors, collapse=if (show) ", " else "")
+  }
+
+indexmethods <- function(fns, text = paste0("`", fns, "()`"), show = TRUE) {
+  documentedfns <<- c(documentedfns, fns)
+  anchors <- paste0('<a name="', fns, '">',
+                    if (show) text,
+                    '</a>')
+  paste(anchors, collapse=if (show) ", " else "")
+}
+
+linkfn <- function(fn, text = paste0("`", fn, "`"), pkg = NA) {
+  if (is.na(pkg))
+    paste0('<a href="#', fn, '">', text, '</a>')
+  else
+    paste0('<a href="../../', pkg, '/help/', fn, '">', text,
+           '</a>')
+}
+
+# Write this once at the start of the document.
+
+cat('<style>
+    .nostripes tr.even {background-color: white;}
+    table {border-style: none;}
+    table th {border-style: none;}
+    table td {border-style: none;}
+    a[href^=".."] {text-decoration: underline;}
+    </style>
+    ')
+
+writeIndex <- function(cols = 4) {
+  documentedfns <- sort(documentedfns)
+  entries <- paste0('<a href="#', documentedfns, '">', documentedfns, '</a>  ')
+  len <- length(entries)
+  padding <- ((len + cols - 1) %/% cols) * cols - len
+  if (padding)
+    entries <- c(entries, rep("", length.out=padding))
+  cat('\n<div class="nostripes">\n')
+  print(knitr::kable(matrix(entries, ncol=cols), format="pandoc"))
+  cat("</div>\n")
+}
+
+# This displays the string code as `r code` when entered
+# as `r rinline(code)`.  Due to Stephane Laurent
+rinline <- function(code, script = FALSE){
+  if (script)
+    html <- "`r CODE`"
+  else
+    html <- '<code  class="r">``` `r CODE` ```</code>'
+  sub("CODE", code, html)
+}

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/r-cran-rgl.git



More information about the debian-med-commit mailing list