arsd.nanovega

The NanoVega API is modeled loosely on HTML5 canvas API. If you know canvas, you're up to speed with NanoVega in no time.

D code with nanovega:
1 import arsd.simpledisplay;
2 
3 import arsd.nanovega;
4 
5 void main () {
6   NVGContext nvg; // our NanoVega context
7 
8   // we need at least OpenGL3 with GLSL to use NanoVega,
9   // so let's tell simpledisplay about that
10   setOpenGLContextVersion(3, 0);
11 
12   // now create OpenGL window
13   auto sdmain = new SimpleWindow(800, 600, "NanoVega Simple Sample", OpenGlOptions.yes, Resizability.allowResizing);
14 
15   // we need to destroy NanoVega context on window close
16   // stricly speaking, it is not necessary, as nothing fatal
17   // will happen if you'll forget it, but let's be polite.
18   // note that we cannot do that *after* our window was closed,
19   // as we need alive OpenGL context to do proper cleanup.
20   sdmain.onClosing = delegate () {
21     nvg.kill();
22   };
23 
24   // this is called just before our window will be shown for the first time.
25   // we must create NanoVega context here, as it needs to initialize
26   // internal OpenGL subsystem with valid OpenGL context.
27   sdmain.visibleForTheFirstTime = delegate () {
28     // yes, that's all
29     nvg = nvgCreateContext();
30     if (nvg is null) assert(0, "cannot initialize NanoVega");
31   };
32 
33   // this callback will be called when we will need to repaint our window
34   sdmain.redrawOpenGlScene = delegate () {
35     // fix viewport (we can do this in resize event, or here, it doesn't matter)
36     glViewport(0, 0, sdmain.width, sdmain.height);
37 
38     // clear window
39     glClearColor(0, 0, 0, 0);
40     glClear(glNVGClearFlags); // use NanoVega API to get flags for OpenGL call
41 
42     {
43       nvg.beginFrame(sdmain.width, sdmain.height); // begin rendering
44       scope(exit) nvg.endFrame(); // and flush render queue on exit
45 
46       nvg.beginPath(); // start new path
47       nvg.roundedRect(20.5, 30.5, sdmain.width-40, sdmain.height-60, 8); // .5 to draw at pixel center (see NanoVega documentation)
48       // now set filling mode for our rectangle
49       // you can create colors using HTML syntax, or with convenient constants
50       nvg.fillPaint = nvg.linearGradient(20.5, 30.5, sdmain.width-40, sdmain.height-60, NVGColor("#f70"), NVGColor.green);
51       // now fill our rect
52       nvg.fill();
53       // and draw a nice outline
54       nvg.strokeColor = NVGColor.white;
55       nvg.strokeWidth = 2;
56       nvg.stroke();
57       // that's all, folks!
58     }
59   };
60 
61   sdmain.eventLoop(0, // no pulse timer required
62     delegate (KeyEvent event) {
63       if (event == "*-Q" || event == "Escape") { sdmain.close(); return; } // quit on Q, Ctrl+Q, and so on
64     },
65   );
66 
67   flushGui(); // let OS do it's cleanup
68 }
Javascript code with HTML5 Canvas
1 <!DOCTYPE html>
2 <html>
3 <head>
4 	<title>NanoVega Simple Sample (HTML5 Translation)</title>
5 	<style>
6 		body { background-color: black; }
7 	</style>
8 </head>
9 <body>
10 	<canvas id="my-canvas" width="800" height="600"></canvas>
11 <script>
12 	var canvas = document.getElementById("my-canvas");
13 	var context = canvas.getContext("2d");
14 
15 	context.beginPath();
16 
17 	context.rect(20.5, 30.5, canvas.width - 40, canvas.height - 60);
18 
19 	var gradient = context.createLinearGradient(20.5, 30.5, canvas.width - 40, canvas.height - 60);
20 	gradient.addColorStop(0, "#f70");
21 	gradient.addColorStop(1, "green");
22 
23 	context.fillStyle = gradient;
24 	context.fill();
25 	context.closePath();
26 	context.strokeStyle = "white";
27 	context.lineWidth = 2;
28 	context.stroke();
29 </script>
30 </body>
31 </html>

Members

Context Management

Functions to create and destory NanoVega context.

Context management Aliases

NVGContext
alias NVGContext = NVGcontextinternal*

Pointer to opaque NanoVega context structure.

Context management Enums

NVGContextFlag
enum NVGContextFlag

Context creation flags.

Context management Functions

devicePixelRatio
float devicePixelRatio(NVGContext ctx)

valid only inside beginFrame/endFrame

glNVGClearFlags
uint glNVGClearFlags()

Returns flags for glClear().

height
int height(NVGContext ctx)

valid only inside beginFrame/endFrame

inFrame
bool inFrame(NVGContext ctx)

Returns true if beginFrame was called, and neither endFrame, nor cancelFrame were.

kill
void kill(ref NVGContext ctx)

Delete NanoVega context.

nvgCreateContext
NVGContext nvgCreateContext(const(NVGContextFlag)[] flagList...)

Creates NanoVega contexts for OpenGL2+.

pickid
int pickid(NVGContext ctx)

>=0: this pickid will be assigned to all filled/stroked paths

pickid
void pickid(NVGContext ctx, int v)

>=0: this pickid will be assigned to all filled/stroked paths

pickmode
uint pickmode(NVGContext ctx)

pick autoregistration mode; see NVGPickKind

pickmode
void pickmode(NVGContext ctx, uint v)

pick autoregistration mode; see NVGPickKind

valid
bool valid(in NVGContext ctx)

Returns true if the given context is not null and can be used for painting.

width
int width(NVGContext ctx)

valid only inside beginFrame/endFrame

Context management Manifest constants

NVGNoPick
enum NVGNoPick;

pickid to stop autoregistration.

Frame Management

To start drawing with NanoVega context, you have to "begin frame", and then "end frame" to flush your rendering commands to GPU.

Frame management Functions

beginFrame
void beginFrame(NVGContext ctx, int windowWidth, int windowHeight, float devicePixelRatio = 1.0f)

Begin drawing a new frame.

cancelFrame
void cancelFrame(NVGContext ctx)

Cancels drawing the current frame. Cancels path recording.

endFrame
void endFrame(NVGContext ctx)

Ends drawing the current frame (flushing remaining render state). Commits recorded paths.

