source: project/wiki/eggref/4/glls @ 30938

Last change on this file since 30938 was 30938, checked in by acharlton, 6 years ago

Document renderable maker data: argument

File size: 22.6 KB
Line 
1== glls
2[[toc:]]
3glls (GL Lisp Shaders) lets you write [[https://www.opengl.org/documentation/glsl/|GLSL]] (OpenGL Shader Language) shaders in a convenient pseudo-scheme language in Chicken Scheme. The compilation into GLSL happens at compile-time for zero run-time cost. Run-time compilation is also supported. To those that want to dynamically construct shaders: I solute you.
4
5In addition to the eponymous module, glls also provides the {{glls-render}} module. {{glls-render}} enhances glls to create automatic rendering functions for each pipeline. When compiled, these rendering functions are created in efficient C, although dynamic functions are also provided. See the section [[#automatic-render-functions|Automatic render functions]] for details.
6
7The idea for glls was hugely inspired by [[https://github.com/cbaggers/varjo|Varjo]]. Before learning about Varjo, I had never considered the possibility of writing shaders in anything but the GLSL. Seeing them being written in Lisp was a major, "Of course!" moment.
8
9That said, while this library bears some superficial resemblance to Varjo, the approach is quite different. While Varjo does a lot of work to validate the the lispy-glls expressions (including type checking), glls only performs cursory syntactic checking. The result of this is that one could probably write shaders in Varjo without knowing the GLSL and could be reasonably sure that those shaders would always compile to something that would mostly work. glls makes no such promises, so it is entirely possible to generate GLSL that won’t compile. Being able to understand GLSL code is therefore a prerequisite for successful shader debugging. The GLSL code output by glls is beautifully formatted, thanks to Alex Shinn’s amazing [[http://synthcode.com/scheme/fmt/|fmt]] library. fmt is responsible for far more than just the GLSL formatting, since it is basically a compiler of its own. The compilation portion of glsl is more or less a thin layer on top of fmt.
10
11
12=== Requirements
13* fmt
14* matchable
15* miscmacros
16* opengl-glew
17* srfi-42
18
19
20=== Documentation
21<parameter> glsl-version</parameter>
22
23The default GLSL version used by shaders. Defaults to {{330}}.
24
25
26==== Shaders
27<record> (shader TYPE SOURCE INPUTS OUTPUTS UNIFORMS PROGRAM)</record>
28
29Used to represent shaders. Returned by {{define-shader}} and {{create-shader}}. It should not typically be necessary to access the slots of this record.
30
31<macro> (define-shader SHADER-NAME GLLS-SHADER)</macro>
32
33Defines, for syntax and run-time, a new {{shader}} named {{NAME}}. The (unquoted) form {{GLLS-SHADER}} should conform to language defined in the section [[#the-glls-shader-language|The glls shader language]]. Before shaders are used, they must be compiled by OpenGL with {{compile-shader}}.
34
35<procedure> (create-shader GLLS-SHADER #!key INPUTS)</procedure>
36
37Creates a new {{shader}}. The form {{GLLS-SHADER}} should conform to language defined in the section [[#the-glls-shader-language|The glls shader language]]. The key {{INPUTS}} can be used to include additional inputs to the shader. Before shaders are used, they must be compiled by OpenGL with {{compile-shader}}.
38
39<procedure> (compile-glls GLLS-SHADER #!key INPUTS)</procedure>
40
41Returns the source string for a shader. The form {{GLLS-SHADER}} should conform to language defined in the section [[#the-glls-shader-language|The glls shader language]]. The key {{INPUTS}} can be used to include additional inputs to the shader.
42
43<procedure> (compile-shader SHADER)</procedure>
44
45Compile (in OpenGL) {{SHADER}}. Nothing is done if the shader has already been compiled. This typically does not need to be called, since {{compile-pipeline}} does so. Must be called while there is an active OpenGL context.
46
47
48==== Pipelines
49''Pipelines'' are the term that glsl uses to describe a collection of shaders that will be linked together. This is equivalent to a GL ''program'', just less ambiguously named.
50
51<record> (pipeline SHADERS ATTRIBUTES UNIFORMS PROGRAM)</record>
52
53Created with {{define-pipeline}} or {{create-pipeline}}, contains the data needed for a pipeline. {{SHADERS}} is the list of shader records. {{ATTRIBUTES}} and {{UNIFORMS}} are lists of the attributes and uniforms of the shader, specified as {{(name . type)}} pairs before compilation (with {{compile-pipeline}} or {{compile-pipelines}}) and {{(name location type)}} lists after compilation. {{PROGRAM}} is the GL ID of the program (always 0 before compilation).
54
55<macro> (define-pipeline PIPELINE-NAME . SHADERS)</macro>
56
57Defines, for syntax and run-time, a new {{pipeline}} named {{NAME}}. The {{SHADERS}} should either be forms conforming to language defined in the section [[#the-glls-shader-language|The glls shader language]], {{shader}}s defined by {{define-shader}}, or a mix of the two. Pipelines must have at least one vertex and one fragment shader to be able to compile. Before pipelines are used, they must be compiled by OpenGL with {{compile-pipeline}} or {{compile-pipelines}}.
58
59{{define-pipeline}} has additional effects when used with the {{glls-render}} module (see [[#automatic-render-functions|Automatic render functions]]).
60
61<procedure> (create-pipeline . SHADERS)</procedure>
62
63Creates a new {{pipeline}}. The {{SHADERS}} should either be forms conforming to language defined in the section [[#the-glls-shader-language|The glls shader language]], {{shader}}s, or a mix of the two. Pipelines must have at least one vertex and one fragment shader to be able to compile. Before pipelines are used, they must be compiled by OpenGL with {{compile-pipeline}} or {{compile-pipelines}}.
64
65<procedure> (compile-pipeline PIPELINE)</procedure>
66
67Compile (in OpenGL) the {{PIPELINE}} and sets its {{PROGRAM}} slot to the OpenGL program ID. Compiles all of the pipeline’s shaders with {{compile-shader}}. Must be called while there is an active OpenGL context.
68
69<procedure> (compile-pipelines)</procedure>
70
71Compile (as per {{compile-pipeline}}) all the pipelines defined by {{define-pipeline}} and {{create-pipeline}}. Must be called while there is an active OpenGL context.
72
73<procedure> (pipeline-uniform UNIFORM PIPELINE)</procedure>
74
75Return the location of {{UNIFORM}}. The {{PIPELINE}} must be compiled before this function can be used.
76
77<procedure> (pipeline-attribute ATTRIBUTE PIPELINE)</procedure>
78
79Return the location of {{ATTRIBUTE}}. The {{PIPELINE}} must be compiled before this function can be used.
80
81
82==== The glls shader language
83
84===== Shader syntax
85The shaders of glls – the forms that {{define-shader}}, {{define-pipeline}}, etc. expect – have the following syntax:
86
87    (<type> [#:version <version>] [#:extensions <extension>] [#:pragmas <pragma>]) <inputs> <body> -> <outputs>
88
89{{type}} is the keyword type of the shader. It must be one of {{#:vertex}}, {{#:fragment}}, {{#:geometry}}, {{#:tess-control}}, {{#:tess-evaluation}}, or {{#:compute}}.
90
91{{version}} is the integer version number of the shader, i.e. the number you would write at the top of the shader source (e.g. {{#version 410}}). Defaults to the {{glsl-version}} parameter.
92
93{{extensions}} is the list of GLSL extensions desired (in string form). E.g. {{'("GL_EXT_gpu_shader4 : enable")}}. Defaults to {{'()}}
94
95{{pragmas}} is the list of GLSL pragmas desired (in string form). E.g. {{'("optimize(on)")}}. Defaults to {{'()}}
96
97{{inputs}} is a list of the input variables to the shader. These are given in {{(name type)}} lists. The keyword {{#:uniform}} may be used, and all following inputs will be uniforms. E.g.: {{((vertex #:vec2) (color #:vec3) #:uniform (view-matrix #:mat4))}}
98
99{{body}} is the form representing the code of the shader. See the section [[#shader-lisp|Shader Lisp]] for an explanation of the kind of code that is expected.
100
101{{outputs}} is a list of the output variables from the shader. These are given in {{(name type)}} lists.
102
103
104===== Shader Lisp
105For the most part, the Lisp used to define glls shaders looks like Scheme with one notable difference: types must be specified whenever a variable or function is defined. Under the hood, forms are being passed to [[https://wiki.call-cc.org/eggref/4/fmt#c-as-s-expressions|fmt]], so everything that you can do there will work in glls. Details of the Lisp used for shaders is provided in the following sections.
106
107It should be possible to do almost anything in glls that you would want to do with the GLSL. Known exceptions to this is are: layout qualifiers (which I don’t feel are terribly relevant in the context of Scheme, at least not until uniform locations become prevalent), do-while loops (which have no Scheme analog), uniform blocks (for no good reason), {{#error}}, {{#line}}, {{#undef}}, and struct uniforms (implementation reasons). Let me know if there are any features that you find lacking.
108
109Keep in mind that glls cannot do anything that the GLSL can’t, such as making anonymous or recursive functions.
110
111
112====== Variables and naming
113Symbols in glls are transformed from a Scheme style into the C style used in the GLSL. Letters after dashes are uppercased (i.e., symbols become camelCased). Symbols prefixed by {{gl:}} in glls become prefixed by {{gl_}} in GLSL.
114
115For programmer-defined variables this has little consequence. The importance of learning the renaming conventions comes when you want to call GLSL functions or variables. Examples of mappings between glls and GLSL names are: {{gl:position}} → {{gl_Position}}, {{float-bits-to-uint}} → {{floatBitsToUint}}, {{shadow-2d-proj-lod}} → {{shadow2DProjLod}}, and {{sampler-2d-ms-array}} → {{sampler2DMSArray}}. Two special cases are {{emit-vertex}} and {{end-primitive}} which are translated into the functions {{EmitVertex}} and {{EndPrimitive}} respectively (which, for some reason, go against the usual GLSL naming conventions).
116
117
118====== Types
119When defining variables or functions in glls, types must be supplied. Basic types (e.g. {{int}}, {{mat2x2}}) are given either as a symbol or keyword (e.g. {{int}}, {{#:mat2x2}}), whichever is preferred. Types with qualifiers (e.g. {{lowp float}}, {{out mediump vec2}}) are given as lists (e.g. {{(lowp float)}}, {{(out mediump vec2)}}).
120
121Arrays are specified as lists beginning with the keyword {{#:array}}. The next element in the list is the type, while the optional third element is the size. E.g. {{(#:array int 5)}}. When used with qualifiers, the array takes the place of the type, e.g. {{(highp (#:array float))}}.
122
123
124====== Functions
125GLSL functions and operators are all called like normal Lisp functions. In almost all cases the GLSL symbol (taking into account the renaming described in [[#variables-and-naming|Variables and naming]] can be used, while many operators can be called with their Scheme counterpart. The only operators that may not be used directly are {{|}}, {{||}}, {{|=}}, {{.}}, {{=}}, and array reference which must be called with their counterparts.
126
127The following is a mapping between glls aliases for GLSL functions and operators:
128
129* {{modulo}}: {{%}}
130* {{expt}}: {{pow}}
131* {{equal?}}, {{eqv?}}, {{eq}}, {{=}}: {{==}}
132* {{set!}}: {{=}}
133* {{and}}: {{&&}}
134* {{or}}: {{||}}
135* {{not}}: {{!}}
136* {{bitwise-and}}, {{bit-or}}: {{&}}
137* {{bitwise-ior}}, {{bit-or}}: {{|}}
138* {{bitwise-xor}}, {{bit-xor}}: {{^}}
139* {{bitwise-not}}, {{bit-not}}: {{~}}
140* {{arithmetic-shift}}: {{<<}}
141* {{field}}: {{.}} (struct field reference, e.g. {{(field point x)}} → {{point.x}})
142* {{swizzle}}: {{.}} (vector swizzling, e.g. {{(swizzle color r g)}} → {{color.rg}})
143* {{array-ref}}, {{vector-ref}}: {{[]}} (array reference, e.g. {{(array-ref a 4)}} → {{a[4]}})
144* {{length}}: {{.length()}} (vector length, e.g. {{(length vec)}} → {{vec.length()}}
145
146
147====== Definition
148Variables, functions, and records (structs) are defined much like they are in Scheme, with additional requirement of including types.
149
150    (define <name> <type> [<value>])
151
152Defines the variable {{name}}. When {{type}} is an array, a vector literal (eg. {{#(1 2 3)}}) may be used.
153
154    (define (<name> [(<parameter> <type>) ...]) <return-type> <body> ...)
155
156Defines the function {{name}}. The last expression in the body of a non-void function is automatically returned.
157
158    (let ((<name> <type> [<value>]) ...) <body> ...)
159
160Defines the supplied variables. When {{type}} is an array, a vector literal (eg. {{#(1 2 3)}}) may be used. Note that, unlike Scheme, the variables created will continue to exist outside of the {{let}} (until the extent of whatever lexical scope the {{let}} exists within). In other words, {{let}} does not introduce scope. Note also that variables defined in {{let}} are within the scope of variables that are subsequently defined in the same {{let}} (i.e. {{let}} functions like {{let*}} in Scheme, and in fact {{let*}} may be used if preferred).
161
162    (define-record <name> (<type> <field>) ...)
163
164Defines the struct {{name}}.
165
166
167====== Control
168The following can be used with identical syntax to scheme:
169
170    (if <test> <true> [<false>])
171   
172    (cond (<test> <result> ...) ... (else <result>))
173   
174    (case <key> ((<value> ...) <result> ...) ... (else <result>))
175   
176    (begin <body> ...)
177
178Keep in mind that they may only be used in the same place as their corresponding GLSL statements, with the exception of {{begin}}, which can only be used where it is possible to have multiple expressions.
179
180
181====== Iteration
182    (for <init> <condition> <update> <body> ...)
183
184GLSL style {{for}} loop.
185
186    (do-times (<var> [<start>] <end>) <body> ...)
187
188Equivalent to {{(for (define <var> #:int <start>) (< <var> <end>) (++ <var>) <body> ...)}}. {{start}} defaults to 0.
189
190    (while <condition> <body> ...)
191
192GLSL style {{while}} loop.
193
194
195====== Jumps
196All GLSL jumps ({{continue}}, {{break}}, {{return}}, {{discard}}) can be called like functions. Return may accept one argument. Keep in mind that the last expression in a non void function is automatically returned.
197
198
199====== Pre-processor
200The following forms can be used to add pre-processor directives:
201
202    (%define <name> [<value>])
203   
204    (%if <test> <true> [<false>])
205   
206    (%ifdef <value> <true> [<false>])
207   
208    (%ifndef <value> <true> [<false>])
209
210
211==== Automatic render functions
212By using the {{glls-render}} module, you can have glls automatically generate a function that will render an object with your glls shader. {{glls-render}} exports a new {{define-pipeline}} that defines a set of functions used for rendering and managing the objects that will be rendered. {{glls-render}} should not be used with the {{glls}} module: It re-exports everything that you need from {{glls}}.
213
214Recalling {{define-pipeline}}:
215
216    (define-pipeline PIPELINE-NAME . SHADERS)
217
218There is one difference that you need to know when calling {{glls-render}}’s {{define-pipeline}}: All shaders must include a list of the shader’s uniforms since the uniforms are the important information needed to derive rendering functions. This means that if you previously define some shaders (for example: {{my-vertex-shader}} and {{my-fragment-shader}}) and you wish to combine them in a pipeline, you ''must'' include the uniforms in the pipeline definition. This is done with a list that takes the form {{(SHADER uniform: [UNIFORM] ...)}}. This list must be present even if the shader does not use any uniforms. For example:
219
220    (define-pipeline my-pipeline
221      (my-vertex-shader uniform: mvp-matrix inverse-transpose-matrix)
222      (my-fragment-shader uniform:))
223
224Of course, if you are defining the shaders in the pipeline, then a separate list of uniforms is not necessary.
225
226{{glls-render}} causes {{define-pipeline}} to define several new functions. First is {{render-PIPELINE-NAME}}. {{render-PIPELINE-NAME}} takes one argument: a renderable object (see [[#renderables|Renderables]]).
227
228The {{render-PIPELINE-NAME}} function works differently depending on whether the {{define-pipeline}} has been compiled or interpreted (although the end results should stay the same). When {{define-pipeline}} is compiled, the resulting {{render-PIPELINE-NAME}} function compiled directly to efficient (non-branching) C. When {{define-pipeline}} is interpreted, {{render-PIPELINE-NAME}} calls a generic rendering function that is not nearly as fast.
229
230
231===== Renderables
232In order to use one of the pre-generated render functions, you must have something to render. That’s why {{define-pipeline}} also defines a function that constructs a renderable object: {{make-SHADER-NAME-renderable}}. This function takes a number of keyword arguments:
233
234* {{vao:}} – A VAO such as those returned by [[http://api.call-cc.org/doc/opengl-glew/make-vao|opengl-glew’s {{make-vao}}]]. I.e.: A VAO that binds an array of attributes – for each element in the pipeline – as well as an element array.
235* {{mode:}} – The drawing mode to use when drawing the elements of the VAO. Must be one of (opengl-glew’s): {{+points+}}, {{+line-strip+}}, {{+line-loop+}}, {{+lines+}}, {{+line-strip-adjacency+}}, {{+triangles+}}, {{+triangle-strip+}}, {{+triangle-fan+}}, {{+triangles-adjacency+}}, {{+triangle-strip-adjacency+}}, or {{+patches+}}. Defaults to {{+triangles+}}.
236* {{n-elements:}} – The number of elements (vertices) to draw.
237* {{element-type:}} – The type of the values in the VAO’s element array. Must be one of {{+unsigned-byte+}}, {{+unsigned-short+}}, or {{+unsigned-int+}}.
238* {{offset:}} – A byte offset to the location of the desired indices to draw.
239* {{data:}} – An optional pointer to an appropriate glls renderable object. If not provided, a fresh renderable object will be created. [[https://github.com/AlexCharlton/glls/blob/master/gllsRender.h|gllsRenderable.h]] defines the structs used for renderables. The are chosen based on the number of uniforms present in the pipeline.
240
241See the [[https://www.opengl.org/sdk/docs/man/html/glDrawElements.xhtml|{{glDrawElements}} documentation]] for more information about these expected arguments.
242
243{{make-SHADER-NAME-renderable}} also expects one keyword argument for each uniform in the pipeline. These arguments should either be an f32vector, an s32vector, a u32vector, a pointer to the uniform data, or – in the case of a texture – a fixnum. Even if the uniform is a single value (e.g. a float), it must still be passed as a vector (or a pointer). This lets the value of the uniform be updated independently of the renderable.
244
245Additionally, {{define-pipeline}} defines a number of renderable setters for each of the keyword arguments accepted by {{make-SHADER-NAME-renderable}}. These are named:
246
247* {{set-SHADER-NAME-renderable-vao!}}
248* {{set-SHADER-NAME-renderable-mode!}}
249* {{set-SHADER-NAME-renderable-n-elements!}}
250* {{set-SHADER-NAME-renderable-element-type!}}
251* {{set-SHADER-NAME-renderable-offset!}}
252
253And for each uniform in the pipeline, {{set-SHADER-NAME-renderable-UNIFORM-NAME!}} is created.
254
255
256===== Fast render functions
257When compiled, the render function defined by {{define-pipeline}} is actually a combination of three “fast” render functions: a begin render function, a render function, and an end render function. This is done so that, if desired, all of the renderables that belong to the same pipeline may be rendered at the same time, without needing to perform expensive calls like program changes or texture binding more than once. To use these functions, simply call the begin render function with the first renderable, then call the render function on all renderables (including the first), finally calling the end render function (with no arguments) to clean up.
258
259{{define-pipeline}} does not define all of these functions separately, but instead defines a single function with which to access them: {{PIPELINE-NAME-fast-render-functions}}. This function returns six values: the begin render function, the render function, the end render function, and pointers to those same C functions in that order.
260
261One major assumption must be kept in mind while working with the fast render functions: textures are only bound once. In other words: it is assumed that that all of the renderables belonging to the same pipeline share a common “sprite sheet” (or other shared texture type). If this assumption does not hold true, simply use the standard render function, or call the begin render function for every set of renderables that uses a separate texture.
262
263
264=== Examples
265These examples depends on the [[http://wiki.call-cc.org/eggref/4/glfw3|glfw3]] egg for window and context creation. The examples presented here illustrate only very basic shader definition and loading. For more complete examples, see the [[https://github.com/AlexCharlton/glls/tree/master/examples|examples directory]] of the source.
266
267Aside from knowing how to write glls shaders, only one macro, one function, and one record is necessary to use glls: {{define-pipeline}}, {{compile-pipelines}}, and the record {{pipeline}}. This example illustrates this minimal pipeline creation
268
269<enscript highlight="scheme">    
270(import chicken scheme)
271
272(use glls (prefix glfw3 glfw:) (prefix opengl-glew gl:))
273
274(define-pipeline foo
275  ((#:vertex) ((vertex #:vec2) (color #:vec3) #:uniform (mvp #:mat4))
276     (define (main) #:void
277       (set! gl:position (* mvp (vec4 vertex 0.0 1.0)))
278       (set! c color))
279     -> ((c #:vec3)))
280  ((#:fragment) ((c #:vec3))
281     (define (main) #:void
282       (set! frag-color (vec4 c 1.0)))
283     -> ((frag-color #:vec4))))
284
285(glfw:with-window (640 480 "Example" resizable: #f)
286   (gl:init)
287   (compile-pipelines)
288   (print foo)
289   (gl:use-program (pipeline-program foo)))
290</enscript>
291
292This example is similar to the first, but also illustrates the ability to define pipelines in different ways.
293
294<enscript highlight="scheme">    
295(import chicken scheme)
296
297(use glls (prefix glfw3 glfw:) (prefix opengl-glew gl:))
298
299(define-pipeline foo
300  ((#:vertex) ((vertex #:vec2) (color #:vec3) #:uniform (mvp #:mat4))
301     (define (main) #:void
302       (set! gl:position (* mvp (vec4 vertex 0.0 1.0)))
303       (set! c color))
304     -> ((c #:vec3)))
305  ((#:fragment) ((c #:vec3))
306     (define (main) #:void
307       (set! frag-color (vec4 c 1.0)))
308     -> ((frag-color #:vec4))))
309
310(define-shader bar (#:vertex)
311    ((vertex #:vec2) (color #:vec3) #:uniform (mvp #:mat4))
312  (define (main) #:void
313    (set! gl:position (* mvp (vec4 vertex 0.0 1.0)))
314    (set! c color))
315  -> ((c #:vec3)))
316
317(define-pipeline baz
318  bar
319  (cadr (pipeline-shaders foo)))
320
321(glfw:with-window (640 480 "Example" resizable: #f)
322   (gl:init)
323   (compile-pipelines)
324   (print foo)
325   (print baz))
326</enscript>
327
328
329=== Version history
330
331==== Version 0.2.0
33228 May 2014
333- Automatic render function generation
334- Removed {{eval}} from {{defpipeline}} (which broke some things when used in modules)
335- Renamed {{defpipeline}}, {{defshader}}
336
337
338==== Version 0.1.0
339* Initial release
340
341
342=== Roadmap
343Some features that are planned for glls:
344
345* Automatic creation and compilation of rendering functions for a given pipeline
346* Dynamic re-compilation of pipelines suited for REPL sessions
347
348
349=== Source repository
350Source available on [[https://github.com/AlexCharlton/glls|GitHub]].
351
352Bug reports and patches welcome! Bugs can be reported via GitHub or to alex.n.charlton at gmail.
353
354
355=== Author
356Alex Charlton
357
358
359=== Licence
360BSD
Note: See TracBrowser for help on using the repository browser.