OpenCSG - The CSG rendering library
Author: Florian Kirsch
Keywords: OpenCSG, CSG, image-based, image-based CSG, rendering, SCS, Goldfeather, OpenGL

| # OpenCSG ### The CSG rendering library News Introduction Benefits Prerequisites Usage Download Applications Background Publications FAQ License |

### Latest release: OpenCSG 1.3.2 (02.12.2011)

### Introduction

OpenCSG is a library that does image-based CSG rendering using OpenGL. OpenCSG is written in C++ and supports most modern graphics hardware using Microsoft Windows or the Linux operating system. OpenCSG-1.3.2 is the current version.

What is CSG, anyway? CSG is short for Constructive Solid Geometry and denotes an approach to model complex 3D-shapes using simpler ones. I.e., two shapes can be combined by taking the union of them, by intersecting them, or by subtracting one shape of the other. The most basic shapes, which are not result of such a CSG operation, are called primitives. Primitives must be solid, i.e., they must have a clearly defined interior and exterior. By construction, a CSG shape is also solid then.

Image-based CSG rendering (also z-buffer CSG rendering) is a term that denotes algorithms for rendering CSG shapes without an explicit calculation of the geometric boundary of a CSG shape. Such algorithms use frame-buffer settings of the graphics hardware, e.g., the depth and stencil buffer, to compose CSG shapes. OpenCSG implements a variety of those algorithms, namely the Goldfeather algorithm and the SCS algorithm, both of them in several variants.

### Benefits

CSG is often used as fundamental modeling technique in CAD/CAM applications. Here, image-based CSG rendering is the key to interactively manipulate CSG shapes. Since OpenCSG renders even complex CSG shapes fast, it can be advantageously used in such applications.

Raytracers such as PovRay have used CSG for shape modeling since long ago. Interactive modeling toolkits for such raytracers normally just ignore CSG commands, though. OpenCSG represents a valuable addition for such applications.

Overall, up to the present CSG rendering has been hardly used in interactive applications, since the necessary algorithms are complicated and error-prone. We hope that by providing a free library that is easy to use, fast, and versatile, CSG rendering can be made more mainstream than it currently is.

### Prerequisites

The OpenCSG library requires graphics hardware that either supports frame buffer objects or PBuffers in OpenGL.

Frame buffer objects are a more recent extension for OpenGL. They are easy to develop for, and can be nowadays considered mature. They are also part of OpenGL 3.0. Beginning with OpenCSG 1.2.0, they are used by default.

In older versions, PBuffers were required to run OpenCSG. PBuffers have been widely supported since a long time now. NVidia supports them since the Riva TNT, and ATI at least since the Radeon series. Graphics hardware from other hardware vendors, however, likely do not support PBuffers. Therefore, if you have obscure graphics hardware that also does not support frame buffer objects, you are probably out of luck and you cannot run programs using OpenCSG. With Linux, you have the option to use Mesa 3D, which implements OpenGL software rendering and provides a solid frame buffer object implementation.

The PBuffer in OpenCSG is actually implemented via the (patched) RenderTexture class. For OpenGL extension checking, OpenCSG uses the OpenGL Extension Wrangler Library GLEW. Both these libraries are included in the OpenCSG download.

OpenCSG is written in C++, uses namespaces and requires the STL. There are no significant compiler incompatibilities under Windows. Workspaces for with MSVC6, VC2003 .net and Dev-C++ 5 beta are provided. Under Linux, you should use gcc version 3 or newer. gcc-2.95.x will not work, since this compiler does not come with a `std::map` implementation, which is required internally.

To run OpenCSG well, you should have graphics hardware with lots of fill rate. NVidia graphics hardware since GeForce and ATI Radeon qualify. The `OpenCSG::OcclusionQuery` option obviously requires occlusion queries, which are available since Radeon 9x00 (x>=5) and GeForce3 (beware that the GeForce4MX counts as GeForce2!).

OpenCSG has been sucessfully run on Intel and AMD hardware using GeForce 250 GTS Radeon HD 4670, GeForce 8x00, GeForceFX 6800, GeForceFX 5600, Radeon 9700, GeForce3, GeForce4MX, and TNT2 graphcs hardware (on the latter, it crawls ...).