Composite Operation

The composite operations in NanoVega are modeled after HTML Canvas API, and the blend func is based on OpenGL (see corresponding manuals for more info). The colors in the blending state have premultiplied alpha.

Composite operation Enums

NVGBlendFactor
enum NVGBlendFactor

Blending type.

NVGCompositeOperation
enum NVGCompositeOperation

Composite operation (HTML5-alike).

Composite operation Functions

globalCompositeBlendFunc
void globalCompositeBlendFunc(NVGContext ctx, NVGBlendFactor sfactor, NVGBlendFactor dfactor)

Sets the composite operation with custom pixel arithmetic.

globalCompositeBlendFuncSeparate
void globalCompositeBlendFuncSeparate(NVGContext ctx, NVGBlendFactor srcRGB, NVGBlendFactor dstRGB, NVGBlendFactor srcAlpha, NVGBlendFactor dstAlpha)

Sets the composite operation with custom pixel arithmetic for RGB and alpha components separately.

globalCompositeOperation
void globalCompositeOperation(NVGContext ctx, NVGCompositeOperation op)

Sets the composite operation.

Composite operation Structs

NVGCompositeOperationState
struct NVGCompositeOperationState

Composite operation state.

Color Utils

Colors in NanoVega are stored as ARGB. Zero alpha means "transparent color".

Color utils Aliases

nvgHSL
alias nvgHSL = nvgHSLA

Returns color value specified by hue, saturation and lightness. HSL values are all in range [0..1], alpha will be set to 255.

Color utils Functions

nvgHSLA
NVGColor nvgHSLA(float h, float s, float l, ubyte a = 255)

Returns color value specified by hue, saturation and lightness and alpha. HSL values are all in range [0..1], alpha in range [0..255].

nvgHSLA
NVGColor nvgHSLA(float h, float s, float l, float a)

Returns color value specified by hue, saturation and lightness and alpha. HSL values and alpha are all in range [0..1].

nvgLerpRGBA
NVGColor nvgLerpRGBA(in auto ref NVGColor c0, in auto ref NVGColor c1, float u)

Linearly interpolates from color c0 to c1, and returns resulting color value.

nvgRGB
NVGColor nvgRGB(const(char)[] srgb)

Returns a color value from string form. Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"

nvgRGB
NVGColor nvgRGB(int r, int g, int b)

Returns a color value from red, green, blue values. Alpha will be set to 255 (1.0f).

nvgRGBA
NVGColor nvgRGBA(const(char)[] srgb)

Returns a color value from string form. Supports: "#rgb", "#rrggbb", "#argb", "#aarrggbb"

nvgRGBA
NVGColor nvgRGBA(int r, int g, int b, int a = 255)

Returns a color value from red, green, blue and alpha values.

nvgRGBAf
NVGColor nvgRGBAf(float r, float g, float b, float a = 1.0f)

Returns a color value from red, green, blue and alpha values.

nvgRGBf
NVGColor nvgRGBf(float r, float g, float b)

Returns a color value from red, green, blue values. Alpha will be set to 1.0f.

nvgTransRGBA
NVGColor nvgTransRGBA(NVGColor c, ubyte a)
nvgTransRGBAf
NVGColor nvgTransRGBAf(NVGColor c, float a)

Returns new color with transparency (alpha) set to a.

Color utils Structs

NVGColor
struct NVGColor

NanoVega RGBA color

NVGHSL
struct NVGHSL

NanoVega A-HSL color

Matrices and Transformations

The paths, gradients, patterns and scissor region are transformed by an transformation matrix at the time when they are passed to the API. The current transformation matrix is an affine matrix:

[sx kx tx]
[ky sy ty]
[ 0  0  1]

Where: (sx, sy) define scaling, (kx, ky) skewing, and (tx, ty) translation. The last row is assumed to be (0, 0, 1) and is not stored.

Apart from resetTransform, each transformation function first creates specific transformation matrix and pre-multiplies the current transformation by it.

Current coordinate system (transformation) can be saved and restored using save and restore.

The following functions can be used to make calculations on 2x3 transformation matrices. A 2x3 matrix is represented as float[6].

Matrices Functions

nvgDegToRad
float nvgDegToRad(in float deg)

Converts degrees to radians.

nvgRadToDeg
float nvgRadToDeg(in float rad)

Converts radians to degrees.

Matrices Structs

NVGMatrix
struct NVGMatrix

Matrix class.

State Handling

NanoVega contains state which represents how paths will be rendered. The state contains transform, fill and stroke styles, text and font styles, and scissor clipping.

State handling Functions

canRestore
bool canRestore(NVGContext ctx)

Returns true if we have any saved state.

canSave
bool canSave(NVGContext ctx)

Returns true if we have any room in state stack. It is guaranteed to have at least 32 stack slots.

renderBlocked
bool renderBlocked(NVGContext ctx)

Returns true if rendering is currently blocked.

renderBlocked
void renderBlocked(NVGContext ctx, bool v)

Blocks/unblocks rendering

reset
void reset(NVGContext ctx)

Resets current render state to default values. Does not affect the render state stack.

restore
bool restore(NVGContext ctx)

Pops and restores current render state.

save
bool save(NVGContext ctx)

Pushes and saves the current render state into a state stack. A matching restore must be used to restore the state. Returns false if state stack overflowed.

setRenderBlocked
bool setRenderBlocked(NVGContext ctx, bool v)

Blocks/unblocks rendering; returns previous state.

Render Styles

Fill and stroke render style can be either a solid color or a paint which is a gradient or a pattern. Solid color is simply defined as a color value, different kinds of paints can be created using linearGradient, boxGradient, radialGradient and imagePattern.

Current render style can be saved and restored using save and restore.

Note that if you want "almost perfect" pixel rendering, you should set aspect ratio to 1, and use integerCoord+0.5f as pixel coordinates.

Render styles Enums

NVGLineCap
enum NVGLineCap

Line cap style.

Render styles Functions

evenOddFill
void evenOddFill(NVGContext ctx)

Sets filling mode to "even-odd".

fillColor
void fillColor(NVGContext ctx, in auto ref NVGColor color)

Sets current fill style to a solid color.

fillColor
void fillColor(NVGContext ctx, Color color)

Sets current fill style to a solid color.

fillPaint
void fillPaint(NVGContext ctx, in auto ref NVGPaint paint)

