1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # OpenGL graphics rendering library for embedded systems, version 2.0
19 # This is a low-level wrapper, it can be useful for developers already familiar
20 # with the C API of OpenGL. Most developers will prefer to use higher level
21 # wrappers such as `mnit` and `gammit`.
23 # Defines the annotations `glsl_vertex_shader` and `glsl_fragment_shader`
24 # applicable on string literals to check shader code using `glslangValidator`.
25 # The tool must be in PATH. It can be downloaded from
26 # https://www.khronos.org/opengles/sdk/tools/Reference-Compiler/
28 # Most services of this module are a direct wrapper of the underlying
29 # C library. If a method or class is not documented in Nit, refer to
30 # the official documentation by the Khronos Group at:
31 # http://www.khronos.org/opengles/sdk/docs/man/
34 new_annotation glsl_vertex_shader
35 new_annotation glsl_fragment_shader
40 #include <GLES2/gl2.h>
43 # OpenGL ES program to which we attach shaders
44 extern class GLProgram `{GLuint`}
45 # Create a new program
47 # The newly created instance should be checked using `is_ok
`.
48 new `{ return glCreateProgram(); `}
50 # Is this a valid program?
51 fun is_ok
: Bool `{ return glIsProgram(recv); `}
53 # Attach a `shader
` to this program
54 fun attach_shader(shader: GLShader) `{ glAttachShader(recv, shader); `}
56 # Set the location for the attribute by `name`
57 fun bind_attrib_location
(index
: Int, name
: String) import String.to_cstring
`{
58 GLchar *c_name = String_to_cstring(name);
59 glBindAttribLocation(recv, index, c_name);
62 # Get the location of the attribute by `name`
64 # Returns `-1` if there is no active attribute named `name`.
65 fun attrib_location
(name
: String): Int import String.to_cstring
`{
66 GLchar *c_name = String_to_cstring(name);
67 return glGetAttribLocation(recv, c_name);
70 # Get the location of the uniform by `name`
72 # Returns `-1` if there is no active uniform named `name`.
73 fun uniform_location
(name
: String): Int import String.to_cstring
`{
74 GLchar *c_name = String_to_cstring(name);
75 return glGetUniformLocation(recv, c_name);
78 # Query information on this program
79 fun query
(pname
: Int): Int `{
81 glGetProgramiv(recv, pname, &val);
85 # Try to link this program
87 # Check result using `in_linked` and `info_log`.
88 fun link
`{ glLinkProgram(recv); `}
90 # Is this program linked?
91 fun is_linked: Bool do return query(0x8B82) != 0
93 # Use this program for the following operations
94 fun use `{ glUseProgram(recv); `}
97 fun delete
`{ glDeleteProgram(recv); `}
99 # Has this program been deleted?
100 fun is_deleted: Bool do return query(0x8B80) != 0
102 # Validate whether this program can be executed in the current OpenGL state
104 # Check results using `is_validated
` and `info_log
`.
105 fun validate `{ glValidateProgram(recv); `}
107 # Boolean result of `validate`, must be called after `validate`
108 fun is_validated
: Bool do return query
(0x8B83) != 0
110 # Retrieve the information log of this program
112 # Useful with `link` and `validate`
113 fun info_log
: String import NativeString.to_s
`{
115 glGetProgramiv(recv, GL_INFO_LOG_LENGTH, &size);
116 GLchar *msg = malloc(size);
117 glGetProgramInfoLog(recv, size, NULL, msg);
118 return NativeString_to_s(msg);
121 # Number of active uniform in this program
123 # This should be the number of uniforms declared in all shader, except
124 # unused uniforms which may have been optimized out.
125 fun n_active_uniforms
: Int do return query
(0x8B86)
127 # Length of the longest uniform name in this program, including `\n`
128 fun active_uniform_max_length
: Int do return query
(0x8B87)
130 # Number of active attributes in this program
132 # This should be the number of uniforms declared in all shader, except
133 # unused uniforms which may have been optimized out.
134 fun n_active_attributes
: Int do return query
(0x8B89)
136 # Length of the longest uniform name in this program, including `\n`
137 fun active_attribute_max_length
: Int do return query
(0x8B8A)
139 # Number of shaders attached to this program
140 fun n_attached_shaders
: Int do return query
(0x8B85)
142 # Name of the active attribute at `index`
143 fun active_attrib_name
(index
: Int): String
145 var max_size
= active_attribute_max_length
146 return active_attrib_name_native
(index
, max_size
).to_s
148 private fun active_attrib_name_native
(index
, max_size
: Int): NativeString `{
149 char *name = malloc(max_size);
150 glGetActiveAttrib(recv, index, max_size, NULL, NULL, NULL, name);
154 # Size of the active attribute at `index`
155 fun active_attrib_size
(index
: Int): Int `{
157 glGetActiveAttrib(recv, index, 0, NULL, NULL, &size, NULL);
161 # Type of the active attribute at `index`
163 # May only be float related data types (single float, vectors and matrix).
164 fun active_attrib_type
(index
: Int): GLFloatDataType `{
166 glGetActiveAttrib(recv, index, 0, NULL, &type, NULL, NULL);
170 # Name of the active uniform at `index`
171 fun active_uniform_name
(index
: Int): String
173 var max_size
= active_attribute_max_length
174 return active_uniform_name_native
(index
, max_size
).to_s
176 private fun active_uniform_name_native
(index
, max_size
: Int): NativeString `{
177 char *name = malloc(max_size);
178 glGetActiveUniform(recv, index, max_size, NULL, NULL, NULL, name);
182 # Size of the active uniform at `index`
183 fun active_uniform_size
(index
: Int): Int `{
185 glGetActiveUniform(recv, index, 0, NULL, NULL, &size, NULL);
189 # Type of the active uniform at `index`
191 # May be any data type supported by OpenGL ES 2.0 shaders.
192 fun active_uniform_type
(index
: Int): GLDataType `{
194 glGetActiveUniform(recv, index, 0, NULL, &type, NULL, NULL);
199 # Abstract OpenGL ES shader object, implemented by `GLFragmentShader` and `GLVertexShader`
200 extern class GLShader `{GLuint`}
201 # Set the source of the shader
202 fun source=(code: NativeString) `{
203 glShaderSource
(recv
, 1, (GLchar const
**)&code
, NULL);
206 # Source of the shader, if available
208 # Returns `null` if the source is not available, usually when the shader
209 # was created from a binary file.
210 fun source: nullable String
212 var size = query(0x8B88)
213 if size == 0 then return null
214 return source_native(size).to_s
217 private fun source_native(size: Int): NativeString `{
218 GLchar *code
= malloc
(size
);
219 glGetShaderSource
(recv
, size
, NULL, code
);
223 # Query information on this shader
224 protected fun query(pname: Int): Int `{
226 glGetShaderiv
(recv
, pname
, &val
);
230 # Try to compile `source
` into a binary GPU program
232 # Check the result using `is_compiled
` and `info_log
`
233 fun compile `{ glCompileShader(recv); `}
235 # Has this shader been compiled?
236 fun is_compiled
: Bool do return query
(0x8B81) != 0
239 fun delete
`{ glDeleteShader(recv); `}
241 # Has this shader been deleted?
242 fun is_deleted: Bool do return query(0x8B80) != 0
244 # Is this a valid shader?
245 fun is_ok: Bool `{ return glIsShader(recv); `}
247 # Retrieve the information log of this shader
249 # Useful with `link` and `validate`
250 fun info_log
: String import NativeString.to_s
`{
252 glGetShaderiv(recv, GL_INFO_LOG_LENGTH, &size);
253 GLchar *msg = malloc(size);
254 glGetShaderInfoLog(recv, size, NULL, msg);
255 return NativeString_to_s(msg);
259 # An OpenGL ES 2.0 fragment shader
260 extern class GLFragmentShader
263 # Create a new fragment shader
265 # The newly created instance should be checked using `is_ok`.
266 new `{ return glCreateShader(GL_FRAGMENT_SHADER); `}
269 # An OpenGL ES 2.0 vertex shader
270 extern class GLVertexShader
273 # Create a new fragment shader
275 # The newly created instance should be checked using `is_ok
`.
276 new `{ return glCreateShader(GL_VERTEX_SHADER); `}
279 # An array of `Float` associated to a program variable
283 # Number of data per vertex
286 protected var glfloat_array
: GLfloatArray
288 init(index
, count
: Int, array
: Array[Float])
292 self.glfloat_array
= new GLfloatArray(array
)
295 fun attrib_pointer
do attrib_pointer_intern
(index
, count
, glfloat_array
)
296 private fun attrib_pointer_intern
(index
, count
: Int, array
: GLfloatArray) `{
297 glVertexAttribPointer(index, count, GL_FLOAT, GL_FALSE, 0, array);
300 fun enable
do enable_intern
(index
)
301 private fun enable_intern
(index
: Int) `{ glEnableVertexAttribArray(index); `}
303 fun draw_arrays_triangles do draw_arrays_triangles_intern(index, count)
304 private fun draw_arrays_triangles_intern(index, count: Int) `{
305 glDrawArrays
(GL_TRIANGLES, index
, count
);
309 # Low level array of `Float`
310 extern class GLfloatArray `{GLfloat *`}
311 new (array
: Array[Float]) import Array[Float].length
, Array[Float].[] `{
313 int len = Array_of_Float_length(array);
314 GLfloat *vertex_array = malloc(sizeof(GLfloat)*len);
315 for (i = 0; i < len; i ++) vertex_array[i] = Array_of_Float__index(array, i);
320 # General type for OpenGL enumerations
321 extern class GLEnum `{ GLenum `}
323 redef fun hash `{ return recv; `}
325 redef fun ==(o
) do return o
!= null and is_same_type
(o
) and o
.hash
== self.hash
328 # An OpenGL ES 2.0 error code
333 fun is_ok
: Bool do return is_no_error
335 # Is this not an error?
336 fun is_no_error
: Bool `{ return recv == GL_NO_ERROR; `}
338 fun is_invalid_enum: Bool `{ return recv == GL_INVALID_ENUM; `}
339 fun is_invalid_value
: Bool `{ return recv == GL_INVALID_VALUE; `}
340 fun is_invalid_operation: Bool `{ return recv == GL_INVALID_OPERATION; `}
341 fun is_invalid_framebuffer_operation
: Bool `{ return recv == GL_INVALID_FRAMEBUFFER_OPERATION; `}
342 fun is_out_of_memory: Bool `{ return recv == GL_OUT_OF_MEMORY; `}
346 if is_no_error
then return "No error"
347 if is_invalid_enum
then return "Invalid enum"
348 if is_invalid_value
then return "Invalid value"
349 if is_invalid_operation
then return "Invalid operation"
350 if is_invalid_framebuffer_operation
then return "invalid framebuffer operation"
351 if is_out_of_memory
then return "Out of memory"
352 return "Truely unknown error"
356 protected fun assert_no_gl_error
359 if not error
.is_ok
then
360 print
"GL error: {error}"
365 # Texture minifying function
367 # Used by: `GLES::tex_parameter_min_filter`
368 extern class GLTextureMinFilter
371 new nearest
`{ return GL_NEAREST; `}
372 new linear `{ return GL_LINEAR; `}
375 # Texture magnification function
377 # Used by: `GLES::tex_parameter_mag_filter`
378 extern class GLTextureMagFilter
381 new nearest
`{ return GL_NEAREST; `}
382 new linear `{ return GL_LINEAR; `}
383 new nearest_mipmap_nearest
`{ return GL_NEAREST_MIPMAP_NEAREST; `}
384 new linear_mipmap_nearest `{ return GL_LINEAR_MIPMAP_NEAREST; `}
385 new nearest_mipmap_linear
`{ return GL_NEAREST_MIPMAP_LINEAR; `}
386 new linear_mipmap_linear `{ return GL_LINEAR_MIPMAP_LINEAR; `}
389 # Wrap parameter of a texture
391 # Used by: `tex_parameter_wrap_*`
392 extern class GLTextureWrap
395 new clamp_to_edge
`{ return GL_CLAMP_TO_EDGE; `}
396 new mirrored_repeat `{ return GL_MIRRORED_REPEAT; `}
397 new repeat
`{ return GL_REPEAT; `}
402 # Used by: `tex_parameter_
*`
403 extern class GLTextureTarget
406 new flat `{ return GL_TEXTURE_2D; `}
407 new cube_map
`{ return GL_TEXTURE_CUBE_MAP; `}
411 private var gles = new GLES is lazy
414 # Entry points to OpenGL ES 2.0 services
415 fun gl: GLES do return sys.gles
417 # OpenGL ES 2.0 services
420 # Clear the color buffer to `red
`, `green
`, `blue
` and `alpha
`
421 fun clear_color(red, green, blue, alpha: Float) `{
422 glClearColor
(red
, green
, blue
, alpha
);
426 fun viewport(x, y, width, height: Int) `{ glViewport(x, y, width, height); `}
428 # Define front- and back-facing polygons
430 # Front-facing polygons are clockwise if `value`, counter-clockwise otherwise.
431 fun front_face
=(value
: Bool) `{ glFrontFace(value? GL_CW: GL_CCW); `}
433 # Specify whether front- or back-facing polygons can be culled, default is `back
` only
435 # One or both of `front
` or `back
` must be `true`. If you want to deactivate culling
436 # use `(new GLCap.cull_face
).disable
`.
438 # Require: `front
or back
`
439 fun cull_face(front, back: Bool)
441 assert not (front or back)
442 cull_face_native(front, back)
445 private fun cull_face_native(front, back: Bool) `{
446 glCullFace
(front
? back
? GL_FRONT_AND_BACK: GL_BACK: GL_FRONT);
450 fun clear(buffer: GLBuffer) `{ glClear(buffer); `}
452 # Last error from OpenGL ES 2.0
453 fun error
: GLError `{ return glGetError(); `}
455 # Query the boolean value at `key
`
456 private fun get_bool(key: Int): Bool `{
458 glGetBooleanv
(key
, &val
);
459 return val
== GL_TRUE;
462 # Query the floating point value at `key
`
463 private fun get_float(key: Int): Float `{
465 glGetFloatv
(key
, &val
);
469 # Query the integer value at `key
`
470 private fun get_int(key: Int): Int `{
472 glGetIntegerv
(key
, &val
);
476 # Does this driver support shader compilation?
478 # Should always return `true` in OpenGL ES 2.0 and 3.0.
479 fun shader_compiler: Bool do return get_bool(0x8DFA)
481 # Set the texture minifying function
483 # Foreign: glTexParameter with GL_TEXTURE_MIN_FILTER
484 fun tex_parameter_min_filter(target: GLTextureTarget, value: GLTextureMinFilter) `{
485 glTexParameteri
(target
, GL_TEXTURE_MIN_FILTER, value
);
488 # Set the texture magnification function
490 # Foreign: glTexParameter with GL_TEXTURE_MAG_FILTER
491 fun tex_parameter_mag_filter(target: GLTextureTarget, value: GLTextureMagFilter) `{
492 glTexParameteri
(target
, GL_TEXTURE_MAG_FILTER, value
);
495 # Set the texture wrap parameter for coordinates _s_
497 # Foreign: glTexParameter with GL_TEXTURE_WRAP_S
498 fun tex_parameter_wrap_s(target: GLTextureTarget, value: GLTextureWrap) `{
499 glTexParameteri
(target
, GL_TEXTURE_WRAP_S, value
);
502 # Set the texture wrap parameter for coordinates _t_
504 # Foreign: glTexParameter with GL_TEXTURE_WRAP_T
505 fun tex_parameter_wrap_t(target: GLTextureTarget, value: GLTextureWrap) `{
506 glTexParameteri
(target
, GL_TEXTURE_WRAP_T, value
);
510 # Float related data types of OpenGL ES 2.0 shaders
512 # Only data types supported by shader attributes, as seen with
513 # `GLProgram::active_attrib_type
`.
514 extern class GLFloatDataType
517 fun is_float: Bool `{ return recv == GL_FLOAT; `}
518 fun is_float_vec2
: Bool `{ return recv == GL_FLOAT_VEC2; `}
519 fun is_float_vec3: Bool `{ return recv == GL_FLOAT_VEC3; `}
520 fun is_float_vec4
: Bool `{ return recv == GL_FLOAT_VEC4; `}
521 fun is_float_mat2: Bool `{ return recv == GL_FLOAT_MAT2; `}
522 fun is_float_mat3
: Bool `{ return recv == GL_FLOAT_MAT3; `}
523 fun is_float_mat4: Bool `{ return recv == GL_FLOAT_MAT4; `}
525 # Instances of `GLFloatDataType` can be equal to instances of `GLDataType`
528 return o
!= null and o
isa GLFloatDataType and o
.hash
== self.hash
532 # All data types of OpenGL ES 2.0 shaders
534 # These types can be used by shader uniforms, as seen with
535 # `GLProgram::active_uniform_type`.
536 extern class GLDataType
537 super GLFloatDataType
539 fun is_int
: Bool `{ return recv == GL_INT; `}
540 fun is_int_vec2: Bool `{ return recv == GL_INT_VEC2; `}
541 fun is_int_vec3
: Bool `{ return recv == GL_INT_VEC3; `}
542 fun is_int_vec4: Bool `{ return recv == GL_INT_VEC4; `}
543 fun is_bool
: Bool `{ return recv == GL_BOOL; `}
544 fun is_bool_vec2: Bool `{ return recv == GL_BOOL_VEC2; `}
545 fun is_bool_vec3
: Bool `{ return recv == GL_BOOL_VEC3; `}
546 fun is_bool_vec4: Bool `{ return recv == GL_BOOL_VEC4; `}
547 fun is_sampler_2d
: Bool `{ return recv == GL_SAMPLER_2D; `}
548 fun is_sampler_cube: Bool `{ return recv == GL_SAMPLER_CUBE; `}
551 # Set of buffers as a bitwise OR mask, used by `GLES::clear`
554 # var buffers = (new GLBuffer).color.depth
557 extern class GLBuffer `{ GLbitfield `}
558 # Get an empty set of buffers
561 # Add the color buffer to the returned buffer set
562 fun color
: GLBuffer `{ return recv | GL_COLOR_BUFFER_BIT; `}
564 # Add the depth buffer to the returned buffer set
565 fun depth: GLBuffer `{ return recv | GL_DEPTH_BUFFER_BIT; `}
567 # Add the stencil buffer to the returned buffer set
568 fun stencil
: GLBuffer `{ return recv | GL_STENCIL_BUFFER_BIT; `}