On a Radeon 9000, OpenCSG was once known to produce rendering errors in all but the standard Goldfeather rendering path. It is unclear whether this was possibly a driver issue. I have no experiences running OpenCSG on graphics hardware other than from NVidia or ATI/AMD.

### Usage

The interface of OpenCSG is very easy to use. There is only a single abstract class called `OpenCSG::Primitive`. A `Primitive` object has an attribute `Operation` that denotes whether the primitive is intersected or subtracted. To use OpenCSG, create a derived concrete primitive class by implementing the `render()` method.

To actually do the CSG rendering, there is the function `OpenCSG::render()` that takes a `std::vector<Primitive*>` as argument. The render function evaluates the CSG expression given by the array of primitives and initializes the z-buffer with the proper values for the CSG expression. The color buffer remains unchanged, so afterwards, you must shade the primitives in the array using a `GL_EQUAL` depth function.

Note that the render function does not evaluate a generic CSG tree that also would contain unions of CSG shapes. It has been shown that a generic CSG tree can be converted into an equivalent set of CSG expressions that the render function can handle. OpenCSG does not contain the functionality for this conversion since, after all, it is a rendering library.

Here is the complete interface of OpenCSG:

`namespace OpenCSG {
enum Operation { Intersection, Subtraction };
class Primitive {
public:
Primitive(Operation, unsigned int convexity);
virtual ~Primitive();
void setOperation(Operation);
Operation getOperation() const;
void setConvexity(unsigned int);
unsigned int getConvexity() const;
void setBoundingBox(float minx, float miny, float minz,
float maxx, float maxy, float maxz);
void getBoundingBox(float& minx, float& miny, float& minz,
float& maxx, float& maxy, float& maxz) const;
virtual void render() = 0;
};
enum OptionType {
AlgorithmSetting,
DepthComplexitySetting,
OffscreenSetting,
DepthBoundsOptimization,
};
void setOption(OptionType option, int newSetting);
int getOption(OptionType option);
enum Algorithm { Automatic, Goldfeather, SCS };
enum DepthComplexityAlgorithm { NoDepthComplexitySampling, OcclusionQuery, DepthComplexitySampling };
enum OffscreenType { AutomaticOffscreenType, FrameBufferObject, PBuffer, FrameBufferObjectARB, FrameBufferObjectEXT };
enum Optimization { OptimizationDefault, OptimizationDefault, OptimizationOn, OptimizationOff };
void render(const std::vector<Primitive*>& primitives);
void setContext(int context);
int getContext();
void freeResources();
}
`

The convexity of a primitive is the maximum number of front (or back) faces of the primitive at a single position. For example, the convexity of a sphere is one and the convexity of a torus is two. Actually the convexity attribute is currently only used in the standard Goldfeather algorithm. For this algorithm, a convexity too low may result in rendering errors, a convexity too high will reduce rendering performance. The other Goldfeather variants render primitives of any convexity correctly without analyzing the convexity attribute. The SCS algorithms, on the other hand, can only handle primitives that have a convexity of one, else they produce rendering errors. Hence, SCS algorithms do not check this attribute.

The bounding box of the primitive can be provided using normal device coordinates, i.e., after transforming the primitive with modelview and projection transformation. It is not necessary to set the bounding box, but it allows for various performance optimizations.

The abstract `render` method of the primitive is implemented in a derived class. Your implementation must not alter the modelview or projection matrix (use `glPushMatrix` / `glPopMatrix` if in doubt). Also you must not change the primary color in your implementation, since OpenCSG uses it internally (in all rendering algorithms). For best performance, you should only transmit vertex positions; no normals, texture coordinates, or whatever else.

The `render` function performs, as said above, z-shading of a CSG expression. The content of the stencil buffer is destroyed when handling concave primitives or when using the `DepthComplexitySampling` strategy.

Using the functions `setOption() / getOption` you can control and ask for certain settings used when rendering a CSG expression. These functions were introduced with version 1.1.0 of OpenCSG. You can specify the Algorithm, the method of depth complexity usage and the type of offscreen buffer. There is an obsolete variant of the `render()` function that takes these two options as additional arguments, temporarily overriding the currently set options.