Sets current fill style to a paint, which can be a one of the gradients or a pattern.

fillPaint
void fillPaint(NVGContext ctx, in auto ref NVGLGS lgs)

Sets current fill style to a multistop linear gradient.

globalAlpha
void globalAlpha(NVGContext ctx, float alpha)

Sets the transparency applied to all rendered shapes. Already transparent paths will get proportionally more transparent as well.

lineCap
void lineCap(NVGContext ctx, NVGLineCap cap)

Sets how the end of the line (cap) is drawn, Can be one of: NVGLineCap.Butt (default), NVGLineCap.Round, NVGLineCap.Square.

lineJoin
void lineJoin(NVGContext ctx, NVGLineCap join)

Sets how sharp path corners are drawn. Can be one of NVGLineCap.Miter (default), NVGLineCap.Round, NVGLineCap.Bevel.

miterLimit
void miterLimit(NVGContext ctx, float limit)

Sets the miter limit of the stroke style. Miter limit controls when a sharp corner is beveled.

nonZeroFill
void nonZeroFill(NVGContext ctx)

Sets filling mode to "non-zero" (this is default mode).

setLineDash
void setLineDash(NVGContext ctx, const(float)[] dashdata)

Sets stroke dashing, using (dash_length, gap_length) pairs. Current limit is 16 pairs. Resets dash start to zero.

setLineDashStart
void setLineDashStart(NVGContext ctx, in float dashStart)

Sets stroke dashing, using (dash_length, gap_length) pairs. Current limit is 16 pairs.

shapeAntiAlias
void shapeAntiAlias(NVGContext ctx, bool enabled)

Sets whether to draw antialias for stroke and fill. It's enabled by default.

strokeColor
void strokeColor(NVGContext ctx, Color color)

Sets current stroke style to a solid color.

strokeColor
void strokeColor(NVGContext ctx, in auto ref NVGColor color)

Sets current stroke style to a solid color.

strokePaint
void strokePaint(NVGContext ctx, in auto ref NVGPaint paint)

Sets current stroke style to a paint, which can be a one of the gradients or a pattern.

strokeWidth
void strokeWidth(NVGContext ctx, float width)

Sets the stroke width of the stroke style.

Render styles Structs

NVGPaint
struct NVGPaint

Paint parameters for various fills. Don't change anything here!

Render Transformations

Transformation matrix management for the current rendering style. Transformations are applied in backwards order. I.e. if you first translate, and then rotate, your path will be rotated around it's origin, and then translated to the destination point.

Render transformations Functions

currTransform
NVGMatrix currTransform(NVGContext ctx)

Returns current transformation matrix.

currTransform
void currTransform(NVGContext ctx, in auto ref NVGMatrix m)

Sets current transformation matrix.

resetTransform
void resetTransform(NVGContext ctx)

Resets current transform to an identity matrix.

rotate
void rotate(NVGContext ctx, in float angle)

Rotates current coordinate system. Angle is specified in radians.

scale
void scale(NVGContext ctx, in float x, in float y)

Scales the current coordinate system.

skewX
void skewX(NVGContext ctx, in float angle)

Skews the current coordinate system along X axis. Angle is specified in radians.

skewY
void skewY(NVGContext ctx, in float angle)

Skews the current coordinate system along Y axis. Angle is specified in radians.

transform
void transform(NVGContext ctx, in auto ref NVGMatrix mt)

Premultiplies current coordinate system by specified matrix.

translate
void translate(NVGContext ctx, in float x, in float y)

Translates current coordinate system.

Scissoring

Scissoring allows you to clip the rendering into a rectangle. This is useful for various user interface cases like rendering a text edit or a timeline.

Scissoring Functions

intersectScissor
void intersectScissor(NVGContext ctx, in float x, in float y, in float w, in float h)

Intersects current scissor rectangle with the specified rectangle. The scissor rectangle is transformed by the current transform. Note: in case the rotation of previous scissor rect differs from the current one, the intersection will be done between the specified rectangle and the previous scissor rectangle transformed in the current transform space. The resulting shape is always rectangle.

intersectScissor
void intersectScissor(NVGContext ctx, in float[] args)

Intersects current scissor rectangle with the specified rectangle. The scissor rectangle is transformed by the current transform. Note: in case the rotation of previous scissor rect differs from the current one, the intersection will be done between the specified rectangle and the previous scissor rectangle transformed in the current transform space. The resulting shape is always rectangle.

resetScissor
void resetScissor(NVGContext ctx)

Reset and disables scissoring.

scissor
void scissor(NVGContext ctx, in float x, in float y, float w, float h)

Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform.

scissor
void scissor(NVGContext ctx, in float[] args)

Sets the current scissor rectangle. The scissor rectangle is transformed by the current transform. Arguments: [x, y, w, h]*

Images

NanoVega allows you to load image files in various formats (if arsd loaders are in place) to be used for rendering. In addition you can upload your own image. The parameter imageFlagsList is a list of flags defined in NVGImageFlag.

If you will use your image as fill pattern, it will be scaled by default. To make it repeat, pass NVGImageFlag.RepeatX and NVGImageFlag.RepeatY flags to image creation function respectively.

Images Enums

NVGImageFlag
enum NVGImageFlag

Image creation flags.

Images Functions

createImage
NVGImage createImage(NVGContext ctx, const(char)[] filename, const(NVGImageFlag)[] imageFlagsList...)

Creates image by loading it from the disk from specified file name. Returns handle to the image or 0 on error.

createImageFromMemoryImage
NVGImage createImageFromMemoryImage(NVGContext ctx, MemoryImage img, const(NVGImageFlag)[] imageFlagsList...)

Creates image by loading it from the specified memory image. Returns handle to the image or 0 on error.

createImageMem
NVGImage createImageMem(NVGContext ctx, const(ubyte)* data, int ndata, const(NVGImageFlag)[] imageFlagsList...)

Creates image by loading it from the specified chunk of memory. Returns handle to the image or 0 on error.

createImageRGBA
NVGImage createImageRGBA(NVGContext ctx, int w, int h, const(void)[] data, const(NVGImageFlag)[] imageFlagsList...)

Creates image from specified image data. Returns handle to the image or 0 on error.

deleteImage
void deleteImage(NVGContext ctx, ref NVGImage image)

Deletes created image.