The `Algorithm` parameter specifies the method used for CSG rendering. Besides `Goldfeather` and `SCS`, you can also choose `Automatic`: This setting chooses the Goldfeather algorithm if the primitive array contains concave primitives, else it chooses SCS. The automatic setting also sets the `DepthComplexityAlgorithm` (`NoDepthComplexitySampling` for arrays with few primitives, else `OcclusionQuery` or at the last resort `DepthComplexitySampling`).

Aforesaid means that it is, currently, not possible to do CSG rendering of concave primitives and preserving the stencil buffer. I am looking for ways to change this situation (The ARB_buffer_region extension appears to be a possible way for this).

If the `Automatic` setting is not used, the `DepthComplexityAlgorithm` parameter specifies the strategy for profiting from depth complexity.

- `NoDepthComplexitySampling`: Does not employ the depth complexity. This essentially makes the algorithm O(n²), but with low constant costs.
- `DepthComplexitySampling`: Calculates the depth complexity k using the stencil buffer. This makes the algorithm O(n*k), but with high constant costs. In case of the Goldfeather algorithm, the literature denotes this as layered Goldfeather algorithm.
- `OcclusionQuery`: Uses occlusion queries to profit implicitly from depth complexity without calculating it. This is especially useful for the SCS algorithm where this strategy is applied at shape level, resulting in a O(n*k') algorithm (where k' <= k), without significant constant overhead. This strategy requires hardware occlusion queries, i.E., the OpenGL extensions `GL_ARB_occlusion_query`, eventually `GL_ARB_occlusion_query2`, or `GL_NV_occlusion_query`.

The offscreen type specifies what kind of offscreen buffer OpenCSG uses for internal CSG calculations. The default `AutomaticOffscreenType` preferably uses, if the required OpenGL extensions are available, `FrameBufferObjectARB`, then `FrameBufferObjectEXT`, then `PBuffer`. The `FrameBufferObject` uses preferably `FrameBufferObjectARB`, then `FrameBufferObjectEXT`. These priorities are subject to change between different releases based on experiences with compatibility of OpenCSG with different extensions and graphics hardware. The remaining settings `PBuffer`, `FrameBufferObjectARB`, and `FrameBufferObjectEXT` directly map to the usage of the corresponding OpenGL extension. Overall, using frame buffer objects is potentially faster, because they do not impose a separate rendering context for the offscreen buffer and hence require no context switching. In typical scenarios, there is no difference though.

The depth bounds optimization improves the rendering performance by using the OpenGL extension `GL_EXT_depth_bounds_test` to restrict rendering to only the depth range indicated by the bounding box of a primitive. This optimization is, by default, turned off. If you enable it, ensure that the z-ranges of the bounding boxes are large enough, otherwise they will not be correctly rendered. The gains you will get from this optimization is probably only small.

OpenCSG creates, and reuses between different `render()` calls, various OpenGL resources such as PBuffers or frame buffer objects. This may be a problem in MDI applications with several OpenGL windows, of which the OpenGL contexts are not shared. In this case, OpenGL resources allocated in one OpenGL context cannot be reused with another context, so OpenCSG would produce rendering errors. To solve this, the OpenCSG context can be set to some unique integer identifier of the OpenGL window. OpenCSG then creates/uses OpenGL resources in the `render()` function per context. The function `freeResources()` frees OpenGL resources for the currently active OpenCSG context.

### Download

Download OpenCSG-1.3.2.tar.gz. The archive contains all required helper libraries, i.e., also RenderTexture and GLEW. It comes with makefiles for Linux and with project files for MSVC6, VS2003, and Dev-C++ 5.

The older versions
OpenCSG-1.3.1
OpenCSG-1.3.0
OpenCSG-1.2.0
OpenCSG-1.1.1
OpenCSG-1.1.0
OpenCSG-1.0.2
OpenCSG-1.0.1
OpenCSG-1.0.0
OpenCSG-0.9.2
OpenCSG-0.9.1
OpenCSG-0.9
are still available for download.

### Applications

Currently, I know of the following applications making use of OpenCSG:

| OpenSCAD is a software for creating solid 3D CAD objects by means of a scripting language. It supports interactive preview of the CSG geometry as well as exporting the final geometry as 3D model. There are precompiled binaries for Linux, Windows, and MacOS X.
| Ayam is a 3D modelling environment for the RenderMan interface, running on Unix, Win32, and Mac OS X. Since version 1.8, Ayam provides the plugin aycsg for real-time CSG preview of complex CSG hierarchies using OpenCSG as rendering library.
| koraX's CSG Editor. This editor for MS Windows allows to compose textured CSG shapes from a set of predefined primitives. The application contains a very good online help that depicts nicely what CSG is about, and that furthermore contains some tutorial how to create 1) a graphical widget and 2) a pipe.

### Background

I have developed the algorithms for OpenCSG in my time as research assistent at HPI at the University Potsdam. In this time the following publications about OpenCSG and about image-based CSG rendering have been written:

| F. Kirsch, J. Döllner: Rendering Techniques for Hardware-Accelerated Image-Based CSG. Journal of WSCG, 12(2):221-228, 2004. This paper gives an introduction to image-based CSG rendering and describes the two techniques that are used in OpenCSG to accelerate rendering compared to older implementations: Visibility transfer using textures and occlusion queries for the SCS algorithm.
| F. Kirsch, J. Döllner: OpenCSG: A Library for Image-Based CSG Rendering. Proceedings of the FREENIX / Open Source Track, 2005 USENIX Annual Technical Conference, 129-140, 2005. This paper describes OpenCSG itself. It concentrates on the API, explaining internal implementation details only as shortly as possible. It also outlines possible non-obvious uses of OpenCSG.
| F. Kirsch: Entwurf und Implementierung eines computergraphischen Systems zur Integration komplexer, echtzeitfähiger 3D-Renderingverfahren. Published online, URN: urn:nbn:de:kobv:517-opus-6079, 2005. My doctoral dissertation (in german) describes an approach for integration and combination of several rendering techniques using a scene graph system. As such, it contains a long chapter covering CSG rendering.

### FAQ

1. Can I render a shape with different colors? The documentation says I must not change the primary color in the function of my class for primitives, since OpenCSG uses the color for internal purposes.

   You can shade your shapes with whatever color you want. While your primitive objects for use in OpenCSG must not use the primary color, after calculating z-values with OpenCSG you are free to render the same geometry with primary colors.

2. Does OpenCSG require a stencil buffer?

   You must setup a stencil buffer in your application when rendering concave primitives or when using `DepthComplexitySampling`. Internally, the stencil buffer is always needed in OpenCSG when rendering into the offscreen frame buffer object resp. PBuffer.

3. Can OpenCSG calculate the geometry of a CSG expression?

   No, unfortunately this is not possible using image-based CSG algorithms (at least not in a trivial way). If you require this, have a look at other libraries such as the GTS library.

4. What are the dependencies of the example program?

   The OpenCSG example requires GLUT. This library is likely pre-installed with your favorite linux installation. Visual Studio users can install GLUT for Windows. Dev-C++ users can install the precompiled GLUT for Mingw32.

### License

OpenCSG is copyrighted by Florian Kirsch and by the Hasso-Plattner-Institute at the University of Potsdam (HPI), Germany.

You can license OpenCSG by terms of the GNU GPL, Version 2. This means that you may release applications or libraries that use (parts of) OpenCSG (a) only if you release the complete source code of your application or library and (b) only if you release it under the GPL license.

If you do not want to release your source code unter terms of the GPL, you can't use and link against OpenCSG and ship the software by licensing it unter GPL. In this case, e.g., if you want to use OpenCSG in a proprietary application or library, you can always ask for a separate license and use it for development and production purposes.

According to the GPL, you are free to modify and redistribute OpenCSG under terms of the GPL. We welcome contribution of your modifications to OpenCSG, however to let us integrate your modifications into OpenCSG, you must assign the copyright of the modifications to the HPI, Florian Kirsch. In other words, modifications from you that you would like to be integrated into OpenCSG should not hinder us to distribute OpenCSG under other, non-free licenses.

Note that OpenCSG comes with code that is not under copyright of the HPI or Florian Kirsch. These are GLEW and RenderTexture. These libraries are licensed under the terms of their respective authors.

© 2002-2011, Florian Kirsch, e-mail: mail at opencsg dot org,
2002-2005 Hasso-Plattner-Institute Potsdam.
Last change: 02.12.2011