glCreateImageFromHandleGL2
int glCreateImageFromHandleGL2(NVGContext ctx, GLuint textureId, int w, int h, int imageFlags)

Create NanoVega OpenGL image from texture id.

glImageHandleGL2
GLuint glImageHandleGL2(NVGContext ctx, int image)

Returns OpenGL texture id for NanoVega image.

imageSize
void imageSize(NVGContext ctx, in auto ref NVGImage image, out int w, out int h)

Returns the dimensions of a created image.

updateImage
void updateImage(NVGContext ctx, auto ref NVGImage image, const(void)[] data)

Updates image data specified by image handle.

Images Structs

NVGImage
struct NVGImage

NanoVega image handle.

Paints

NanoVega supports four types of paints: linear gradient, box gradient, radial gradient and image pattern. These can be used as paints for strokes and fills.

Paints Functions

asPaint
NVGPaint asPaint(NVGContext ctx, in auto ref NVGLGS lgs)

Returns NVGPaint for linear gradient with stops, created with createLinearGradientWithStops. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

boxGradient
NVGPaint boxGradient(NVGContext ctx, float x, float y, float w, float h, float r, float f, in auto ref NVGColor icol, in auto ref NVGColor ocol)

Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering drop shadows or highlights for boxes. Parameters (x, y) define the top-left corner of the rectangle, (w, h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

boxGradient
NVGPaint boxGradient(NVGContext ctx, in float x, in float y, in float w, in float h, in float r, in float f, in Color icol, in Color ocol)

Creates and returns a box gradient. Box gradient is a feathered rounded rectangle, it is useful for rendering drop shadows or highlights for boxes. Parameters (x, y) define the top-left corner of the rectangle, (w, h) define the size of the rectangle, r defines the corner radius, and f feather. Feather defines how blurry the border of the rectangle is. Parameter icol specifies the inner color and ocol the outer color of the gradient. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

createLinearGradientWithStops
NVGLGS createLinearGradientWithStops(NVGContext ctx, in float sx, in float sy, in float ex, in float ey, const(NVGGradientStop)[] stops...)

Create linear gradient data suitable to use with linearGradient(res). Don't forget to destroy the result when you don't need it anymore with ctx.kill(res);.

THIS IS EXPERIMENTAL API AND MAY BE CHANGED/BROKEN IN NEXT RELEASES!
imagePattern
NVGPaint imagePattern(NVGContext ctx, float cx, float cy, float w, float h, float angle, in auto ref NVGImage image, float alpha = 1)

Creates and returns an image pattern. Parameters (cx, cy) specify the left-top location of the image pattern, (w, h) the size of one image, angle rotation around the top-left corner, image is handle to the image to render. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

linearGradient
NVGPaint linearGradient(NVGContext ctx, in float sx, in float sy, in float ex, in float ey, in Color icol, in Color ocol)

Creates and returns a linear gradient. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

linearGradient
NVGPaint linearGradient(NVGContext ctx, in float sx, in float sy, in float ex, in float ey, in Color icol, in float midp, in Color mcol, in Color ocol)

Creates and returns a linear gradient with middle stop. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color, midp specifies stop point in range (0..1), and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

linearGradient
NVGPaint linearGradient(NVGContext ctx, float sx, float sy, float ex, float ey, in auto ref NVGColor icol, in auto ref NVGColor ocol)

Creates and returns a linear gradient. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

linearGradient
NVGPaint linearGradient(NVGContext ctx, float sx, float sy, float ex, float ey, in auto ref NVGColor icol, in float midp, in auto ref NVGColor mcol, in auto ref NVGColor ocol)

Creates and returns a linear gradient with middle stop. Parameters (sx, sy) (ex, ey) specify the start and end coordinates of the linear gradient, icol specifies the start color, midp specifies stop point in range (0..1), and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

radialGradient
NVGPaint radialGradient(NVGContext ctx, in float cx, in float cy, in float inr, in float outr, in Color icol, in Color ocol)

Creates and returns a radial gradient. Parameters (cx, cy) specify the center, inr and outr specify the inner and outer radius of the gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

radialGradient
NVGPaint radialGradient(NVGContext ctx, float cx, float cy, float inr, float outr, in auto ref NVGColor icol, in auto ref NVGColor ocol)

Creates and returns a radial gradient. Parameters (cx, cy) specify the center, inr and outr specify the inner and outer radius of the gradient, icol specifies the start color and ocol the end color. The gradient is transformed by the current transform when it is passed to fillPaint or strokePaint.

Paints Structs

NVGGradientStop
struct NVGGradientStop

Gradient Stop Point.

THIS IS EXPERIMENTAL API AND MAY BE CHANGED/BROKEN IN NEXT RELEASES!
NVGLGS
struct NVGLGS

Linear gradient with multiple stops.

THIS IS EXPERIMENTAL API AND MAY BE CHANGED/BROKEN IN NEXT RELEASES!

Render-Time Affine Transformations

It is possible to set affine transformation matrix for GPU. That matrix will be applied by the shader code. This can be used to quickly translate and rotate saved paths. Call this only between beginFrame and endFrame.

Note that beginFrame resets this matrix to identity one.

Don't use this for scaling or skewing, or your image will be heavily distorted!

Gpu affine Functions

affineGPU
void affineGPU(NVGContext ctx, in auto ref NVGMatrix mat)

Sets GPU affine transformatin matrix. Don't do scaling or skewing here. This matrix won't be saved/restored with context state save/restore operations, as it is not a part of that state.

affineGPU
NVGMatrix affineGPU(NVGContext ctx)

Get current GPU affine transformatin matrix.

gpuUntransformPoint
void gpuUntransformPoint(NVGContext ctx, float* dx, float* dy, in float x, in float y)

"Untransform" point using current GPU affine matrix.

Paths

Drawing a new shape starts with beginPath, it clears all the currently defined paths. Then you define one or more paths and sub-paths which describe the shape. The are functions to draw common shapes like rectangles and circles, and lower level step-by-step functions, which allow to define a path curve by curve.

NanoVega uses even-odd fill rule to draw the shapes. Solid shapes should have counter clockwise winding and holes should have counter clockwise order. To specify winding of a path you can call pathWinding. This is useful especially for the common shapes, which are drawn CCW.

Finally you can fill the path using current fill style by calling fill, and stroke it with current stroke style by calling stroke.

The curve segments and sub-paths are transformed by the current transform.

Paths Enums

NVGSolidity
enum NVGSolidity

Path solidity.

NVGWinding
enum NVGWinding

Path winding.

Paths Functions

arc
void arc(NVGContext ctx, NVGWinding dir, in float cx, in float cy, in float r, in float a0, in float a1)

Creates new circle arc shaped sub-path. The arc center is at (cx, cy), the arc radius is r, and the arc is drawn from angle a0 to a1, and swept in direction dir (NVGWinding.CCW, or NVGWinding.CW). Angles are specified in radians.

arc
void arc(NVGContext ctx, NVGWinding dir, in float[] args)

Creates new circle arc shaped sub-path. The arc center is at (cx, cy), the arc radius is r, and the arc is drawn from angle a0 to a1, and swept in direction dir (NVGWinding.CCW, or NVGWinding.CW). Angles are specified in radians.

arcTo
void arcTo(NVGContext ctx, in float x1, in float y1, in float x2, in float y2, in float radius)

Adds an arc segment at the corner defined by the last path point, and two specified points.

arcTo
void arcTo(NVGContext ctx, in float[] args)

Adds an arc segment at the corner defined by the last path point, and two specified points. Arguments: [x1, y1, x2, y2, radius]*

beginPath
void beginPath(NVGContext ctx)

Clears the current path and sub-paths.

bezierTo
void bezierTo(NVGContext ctx, in float[] args)

Adds cubic bezier segment from last point in the path via two control points to the specified point. Arguments: [c1x, c1y, c2x, c2y, x, y]*

bezierTo
void bezierTo(NVGContext ctx, in float c1x, in float c1y, in float c2x, in float c2y, in float x, in float y)

Adds cubic bezier segment from last point in the path via two control points to the specified point.

circle
void circle(NVGContext ctx, in float cx, in float cy, in float r)

Creates new circle shaped sub-path.

circle
void circle(NVGContext ctx, in float[] args)

Creates new circle shaped sub-path. Arguments: [cx, cy, r]*

closePath
void closePath(NVGContext ctx)

Closes current sub-path with a line segment.

ellipse
void ellipse(NVGContext ctx, in float cx, in float cy, in float rx, in float ry)

Creates new ellipse shaped sub-path.

ellipse
void ellipse(NVGContext ctx, in float[] args)

Creates new ellipse shaped sub-path. Arguments: [cx, cy, rx, ry]*

fill
void fill(NVGContext ctx)

Fills the current path with current fill style.

getCurrPathOutline
NVGPathOutline getCurrPathOutline(NVGContext ctx)

Return outline of the current path. Returned outline is not flattened.

lineTo
void lineTo(NVGContext ctx, in float[] args)

Adds line segment from the last point in the path to the specified point. Arguments: [x, y]*

lineTo
void lineTo(NVGContext ctx, in float x, in float y)

Adds line segment from the last point in the path to the specified point.

moveTo
void moveTo(NVGContext ctx, in float x, in float y)

Starts new sub-path with specified point as first point.

moveTo
void moveTo(NVGContext ctx, in float[] args)

Starts new sub-path with specified point as first point. Arguments: [x, y]*

pathWinding
void pathWinding(NVGContext ctx, NVGWinding dir)
void pathWinding(NVGContext ctx, NVGSolidity dir)

Sets the current sub-path winding, see NVGWinding and NVGSolidity.

quadTo
void quadTo(NVGContext ctx, in float[] args)

Adds quadratic bezier segment from last point in the path via a control point to the specified point. Arguments: [cx, cy, x, y]*

quadTo
void quadTo(NVGContext ctx, in float cx, in float cy, in float x, in float y)

Adds quadratic bezier segment from last point in the path via a control point to the specified point.

rect
void rect(NVGContext ctx, in float x, in float y, in float w, in float h)

Creates new rectangle shaped sub-path.

rect
void rect(NVGContext ctx, in float[] args)

Creates new rectangle shaped sub-path. Arguments: [x, y, w, h]*

roundedRect
void roundedRect(NVGContext ctx, in float x, in float y, in float w, in float h, in float radius)

Creates new rounded rectangle shaped sub-path.

roundedRect
void roundedRect(NVGContext ctx, in float[] args)

Creates new rounded rectangle shaped sub-path. Arguments: [x, y, w, h, radius]*

roundedRectEllipse
void roundedRectEllipse(NVGContext ctx, in float x, in float y, in float w, in float h, in float rw, in float rh)

Creates new rounded rectangle shaped sub-path. Specify ellipse width and height to round corners according to it.

roundedRectEllipse
void roundedRectEllipse(NVGContext ctx, in float[] args)

Creates new rounded rectangle shaped sub-path. Specify ellipse width and height to round corners according to it. Arguments: [x, y, w, h, rw, rh]*

roundedRectVarying
void roundedRectVarying(NVGContext ctx, in float x, in float y, in float w, in float h, in float radTopLeft, in float radTopRight, in float radBottomRight, in float radBottomLeft)

Creates new rounded rectangle shaped sub-path. This one allows you to specify different rounding radii for each corner.

roundedRectVarying
void roundedRectVarying(NVGContext ctx, in float[] args)

Creates new rounded rectangle shaped sub-path. This one allows you to specify different rounding radii for each corner. Arguments: [x, y, w, h, radTopLeft, radTopRight, radBottomRight, radBottomLeft]*

stroke
void stroke(NVGContext ctx)

Fills the current path with current stroke style.

Picking API

This is picking API that works directly on paths, without rasterizing them first.

beginFrame resets picking state. Then you can create paths as usual, but there is a possibility to perform hit checks before rasterizing a path. Call either id assigning functions (currFillHitId/currStrokeHitId), or immediate hit test functions (hitTestCurrFill/hitTestCurrStroke) before rasterizing (i.e. calling fill or stroke) to perform hover effects, for example.

Also note that picking API is ignoring GPU affine transformation matrix. You can "untransform" picking coordinates before checking with gpuUntransformPoint.

Picking API completely ignores clipping. If you want to check for clip regions, you have to manually register them as fill/stroke paths, and perform the necessary logic. See hitTestForId function.

Picking api Enums

NVGPickKind
enum NVGPickKind

Pick type query. Used in hitTest and hitTestAll.

Picking api Functions

currFillHitId
void currFillHitId(NVGContext ctx, int id)

Marks the fill of the current path as pickable with the specified id. Note that you can create and mark path without rasterizing it.

currStrokeHitId
void currStrokeHitId(NVGContext ctx, int id)

Marks the stroke of the current path as pickable with the specified id. Note that you can create and mark path without rasterizing it.

hitTest
int hitTest(NVGContext ctx, in float x, in float y, NVGPickKind kind = NVGPickKind.All)

Returns the id of the pickable shape containing x,y or NVGNoPick if no shape was found.

hitTestAll
int[] hitTestAll(NVGContext ctx, in float x, in float y, NVGPickKind kind, int[] ids)

Fills ids with a list of the top most hit ids (from bottom to top) under the specified position. Returns the slice of ids.

hitTestCurrFill
bool hitTestCurrFill(NVGContext ctx, in float x, in float y)

Returns true if the given point is within the fill of the currently defined path. This operation can be done before rasterizing the current path.

hitTestCurrStroke
bool hitTestCurrStroke(NVGContext ctx, in float x, in float y)

Returns true if the given point is within the stroke of the currently defined path. This operation can be done before rasterizing the current path.

hitTestDG
int hitTestDG(NVGContext ctx, in float x, in float y, NVGPickKind kind, scope DG dg)

Call delegate dg for each path under the specified position (in no particular order). Returns the id of the path for which delegate dg returned true or NVGNoPick. dg is: bool delegate (int id, int order) -- order is path ordering (ascending).

hitTestForId
bool hitTestForId(NVGContext ctx, in int id, in float x, in float y, NVGPickKind kind = NVGPickKind.All)

Returns true if the path with the given id contains x,y.

Clipping with paths

If scissoring is not enough for you, you can clip rendering with arbitrary path, or with combination of paths. Clip region is saved by save and restored by restore NanoVega functions. You can combine clip paths with various logic operations, see NVGClipMode.

Note that both clip and clipStroke are ignoring scissoring (i.e. clip mask is created as if there was no scissor set). Actual rendering is affected by scissors, though.

Clipping Aliases

clipFill
alias clipFill = clip

Sets current path as clipping region.

Clipping Enums

NVGClipMode
enum NVGClipMode

Mask combining more

Clipping Functions

clip
void clip(NVGContext ctx, NVGClipMode aclipmode = NVGClipMode.Union)

Sets current path as clipping region.

clipStroke
void clipStroke(NVGContext ctx, NVGClipMode aclipmode = NVGClipMode.Union)

Sets current path' stroke as clipping region.

Text

NanoVega allows you to load .ttf files and use the font to render text. You have to load some font, and set proper font size before doing anything with text, as there is no "default" font provided by NanoVega. Also, don't forget to check return value of createFont(), 'cause NanoVega won't fail if it cannot load font, it will silently try to render nothing.

The appearance of the text can be defined by setting the current text style and by specifying the fill color. Common text and font settings such as font size, letter spacing and text align are supported. Font blur allows you to create simple text effects such as drop shadows.

At render time the font face can be set based on the font handles or name.

Font measure functions return values in local space, the calculations are carried in the same resolution as the final rendering. This is done because the text glyph positions are snapped to the nearest pixels sharp rendering.

The local space means that values are not rotated or scale as per the current transformation. For example if you set font size to 12, which would mean that line height is 16, then regardless of the current scaling and rotation, the returned line height is always 16. Some measures may vary because of the scaling since aforementioned pixel snapping.

While this may sound a little odd, the setup allows you to always render the same way regardless of scaling. I.e. following works regardless of scaling:

1 string txt = "Text me up.";
2 vg.textBounds(x, y, txt, bounds);
3 vg.beginPath();
4 vg.roundedRect(bounds[0], bounds[1], bounds[2]-bounds[0], bounds[3]-bounds[1], 6);
5 vg.fill();

Note: currently only solid color fill is supported for text.

Text api Functions

addFontsFrom
void addFontsFrom(NVGContext ctx, NVGContext source)

Add fonts from another context. This is more effective than reloading fonts, 'cause font data will be shared.

charOutline
NVGPathOutline charOutline(NVGContext ctx, dchar dch)

Returns glyph outlines as array of commands. Vertical 0 is baseline. The glyph is not scaled in any way, so you have to use NanoVega transformations instead. Returns null if there is no such glyph, or current font is not scalable.

charPathBounds
bool charPathBounds(NVGContext ctx, dchar dch, float[] bounds)

Returns bounds of the glyph outlines. Vertical 0 is baseline. The glyph is not scaled in any way. Returns false if there is no such glyph, or current font is not scalable.

charToPath
bool charToPath(NVGContext ctx, dchar dch, float[] bounds = null)

Adds glyph outlines to the current path. Vertical 0 is baseline. The glyph is not scaled in any way, so you have to use NanoVega transformations instead. Returns false if there is no such glyph, or current font is not scalable.

createFont
int createFont(NVGContext ctx, const(char)[] name, const(char)[] path)

Creates font by loading it from the disk from specified file name. Returns handle to the font or FONS_INVALID (aka -1) on error. Use "fontname:noaa" as name to turn off antialiasing (if font driver supports that).

createFontMem
int createFontMem(NVGContext ctx, const(char)[] name, ubyte* data, int ndata, bool freeData)

Creates font by loading it from the specified memory chunk. Returns handle to the font or FONS_INVALID (aka -1) on error. Won't free data on error.

findFont
int findFont(NVGContext ctx, const(char)[] name)

Finds a loaded font of specified name, and returns handle to it, or FONS_INVALID (aka -1) if the font is not found.

fontBlur
void fontBlur(NVGContext ctx, float blur)

Sets the blur of current text style.

fontBlur
float fontBlur(NVGContext ctx)

Gets the blur of current text style.

fontFace
void fontFace(NVGContext ctx, const(char)[] font)

Sets the font face based on specified name of current text style.

fontFaceId
void fontFaceId(NVGContext ctx, int font)

Sets the font face based on specified id of current text style.

fontFaceId
int fontFaceId(NVGContext ctx)

Gets the font face based on specified id of current text style.

fontSize
float fontSize(NVGContext ctx)

Gets the font size of current text style.

fontSize
void fontSize(NVGContext ctx, float size)

Sets the font size of current text style.

kill
void kill(ref NVGPathOutline ol)

Destroy glyph outiline and free allocated memory.

text
float text(NVGContext ctx, float x, float y, const(T)[] str)

Draws text string at specified location. Returns next x position.

textAlign
void textAlign(NVGContext ctx, NVGTextAlign talign)
void textAlign(NVGContext ctx, NVGTextAlign.H h)
void textAlign(NVGContext ctx, NVGTextAlign.V v)
void textAlign(NVGContext ctx, NVGTextAlign.H h, NVGTextAlign.V v)
void textAlign(NVGContext ctx, NVGTextAlign.V v, NVGTextAlign.H h)

Sets the text align of current text style, see NVGTextAlign for options.

textAlign
NVGTextAlign textAlign(NVGContext ctx)

Gets the text align of current text style, see NVGTextAlign for options.

textBounds
float textBounds(NVGContext ctx, float x, float y, const(T)[] str, float[] bounds)

Measures the specified text string. Parameter bounds should be a float[4], if the bounding box of the text should be returned. The bounds value are [xmin, ymin, xmax, ymax] Returns the horizontal advance of the measured text (i.e. where the next character should drawn). Measured values are returned in local coordinate space.

textBox
void textBox(NVGContext ctx, float x, float y, float breakRowWidth, const(T)[] str)

Draws multi-line text string at specified location wrapped at the specified width. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation).

textBoxBounds
void textBoxBounds(NVGContext ctx, float x, float y, float breakRowWidth, const(T)[] str, float[] bounds)

Measures the specified text string. Parameter bounds should be a float[4], if the bounding box of the text should be returned. The bounds value are [xmin, ymin, xmax, ymax] Returns the horizontal advance of the measured text (i.e. where the next character should drawn). Measured values are returned in local coordinate space.

textBreakLines
NVGTextRow!T[] textBreakLines(NVGContext ctx, const(T)[] str, float breakRowWidth, NVGTextRow!T[] rows)
int textBreakLines(NVGContext ctx, const(T)[] str, float breakRowWidth, scope DG dg)

Breaks the specified text into lines. White space is stripped at the beginning of the rows, the text is split at word boundaries or when new-line characters are encountered. Words longer than the max width are slit at nearest character (i.e. no hyphenation).

textExtents
void textExtents(NVGContext ctx, const(T)[] str, float* w, float* h)

Measures the specified text string. Returns horizontal and vertical sizes of the measured text. Measured values are returned in local coordinate space.

textFontAscender
float textFontAscender(NVGContext ctx)

Returns font ascender (positive), measured in local coordinate space.

textFontDescender
float textFontDescender(NVGContext ctx)

Returns font descender (negative), measured in local coordinate space.

textFontHeight
float textFontHeight(NVGContext ctx)

Returns font line height (without line spacing), measured in local coordinate space.

textGlyphPositions
NVGGlyphPosition[] textGlyphPositions(NVGContext ctx, float x, float y, const(T)[] str, NVGGlyphPosition[] positions)
int textGlyphPositions(NVGContext ctx, float x, float y, const(T)[] str, scope DG dg)

Calculates the glyph x positions of the specified text. Measured values are returned in local coordinate space.

textLetterSpacing
float textLetterSpacing(NVGContext ctx)

Gets the letter spacing of current text style.

textLetterSpacing
void textLetterSpacing(NVGContext ctx, float spacing)

Sets the letter spacing of current text style.

textLineHeight
void textLineHeight(NVGContext ctx, float lineHeight)

Sets the proportional line height of current text style. The line height is specified as multiple of font size.

textLineHeight
float textLineHeight(NVGContext ctx)

Gets the proportional line height of current text style. The line height is specified as multiple of font size.

textMetrics
void textMetrics(NVGContext ctx, float* ascender, float* descender, float* lineh)

Returns the vertical metrics based on the current text style. Measured values are returned in local coordinate space.

textWidth
float textWidth(NVGContext ctx, const(T)[] str)

Measures the specified text string. Returns horizontal size of the measured text. Measured values are returned in local coordinate space.

Text api Structs

NVGGlyphPosition
struct NVGGlyphPosition

Glyph position info.

NVGPathOutline
struct NVGPathOutline

charOutline will return NVGPathOutline.

NVGTextAlign
struct NVGTextAlign

Text align.

NVGTextRow
struct NVGTextRow(CT)

Text row storage.

TextBoundsIterator
struct TextBoundsIterator

Returns iterator which you can use to calculate text bounds and advancement. This is usable when you need to do some text layouting with wrapping, to avoid guesswork ("will advancement for this space stay the same?"), and Schlemiel's algorithm. Note that you can copy the returned struct to save iterator state.

Recording and Replaying Pathes

This API is hightly experimental, and is subject to change. While I will try to keep it compatible in future NanoVega versions, no promises are made. Also note that NanoVega rendering is quite fast, so you prolly don't need this functionality. If you really want to render-once-and-copy, consider rendering to FBO, and use imaging API to blit FBO texture instead. Note that NanoVega supports alot of blit/copy modes.

It is posible to record render commands and replay them later. This will allow you to skip possible time-consuming tesselation stage. Potential uses of this feature is, for example, rendering alot of similar complex paths, like game tiles, or enemy sprites.

Path replaying has some limitations, though: you cannot change stroke width, fringe size, tesselation tolerance, or rescale path. But you can change fill color/pattern, stroke color, translate and/or rotate saved paths.

Note that text rendering commands are not saved, as technically text rendering is not a path.

To translate or rotate a record, use affineGPU API call.

To record render commands, you must create new path set with newPathSet function, then start recording with startRecording. You can cancel current recording with cancelRecording, or commit (save) recording with stopRecording.

You can resume recording with startRecording after stopRecording call. Calling cancelRecording will cancel only current recording session (i.e. it will forget everything from the very latest startRecording, not the whole record).

Finishing frame with endFrame will automatically commit current recording, and calling cancelFrame will cancel recording by calling cancelRecording.

Note that commit recording will clear current picking scene (but cancelling won't).

Calling startRecording without commiting or cancelling recoriding will commit.

Text output is not recorded now. Neither is scissor, so if you are using scissoring or text in your paths (UI, for example), things will not work as you may expect.

Path recording Aliases

NVGPathSet
alias NVGPathSet = NVGPathSetS*

Saved path set.

Path recording Functions

cancelRecording
void cancelRecording(NVGContext ctx)

Cancel path recording.

clear
void clear(NVGPathSet svp)

Clear path set contents. Will release some allocated memory (this function is meant to clear something that will be reused).

empty
bool empty(NVGPathSet svp)

Is the given path set empty? Empty path set can be null.

kill
void kill(ref NVGPathSet svp)

Destroy path set (frees all allocated memory).

newPathSet
NVGPathSet newPathSet(NVGContext ctx)

Create new empty path set.

replayRecording
void replayRecording(NVGContext ctx, NVGPathSet svp)
void replayRecording(NVGContext ctx, NVGPathSet svp, in auto ref NVGColor fillTint)

Replay saved path set.

replayRecording
void replayRecording(NVGContext ctx, NVGPathSet svp, in auto ref NVGColor fillTint, in auto ref NVGColor strokeTint)

Replay saved path set.

startBlockingRecording
void startBlockingRecording(NVGContext ctx, NVGPathSet svp)

Start path recording. svp should be alive until recording is cancelled or stopped.

startRecording
void startRecording(NVGContext ctx, NVGPathSet svp)

Start path recording. svp should be alive until recording is cancelled or stopped.

stopRecording
void stopRecording(NVGContext ctx)

Commit recorded paths. It is safe to call this when recording is not started.

Other

Other Enums

NVGTesselation
enum NVGTesselation

Bezier curve rasterizer.

Other Functions

nvgClampToByte
ubyte nvgClampToByte(T n)

this is branchless for ints on x86, and even for longs on x86_64

renderPathComplex
bool renderPathComplex(NVGContext ctx, int pathidx)

Returns "complex path" flag for the given render path.

renderPathCount
int renderPathCount(NVGContext ctx)

Returns number of tesselated pathes in context.

renderPathFillVertices
const(NVGVertex)[] renderPathFillVertices(NVGContext ctx, int pathidx)

Get vertices of "fill" triangle fan for the given render path. Can return empty slice.

renderPathStrokeVertices
const(NVGVertex)[] renderPathStrokeVertices(NVGContext ctx, int pathidx)

Get vertices of "stroke" triangle strip for the given render path. Can return empty slice.

renderPathWinding
NVGWinding renderPathWinding(NVGContext ctx, int pathidx)

Returns winding for the given render path.

tesselation
NVGTesselation tesselation(NVGContext ctx)

Group: context_management

tesselation
void tesselation(NVGContext ctx, NVGTesselation v)

Group: context_management

Other Manifest constants

scriptable
enum scriptable;

Annotation to indicate the marked function is compatible with arsd.script.

Other Static variables

NVG_DEFAULT_TESSELATOR
NVGTesselation NVG_DEFAULT_TESSELATOR;

Default tesselator for Bezier curves.

Other Structs

NVGVertex
struct NVGVertex

General NanoVega vertex struct. Contains geometry coordinates, and (sometimes unused) texture coordinates.

Detailed Description

Creating drawing context

The drawing context is created using platform specific constructor function.

NVGContext vg = nvgCreateContext();
You must use created context ONLY in that thread where you created it. There is no way to "transfer" context between threads. Trying to do so will lead to UB.
Never issue any commands outside of beginFrame/endFrame. Trying to do so will lead to UB.

Drawing shapes with NanoVega

Drawing a simple shape using NanoVega consists of four steps:

  • begin a new shape,
  • define the path to draw,
  • set fill or stroke,
  • and finally fill or stroke the path.
vg.beginPath();
vg.rect(100, 100, 120, 30);
vg.fillColor(nvgRGBA(255, 192, 0, 255));
vg.fill();

Calling beginPath will clear any existing paths and start drawing from blank slate. There are number of number of functions to define the path to draw, such as rectangle, rounded rectangle and ellipse, or you can use the common moveTo, lineTo, bezierTo and arcTo API to compose the paths step by step.

Understanding Composite Paths

Because of the way the rendering backend is built in NanoVega, drawing a composite path, that is path consisting from multiple paths defining holes and fills, is a bit more involved. NanoVega uses non-zero filling rule and by default, and paths are wound in counter clockwise order. Keep that in mind when drawing using the low level draw API. In order to wind one of the predefined shapes as a hole, you should call pathWinding(NVGSolidity.Hole), or pathWinding(NVGSolidity.Solid) after defining the path.

1 vg.beginPath();
2 vg.rect(100, 100, 120, 30);
3 vg.circle(120, 120, 5);
4 vg.pathWinding(NVGSolidity.Hole); // mark circle as a hole
5 vg.fillColor(nvgRGBA(255, 192, 0, 255));
6 vg.fill();

Rendering is wrong, what to do?

  • make sure you have created NanoVega context using nvgCreateContext call
  • make sure you have initialised OpenGL with stencil buffer
  • make sure you have cleared stencil buffer
  • make sure all rendering calls happen between beginFrame and endFrame
  • to enable more checks for OpenGL errors, add NVGContextFlag.Debug flag to nvgCreateContext

OpenGL state touched by the backend

The OpenGL back-end touches following states:

When textures are uploaded or updated, the following pixel store is set to defaults: GL_UNPACK_ALIGNMENT, GL_UNPACK_ROW_LENGTH, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_SKIP_ROWS. Texture binding is also affected. Texture updates can happen when the user loads images, or when new font glyphs are added. Glyphs are added as needed between calls to beginFrame and endFrame.

The data for the whole frame is buffered and flushed in endFrame. The following code illustrates the OpenGL state touched by the rendering code:

1 glUseProgram(prog);
2 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
3 glEnable(GL_CULL_FACE);
4 glCullFace(GL_BACK);
5 glFrontFace(GL_CCW);
6 glEnable(GL_BLEND);
7 glDisable(GL_DEPTH_TEST);
8 glDisable(GL_SCISSOR_TEST);
9 glDisable(GL_COLOR_LOGIC_OP);
10 glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
11 glStencilMask(0xffffffff);
12 glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
13 glStencilFunc(GL_ALWAYS, 0, 0xffffffff);
14 glActiveTexture(GL_TEXTURE1);
15 glActiveTexture(GL_TEXTURE0);
16 glBindBuffer(GL_UNIFORM_BUFFER, buf);
17 glBindVertexArray(arr);
18 glBindBuffer(GL_ARRAY_BUFFER, buf);
19 glBindTexture(GL_TEXTURE_2D, tex);
20 glUniformBlockBinding(... , GLNVG_FRAG_BINDING);

Meta

Suggestion Box / Bug Report