licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 51708 | "Global OpenGL state, mostly related to the fixed-function stuff like blending"
@kwdef struct RenderState
# NOTE: these default values do not necessarily represent the default values
# of a new OpenGL context.
color_write_mask::vRGBA{Bool} = Vec(true, true, true, true)
depth_write::Bool = true
cull_mode::E_FaceCullModes = FaceCullModes.off
# Viewport and scissor rectangles are 1-based, not 0-based.
viewport::Box2Di = Box2Di(min=v2i(0, 0), max=v2i(1, 1)) # Dummy initial value
scissor::Optional{Box2Di} = nothing
# TODO: Changing viewport Y axis and depth (how can my matrix math support this depth mode?): https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glClipControl.xhtml
# There can be different blend modes for color vs alpha.
blend_mode::@NamedTuple{rgb::BlendStateRGB, alpha::BlendStateAlpha} = (
rgb = make_blend_opaque(BlendStateRGB),
alpha = make_blend_opaque(BlendStateAlpha)
)
depth_test::E_ValueTests = ValueTests.pass
# There can be different stencil behaviors for front-faces vs back-faces.
stencil_test::Union{StencilTest, @NamedTuple{front::StencilTest, back::StencilTest}} = StencilTest()
stencil_result::Union{StencilResult, @NamedTuple{front::StencilResult, back::StencilResult}} = StencilResult()
stencil_write_mask::Union{GLuint, @NamedTuple{front::GLuint, back::GLuint}} = ~zero(GLuint)
end
"GPU- and context-specific constants"
struct Device
# The max supported OpenGL major and minor version.
# You can assume it's at least 4.6.
gl_version::NTuple{2, Int}
# The name of the graphics device.
# Can help you double-check that you didn't accidentally start on the integrated GPU.
gpu_name::String
# Texture/sampler anisotropy can be between 1.0 and this value.
max_anisotropy::Float32
# Compute shader limitations:
max_work_group_size::v3u
max_threads_per_workgroup::UInt
max_work_groups_per_dispatch::v3u
# The max number of individual float/int/bool uniform values
# that can exist in a shader.
# Guaranteed by OpenGL to be at least 1024.
max_uniform_components_in_vertex_shader::Int
max_uniform_components_in_fragment_shader::Int
#TODO: Other shader types
# The maximum byte size of a UBO.
max_uniform_block_byte_size::Int
# The number of available UBO slots for programs to share.
n_uniform_block_slots::Int
# The number of UBO's that a single shader can reference at once.
max_uniform_blocks_in_vertex_shader::Int
max_uniform_blocks_in_fragment_shader::Int
#TODO: Other shader types
# The number of available SSBO slots for programs to share.
n_storage_block_slots::Int
# The number of SSBO's that a single shader can reference at once.
max_storage_blocks_in_vertex_shader::Int
max_storage_blocks_in_fragment_shader::Int
#TODO: Other shader types
# Driver hints about thresholds you should not cross or else performance gets bad:
recommended_max_mesh_vertices::Int
recommended_max_mesh_indices::Int
# Limits to the amount of stuff attached to Targets:
max_target_color_attachments::Int
max_target_draw_buffers::Int
end
"Reads the device constants from OpenGL using the current context"
function Device(window::GLFW.Window)
return Device((GLFW.GetWindowAttrib(window, GLFW.CONTEXT_VERSION_MAJOR),
GLFW.GetWindowAttrib(window, GLFW.CONTEXT_VERSION_MINOR)),
unsafe_string(glGetString(GL_RENDERER)),
get_from_ogl(GLfloat, glGetFloatv, GL_MAX_TEXTURE_MAX_ANISOTROPY),
v3u(get_from_ogl(GLint, glGetIntegeri_v, GL_MAX_COMPUTE_WORK_GROUP_SIZE, 0),
get_from_ogl(GLint, glGetIntegeri_v, GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1),
get_from_ogl(GLint, glGetIntegeri_v, GL_MAX_COMPUTE_WORK_GROUP_SIZE, 2)),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS),
v3u(get_from_ogl(GLint, glGetIntegeri_v, GL_MAX_COMPUTE_WORK_GROUP_COUNT, 0),
get_from_ogl(GLint, glGetIntegeri_v, GL_MAX_COMPUTE_WORK_GROUP_COUNT, 1),
get_from_ogl(GLint, glGetIntegeri_v, GL_MAX_COMPUTE_WORK_GROUP_COUNT, 2)),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_VERTEX_UNIFORM_COMPONENTS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_FRAGMENT_UNIFORM_COMPONENTS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_UNIFORM_BLOCK_SIZE),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_UNIFORM_BUFFER_BINDINGS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_VERTEX_UNIFORM_BLOCKS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_FRAGMENT_UNIFORM_BLOCKS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_ELEMENTS_VERTICES),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_ELEMENTS_INDICES),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_COLOR_ATTACHMENTS),
get_from_ogl(GLint, glGetIntegerv, GL_MAX_DRAW_BUFFERS))
end
############################
# Context #
############################
"
The OpenGL context, which owns all state and data, including the GLFW window it belongs to.
This type is a per-thread singleton, because OpenGL only allows one active context per thread.
Like the other GL resource objects, you can't set the fields of this struct;
use the provided functions to change its state.
It's highly recommended to wrap a context with `bp_gl_context()`, as otherwise
Julia may juggle the Task running that context across threads, which breaks OpenGL.
"
mutable struct Context
window::GLFW.Window
vsync::E_VsyncModes
device::Device
debug_mode::Bool
supported_extensions::Vector{ExtensionRequest}
state::RenderState
active_program::Ptr_Program
active_mesh::Ptr_Mesh
active_ubos::Vector{Tuple{Ptr_Buffer, Interval{Int}}} # Handle and byte range
active_ssbos::Vector{Tuple{Ptr_Buffer, Interval{Int}}} # Handle and byte range
# You can register any number of callbacks to GLFW events here.
# Each is invoked with similar arguments to the raw callbacks minus the window handle.
glfw_callbacks_mouse_button::Vector{Base.Callable} # (GLFW.MouseButton, GLFW.Action, Int)
glfw_callbacks_scroll::Vector{Base.Callable} # (v2f)
glfw_callbacks_key::Vector{Base.Callable} # (GLFW.Key, Int, GLFW.Action, Int)
glfw_callbacks_char::Vector{Base.Callable} # (Char)
glfw_callbacks_joystick_connection::Vector{Base.Callable} # (GLFW.Joystick, Bool [if false, disconnection])
glfw_callbacks_window_focused::Vector{Base.Callable} # (Bool [if false, lost focus rather than gained])
glfw_callbacks_window_resized::Vector{Base.Callable} # (v2i)
# To interact with services, see the docstring for '@bp_service'.
services::Set{AbstractService}
unique_service_lookup::Dict{Type{<:AbstractService}, AbstractService}
function Context( size::v2i, title::String
;
extensions::Vector{ExtensionRequest} = collect(OGL_RECOMMENDED_EXTENSIONS),
vsync::E_VsyncModes = VsyncModes.off,
debug_mode::Bool = false, # See GL/debugging.jl
glfw_hints::Dict = Dict{Int32, Int32}(),
# Below are GLFW input settings that can be changed at will,
# but will be set to these specific values on initialization.
glfw_cursor::@ano_enum(Normal, Hidden, Centered) = Val(:Normal)
)::Context
# Create the window and OpenGL context.
if debug_mode
GLFW.WindowHint(GLFW.OPENGL_DEBUG_CONTEXT, true)
end
for (hint_name, hint_val) in glfw_hints
GLFW.WindowHint(Int32(hint_name), Int32(hint_val))
end
window = GLFW.CreateWindow(size..., title)
GLFW.MakeContextCurrent(window)
# Configure the window's inputs.
GLFW.SetInputMode(window, GLFW.CURSOR,
if glfw_cursor isa Val{:Normal}
GLFW.CURSOR_NORMAL
elseif glfw_cursor isa Val{:Hidden}
GLFW.CURSOR_HIDDEN
else
@assert(glfw_cursor isa Val{:Centered})
GLFW.CURSOR_DISABLED
end)
device = Device(window)
# Check the version that GLFW gave us.
gl_version_str::String = join(map(string, device.gl_version), '.')
@bp_check(
(device.gl_version[1] > OGL_MAJOR_VERSION) ||
((device.gl_version[1] == OGL_MAJOR_VERSION) && (device.gl_version[2] >= OGL_MINOR_VERSION)),
"OpenGL context is version ", device.gl_version[1], ".", device.gl_version[2],
", which is too old! B+ requires ", OGL_MAJOR_VERSION, ".", OGL_MINOR_VERSION,
". If you're on a laptop with a discrete GPU, make sure you're not accidentally",
" using the Integrated Graphics.",
" This program was using the GPU '", device.gpu_name, "'."
)
# Set up the Context singleton.
@bp_check(isnothing(get_context()), "A Context already exists on this thread")
con::Context = new(
window, vsync, device, debug_mode, [ ],
RenderState(),
Ptr_Program(), Ptr_Mesh(),
fill((Ptr_Buffer(), Interval{Int}(min=-1, max=-1)),
device.n_uniform_block_slots),
fill((Ptr_Buffer(), Interval{Int}(min=-1, max=-1)),
device.n_storage_block_slots),
Vector{Base.Callable}(), Vector{Base.Callable}(),
Vector{Base.Callable}(), Vector{Base.Callable}(),
Vector{Base.Callable}(), Vector{Base.Callable}(),
Vector{Base.Callable}(),
Set{AbstractService}(),
Dict{Type{<:AbstractService}, AbstractService}()
)
CONTEXTS_PER_THREAD[Threads.threadid()] = con
# Hook GLFW callbacks so that multiple independent sources can subscribe to these events.
GLFW.SetCharCallback(con.window, (window::GLFW.Window, c::Char) -> begin
for callback in con.glfw_callbacks_char
callback(c)
end
end)
GLFW.SetKeyCallback(con.window, (wnd::GLFW.Window,
key::GLFW.Key, scancode::Cint,
action::GLFW.Action, mods::Cint) -> begin
for callback in con.glfw_callbacks_key
callback(key, Int(scancode), action, Int(mods))
end
end)
GLFW.SetMouseButtonCallback(con.window, (window::GLFW.Window,
button::GLFW.MouseButton,
action::GLFW.Action,
mods::Cint) -> begin
for callback in con.glfw_callbacks_mouse_button
callback(button, action, Int(mods))
end
end)
GLFW.SetScrollCallback(con.window, (window::GLFW.Window,
delta_x::Float64, delta_y::Float64) -> begin
for callback in con.glfw_callbacks_scroll
callback(v2f(@f32(delta_x), @f32(delta_y)))
end
end)
GLFW.SetJoystickCallback((id::GLFW.Joystick, event::GLFW.DeviceConfigEvent) -> begin
for callback in con.glfw_callbacks_joystick_connection
callback(id, event == GLFW.CONNECTED)
end
end)
GLFW.SetWindowFocusCallback(con.window, (window::GLFW.Window, focused::Bool) -> begin
for callback in con.glfw_callbacks_window_focused
callback(focused != 0)
end
end)
GLFW.SetWindowSizeCallback(window, (wnd::GLFW.Window, new_x::Cint, new_y::Cint) -> begin
size = v2i(new_x, new_y)
for callback in con.glfw_callbacks_window_resized
callback(size)
end
end)
if debug_mode
glEnable(GL_DEBUG_OUTPUT)
# Below is the call for the original callback-based logging, in case we ever fix that:
# glDebugMessageCallback(ON_OGL_MSG_ptr, C_NULL)
end
# Check for the requested extensions.
for ext in extensions
if GLFW.ExtensionSupported(ext.name)
push!(con.supported_extensions, ext)
else
error_msg = string(
"OpenGL extension not supported: ", ext.name,
". If you're on a laptop with a discrete GPU, make sure you're not accidentally",
" using the Integrated Graphics. This program was using the GPU '",
unsafe_string(ModernGLbp.glGetString(GL_RENDERER)), "'."
)
if ext.mode == ExtensionMode.require
error(error_msg)
elseif ext.mode == ExtensionMode.prefer
@warn error_msg
elseif ext.mode == ExtensionMode.enable
@info error_msg
else
error("Unhandled case: ", ext.mode)
end
end
end
# Set up the OpenGL/window state.
refresh(con)
GLFW.SwapInterval(Int(con.vsync))
return con
end
end
export Context
@inline function Base.setproperty!(c::Context, name::Symbol, new_val)
if hasfield(RenderState, name)
set_render_state(Val(name), new_val, c)
elseif name == :vsync
set_vsync(c, new_val)
elseif name == :state
error("Don't set GL.Context::state manually; call one of the setter functions")
else
error("BplusApp.GL.Context has no field '", name, "'")
end
end
function Base.close(c::Context)
my_thread = Threads.threadid()
@bp_check(CONTEXTS_PER_THREAD[my_thread] === c,
"Trying to close a context on the wrong thread!")
# Clean up all services.
for service::AbstractService in c.services
service_internal_shutdown(service)
end
empty!(c.services)
empty!(c.unique_service_lookup)
GLFW.DestroyWindow(c.window)
setfield!(c, :window, GLFW.Window(C_NULL))
CONTEXTS_PER_THREAD[my_thread] = nothing
end
"
Runs the given code on a new OpenGL context, ensuring the context will get cleaned up.
This call blocks as if the context runs on this thread/task,
but for technical reasons it actually runs on a separate task.
The reason is that Julia tasks can get shifted to different threads
unless you explicitly mark them as `sticky`.
"
@inline function bp_gl_context(to_do::Base.Callable, args...; kw_args...)
task = Task() do
c::Optional{Context} = nothing
try
c = Context(args...; kw_args...)
return to_do(c)
finally
if exists(c)
# Make sure the mouse doesn't get stuck after a crash.
GLFW.SetInputMode(c.window, GLFW.CURSOR, GLFW.CURSOR_NORMAL)
close(c)
end
end
end
task.sticky = true
schedule(task)
return fetch(task)
end
export bp_gl_context
"Gets the current context, if it exists"
@inline get_context()::Optional{Context} = CONTEXTS_PER_THREAD[Threads.threadid()]
export get_context
"Gets the pixel size of the context's window."
get_window_size(context::Context = get_context()) = get_window_size(context.window)
function get_window_size(window::GLFW.Window)::v2i
window_size_data::NamedTuple = GLFW.GetWindowSize(window)
return v2i(window_size_data.width, window_size_data.height)
end
export get_window_size
"Checks whether the given extension (e.x. `GL_ARB_bindless_texture`) is supported in the Context"
extension_supported(name::String, context::Context = get_context()) = any(e.name == name for e in context.supported_extensions)
export extension_supported
"
You can call this after some external tool messes with OpenGL state,
to force the Context to read the new state and update itself.
However, keep in mind this function is pretty slow!
"
function refresh(context::Context)
# A handful of features will be left enabled permanently for simplicity;
# many can still be effectively disabled per-draw or per-asset.
glEnable(GL_BLEND)
glEnable(GL_STENCIL_TEST)
# Depth-testing is particularly important to keep on, because disabling it
# has a side effect of disabling any depth writes.
# You can always soft-disable depth tests by setting them to "Pass".
glEnable(GL_DEPTH_TEST)
# Point meshes must always specify their pixel size in their shaders;
# we don't bother with the global setting.
# See https://www.khronos.org/opengl/wiki/Primitive#Point_primitives
glEnable(GL_PROGRAM_POINT_SIZE)
# Don't force a "fixed index" for primitive restart;
# this would only be useful for OpenGL ES compatibility.
glDisable(GL_PRIMITIVE_RESTART_FIXED_INDEX)
# Force pixel upload/download to always use tightly-packed bytes, for simplicity.
glPixelStorei(GL_PACK_ALIGNMENT, 1)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0)
# Keep point sprite coordinates at their default origin: upper-left.
glPointParameteri(GL_POINT_SPRITE_COORD_ORIGIN, GL_UPPER_LEFT)
# Originally we enabled GL_TEXTURE_CUBE_MAP_SEAMLESS,
# because from my understanding virtually all implementations can easily do this nowadays,
# but that apparently doesn't do anything for bindless textures.
# Instead, we use the extension 'ARB_seamless_cubemap_per_texture'
# to make the 'seamless' setting a per-sampler parameter.
#glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS)
# Read the render state.
# Viewport:
viewport = Vec(get_from_ogl(GLint, 4, glGetIntegerv, GL_VIEWPORT)...)
viewport = Box2Di(min=convert(v2i, viewport.xy + 1),
max=convert(v2i, viewport.xy + 1 + viewport.zw - 1))
# Scissor:
if glIsEnabled(GL_SCISSOR_TEST)
scissor = Vec(get_from_ogl(GLint, 4, glGetIntegerv, GL_SCISSOR_BOX)...)
scissor = Box2Di(min=convert(v2i, scissor.xy + 1),
max=convert(v2i, scissor.xy + 1 + scissor.zw - 1))
else
scissor = nothing
end
# Simple one-off settings:
color_mask = get_from_ogl(GLboolean, 4, glGetBooleanv, GL_COLOR_WRITEMASK)
color_mask = Vec(map(b -> !iszero(b), color_mask))
depth_write = (get_from_ogl(GLboolean, glGetBooleanv, GL_DEPTH_WRITEMASK) != 0)
cull_mode = glIsEnabled(GL_CULL_FACE) ?
FaceCullModes.from(get_from_ogl(GLint, glGetIntegerv, GL_CULL_FACE_MODE)) :
FaceCullModes.off
depth_test = ValueTests.from(get_from_ogl(GLint, glGetIntegerv, GL_DEPTH_FUNC))
# Blending:
blend_constant = get_from_ogl(GLfloat, 4, glGetFloatv, GL_BLEND_COLOR)
blend_rgb = BlendStateRGB(
BlendFactors.from(get_from_ogl(GLint, glGetIntegerv, GL_BLEND_SRC_RGB)),
BlendFactors.from(get_from_ogl(GLint, glGetIntegerv, GL_BLEND_DST_RGB)),
BlendOps.from(get_from_ogl(GLint, glGetIntegerv, GL_BLEND_EQUATION_RGB)),
vRGBf(blend_constant[1:3])
)
blend_alpha = BlendStateAlpha(
BlendFactors.from(get_from_ogl(GLint, glGetIntegerv, GL_BLEND_SRC_ALPHA)),
BlendFactors.from(get_from_ogl(GLint, glGetIntegerv, GL_BLEND_DST_ALPHA)),
BlendOps.from(get_from_ogl(GLint, glGetIntegerv, GL_BLEND_EQUATION_ALPHA)),
blend_constant[4]
)
# Stencil:
stencils = ntuple(2) do i::Int # Front and back faces
ge_side = (GL_FRONT, GL_BACK)[i]
ge_test = (GL_STENCIL_FUNC, GL_STENCIL_BACK_FUNC)[i]
ge_ref = (GL_STENCIL_REF, GL_STENCIL_BACK_REF)[i]
ge_value_mask = (GL_STENCIL_VALUE_MASK, GL_STENCIL_BACK_VALUE_MASK)[i]
ge_on_fail = (GL_STENCIL_FAIL, GL_STENCIL_BACK_FAIL)[i]
ge_on_fail_depth = (GL_STENCIL_PASS_DEPTH_FAIL, GL_STENCIL_BACK_PASS_DEPTH_FAIL)[i]
ge_on_pass = (GL_STENCIL_PASS_DEPTH_PASS, GL_STENCIL_BACK_PASS_DEPTH_PASS)[i]
ge_write_mask = (GL_STENCIL_WRITEMASK, GL_STENCIL_BACK_WRITEMASK)[i]
return (
StencilTest(
ValueTests.from(get_from_ogl(GLint, glGetIntegerv, ge_test)),
get_from_ogl(GLint, glGetIntegerv, ge_ref),
reinterpret(GLuint, get_from_ogl(GLint, glGetIntegerv, ge_value_mask))
),
StencilResult(
StencilOps.from(get_from_ogl(GLint, glGetIntegerv, ge_on_fail)),
StencilOps.from(get_from_ogl(GLint, glGetIntegerv, ge_on_fail_depth)),
StencilOps.from(get_from_ogl(GLint, glGetIntegerv, ge_on_pass))
),
reinterpret(GLuint, get_from_ogl(GLint, glGetIntegerv, ge_write_mask))
)
end
if stencils[1] == stencils[2]
stencils = stencils[1]
else
stencils = (
(front=stencils[1][1], back=stencils[2][1]),
(front=stencils[1][2], back=stencils[2][2]),
(front=stencils[1][3], back=stencils[2][3])
)
end
# Assemble them all together and update the Context.
setfield!(context, :state, RenderState(
color_mask, depth_write,
cull_mode, viewport, scissor,
(rgb=blend_rgb, alpha=blend_alpha),
depth_test,
stencils...
))
# Get any important bindings.
setfield!(
context, :active_mesh,
Ptr_Mesh(get_from_ogl(GLint, glGetIntegerv, GL_VERTEX_ARRAY_BINDING))
)
setfield!(
context, :active_program,
Ptr_Program(get_from_ogl(GLint, glGetIntegerv, GL_CURRENT_PROGRAM))
)
for i in 1:length(context.active_ubos)
getfield(context, :active_ubos)[i] = (
Ptr_Buffer(
get_from_ogl(GLint, glGetIntegeri_v,
GL_UNIFORM_BUFFER_BINDING, i - 1)
),
Interval{Int}(
min=1 + get_from_ogl(GLint, glGetIntegeri_v,
GL_UNIFORM_BUFFER_START, i - 1),
size=get_from_ogl(GLint, glGetIntegeri_v,
GL_UNIFORM_BUFFER_SIZE, i - 1)
)
)
end
for i in 1:length(context.active_ssbos)
getfield(context, :active_ssbos)[i] = (
Ptr_Buffer(
get_from_ogl(GLint, glGetIntegeri_v,
GL_SHADER_STORAGE_BUFFER_BINDING, i - 1)
),
Interval{Int}(
min=1 + get_from_ogl(GLint, glGetIntegeri_v,
GL_SHADER_STORAGE_BUFFER_START, i - 1),
size=get_from_ogl(GLint, glGetIntegeri_v,
GL_SHADER_STORAGE_BUFFER_SIZE, i - 1)
)
)
end
# Update any attached services.
for service::AbstractService in context.services
service_internal_refresh(service)
end
end
export refresh
############################
# Render State getters #
############################
"Gets the stencil test being used for front-faces"
get_stencil_test_front(context::Context)::StencilTest =
(context.state.stencil_test isa StencilTest) ?
context.state.stencil_test :
context.state.stencil_test.front
"Gets the stencil test being used for back-faces"
get_stencil_test_back(context::Context)::StencilTest =
(context.state.stencil_test isa StencilTest) ?
context.state.stencil_test :
context.state.stencil_test.back
export get_stencil_test_front, get_stencil_test_back
"Gets the stencil ops being performed on front-faces"
get_stencil_results_front(context::Context)::StencilResult =
(context.state.stencil_result isa StencilResult) ?
context.state.stencil_result :
context.state.stencil_result.front
"Gets the stencil ops being performed on back-faces"
get_stencil_results_back(context::Context)::StencilResult =
(context.state.stencil_result isa StencilResult) ?
context.state.stencil_result :
context.state.stencil_result.back
export get_stencil_results_front, get_stencil_results_back
"Gets the stencil write mask for front-faces"
get_stencil_write_mask_front(context::Context)::GLuint =
(context.state.stencil_write_mask isa GLuint) ?
context.state.stencil_write_mask :
context.state.stencil_write_mask.front
"Gets the stencil write mask for back-faces"
get_stencil_write_mask_back(context::Context)::GLuint =
(context.state.stencil_write_mask isa GLuint) ?
context.state.stencil_write_mask :
context.state.stencil_write_mask.back
export get_stencil_write_mask_front, get_stencil_write_mask_back
############################
# Render State setters #
############################
function set_render_state(context::Context, state::RenderState)
set_culling(context, state.cull_mode)
set_color_writes(context, state.color_write_mask)
set_depth_test(context, state.depth_test)
set_depth_writes(context, state.depth_write)
set_blending(context, state.blend_mode.rgb)
set_blending(context, state.blend_mode.alpha)
if state.stencil_test isa StencilTest
set_stencil_test(context, state.stencil_test)
else
set_stencil_test(context, state.stencil_test.front, state.stencil_test.back)
end
if state.stencil_result isa StencilResult
set_stencil_result(context, state.stencil_result)
else
set_stencil_result(context, state.stencil_result.front, state.stencil_result.back)
end
if state.stencil_write_mask isa GLuint
set_stencil_write_mask(context, state.stencil_write_mask)
else
set_stencil_write_mask(context, state.stencil_write_mask.front, state.stencil_write_mask.back)
end
set_viewport(context, state.viewport)
set_scissor(context, state.scissor)
end
export set_render_state
function set_vsync(context::Context, sync::E_VsyncModes)
GLFW.SwapInterval(Int(context.vsync))
setfield(context, :vsync, sync)
end
export set_vsync
"Configures the culling of primitives that face away from (or towards) the camera"
function set_culling(context::Context, cull::E_FaceCullModes)
if context.state.cull_mode != cull
# Disable culling?
if cull == FaceCullModes.off
glDisable(GL_CULL_FACE)
else
# Re-enable culling?
if context.state.cull_mode == FaceCullModes.off
glEnable(GL_CULL_FACE)
end
glCullFace(GLenum(cull))
end
# Update the context's fields.
set_render_state_field!(context, :cull_mode, cull)
end
end
set_render_state(::Val{:cull_mode}, val::E_FaceCullModes, c::Context) = set_culling(c, val)
export set_culling
"Toggles the writing of individual color channels"
function set_color_writes(context::Context, enabled::vRGBA{Bool})
if context.state.color_write_mask != enabled
glColorMask(enabled...)
set_render_state_field!(context, :color_write_mask, enabled)
end
end
set_render_state(::Val{:color_write_mask}, val::vRGBA{Bool}, c::Context) = set_color_writes(c, val)
export set_color_writes
"Configures the depth test"
function set_depth_test(context::Context, test::E_ValueTests)
if context.state.depth_test != test
glDepthFunc(GLenum(test))
set_render_state_field!(context, :depth_test, test)
end
end
set_render_state(::Val{:depth_test}, val::E_ValueTests, c::Context) = set_depth_test(c, val)
export set_depth_test
"Toggles the writing of fragment depths into the depth buffer"
function set_depth_writes(context::Context, enabled::Bool)
if context.state.depth_write != enabled
glDepthMask(enabled)
set_render_state_field!(context, :depth_write, enabled)
end
end
set_render_state(::Val{:depth_write}, val::Bool, c::Context) = set_depth_writes(c, val)
export set_depth_writes
"Sets the blend mode for RGB and Alpha channels"
function set_blending(context::Context, blend::BlendStateRGBA)
blend_rgb = BlendStateRGB(blend.src, blend.dest, blend.op, blend.constant.rgb)
blend_a = BlendStateAlpha(blend.src, blend.dest, blend.op, blend.constant.a)
new_blend = (rgb=blend_rgb, alpha=blend_a)
current_blend = context.state.blend_mode
if new_blend != current_blend
glBlendFunc(GLenum(blend.src), GLenum(blend.dest))
glBlendEquation(GLenum(blend.op))
@bp_gl_assert(all(blend.constant >= 0) & all(blend.constant <= 1),
"Blend mode's constant value of ", blend.constant,
" is outside the allowed 0-1 range!")
glBlendColor(blend.constant...)
set_render_state_field!(context, :blend_mode, new_blend)
end
end
"Sets the blend mode for RGB channels, leaving Alpha unchanged"
function set_blending(context::Context, blend_rgb::BlendStateRGB)
if blend_rgb != context.state.blend_mode.rgb
blend_a::BlendStateAlpha = context.state.blend_mode.alpha
glBlendFuncSeparate(GLenum(blend_rgb.src), GLenum(blend_rgb.dest),
GLenum(blend_a.src), GLenum(blend_a.dest))
glBlendEquationSeparate(GLenum(blend_rgb.op), GLenum(blend_a.op))
glBlendColor(blend_rgb.constant..., blend_a.constant)
set_render_state_field!(context, :blend_mode, (
rgb = blend_rgb,
alpha = context.state.blend_mode.alpha
))
end
end
"Sets the blend mode for Alpha channels, leaving the RGB unchanged"
function set_blending(context::Context, blend_a::BlendStateAlpha)
if blend_a != context.state.blend_mode.alpha
blend_rgb::BlendStateRGB = context.state.blend_mode.rgb
glBlendFuncSeparate(GLenum(blend_rgb.src), GLenum(blend_rgb.dest),
GLenum(blend_a.src), GLenum(blend_a.dest))
glBlendEquationSeparate(GLenum(blend_rgb.op), GLenum(blend_a.op))
glBlendColor(blend_rgb.constant..., blend_a.constant)
set_render_state_field!(context, :blend_mode, (
rgb = context.state.blend_mode.rgb,
alpha = context.state.blend_mode.alpha
))
end
end
"Sets the blend mode for RGB and Alpha channels separately"
function set_blending(context::Context, blend_rgb::BlendStateRGB, blend_a::BlendStateAlpha)
new_blend = (rgb=blend_rgb, alpha=blend_a)
if new_blend != context.state.blend_mode
glBlendFuncSeparate(GLenum(blend_rgb.src), GLenum(blend_rgb.dest),
GLenum(blend_a.src), GLenum(blend_a.dest))
glBlendEquationSeparate(GLenum(blend_rgb.op), GLenum(blend_a.op))
glBlendColor(blend_rgb.constant..., blend_a.constant)
set_render_state_field!(context, :blend_mode, (
rgb = context.state.blend_mode.rgb,
alpha = blend_a
))
end
end
function set_blending(context::Context, val::@NamedTuple{rgb::BlendStateRGB, alpha::BlendStateAlpha})
set_blending(context, val.rgb, val.alpha)
end
set_render_state(::Val{:blend_mode}, val::@NamedTuple{rgb::BlendStateRGB, alpha::BlendStateAlpha}, c::Context) =
set_blending(c, val.rgb, val.alpha)
export set_blending
"Sets the stencil test to use, for both front- and back-faces"
function set_stencil_test(context::Context, test::StencilTest)
if context.state.stencil_test != test
glStencilFunc(GLenum(test.test), test.reference, test.bitmask)
set_render_state_field!(context, stencil_test, test)
end
end
"Sets the stencil test to use for front-faces, leaving the back-faces test unchanged"
function set_stencil_test_front(context::Context, test::StencilTest)
if get_stencil_test_front(context) != test
glStencilFuncSeparate(GL_FRONT, GLenum(test.test), test.reference, test.bitmask)
current_back::StencilTest = get_stencil_test_back(context)
set_render_state_field!(context, stencil_test, (front=test, back=current_back))
end
end
"Sets the stencil test to use for back-faces, leaving the front-faces test unchanged"
function set_stencil_test_back(context::Context, test::StencilTest)
if get_stencil_test_back(context) != test
glStencilFuncSeparate(GL_BACK, GLenum(test.test), test.reference, test.bitmask)
current_front::StencilTest = get_stencil_test_front(context)
set_render_state_field!(context, :stencil_test, (front=current_front, back=test))
end
end
"Sets the stencil test to use on front-faces and back-faces, separately"
function set_stencil_test(context::Context, front::StencilTest, back::StencilTest)
set_stencil_test_front(context, front)
set_stencil_test_back(context, back)
end
set_render_state(::Val{:stencil_test}, val::StencilTest, context::Context) = set_stencil_test(context, val)
@inline set_render_state(::Val{:stencil_test}, val::NamedTuple, context::Context) = set_stencil_test(context, val.front, val.back)
export set_stencil_test, set_stencil_test_front, set_stencil_test_back
"
Sets the stencil operations to perform based on the stencil and depth tests,
for both front- and back-faces.
"
function set_stencil_result(context::Context, ops::StencilResult)
if context.state.stencil_result != ops
glStencilOp(GLenum(ops.on_failed_stencil),
GLenum(ops.on_passed_stencil_failed_depth),
GLenum(ops.on_passed_all))
set_render_state_field!(context, :stencil_result, ops)
end
end
"Sets the stencil operations to use on front-faces, based on the stencil and depth tests"
function set_stencil_result_front(context::Context, ops::StencilResult)
if get_stencil_results_front(context) != ops
current_back_ops::StencilResult = get_stencil_results_back(context)
glStencilOpSeparate(GL_FRONT,
GLenum(ops.on_failed_stencil),
GLenum(ops.on_passed_stencil_failed_depth),
GLenum(ops.on_passed_all))
set_render_state_field!(context, :stencil_result, (
front=ops,
back=current_back_ops
))
end
end
"Sets the stencil operations to use on back-faces, based on the stencil and depth tests"
function set_stencil_result_back(context::Context, ops::StencilResult)
if get_stencil_results_back(context) != ops
current_front_ops::StencilResult = get_stencil_results_front(context)
glStencilOpSeparate(GL_BACK,
GLenum(ops.on_failed_stencil),
GLenum(ops.on_passed_stencil_failed_depth),
GLenum(ops.on_passed_all))
set_render_state_field!(context, :stencil_result, (
front=current_front_ops,
back=ops
))
end
end
"
Sets the stencil operations to use on front-faces and back-faces, separately,
based on the stencil and depth tests.
"
function set_stencil_result(context::Context, front::StencilResult, back::StencilResult)
set_stencil_result_front(context, front)
set_stencil_result_back(context, back)
end
set_render_state(::Val{:stencil_result}, val::StencilResult, context::Context) = set_stencil_result(context, val)
@inline set_render_state(::Val{:stencil_result}, val::NamedTuple, context::Context) = set_stencil_result(context, val.front, val.back)
export set_stencil_result, set_stencil_result_front, set_stencil_result_back
"Sets the bitmask which enables/disables bits of the stencil buffer for writing"
function set_stencil_write_mask(context::Context, mask::GLuint)
if context.state.stencil_write_mask != mask
glStencilMask(mask)
set_render_state_field!(context, :stencil_write_mask, mask)
end
end
"
Sets the bitmask which enables/disables bits of the stencil buffer for writing.
Only applies to front-facing primitives.
"
function set_stencil_write_mask_front(context::Context, mask::GLuint)
if get_stencil_write_mask_front(context) != mask
current_back_mask::GLuint = context.state.stencil_write_mask.back
glStencilMaskSeparate(GL_FRONT, mask)
set_render_state_field!(context, :stencil_write_mask, (
front=mask,
back=current_back_mask
))
end
end
"
Sets the bitmask which enables/disables bits of the stencil buffer for writing.
Only applies to back-facing primitives.
"
function set_stencil_write_mask_back(context::Context, mask::GLuint)
if get_stencil_write_mask_back(context) != mask
current_front_mask::GLuint = context.state.stencil_write_mask.front
glStencilMaskSeparate(GL_BACK, mask)
set_render_state_field!(context, :stencil_write_mask, (
front=current_front_mask,
back=mask
))
end
end
"
Sets the bitmasks which enable/disable bits of the stencil buffer for writing.
Applies different values to front-faces and back-faces.
"
function set_stencil_write_mask(context::Context, front::GLuint, back::GLuint)
set_stencil_write_mask_front(context, front)
set_stencil_write_mask_back(context, back)
end
set_render_state(::Val{:stencil_write_mask}, val::GLuint, c::Context) = set_stencil_write_mask(c, val)
@inline set_render_state(::Val{:stencil_write_mask}, val::NamedTuple, c::Context) = set_stencil_write_mask(c, val.front, val.back)
export set_stencil_write_mask, set_stencil_write_mask_front, set_stencil_write_mask_back
"
Changes the area of the screen which rendering outputs to,
in terms of pixels (using 1-based indices).
By default, the min/max corners of the render are the min/max corners of the screen,
but you can set this to render to a subset of the whole screen.
The max corner is inclusive.
"
function set_viewport(context::Context, area::Box2Di)
if context.state.viewport != area
glViewport((min_inclusive(area) - 1)..., size(area)...)
set_render_state_field!(context, :viewport, area)
end
end
set_render_state(::Val{:viewport}, val::Box2Di, c::Context) = set_viewport(c, val)
export set_viewport
"
Changes the area of the screen where rendering can happen,
in terms of pixels (using 1-based indices).
Any rendering outside this view is discarded.
Pass 'nothing' to disable the scissor.
The 'max' corner is inclusive.
"
function set_scissor(context::Context, area::Optional{Box2Di})
if context.state.scissor != area
if exists(area)
if isnothing(context.state.scissor)
glEnable(GL_SCISSOR_TEST)
end
glScissor((min_inclusive(area) - 1)...,
size(area)...)
else
glDisable(GL_SCISSOR_TEST)
end
set_render_state_field!(context, :scissor, area)
end
end
set_render_state(::Val{:scissor}, val::Optional{Box2Di}, c::Context) = set_scissor(c, val)
export set_scissor
# Provide convenient versions of the above which get the context automatically.
set_vsync(sync::E_VsyncModes) = set_vsync(get_context(), sync)
set_render_state(state::RenderState) = set_render_state(get_context(), state)
set_culling(cull::E_FaceCullModes) = set_culling(get_context(), cull)
set_color_writes(enabled::vRGBA{Bool}) = set_color_writes(get_context(), enabled)
set_depth_test(test::E_ValueTests) = set_depth_test(get_context(), test)
set_depth_writes(enabled::Bool) = set_depth_writes(get_context(), enabled)
set_blending(blend::BlendState_) = set_blending(get_context(), blend)
set_blending(rgb::BlendStateRGB, a::BlendStateAlpha) = set_blending(get_context(), rgb, a)
set_blending(val::@NamedTuple{rgb::BlendStateRGB, alpha::BlendStateAlpha}) = set_blending(get_context(), val)
set_stencil_test(test::StencilTest) = set_stencil_test(get_context(), test)
set_stencil_test_front(test::StencilTest) = set_stencil_test_front(get_context(), test)
set_stencil_test_back(test::StencilTest) = set_stencil_test_back(get_context(), test)
set_stencil_test(front::StencilTest, back::StencilTest) = set_stencil_test(get_context(), front, back)
set_stencil_result(result::StencilResult) = set_stencil_result(get_context(), result)
set_stencil_result_front(result::StencilResult) = set_stencil_result_front(get_context(), result)
set_stencil_result_back(result::StencilResult) = set_stencil_result_back(get_context(), result)
set_stencil_result(front::StencilResult, back::StencilResult) = set_stencil_result(get_context(), front, back)
set_stencil_write_mask(write_mask::GLuint) = set_stencil_write_mask(get_context(), write_mask)
set_stencil_write_mask_front(write_mask::GLuint) = set_stencil_write_mask_front(get_context(), write_mask)
set_stencil_write_mask_back(write_mask::GLuint) = set_stencil_write_mask_back(get_context(), write_mask)
set_stencil_write_mask(front::GLuint, back::GLuint) = set_stencil_write_mask(get_context(), front, back)
set_viewport(area::Box2Di) = set_viewport(get_context(), area)
set_scissor(area::Optional{Box2Di}) = set_scissor(get_context(), area)
##########################
# Render State Wrappers #
##########################
# These functions set render state, execute a lambda, then restore that state.
# This helps you write more stateless graphics code.
# For example: 'with_culling(FaceCullModes.off) do ... end'
"
Defines a function which sets some render state, executes a lambda,
then restores the original render state.
There will be two overloads, one which takes an explicit Context and one which does not.
The signature you provide should not include the context or the lambda;
those parameters are inserted automatically.
The doc-string will be generated with the help of the last macro parameter.
The function is automatically exported.
"
macro render_state_wrapper(signature, cache_old, set_new, set_old, description)
func_data = SplitDef(:( $signature = nothing ))
insert!(func_data.args, 1, SplitArg(:to_do))
# Define an overload that gets the context implicitly,
# then calls the overload with an explicit context.
no_context_func_data = SplitDef(func_data)
# Generate the inner call:
inner_call_ordered_args = Any[a.name for a in func_data.args]
insert!(inner_call_ordered_args, 2, :( $(@__MODULE__).get_context() ))
inner_call_named_args = map(a -> Expr(:kw, a, a), func_data.kw_args)
no_context_func_inner_call = Expr(:call,
func_data.name,
@optional(!isempty(inner_call_named_args), Expr(:parameters, inner_call_named_args...)),
inner_call_ordered_args...
)
no_context_func_data.body = no_context_func_inner_call
# Define the main overload which has an explicit context
# as the first parameter after the lambda.
with_context_func_data = SplitDef(func_data)
insert!(with_context_func_data.args, 2,
SplitArg(:( context::$(@__MODULE__).Context )))
with_context_func_data.body = quote
$cache_old
$set_new
try
return to_do()
finally
$set_old
end
end
return esc(quote
Core.@doc(
$(string("Executes some code with the given ", description,
", then restores the original setting. ",
"Optionally takes an explicit context ",
"if you have the reference to it already.")),
$(combinedef(no_context_func_data))
)
$(combinedef(with_context_func_data))
export $(func_data.name)
end)
end
@render_state_wrapper(with_culling(cull::E_FaceCullModes),
old_cull = context.state.cull_mode,
set_culling(context, cull),
set_culling(context, old_cull),
"cull state")
@render_state_wrapper(with_color_writes(enabled_per_channel::vRGBA{Bool}),
old_writes = context.state.color_write_mask,
set_color_writes(context, enabled_per_channel),
set_color_writes(context, old_writes),
"color write mask")
@render_state_wrapper(with_depth_writes(write_depth::Bool),
old_writes = context.state.depth_write,
set_depth_writes(context, write_depth),
set_depth_writes(context, old_writes),
"depth write flag")
@render_state_wrapper(with_stencil_write_mask(bit_mask::GLuint),
old_writes = (get_stencil_write_mask_front(context), get_stencil_write_mask_back(context)),
set_stencil_write_mask(context, bit_mask),
set_stencil_write_mask(context, old_writes...),
"stencil write mask")
@render_state_wrapper(with_stencil_write_mask(front_faces_bit_mask::GLuint, back_faces_bit_mask::GLuint),
old_writes = (get_stencil_write_mask_front(context), get_stencil_write_mask_back(context)),
set_stencil_write_mask(context, front_faces_bit_mask, back_faces_bit_mask),
set_stencil_write_mask(context, old_writes...),
"per-face stencil write mask")
@render_state_wrapper(with_stencil_write_mask_front(front_faces_bit_mask::GLuint),
old_writes = get_stencil_write_mask_front(context),
set_stencil_write_mask_front(context, front_faces_bit_mask),
set_stencil_write_mask_front(context, old_writes),
"front-faces stencil write mask")
@render_state_wrapper(with_stencil_write_mask_back(back_faces_bit_mask::GLuint),
old_writes = get_stencil_write_mask_back(context),
set_stencil_write_mask_back(context, back_faces_bit_mask),
set_stencil_write_mask_back(context, old_writes),
"back-faces stencil write mask")
@render_state_wrapper(with_depth_test(test::E_ValueTests),
old_test = context.state.depth_test,
set_depth_test(context, test),
set_depth_test(context, old_test),
"depth test")
@render_state_wrapper(with_blending(blend::BlendStateRGBA),
old_blend = context.state.blend_mode,
set_blending(context, blend),
set_blending(context, old_blend),
"Color+Alpha blend mode")
@render_state_wrapper(with_blending(color_blend::BlendStateRGB, alpha_blend::BlendStateAlpha),
old_blend = context.state.blend_mode,
set_blending(context, color_blend, alpha_blend),
set_blending(context, old_blend.rgb, old_blend.alpha),
"Color+Alpha blend mode")
@render_state_wrapper(with_blending(color_blend::BlendStateRGB),
old_blend = context.state.blend_mode.rgb,
set_blending(context, color_blend),
set_blending(context, old_blend),
"Color blend mode")
@render_state_wrapper(with_blending(alpha_blend::BlendStateAlpha),
old_blend = context.state.blend_mode.alpha,
set_blending(context, alpha_blend),
set_blending(context, old_blend),
"Alpha blend mode")
@render_state_wrapper(with_stencil_test(test::StencilTest),
old_tests = (get_stencil_test_front(context), get_stencil_test_back(context)),
set_stencil_test(context, test),
set_stencil_test(context, old_tests...),
"stencil test")
@render_state_wrapper(with_stencil_test(front_faces::StencilTest, back_faces::StencilTest),
old_tests = (get_stencil_test_front(context), get_stencil_test_back(context)),
set_stencil_test(context, front_faces, back_faces),
set_stencil_test(context, old_tests...),
"per-face stencil tests")
@render_state_wrapper(with_stencil_test_front(test::StencilTest),
old_test = get_stencil_test_front(context),
set_stencil_test_front(context, test),
set_stencil_test_front(context, old_test),
"front-face stencil test")
@render_state_wrapper(with_stencil_test_back(test::StencilTest),
old_test = get_stencil_test_back(context),
set_stencil_test_back(context, test),
set_stencil_test_back(context, old_test),
"back-face stencil test")
@render_state_wrapper(with_stencil_result(ops::StencilResult),
old_results = (get_stencil_results_front(context), get_stencil_results_back(context)),
set_stencil_result(context, ops),
set_stencil_result(context, old_results...),
"stencil result")
@render_state_wrapper(with_stencil_result(front_faces::StencilResult, back_faces::StencilResult),
old_results = (get_stencil_results_front(context), get_stencil_results_back(context)),
set_stencil_result(context, front_faces, back_faces),
set_stencil_result(context, old_results...),
"per-face stencil results")
@render_state_wrapper(with_stencil_result_front(ops::StencilResult),
old_result = get_stencil_results_front(context),
set_stencil_result(context, ops),
set_stencil_result(context, old_result),
"front-face stencil result")
@render_state_wrapper(with_stencil_result_back(ops::StencilResult),
old_result = get_stencil_results_back(context),
set_stencil_result(context, ops),
set_stencil_result(context, old_result),
"back-face stencil result")
@render_state_wrapper(with_viewport(pixel_area::Box2Di),
old_viewport = context.state.viewport,
set_viewport(context, pixel_area),
set_viewport(context, old_viewport),
"viewport rect")
@render_state_wrapper(with_scissor(pixel_area::Optional{Box2Di}),
old_scissor = context.state.scissor,
set_scissor(context, pixel_area),
set_scissor(context, old_scissor),
"scissor rect")
@render_state_wrapper(with_render_state(full_state::RenderState),
old_state = context.state,
set_render_state(context, full_state),
set_render_state(context, old_state),
"all render state")
###############
# Utilities #
###############
@inline function set_render_state_field!(c::Context, field::Symbol, value)
rs = set(c.state, Setfield.PropertyLens{field}(), value)
setfield!(c, :state, rs)
end
####################################
# Thread-local context storage #
####################################
# Set up the thread-local storage.
const CONTEXTS_PER_THREAD = Vector{Optional{Context}}()
push!(RUN_ON_INIT, () -> begin
empty!(CONTEXTS_PER_THREAD)
for i in 1:Threads.nthreads()
push!(CONTEXTS_PER_THREAD, nothing)
end
end) | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 2584 | # Defines simple data types used by GL
# GLFW Vsync settings
@bp_enum(VsyncModes,
off = 0,
on = 1,
adaptive = -1
)
export VsyncModes, E_VsyncModes
#=
Whether to ignore polygon faces that are pointing away from the camera
(or towards the camera, in "Backwards" mode).
=#
@bp_gl_enum(FaceCullModes::GLenum,
off = GL_INVALID_ENUM,
on = GL_BACK,
backwards = GL_FRONT,
all = GL_FRONT_AND_BACK
)
export FaceCullModes, E_FaceCullModes
# Define conversions from ImageIO pixels to data that GL understands.
"Converts an incoming pixel of an `ImageIO` image into GPU-friendly pixel data of the given type"
convert_pixel(input, Output::Type)::Output = error("Can't convert a ", typeof(input), " into a ", Output)
# Identity conversion:
convert_pixel(u::U, ::Type{U}) where {U} = u
# Convert unsigned into signed by effectively subtracting half the range.
convert_pixel(u::U, I::Type{<:Signed}) where {U<:Unsigned} = (I == signed(U)) ?
typemax(signed(U)) + reinterpret(signed(U), u) + one(signed(U)) :
error(I, " isn't the signed version of ", U)
# Fixed-point already is an unsigned format, just need to reinterpret it.
convert_pixel(u::N0f8, I::Type{<:Union{Int8, UInt8}}) = convert_pixel(reinterpret(u), I)
# Take whatever subset of color channels the user desires.
convert_pixel(p_in::Colorant, T::Type{<:Union{Int8, UInt8}}) = convert_pixel(red(p_in), T)
convert_pixel(p_in::Colorant, T::Type{<:Vec2{I}}) where {I<:Union{Int8, UInt8}} = T(convert_pixel(red(p_in), I),
convert_pixel(green(p_in), I))
convert_pixel(p_in::Colorant, T::Type{<:Vec3{I}}) where {I<:Union{Int8, UInt8}} = T(convert_pixel(red(p_in), I),
convert_pixel(green(p_in), I),
convert_pixel(blue(p_in), I))
convert_pixel(p_in::Colorant, T::Type{<:Vec4{I}}) where {I<:Union{Int8, UInt8}} = T(convert_pixel(red(p_in), I),
convert_pixel(green(p_in), I),
convert_pixel(blue(p_in), I),
convert_pixel(alpha(p_in), I))
export convert_pixel | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 10336 | # Provides an interface into the more modern OpenGL 'Debug Output'.
# Reference: https://www.khronos.org/opengl/wiki/Debug_Output
##################
## Data ##
##################
"Provides a string description of the given debug enum value"
function debug_string(enum)::String end
export debug_string
@bp_gl_enum(DebugEventSources::GLenum,
api = GL_DEBUG_SOURCE_API,
window_system = GL_DEBUG_SOURCE_WINDOW_SYSTEM,
shader_compiler = GL_DEBUG_SOURCE_SHADER_COMPILER,
user = GL_DEBUG_SOURCE_APPLICATION,
library = GL_DEBUG_SOURCE_THIRD_PARTY,
other = GL_DEBUG_SOURCE_OTHER
)
function debug_string(source::E_DebugEventSources)
if source == DebugEventSources.api
return "calling a 'gl' method"
elseif source == DebugEventSources.window_system
return "calling an SDL-related method"
elseif source == DebugEventSources.shader_compiler
return "compiling a shader"
elseif source == DebugEventSources.third_party
return "within some internal OpenGL app"
elseif source == DebugEventSources.user
return "raised by the user (`glDebugMessageInsert()`)"
elseif source == DebugEventSources.other
return "some unspecified context"
else
return "INTERNAL_B+_ERROR(Unhandled source: $source)"
end
end
export DebugEventSources, E_DebugEventSources
@bp_gl_enum(DebugEventTopics::GLenum,
deprecation = GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
undefined_behavior = GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
portability = GL_DEBUG_TYPE_PORTABILITY,
performance = GL_DEBUG_TYPE_PERFORMANCE,
custom = GL_DEBUG_TYPE_MARKER,
begin_group = GL_DEBUG_TYPE_PUSH_GROUP,
end_group = GL_DEBUG_TYPE_POP_GROUP,
other = GL_DEBUG_TYPE_OTHER
)
function debug_string(topic::E_DebugEventTopics)
if topic == DebugEventTopics.deprecation
return "deprecated usage"
elseif topic == DebugEventTopics.undefined_behavior
return "undefined behavior"
elseif topic == DebugEventTopics.portability
return "non-portable behavior"
elseif topic == DebugEventTopics.performance
return "inefficiency"
elseif topic == DebugEventTopics.custom
return "command-stream annotation"
elseif topic == DebugEventTopics.begin_group
return "BEGIN group"
elseif topic == DebugEventTopics.end_group
return "END group"
elseif topic == DebugEventTopics.other
return "other"
else
return "INTERNAL_B+_ERROR(Unhandled topic: $topic)"
end
end
export DebugEventTopics, E_DebugEventTopics
@bp_gl_enum(DebugEventSeverities::GLenum,
none = GL_DEBUG_SEVERITY_NOTIFICATION,
low = GL_DEBUG_SEVERITY_LOW,
medium = GL_DEBUG_SEVERITY_MEDIUM,
high = GL_DEBUG_SEVERITY_HIGH
)
function debug_string(severity::E_DebugEventSeverities)
if severity == DebugEventSeverities.none
return "information"
elseif severity == DebugEventSeverities.low
return "mild"
elseif severity == DebugEventSeverities.medium
return "concerning"
elseif severity == DebugEventSeverities.high
return "fatal"
else
return "INTERNAL_B+_ERROR(Unhandled severity: $severity)"
end
end
export DebugEventSeverities, E_DebugEventSeverities
#####################
## Interface ##
#####################
struct OpenGLEvent
source::E_DebugEventSources
topic::E_DebugEventTopics
severity::E_DebugEventSeverities
msg::String
msg_id::Int
end
Base.show(io::IO, event::OpenGLEvent) = print(io,
"OpenGL (", event.msg_id, ") | ",
uppercasefirst(debug_string(event.severity)), " event about ",
debug_string(event.topic), ", from ",
debug_string(event.source), ": \"", event.msg, "\""
)
"
Pulls all unread event logs from the current OpenGL context,
in chronological order.
Only works if the context was started in debug mode.
"
function pull_gl_logs()::Vector{OpenGLEvent}
PULL_INCREMENT::Int = 32
max_msg_length::GLint = get_from_ogl(GLint, glGetIntegerv, GL_MAX_DEBUG_MESSAGE_LENGTH)
output = OpenGLEvent[ ]
lock(GL_EVENT_LOCKER) do
# Make sure the buffers are large enough.
resize!(BUFFER_EVENT_SOURCES, PULL_INCREMENT)
resize!(BUFFER_EVENT_TOPICS, PULL_INCREMENT)
resize!(BUFFER_EVENT_SEVERITIES, PULL_INCREMENT)
resize!(BUFFER_EVENT_IDS, PULL_INCREMENT)
resize!(BUFFER_EVENT_LENGTHS, PULL_INCREMENT)
resize!(BUFFER_EVENT_MSGS, PULL_INCREMENT * max_msg_length)
# Read messages.
pull_amount::GLuint = GLuint(1)
while pull_amount > 0
# Load the data from OpenGL.
pull_amount = glGetDebugMessageLog(
PULL_INCREMENT,
length(BUFFER_EVENT_MSGS),
Ref(BUFFER_EVENT_SOURCES, 1),
Ref(BUFFER_EVENT_TOPICS, 1),
Ref(BUFFER_EVENT_IDS, 1),
Ref(BUFFER_EVENT_SEVERITIES, 1),
Ref(BUFFER_EVENT_LENGTHS, 1),
Ref(BUFFER_EVENT_MSGS, 1)
)
# Copy the data into the output array.
msg_start_idx::Int = 1
for log_i::Int in 1:Int(pull_amount)
msg_range = msg_start_idx : (msg_start_idx + BUFFER_EVENT_LENGTHS[log_i] - 1)
msg_start_idx += BUFFER_EVENT_LENGTHS[log_i] # The string lengths include
# the null-terminator
push!(output, OpenGLEvent(
BUFFER_EVENT_SOURCES[log_i],
BUFFER_EVENT_TOPICS[log_i],
BUFFER_EVENT_SEVERITIES[log_i],
String(@view(BUFFER_EVENT_MSGS[msg_range])),
BUFFER_EVENT_IDS[log_i]
))
end
end
end
return output
end
"
By default, when using `@check_gl_logs`, a very annoying spammy message about buffers is suppressed.
Disable that by setting this var to false.
"
SUPPRESS_SPAMMY_LOGS::Bool = true
"
A macro to help find OpenGL issues.
Place it before or after each OpenGL call to detect the most recent errors.
By default, a very annoying spammy message about buffers is suppressed;
disable this by setting `GL.SUPPRESS_SPAMMY_LOGS` to false.
"
macro check_gl_logs(context...)
out_msg = :( string($(esc.(context)...)) )
gl_module = @__MODULE__
return quote
out_msg() = $out_msg
for log in $gl_module.pull_gl_logs()
if log.severity in ($gl_module.DebugEventSeverities.high, $gl_module.DebugEventSeverities.medium)
@error "$(out_msg()) $(sprint(show, log))"
elseif log.severity == $gl_module.DebugEventSeverities.low
@warn "$(out_msg()) $(sprint(show, log))"
elseif log.severity == $gl_module.DebugEventSeverities.none
if !SUPPRESS_SPAMMY_LOGS ||
(!occursin(" will use VIDEO memory as the source for buffer object operations", log.msg) &&
!occursin("Based on the usage hint and actual usage, buffer object ", log.msg))
@info "$(out_msg()) $(sprint(show, log))"
end
else
error("Unhandled case: ", log.severity)
end
end
end
end
export OpenGLEvent, pull_gl_logs, @check_gl_logs
##########################
## Implementation ##
##########################
const GL_EVENT_LOCKER = ReentrantLock()
const BUFFER_EVENT_SOURCES = Vector{E_DebugEventSources}()
const BUFFER_EVENT_TOPICS = Vector{E_DebugEventTopics}()
const BUFFER_EVENT_SEVERITIES = Vector{E_DebugEventSeverities}()
const BUFFER_EVENT_IDS = Vector{GLuint}()
const BUFFER_EVENT_LENGTHS = Vector{GLsizei}()
const BUFFER_EVENT_MSGS = Vector{GLchar}()
###########################################################################
###########################################################################
# Unfortunately, the nicer callback-based interface doesn't work.
# As far as I can tell, it's due to a limitation with Julia's feature
# of turning Julia functions into C-friendly functions --
# the calling convention expected by OpenGL can't be chosen from the @cfunction macro.
###########################
## Old Interface ##
###########################
"
The global callback for OpenGL errors and log messages.
Only raised if the context is created in debug mode.
You can freely set this to point to a different function.
"
ON_OGL_MSG = (source::E_DebugEventSources,
topic::E_DebugEventTopics,
severity::E_DebugEventSeverities,
msg_id::Int,
msg::String) ->
begin
println(stderr,
"OpenGL (", msg_id, ") | ",
uppercasefirst(debug_string(severity)), " event about ",
debug_string(topic), ", from ",
debug_string(source), ": \"", msg, "\"")
end
"
Raises the global OpenGL message-handling callback with some message.
This must be called from a thread with an active OpenGL context.
"
function raise_ogl_msg(topic::E_DebugEventTopics,
severity::E_DebugEventSeverities,
message::String
;
source::E_DebugEventSources = DebugEventSources.user,
id::GLuint = 0)
glDebugMessageInsert(GLenum(source), GLenum(topic), id, GLenum(severity),
length(message), Ref(message))
end
############################
## Implementation ##
############################
"The internal C callback for OpenGL errors/messages."
function ON_OGL_MSG_impl(source::GLenum, topic::GLenum, msg_id::GLuint,
severity::GLenum,
msg_len::GLsizei, msg::Ptr{GLchar},
::Ptr{Cvoid})::Cvoid
println("RECEIVED")
ON_OGL_MSG(E_DebugEventSources(source),
E_DebugEventTopics(topic),
E_DebugEventSeverities(severity),
Int(msg_id),
unsafe_string(msg, msg_len))
return nothing
end
"A C-friendly function pointer to the OpenGL error/message callback."
const ON_OGL_MSG_ptr = @cfunction(ON_OGL_MSG_impl, Cvoid,
(GLenum, GLenum, GLuint, GLenum,
GLsizei, Ptr{GLchar}, Ptr{Cvoid})) | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 3514 | #=
The depth buffer is used to keep track of how close each rendered pixel is to the camera.
As new pixels are rendered, any that are behind the depth buffer are discarded,
and any that are in front of the depth buffer will be applied and update the buffer's value.
This default behavior can be configured in a number of ways.
The stencil buffer is a similar kind of filter, but with integer data and bitwise operations
instead of floating-point depth values.
=#
#=
Comparisons that can be used for depth/stencil testing,
against the value currently in the depth/stencil buffer.
In depth testing, the "test" value is the incoming fragment's depth.
In stencil testing, the "test" value is a constant you can set, called the "reference".
=#
@bp_gl_enum(ValueTests::GLenum,
# Always passes ('true').
pass = GL_ALWAYS,
# Always fails ('false').
fail = GL_NEVER,
# Passes if the "test" value is less than the existing value.
less_than = GL_LESS,
# Passes if the "test" value is less than or equal to the existing value.
less_than_or_equal = GL_LEQUAL,
# Passes if the "test" value is greater than the existing value.
greater_than = GL_GREATER,
# Passes if the "test" value is greater than or equal to the existing value.
greater_than_or_equal = GL_GEQUAL,
# Passes if the "test" value is equal to the existing value.
equal = GL_EQUAL,
# Passes if the "test" value is not equal to the existing value.
not_equal = GL_NOTEQUAL
)
export ValueTests, E_ValueTests
#=
The various actions that can be performed on a stencil buffer pixel,
based on a new fragment that was just drawn over it.
=#
@bp_gl_enum(StencilOps::GLenum,
# Don't do anything.
nothing = GL_KEEP,
# Set the value to 0.
zero = GL_ZERO,
# Replace the stencil buffer's value with the "reference" value used for the test.
replace = GL_REPLACE,
# Flip all bits in the buffer (a.k.a. bitwise NOT).
invert = GL_INVERT,
# Increment the stencil buffer's value, clamping it to stay inside its range.
increment_clamp = GL_INCR,
# Increment the stencil buffer's value, wrapping around to 0 if it passes the max value.
increment_wrap = GL_INCR_WRAP,
# Decrement the stencil buffer's value, clamping it to stay inside its range.
decrement_clamp = GL_DECR,
# Decrement the stencil buffer's value, wrapping around to the max value if it passes below 0.
decrement_wrap = GL_DECR_WRAP,
)
export StencilOps, E_StencilOps
"
A predicate/filter evaluated for the stencil buffer,
to control which pixels can be drawn into.
"
struct StencilTest
test::E_ValueTests
# The value to be compared against the stencil buffer.
reference::GLint
# Limits the bits that are used in the test.
bitmask::GLuint
StencilTest(test::E_ValueTests, reference::GLint, mask::GLuint = ~GLuint(0)) = new(test, reference, mask)
StencilTest() = new(ValueTests.pass, GLint(0), ~GLuint(0))
end
export StencilTest
"What happens to the stencil buffer when a fragment is going through the stencil/depth tests"
struct StencilResult
on_failed_stencil::E_StencilOps
on_passed_stencil_failed_depth::E_StencilOps
on_passed_all::E_StencilOps
StencilResult(on_failed_stencil, on_passed_stencil_failed_depth, on_passed_all) = new(
on_failed_stencil, on_passed_stencil_failed_depth, on_passed_all
)
StencilResult() = new(StencilOps.nothing, StencilOps.nothing, StencilOps.nothing)
end
export StencilResult | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 13874 |
#########################
# Clearing #
#########################
"Clears the screen's color to the given value"
function clear_screen(color::vRGBA{<:Union{GLint, GLuint, GLfloat}})
@bp_gl_assert(exists(get_context()), "Clearing render target from a non-rendering thread")
if color isa vRGBA{GLint}
glClearNamedFramebufferiv(Ptr_Target(), GL_COLOR, 0, Ref(color.data))
elseif color isa vRGBA{GLuint}
glClearNamedFramebufferuv(Ptr_Target(), GL_COLOR, 0, Ref(color.data))
elseif color isa vRGBA{GLfloat}
glClearNamedFramebufferfv(Ptr_Target(), GL_COLOR, 0, Ref(color.data))
else
error("Unexpected color component type: ", T)
end
end
"Clears the screen's depth buffer to the given value"
function clear_screen(depth::GLfloat)
@bp_gl_assert(exists(get_context()), "Clearing the screen from a non-rendering thread")
glClearNamedFramebufferfv(Ptr_Target(), GL_DEPTH, 0, Ref(depth))
end
"Clears the screen's stencil buffer to the given value"
function clear_screen(stencil::GLuint)
@bp_gl_assert(exists(get_context()), "Clearing the screen from a non-rendering thread")
glClearNamedFramebufferiv(Ptr_Target(), GL_STENCIL, 0,
Ref(reinterpret(GLint, stencil)))
end
"Clears the screen's hybrid-depth-stencil buffer to the given value"
function clear_screen(depth::GLfloat, stencil::GLuint)
@bp_gl_assert(exists(get_context()), "Clearing the screen from a non-rendering thread")
glClearNamedFramebufferfi(Ptr_Target(), GL_DEPTH_STENCIL, 0,
depth, reinterpret(GLint, stencil))
end
export clear_screen
########################
# Drawing #
########################
"Extra parameters used for drawing indexed meshes"
Base.@kwdef struct DrawIndexed
# An index of this value signals OpenGL to restart the drawing primitive
# (e.x. if occurred within a triangle_strip, a new strip is started).
# Has no effect for primitive types which aren't linked, like point, triangle, or line.
reset_value::Optional{GLuint} = nothing
# All index values are offset by this amount.
# Does not affect the 'reset_value' above; that test happens before this offset is applied.
value_offset::UInt = zero(UInt)
end
"
Renders a mesh using the currently-active shader program.
IMPORTANT NOTE: All counting/indices follow Julia's 1-based convention.
Under the hood, they will get converted to 0-based for OpenGL.
You can manually disable the use of indexed rendering for an indexed mesh
by passing 'indexed_params=nothing'.
You can configure one (and only one) of the following optional features:
1. Instanced rendering (by setting 'instances' to a range like `IntervalU(1, N)`)
2. Multi-draw (by setting 'elements' to a list of ranges, instead of a single range).
3. An optimization hint (by setting 'known_vertex_range') about what vertices
are actually going to be drawn with indexed rendering,
to help the GPU driver optimize memory usage.
NOTE: There is one small, relatively-esoteric OpenGL feature that is not included
(adding it would probably require separating this function into 3 different ones):
indexed multi-draw could use different index offsets for each subset of elements.
"
function render_mesh( mesh::Mesh, program::Program
;
#TODO: Can't do type inference with named parameters! This might create garbage and slowdown.
shape::E_PrimitiveTypes = mesh.type,
indexed_params::Optional{DrawIndexed} =
exists(mesh.index_data) ? DrawIndexed() : nothing,
elements::Union{IntervalU, TMultiDraw} = IntervalU((
min=1,
size=exists(indexed_params) ?
count_mesh_elements(mesh) :
count_mesh_vertices(mesh)
)),
instances::Optional{IntervalU} = nothing,
known_vertex_range::Optional{IntervalU} = nothing
) where {TMultiDraw<:Union{AbstractVector{IntervalU}, ConstVector{IntervalU}}}
context::Context = get_context()
@bp_check(isnothing(indexed_params) || exists(mesh.index_data),
"Trying to render with indexed_params but the mesh has no indices")
# Several of the optional drawing parameters are mutually exclusive.
n_used_features::Int = (exists(indexed_params) ? 1 : 0) +
((elements isa IntervalU) ? 0 : 1) +
(exists(known_vertex_range) ? 1 : 0)
@bp_check(n_used_features <= 1,
"Trying to use more than one of the mutually-exclusive features: ",
"instancing, multi-draw, and known_vertex_range!")
# Let the View-Debugger know that we are rendering with this program.
service_ViewDebugging_check(get_ogl_handle(program))
# Activate the mesh and program.
glUseProgram(program.handle)
setfield!(context, :active_program, program.handle)
glBindVertexArray(mesh.handle)
setfield!(context, :active_mesh, mesh.handle)
#=
The notes I took when preparing the old C++ draw calls interface:
All draw modes:
* Normal "glDrawArrays()" ("first" element index and "count" elements)
* Normal + Multi-Draw "glMultiDrawArrays()" (multiple Normal draws from the same buffer data)
* Normal + Instance "glDrawArraysInstanced()" (draw multiple instances of the same mesh).
should actually use "glDrawArraysInstancedBaseInstance()" to support an offset for the first instance to use
* Indexed "glDrawElements()" (draw indices instead of vertices)
* Indexed + Multi-Draw "glMultiDrawElements()"
* Indexed + Instance "glDrawElementsInstanced()" (draw multiple instances of the same indexed mesh).
should actually use "glDrawElementsInstancedBaseInstance()" to support an offset for the first instance to use
* Indexed + Range "glDrawRangeElements()" (provide the known range of indices that could be drawn, for driver optimization)
* Indexed + Base Index "glDrawElementsBaseVertex()" (an offset for all indices)
* Indexed + Base Index + Multi-Draw "glMultiDrawElementsBaseVertex()" (each element of the multi-draw has a different "base index" offset)
* Indexed + Base Index + Range "glDrawRangeElementsBaseVertex()"
* Indexed + Base Index + Instanced "glDrawElementsInstancedBaseVertex()"
should actually use "glDrawElementsInstancedBaseVertexBaseInstance()" to support an offset for the first instance to use
All Indexed draw modes can have a "reset index", which is
a special index value to reset for continuous fan/strip primitives
=#
if exists(indexed_params)
# Configure the "primitive restart" index.
if exists(indexed_params.reset_value)
glEnable(GL_PRIMITIVE_RESTART)
glPrimitiveRestartIndex(indexed_params.reset_value)
else
glDisable(GL_PRIMITIVE_RESTART)
end
# Pre-compute data.
index_type = get_index_ogl_enum(mesh.index_data.type)
index_byte_size = sizeof(mesh.index_data.type)
# Make the draw calls.
if elements isa AbstractArray{IntervalU}
offsets = ntuple(i -> index_byte_size * (min_inclusive(elements[i]) - 1), length(elements))
counts = ntuple(i -> size(elements[i]), length(elements))
value_offsets = ntuple(i -> indexed_params.value_offset, length(elements))
glMultiDrawElementsBaseVertex(shape,
Ref(counts),
index_type,
Ref(offsets),
length(elements),
Ref(value_offsets))
else
# OpenGL has a weird requirement that the index offset be a void*,
# not a simple integer.
index_byte_offset = Ptr{Cvoid}(index_byte_size * (min_inclusive(elements) - 1))
if indexed_params.value_offset == 0
if exists(instances)
if min_inclusive(instances) == 1
glDrawElementsInstanced(shape, size(elements),
index_type,
index_byte_offset,
size(instances))
else
glDrawElementsInstancedBaseInstance(shape, size(elements),
index_type,
index_byte_offset,
size(instances),
min_inclusive(instances) - 1)
end
elseif exists(known_vertex_range)
glDrawRangeElements(shape,
min_inclusive(known_vertex_range) - 1,
max_inclusive(known_vertex_range) - 1,
size(elements),
index_type,
index_byte_offset)
else
glDrawElements(shape, size(elements),
index_type,
index_byte_offset)
end
else
if exists(instances)
if min_inclusive(instances) == 1
glDrawElementsInstancedBaseVertex(shape, size(elements),
index_type,
index_byte_offset,
size(instances),
indexed_params.value_offset)
else
glDrawElementsInstancedBaseVertexBaseInstance(shape, size(elements),
index_type,
index_byte_offset,
size(instances),
indexed_params.value_offset,
min_inclusive(instances) - 1)
end
elseif exists(known_vertex_range)
glDrawRangeElementsBaseVertex(shape,
min_inclusive(known_vertex_range) - 1,
max_inclusive(known_vertex_range) - 1,
size(elements),
index_type,
index_byte_offset,
indexed_params.value_offset)
else
glDrawElementsBaseVertex(shape, size(elements),
index_type,
index_byte_offset,
indexed_params.value_offset)
end
end
end
else
if elements isa AbstractArray{IntervalU}
offsets = ntuple(i -> min_inclusive(elements[i]) - 1, length(elements))
counts = ntuple(i -> size(elements[i]), length(elements))
glMultiDrawArrays(shape, Ref(offsets), Ref(counts), length(elements))
elseif exists(instances)
if min_inclusive(instances) == 1
glDrawArraysInstanced(shape,
min_inclusive(elements) - 1, size(elements),
size(instances))
else
glDrawArraysInstancedBaseInstance(shape,
min_inclusive(elements) - 1, size(elements),
size(instances), min_inclusive(instances) - 1)
end
else
glDrawArrays(shape, min_inclusive(elements) - 1, size(elements))
end
end
end
export DrawIndexed, render_mesh
############################
# Compute Dispatch #
############################
"Dispatches the given compute shader with enough work-groups for the given number of threads"
function dispatch_compute_threads(program::Program, count::Vec3{<:Integer}
; context::Context = get_context())
@bp_check(exists(program.compute_work_group_size),
"Program isn't a compute shaer: " + get_ogl_handle(program))
group_size::v3u = program.compute_work_group_size
dispatch_compute_groups(program,
round_up_to_multiple(count, group_size) ÷ group_size
; context=context)
end
"Dispatches the given commpute shader with the given number of work-groups"
function dispatch_compute_groups(program::Program, count::Vec3{<:Integer}
; context::Context = get_context())
# Activate the program.
glUseProgram(get_ogl_handle(program))
setfield!(context, :active_program, get_ogl_handle(program))
glDispatchCompute(convert(Vec{3, GLuint}, count)...)
end
export dispatch_compute_threads, dispatch_compute_groups | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 3190 | # Define the handles to various OpenGL objects.
# Most define an "emmpty" constructor which creates a null-pointer,
# a.k.a. a value which OpenGL promises will not be a valid handle.
# They also provide a `gl_type(::Type)` that retrieves their underlying integer data type.
"""
Defines a primitive type representing an OpenGL handle.
Think of this like a stronger version of type aliasing,
which provides more type safety.
The type will also have an empty constructor which creates a "null" value
(usually 0 or -1).
"""
macro ogl_handle(name::Symbol, gl_type_name,
display_name = lowercase(string(name)),
null_val = zero(eval(gl_type_name))) #TODO: Eliminate eval by using `:( zero($gl_type_name) )`
gl_type = eval(gl_type_name)
@bp_gl_assert(gl_type <: Integer,
"Unexpected GL type: ", gl_type, ".",
" I only really planned for integers in this macro")
type_name = esc(Symbol(:Ptr_, name))
null_val = esc(null_val)
gl_type_name = esc(gl_type_name)
hash_extra = hash(name)
return quote
Base.@__doc__(
primitive type $type_name (8*sizeof($gl_type)) end
)
$type_name() = reinterpret($type_name, $gl_type($null_val))
$type_name(i::$gl_type) = reinterpret($type_name, i)
$type_name(i::Integer) = $type_name(convert($gl_type, i))
$gl_type_name(i::$type_name) = reinterpret($gl_type_name, i)
$(esc(:gl_type))(x::$type_name) = $gl_type_name(x)
$(esc(:gl_type))(::Type{$type_name}) = $gl_type_name
Base.show(io::IO, x::$type_name) = print(io, $display_name, '<', Int($gl_type_name(x)), '>')
Base.print(io::IO, x::$type_name) = print(io, Int($gl_type_name(x)))
Base.convert(::Type{$gl_type_name}, i::$type_name) = reinterpret($gl_type, i)
Base.unsafe_convert(::Type{Ptr{$gl_type}}, r::Base.RefValue{$type_name}) =
Base.unsafe_convert(Ptr{$gl_type}, Base.unsafe_convert(Ptr{Nothing}, r))
Base.hash(h::$type_name, u::UInt) = hash(tuple(gl_type(h), $hash_extra), u)
Base.:(==)(a::$type_name, b::$type_name) = (gl_type(a) == gl_type(b))
end
end
@ogl_handle Program GLuint
@ogl_handle Uniform GLint "uniform" -1
@ogl_handle ShaderBuffer GLuint "shaderBuffer" GL_INVALID_INDEX
@ogl_handle Texture GLuint
@ogl_handle Image GLuint
@ogl_handle View GLuint64
@ogl_handle Sampler GLuint
"Equivalent to an OpenGL 'Framebuffer'"
@ogl_handle Target GLuint
"Equivalent to an OpenGL 'RenderBuffer'"
@ogl_handle TargetBuffer GLuint
@ogl_handle Buffer GLuint
@ogl_handle Mesh GLuint
# Some handle types benefit from supporting pointer arithmetic.
const POINTER_ARITHMETIC_HANDLES = tuple(
Ptr_Uniform, Ptr_ShaderBuffer
)
for TP in POINTER_ARITHMETIC_HANDLES
for op in (:+, :-, :*, :÷)
@eval begin
Base.$op(p::$TP, i::Integer) = $TP(
gl_type($TP)(
$op(gl_type(p), gl_type($TP)(i))
)
)
Base.$op(i::Integer, p::$TP) = $TP(
gl_type($TP)(
$op(gl_type($TP)(i), gl_type(p))
)
)
end
end
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 38695 | ######################
# Uniforms #
######################
# Uniforms are shader parameters, set by the user through OpenGL calls.
const UniformScalar = Union{Scalar32, Scalar64, Bool}
const UniformVector{N} = Vec{N, <:UniformScalar}
const UniformMatrix{C, R, L} = Mat{C, R, <:Union{Float32, Float64}, L}
"
Acceptable types of data for `set_uniform()` and `set_uniforms()`
(note that buffers are handled separately)
"
const Uniform = Union{UniformScalar,
@unionspec(UniformVector{_}, 1, 2, 3, 4),
# All Float32 and Float64 matrices from 2x2 to 4x4:
(
UniformMatrix{size..., prod(size)}
for size in Iterators.product(2:4, 2:4)
)...,
# "Opaque" types:
Texture, Ptr_View, View
}
export Uniform
"
Information about a specific Program uniform.
A uniform can be an array of its data type; if the uniform is an array of structs,
each UniformData instance will be about one specific field of one specific element.
The name is not stored because it will be used as the key for an instance of this struct.
"
struct UniformData
handle::Ptr_Uniform
type::Type{<:Uniform}
array_size::Int # Set to 1 for non-array uniforms.
end
"
Information about a specific Program buffer block (a.k.a. UBO/SSBO).
The name is not stored because it will be used as the key for an instance of this struct.
"
struct ShaderBlockData
handle::Ptr_ShaderBuffer
byte_size::Int32 # For SSBO's with a dynamic-length array at the end,
# this assumes an element count of 1 (although 0 elements is legal).
end
"""
`set_uniform(::Program, ::String, ::T[, array_index::Int])`
Sets a program's uniform to the given value.
If the uniform is an array, you must provide a (1-based) index.
If the uniform is a struct or array of structs, you must name the individual fields/elements,
e.x. `set_uniform(p, "my_lights[0].pos", new_pos)`.
This naming is 0-based, not 1-based, unfortunately.
"""
function set_uniform end
"""
`set_uniforms(::Program, ::String, ::AbstractVector{T}[, dest_offset=0])`
`set_uniforms(::Program, ::String, T, ::Contiguous{T}[, dest_offset=0])`
Sets a program's uniform to the given value.
You must provide an array of *contiguous* values.
If the contiguous array is more nested than a mere `Array{T}`, `Vec{N, T}`, `NTuple{N, T}`, etc
(e.x. `Vector{NTuple{5, v2f}}`), then you must also pass the `T` value to remove ambiguity.
If you are passing an array of `Texture`/`View` instances, rather than raw `Ptr_View`s,
then the collection does not need to be contiguous.
If the uniform is a struct or array of structs, you must name the individual fields/elements,
e.x. `set_uniform(p, "my_lights[0].pos", new_pos)`.
This naming is 0-based, not 1-based, unfortunately.
"""
function set_uniforms end
"""
`set_uniform_block(::Buffer, ::Int; byte_range=[full buffer])`
Sets the given buffer to be used for one of the
globally-available Uniform Block (a.k.a. "UBO") slots.
`set_uniform_block(::Program, ::String, ::Int)`
Sets a program's Uniform Block (a.k.a. "UBO")
to use the given global slot, which can be assigned a Buffer with the other overload.
`set_uniform_block(::Int)`
Clears the binding for the given global UBO slot.
**NOTE**: Indices and byte ranges are 1-based!
"""
function set_uniform_block end
"""
`set_storage_block(::Buffer, ::Int; byte_range=[full buffer])`
Sets the given buffer to be used for one of the
globally-available Shader Storage Block (a.k.a. "SSBO") slots.
`set_storage_block(::Program, ::String, ::Int)`
Sets a program's Shader-Storage Block (a.k.a. "SSBO")
to use the given global slot, which can be assigned a Buffer with the other overload.
`set_storage_block(::Int)`
Clears the binding for the given global SSBO slot.
**NOTE**: Indices and byte ranges are 1-based!
"""
function set_storage_block end
export Uniform, UniformData, set_uniform, set_uniforms, set_uniform_block, set_storage_block
################################
# PreCompiledProgram #
################################
# A binary blob representing a previously-compiled shader.
# You can usually cache these to avoid recompiling shaders.
mutable struct PreCompiledProgram
header::GLenum
data::Vector{UInt8}
end
export PreCompiledProgram
#############################
# compile_stage() #
#############################
"
Internal helper that compiles a single stage of a shader program.
Returns the program's handle, or an error message.
"
function compile_stage( name::String,
type::GLenum,
source::String
; extensions::Vector{ExtensionRequest} = get_context().supported_extensions
)::Union{GLuint, String}
source = string(glsl_header(extensions), "\n", source)
handle::GLuint = glCreateShader(type)
# The OpenGL call wants an array of strings, a.k.a. a pointer to a pointer to a string.
# ModernGL provides an example of how to do this with Ptr,
# but ideally I'd like to know how to do it with Ref.
source_array = [ convert(Ptr{GLchar}, pointer(source)) ]
source_array_ptr = convert(Ptr{UInt8}, pointer(source_array))
glShaderSource(handle, 1, source_array_ptr, C_NULL)
glCompileShader(handle)
if get_from_ogl(GLint, glGetShaderiv, handle, GL_COMPILE_STATUS) == GL_TRUE
return handle
else
err_msg_len = get_from_ogl(GLint, glGetShaderiv, handle, GL_INFO_LOG_LENGTH)
err_msg_data = Vector{UInt8}(undef, err_msg_len)
glGetShaderInfoLog(handle, err_msg_len, Ref(GLsizei(err_msg_len)), Ref(err_msg_data, 1))
return string("Error compiling ", name, ": ",
String(view(err_msg_data, 1:err_msg_len)))
end
end
#############################
# ProgramCompiler #
#############################
struct RenderProgramSource
src_vertex::String
src_fragment::String
src_geometry::Optional{String}
end
struct ComputeProgramSource
src::String
end
"A set of data to be compiled into an OpenGL shader program"
mutable struct ProgramCompiler
source::Union{RenderProgramSource, ComputeProgramSource}
# A pre-compiled version of this shader which this compiler can attempt to use first.
# The shader source code is still needed as a fallback,
# as shaders may need recompilation after driver changes.
# After compilation, if the user wants, this field can be updated with the newest binary.
cached_binary::Optional{PreCompiledProgram}
end
ProgramCompiler( src_vertex::AbstractString, src_fragment::AbstractString
;
src_geometry::Optional{AbstractString} = nothing,
cached_binary::Optional{PreCompiledProgram} = nothing
) = ProgramCompiler(
RenderProgramSource(string(src_vertex), string(src_fragment),
isnothing(src_geometry) ? nothing : string(src_geometry)),
cached_binary
)
ProgramCompiler( src_compute::AbstractString
;
cached_binary::Optional{PreCompiledProgram} = nothing
) = ProgramCompiler(
ComputeProgramSource(string(src_compute)),
cached_binary
)
"
Run the given compile job.
Returns the new program's handle, or a compile error message.
Also optionally updates the compiler 'cached_binary' field to contain
the program's up-to-date binary blob.
"
function compile_program( p::ProgramCompiler,
update_cache::Bool = false
; extensions::Vector{ExtensionRequest} = get_context().supported_extensions
)::Union{Ptr_Program, String}
@bp_check(exists(get_context()), "Can't create a Program outside a BplusApp.GL.Context")
out_ptr = Ptr_Program(glCreateProgram())
# Try to use the pre-compiled binary blob.
if exists(p.cached_binary)
glProgramBinary(out_ptr, p.cached_binary.header,
Ref(p.cached_binary.data, 1),
length(p.cached_binary.data))
if get_from_ogl(GLint, glGetProgramiv, GL_LINK_STATUS) == GL_TRUE
return out_ptr
end
end
# Compile the individual shaders.
compiled_handles::Vector{GLuint} = [ ]
if p.source isa RenderProgramSource
for data in (("vertex", GL_VERTEX_SHADER, p.source.src_vertex),
("fragment", GL_FRAGMENT_SHADER, p.source.src_fragment),
("geometry", GL_GEOMETRY_SHADER, p.source.src_geometry))
if exists(data[3])
result = compile_stage(data...; extensions=extensions)
if result isa String
# Clean up the shaders/program, then return the error message.
map(glDeleteShader, compiled_handles)
glDeleteProgram(out_ptr)
return result
else
push!(compiled_handles, result)
end
end
end
elseif p.source isa ComputeProgramSource
result = compile_stage("compute", GL_COMPUTE_SHADER, p.source.src; extensions=extensions)
if result isa String
# Clean up the shaders/program, then return the error message.
map(glDeleteShader, compiled_handles)
glDeleteProgram(out_ptr)
return result
else
push!(compiled_handles, result)
end
else
error("Unhandled case: ", typeof(p.source))
end
# Link the shader program together.
for shad_ptr in compiled_handles
glAttachShader(out_ptr, shad_ptr)
end
glLinkProgram(out_ptr)
map(glDeleteShader, compiled_handles)
# Check for link errors.
if get_from_ogl(GLint, glGetProgramiv, out_ptr, GL_LINK_STATUS) == GL_FALSE
msg_len = get_from_ogl(GLint, glGetProgramiv, out_ptr, GL_INFO_LOG_LENGTH)
msg_data = Vector{UInt8}(undef, msg_len)
glGetProgramInfoLog(out_ptr, msg_len, Ref(Int32(msg_len)), Ref(msg_data, 1))
glDeleteProgram(out_ptr)
return string("Error linking shaders: ", String(msg_data[1:msg_len]))
end
# We need to "detach" the shader objects
# from the main program object, so that they can be cleaned up.
for handle in compiled_handles
glDetachShader(out_ptr, handle)
end
# Update the cached compiled program.
if update_cache
byte_size = get_from_ogl(GLint, glGetProgramiv, GL_PROGRAM_BINARY_LENGTH)
@bp_gl_assert(byte_size > 0,
"Didn't return an error message earlier, yet compilation failed?")
# Allocate space in the cache to hold the program binary.
if exists(p.cached_binary)
resize!(p.cached_binary, byte_size)
else
p.cached_binary = PreCompiledProgram(zero(GLenum), Vector{UInt8}(undef, byte_size))
end
glGetProgramBinary(program, byte_size,
Ref(C_NULL),
Ref(p.cached_binary.header),
Ref(p.cached_binary.data, 1))
end
return out_ptr
end
export ProgramCompiler, compile_program
######################
# Program #
######################
"A compiled group of OpenGL shaders (vertex, fragment, etc.)"
mutable struct Program <: AbstractResource
handle::Ptr_Program
compute_work_group_size::Optional{v3u} # Only exists for compute shaders
uniforms::Dict{String, UniformData}
uniform_blocks::Dict{String, ShaderBlockData}
storage_blocks::Dict{String, ShaderBlockData}
flexible_mode::Bool # Whether to silently ignore invalid uniforms
end
function Program(vert_shader::String, frag_shader::String
;
geom_shader::Optional{String} = nothing,
flexible_mode::Bool = true,
extensions::Vector{ExtensionRequest} = get_context().supported_extensions)
compiler = ProgramCompiler(vert_shader, frag_shader; src_geometry = geom_shader)
result = compile_program(compiler; extensions=extensions)
if result isa Ptr_Program
return Program(result, flexible_mode)
elseif result isa String
error(result)
else
error("Unhandled case: ", typeof(result), "\n\t: ", result)
end
end
function Program(compute_shader::String
;
flexible_mode::Bool = true,
extensions::Vector{ExtensionRequest} = get_context().supported_extensions)
compiler = ProgramCompiler(compute_shader)
result = compile_program(compiler; extensions=extensions)
if result isa Ptr_Program
return Program(result, flexible_mode; is_compute=true)
elseif result isa String
error(result)
else
error("Unhandled case: ", typeof(result), "\n\t: ", result)
end
end
function Program(handle::Ptr_Program, flexible_mode::Bool = false; is_compute::Bool = false)
context = get_context()
@bp_check(exists(context), "Creating a Program without a valid Context")
name_c_buffer = Vector{GLchar}(undef, 128)
# Get the shader storage blocks.
n_storage_blocks = get_from_ogl(GLint, glGetProgramInterfaceiv,
handle, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES)
storage_blocks = Dict{String, ShaderBlockData}()
resize!(name_c_buffer,
get_from_ogl(GLint, glGetProgramInterfaceiv,
handle, GL_SHADER_STORAGE_BLOCK, GL_MAX_NAME_LENGTH))
for block_idx::Int in 1:n_storage_blocks
block_name_length = Ref(zero(GLsizei))
glGetProgramResourceiv(handle,
# The resource:
GL_SHADER_STORAGE_BLOCK, block_idx - 1,
# The desired data:
1, Ref(GL_NAME_LENGTH),
# The output buffer(s):
1, C_NULL, block_name_length)
glGetProgramResourceName(handle,
GL_SHADER_STORAGE_BLOCK, block_idx - 1,
block_name_length[], C_NULL, Ref(name_c_buffer, 1))
# For some reason, this string is sometimes null-terminated and sometimes not.
if iszero(name_c_buffer[block_name_length[]])
block_name_length[] -= 1
end
block_name = String(@view name_c_buffer[1 : block_name_length[]])
storage_blocks[block_name] = ShaderBlockData(
Ptr_ShaderBuffer(block_idx - 1),
get_from_ogl(GLint, glGetProgramResourceiv,
# The resource:
handle, GL_SHADER_STORAGE_BLOCK, block_idx - 1,
# The desired data:
1, Ref(GL_BUFFER_DATA_SIZE),
# The output buffer(s):
1, C_NULL)
)
end
# Get the uniform buffer blocks.
n_uniform_blocks = get_from_ogl(GLint, glGetProgramiv, handle, GL_ACTIVE_UNIFORM_BLOCKS)
uniform_blocks = Dict{String, ShaderBlockData}()
resize!(name_c_buffer,
get_from_ogl(GLint, glGetProgramiv, handle, GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH))
for block_idx::Int in 1:n_uniform_blocks
block_name_length::GLsizei = 0
@c glGetActiveUniformBlockName(handle, block_idx - 1, length(name_c_buffer),
&block_name_length, &name_c_buffer[0])
# For some reason, this string is sometimes null-terminated and sometimes not.
if iszero(name_c_buffer[block_name_length])
block_name_length -= 1
end
block_name = String(@view name_c_buffer[1:block_name_length])
uniform_blocks[block_name] = ShaderBlockData(
Ptr_ShaderBuffer(block_idx - 1),
get_from_ogl(GLint, glGetActiveUniformBlockiv,
handle, block_idx - 1, GL_UNIFORM_BLOCK_DATA_SIZE)
)
end
# Gather handles of uniforms witin the blocks and ignore them below.
uniform_indices_to_skip = Set{GLint}()
block_uniform_indices = Vector{GLint}(undef, 128)
for block_idx::Int in 1:n_uniform_blocks
resize!(block_uniform_indices,
get_from_ogl(GLint, glGetActiveUniformBlockiv, handle, block_idx - 1,
GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS))
@c glGetActiveUniformBlockiv(handle, block_idx - 1,
GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES,
&block_uniform_indices[0])
append!(uniform_indices_to_skip, block_uniform_indices)
end
# Get the uniforms.
uniforms = Dict{String, UniformData}()
glu_array_count = Ref{GLint}() # The length of this uniform array (1 if it's not an array).
glu_type = Ref{GLenum}()
glu_name_buf = Vector{GLchar}(
undef,
get_from_ogl(GLint, glGetProgramiv,
handle, GL_ACTIVE_UNIFORM_MAX_LENGTH)
)
n_uniforms = get_from_ogl(GLint, glGetProgramiv, handle, GL_ACTIVE_UNIFORMS)
glu_name_len = Ref{GLsizei}()
for i in 1:n_uniforms
if i in uniform_indices_to_skip
continue
end
glGetActiveUniform(handle, i - 1,
length(glu_name_buf), glu_name_len,
glu_array_count,
glu_type,
Ref(glu_name_buf, 1))
# The name string is NOT null-terminated, unlike block names.
u_name_buf = glu_name_buf[1:glu_name_len[]]
u_name = String(u_name_buf)
# Array uniforms come in with the suffix "[0]".
# Remove that to keep things simple to the user.
if endswith(u_name, "[0]")
u_name = u_name[1:(end-3)]
end
@bp_gl_assert(!haskey(uniforms, u_name))
uniforms[u_name] = UniformData(
Ptr_Uniform(glGetUniformLocation(handle, Ref(glu_name_buf, 1))),
UNIFORM_TYPE_FROM_GL_ENUM[glu_type[]],
glu_array_count[]
)
end
# Connect to the view-debugger service.
service_ViewDebugging_add_program(handle)
return Program(handle,
is_compute ?
v3u(get_from_ogl(GLint, 3, glGetProgramiv,
handle, GL_COMPUTE_WORK_GROUP_SIZE)...) :
nothing,
uniforms,
uniform_blocks,
storage_blocks,
flexible_mode)
end
function Base.close(p::Program)
service_ViewDebugging_remove_program(p.handle)
@bp_check(p.handle != Ptr_Program(), "Already closed this Program")
glDeleteProgram(p.handle)
setfield!(p, :handle, Ptr_Program())
end
"Gets the raw Julia type of a uniform with the given OpenGL type."
const UNIFORM_TYPE_FROM_GL_ENUM = Dict{GLenum, Type{<:Uniform}}(
GL_FLOAT => Float32,
GL_FLOAT_VEC2 => v2f,
GL_FLOAT_VEC3 => v3f,
GL_FLOAT_VEC4 => v4f,
GL_DOUBLE => Float64,
GL_DOUBLE_VEC2 => v2d,
GL_DOUBLE_VEC3 => v3d,
GL_DOUBLE_VEC4 => v4d,
GL_INT => Int32,
GL_INT_VEC2 => Vec{2, Int32},
GL_INT_VEC3 => Vec{3, Int32},
GL_INT_VEC4 => Vec{4, Int32},
GL_UNSIGNED_INT => UInt32,
GL_UNSIGNED_INT_VEC2 => Vec{2, UInt32},
GL_UNSIGNED_INT_VEC3 => Vec{3, UInt32},
GL_UNSIGNED_INT_VEC4 => Vec{4, UInt32},
GL_INT64_ARB => Int64,
GL_INT64_VEC2_ARB => Vec{2, Int64},
GL_INT64_VEC3_ARB => Vec{3, Int64},
GL_INT64_VEC4_ARB => Vec{4, Int64},
GL_UNSIGNED_INT64_ARB => UInt64,
GL_UNSIGNED_INT64_VEC2_ARB => Vec{2, UInt64},
GL_UNSIGNED_INT64_VEC3_ARB => Vec{3, UInt64},
GL_UNSIGNED_INT64_VEC4_ARB => Vec{4, UInt64},
GL_BOOL => Bool,
GL_BOOL_VEC2 => v2b,
GL_BOOL_VEC3 => v3b,
GL_BOOL_VEC4 => v4b,
GL_FLOAT_MAT2 => fmat2,
GL_FLOAT_MAT3 => fmat3,
GL_FLOAT_MAT4 => fmat4,
GL_FLOAT_MAT2x3 => fmat2x3,
GL_FLOAT_MAT2x4 => fmat2x4,
GL_FLOAT_MAT3x2 => fmat3x2,
GL_FLOAT_MAT3x4 => fmat3x4,
GL_FLOAT_MAT4x2 => fmat4x2,
GL_FLOAT_MAT4x3 => fmat4x3,
GL_DOUBLE_MAT2 => dmat2,
GL_DOUBLE_MAT3 => dmat3,
GL_DOUBLE_MAT4 => dmat4,
GL_DOUBLE_MAT2x3 => dmat2x3,
GL_DOUBLE_MAT2x4 => dmat2x4,
GL_DOUBLE_MAT3x2 => dmat3x2,
GL_DOUBLE_MAT3x4 => dmat3x4,
GL_DOUBLE_MAT4x2 => dmat4x2,
GL_DOUBLE_MAT4x3 => dmat4x3,
GL_SAMPLER_1D => Ptr_View,
GL_SAMPLER_2D => Ptr_View,
GL_SAMPLER_3D => Ptr_View,
GL_SAMPLER_CUBE => Ptr_View,
GL_SAMPLER_1D_SHADOW => Ptr_View,
GL_SAMPLER_2D_SHADOW => Ptr_View,
GL_SAMPLER_1D_ARRAY => Ptr_View,
GL_SAMPLER_2D_ARRAY => Ptr_View,
GL_SAMPLER_1D_ARRAY_SHADOW => Ptr_View,
GL_SAMPLER_2D_ARRAY_SHADOW => Ptr_View,
GL_SAMPLER_2D_MULTISAMPLE => Ptr_View,
GL_SAMPLER_2D_MULTISAMPLE_ARRAY => Ptr_View,
GL_SAMPLER_CUBE_SHADOW => Ptr_View,
GL_SAMPLER_BUFFER => Ptr_View,
GL_SAMPLER_2D_RECT => Ptr_View,
GL_SAMPLER_2D_RECT_SHADOW => Ptr_View,
GL_INT_SAMPLER_1D => Ptr_View,
GL_INT_SAMPLER_2D => Ptr_View,
GL_INT_SAMPLER_3D => Ptr_View,
GL_INT_SAMPLER_CUBE => Ptr_View,
GL_INT_SAMPLER_1D_ARRAY => Ptr_View,
GL_INT_SAMPLER_2D_ARRAY => Ptr_View,
GL_INT_SAMPLER_2D_MULTISAMPLE => Ptr_View,
GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY => Ptr_View,
GL_INT_SAMPLER_BUFFER => Ptr_View,
GL_INT_SAMPLER_2D_RECT => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_1D => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_2D => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_3D => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_CUBE => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_1D_ARRAY => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_2D_ARRAY => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_BUFFER => Ptr_View,
GL_UNSIGNED_INT_SAMPLER_2D_RECT => Ptr_View,
GL_IMAGE_1D => Ptr_View,
GL_IMAGE_2D => Ptr_View,
GL_IMAGE_3D => Ptr_View,
GL_IMAGE_2D_RECT => Ptr_View,
GL_IMAGE_CUBE => Ptr_View,
GL_IMAGE_BUFFER => Ptr_View,
GL_IMAGE_1D_ARRAY => Ptr_View,
GL_IMAGE_2D_ARRAY => Ptr_View,
GL_IMAGE_2D_MULTISAMPLE => Ptr_View,
GL_IMAGE_2D_MULTISAMPLE_ARRAY => Ptr_View,
GL_INT_IMAGE_1D => Ptr_View,
GL_INT_IMAGE_2D => Ptr_View,
GL_INT_IMAGE_3D => Ptr_View,
GL_INT_IMAGE_2D_RECT => Ptr_View,
GL_INT_IMAGE_CUBE => Ptr_View,
GL_INT_IMAGE_BUFFER => Ptr_View,
GL_INT_IMAGE_1D_ARRAY => Ptr_View,
GL_INT_IMAGE_2D_ARRAY => Ptr_View,
GL_INT_IMAGE_2D_MULTISAMPLE => Ptr_View,
GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY => Ptr_View,
GL_UNSIGNED_INT_IMAGE_1D => Ptr_View,
GL_UNSIGNED_INT_IMAGE_2D => Ptr_View,
GL_UNSIGNED_INT_IMAGE_3D => Ptr_View,
GL_UNSIGNED_INT_IMAGE_2D_RECT => Ptr_View,
GL_UNSIGNED_INT_IMAGE_CUBE => Ptr_View,
GL_UNSIGNED_INT_IMAGE_BUFFER => Ptr_View,
GL_UNSIGNED_INT_IMAGE_1D_ARRAY => Ptr_View,
GL_UNSIGNED_INT_IMAGE_2D_ARRAY => Ptr_View,
GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE => Ptr_View,
GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY => Ptr_View,
#TODO: GL_UNSIGNED_INT_ATOMIC_COUNTER => Ptr_Buffer ??
)
export Program
#################################
# Setting uniforms Impl #
#################################
get_uniform(program::Program, name::String) =
if haskey(program.uniforms, name)
program.uniforms[name]
elseif program.flexible_mode
nothing
else
error("Uniform not found (was it optimized out?): '", name, "'")
end
#
# Setting a single uniform:
function set_uniform(program::Program, name::String, value::T) where {T}
# If the data is a higher-level object, convert it into its lowered form.
if T == Texture
set_uniform(program, name, get_view(value))
elseif T == View
set_uniform(program, name, value.handle)
else
u_data::Optional{UniformData} = get_uniform(program, name)
if isnothing(u_data)
return
end
@bp_check(u_data.array_size == 1, "No index given for the array uniform '", name, "'")
ref = Ref(value)
GC.@preserve ref begin
ptr = contiguous_ptr(ref, T)
set_uniform(u_data.type, T, ptr, program.handle, u_data.handle, 1)
end
end
end
# Setting an element of a uniform array:
function set_uniform(program::Program, name::String, value::T, index::Int) where {T<:Uniform}
# If the data is a higher-level object, convert it into its lowered form.
if T == Texture
set_uniform(program, name, get_view(value), index)
elseif T == View
set_uniform(program, name, value.handle, index)
else
u_data::Optional{UniformData} = get_uniform(program, name)
if isnothing(u_data)
return
end
@bp_check(index <= u_data.array_size,
"Array uniform '", name, "' only has ", u_data.array_size, " elements,",
" and you're trying to set index ", index)
handle = Ptr_Uniform(gl_type(u_data.handle) + (index - 1))
ref = Ref(value)
GC.@preserve ref begin
ptr = contiguous_ptr(ref, T)
set_uniform(u_data.type, T, ptr, program.handle, handle, 1)
end
end
end
# Setting an array of uniforms:
@inline set_uniforms( program::Program, name::String,
values::TContiguousSimple,
dest_offset::Integer = 0
) where {T<:Uniform, TContiguousSimple <: ContiguousSimple{T}} =
set_uniforms(program, name, T, values, dest_offset)
function set_uniforms( program::Program, name::String,
::Type{T}, values::TCollection,
dest_offset::Integer = 0
) where {T<:Uniform, TCollection}
# If the incoming data is higher-level objects, convert them to their lowered version.
if T <: Union{Texture, View}
@bp_check(TCollection <: Union{ConstVector{T}, AbstractArray{T}},
"Passing a collection of textures/views to set a uniform array,",
" but the collection isn't array-like! It's a ", TCollection)
handles::Vector{Ptr_View} = map(values) do element::Union{Texture, View}
if element isa Texture
return get_view(element).handle
elseif element isa View
return element.handle
else
error("Unhandled case: ", typeof(element))
end
end
set_uniforms(program, name, Ptr_View, handles, dest_offset)
else
# The collection must be contiguous to be uploaded to OpenGL through the C API.
@bp_check(TCollection <: Contiguous{T},
"Passing an array of data to set a uniform array,",
" but the data isn't contiguous! It's a ", TCollection)
u_data::Optional{UniformData} = get_uniform(program, name)
if isnothing(u_data)
return
end
n_available_uniforms::Int = u_data.array_size - dest_offset
count::Int = contiguous_length(values, T)
@bp_check(count <= n_available_uniforms,
"Array uniform '", name, "' only has ", u_data.array_size, " elements,",
" and you're trying to set elements ",
(dest_offset + 1), ":", (dest_offset + count))
handle = Ptr_Uniform(gl_type(u_data.handle) + dest_offset)
ref = contiguous_ref(values, T)
GC.@preserve ref begin
ptr = contiguous_ptr(ref, T)
set_uniform(u_data.type, T, ptr, program.handle, handle, count)
end
end
end
# The actual implementation, which calls into the proper OpenGL function
# based on the uniform type:
@generated function set_uniform( ::Type{TOut}, ::Type{TIn},
data_ptr::Ptr,
program::Ptr_Program,
first_param::Ptr_Uniform, n_params::Integer
) where {TOut<:Uniform, TIn<:Contiguous}
if TOut == Ptr_View
return quote
# Update the view-debugger service with these new uniforms.
# REPL tests indicate that the unsafe_wrap() call always happens,
# even if the view-debugger code is compiled into a no-op.
# This apparently leads to a heap-allocation.
# Avoid this by manually wrapping in the "debug-only" macro.
@bp_gl_debug service_ViewDebugging_set_views(
program, first_param,
unsafe_wrap(Array, data_ptr, n_params)
)
glProgramUniformHandleui64vARB(program, first_param, n_params, data_ptr)
end
elseif TOut <: UniformScalar
gl_func_name = Symbol(:glProgramUniform1, get_uniform_ogl_letter(TOut), :v)
return :( $gl_func_name(program, first_param, n_params, data_ptr) )
elseif TOut <: UniformVector
(N, T) = TOut.parameters
gl_func_name = Symbol(:glProgramUniform, N, get_uniform_ogl_letter(T), :v)
return :( $gl_func_name(program, first_param, n_params, data_ptr) )
elseif TOut <: UniformMatrix
(C, R, T) = mat_params(TOut)
gl_func_name = Symbol(:glProgramUniformMatrix,
(C == R) ? C : Symbol(C, :x, R),
get_uniform_ogl_letter(T),
:v)
return :( $gl_func_name(program, first_param, n_params, GL_FALSE, data_ptr) )
else
error("Unexpected uniform type ", TOut, " being set with a ", TIn, " value")
end
end
# Uniform blocks:
function set_uniform_block(buf::Buffer, idx::Int;
context::Context = get_context(),
byte_range::Interval{<:Integer} = Interval(
min=1,
max=buf.byte_size
))
handle = get_ogl_handle(buf)
binding = (handle, convert(Interval{Int}, byte_range))
if context.active_ubos[idx] != binding
context.active_ubos[idx] = binding
glBindBufferRange(GL_UNIFORM_BUFFER, idx - 1, handle,
min_inclusive(byte_range) - 1,
size(byte_range))
end
return nothing
end
function set_uniform_block(program::Program, name::AbstractString, idx::Int)
if !haskey(program.uniform_blocks, name)
if program.flexible_mode
return nothing
else
error("Uniform block not found (was it optimized out?): '", name, "'")
end
end
glUniformBlockBinding(get_ogl_handle(program),
program.uniform_blocks[name].handle,
idx - 1)
return nothing
end
function set_uniform_block(idx::Int; context::Context = get_context())
cleared_binding = (Ptr_Buffer(), Interval{Int}(min=-1, max=-1))
if context.active_ubos[idx] != cleared_binding
context.active_ubos[idx] = cleared_binding
glBindBufferBase(GL_UNIFORM_BUFFER, idx - 1, Ptr_Buffer())
end
return nothing
end
# Shader Storage blocks:
function set_storage_block(buf::Buffer, idx::Int;
context::Context = get_context(),
byte_range::Interval{<:Integer} = Interval(
min=1,
max=buf.byte_size
))
handle = get_ogl_handle(buf)
binding = (handle, convert(Interval{Int}, byte_range))
if context.active_ssbos[idx] != binding
context.active_ssbos[idx] = binding
glBindBufferRange(GL_SHADER_STORAGE_BUFFER, idx - 1, handle,
min_inclusive(byte_range) - 1,
size(byte_range))
end
return nothing
end
function set_storage_block(program::Program, name::AbstractString, idx::Int)
if !haskey(program.storage_blocks, name)
if program.flexible_mode
return nothing
else
error("Storage block not found (was it optimized out?): '", name, "'")
end
end
glShaderStorageBlockBinding(get_ogl_handle(program),
program.storage_blocks[name].handle,
idx - 1)
return nothing
end
function set_storage_block(idx::Int; context::Context = get_context())
cleared_binding = (Ptr_Buffer(), Interval{Int}(min=-1, max=-1))
if context.active_ssbos[idx] != cleared_binding
context.active_ssbos[idx] = cleared_binding
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, idx - 1, Ptr_Buffer())
end
return nothing
end
# Retrieve the correct OpenGL uniform function letter for a given type of data.
get_uniform_ogl_letter(::Type{Float32}) = :f
get_uniform_ogl_letter(::Type{Float64}) = :d
get_uniform_ogl_letter(::Type{Int32}) = :i
get_uniform_ogl_letter(::Type{UInt32}) = :ui
get_uniform_ogl_letter(::Type{UInt64}) = :ui64
####################################
# Shader string literal #
####################################
"
Compiles an OpenGL Program from a string literal containing the various shader stages.
To compile a non-literal string in the same way, call `bp_glsl_str(shader_string)`.
The code at the top of the shader is shared between all shader stages.
The Vertex Shader starts with the custom command `#START_VERTEX`.
The Fragment Shader starts with the custom command `#START_FRAGMENT`.
The *optional* Geometry Shader starts with the custom command `#START_GEOMETRY`.
For a Compute Shader, use `#START_COMPUTE`.
"
macro bp_glsl_str(src::AbstractString)
return bp_glsl_str(src, Val(true))
end
"
Compiles a string with special formatting into a `Program`.
For info on how to format it, refer to the docs for `@bp_glsl_str`
(the string macro version).
To debug-log the generated shaders, pass a stream to 'debug_out'.
"
function bp_glsl_str(src::AbstractString, ::Val{GenerateCode} = Val(false)
; debug_out::Optional{IO} = nothing
) where {GenerateCode}
# Define info about the different pieces of the shader.
separators = Dict(
:vert => ("#START_VERTEX", findfirst("#START_VERTEX", src)),
:frag => ("#START_FRAGMENT", findfirst("#START_FRAGMENT", src)),
:geom => ("#START_GEOMETRY", findfirst("#START_GEOMETRY", src)),
:compute => ("#START_COMPUTE", findfirst("#START_COMPUTE", src))
)
# Make sure the right shader stages were provided.
local is_compute::Bool
if exists(separators[:compute][2])
is_compute = true
@bp_check(all(isnothing.(getindex.(getindex.(Ref(separators), (:vert, :frag, :geom)),
Ref(2)))),
"Can't provide compute shader with rendering shaders")
else
is_compute = false
if isnothing(separators[:vert][2])
error("Must provide a vertex shader, with the header `", separators[:vert][1], "`")
elseif isnothing(separators[:frag][2])
error("Must provide a fragment shader, with the header `", separators[:frag][1], "`")
end
end
# Find the end of the common section of code at the top.
end_of_common_code::Int = -1 + minimum(first(data[2]) for data in values(separators) if exists(data[2]))
# Get the boundaries of each section of code, in order.
section_bounds = [ data[2] for data in values(separators) if exists(data[2]) ]
sort!(section_bounds, by=first)
# Get the sections of code for each specific stage.
function try_find_range(stage::Symbol)
if isnothing(separators[stage][2])
return nothing
end
my_range_start = last(separators[stage][2]) + 1
next_bounds_idx = findfirst(bounds -> bounds[1] > my_range_start,
section_bounds)
my_range_end = isnothing(next_bounds_idx) ?
length(src) :
first(section_bounds[next_bounds_idx]) - 1
return my_range_start:my_range_end
end
vert_range = try_find_range(:vert)
frag_range = try_find_range(:frag)
geom_range = try_find_range(:geom)
compute_range = try_find_range(:compute)
# Generate the individual shaders.
src_header = src[1:end_of_common_code]
# Use the #line command to preserve line numbers in shader compile errors.
gen_line_command(section_start) = string(
"\n#line ",
(1 + count(f -> f=='\n', src[1:section_start])),
"\n"
)
src_vertex = isnothing(vert_range) ?
nothing :
string("#define IN_VERTEX_SHADER\n", src_header,
gen_line_command(first(vert_range)),
src[vert_range])
src_fragment = isnothing(frag_range) ?
nothing :
string("#define IN_FRAGMENT_SHADER\n", src_header,
gen_line_command(first(frag_range)),
src[frag_range])
src_geom = isnothing(geom_range) ?
nothing :
string("#define IN_GEOMETRY_SHADER\n", src_header,
gen_line_command(first(geom_range)),
src[geom_range])
src_compute = isnothing(compute_range) ?
nothing :
string("#define IN_COMPUTE_SHADER\n", src_header,
gen_line_command(first(compute_range)),
src[compute_range])
if exists(debug_out)
if exists(src_vertex)
print(debug_out, "//START_VERTEX\n", src_vertex, "\n\n\n")
end
if exists(src_geom)
print(debug_out, "//START_GEOM\n", src_geom, "\n\n\n")
end
if exists(src_fragment)
print(debug_out, "//START_FRAGMENT\n", src_fragment, "\n\n\n")
end
if exists(src_compute)
print(debug_out, "//START_COMPUTE\n", src_compute, "\n\n\n")
end
end
if GenerateCode
prog_type = Program
if is_compute
return :( $prog_type($src_compute) )
else
return :( $prog_type($src_vertex, $src_fragment, geom_shader=$src_geom) )
end
else
if is_compute
return Program(src_compute)
else
return Program(src_vertex, src_fragment, geom_shader=src_geom)
end
end
end
export @bp_glsl_str | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1259 | "
A mutable OpenGL object which cannot be copied, and whose fields should not be set directly.
Resources should be created within a Context, and can be cleaned up with `Base.close()`.
The resource's OpenGL handle must be set to a null value after the resource is closed,
so that it's easy to see if a resource has been destroyed.
"
abstract type AbstractResource end
"
Gets the OpenGL handle for a resource.
By default, tries to access the `handle` property.
"
get_ogl_handle(r::AbstractResource) = r.handle
"
Gets whether a resource has already been destroyed.
By default, checks if its OpenGL handle is null.
"
is_destroyed(r::AbstractResource) = (r.handle == typeof(r.handle)())
Base.close(r::AbstractResource) = error("Forgot to implement close() for ", typeof(r))
Base.setproperty!(::AbstractResource, name::Symbol, val) = error("Cannot set the field of a AbstractResource! ",
r, ".", name, " = ", val)
Base.deepcopy(::AbstractResource) = error("Do not try to copy OpenGL resources")
# Unfortunately, OpenGL allows implementations to re-use the handles of destroyed textures;
# otherwise, I'd use that for hashing/equality.
export AbstractResource, get_ogl_handle, is_destroyed | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 15482 | "
A Context-wide mutable singleton, providing some utility for users.
It is highly recommended to define a service with `@bp_service`.
"
abstract type AbstractService end
# The following functions are an internal interface, used by Context, not to be exported:
service_internal_refresh(service::AbstractService) = nothing
service_internal_shutdown(service::AbstractService) = nothing
"""
Defines a B+ Context service with a standardized interface. Services are a mutable struct
with the name `Service_X`, where `X` is the name you provide.
Example usage:
````
@bp_service Input(args...) begin
# Some data that the service will hold:
buttons::Dict{AbstractString, Any}
axes::Dict{AbstractString, Any}
current_scroll_pos::v2f
# ... # [etc]
# The service's initializer.
INIT(a, b) = begin
return new(a, b, zero(v2f)) # Provide values for the above fields
end
# The service's cleanup code.
SHUTDOWN(service, is_context_closing::Bool) = begin
close(service.some_file_handle)
if !is_context_closing # Waste of time to destroy GL resources if the whole context is going away
for tex in service.all_my_textures
close(tex)
end
end
end
# If you want to be notified when the context refreshes,
# for example if outside OpenGL code ran and potentially changed OpenGL's state,
# you can define this:
REFRESH(service) = begin
service.last_rendered_program = glGetIntegerv(blah, blah)
end
# Custom functions for your service.
# See below for info on how they are transformed into real functions.
get_button(service, name) = service.buttons[name]
add_button(service, name, value) = service.buttons[name] = value
end
````
The `args...` in the service name includes the following values:
* `force_unique` makes the service a singleton across the entire Context,
forbidding you from creating multiple ones
and removing the need to pass the service in manually to every service function.
* `lazy` makes the service initialize automatically (with no passed arguments)
if it's retrieved before it's created.
# Interface
The following functions are generated for you based on your service's name
(here we assume you named it `X`, case-sensitive):
## Startup/shutdown
* `service_X_init(args...)` : Executes your defined `INIT(args...)` code,
adds the service to the Context, and returns it.
If you did not specify `force_unique`, then you may call this multiple times
to create multiple service instances.
* `service_X_shutdown([service])` : Closes your service, executing your defined
`SHUTDOWN(service, is_context_closing)` code.
Called automatically on context close, but you may kill it early if you want, in which case
the value of the second parameter will be `false`.
If you specified `force_unique`, then you do not have to provide the service instance when calling.
## Utility
* `service_X()` : Gets the current service instance, assuming it's already been created.
This function only exists if you specified `force_unique`.
* `service_X_exists()` : Gets whether the service has already been created.
This function only exists if you specified `force_unique`.
## Custom
Any other functions you declared get generated basically as-is.
The first argument must always be the service, and then if you specified `force_unique`,
the user of your function omits that parameter when calling.
For example, `f(service, a, b) = a*b + service.z` turns into `f(a, b)` if `force_unique`.
You're encouraged, but not required, to name your functions in the same style as the others:
`service_X_f()`.
# Notes
You can provide type parameters in your service name, in which case
you must also pass them in when calling `new` in your `INIT`,
and the `service_X()` getter will take those types as normal function parameters.
You can similarly provide type parameters in all functions, including special ones like `INIT`.
"""
macro bp_service(service_name, service_definitions)
# Retrieve the different elements of the service declaration.
service_args = [ ]
if @capture(service_name, name_(args__))
service_name = name
service_args = args
end
# Parse the inner parameters to the service.
service_is_unique = false
service_lazy_inits = false
for service_arg in service_args
if service_arg == :force_unique
service_is_unique = true
elseif service_arg == :lazy
service_lazy_inits = true
else
error("Unexpected argument to '", service_name, "': \"", service_arg, "\"")
end
end
# Extract any type parameters for the service.
service_type_params = nothing
if @capture(service_name, generic_{types__})
service_name = generic
service_type_params = types
end
# Check the arguments have correct syntax.
if service_name isa AbstractString
service_name = Symbol(service_name)
elseif !isa(service_name, Symbol)
error("Service's name should be a simple token (or string), but it's '", service_name, "'")
end
if !Base.is_expr(service_definitions, :block)
error("Expected a begin...end block for service's definitions; got: ",
(service_definitions isa Expr) ?
service_definitions.head :
typeof(service_definitions))
else
service_definitions = filter(e -> !isa(e, LineNumberNode), service_definitions.args)
end
# Generate some basic code/snippets.
expr_service_name = (service_name)
expr_struct_name = Symbol(:Service_, service_name)
expr_struct_decl = exists(service_type_params) ?
:( $expr_struct_name{$(service_type_params...)} ) :
expr_struct_name
function_prefix::Symbol = Symbol(:service_, service_name)
expr_function_name_init = (Symbol(function_prefix, :_init))
expr_function_name_shutdown = (Symbol(function_prefix, :_shutdown))
expr_function_name_get = (function_prefix)
expr_function_name_exists = (Symbol(function_prefix, :_exists))
# If the service is unique, then we don't need the user to pass it in for every call,
# because we can grab it from the context.
expr_local_service_var = Symbol("IMPL: SERVICE")
expr_function_body_get_service = if service_is_unique
:( $expr_local_service_var::$expr_struct_name = $expr_function_name_get() )
else
:( )
end
# Parse the individual definitions.
expr_struct_declarations = [ ]
expr_global_declarations = [ ]
# For simplicity, user-code escaping will be done *after* the loop.
for definition in service_definitions
# Is it a function definition?
if function_wrapping_is_valid(definition)
function_data = SplitDef(definition)
# Most of the functions should list the service as the first argument.
check_service_arg() = if length(function_data.args) < 1
error("You must provide a 'service' argument for the function '",
function_data.name, "'")
end
if function_data.name == :INIT
# Define the service's constructor to implement the user's logic.
constructor_data = SplitDef(function_data, false)
constructor_data.doc_string = nothing
constructor_data.name = expr_struct_name
expr_constructor = combinedef(constructor_data)
push!(expr_struct_declarations, expr_constructor)
expr_invoke_constructor = combinecall(constructor_data)
# Define the interface function for creating the context.
init_function_data = SplitDef(function_data, false)
init_function_data.name = expr_function_name_init
init_function_data.body = quote
context = $(@__MODULE__).get_context()
serv = $expr_invoke_constructor
if $service_is_unique && haskey(context.unique_service_lookup, typeof(serv))
$expr_function_name_shutdown(serv, false)
error("Service has already been initialized: ", $(string(service_name)))
end
push!(context.services, serv)
if $service_is_unique
context.unique_service_lookup[typeof(serv)] = serv
end
return serv
end
push!(expr_global_declarations, combinedef(init_function_data))
elseif function_data.name == :SHUTDOWN
check_service_arg()
if length(function_data.args) != 2
error("SHUTDOWN() should have two arguments: the service, and a bool")
end
# Define an internal function that implements the user's logic.
impl_shutdown_func_data = SplitDef(function_data, false)
impl_shutdown_func_data.doc_string = nothing
impl_shutdown_func_data.name = Symbol(function_prefix, :_shutdown_IMPL)
push!(expr_global_declarations, combinedef(impl_shutdown_func_data))
# Define the callback for when a Context is closing.
push!(expr_global_declarations, :(
function $(@__MODULE__).service_internal_shutdown(service::$expr_struct_name)
$(impl_shutdown_func_data.name)(service, true)
end
))
# Define the interface for manually shutting down the service.
manual_shutdown_func_data = SplitDef(function_data, false)
manual_shutdown_func_data.name = expr_function_name_shutdown
if service_is_unique # Is the 'service' argument implicit?
deleteat!(manual_shutdown_func_data.args, 1)
end
manual_shutdown_func_data.body = quote
$expr_function_body_get_service
return $(impl_shutdown_func_data.name)($expr_local_service_var, false)
end
push!(expr_global_declarations, combinedef(manual_shutdown_func_data))
elseif function_data.name == :REFRESH
check_service_arg()
if length(function_data.args) != 1
error("REFRESH() should have one argument: the service")
end
refresh_func_data = SplitDef(function_data, false)
refresh_func_data.name = :( $(@__MODULE__).service_internal_refresh)
push!(expr_global_declarations, combinedef(refresh_func_data))
else
check_service_arg()
# Must be a custom function.
# Our generated boilerplate will internally define then invoke
# the user's literal written function.
# Define an internal function implementing the service's code.
impl_function_data = SplitDef(function_data, false)
impl_function_data.name = Symbol("IMPL: ", impl_function_data.name)
impl_function_data.doc_string = nothing
# Generate an invocation of that function.
function_as_call = combinecall(function_data)
function_as_call.args[1] = impl_function_data.name
# This is the call into the service function, so
# we're passing our internal service variable.
first_nonkw_param_idx = isexpr(function_as_call.args[2], :parameters) ?
3 :
2
function_as_call.args[first_nonkw_param_idx] = expr_local_service_var
# Define the outer function that users will call.
custom_function_data = SplitDef(function_data, false)
if service_is_unique
deleteat!(custom_function_data.args, 1)
end
custom_function_data.body = quote
# Define the users's function locally.
$(combinedef(impl_function_data))
# Get the service if it's passed implicitly.
$expr_function_body_get_service
# Invoke the user's function.
return $function_as_call
end
push!(expr_global_declarations, combinedef(custom_function_data))
end
else
# Must be a field.
(field_name, field_type, is_splat_operator, field_default_value) = splitarg(definition)
if is_splat_operator || exists(field_default_value)
error("Invalid syntax for field '", field_name, "' (did you try to provide a default value?)")
end
push!(expr_struct_declarations, definition)
end
end
# Generate a getter for unique services.
if service_is_unique
push!(expr_global_declarations, :(
@inline function $expr_function_name_get(type_params...)::$expr_struct_name
context = $(@__MODULE__).get_context()
service_type = if isempty(type_params)
$expr_struct_name
else
$expr_struct_name{type_params...}
end
# Check whether the service exists yet.
if !haskey(context.unique_service_lookup, service_type)
if $service_lazy_inits
return $expr_function_name_init()
else
error("Trying to get ", $(string(service_name)),
" service before it was created")
end
else
return context.unique_service_lookup[service_type]
end
end
))
end
# Generate a function to check if the service exists.
if service_is_unique
push!(expr_global_declarations, :(
@inline function $expr_function_name_exists(type_params...)::Bool
context = $(@__MODULE__).get_context()
service_type = if isempty(type_params)
$expr_struct_name
else
$expr_struct_name{type_params...}
end
return haskey(context.unique_service_lookup, service_type)
end
))
end
# Generate the final code.
expr_struct_declarations = (expr_struct_declarations)
expr_global_declarations = (expr_global_declarations)
final_expr = esc(quote
# The service data structure:
Core.@__doc__ mutable struct $expr_struct_decl <: $(@__MODULE__).AbstractService
$(expr_struct_declarations...)
end
$(expr_global_declarations...)
end)
return final_expr
end
export AbstractService, @bp_service | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 3969 | "
Waits until OpenGL is done executing all previously-issued render commands.
This has limited usefulness, but here are a few scenarios:
* You are sharing resources with another context (not natively supported in B+ anyway),
and must ensure the shared resources are done being written to by the source context.
* You are tracking down a driver bug or tricky compute bug,
and want to invoke this after every command to track down the one that crashes.
* You are working around a driver bug.
"
function gl_execute_everything()
glFinish()
end
export gl_execute_everything
#NOTE: glFlush() is not provided here because it doesn't seem useful for anything these days.
"
If you want to sample from the same texture you are rendering to,
which is legal as long as the read area and write area are distinct,
you should call this afterwards to ensure the written pixels can be read.
This helps you ping-pong within a single target rather than having to set up two of them.
"
function gl_flush_texture_writes_in_place()
glTextureBarrier()
end
export gl_flush_texture_writes_in_place
@bp_gl_bitfield(MemoryActions::GLbitfield,
mesh_vertex_data = GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT,
mesh_index_data = GL_ELEMENT_ARRAY_BARRIER_BIT,
buffer_download_or_upload = GL_BUFFER_UPDATE_BARRIER_BIT,
buffer_uniforms = GL_UNIFORM_BARRIER_BIT,
buffer_storage = GL_SHADER_STORAGE_BARRIER_BIT,
texture_samples = GL_TEXTURE_FETCH_BARRIER_BIT,
texture_simple_views = GL_SHADER_IMAGE_ACCESS_BARRIER_BIT,
texture_upload_or_download = GL_TEXTURE_UPDATE_BARRIER_BIT,
target_attachments = GL_FRAMEBUFFER_BARRIER_BIT,
# Not yet relevant to B+, but will be one day:
indirect_draw = GL_COMMAND_BARRIER_BIT,
texture_async_download_or_upload = GL_PIXEL_BUFFER_BARRIER_BIT,
buffer_map_usage = GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT,
buffer_atomics = GL_ATOMIC_COUNTER_BARRIER_BIT,
# This bit generates an OpenGL error if used. Already logged as a B+ ticket.
# queries = GL_QUERY_BUFFER_BARRIER_BIT,
# All data reads/writes that are possible in fragment shaders:
@USE_FRAGMENT_SHADERS(texture_samples | texture_simple_views | target_attachments |
buffer_uniforms | buffer_storage | buffer_atomics),
# All data reads/writes related to Vertex Array Objects:
@USE_MESH(mesh_vertex_data | mesh_index_data),
# All data reads/writes related to Buffers:
@USE_BUFFER(USE_MESH | buffer_atomics | buffer_uniforms | buffer_storage |
buffer_download_or_upload | buffer_map_usage),
# All data reads/writes related to Textures:
@USE_TEXTURES(texture_samples | texture_simple_views | texture_upload_or_download |
texture_async_download_or_upload)
)
"
Inserts a memory barrier in OpenGL so that the given operations
definitely happen *after* all shader operations leading up to this call.
For example, if you ran a compute shader to modify a texture and are about to sample from it,
call `gl_catch_up_before(SyncTypes.texture_samples)`.
This is only needed for incoherent operations.
For example, you do not need a barrier after rendering into a Target.
"
function gl_catch_up_before(actions::E_MemoryActions)
glMemoryBarrier(actions)
end
"
Inserts a memory barrier in OpenGL, like `gl_catch_up_before()`,
but specifically for the subset of the framebuffer that was just rendered to,
in preparation for more fragment shader behavior.
The actions you pass in must be a subset of `MemoryActions.USE_IN_FRAGMENT_SHADERS`.
"
function gl_catch_up_renders_before(actions::E_MemoryActions)
@bp_check(actions <= MemoryActions.USE_FRAGMENT_SHADERS,
"Some provided actions aren't relevant to fragment shaders: ",
actions - MemoryActions.USE_FRAGMENT_SHADERS)
glMemoryBarrierByRegion(actions)
end
export gl_catch_up_before, gl_catch_up_renders_before,
E_MemoryActions, MemoryActions | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1115 | # Define @bp_gl_assert:
@make_toggleable_asserts bp_gl_
"Short-hand for making enums based on OpenGL constants"
macro bp_gl_enum(name, args...)
expr = Utilities.generate_enum(name, :(begin using ..ModernGLbp end), args, false)
return expr
end
"Short-hand for making bitfields based on OpenGL constants"
macro bp_gl_bitfield(name, args...)
expr = Utilities.generate_enum(name, :(begin using ..ModernGLbp end), args, true)
end
"
Helper function that calls OpenGL, reads N elements of data into a buffer,
then returns that buffer as an NTuple.
"
function get_from_ogl( output_type::DataType,
output_count::Int,
gl_func::Function,
func_args...
)::NTuple{output_count, output_type}
ref = Ref(ntuple(i->zero(output_type), output_count))
gl_func(func_args..., ref)
return ref[]
end
"Helper function that calls OpenGL, reads some kind of data, then returns that data"
get_from_ogl(output_type::DataType, gl_func::Function, func_args...)::output_type = get_from_ogl(output_type, 1, gl_func, func_args...)[1] | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1867 | const OGL_MAJOR_VERSION = 4
const OGL_MINOR_VERSION = 6
# "Different ways an OpenGL extension can be supported"
@bp_enum(ExtensionMode,
# The extension must exist, or there will be an error
require,
# The extension should be added, otherwise there will be a warning
prefer,
# The extension should be added if available
enable
)
"A requested OpenGL extension"
struct ExtensionRequest
name::String
mode::E_ExtensionMode
# If the GLSL code to invoke this extension is abnormal, specify it here.
glsl_override::Optional{String}
ExtensionRequest(name, mode, override = nothing) = new(name, mode, override)
end
extension_glsl(r::ExtensionRequest)::String = if exists(r.glsl_override)
r.glsl_override
elseif r.mode in (ExtensionMode.require, ExtensionMode.enable)
"#extension $(r.name) : $(r.mode)"
elseif r.mode == ExtensionMode.prefer
"#extension $(r.name) : warn"
else
error("Unhandled case: ", r.mode)
end
"The core OpenGL extensions recommended for B+"
const OGL_RECOMMENDED_EXTENSIONS = (
ExtensionRequest(
"GL_ARB_bindless_texture",
ExtensionMode.require
),
# For seamless bindless cubemaps:
ExtensionRequest(
"GL_ARB_seamless_cubemap_per_texture",
ExtensionMode.prefer,
"" # No GLSL code needed
),
# For native 64-bit integer types (otherwise you need to use uint2):
ExtensionRequest(
"GL_ARB_gpu_shader_int64",
ExtensionMode.enable
)
)
"Generates the top of a B+ shader, including `#version` and `#extension` statements"
glsl_header(extensions::Vector{ExtensionRequest}) = string(
"#version $(OGL_MAJOR_VERSION)$(OGL_MINOR_VERSION)0 \n",
(string(extension_glsl(e), "\n") for e in extensions)...,
"#line 1\n"
)
export ExtensionRequest, ExtensionMode, E_ExtensionMode, OGL_RECOMMENDED_EXTENSIONS | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 11130 | """
A contiguous block of memory on the GPU,
for storing any kind of data.
Most commonly used to store mesh vertices/indices, or other arrays of things.
To initialize, you can provide its byte-size or some data to upload
(which passes through `buffer_data_convert()`).
For help with uploading a whole data structure to a buffer, see `@std140` and `@std430`.
UNIMPLEMENTED: Instances can be "mapped" to the CPU, allowing you to write/read them directly
as if they were a plain C array.
This is often more efficient than setting the buffer data the usual way,
e.x. you could read the mesh data from disk directly into this mapped memory.
"""
mutable struct Buffer <: AbstractResource
handle::Ptr_Buffer
byte_size::UInt64
is_mutable_from_cpu::Bool
"Create a buffer of the given size, with uninitialized data"
function Buffer( byte_size::Integer, can_change_data_from_cpu::Bool,
recommend_storage_on_cpu::Bool = false
)::Buffer
b = new(Ptr_Buffer(), 0, false)
set_up_buffer(
byte_size, can_change_data_from_cpu,
nothing,
recommend_storage_on_cpu,
b
)
return b
end
"Create a buffer big enough to hold N copies of the given bitstype"
function Buffer( can_change_data_from_cpu::Bool,
T::Type, count::Integer = 1
; recommend_storage_on_cpu::Bool = false)
@bp_check(isbitstype(T),
T, " isn't a bitstype")
return Buffer(sizeof(T) * count, can_change_data_from_cpu,
recommend_storage_on_cpu)
end
"Create a buffer containing your data, given as a pointer and byte-size"
function Buffer( can_change_data_from_cpu::Bool,
ref_and_size::Tuple{<:Ref, <:Integer},
;
recommend_storage_on_cpu::Bool = false,
)::Buffer
b = new(Ptr_Buffer(), 0, false)
set_up_buffer(
ref_and_size[2],
can_change_data_from_cpu,
ref_and_size[1],
recommend_storage_on_cpu,
b
)
return b
end
"Create a buffer containing your data, as an instance of some bits-type"
function Buffer(can_change_data_from_cpu::Bool,
initial_bits_data
;
recommend_storage_on_cpu::Bool = false)
@bp_check(isbits(initial_bits_data),
typeof(initial_bits_data), " isn't a bitstype")
@bp_check(!isa(initial_bits_data, Bool),
"You probably meant to invoke the other overload of Buffer()")
return Buffer(can_change_data_from_cpu,
(Ref(initial_bits_data), sizeof(initial_bits_data))
;
recommend_storage_on_cpu=recommend_storage_on_cpu)
end
"Create a buffer containing your data, as an array of some data"
function Buffer(can_change_data_from_cpu::Bool,
data_array::AbstractArray
;
recommend_storage_on_cpu::Bool = false)
@bp_check(isbitstype(eltype(data_array)),
eltype(data_array), " isn't a bitstype")
if data_array isa SubArray
@bp_check(Base.iscontiguous(data_array),
"Array view isn't contiguous so it can't be uploaded to the GPU")
end
return Buffer(can_change_data_from_cpu,
(Ref(data_array, 1),
sizeof(eltype(data_array)) * length(data_array))
; recommend_storage_on_cpu=recommend_storage_on_cpu)
end
end
@inline function set_up_buffer( byte_size::I, can_change_data_from_cpu::Bool,
initial_byte_data::Optional{Ref},
recommend_storage_on_cpu::Bool,
output::Buffer
) where {I<:Integer}
@bp_check(exists(get_context()), "No B+ GL.Context to create this buffer in")
handle::Ptr_Buffer = Ptr_Buffer(get_from_ogl(gl_type(Ptr_Buffer), glCreateBuffers, 1))
flags::GLbitfield = 0
if recommend_storage_on_cpu
flags |= GL_CLIENT_STORAGE_BIT
end
if can_change_data_from_cpu
flags |= GL_DYNAMIC_STORAGE_BIT
end
setfield!(output, :handle, handle)
setfield!(output, :byte_size, UInt64(byte_size))
setfield!(output, :is_mutable_from_cpu, can_change_data_from_cpu)
glNamedBufferStorage(handle, byte_size,
exists(initial_byte_data) ?
initial_byte_data :
C_NULL,
flags)
end
Base.show(io::IO, b::Buffer) = print(io,
"Buffer<",
Base.format_bytes(b.byte_size),
(b.is_mutable_from_cpu ? " Mutable" : ""),
" ", b.handle,
">"
)
function Base.close(b::Buffer)
h = b.handle
glDeleteBuffers(1, Ref{GLuint}(b.handle))
setfield!(b, :handle, Ptr_Buffer())
end
export Buffer
#########################
# Buffer Set #
#########################
"Updates a buffer's data with a given pointer and destination byte range"
function set_buffer_data(b::Buffer, data::Ref,
buffer_byte_range::Interval{<:Integer} = IntervalU(
min=1,
size=b.byte_size
))
@bp_check(b.is_mutable_from_cpu, "Buffer is immutable")
@bp_check(min_inclusive(buffer_byte_range) > 0,
"Buffer byte range starts behind the first byte! ", buffer_byte_range)
@bp_check(max_inclusive(buffer_byte_range) <= b.byte_size,
"Buffer byte range ends before the last byte! ", buffer_byte_range)
glNamedBufferSubData(
b.handle,
min_inclusive(buffer_byte_range) - 1,
size(buffer_byte_range),
data
)
return nothing
end
"Sets a buffer's data with an array and destination byte range"
function set_buffer_data(b::Buffer, data::AbstractArray, buffer_first_byte::Integer = 1)
T = eltype(data)
@bp_check(isbitstype(T), "Can't upload an array of non-bitstype '$T' to a GPU Buffer")
set_buffer_data(b, Ref(data, 1),
IntervalU(min=buffer_first_byte,
size=length(data)*sizeof(T)))
end
"Sets a buffer's data to a given bitstype data"
@inline function set_buffer_data(b::Buffer, bits_data, buffer_first_byte::Integer = 1)
@bp_check(isbits(bits_data),
typeof(bits_data), " isn't a bitstype")
set_buffer_data(b, Ref(bits_data),
IntervalU(min=buffer_first_byte,
size=sizeof(bits_data)))
end
# Vec is bitstype, but also AbstractArray. It should be treated as the former.
set_buffer_data(b::Buffer, v::Vec, buffer_first_byte::Integer = 1) = set_buffer_data(b, v.data, buffer_first_byte)
export set_buffer_data
#########################
# Buffer Copy #
#########################
"
Copies data from one buffer to another.
By default, copies as much data as possible.
"
function copy_buffer( src::Buffer, dest::Buffer
;
src_byte_offset::UInt = 0x0,
dest_byte_offset::UInt = 0x0,
byte_size::UInt = min(src.byte_size - src.byte_offset,
dest.byte_size - dest.byte_offset)
)
@bp_check(src_byte_offset + byte_size <= src.byte_size,
"Going outside the bounds of the 'src' buffer in a copy:",
" from ", src_byte_offset, " to ", src_byte_offset + byte_size)
@bp_check(dest_byte_offset + byte_size <= dest.byte_size,
"Going outside the bounds of the 'dest' buffer in a copy:",
" from ", dest_byte_offset, " to ", dest_byte_offset + byte_size)
@bp_check(dest.is_mutable_from_cpu, "Destination buffer is immutable")
glCopyNamedBufferSubData(src.handle, dest.handle,
src_byte_offset,
dest_byte_offset,
byte_size)
end
export copy_buffer
#########################
# Buffer Get #
#########################
"
Gets a buffer's data and writes it to the given pointer.
Optionally uses a subset of the buffer's bytes.
"
function get_buffer_data(b::Buffer, output::Ref,
buffer_byte_range::Interval{<:Integer} = IntervalU(
min=1,
size=b.byte_size
))::Nothing
@bp_check(min_inclusive(buffer_byte_range) > 0,
"Buffer byte range passes behind the start of the buffer: ", buffer_byte_range)
@bp_check(max_inclusive(buffer_byte_range) <= b.byte_size,
"Buffer byte range passes beyond the end of the buffer ",
"(size ", b.byte_size, ") ",
"(range ", min_inclusive(buffer_byte_range), " - ", max_inclusive(buffer_byte_range), ")")
glGetNamedBufferSubData(
b.handle,
min_inclusive(buffer_byte_range) - 1,
size(buffer_byte_range),
output
)
end
"Gets a buffer's data and returns it as an instance of the given bits-type"
function get_buffer_data(b::Buffer, ::Type{T},
buffer_first_byte::Integer = 1
)::T where {T}
@bp_check(isbitstype(T), T, " isn't a bitstype")
let r = Ref{T}()
get_buffer_data(b, r,
IntervalU(min=buffer_first_byte, size=sizeof(T)))
return r[]
end
end
"Gets a buffer's data and writes it into the given array of bitstypes"
function get_buffer_data(b::Buffer, a::AbstractArray{T},
buffer_first_byte::Integer = 1
)::Nothing where {T}
@bp_check(!isbitstype(a), typeof(a), " doesn't appear to be a mutable array")
# Note that we can't use ismutable() because some immutable structs hold a reference to mutable data
@bp_check(isbitstype(T), T, " isn't a bitstype")
if a isa SubArray
@bp_check(Base.iscontiguous(a),
"Array view isn't contiguous so it can't be uploaded to the GPU")
end
get_buffer_data(b, Ref(a, 1),
IntervalU(min=buffer_first_byte,
size=sizeof(T)*length(a)))
return nothing
end
"Gets a buffer's data and returns it as an array of the given count (per-axis) and bits-type"
function get_buffer_data(b::Buffer, output::Tuple{Type, Vararg{Integer}},
buffer_first_byte::Integer = 1)::Vector{output[1]}
(T, vec_size...) = output
@bp_check(isbitstype(T), T, "isn't a bitstype")
Dimensions = length(vec_size)
@bp_check(Dimensions > 0,
"Must provide at least one axis for the output array; provided ",
vec_size)
arr = Array{T, Dimensions}(undef, vec_size)
get_buffer_data(b, arr, buffer_first_byte)
return arr
end
export get_buffer_data | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 34695 | # Use the macros @std140 and @std430 to automatically pad your struct to match its GPU layout.
# The struct that is generated holds a byte array on the heap
# and offers properties to get/set fields by updating this byte array.
# It can also be automatically converted to a pointer for C calls/GPU uploads.
"
Some kind of bitstype data, laid out in a way that OpenGL/GLSL can understand.
While the structs themselves are immutable, they are backed by a mutable array
so you can set their properties.
To pass it into a C function, wrap it with a `Ref()` call.
To create an array of your block type `T`, construct `StaticBlockArray` with either
`StaticBlockArray{T}(bytes::AbstractVector{UInt8})` or
`StaticBlockArray{N, T}()`.
For simplicity, the buffer's bytes will always be filled with 0xAA by default,
and the `==` operator is defined to do fast bytewise comparison.
"
abstract type AbstractOglBlock end
abstract type OglBlock_std140 <: AbstractOglBlock end
abstract type OglBlock_std430 <: AbstractOglBlock end
#TODO: Dynamically support both 140 and 430 for each block type
export AbstractOglBlock, OglBlock_std140, OglBlock_std430
# Interface: #
"Gets the layout type of a struct (or struct type). An example return value is `OglBlock_std140`"
block_mode(a::AbstractOglBlock) = block_mode(typeof(a))
block_mode(::Type{<:OglBlock_std140}) = OglBlock_std140
block_mode(::Type{<:OglBlock_std430}) = OglBlock_std430
"
Block structs (and block arrays) have a type parameter for the kind of array backing their data.
This function strips that parameter from the type.
"
block_simple_type(::Type{<:AbstractOglBlock})::UnionAll = error()
"
Gets the total byte-size of the given struct (or array property), including padding.
Use this instead of `sizeof()`.
For convenience, falls through to `sizeof()` for non-block data types.
"
block_byte_size(x::AbstractOglBlock) = block_byte_size(typeof(x))
block_byte_size(T) = if isbitstype(T)
sizeof(T)
elseif T <: StaticBlockArray
error("Must provide all type-parameters to `StaticBlockArray`; provided: ", T)
else
error("Not bitstype: ", T)
end
block_byte_size(T::Type{<:AbstractOglBlock}) = error("Not implemented: ", T)
"Gets the amount of padding in the given struct, in bytes"
block_padding_size(b::AbstractOglBlock) = block_padding_size(typeof(b))
block_padding_size(T::Type{<:AbstractOglBlock}) = error("Not implemented: ", T)
block_alignment(b::AbstractOglBlock) = block_alignment(typeof(b))
block_alignment(T::Type{<:AbstractOglBlock}) = error("Not implemented: ", T)
const BUFFER_FIELD_NAME = Symbol("raw byte buffer")
"Gets the bytes of a block, as a mutable array of `UInt8`"
block_byte_array(b::AbstractOglBlock)::AbstractVector{UInt8} = getfield(b, BUFFER_FIELD_NAME)
"Returns the type of an `AbstractOglBlock`'s property"
@inline block_property_type(b::AbstractOglBlock, name::Symbol) = block_property_type(typeof(b), Val(name))
@inline block_property_type(T::Type{<:AbstractOglBlock}, name::Symbol) = block_property_type(T, Val(name))
@inline block_property_type(T::Type{<:AbstractOglBlock}, Name::Val) = error(T, " has no property '", val_type(Name))
"Returns a tuple of the type for each named property from `Base.propertynames`"
block_property_types(b::AbstractOglBlock) = block_property_types(typeof(b))
block_property_types(T::Type{<:AbstractOglBlock}) = error(T, " didn't implement ", block_property_types)
"
Emits declarations of the fields of an OpenGL struct or block,
based on the Julia struct you created with `@std140` or `@std430`
"
function glsl_decl(T::Type{<:AbstractOglBlock},
glsl_type_names::Dict{Type, String} = Dict{Type, String}()
; separator::String = "\n\t"
)::String
@bp_check(!isabstracttype(T), T, " is abstract")
return sprint() do io
for (i, (name, type)) in enumerate(zip(propertynames(T), block_property_types(T)))
if i > 1
print(io, "\n", separator)
end
print(io, glsl_type_decl(type, string(name), glsl_type_names), ";")
end
end
end
"A facade for a mutable array of items within an `AbstractOglBlock`"
abstract type BlockArray{T, TMode<:AbstractOglBlock, TByteArray<:AbstractVector{UInt8}} <: AbstractVector{T} end
"A facade for a mutable array of items within an `AbstractOglBlock`, of static size"
struct StaticBlockArray{N, T, TMode<:AbstractOglBlock, TByteArray<:AbstractVector{UInt8}} <: BlockArray{T, TMode, TByteArray}
buffer::TByteArray # Use same field name as the blocks themselves, for convenience
end
block_static_array_length(::Type{<:StaticBlockArray{N}}) where {N} = N
block_simple_type(::Type{<:StaticBlockArray{N, T, TMode}}) where {N, T, TMode} = StaticBlockArray{N, T, TMode}
export block_mode, block_simple_type, block_static_array_length,
block_byte_size, block_padding_size, block_alignment,
block_byte_array, block_property_type, block_property_types,
glsl_decl,
BlockArray, StaticBlockArray
# Internals: #
Buffer(can_change_data_from_cpu::Bool, T::Type{<:Union{AbstractOglBlock, StaticBlockArray}}
; recommend_storage_on_cpu::Bool = false
) = Buffer(block_byte_size(T), can_change_data_from_cpu, recommend_storage_on_cpu)
Buffer(can_change_data_from_cpu::Bool,
data::AbstractOglBlock
; recommend_storage_on_cpu::Bool = false
) = Buffer(can_change_data_from_cpu, block_byte_array(data); recommend_storage_on_cpu=recommend_storage_on_cpu)
Buffer(can_change_data_from_cpu::Bool,
data::BlockArray
; recommend_storage_on_cpu::Bool = false
) = Buffer(can_change_data_from_cpu, block_byte_array(data); recommend_storage_on_cpu=recommend_storage_on_cpu)
"Sets a buffer's data to contain the given `@std140` or `@std430` struct"
function set_buffer_data(buffer::Buffer, data::AbstractOglBlock, buffer_first_byte::Integer=1)
set_buffer_data(buffer, block_byte_array(data), buffer_first_byte)
end
"Gets a buffer's data as the given `@std140` or `@std430` struct type"
function get_buffer_data(b::Buffer, T::Type{<:AbstractOglBlock},
buffer_first_byte::Integer = 1
)::T
arr::Vector{UInt8} = get_buffer_data(b, (UInt8, block_byte_size(T)), buffer_first_byte)
return T{typeof(arr)}(arr)
end
"Sets a buffer's data to contain the given `BlockArray`"
function set_buffer_data(buffer::Buffer, data::BlockArray, buffer_first_byte::Integer=1)
set_buffer_data(buffer, block_byte_array(data), buffer_first_byte)
end
"
Gets a buffer's data as a kind of `BlockArray`,
for data mode `OglBlock_std140` or `OglBlock_std430`.
"
function get_buffer_data(b::Buffer,
TOut::Type{StaticBlockArray{N, T, TMode}},
buffer_first_byte::Integer = 1
)::T where {N, T, TMode}
arr::Vector{UInt8} = get_buffer_data(
b,
(UInt8, block_array_element_stride(T) * N),
buffer_first_byte
)
return TOut{typeof(arr)}(arr)
end
glsl_type_decl(T::Type , name, struct_lookup::Dict{Type, String}) = "$(glsl_type_decl(T, struct_lookup)) $name"
glsl_type_decl( ::Type{StaticBlockArray{N, T}}, name, struct_lookup::Dict{Type, String}) where {N, T} = "$(glsl_type_decl(T, struct_lookup)) $name[$N]"
glsl_type_decl(::Type{Bool}, struct_lookup::Dict{Type, String}) = "bool"
glsl_type_decl(::Type{Int32}, struct_lookup::Dict{Type, String}) = "int"
glsl_type_decl(::Type{Int64}, struct_lookup::Dict{Type, String}) = "int64_t"
glsl_type_decl(::Type{UInt32}, struct_lookup::Dict{Type, String}) = "uint"
glsl_type_decl(::Type{UInt64}, struct_lookup::Dict{Type, String}) = "uint64_t"
glsl_type_decl(::Type{Float32}, struct_lookup::Dict{Type, String}) = "float"
glsl_type_decl(::Type{Float64}, struct_lookup::Dict{Type, String}) = "double"
glsl_type_decl(::Type{Vec{N, Bool}}, struct_lookup::Dict{Type, String}) where {N} = "bvec$N"
glsl_type_decl(::Type{Vec{N, Int32}}, struct_lookup::Dict{Type, String}) where {N} = "ivec$N"
glsl_type_decl(::Type{Vec{N, UInt32}}, struct_lookup::Dict{Type, String}) where {N} = "uvec$N"
glsl_type_decl(::Type{Vec{N, Float32}}, struct_lookup::Dict{Type, String}) where {N} = "vec$N"
glsl_type_decl(::Type{Vec{N, Float64}}, struct_lookup::Dict{Type, String}) where {N} = "dvec$N"
glsl_type_decl(::Type{<:Mat{C, R, Float32}}, struct_lookup::Dict{Type, String}) where {C, R} = "mat$(C)x$(R)"
glsl_type_decl(::Type{<:Mat{C, R, Float64}}, struct_lookup::Dict{Type, String}) where {C, R} = "dmat$(C)x$(R)"
glsl_type_decl(T::Type{<:AbstractOglBlock}, struct_lookup::Dict{Type, String}) = get(struct_lookup, T,
# Stripping the module path from the type name is tricky.
if T isa UnionAll
string(T.body.name.name)
elseif T isa DataType
string(T.name.name)
else
error("Unexpected: ", typeof(T))
end
)
const BLOCK_DEFAULT_BYTE::UInt8 = 0xAA
Base.propertynames(x::AbstractOglBlock) = propertynames(typeof(x))
struct BlockRef{T<:AbstractOglBlock} <: Ref{T}
block::T
end
Base.Ref(a::AbstractOglBlock) = BlockRef{typeof(a)}(a)
Base.getindex(r::BlockRef) = r.block
Base.unsafe_convert(P::Type{<:Ptr{<:Union{UInt8, Cvoid, T}}}, r::BlockRef{T}) where {T} = begin
arr = block_byte_array(r.block)
return Base.unsafe_convert(P, Base.pointer(Ref(arr, 1)))
end
@inline Base.getproperty(a::AbstractOglBlock, name::Symbol) = let Name = Val(name)
block_property_get(
a, Name,
block_property_type(typeof(a), Name)
)
end
@inline Base.setproperty!(a::AbstractOglBlock, name::Symbol, value) = let Name = Val(name)
block_property_set(
a, Name,
block_property_type(typeof(a), Name),
value
)
end
# Equality and hashing:
function Base.:(==)(a::AbstractOglBlock, b::AbstractOglBlock)::Bool
if block_simple_type(typeof(a)) != block_simple_type(typeof(b))
return false
end
values_a = getproperty.(Ref(a), propertynames(typeof(a)))
values_b = getproperty.(Ref(b), propertynames(typeof(b)))
comparisons = values_a .== values_b
return all(comparisons)
end
Base.hash(a::AbstractOglBlock, h::UInt)::UInt = hash(getproperty.(Ref(a), propertynames(typeof(a))))
function Base.show(io::IO, a::AbstractOglBlock)
print(io, Base.typename(typeof(a)).name, '(')
for (i, prop) in enumerate(propertynames(a))
if i > 1
print(io, ", ")
end
show(io, getproperty(a, prop))
end
print(io, ')')
end
# Block Arrays: #
# (types defined above out of necessity)
"Returns the array's associated OglBlock type, OglBlock_std140 or OglBlock_std430" penis
block_array_mode(::BlockArray{T, TMode}) where {T, TMode} = TMode
# AbstractVector stuff:
Base.eltype(::BlockArray{T}) where {T} = T
Base.eltype(::Type{<:BlockArray{T}}) where {T} = T
function Base.size(a::BlockArray{T}) where {T}
stride = block_array_element_stride(T, block_array_mode(a))
n_bytes = length(block_byte_array(a))
@bp_gl_assert((n_bytes % stride) == 0, "$n_byte bytes total / $stride")
n_elements = n_bytes ÷ stride
return tuple(n_elements)
end
Base.Ref(a::BlockArray{T}, i::Integer = 1) where {T} = Ref(block_byte_array(a), i * block_array_element_stride(T, block_array_mode(a)))
@inline Base.getindex(a::BlockArray, i::Integer) = block_index_get(a, i, eltype(a))
@inline Base.setindex!(a::BlockArray, v, i::Integer) = block_index_set(a, i, eltype(a), v)
"Gets the mutable byte array underlying this array"
block_byte_array(b::BlockArray)::AbstractVector{UInt8} = getfield(b, :buffer)
@inline block_byte_size(x::BlockArray) = length(block_byte_array(x))
block_byte_size(::Type{<:StaticBlockArray{N, T, TMode}}) where {N, T, TMode} = N * block_array_element_stride(T, TMode)
Base.Ref(a::BlockArray, i) = Ref(block_byte_array(a), i)
"Constructs the block-array with an existing byte array"
StaticBlockArray{N, T }(a::AbstractVector{UInt8}) where {N, T<:AbstractOglBlock} = begin
byte_stride = block_array_element_stride(T, block_mode(T))
@bp_check(length(a) ÷ byte_stride == N,
"Should have provided ", byte_stride * N, " bytes but provided ", length(a))
StaticBlockArray{N, T, block_mode(T), typeof(a)}(a)
end
StaticBlockArray{N, T, TMode}(a::AbstractVector{UInt8}) where {N, T, TMode } = begin
byte_stride = block_array_element_stride(T, TMode)
@bp_check(length(a) ÷ byte_stride == N,
"Should have provided ", byte_stride * N, " bytes but provided ", length(a))
StaticBlockArray{N, T, TMode , typeof(a)}(a)
end
"Constructs the block-array with an element count"
StaticBlockArray{N, T }() where {N, T<:AbstractOglBlock} = StaticBlockArray{N, T, block_mode(T), Vector{UInt8}}(fill(BLOCK_DEFAULT_BYTE, block_array_element_stride(T, block_mode(T)) * N))
StaticBlockArray{N, T, TMode}() where {N, T, TMode } = StaticBlockArray{N, T, TMode , Vector{UInt8}}(fill(BLOCK_DEFAULT_BYTE, block_array_element_stride(T, TMode ) * N))
# Property/element getters and setters: #
# Block properties each have a type and a byte offset in the larger buffer.
block_property_type(block_type, Name)::Type = error(block_type, " has no property '", val_type(Name), "'")
block_property_first_byte(block_type, Name)::Int = error(block_type, " has no property '", val_type(Name), "'")
# Add helpful error messages for specific cases.
block_property_type(b::AbstractOglBlock, name) = error("You should pass in a type, not an instance")
block_property_type(b, name::Symbol) = error("You should pass in a Val{} for the name, not a Symbol")
block_property_first_byte(b::AbstractOglBlock, name) = error("You should pass in a type, not an instance")
block_property_first_byte(b, name::Symbol) = error("You should pass in a Val{} for the name, not a Symbol")
# Helpers to get the byte range for properties/elements.
function block_property_byte_range(block_type, Name)
T = block_property_type(block_type, Name)
b1 = block_property_first_byte(block_type, Name)
bN = block_field_size(T, block_mode(block_type))
return b1 : (b1 + bN - 1)
end
function block_array_byte_range(el_type, mode, index)
bN = block_array_element_stride(el_type, mode)
b1 = 1 + (bN * (index - 1))
return b1 : (b1 + bN - 1)
end
# You can get and set the properties of a buffer block.
block_property_get(block, name, TReturn) = error(
typeof(block), " has no property '",
val_type(name), "' of type ", TReturn
)
block_property_set(block, name, TReturn, value) = error(
typeof(block), " has no property '", val_type(name), "' of type ", TReturn,
", or it can't be set to a ", typeof(value)
)
# You can get and set elements of a buffer array.
block_index_get(block, i, TReturn) = error(typeof(block), " cannot be indexed to get a ", TReturn)
block_index_set(block, i, TReturn, value) = error(typeof(block), " cannot be indexed to set a ", TReturn, " to a ", typeof(value))
# Normal bitstype getters/setters.
@inline block_property_get(a::AbstractOglBlock, Name::Val, ::Type{TReturn}) where {TReturn} = reinterpret_bytes(
@view(block_byte_array(a)[block_property_byte_range(typeof(a), Name)]),
TReturn
)
@inline block_property_set(a::AbstractOglBlock, Name::Val, ::Type{TReturn}, value) where {TReturn} = reinterpret_bytes(
convert(TReturn, value),
@view(block_byte_array(a)[block_property_byte_range(typeof(a), Name)])
)
@inline block_index_get(a::BlockArray, i::Integer, ::Type{TReturn}) where {TReturn} = reinterpret_bytes(
@view(block_byte_array(a)[block_array_byte_range(TReturn, block_array_mode(a), i)]),
TReturn
)
@inline block_index_set(a::BlockArray, i::Integer, ::Type{TReturn}, value) where {TReturn} = reinterpret_bytes(
convert(TReturn, value),
@view(block_byte_array(a)[block_array_byte_range(TReturn, block_array_mode(a), i)])
)
# Bools are stored in a block as UInt32.
@inline block_property_get(a::AbstractOglBlock, Name::Val, ::Type{Bool})::Bool = !iszero(block_property_get(
a,
Name,
UInt32
))
@inline block_property_set(a::AbstractOglBlock, Name::Val, ::Type{Bool}, value) = block_property_set(
a, Name,
UInt32, convert(Bool, value) ? one(UInt32) : zero(UInt32)
)
@inline block_index_get(a::BlockArray, i::Integer, ::Type{Bool})::Bool = !iszero(block_index_get(
a, i, UInt32
))
@inline block_index_set(a::BlockArray, i::Integer, ::Type{Bool}, value) = block_index_set(
a, i,
UInt32, convert(Bool, value) ? one(UInt32) : zero(UInt32)
)
# Bool vectors in a block are stored as UInt32 vectors.
@inline block_property_get(a::AbstractOglBlock, Name::Val, ::Type{VecB{N}}) where {N} = map(f->!iszero(f), block_property_get(
a,
Name,
VecU{N}
))
@inline block_property_set(a::AbstractOglBlock, Name::Val, ::Type{VecB{N}}, value) where {N} = block_property_set(
a, Name,
UInt32,
map(f -> convert(Bool, f) ? one(UInt32) : zero(UInt32), value)
)
@inline block_index_get(a::BlockArray, i::Integer, ::Type{VecB{N}}) where {N} = map(f ->!iszero(f), block_index_get(
a, i, VecU{N}
))
@inline block_index_set(a::BlockArray, i::Integer, ::Type{VecB{N}}, value) where {N} = block_index_set(
a, i, VecU{N},
map(f -> convert(Bool, f) ? one(UInt32) : zero(UInt32), value)
)
# Matrix properties are stored in columns, like an array of vectors.
function block_property_get(a::AbstractOglBlock, Name::Val, ::Type{<:Mat{C, R, F}}) where {C, R, F}
arr = block_property_get(a, Name, StaticBlockArray{C, Vec{R, F}})
elements_by_column = Iterators.flatten(arr)
return @Mat(C, R, F)(elements_by_column...)
end
function block_property_set(a::AbstractOglBlock, Name::Val, ::Type{<:Mat{C, R, F}}, value) where {C, R, F}
arr = block_property_get(a, Name, StaticBlockArray{C, Vec{R, F}})
for col in 1:C
arr[col] = convert(Vec{R, F}, value[:, col])
end
end
function block_index_get(a::BlockArray, i::Integer, T::Type{<:Mat{C, R, F}}) where {C, R, F}
a_view = @view block_byte_array(a)[block_array_byte_range(T, block_array_mode(a), i)]
arr = StaticBlockArray{C, Vec{R, F}, block_array_mode(a)}(a_view)
column_vectors = Iterators.flatten(arr)
elements_by_column = Iterators.flatten(column_vectors)
return @Mat(C, R, F)(elements_by_column...)
end
function block_index_set(a::BlockArray, i::Integer, T::Type{<:Mat{C, R, F}}, value) where {C, R, F}
a_view = @view block_byte_array(a)[block_array_byte_range(T, block_array_mode(a), i)]
arr = StaticBlockArray{C, Vec{R, F}, block_array_mode(a)}(a_view)
for col in 1:C
arr[col] = convert(Vec{R, F}, value[:, col])
end
end
# Implementations of getter/setter for a property that is an array:
@inline function block_property_get(a::AbstractOglBlock, Name::Val, ::Type{<:StaticBlockArray{N, T}}
) where {N, T}
byte_range = block_property_byte_range(typeof(a), Name)
arr = @view(block_byte_array(a)[byte_range])
return StaticBlockArray{N, T, block_mode(a)}(arr)
end
@inline function block_property_set(a::AbstractOglBlock, Name::Val, ::Type{<:StaticBlockArray{N, T}},
values
) where {N, T}
@bp_gl_assert(length(values) == N,
"Expected to set ", typeof(a), ".", val_type(Name), " to an array of ",
N, " elements, but got ", length(values), " elements instead")
arr = block_property_get(a, Name, StaticBlockArray{N, T})
# The padding of the input array likely isn't going to line up with the std140 padding,
# so we have to set it element-by-element.
for (i, element) in enumerate(values)
arr[i] = element
end
end
# Implementations of getter/setter for a block property:
@inline function block_property_get(a::AbstractOglBlock, Name::Val, T::Type{<:AbstractOglBlock})
byte_range = block_property_byte_range(typeof(a), Name)
arr = @view block_byte_array(a)[byte_range]
return T{typeof(arr)}(arr)
end
@inline function block_property_set(a::AbstractOglBlock, Name::Val, ::Type{T}, value::T) where {T<:AbstractOglBlock}
byte_range = block_property_byte_range(typeof(a), Name)
block_byte_array(a)[byte_range] = block_byte_array(value)
end
# Implementations of getter/setter for an array element that's an OglBlock:
@inline function block_index_get(a::StaticBlockArray{N, T}, i::Integer, ::Type{T}) where {N, T<:AbstractOglBlock}
byte_range = block_array_byte_range(T, block_array_mode(a), i)
arr = @view block_byte_array(a)[byte_range]
return T{typeof(arr)}(arr)
end
@inline function block_index_set(a::StaticBlockArray{N, T}, i::Integer, ::Type{T}, value::T) where {N, T<:AbstractOglBlock}
b1 = 1 + (i * block_byte_size(T))
bN = block_byte_size(T)
bEnd = b1 + bN - 1
block_byte_range = block_array_byte_range(T, block_array_mode(a), i)
block_byte_array(a)[block_byte_range] = block_byte_array(value)
end
# OpenGL Spec implementation #
block_field_alignment()::Int = error("Unimplemented")
block_field_size()::Int = error("Unimplemented")
block_array_element_alignment()::Int = error("Unimplemented")
block_array_element_stride()::Int = error("Unimplemented")
block_field_alignment(T::Type{<:AbstractOglBlock}, mode::Type{<:AbstractOglBlock}) = block_alignment(T)
# Most scalars/vectors translate to the GPU trivially.
# However bools are 4 bytes.
block_field_alignment(T::Type{<:ScalarBits} , mode::Type{<:AbstractOglBlock}) = sizeof(T)
block_field_alignment( ::Type{Bool} , mode::Type{<:AbstractOglBlock}) = sizeof(UInt32)
block_field_alignment( ::Type{Vec{N, T}} , mode::Type{<:AbstractOglBlock}) where {N, T} =
if N == 3
block_field_alignment(Vec{4, T}, mode)
elseif T == Bool
block_field_alignment(Vec{N, UInt32}, mode)
else
N * sizeof(T)
end
# AbstractOglBlock's are already sized appropriately.
# Array fields are based on their elements.
block_field_alignment( ::Type{<:StaticBlockArray{N, T}} , mode::Type{<:AbstractOglBlock}) where {N, T} = block_array_element_alignment(T, mode)
# Matrices are like an array of column vectors.
block_field_alignment( ::Type{<:Mat{C, R, F}} , mode::Type{<:AbstractOglBlock}) where {C, R, F} =
block_field_alignment(StaticBlockArray{C, Vec{R, F}, mode}, mode)
block_field_size(T::Type , mode::Type{<:AbstractOglBlock}) = block_field_alignment(T, mode)
block_field_size( ::Type{<:Vec{N, T}} , mode::Type{<:AbstractOglBlock}) where {N, T} = N * sizeof((T == Bool) ? UInt32 : T)
block_field_size(T::Type{<:AbstractOglBlock} , mode::Type{<:AbstractOglBlock}) = block_byte_size(T)
block_field_size( ::Type{<:Mat{C, R, F}} , mode::Type{<:AbstractOglBlock}) where {C, R, F} = block_field_size(StaticBlockArray{C, Vec{R, F}, mode}, mode)
block_field_size( ::Type{<:StaticBlockArray{N, T}}, mode::Type{<:AbstractOglBlock}) where {N, T } = N * block_array_element_stride(T, mode)
# An array element's alignment is equal to its alignment as a field,
# if in std140 then rounded up to a multiple of v4f.
block_array_element_alignment(T, mode) = block_field_alignment(T, mode)
block_array_element_alignment(T, mode::Type{OglBlock_std140}) = round_up_to_multiple(block_field_alignment(T, mode), sizeof(v4f))
block_array_element_stride(T , mode) = block_array_element_alignment(T, mode)
block_array_element_stride(T::Type{<:AbstractOglBlock} , mode) = block_byte_size(T)
block_array_element_stride(T::Type{<:Mat{C}} , mode) where {C} = C * block_array_element_alignment(T, mode)
block_array_element_stride( ::Type{StaticBlockArray{N, T}} , mode) where {N, T} = N * block_array_element_stride(T, mode)
#= A new block struct (call it `s::S`) must implement the following:
* Base.propertynames(::Type{<:S})
* block_property_types(::Type{<:S})
* block_simple_type(::Type{<:S}) = S
* block_byte_size(::Type{<:S})
* block_padding_size(::Type{<:S})
* block_alignment(::Type{<:S})
* Per property:
* block_property_type(::Type{<:S}, ::Val)::Type
* block_property_first_byte(::Type{<:S}, ::Val)
* Internal constructor that takes an `AbstractVector{UInt8}`
* External constructor that takes all the fields and uses a `Vector{UInt8}` buffer initially filled with BLOCK_DEFAULT_BYTE
=#
"Set this global to print generated buffer structs to the stream"
BUFFER_LAYOUT_MACRO_DEBUG_STREAM::Optional{IO} = nothing
#TODO: Support some kind of annotation for row-major matrices.
"""
Generates a struct of OpenGL data,
whose byte layout exactly follows the std140 standard in shader blocks.
The struct is backed by a mutable byte array, so you can get *and set* its properties.
You can also nest `@std140` structs within each other and they will be laid out as the GPU expects.
Sample usage:
````
@std140 struct MyInnerUniformBlock
f::Float32
bools::vb4
position_array::StaticBlockArray{12, v3f}
end
@std140 struct MyOuterUniformBlock
i::Int32 # Be careful; 'Int' in Julia means Int64
items::StaticBlockArray{5, MyInnerUniformBlock}
b::Bool
end
const MY_UBO_DATA = MyOuterUniformBlock(
3,
ntuple(i -> zero(MyInnerUniformBlock), 5),
true
)
println("MyOuterUniformBlock takes up ", length(block_byte_array(MY_UBO_DATA)), " bytes, ",
block_padding_size(MY_UBO_DATA), " of which is padding")
println("i is ", MY_UBO_DATA.i)
MY_UBO_DATA.i = 1122334455
println("Now i is ", MY_UBO_DATA.i)
# Upload the data to your GPU buffer:
set_buffer_data(my_ubo, MY_UBO_DATA)
# Download the data from your GPU buffer into a new or existing instance of the struct:
my_ubo_data = get_buffer_data(my_ubo, MyOuterUniformBlock)
get_buffer_data(my_second_ubo, my_ubo_data)
````
"""
macro std140(struct_expr)
return block_struct_impl(struct_expr, OglBlock_std140, __module__)
end
"""
Generates a struct of OpenGL data,
whose byte layout exactly follows the std430 standard in shader blocks.
The struct is backed by a mutable byte array, so you can get *and set* its properties.
You can also nest `@std430` structs within each other and they will be laid out as the GPU expects.
Sample usage:
````
@std140 struct MyInnerUniformBlock
f::Float32
bools::vb4
position_array::StaticBlockArray{12, v3f}
end
@std430 struct MyOuterShaderStorageBlock
i::Int32 # Be careful; 'Int' in Julia means Int64
items::StaticBlockArray{5, MyInnerShaderStorageBlock}
b::Bool
end
const MY_SSBO_DATA = MyOuterShaderStorageBlock(
3,
ntuple(i -> zero(MyInnerShaderStorageBlock), 5),
true
)
println("MyOuterShaderStorageBlock takes up ", length(block_byte_array(MY_SSBO_DATA)), " bytes, ",
block_padding_size(MY_SSBO_DATA), " of which is padding")
println("i is ", MY_SSBO_DATA.i)
MY_SSBO_DATA.i = 1122334455
println("Now i is ", MY_SSBO_DATA.i)
# Upload the data to your GPU buffer:
set_buffer_data(my_ssbo, MY_SSBO_DATA)
# Download the data from your GPU buffer into a new or existing instance of the struct:
my_ssbo_data = get_buffer_data(my_ssbo, MyOuterShaderStorageBlock)
get_buffer_data(my_second_ssbo, my_ssbo_data)
````
"""
macro std430(struct_expr)
return block_struct_impl(struct_expr, OglBlock_std430, __module__)
end
function block_struct_impl(struct_expr, mode::Type{<:AbstractOglBlock}, invoking_module::Module)
if !Base.is_expr(struct_expr, :struct)
error("Expected struct block, got: ", struct_expr)
elseif struct_expr.args[1]
error("UBO struct cannot be mutable; wrap it in a Ref if you want that!")
end
mode_switch(std140, std430) = if mode == OglBlock_std140
std140()
elseif mode == OglBlock_std430
std430()
else
error("Unexpected mode: ", mode)
end
base_type::Type{<:AbstractOglBlock} = mode
mode_description = mode_switch(() -> :std140,
() -> :std430)
SCALAR_TYPE = Union{Scalar32, Scalar64, Bool}
VECTOR_TYPE = Union{(
Vec{n, t}
for (n, t) in Iterators.product(1:4, union_types(SCALAR_TYPE))
)...}
MATRIX_TYPE = Union{(
@Mat(c, r, f)
for (c, r, f) in Iterators.product(1:4, 1:4, (Float32, Float64))
)...}
NON_ARRAY_TYPE = Union{SCALAR_TYPE, VECTOR_TYPE, MATRIX_TYPE, base_type}
ARRAY_TYPE = StaticBlockArray{N, <:NON_ARRAY_TYPE} where {N}
# Parse the header.
(is_mutable_from_cpu::Bool, struct_name, body::Expr) = struct_expr.args
if !isa(struct_name, Symbol)
error(mode_description, " struct has invalid name: '", struct_name, "'")
elseif is_mutable_from_cpu
@warn "You declared $struct_name as mutable, which is non-standard syntax and does not change anything"
end
# Parse the body.
lines = [line for line in body.args if !isa(line, LineNumberNode)]
function check_field_errors(field_name, T, is_within_array::Bool = false)
if T <: Vec
if !(T <: VECTOR_TYPE)
error("Invalid vector count or type in ", field_name, ": ", T)
end
elseif T <: Mat
if !(T <: MATRIX_TYPE)
error("Invalid matrix size or component type in ", field_name, ": ", T)
end
elseif T <: StaticBlockArray
if is_within_array
error("No nested arrays allowed, for simplicity. Flatten field ", field_name)
end
check_field_errors(field_name, eltype(T), true)
elseif isstructtype(T)
if !(T <: base_type)
error("Non-", mode_description, " struct referenced by ", field_name, ": ", T)
end
elseif T <: SCALAR_TYPE
# Nothing to check
else
error("Unexpected type in field ", struct_name, ".", field_name, ": ", T)
end
end
field_definitions = map(lines) do line
if !Base.is_expr(line, :(::))
error("Expected only field declarations ('a::B'). Got: ", line)
end
(field_name, field_type) = line.args
if !isa(field_name, Symbol)
error("Name of the field should be a simple token. Got: '", field_name, "'")
end
field_type = invoking_module.eval(field_type)
if !isa(field_type, Type)
error("Expected a concrete type for the field's value. Got ", field_type)
end
check_field_errors(field_name, field_type)
return (field_name, field_type)
end
# Figure out padding and field offsets.
total_byte_size::Int = 0
total_padding_bytes::Int = 0
max_field_alignment::Int = 0
property_offsets = Vector{Int}()
function align_to(alignment)
max_field_alignment = max(max_field_alignment, alignment)
missing_bytes = (alignment - (total_byte_size % alignment))
if missing_bytes < alignment # Only if not already aligned
total_byte_size += missing_bytes
total_padding_bytes += missing_bytes
end
end
for (field_name, field_type) in field_definitions
field_alignment = block_field_alignment(field_type, mode)
field_size = block_field_size(field_type, mode)
# Insert padding bytes to align the field.
align_to(field_alignment)
# Insert the field's own bytes.
push!(property_offsets, total_byte_size)
total_byte_size += block_field_size(field_type, mode)
end
# Struct alignment is based on the largest alignment of its fields.
struct_alignment = mode_switch(
() -> round_up_to_multiple(max_field_alignment, sizeof(v4f)),
() -> max_field_alignment
)
# Add padding to the struct to match its alignment.
# Note that this inadvertently modifies 'max_field_alignment',
# but that variable isn't used past this point.
align_to(struct_alignment)
max_field_alignment = -1
# Generate the functions that need generating.
struct_name_esc = esc(struct_name)
struct_type_esc = :( Type{<:$struct_name_esc} )
output = quote
Core.@__doc__ struct $struct_name_esc{Buffer<:AbstractVector{UInt8}} <: $mode
$(BUFFER_FIELD_NAME)::Buffer
$struct_name_esc() = new{Vector{UInt8}}(fill(
$BLOCK_DEFAULT_BYTE,
$(@__MODULE__).block_byte_size($struct_name_esc)
))
$struct_name_esc{TArray}(buffer::TArray) where {TArray<:AbstractVector{UInt8}} = new{TArray}(buffer)
end
$(@__MODULE__).block_simple_type(::$struct_type_esc) = $struct_name_esc
# Constructor that takes field values:
if $(!isempty(field_definitions))
function $struct_name_esc($((esc(n) for (n, t) in field_definitions)...))
s = $struct_name_esc{Vector{UInt8}}(fill(BLOCK_DEFAULT_BYTE, block_byte_size($struct_name_esc)))
# Set each property to its corresponding constructor parameter.
$((map(field_definitions) do (n,t); :(
s.$n = $(esc(n))
) end)...)
return s
end
end
# Provide metadata.
$(@__MODULE__).block_byte_size(::$struct_type_esc) = $total_byte_size
$(@__MODULE__).block_padding_size(::$struct_type_esc) = $total_padding_bytes
$(@__MODULE__).block_alignment(::$struct_type_esc) = $struct_alignment
# Advertise this type's properties.
$Base.propertynames(::$struct_type_esc) = $(Tuple(
n for (n, t) in field_definitions
))
$(@__MODULE__).block_property_types(::$struct_type_esc) = tuple($((
t for (n, t) in field_definitions
)...))
$((map(zip(field_definitions, property_offsets)) do ((field_name, field_type), field_offset)
name_val_expr = :( Val{$(QuoteNode(field_name))} )
quote
$(@__MODULE__).block_property_type( ::$struct_type_esc, ::$name_val_expr) = $field_type
$(@__MODULE__).block_property_first_byte(::$struct_type_esc, ::$name_val_expr) = $field_offset + 1
end
end)...)
end
if exists(BUFFER_LAYOUT_MACRO_DEBUG_STREAM)
println(BUFFER_LAYOUT_MACRO_DEBUG_STREAM,
"@", mode_description, "(", struct_name, "):",
"\n", output)
end
return output
end
export @std140, @std430 | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 10717 | ###############################
# VertexDataSource #
###############################
"
A reference to an array of data stored in a Buffer.
The elements of the array could be numbers, vectors, matrices,
or entire structs.
"
struct VertexDataSource
buf::Buffer
element_byte_size::UInt
buf_byte_offset::UInt
#TODO: For convenience, optionally manage a Buffer internally, with data provided in the constructor.
end
VertexDataSource(buf, element_byte_size::Integer, buf_byte_offset::Integer = 0) =
VertexDataSource(buf, UInt(element_byte_size), UInt(buf_byte_offset))
"Gets the maximum number of elements which can be pulled from the given data source"
function get_max_elements(data::VertexDataSource)
@bp_gl_assert(data.buf.byte_size >= data.buf_byte_offset,
"VertexDataSource's buffer is ", data.buf.byte_size,
", but the byte offset is ", data.buf_byte_offset)
max_bytes = data.buf.byte_size - data.buf_byte_offset
return max_bytes ÷ data.element_byte_size
end
export VertexDataSource, get_max_elements
##############################
# VertexAttribute #
##############################
"Pulls data out of the elements of a VertexDataSource"
struct VertexAttribute
# A reference to the VertexDataSource, as its index in some list (with 1-based indexing).
data_source_idx::Int
# The byte offset from each element of the VertexDataSource
# to the specific field inside it.
field_byte_offset::UInt
# The type of this data.
field_type::AbstractVertexShaderInput
# If 0, this data is regular old per-vertex data.
# If 1, this data is per-instance, for instanced rendering.
# If 2, this data is per-instance, and each element is reused for 2 consecutive instances.
# etc.
per_instance::UInt
end
VertexAttribute(data_source_idx::Integer,
field_byte_offset::Integer,
field_type::AbstractVertexShaderInput,
per_instance::Integer = 0) =
VertexAttribute(Int(data_source_idx), UInt(field_byte_offset),
field_type, UInt(per_instance))
export VertexAttribute
#########################
# Other Data #
#########################
# The different kinds of shapes that mesh vertices can represent.
@bp_gl_enum(PrimitiveTypes::GLenum,
# Each vertex is a screen-space square.
point = GL_POINTS,
# Each pair of vertices is a line.
# If the number of vertices is odd, the last one is ignored.
line = GL_LINES,
# Each triplet of vertices is a triangle.
# If the number of vertices is not a multiple of three, the last one/two are ignored.
triangle = GL_TRIANGLES,
# Each vertex creates a line reaching backwards to the previous vertex.
# If there's only one vertex, no lines are created.
line_strip_open = GL_LINE_STRIP,
# Each vertex creates a line reaching backwards to the previous vertex.
# The last vertex also reaches out to the first, creating a closed loop.
# If there's only one vertex, no lines are created.
line_strip_closed = GL_LINE_LOOP,
# Each new vertex creates a triangle with the two previous vertices.
# If there's only one or two vertices, no triangles are created.
triangle_strip = GL_TRIANGLE_STRIP,
# Each new vertex creates a triangle with its previous vertex plus the first vertex.
# If there's only one or two vertices, no triangles are created.
triangle_fan = GL_TRIANGLE_FAN
);
"The set of valid types for mesh indices"
const MeshIndexTypes = Union{UInt8, UInt16, UInt32}
"Gets the OpenGL enum corresponding to mesh index data of the given type"
get_index_ogl_enum(::Type{UInt8}) = GL_UNSIGNED_BYTE
get_index_ogl_enum(::Type{UInt16}) = GL_UNSIGNED_SHORT
get_index_ogl_enum(::Type{UInt32}) = GL_UNSIGNED_INT
"Gets the OpenGL enum corresponding to mesh index data of the given size"
get_index_ogl_enum(byte_size::Integer) = get_index_ogl_enum(get_index_type(byte_size))
"Gets the mesh index type, given its byte size"
get_index_type(byte_size::Integer) =
if byte_size == 1
UInt8
elseif byte_size == 2
UInt16
elseif byte_size == 4
UInt32
else
error("Not a valid size for mesh index data: ", byte_size)
end
export MeshIndexTypes, PrimitiveTypes, E_PrimitiveTypes
export get_index_type, get_index_ogl_enum
###################
# Mesh #
###################
"A reference to an index buffer for a mesh."
struct MeshIndexData
buffer::Buffer
type::Type{<:MeshIndexTypes}
end
"
A collection of vertices (and optionally indices),
representing geometry that the GPU can render.
The vertex data and indices are taken from a set of Buffers.
This is what OpenGL calls a 'VAO' or 'VertexArrayObject'.
Most data will be per-'vertex', but some data can be
per-instance, for instanced rendering.
"
mutable struct Mesh <: AbstractResource
handle::Ptr_Mesh
type::E_PrimitiveTypes
vertex_data_sources::ConstVector{VertexDataSource}
vertex_data::ConstVector{VertexAttribute}
# The source of the index data, if this mesh uses indices.
index_data::Optional{MeshIndexData}
end
function Mesh( type::E_PrimitiveTypes,
vertex_sources::AbstractVector{VertexDataSource},
vertex_fields::AbstractVector{VertexAttribute},
index_data::Optional{MeshIndexData} = nothing
)
@bp_check(exists(get_context()), "Trying to create a Mesh outside a GL Context")
m::Mesh = Mesh(Ptr_Mesh(get_from_ogl(gl_type(Ptr_Mesh), glCreateVertexArrays, 1)),
type,
tuple(vertex_sources...), tuple(vertex_fields...),
index_data)
# Configure the index buffer.
if exists(index_data)
glVertexArrayElementBuffer(m.handle, index_data.buffer.handle)
end
# Configure the vertex buffers.
for i::Int in 1:length(vertex_sources)
glVertexArrayVertexBuffer(m.handle, GLuint(i - 1),
vertex_sources[i].buf.handle,
vertex_sources[i].buf_byte_offset,
vertex_sources[i].element_byte_size)
end
# Configure the vertex data.
# I suspect that this can be done with one loop instead of three, but I'm not certain of that
# and it shouldn't make any noticeable difference in performance anyway.
for i::Int in 1:length(vertex_fields)
glEnableVertexArrayAttrib(m.handle, GLuint(i - 1))
end
vert_attrib_idx::GLuint = zero(GLuint)
for (i::Int, vert::VertexAttribute) in enumerate(vertex_fields)
# The OpenGL calls to set up vertex attributes have mostly the same arguments,
# regardless of the field type.
# One exception is the 'isNormalized' parameter.
normalized_args = ()
get_gl_args() = (m.handle, vert_attrib_idx,
count_components(vert.field_type),
get_component_ogl_enum(vert.field_type),
normalized_args...,
vert.field_byte_offset)
# Pick the correct OpenGL call for this type of vertex data.
gl_func = nothing
if vert.field_type isa VSInput_IntVector
gl_func = glVertexArrayAttribIFormat
elseif vert.field_type isa VSInput_DoubleVector
gl_func = glVertexArrayAttribLFormat
elseif vert.field_type isa VSInput_Matrix
if vert.field_type.type == VertexInputMatrixTypes.float32
normalized_args = tuple(GL_FALSE)
gl_func = glVertexArrayAttribFormat
elseif vert.field_type.type == VertexInputMatrixTypes.float64
gl_func = glVertexArrayAttribLFormat
else
error("Unimplemented: ", vert.field_type.type)
end
elseif vert.field_type isa VSInput_FloatVector
normalized_args = tuple(fvector_data_is_normalized(vert.field_type) ? GL_TRUE : GL_FALSE)
gl_func = glVertexArrayAttribFormat
else
error("Unhandled case: ", typeof(vert.field_type))
end
# Make the OpenGL calls, and increment the vertex attribute counter.
for _ in 1:count_attribs(vert.field_type)
gl_func(get_gl_args()...)
glVertexArrayBindingDivisor(m.handle, vert_attrib_idx, vert.per_instance)
vert_attrib_idx += 1
end
end
for (i::Int, vert::VertexAttribute) in enumerate(vertex_fields)
glVertexArrayAttribBinding(m.handle, GLuint(i - 1), GLuint(vert.data_source_idx - 1))
end
return m
end
function Base.close(m::Mesh)
@bp_check(m.handle != Ptr_Mesh(), "Already closed this Mesh")
glDeleteVertexArrays(1, Ref{GLuint}(m.handle))
setfield!(m, :handle, Ptr_Mesh())
end
export MeshIndexData, Mesh
##############################
# Mesh Operations #
##############################
"
Gets the maximum number of vertices this mesh can offer for rendering,
based only on vertex data (not index data).
"
function count_mesh_vertices(m::Mesh)::Int
# Find the smallest set of per-vertex data within this mesh.
n_elements::Optional{Int} = nothing
for vertex_data::VertexAttribute in m.vertex_data
if vertex_data.per_instance == 0
buf_source::VertexDataSource = m.vertex_data_sources[vertex_data.data_source_idx]
n_vert_elements = get_max_elements(buf_source)
if isnothing(n_elements) || (n_vert_elements < n_vert_elements)
n_elements = n_vert_elements
end
end
end
# Edge-case: if there's no per-vertex data (meaning it's all per-instance?), return 0
return exists(n_elements) ? n_elements : 0
end
"
Gets the maximum number of vertices (or indices, if indexed)
this mesh can offer for rendering.z
"
function count_mesh_elements(m::Mesh)::Int
if exists(m.index_data)
return m.index_data.buffer.byte_size ÷ sizeof(m.index_data.type)
else
return count_mesh_vertices(m)
end
end
"Adds/changes the index data for this mesh"
function set_index_data(m::Mesh, source::Buffer, type::Type{<:MeshIndexTypes})
setfield!(m, :index_data, MeshIndexData(source, type))
glVertexArrayElementBuffer(m.handle, source.buf.handle)
end
"
Removes any existing index data from this Mesh,
so that its vertices are no longer indexed.
Does nothing if it already wasn't indexed.
"
function remove_index_data(m::Mesh)
setfield!(m, :index_data, nothing)
glVertexArrayElementBuffer(m.handle, Ptr_Buffer())
end
export count_mesh_vertices, count_mesh_elements, set_index_data, remove_index_data | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 11996 | #=
The types of Buffer data that can be read as input into the vertex shader are:
* 1D - 4D vector of 32-bit int (or uint)
* 1D - 4D vector of 64-bit doubles
* 2x2 - 4x4 matrix of 32-bit floats or 64-bit doubles
* 1D - 4D vector of 32-bit float
Most of these inputs are simple, except for the most common type: 32-bit float vectors.
Float vectors can be created from any of the following:
* From 16-bit, 32-bit, or 64-bit float components
* From int/uint components, normalized (or alternatively, casted from int to float)
* From 32-bit fixed decimal components
* From special pre-packed data formats
=#
"Some kind of vertex data that can be read from a Buffer."
abstract type AbstractVertexShaderInput end
"Gets the byte-size of one vertex input of the given type"
vertex_data_byte_size(i::AbstractVertexShaderInput) = error("vertex_data_byte_size() not implemented for ", i)
"Gets the OpenGL enum for the given type"
get_component_ogl_enum(i::AbstractVertexShaderInput) = error("get_component_ogl_enum() not implemented for ", i)
"
Gets the number of components in this type's OpenGL vertex attributes
(i.e. the length of a vector, or the number of columns in a matrix).
"
count_components(i::AbstractVertexShaderInput) = error("count_components() not implemented for ", i)
"
Gets the number of OpenGL vertex attributes that are needed for this data type
(i.e. 1 for a vector, or the number of rows in a matrix).
"
count_attribs(i::AbstractVertexShaderInput) = error("count_attribs() not implemented for ", i)
export AbstractVertexShaderInput
#
###############################
# Basic Types #
###############################
@bp_enum(VertexInputVectorDimensions, D1=1, D2=2, D3=3, D4=4)
@bp_enum(VertexInputMatrixDimensions, D2=2, D3=3, D4=4)
@bp_enum(VertexInputIntSizes, B8=1, B16=2, B32=4)
@bp_enum(VertexInputFloatSizes, B16=2, B32=4, B64=8)
@bp_enum(VertexInputMatrixTypes, float32=4, float64=8)
struct VSInput_IntVector <: AbstractVertexShaderInput
n_dimensions::E_VertexInputVectorDimensions
is_signed::Bool
type::E_VertexInputIntSizes
end
struct VSInput_DoubleVector <: AbstractVertexShaderInput
n_dimensions::E_VertexInputVectorDimensions
end
struct VSInput_Matrix <: AbstractVertexShaderInput
n_rows::E_VertexInputMatrixDimensions
n_columns::E_VertexInputMatrixDimensions
type::E_VertexInputMatrixTypes
end
abstract type VSInput_FloatVector <: AbstractVertexShaderInput end
export VSInput_IntVector, VSInput_FloatVector, VSInput_DoubleVector, VSInput_Matrix
#########################################
# Basic Implementations #
#########################################
vertex_data_byte_size(i::VSInput_IntVector) = sizeof(i.is_signed ? Int32 : UInt32) * Int(i.n_dimensions)
vertex_data_byte_size(i::VSInput_DoubleVector) = sizeof(Float64) * Int(i.n_dimensions)
vertex_data_byte_size(i::VSInput_Matrix) = Int(i.type) * Int(i.n_rows) * Int(i.n_columns)
function get_component_ogl_enum(i::VSInput_IntVector)
if i.is_signed
if i.type == VertexInputIntSizes.B8
return GL_BYTE
elseif i.type == VertexInputIntSizes.B16
return GL_SHORT
elseif i.type == VertexInputIntSizes.B32
return GL_INT
else
error("Unimplemented: signed ", i.type)
end
else # Unsigned
if i.type == VertexInputIntSizes.B8
return GL_UNSIGNED_BYTE
elseif i.type == VertexInputIntSizes.B16
return GL_UNSIGNED_SHORT
elseif i.type == VertexInputIntSizes.B32
return GL_UNSIGNED_INT
else
error("Unimplemented: unsigned ", i.type)
end
end
end
function get_component_ogl_enum(i::VSInput_DoubleVector)
return GL_DOUBLE
end
function get_component_ogl_enum(i::VSInput_Matrix)
if i.type == VertexInputMatrixTypes.float32
return GL_FLOAT
elseif i.type == VertexInputMatrixTypes.float64
return GL_DOUBLE
else
error("Unhandled case: ", i.type)
end
end
count_components(i::VSInput_IntVector) = Int(i.n_dimensions)
count_components(i::VSInput_DoubleVector) = Int(i.n_dimensions)
count_components(i::VSInput_Matrix) = Int(i.n_columns)
count_attribs(i::VSInput_IntVector) = 1
count_attribs(i::VSInput_DoubleVector) = 1
count_attribs(i::VSInput_Matrix) = Int(i.n_rows)
#########################################
# Float Implementations #
#########################################
fvector_data_is_normalized(i::VSInput_FloatVector) = error("Not implemented: ", typeof(i))
# Assume all sub-types have a field 'n_dimensions::E_VertexInputVectorDimensions'.
count_components(i::VSInput_FloatVector) = Int(i.n_dimensions)
count_attribs(::VSInput_FloatVector) = 1
"
Vertex data that comes in as some kind of float vector (e.x. Float16)
and appears in the shader as a Float32 vector
"
struct VSInput_FVector_Plain <: VSInput_FloatVector
n_dimensions::E_VertexInputVectorDimensions
in_size::E_VertexInputFloatSizes
end
VSInput_FVector_Plain(n_dimensions::Integer, component_byte_size::Integer) = VSInput_FVector_Plain(
E_VertexInputVectorDimensions(n_dimensions),
E_VertexInputFloatSizes(component_byte_size)
)
VSInput_FVector_Plain(n_dimensions::Integer, component_type::Type{<:AbstractFloat}) = VSInput_FVector_Plain(
E_VertexInputVectorDimensions(n_dimensions),
E_VertexInputFloatSizes(sizeof(component_type))
)
fvector_data_is_normalized(i::VSInput_FVector_Plain) = false
vertex_data_byte_size(i::VSInput_FVector_Plain) = Int(i.in_size) * Int(i.n_dimensions)
function get_component_ogl_enum(i::VSInput_FVector_Plain)
if i.in_size == VertexInputFloatSizes.B16
return GL_HALF_FLOAT
elseif i.in_size == VertexInputFloatSizes.B32
return GL_FLOAT
elseif i.in_size == VertexInputFloatSizes.B64
return GL_DOUBLE
else
error("Unhandled case: ", i.in_size)
end
end
"
Vertex data that comes in as some kind of integer vector,
and gets interpreted as 32-bit float vector.
If 'normalized' is true, then the values are converted
from the integer's range to the range [0, 1] or [-1, 1].
Otherwise, the values are simply casted to float.
"
struct VSInput_FVector_FromInt <: VSInput_FloatVector
input::VSInput_IntVector
normalized::Bool
end
fvector_data_is_normalized(i::VSInput_FVector_FromInt) = i.normalized
count_components(i::VSInput_FVector_FromInt) = count_components(i.input)
vertex_data_byte_size(i::VSInput_FVector_FromInt) = vertex_data_byte_size(i.input)
get_component_ogl_enum(i::VSInput_FVector_FromInt) = get_component_ogl_enum(i.input)
"
Vertex data that comes in as a vector of fixed-point decimals (16 integer bits, 16 fractional bits)
and gets casted into float32
"
struct VSInput_FVector_Fixed <: VSInput_FloatVector
n_dimensions::E_VertexInputVectorDimensions
end
fvector_data_is_normalized(i::VSInput_FVector_Fixed) = false
vertex_data_byte_size(i::VSInput_FVector_Fixed) = 4 * Int(i.n_dimensions)
get_component_ogl_enum(i::VSInput_FVector_Fixed) = GL_FIXED
"
Vertex data that comes in as a 32-bit uint, and gets interpreted as
an RGB vector of 32-bit floats.
The uint stores 3 unsigned floats, in order:
1. 10 bits for Blue/Z
2. 11 bits for Green/Y
3. 11 more for Red/X
#TODO: How many bits for mantissa vs exponent?
"
struct VSInput_FVector_Packed_UF_B10_G11_R11 <: VSInput_FloatVector
end
fvector_data_is_normalized(i::VSInput_FVector_Packed_UF_B10_G11_R11) = false
count_components(i::VSInput_FVector_Packed_UF_B10_G11_R11) = 3
vertex_data_byte_size(i::VSInput_FVector_Packed_UF_B10_G11_R11) = 4
get_component_ogl_enum(i::VSInput_FVector_Packed_UF_B10_G11_R11) = GL_UNSIGNED_INT_10F_11F_11F_REV
"
Vertex data that comes in as a 32-bit uint, and gets interpreted as
an RGBA vector of 32-bit floats.
The uint stores the components as integers, optionally signed and/or normalized:
2 bits for Alpha/W,
10 bits for Blue/Z,
10 bits for Green/Y,
then 10 bis for Red/X.
The integer values for each component are either normalized to the 0-1 range,
or simply casted to float.
"
struct VSInput_FVector_Packed_A2_BGR10 <: VSInput_FloatVector
signed::Bool
normalized::Bool
end
fvector_data_is_normalized(i::VSInput_FVector_Packed_A2_BGR10) = i.normalized
count_components(i::VSInput_FVector_Packed_A2_BGR10) = 4
vertex_data_byte_size(i::VSInput_FVector_Packed_A2_BGR10) = 4
get_component_ogl_enum(i::VSInput_FVector_Packed_A2_BGR10) = i.signed ?
GL_INT_2_10_10_10_REV :
GL_UNSIGNED_INT_2_10_10_10_REV
export VSInput_FVector_Plain, VSInput_FVector_FromInt, VSInput_FVector_Fixed,
VSInput_FVector_Packed_A2_BGR10, VSInput_FVector_Packed_UF_B10_G11_R11
############################################
# Convenience constructors #
############################################
"Creates a 1D float- or int- or double-vector vertex input"
function VSInput(T::Type{<:Union{Float32, Float64, Integer}})
dims = VertexInputVectorDimensions.D1
if T == Float64
return VSInput_DoubleVector(dims)
elseif T <: AbstractFloat
return VSInput_FVector_Plain(dims,
E_VertexInputFloatSizes(sizeof(T)))
elseif T <: Integer
return VSInput_IntVector(dims,
T <: Signed,
E_VertexInputIntSizes(sizeof(T)))
else
error("Unexpected scalar type for VSInput(): ", T)
end
end
"Creates a simple float- or int- or double-vector vertex input"
function VSInput(::Type{Vec{N, T}}) where {N, T}
if T == Float64
return VSInput_DoubleVector(E_VertexInputVectorDimensions(N))
elseif T <: AbstractFloat
return VSInput_FVector_Plain(E_VertexInputVectorDimensions(N),
E_VertexInputFloatSizes(sizeof(T)))
elseif T <: Integer
return VSInput_IntVector(E_VertexInputVectorDimensions(N),
T <: Signed,
E_VertexInputIntSizes(sizeof(T)))
else
error("Unexpected vector type for VSInput(): ", Vec{N, T})
end
end
"Creates a float or double matrix input"
function VSInput(::Type{<:Mat{C, R, F}}) where {C, R, F<:AbstractFloat}
c = E_VertexInputMatrixDimensions(C)
r = E_VertexInputMatrixDimensions(R)
if F == Float32
return VSInput_Matrix(r, c, VertexInputMatrixTypes.float32)
elseif F == Float64
return VSInput_Matrix(r, c, VertexInputMatrixTypes.float64)
else
error("Unsupported matrix type for VSInput(): ", Mat{C, R, F})
end
end
"Creates a type for an integer vector that get casted or normalized into a float vector in the shader"
function VSInput_FVector(::Type{Vec{N, I}}, normalized::Bool) where {N, I<:Integer}
return VSInput_FVector_FromInt(VSInput(Vec{N, I}), normalized)
end
VSInput_IntVector(n_dimensions::Integer, is_signed::Bool, component_byte_size::Integer) = VSInput_IntVector(
E_VertexInputVectorDimensions(n_dimensions),
is_signed,
E_VertexInputIntSizes(component_byte_size)
)
VSInput_DoubleVector(n_dimensions::Integer) = VSInput_DoubleVector(
E_VertexInputVectorDimensions(n_dimensions)
)
VSInput_FVector_Fixed(n_dimensions::Integer) = VSInput_FVector_Fixed(
E_VertexInputVectorDimensions(n_dimensions)
)
VSInput_Matrix(n_rows::Integer, n_columns::Integer, float_byte_size::Integer) = VSInput_Matrix(
E_VertexInputMatrixDimensions(n_rows),
E_VertexInputMatrixDimensions(n_columns),
E_VertexInputMatrixTypes(float_byte_size)
)
VSInput_Matrix(n_rows::Integer, n_columns::Integer, float_type::Type{<:AbstractFloat}) = VSInput_Matrix(
E_VertexInputMatrixDimensions(n_rows),
E_VertexInputMatrixDimensions(n_columns),
E_VertexInputMatrixTypes(sizeof(float_type))
)
export VSInput, VSInput_FVector | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 20171 | export Target, TargetUnsupportedException,
target_activate, target_configure_fragment_outputs, target_clear
#######################
# Creation Errors #
#######################
"
Thrown if the graphics driver doesn't support a particular combination of texture attachments.
This is the only Target-related error that can't be foreseen, so it's given special representation;
the others are thrown with `error()`.
"
struct TargetUnsupportedException <: Exception
color_formats::Vector{TexFormat}
depth_format::Optional{E_DepthStencilFormats}
end
Base.showerror(io::IO, e::TargetUnsupportedException) = print(io,
"Your graphics driver doesn't support this particular combination of attachment formats;",
" try simpler ones.\n\tThe color attachments: ", e.color_formats,
"\n\tThe depth attachment: ", (exists(e.depth_format) ? e.depth_format : "[none]")
)
#=
string("At least one of the attachments is a compressed-format texture,",
" which generally can't be rendered into.")
elseif e.reason == TargetErrors.layer_mixup
string("Some attachments are layered (i.e. full 3D textures or cubemaps),",
" and some aren't.")
elseif e.reason == TargetErrors.driver_unsupported
string("Your graphics driver doesn't support this particular combination",
" of texture formats; try simpler ones.")
elseif e.reason == TargetErrors.unknown
string("Some unknown error has occurred. You may get more info",
" by turning on BplusApp.GL asserts, and starting the Context in \"debug mode\".")
else
string("ERROR_UNHANDLED(", e.reason, ")")
end
=#
######################################
# Struct/constructors/destructor #
######################################
"""
A destination for rendering, as opposed to rendering into the screen itself.
Has a set of Textures attached to it, described as `TargetOutput` instances,
which receive the rendered output.
OpenGL calls these "framebuffers".
The full list of attached textures is fixed after creation,
but the specific subset used in rendering can be configured with `target_configure_fragment_outputs()`.
"""
mutable struct Target <: AbstractResource
handle::Ptr_Target
size::v2u
attachment_colors::Vector{TargetOutput}
attachment_depth_stencil::Union{Nothing, TargetOutput, TargetBuffer}
# Maps each fragment shader output to a color attachment.
# e.x. the value [2, nothing, 4] means that shader outputs 1 and 3
# go to attachments 2 and 4, while all other outputs get discarded.
color_render_slots::Vector{Optional{Int}}
gl_buf_color_render_slots::Vector{GLenum} # Buffer for the slots data that goes to OpenGL
# Textures which the Target will clean up automatically on close().
# Some Target constructors will automatically create textures for you, for convenience,
# and those get added to this set.
# Feel free to add/remove Textures as desired.
owned_textures::Set{Texture}
end
#=
For reference, here is the process for OpenGL framebuffers:
1. Create it
2. Attach textures/images to it, possibly layered,
with `glNamedFramebufferTexture[Layer]()`.
3. Set which subset of color attachments to use,
with `glNamedFramebufferDrawBuffers()`
4. Depth/stencil attachments are always used
5. Draw!
=#
"
Creates a target with no outputs,
which acts like it has the given size and number of layers.
"
Target(size::v2u, n_layers::Int = 1) = make_target(size, n_layers, TexOutput[ ], nothing, Texture[ ])
"
Creates a target with the given output size, format, and mip levels,
using a single 2D color Texture and a Texture *or* TargetBuffer for depth/stencil.
"
function Target(size::v2u, color::TexFormat, depth_stencil::E_DepthStencilFormats
;
ds_is_target_buffer::Bool = true,
n_tex_mips::Integer = 0,
ds_tex_sampling_mode::E_DepthStencilSources = DepthStencilSources.depth)
color = Texture(color, size, @optional(n_tex_mips > 0, n_mips=n_tex_mips))
depth = ds_is_target_buffer ?
TargetBuffer(size, depth_stencil) :
TargetOutput(tex = Texture(
depth_stencil, size,
@optional(is_depth_and_stencil(depth_stencil),
depth_stencil_sampling = ds_tex_sampling_mode),
@optional(n_tex_mips > 0,
n_mips = n_tex_mips)
))
return make_target(size, 1,
[ TargetOutput(tex=color) ],
depth,
[ color, @optional(!ds_is_target_buffer, depth.tex) ])
end
"
Creates a Target which uses already-existing texture[s].
The Target is *not* responsible for cleaning them up.
"
function Target(color::Union{TargetOutput, Vector{TargetOutput}}, depth::TargetOutput)
local min_color_size::v2u,
color_layer_count::Int,
color_array::Vector{TargetOutput}
if color isa TargetOutput
min_color_size = output_size(color)
color_layer_count = output_layer_count(color)
color_array = [ color ]
else
min_color_size = minimum(output_size, color,
init=v2u(Val(typemax(UInt32))))
color_layer_count = minimum(output_layer_count, color,
init=typemax(Int))
color_array = color
end
return make_target(
min(min_color_size, output_size(depth)),
min(color_layer_count, output_layer_count(depth)),
color_array, depth, Texture[ ]
)
end
"
Creates a depth-/stencil-only target, with no color attachments.
The target is *not* responsible for cleaning them up.
"
Target(depth::TargetOutput) = Target(Vector{TargetOutput}(), depth)
"
Creates a target with the given color output, and generates a corresponding depth/stencil buffer.
By default, the depth/stencil will be a TargetBuffer and not a Texture.
The Target is *not* responsible for cleaning up the color texture, only the new depth/stencil buffer.
"
function Target(color::TargetOutput, depth_stencil::E_DepthStencilFormats,
ds_is_target_buffer::Bool = true,
ds_tex_sampling_mode::E_DepthStencilSources = DepthStencilSources.depth)
size::v2u = output_size(color)
depth = ds_is_target_buffer ?
TargetBuffer(size, depth_stencil) :
TargetOutput(tex = Texture(
depth_stencil, size,
n_mips=color.tex.n_mips,
@optional(is_depth_and_stencil(depth_stencil),
depth_stencil_sampling = ds_tex_sampling_mode)
))
return make_target(size, 1, [ color ], depth,
Texture[ @optional(!ds_is_target_buffer, depth.tex) ])
end
function make_target( size::v2u, n_layers::Int,
colors::Vector{TargetOutput},
depth_stencil::Union{Nothing, TargetOutput, TargetBuffer},
textures_to_manage::Vector{Texture}
)::Target
@bp_check(all(size > 0), "Target's size can't be 0")
@bp_check(exists(get_context()), "Trying to create a Target outside a valid context")
# Check the depth attachment's format.
depth_format::Optional{TexFormat} = nothing
if depth_stencil isa TargetOutput
depth_format = depth_stencil.tex.format
elseif depth_stencil isa TargetBuffer
depth_format = depth_stencil.format
end
if exists(depth_format)
@bp_check(
is_depth_only(depth_format) || is_depth_and_stencil(depth_format),
"Depth/stencil attachment for a Target must be",
" a depth texture or depth-stencil hybrid texture, but it was ",
depth_format
)
end
# Create and configure the Framebuffer handle.
handle = Ptr_Target(get_from_ogl(gl_type(Ptr_Target), glCreateFramebuffers, 1))
if isempty(colors) && isnothing(depth_stencil)
glNamedFramebufferParameteri(handle, GL_FRAMEBUFFER_DEFAULT_WIDTH, (GLint)size.x)
glNamedFramebufferParameteri(handle, GL_FRAMEBUFFER_DEFAULT_HEIGHT, (GLint)size.y)
glNamedFramebufferParameteri(handle, GL_FRAMEBUFFER_DEFAULT_LAYERS, (GLint)n_layers)
end
# Attach the color textures.
for (i::Int, color::TargetOutput) in enumerate(colors)
@bp_check(is_color(color.tex.format),
"Color attachment for a Target must be a color format, not ", color.tex.format)
@bp_check(!(color.tex.format isa E_CompressedFormats),
"Color attachment can't be a compressed format: ", color.tex.format)
attach_output(handle, GLenum(GL_COLOR_ATTACHMENT0 + i-1), color)
end
# Attach the depth texture/buffer.
if exists(depth_format)
attachment::GLenum = if is_depth_only(depth_format)
GL_DEPTH_ATTACHMENT
elseif is_depth_and_stencil(depth_format)
GL_DEPTH_STENCIL_ATTACHMENT
else
error("Unhandled case: ", depth_format)
end
attach_output(handle, attachment, depth_stencil)
end
# Make sure all color attachments start out active.
attachments = collect(Optional{Int}, 1:length(colors))
attachments_buf = map(i -> GLenum(GL_COLOR_ATTACHMENT0 + i-1), attachments)
glNamedFramebufferDrawBuffers(handle, length(colors), Ref(attachments_buf, 1))
# Check the final state of the framebuffer object.
status::GLenum = glCheckNamedFramebufferStatus(handle, GL_DRAW_FRAMEBUFFER)
if status == GL_FRAMEBUFFER_COMPLETE
# Everything is good!
elseif status == GL_FRAMEBUFFER_UNSUPPORTED
throw(TargetUnsupportedException(map(c -> c.tex.format, colors),
depth_format))
elseif status == GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS
error("Some attachments are layered (i.e. full 3D textures or cubemaps),",
" and some aren't.")
else
error("Unknown framebuffer error: ", GLENUM(status))
end
# Assemble the final instance.
return Target(handle, size,
copy(colors), depth_stencil,
attachments,
attachments_buf,
Set(textures_to_manage))
end
function attach_output(handle::Ptr_Target, slot::GLenum, output::TargetOutput)
output_validate(output)
# There are two variants of the OpenGL function to attach a texture to a framebuffer.
# The only difference is that one of them has an extra argument at the end.
main_args = (handle, slot, get_ogl_handle(output.tex), output.mip_level - 1)
if output_is_layered(output) || !output_can_be_layered(output)
glNamedFramebufferTexture(main_args...)
else
glNamedFramebufferTextureLayer(main_args..., GLint(Int(output.layer) - 1))
end
end
function attach_output(handle::Ptr_Target, slot::GLenum, buffer::TargetBuffer)
glNamedFramebufferRenderbuffer(handle, slot, GL_RENDERBUFFER, get_ogl_handle(buffer))
end
function Base.close(target::Target)
# Clean up managed Textures.
for tex in target.owned_textures
close(tex)
end
empty!(target.owned_textures)
# Clean up the depth/stencil TargetBuffer.
if target.attachment_depth_stencil isa TargetBuffer
close(target.attachment_depth_stencil)
elseif target.attachment_depth_stencil isa TargetOutput
# Already cleared up from the previous 'owned_textures' loop.
elseif !isnothing(target.attachment_depth_stencil)
error("Unhandled case: ", typeof(target.attachment_depth_stencil))
end
setfield!(target, :attachment_depth_stencil, nothing)
# Finally, delete the framebuffer object itself.
glDeleteFramebuffers(1, Ref(target.handle))
setfield!(target, :handle, Ptr_Target())
end
#######################
# Pubic interface #
#######################
"
Sets a Target as the active one for rendering.
Pass `nothing` to render directly to the screen instead.
"
function target_activate(target::Optional{Target};
reset_viewport::Bool = true,
reset_scissor::Bool = true)
context = get_context()
@bp_gl_assert(exists(context), "Activating a Target (or the screen) outside of its context")
if exists(target)
glBindFramebuffer(GL_FRAMEBUFFER, get_ogl_handle(target))
reset_viewport && set_viewport(context, Box2Di(min=one(v2i), size=convert(v2i, target.size)))
reset_scissor && set_scissor(context, nothing)
else
glBindFramebuffer(GL_FRAMEBUFFER, Ptr_Target())
reset_viewport && set_viewport(context, Box2Di(min=one(v2i), size=get_window_size(context)))
reset_scissor && set_scissor(context, nothing)
end
end
"
Selects a subset of a Target's color attachments to use for rendering, by their (1-based) index.
For example, passing `[5, nothing, 1]` means that
the fragment shader's first output goes to color attachment 5,
the third output goes to color attachment 1,
and all other outputs (i.e. 2 and 4+) are safely discarded.
"
function target_configure_fragment_outputs(target::Target, slots::AbstractVector{<:Optional{Integer}})
is_valid_slot(i) = isnothing(i) ||
((i > 0) && (i <= length(target.attachment_colors)))
@bp_check(all(is_valid_slot, slots),
"One or more color output slots reference a nonexistent attachment!",
" This Target only has ", length(target.attachment_colors), ".",
" Slots: ", slots)
# Update the internal list.
empty!(target.color_render_slots)
append!(target.color_render_slots, slots)
# Tell OpenGL about the new list.
empty!(target.gl_buf_color_attachments)
append!(target.gl_buf_color_render_slots, Iterators.map(slots) do slot
if isnothing(slot)
GL_NONE
else
GLenum(GL_COLOR_ATTACHMENT0 + slot - 1)
end
end)
glNamedFramebufferDrawBuffers(get_ogl_handle(target),
length(target.gl_buf_color_attachments),
Ref(target.gl_buf_color_attachments, 1))
end
"
Clears a Target's color attachment.
If the color texture is `uint`, then you must clear to a `vRGBAu`.
If the color texture is `int`, then you must clear to a `vRGBAi`.
Otherwise, the color texture is `float` or `normalized_[u]int`, and you must clear to a `vRGBAf`.
The index is *not* the color attachment itself but the render slot,
a.k.a. the fragment shader output.
For example, if you previously called `target_configure_fragment_outputs(t, [ 3, nothing, 1])`,
and you want to clear color attachment 1, pass the index `3`.
"
function target_clear(target::Target,
color::vRGBA{<:Union{Float32, Int32, UInt32}},
slot_index::Integer = 1)
@bp_check(slot_index <= length(target.color_render_slots),
"The Target only has ", length(target.color_render_slots),
" active render slots, but you're trying to clear #", slot_index)
@bp_check(exists(target.color_render_slots[slot_index]),
"The Target currently has nothing bound to render slot ", slot_index, ",",
" but you're trying to clear that slot")
# Get the correct OpenGL function to call.
# Also double-check that the texture format closely matches the clear data,
# as OpenGL requires.
local gl_func::Function
format::TexFormat = target.attachment_colors[slot_index].tex.format
@bp_gl_assert(is_color(format), "Color attachment isn't a color format??? ", format)
if color isa vRGBAf
@bp_gl_assert(!is_integer(format),
"Color attachment is an integer format (", format, "),",
" you can't clear it with float data")
gl_func = glClearNamedFramebufferfv
else
@bp_gl_assert(is_integer(format),
"Color attachment isn't an integer format (", format, "),",
" you can't clear it with integer data")
if color isa vRGBAi
@bp_gl_assert(is_signed(format),
"Color attachment is an unsigned format (", format, "),",
" you can't clear it with signed data")
gl_func = glClearNamedFramebufferiv
elseif color isa vRGBAu
@bp_gl_assert(!is_signed(format),
"Color attachment is a signed format (", format, "),",
" you can't clear it with unsigned data")
gl_func = glClearNamedFramebufferuiv
else
error("Unhandled case: ", color)
end
end
gl_func(get_ogl_handle(target), GL_COLOR, slot_index - 1, Ref(color))
end
"
Clears a Target's depth attachment.
Note that this is *legal* on a hybrid depth-stencil buffer; the stencil values will be left alone.
The clear value will be casted to `Float32` and clamped to 0-1.
Be sure that depth writes are turned on in the Context!
Otherwise this would become a no-op, and an error may be thrown.
"
function target_clear(target::Target, depth::AbstractFloat)
@bp_gl_assert(get_context().state.depth_write,
"Can't clear a Target's depth-buffer while depth writes are off")
glClearNamedFramebufferfv(get_ogl_handle(target), GL_DEPTH, 0, Ref(@f32 depth))
end
"
Clears a Target's stencil attachment.
Note that this is *legal* on a hybrid depth-stencil buffer; the depth values will be left alone.
The clear value will be casted to `UInt8`.
Watch your Context's stencil write mask carefully!
If some bits are disabled from writing, then this clear operation wouldn't affect those bits.
By default, there is a debug check to prevent the stencil write mask from surprising you.
If the masking behavior is desired, you can disable the check by passing `false`.
"
function target_clear(target::Target, stencil::Unsigned,
prevent_partial_clears::Bool = true)
if prevent_partial_clears
@bp_check(get_context().state.stencil_write_mask == typemax(GLuint),
"The Context has had its `stencil_write_mask` set,",
" which can screw up the clearing of stencil buffers!",
" To disable this check, pass `false` to this `target_clear()` call.")
end
@bp_check(stencil <= typemax(UInt8),
"Stencil buffer is assumed to have 8 bits, but your clear value (",
stencil, ") is larger than the max 8-bit value ", typemax(UInt8))
stencil_ref = Ref(reinterpret(GLint, UInt32(stencil)))
glClearNamedFramebufferiv(get_ogl_handle(target), GL_STENCIL, 0, stencil_ref)
end
"
Clears a Target's hybrid depth/stencil attachment.
This is more efficient than clearing depth and stencil separately.
See above for important details about clearing depth and clearing stencil.
"
function target_clear(target::Target, depth_stencil::Depth32fStencil8u,
prevent_partial_clears::Bool = true)
@bp_gl_assert(get_context().state.depth_write,
"Can't clear a Target's depth/stencli buffer while depth writes are off")
if prevent_partial_clears
@bp_gl_assert(get_context().state.stencil_write_mask == typemax(GLuint),
"The Context has had its `stencil_write_mask` set,",
" which can screw up the clearing of stencil buffers!",
" To disable this check, pass `false` to this `target_clear()` call.")
end
(depth::Float32, raw_stencil::UInt8) = split(depth_stencil)
stencil = reinterpret(GLint, UInt32(raw_stencil))
glClearNamedFramebufferfi(get_ogl_handle(target), GL_DEPTH_STENCIL, 0, depth, stencil)
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1446 | """
Something like a texture, but highly optimized for rendering into it and not much else --
you cannot easily manipulate or sample its data.
The OpenGL term for this is "renderbuffer".
The main use for this is as a depth or stencil buffer,
any time you don't care about sampling depth/stencil data
(it can still be used for depth/stencil tests, just not sampled in shaders).
This is an AbstractResource, but it's managed internally by Target instances.
You probably won't interact with it much yourself.
"""
mutable struct TargetBuffer <: AbstractResource
handle::Ptr_TargetBuffer
size::v2i
format::TexFormat
end
function TargetBuffer(size::Vec2{<:Integer}, format::TexFormat)
@bp_check(exists(get_context()), "Can't create a TargetBuffer without a Context")
gl_format::Optional{GLenum} = get_ogl_enum(format)
@bp_check(exists(gl_format),
"Invalid format given to a TargetBuffer: ", format)
@bp_check(!(format isa E_CompressedFormats),
"Can't use a compressed format (", format, ") for a TargetBuffer")
handle = Ptr_TargetBuffer(get_from_ogl(gl_type(Ptr_TargetBuffer), glCreateRenderbuffers, 1))
glNamedRenderbufferStorage(handle, gl_format, size...)
return TargetBuffer(handle, size, format)
end
function Base.close(b::TargetBuffer)
glDeleteRenderbuffers(1, Ref(gl_type(b.handle)))
setfield!(b, :handle, Ptr_TargetBuffer())
end
export TargetBuffer | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 3107 | """
A reference to part or all of a texture, to be attached to a Target and rendered into.
You can attach any texture at any mip level.
In the case of 3D and cubemap textures,
you can optionally attach a specific "layer" of that texture.
The layers of a cubemap texture are its faces, ordered in the usual way.
The layers of a 3D texture are its Z-slices.
Note that mip levels and layers are counted starting at 1,
to be consistent with Julia's 1-based convention.
"""
Base.@kwdef struct TargetOutput
tex::Texture
mip_level::Int = 1
layer::Union{Nothing, E_CubeFaces, Int} = nothing
end
function Base.show(io::IO, o::TargetOutput)
if o.mip_level != 1
print(io, "Mip #", o.mip_level, " of a ")
else
print(io, "A ")
end
print(io, tex.type, " texture")
if o.layer isa Nothing
# Print nothing in this case.
elseif o.layer isa E_CubeFaces
print(io, "; face ", o.layer)
elseif o.layer isa Int
print(io, "; Z-slice #", o.layer)
else
print(io, "ERROR_CASE(", typeof(o.layer), ")")
end
end
"Gets this output's render size."
output_size(t::TargetOutput)::v2u = t.tex.size.xy
"Validates this output's combination of texture type and chosen layer."
function output_validate(t::TargetOutput)
if t.tex.type == TexTypes.threeD
@bp_check(t.layer isa Union{Nothing, Int},
"ThreeD texture has a TargetOutput layer of type ", typeof(t.layer),
", it should be `Int` (or `nothing`)")
elseif t.tex.type == TexTypes.cube_map
@bp_check(t.layer isa Union{Nothing, E_CubeFaces},
"Cubemap texture has a TargetOutput layer of type ", typeof(t.layer),
", it should be `E_CubeFaces` (or `nothing`)")
elseif t.tex.type in (TexTypes.oneD, TexTypes.twoD)
@bp_check(isnothing(t.layer),
"Trying to set the layer ", typeof(t.layer), "(", t.layer, ")",
" for a ", t.tex.type, " texture, which is a 1-layered texture")
else
error("Unhandled case: ", t.tex.type)
end
end
"Gets whether this output's texture could support multiple render layers."
output_can_be_layered(t::TargetOutput) = (t.tex.type in (TexTypes.threeD, TexTypes.cube_map))
"Gets whether this output has multiple render layers."
output_is_layered(t::TargetOutput) = isnothing(t.layer) && (t.tex.type in (TexTypes.threeD, TexTypes.cube_map))
"Gets this output's single render layer."
output_layer(t::TargetOutput) = output_layer(t.layer)
output_layer(::Nothing) = 1
output_layer(face::E_CubeFaces) = enum_to_index(face)
output_layer(z_slice::Int) = z_slice
"Gets the number of layers in this output."
output_layer_count(t::TargetOutput)::Int = output_layer_count(t.tex.type, t.layer)
output_layer_count(tex_type::E_TexTypes, ::Nothing) =
if tex_type in (TexTypes.oneD, TexTypes.twoD)
1
elseif tex_type == TexTypes.threeD
Int(tex_type.size.z)
elseif tex_type == TexTypes.cube_map
6
end
output_layer_count(E_TexTypes, ::Union{Int, E_CubeFaces}) = 1
export TargetOutput | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 2457 | # The six faces of a cube, defined to match the OpenGL cubemap texture faces.
# They are ordered in the same way that OpenGL orders them in memory.
@bp_gl_enum(CubeFaces::GLenum,
pos_x = GL_TEXTURE_CUBE_MAP_POSITIVE_X,
neg_x = GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
pos_y = GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
neg_y = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
pos_z = GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
neg_z = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
)
export CubeFaces, E_CubeFaces
"Defines, for a specific face of a cube-map texture, how it is oriented in 3D space."
struct CubeFaceOrientation
face::E_CubeFaces
# The 'min' corner maps the first pixel of the 2D texture face
# to its 3D corner in the cube-map (from -1 to +1).
# The 'max' corner does the same for the last pixel.
min_corner::Vec{3, Int8}
max_corner::Vec{3, Int8}
# The 3D axis for each axis of the texture face.
# 1=X, 2=Y, 3=Z.
horz_axis::UInt8
vert_axis::UInt8
end
export CubeFaceOrientation
"
Converts a UV coordinate on a cubemap face to a 3D cubemap vector.
NOTE: be careful with your UV computation!
If your cubemap faces are 512x512 pixels, then the first pixel should have UV `0.5/512`,
and the last pixel should have UV `511.5/512`.
"
function get_cube_dir(face::CubeFaceOrientation, uv::v2f)::v3f
dir3D = convert(v3f, face.min_corner)
@set! dir3D[face.horz_axis] = lerp(face.min_corner[face.horz_axis],
face.max_corner[face.horz_axis],
uv.x)
@set! dir3D[face.vert_axis] = lerp(face.min_corner[face.vert_axis],
face.max_corner[face.vert_axis],
uv.y)
return dir3D
end
export get_cube_dir
"The memory layout for each cubemap face, in order on the GPU"
const CUBEMAP_MEMORY_LAYOUT = let v3i8 = Vec{3, Int8}
(
CubeFaceOrientation(CubeFaces.pos_x, v3i8(1, 1, 1), v3i8(1, -1, -1), 3, 2),
CubeFaceOrientation(CubeFaces.neg_x, v3i8(-1, 1, -1), v3i8(-1, -1, 1), 3, 2),
CubeFaceOrientation(CubeFaces.pos_y, v3i8(-1, 1, -1), v3i8(1, 1, 1), 1, 3),
CubeFaceOrientation(CubeFaces.neg_y, v3i8(-1, -1, 1), v3i8(1, -1, -1), 1, 3),
CubeFaceOrientation(CubeFaces.pos_z, v3i8(-1, 1, 1), v3i8(1, -1, 1), 1, 2),
CubeFaceOrientation(CubeFaces.neg_z, v3i8(1, 1, -1), v3i8(-1, -1, -1), 1, 2),
)
end
export CUBEMAP_MEMORY_LAYOUT | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 10063 | # Defines other aspects of texture interaction that aren't "sampling" or "format".
#######################################
# Upload/download channels #
#######################################
# Subsets of color channels that can be uploaded to a texture.
@bp_gl_enum(PixelIOChannels::GLenum,
red = GL_RED,
green = GL_GREEN,
blue = GL_BLUE,
RG = GL_RG,
RGB = GL_RGB,
RGBA = GL_RGBA,
BGR = GL_BGR,
BGRA = GL_BGRA
)
"Gets the number of channels that will get uploaded with the given upload format"
get_n_channels(c::E_PixelIOChannels) =
if (c == PixelIOChannels.red) ||
(c == PixelIOChannels.green) ||
(c == PixelIOChannels.blue)
1
elseif (c == PixelIOChannels.RG)
2
elseif (c == PixelIOChannels.RGB) ||
(c == PixelIOChannels.BGR)
3
elseif (c == PixelIOChannels.RGBA) ||
(c == PixelIOChannels.BGRA)
4
else
error("Unhandled case: ", c)
end
# get_n_channels() is already defined an exported by another GL function
"Gets the OpenGL enum to use when uploading an integer version of the given components"
get_int_ogl_enum(c::E_PixelIOChannels) =
if c == PixelIOChannels.red
GL_RED_INTEGER
elseif c == PixelIOChannels.green
GL_GREEN_INTEGER
elseif c == PixelIOChannels.blue
GL_BLUE_INTEGER
elseif c == PixelIOChannels.RG
GL_RG_INTEGER
elseif c == PixelIOChannels.RGB
GL_RGB_INTEGER
elseif c == PixelIOChannels.RGBA
GL_RGBA_INTEGER
elseif c == PixelIOChannels.BGR
GL_BGR_INTEGER
elseif c == PixelIOChannels.BGRA
GL_BGRA_INTEGER
else
error("Unhandled case: ", c)
end
"Gets the set of channels needed to handle data with the given number of components"
function get_pixel_io_channels( ::Val{N},
use_bgr_ordering::Bool,
color_for_1D::E_PixelIOChannels = PixelIOChannels.red
)::E_PixelIOChannels where {N}
@bp_check(color_for_1D in (PixelIOChannels.red, PixelIOChannels.green, PixelIOChannels.blue),
"Single-channel color enum isn't actually single-channel: ", color_for_1D)
if N == 1
return color_for_1D
elseif N == 2
return PixelIOChannels.RG
elseif N == 3
return use_bgr_ordering ? PixelIOChannels.BGR : PixelIOChannels.RGB
elseif N == 4
return use_bgr_ordering ? PixelIOChannels.BGRA : PixelIOChannels.RGBA
else
error("Unhandled case: ", N)
end
end
"
Gets the OpenGL enum for a set of channels being uploaded to a texture.
Needs to know whether the texture has an int/uint format.
"
function get_ogl_enum(channels::E_PixelIOChannels, is_integer_format::Bool)
if is_integer_format
if channels == PixelIOChannels.red
return GL_RED_INTEGER
elseif channels == PixelIOChannels.green
return GL_GREEN_INTEGER
elseif channels == PixelIOChannels.blue
return GL_BLUE_INTEGER
elseif channels == PixelIOChannels.RG
return GL_RG_INTEGER
elseif channels == PixelIOChannels.RGB
return GL_RGB_INTEGER
elseif channels == PixelIOChannels.BGR
return GL_BGR_INTEGER
elseif channels == PixelIOChannels.RGBA
return GL_RGBA_INTEGER
elseif channels == PixelIOChannels.BGRA
return GL_BGRA_INTEGER
else
error("Unhandled case: ", channels)
end
else
return GLenum(channels)
end
end
export PixelIOChannels, E_PixelIOChannels
#########################################
# Upload/download data types #
#########################################
# Data types that pixel data can be uploaded/downloaded as.
# This does not always have to match the texture's format or sampler.
@bp_gl_enum(PixelIOTypes::GLenum,
uint8 = GL_UNSIGNED_BYTE,
uint16 = GL_UNSIGNED_SHORT,
uint32 = GL_UNSIGNED_INT,
int8 = GL_BYTE,
int16 = GL_SHORT,
int32 = GL_INT,
float32 = GL_FLOAT
)
"Gets the byte-size of the given pixel component type"
get_byte_size(t::E_PixelIOTypes) =
if (t == PixelIOTypes.uint8) || (t == PixelIOTypes.int8)
1
elseif (t == PixelIOTypes.uint16) || (t == PixelIOTypes.int16)
2
elseif (t == PixelIOTypes.uint32) || (t == PixelIOTypes.int32) || (t == PixelIOTypes.float32)
4
else
error("Unhandled case: ", t)
end
"Converts from a type to the corresponding PixelIOTypes"
get_pixel_io_type(::Type{UInt8}) = PixelIOTypes.uint8
get_pixel_io_type(::Type{UInt16}) = PixelIOTypes.uint16
get_pixel_io_type(::Type{UInt32}) = PixelIOTypes.uint32
get_pixel_io_type(::Type{Int8}) = PixelIOTypes.int8
get_pixel_io_type(::Type{Int16}) = PixelIOTypes.int16
get_pixel_io_type(::Type{Int32}) = PixelIOTypes.int32
get_pixel_io_type(::Type{Float32}) = PixelIOTypes.float32
"
The set of all number types which can be used for pixel upload/download.
Does not include special packed types like Depth24uStencil8.
"
@inline supported_pixel_io_types() = (
UInt8, UInt16, UInt32,
Int8, Int16, Int32,
Float32
)
"Types which can be used as pixel components for texture upload/download"
const PixelIOComponent = Union{supported_pixel_io_types()..., Depth24uStencil8u, Depth32fStencil8u}
"
Types which can be uploaded to/downloaded from a texture.
One-component texture data can be a number or a Vec1;
higher-component data must be a Vec.
"
const PixelIOValue = Union{PixelIOComponent,
Vec{1, <:PixelIOComponent},
Vec{2, <:PixelIOComponent},
Vec{3, <:PixelIOComponent},
Vec{4, <:PixelIOComponent}}
"An array of pixels for texture upload/download"
const PixelBufferD{N, T<:PixelIOValue} = Array{T, N}
"The total set of valid pixel arrays for texture upload/download"
const PixelBuffer{T} = Union{PixelBufferD{1, T}, PixelBufferD{2, T}, PixelBufferD{3, T}}
"Gets the type of pixel data in the given buffer"
get_pixel_type(::PixelBufferD{N, T}) where {N, T} = T
"Gets the type of the individual components in some pixel buffer data"
get_component_type(T::Type{<:Number}) = T
get_component_type(V::Type{<:Vec}) = V.parameters[2]
get_component_type(::Type{PixelBufferD{N, T}}) where {N, T} = get_component_type(T)
"Gets the number of components in some pixel buffer data"
get_component_count(T::Type{<:Number}) = 1
get_component_count(V::Type{<:Vec}) = V.parameters[1]
get_component_count(::Type{PixelBufferD{N, T}}) where {N, T} = get_component_count(T)
export PixelIOTypes, E_PixelIOTypes,
get_pixel_io_type, supported_pixel_io_types, get_component_type, get_component_count,
PixelIOComponent, PixelIOValue, PixelBufferD, PixelBuffer
#########################################
# Upload/download data types #
#########################################
"
Parameters for specifying a subset of data in an N-dimensional texture.
Note that mips and pixel ranges follow the 1-based Julia convention,
not the 0-based convention of OpenGL.
"
struct TexSubset{N}
# Rectangular subset of the texture, or `nothing` for all pixels.
area::Optional{BoxU{N}}
# 1 means the original (full-size) texture.
# Higher values are smaller mips.
mip::UInt
TexSubset{N}(area = nothing, mip = 1) where {N} = new{N}(area, mip)
TexSubset(area::Box{N}, mip = 1) where {N} = new{N}(convert(BoxU{N}, area), mip)
end
get_subset_dims(::TexSubset{N}) where {N} = N
get_subset_dims(::Type{TexSubset{N}}) where {N} = N
"
Calculates the subset of a texture to use.
The `full_size` parameter should have the same dimensionality as the subset;
for convenience it can have more and those extra dimensions will be ignored.
"
get_subset_range(subset::TexSubset{N}, full_size::VecT{I}) where {N, I<:Integer} =
if isnothing(subset.area)
Box(
min=one(Vec{N, I}),
size=Vec{N, eltype(full_size)}(i -> full_size[i])
)
else
subset.area
end
@inline get_subset_range(subset::TexSubset{1}, full_size::Integer) =
get_subset_range(subset, Vec(full_size))
"
Converts a subset to a lower- or higher-dimensional one.
"
change_dimensions(subset::TexSubset{N}, N2::Int) where {N} = TexSubset{N2}(
isnothing(subset.area) ?
nothing :
reshape(subset.area, N2;
new_dims_min=1),
subset.mip
)
export TexSubset
########################
# Swizzling #
########################
# Various sources a color texture can pull from during sampling.
# Note that swizzling is set per-texture, not per-sampler.
@bp_gl_enum(SwizzleSources::GLenum,
red = GL_RED,
green = GL_GREEN,
blue = GL_BLUE,
alpha = GL_ALPHA,
# The below sources output a constant value instead of reading from the texture.
zero = GL_ZERO,
one = GL_ONE
)
const SwizzleRGBA = Vec4{E_SwizzleSources}
SwizzleRGBA() = Vec(SwizzleSources.red, SwizzleSources.green, SwizzleSources.blue, SwizzleSources.alpha)
export SwizzleSources, E_SwizzleSources
######################
# General #
######################
"Gets the number of mips needed for a texture of the given size"
@inline function get_n_mips(tex_size::Union{Integer, VecT{<:Integer}})
largest_axis = max(tex_size)
return 1 + Int(floor(log2(largest_axis)))
end
get_n_mips(length::Integer) = get_n_mips(Vec(length))
"Gets the size of a mip level, given the original size of the texture"
@inline function get_mip_size(original_size::Union{Integer, VecT{<:Integer}}, mip_level::Integer)
size = original_size
for _ in 2:mip_level
size = max(size ÷ 2, 1)
end
return size
end
# When using this texture through a Simple View, these are the modes it is available in.
@bp_gl_enum(ImageAccessModes::GLenum,
read = GL_READ_ONLY,
write = GL_WRITE_ONLY,
read_write = GL_READ_WRITE
)
export get_n_mips, get_mip_size,
ImageAccessModes, E_ImageAccessModes | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 27834 | ####################
# Enums #
####################
# The types of textures that can be created.
@bp_gl_enum(TexTypes::GLenum,
oneD = GL_TEXTURE_1D,
twoD = GL_TEXTURE_2D,
threeD = GL_TEXTURE_3D,
cube_map = GL_TEXTURE_CUBE_MAP
# Array textures are not supported, because they aren't necessary
# now that we have bindless textures.
)
@bp_gl_enum(ColorChannels::UInt8,
red = 1,
green = 2,
blue = 3,
alpha = 4
)
@bp_gl_enum(OtherChannels::UInt8,
depth = 5,
stencil = 6
)
const AllChannels = Union{E_ColorChannels, E_OtherChannels}
# The type of data representing each channel of a texture's pixels.
@bp_gl_enum(FormatTypes::UInt8,
# A floating-point number (allowing "HDR" values outside the traditional 0-1 range)
float,
# A value between 0 - 1, stored as an unsigned integer between 0 and its maximum value.
normalized_uint,
# A value between -1 and +1, stored as a signed integer between its minimum and maximum value.
normalized_int,
# An unsigned integer. Sampling from this texture yields integers, not floats.
uint,
# A signed integer. Sampling from this texture yields integers, not floats.
int
)
export TexTypes, E_TexTypes,
ColorChannels, E_ColorChannels,
OtherChannels, E_OtherChannels,
AllChannels,
FormatTypes, E_FormatTypes
#
###########################
# TexFormat interface #
###########################
# The format types are split into different "archetypes",
# each of which implement the following queries:
"Is the given format supported for the given TexType?"
function is_supported end
"Is the given format a color type (as opposed to depth and/or stencil)?"
function is_color end
"Is the given format a depth type (no color/stencil)?"
function is_depth_only end
"Is the given format a stencil type (no color/depth)?"
function is_stencil_only end
"Is the given format a hybrid depth/stencil type?"
function is_depth_and_stencil end
"Does the given format use FormatTypes.int or FormatTypes.uint?"
function is_integer end
"
Does the given format have signed components, or unsigned components?
NOTE that for color formats, this is primarily about the RGB components;
the Alpha may sometimes be in a different format.
"
function is_signed end
"Does the given format store the given channel?"
function stores_channel end
"Gets the number of channels offered by the given format."
function get_n_channels end
"
Gets the size (in bits) of each pixel for the given texture format.
If the format is block-compressed, this will provide an accurate answer
by dividing the block's bit-size by the number of pixels in that block.
"
function get_pixel_bit_size end
"Gets the total size (in bytes) of a texture of the given format and size"
function get_byte_size end
"
Gets the OpenGL enum value representing this format,
or 'nothing' if the format isn't valid.
"
function get_ogl_enum end
export get_ogl_enum
#
"
Gets the OpenGL enum value for the actual format that this machine's GPU will use
to represent the given format, on the given type of texture.
Often-times, the graphics driver will pick a more robust format
(e.x. r3_g3_b2 is almost always upgraded to r5_g6_b5).
If no texture type is given, then the format will be used in a TargetBuffer.
Returns 'nothing' if the format is invalid for the given texture type.
"
function get_native_ogl_enum(format, tex_type::Optional{E_TexTypes})::GLenum
gl_tex_type::GLenum = exists(tex_type) ? GLenum(tex_type) : GL_RENDERBUFFER
gl_format::GLenum = get_ogl_enum(format)
actual_format::GLint = get_from_ogl(GLint, glGetInternalformativ,
gl_tex_type, gl_format, GL_INTERNALFORMAT_PREFERRED, 1)
return actual_format
end
export get_native_ogl_enum
# Default behavior for texture byte size: pixel bit size * number of pixels * 8.
get_byte_size(format, size::VecI) = get_pixel_bit_size(format) * 8 * reduce(*, map(Int64, size))
###########################
# SimpleFormat #
###########################
# The sets of components that can be used in "simple" texture formats.
@bp_gl_enum(SimpleFormatComponents::UInt8,
R = 1,
RG = 2,
RGB = 3,
RGBA = 4
)
# The bit-depths that components can have in "simple" texture formats.
# Note that not all combinations of bit depth and components are legal
# (for example, 2-bit components are only allowed if you use all four channels, RGBA).
@bp_gl_enum(SimpleFormatBitDepths::UInt8,
B2 = 2,
B4 = 4,
B5 = 5,
B8 = 8,
B10 = 10,
B12 = 12,
B16 = 16,
B32 = 32
)
"A straight-forward texture format, with each component having the same bit-depth"
struct SimpleFormat
type::E_FormatTypes
components::E_SimpleFormatComponents
bit_size::E_SimpleFormatBitDepths
end
Base.show(io::IO, f::SimpleFormat) = print(io,
f.components, Int(f.bit_size), "<", f.type, ">"
)
export SimpleFormatComponents, E_SimpleFormatComponents,
SimpleFormatBitDepths, E_SimpleFormatBitDepths,
SimpleFormat
#
is_supported(::SimpleFormat, ::E_TexTypes) = true
is_color(f::SimpleFormat) = true
is_depth_only(f::SimpleFormat) = false
is_stencil_only(f::SimpleFormat) = false
is_depth_and_stencil(f::SimpleFormat) = false
is_integer(f::SimpleFormat) = (f.type == FormatTypes.uint) || (f.type == FormatTypes.int)
is_signed(f::SimpleFormat) = (f.type == FormatTypes.int) || (f.type == FormatTypes.float) || (f.type == FormatTypes.normalized_int)
stores_channel(f::SimpleFormat, c::E_ColorChannels) =
if f.components == SimpleFormatComponents.R
return c == ColorChannels.red
elseif f.components == SimpleFormatComponents.RG
return c <= ColorChannels.green
elseif f.components == SimpleFormatComponents.RGB
return c <= ColorChannels.blue
elseif f.components == SimpleFormatComponents.RGBA
return true
else
error("Unhandled case: ", f.components)
end
stores_channel(f::SimpleFormat, c::E_OtherChannels) = false
get_n_channels(f::SimpleFormat) = Int(f.components)
get_pixel_bit_size(f::SimpleFormat) = Int(f.bit_size) * Int(f.components)
function get_ogl_enum(f::SimpleFormat)::Optional{GLenum}
@inline check_components(if_r, if_rg, if_rgb, if_rgba) =
if (f.components == SimpleFormatComponents.R)
if_r
elseif (f.components == SimpleFormatComponents.RG)
if_rg
elseif (f.components == SimpleFormatComponents.RGB)
if_rgb
elseif (f.components == SimpleFormatComponents.RGBA)
if_rgba
else
error("Unhandled case: ", f.components)
end
@inline check_types(if_float, if_unorm, if_inorm, if_uint, if_int) =
if (f.type == FormatTypes.float)
if_float()
elseif (f.type == FormatTypes.normalized_uint)
if_unorm()
elseif (f.type == FormatTypes.normalized_int)
if_inorm()
elseif (f.type == FormatTypes.uint)
if_uint()
elseif (f.type == FormatTypes.int)
if_int()
else
error("Unhandled case: ", f.type)
end
if (f.bit_size == SimpleFormatBitDepths.B2)
return ((f.type == FormatTypes.normalized_uint) && (f.components == SimpleFormatComponents.RGBA)) ?
GL_RGBA2 :
nothing
elseif (f.bit_size == SimpleFormatBitDepths.B4)
return (f.type == FormatTypes.normalized_uint) ?
check_components(nothing, nothing, GL_RGB4, GL_RGBA4) :
nothing
elseif (f.bit_size == SimpleFormatBitDepths.B5)
return ((f.type == FormatTypes.normalized_uint) && (f.components == SimpleFormatComponents.RGB)) ?
GL_RGB5 :
nothing
elseif (f.bit_size == SimpleFormatBitDepths.B8)
return check_types(() -> nothing,
() -> check_components(GL_R8, GL_RG8, GL_RGB8, GL_RGBA8),
() -> check_components(GL_R8_SNORM, GL_RG8_SNORM, GL_RGB8_SNORM, GL_RGBA8_SNORM),
() -> check_components(GL_R8UI, GL_RG8UI, GL_RGB8UI, GL_RGBA8UI),
() -> check_components(GL_R8I, GL_RG8I, GL_RGB8I, GL_RGBA8I))
elseif (f.bit_size == SimpleFormatBitDepths.B10)
return ((f.type == FormatTypes.normalized_uint) && (f.components == SimpleFormatComponents.RGB)) ?
GL_RGB10 :
nothing
elseif (f.bit_size == SimpleFormatBitDepths.B12)
return (f.type == FormatTypes.normalized_uint) ?
check_components(nothing, nothing, GL_RGB12, GL_RGBA12) :
nothing
elseif (f.bit_size == SimpleFormatBitDepths.B16)
return check_types(() -> check_components(GL_R16F, GL_RG16F, GL_RGB16F, GL_RGBA16F),
() -> check_components(GL_R16, GL_RG16, GL_RGB16, GL_RGBA16),
() -> check_components(GL_R16_SNORM, GL_RG16_SNORM, GL_RGB16_SNORM, GL_RGBA16_SNORM),
() -> check_components(GL_R16UI, GL_RG16UI, GL_RGB16UI, GL_RGBA16UI),
() -> check_components(GL_R16I, GL_RG16I, GL_RGB16I, GL_RGBA16I))
elseif (f.bit_size == SimpleFormatBitDepths.B32)
return check_types(() -> check_components(GL_R32F, GL_RG32F, GL_RGB32F, GL_RGBA32F),
() -> nothing, () -> nothing,
() -> check_components(GL_R32UI, GL_RG32UI, GL_RGB32UI, GL_RGBA32UI),
() -> check_components(GL_R32I, GL_RG32I, GL_RGB32I, GL_RGBA32I))
else
error("Unhandled case: ", f.bit_size)
end
end
###########################
# SpecialFormat #
###########################
# Special one-off texture formats.
@bp_gl_enum(SpecialFormats::GLenum,
# normalized_uint texture packing each pixel into 2 bytes:
# 5 bits for Red, 6 for Green, and 5 for Blue (no alpha).
r5_g6_b5 = GL_RGB565,
# normalized_uint texture packing each pixel into 4 bytes:
# 10 bits each for Red, Green, and Blue, and 2 bits for Alpha.
rgb10_a2 = GL_RGB10_A2,
# UInt texture (meaning it outputs integer values, not floats!)
# that packs each pixel into 4 bytes:
# 10 bits each for Red, Green, and Blue, and 2 bits for Alpha.
rgb10_a2_uint = GL_RGB10_A2UI,
# Floating-point texture using special unsigned 11-bit floats for Red and Green,
# and unsigned 10-bit float for Blue. No Alpha.
# Floats of this size can represent values from .0000610 to 65500,
# with ~2 digits of precision.
rgb_tiny_ufloats = GL_R11F_G11F_B10F,
# Floating-point texture using unsigned 14-bit floats for RGB (no alpha), with a catch:
# They share the same 5-bit exponent, to fit into 32 bits per pixel.
rgb_shared_exp_ufloats = GL_RGB9_E5,
# Each pixel is a 24-bit sRGB colorspace image (no alpha).
# Each channel is 8 bits, and the texture data is treated as non-linear,
# which means it's converted into linear values on the fly when sampled.
sRGB = GL_SRGB8,
# Same as sRGB, but with the addition of a linear (meaning non-sRGB) 8-bit Alpha value.
sRGB_linear_alpha = GL_SRGB8_ALPHA8,
# normalized_uint texture packing each pixel into a single byte:
# 3 bits for Red, 3 for Green, and 2 for Blue (no alpha).
# Note that, from reading on the Internet,
# it seems most hardware just converts to r5_g6_b5 under the hood.
r3_g3_b2 = GL_R3_G3_B2,
# normalized_uint texture packing each pixel into 2 bytes:
# 5 bits each for Red, Green, and Blue, and 1 bit for Alpha.
# It is highly recommended to use a compressed format instead of this one.
rgb5_a1 = GL_RGB5_A1
)
export SpecialFormats, E_SpecialFormats
is_supported(::E_SpecialFormats, ::E_TexTypes) = true
is_color(f::E_SpecialFormats) = true
is_depth_only(f::E_SpecialFormats) = false
is_stencil_only(f::E_SpecialFormats) = false
is_depth_and_stencil(f::E_SpecialFormats) = false
function is_integer(f::E_SpecialFormats)
if (f == SpecialFormats.r3_g3_b2) ||
(f == SpecialFormats.r5_g6_b5) ||
(f == SpecialFormats.rgb10_a2) ||
(f == SpecialFormats.rgb5_a1) ||
(f == SpecialFormats.rgb_shared_exp_ufloats) ||
(f == SpecialFormats.rgb_tiny_ufloats) ||
(f == SpecialFormats.sRGB) ||
(f == SpecialFormats.sRGB_linear_alpha)
#begin
return false
elseif (f == SpecialFormats.rgb10_a2_uint)
return true
else
error("Unhandled case: ", f)
end
end
function is_signed(f::E_SpecialFormats)
if (f == SpecialFormats.r3_g3_b2) ||
(f == SpecialFormats.r5_g6_b5) ||
(f == SpecialFormats.rgb10_a2) ||
(f == SpecialFormats.rgb5_a1) ||
(f == SpecialFormats.rgb_shared_exp_ufloats) ||
(f == SpecialFormats.rgb_tiny_ufloats) ||
(f == SpecialFormats.sRGB) ||
(f == SpecialFormats.sRGB_linear_alpha) ||
(f == SpecialFormats.rgb10_a2_uint)
#begin
return false
else
error("Unhandled case: ", f)
end
end
function stores_channel(f::E_SpecialFormats, c::E_ColorChannels)
if (f == SpecialFormats.r3_g3_b2) ||
(f == SpecialFormats.r5_g6_b5) ||
(f == SpecialFormats.rgb_shared_exp_ufloats) ||
(f == SpecialFormats.rgb_tiny_ufloats) ||
(f == SpecialFormats.sRGB)
#begin
return stores_channel(SimpleFormat(FormatTypes.normalized_uint,
SimpleFormatComponents.RGB,
SimpleFormatBitDepths.B8),
c)
elseif (f == SpecialFormats.rgb10_a2) ||
(f == SpecialFormats.rgb10_a2_uint) ||
(f == SpecialFormats.rgb5_a1) ||
(f == SpecialFormats.sRGB_linear_alpha)
#begin
return stores_channel(SimpleFormat(FormatTypes.normalized_uint,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B8),
c)
else
error("Unhandled case: ", f)
end
end
stores_channel(f::E_SpecialFormats, c::E_OtherChannels) = false
function get_n_channels(f::E_SpecialFormats)
if (f == SpecialFormats.r3_g3_b2) ||
(f == SpecialFormats.r5_g6_b5) ||
(f == SpecialFormats.rgb_shared_exp_ufloats) ||
(f == SpecialFormats.rgb_tiny_ufloats) ||
(f == SpecialFormats.sRGB)
#begin
return 3
elseif (f == SpecialFormats.rgb10_a2) ||
(f == SpecialFormats.rgb10_a2_uint) ||
(f == SpecialFormats.rgb5_a1) ||
(f == SpecialFormats.sRGB_linear_alpha)
#begin
return 4
else
error("Unhandled case: ", f)
end
end
function get_pixel_bit_size(f::E_SpecialFormats)
if (f == SpecialFormats.r3_g3_b2)
return 8
elseif (f == SpecialFormats.r5_g6_b5)
return 16
elseif (f == SpecialFormats.rgb_shared_exp_ufloats)
return 32
elseif (f == SpecialFormats.rgb_tiny_ufloats)
return 32
elseif (f == SpecialFormats.sRGB)
return 24
elseif (f == SpecialFormats.rgb10_a2)
return 32
elseif (f == SpecialFormats.rgb10_a2_uint)
return 32
elseif (f == SpecialFormats.rgb5_a1)
return 16
elseif (f == SpecialFormats.sRGB_linear_alpha)
return 32
else
error("Unhandled case: ", f)
end
end
get_ogl_enum(f::E_SpecialFormats) = GLenum(f)
##############################
# CompressedFormat #
##############################
# All below formats are based on "block compression", where 4x4 blocks of pixels
# are intelligently compressed together.
@bp_gl_enum(CompressedFormats::GLenum,
# BC4 compression, with one color channel and a value range from 0 - 1.
greyscale_normalized_uint = GL_COMPRESSED_RED_RGTC1,
# BC4 compression, with one color channel and a value range from -1 to 1.
greyscale_normalized_int = GL_COMPRESSED_SIGNED_RED_RGTC1,
# BC5 compression, with two color channels and values range from 0 - 1.
rg_normalized_uint = GL_COMPRESSED_RG_RGTC2,
# BC5 compression, with two color channels and values range from -1 - 1.
rg_normalized_int = GL_COMPRESSED_SIGNED_RG_RGTC2,
# BC6 compression, with RGB color channels and floating-point values.
rgb_float = GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT,
# BC6 compression, with RGB color channels and *unsigned* floating-point values.
rgb_ufloat = GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT,
# TODO: DXT1 for low-quality compression, with or without 1-bit alpha.
# BC7 compression, with RGBA channels and values range from 0 - 1.
rgba_normalized_uint = GL_COMPRESSED_RGBA_BPTC_UNORM,
# BC7 compression, with RGBA channels and sRGB values ranging from 0 - 1.
# "sRGB" meaning that the values get converted from sRGB space to linear space when sampled.
rgba_sRGB_normalized_uint = GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM
);
"Gets the width/height/depth of each block of pixels in a block-compressed texture of the given format"
function get_block_size(format::E_CompressedFormats)
# Currently, all Bplus-supported compressed formats
# use a block size of 4.
return 4
end
"Gets the number of blocks along each axis for a block-compressed texture of the given size and format"
function get_block_count(format::E_CompressedFormats, tex_size::Vec{N, I}) where {N, I<:Integer}
block_size::Int = get_block_size(format)
# Round up to the next full block.
return (size + (block_size - 1)) ÷ block_size
end
export CompressedFormats, E_CompressedFormats,
get_block_size, get_block_count
#
function is_supported(::E_CompressedFormats, tex_type::E_TexTypes)::Bool
# Currently, all Bplus-supported compressed formats
# only work with 2D textures.
return (tex_type != TexTypes.twoD) && (tex_type != TexTypes.cube_map)
end
is_color(f::E_CompressedFormats) = true
is_depth_only(f::E_CompressedFormats) = false
is_stencil_only(f::E_CompressedFormats) = false
is_depth_and_stencil(f::E_CompressedFormats) = false
is_integer(f::E_CompressedFormats) = false
is_signed(f::E_CompressedFormats) = (
if (f == CompressedFormats.greyscale_normalized_uint) ||
(f == CompressedFormats.rg_normalized_uint) ||
(f == CompressedFormats.rgb_ufloat) ||
(f == CompressedFormats.rgba_normalized_uint) ||
(f == CompressedFormats.rgba_sRGB_normalized_uint)
#begin
false
elseif (f == CompressedFormats.greyscale_normalized_int) ||
(f == CompressedFormats.rg_normalized_int) ||
(f == CompressedFormats.rgb_float)
true
else
error("Unhandled case: ", f)
end
)
function stores_channel(f::E_CompressedFormats, c::E_ColorChannels)
if (f == CompressedFormats.greyscale_normalized_uint) ||
(f == CompressedFormats.greyscale_normalized_int)
#begin
return c == ColorChannels.red
elseif (f == CompressedFormats.rg_normalized_uint) ||
(f == CompressedFormats.rg_normalized_int)
#begin
return c <= ColorChannels.green
elseif (f == CompressedFormats.rgb_float) ||
(f == CompressedFormats.rgb_ufloat)
#begin
return c <= ColorChannels.blue
elseif (f == CompressedFormats.rgba_normalized_uint) ||
(f == CompressedFormats.rgba_sRGB_normalized_uint)
return true
else
error("Unhandled case: ", f)
end
end
stores_channel(f::E_CompressedFormats, c::E_OtherChannels) = false
function get_n_channels(f::E_CompressedFormats)
if (f == CompressedFormats.greyscale_normalized_uint) ||
(f == CompressedFormats.greyscale_normalized_int)
#begin
return 1
elseif (f == CompressedFormats.rg_normalized_uint) ||
(f == CompressedFormats.rg_normalized_int)
#begin
return 2
elseif (f == CompressedFormats.rgb_float) ||
(f == CompressedFormats.rgb_ufloat)
#begin
return 3
elseif (f == CompressedFormats.rgba_normalized_uint) ||
(f == CompressedFormats.rgba_sRGB_normalized_uint)
return 4
else
error("Unhandled case: ", f)
end
end
function get_pixel_bit_size(f::E_CompressedFormats)
block_len::Int = get_block_size(f)
n_block_bytes::Int =
if (f == CompressedFormats.greyscale_normalized_uint) ||
(f == CompressedFormats.greyscale_normalized_int)
8
elseif (f == CompressedFormats.rg_normalized_uint) ||
(f == CompressedFormats.rg_normalized_int) ||
(f == CompressedFormats.rgb_float) ||
(f == CompressedFormats.rgb_ufloat) ||
(f == CompressedFormats.rgba_normalized_uint) ||
(f == CompressedFormats.rgba_sRGB_normalized_uint)
16
else
error("Unhandled case: ", f)
end
return (n_block_bytes * 8) ÷ (block_len * block_len)
end
get_ogl_enum(f::E_CompressedFormats) = GLenum(f)
###################################
# Depth/Stencil Formats #
###################################
# Formats for depth and/or stencil textures.
@bp_gl_enum(DepthStencilFormats::GLenum,
# Depth texture with unsigned 16-bit data.
depth_16u = GL_DEPTH_COMPONENT16,
# Depth texture with unsigned 24-bit data.
depth_24u = GL_DEPTH_COMPONENT24,
# Depth texture with unsigned 32-bit data.
depth_32u = GL_DEPTH_COMPONENT32,
# Depth texture with floating-point 32-bit data.
depth_32f = GL_DEPTH_COMPONENT32F,
# Stencil texture with unsigned 8-bit data.
# Note that other sizes exist for stencil textures,
# but the OpenGL wiki strongly advises against using them.
stencil_8 = GL_STENCIL_INDEX8,
# Hybrid Depth/Stencil texture with unsigned 24-bit depth
# and unsigned 8-bit stencil.
depth24u_stencil8 = GL_DEPTH24_STENCIL8,
# Hybrid Depth/Stencil texture with floating-point 32-bit depth
# and unsigned 8-bit stencil (and 24 bits of padding in between them).
depth32f_stencil8 = GL_DEPTH32F_STENCIL8
);
primitive type Depth24uStencil8u 32 end
"The data in each pixel of a `depth24u_stencil8` texture"
Depth24uStencil8u(u::UInt32) = reinterpret(Depth24uStencil8u, u)
Depth24uStencil8u(depth::UInt32, stencil::UInt8) = Depth24uStencil8u(
(depth << 8) | stencil
)
Depth24uStencil8u(depth::UInt64, stencil::UInt8) = Depth24uStencil8u(UInt32(depth), stencil)
function Depth24uStencil8u(depth01::AbstractFloat, stencil::UInt8)
max_uint24 = UInt32((2^24) - 1)
return Depth24uStencil8u(
UInt32(clamp(floor(depth01 * Float32(max_uint24)),
0, max_uint24)),
stencil
)
end
Base.zero(::Type{Depth24uStencil8u}) = Depth24uStencil8u(0x000000, 0x0)
export Depth24uStencil8u
primitive type Depth32fStencil8u 64 end
"The data in each pixel of a `depth32f_stencil8` texture"
Depth32fStencil8u(u::UInt64) = reinterpret(Depth32fStencil8u, u)
Depth32fStencil8u(depth::Float32, stencil::UInt8) = Depth32fStencil8u(
(UInt64(reinterpret(UInt32, depth)) << 32) |
stencil
)
Base.zero(::Type{Depth32fStencil8u}) = Depth32fStencil8u(Float32(0), 0x0)
export Depth32fStencil8u
"Pulls the depth and stencil values out of a packed texture pixel"
function Base.split(pixel::Depth24uStencil8u)::Tuple{UInt32, UInt8}
u = reinterpret(UInt32, pixel)
return (
(u & 0xffffff00) >> 8,
UInt8(u & 0xff)
)
end
function Base.split(pixel::Depth32fStencil8u)::Tuple{Float32, UInt8}
u = reinterpret(UInt64, pixel)
return (
Float32((u & 0xffffffff00000000) >> 32),
UInt8(u & 0x00000000000000ff)
)
end
export DepthStencilFormats, E_DepthStencilFormats,
Depth24uStencil8u, Depth32fStencil8u
#
function is_supported(f::E_DepthStencilFormats, t::E_TexTypes)
# Depth/stencil formats are not supported on 3D textures.
return t != TexTypes.threeD
end
is_color(f::E_DepthStencilFormats) = false
is_depth_only(f::E_DepthStencilFormats) =
if (f == DepthStencilFormats.depth_16u) ||
(f == DepthStencilFormats.depth_24u) ||
(f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f)
true
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8) ||
(f == DepthStencilFormats.stencil_8)
false
else
error("Unhandled case: ", f)
end
is_stencil_only(f::E_DepthStencilFormats) =
if (f == DepthStencilFormats.stencil_8)
true
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8) ||
(f == DepthStencilFormats.depth_16u) ||
(f == DepthStencilFormats.depth_24u) ||
(f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f)
false
else
error("Unhandled case: ", f)
end
is_depth_and_stencil(f::E_DepthStencilFormats) =
if (f == DepthStencilFormats.depth_16u) ||
(f == DepthStencilFormats.depth_24u) ||
(f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f) ||
(f == DepthStencilFormats.stencil_8)
false
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8)
true
else
error("Unhandled case: ", f)
end
is_integer(f::E_DepthStencilFormats) =
if (f == DepthStencilFormats.stencil_8)
true
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8) ||
(f == DepthStencilFormats.depth_16u) ||
(f == DepthStencilFormats.depth_24u) ||
(f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f)
false
else
error("Unhandled case: ", f)
end
stores_channel(f::E_DepthStencilFormats, c::E_ColorChannels) = false
stores_channel(f::E_DepthStencilFormats, c::E_OtherChannels) =
if (f == DepthStencilFormats.depth_16u) ||
(f == DepthStencilFormats.depth_24u) ||
(f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f)
#begin
(c == OtherChannels.depth)
elseif (f == DepthStencilFormats.stencil_8)
(c == OtherChannels.stencil)
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8)
true
else
error("Unhandled case: ", f)
end
get_n_channels(f::E_DepthStencilFormats) =
if (f == DepthStencilFormats.depth_16u) ||
(f == DepthStencilFormats.depth_24u) ||
(f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f) ||
(f == DepthStencilFormats.stencil_8)
1
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8)
2
else
error("Unhandled case: ", f)
end
get_pixel_bit_size(f::E_DepthStencilFormats) =
if (f == DepthStencilFormats.depth_16u)
16
elseif (f == DepthStencilFormats.depth_24u)
24
elseif (f == DepthStencilFormats.depth_32u) ||
(f == DepthStencilFormats.depth_32f)
32
elseif (f == DepthStencilFormats.depth24u_stencil8) ||
(f == DepthStencilFormats.depth32f_stencil8)
64
else
error("Unhandled case: ", f)
end
get_ogl_enum(f::E_DepthStencilFormats) = GLenum(f)
#######################
# TexFormat #
#######################
"Describes a pixel format for any kind of texture"
const TexFormat = Union{SimpleFormat, E_SpecialFormats, E_CompressedFormats, E_DepthStencilFormats}
export TexFormat | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 11777 |
########################
# Filtering #
########################
# The behavior of a texture when you sample past its boundaries.
@bp_gl_enum(WrapModes::GLenum,
# Repeat the texture indefinitely, creating a tiling effect.
repeat = GL_REPEAT,
# Repeat the texture indefinitely, but mirror it across each edge.
mirrored_repeat = GL_MIRRORED_REPEAT,
# Clamp the coordinates so that the texture outputs its last edge pixels
# when going past its border.
clamp = GL_CLAMP_TO_EDGE,
# Outputs a custom color when outside the texture.
custom_border = GL_CLAMP_TO_BORDER
)
export WrapModes, E_WrapModes
# The filtering mode for a texture's pixels.
@bp_gl_enum(PixelFilters::GLenum,
# "Nearest" sampling. Individual pixels are crisp and square.
rough = GL_NEAREST,
# "Linear" sampling. Blends the nearest neighbor pixels together.
smooth = GL_LINEAR
)
export PixelFilters, E_PixelFilters
"Mip-maps can be sampled in the same way as neighboring pixels, or turned off entirely"
const MipFilters = Optional{E_PixelFilters}
export MipFilters
"Converts a texture 'mag' filter into an OpenGL enum value"
get_ogl_enum(pixel_filtering::E_PixelFilters) = GLenum(pixel_filtering)
"Converts a texture 'min' filter into an OpenGL enum value"
function get_ogl_enum(pixel_filtering::E_PixelFilters, mip_filtering::MipFilters)
if pixel_filtering == PixelFilters.rough
if isnothing(mip_filtering)
return GL_NEAREST
elseif mip_filtering == PixelFilters.rough
return GL_NEAREST_MIPMAP_NEAREST
elseif mip_filtering == PixelFilters.smooth
return GL_NEAREST_MIPMAP_LINEAR
else
error("Unhandled case: ", mip_filtering)
end
elseif pixel_filtering == PixelFilters.smooth
if isnothing(mip_filtering)
return GL_LINEAR
elseif mip_filtering == PixelFilters.rough
return GL_LINEAR_MIPMAP_NEAREST
elseif mip_filtering == PixelFilters.smooth
return GL_LINEAR_MIPMAP_LINEAR
else
error("Unhandled case: ", mip_filtering)
end
else
error("Unhandled case: ", pixel_filtering)
end
end
# Note: get_ogl_enum() is already defined and exported by other GL code
#########################
# Sampler struct #
#########################
"Information about a sampler for an N-dimensional texture"
@kwdef struct TexSampler{N}
# The wrapping mode along each individual axis.
# This settings means nothing for cubemap textures.
wrapping::Union{E_WrapModes, Vec{N, E_WrapModes}} = WrapModes.repeat
pixel_filter::E_PixelFilters = PixelFilters.smooth
mip_filter::MipFilters = pixel_filter
# A separate filter to use when shrinking the image (as opposed to magnifying it).
pixel_min_filter::E_PixelFilters = pixel_filter
# Anisotropic filtering.
# Should have a value between 1 and get_context().device.max_anisotropy.
anisotropy::Float32 = one(Float32)
# Offsets the mip level calculation, if using mipmapping.
# For example, a value of 1 essentially forces all samples to go up one mip level.
mip_offset::Float32 = zero(Float32)
# Sets the boundaries of the mip levels used in sampling.
# As usual, 1 is the first mip (i.e. original texture), and
# higher values represent smaller mips.
mip_range::IntervalF = Interval(min=-999, max=1001)
# If this is a depth (or depth-stencil) texture,
# this setting makes it a "shadow" sampler.
depth_comparison_mode::Optional{E_ValueTests} = nothing
# Whether cubemaps should be sampled seamlessly.
# This comes from the extension 'ARB_seamless_cubemap_per_texture',
# and is important for bindless cubemap textures which ignore the global setting.
cubemap_seamless::Bool = true
end
# StructTypes doesn't have any way to deserialize an immutable @kwdef struct.
StructTypes.StructType(::Type{<:TexSampler}) = StructTypes.UnorderedStruct()
function StructTypes.construct(values::Vector{Any}, T::Type{<:TexSampler})
kw_args = NamedTuple()
if isassigned(values, 1)
kw_args = (kw_args..., wrapping=values[1])
end
if isassigned(values, 2)
kw_args = (kw_args..., pixel_filter=values[2])
end
if isassigned(values, 3)
kw_args = (kw_args..., mip_filter=values[3])
end
if isassigned(values, 4)
kw_args = (kw_args..., pixel_min_filter=values[4])
end
if isassigned(values, 5)
kw_args = (kw_args..., anisotropy=values[5])
end
if isassigned(values, 6)
kw_args = (kw_args..., mip_offset=values[6])
end
if isassigned(values, 7)
kw_args = (kw_args..., mip_range=values[7])
end
if isassigned(values, 8)
kw_args = (kw_args..., depth_comparison_mode=values[8])
end
if isassigned(values, 9)
kw_args = (kw_args..., cubemap_seamless=values[9])
end
return T(; kw_args...)
end
# The "wrapping" being a union slightly complicates equality/hashing.
Base.:(==)(a::TexSampler{N}, b::TexSampler{N}) where {N} = (
(a.pixel_filter == b.pixel_filter) &&
(a.pixel_min_filter == b.pixel_min_filter) &&
(a.mip_filter == b.mip_filter) &&
(a.anisotropy == b.anisotropy) &&
(a.mip_offset == b.mip_offset) &&
(a.mip_range == b.mip_range) &&
(a.depth_comparison_mode == b.depth_comparison_mode) &&
(a.cubemap_seamless == b.cubemap_seamless) &&
if a.wrapping isa E_WrapModes
if b.wrapping isa E_WrapModes
a.wrapping == b.wrapping
else
all(i -> b.wrapping[i] == a.wrapping, 1:N)
end
else
if b.wrapping isa E_WrapModes
all(i -> a.wrapping[i] == b.wrapping, 1:N)
else
a.wrapping == b.wrapping
end
end
)
Base.hash(s::TexSampler{N}, u::UInt) where {N} = hash(
tuple(
s.pixel_filter, s.mip_filter, s.pixel_min_filter, s.anisotropy,
s.mip_offset, s.mip_range,
s.depth_comparison_mode, s.cubemap_seamless,
if s.wrapping isa E_WrapModes
Vec(i -> s.wrapping, N)
else
s.wrapping
end
),
u
)
# Convert a sampler to a different-dimensional one.
# Fill in the extra dimensions with a constant pre-chosen value,
# to make it easier to use 3D samplers as dictionary keys.
Base.convert(::Type{TexSampler{N2}}, s::TexSampler{N1}) where {N1, N2} = TexSampler{N2}(
if s.wrapping isa E_WrapModes
s.wrapping
else
Vec(ntuple(i -> s.wrapping[i], Val(min(N1, N2)))...,
ntuple(i -> WrapModes.repeat, Val(max(0, N2 - N1)))...)
end,
s.pixel_filter, s.mip_filter, s.pixel_min_filter,
s.anisotropy, s.mip_offset, s.mip_range,
s.depth_comparison_mode,
s.cubemap_seamless
)
"Gets a sampler's wrapping mode across all axes, assuming they're all the same"
@inline function get_wrapping(s::TexSampler)
if s.wrapping isa E_WrapModes
return s.wrapping
else
@bp_gl_assert(all(w-> w==s.wrapping[1], s.wrapping),
"TexSampler's wrapping setting has different values along each axis: ", s.wrapping)
return s.wrapping[1]
end
end
"Applies a sampler's settings to a texture"
apply(s::TexSampler, tex::Ptr_Texture) = apply_impl(s, convert(GLuint, tex), glTextureParameteri, glTextureParameterf)
"Applies a sampler's settings to an OpenGL sampler object"
apply(s::TexSampler, tex::Ptr_Sampler) = apply_impl(s, convert(GLuint, tex), glSamplerParameteri, glSamplerParameterf)
"Implementation for apply() with samplers"
function apply_impl( s::TexSampler{N},
ptr::GLuint,
gl_set_func_i::Function,
gl_set_func_f::Function
) where {N}
context::Optional{Context} = get_context()
@bp_check(exists(context), "Can't apply sampler settings to a texture outside of an OpenGL context")
# Set filtering.
gl_set_func_i(ptr, GL_TEXTURE_MIN_FILTER, get_ogl_enum(s.pixel_min_filter, s.mip_filter))
gl_set_func_i(ptr, GL_TEXTURE_MAG_FILTER, get_ogl_enum(s.pixel_filter))
# Set anisotropy.
@bp_check(s.anisotropy >= 1,
"TexSampler anisotropy of ", s.anisotropy, " is too low!",
" It should be between 1 and ", context.device.max_anisotropy, ", inclusive")
@bp_check(s.anisotropy <= context.device.max_anisotropy,
"TexSampler anisotropy of ", s.anisotropy,
" is above the GPU driver's max value of ",
context.device.max_anisotropy)
gl_set_func_f(ptr, GL_TEXTURE_MAX_ANISOTROPY, s.anisotropy)
# Set mip bias.
gl_set_func_f(ptr, GL_TEXTURE_MIN_LOD, min_inclusive(s.mip_range) - 1)
gl_set_func_f(ptr, GL_TEXTURE_MAX_LOD, max_inclusive(s.mip_range) - 1)
gl_set_func_f(ptr, GL_TEXTURE_LOD_BIAS, s.mip_offset)
# Depth comparison.
if exists(s.depth_comparison_mode)
gl_set_func_i(ptr, GL_TEXTURE_COMPARE_MODE, GLint(GL_COMPARE_REF_TO_TEXTURE))
gl_set_func_i(ptr, GL_TEXTURE_COMPARE_FUNC, GLint(s.depth_comparison_mode))
else
gl_set_func_i(ptr, GL_TEXTURE_COMPARE_MODE, GLint(GL_NONE))
end
# Set wrapping.
# Interesting note: OpenGL does *not* care if you try to set this value for higher dimensions
# than the texture actually has.
wrapping_keys = (GL_TEXTURE_WRAP_S, GL_TEXTURE_WRAP_T, GL_TEXTURE_WRAP_R)
wrapping_vec = if s.wrapping isa E_WrapModes
Vec(i -> s.wrapping, N)
else
s.wrapping
end
for i::Int in 1:N
gl_set_func_i(ptr, wrapping_keys[i], GLint(wrapping_vec[i]))
end
# Set cubemap sampling.
gl_set_func_i(ptr, GL_TEXTURE_CUBE_MAP_SEAMLESS, GLint(GL_TRUE))
end
export TexSampler, get_wrapping, apply,
SwizzleRGBA
##############################
# Depth/Stencil Sampling #
##############################
# Textures containing hybrid depth/stencil data can be sampled in a few ways.
@bp_gl_enum(DepthStencilSources::GLenum,
# The depth component is sampled, acting like a Red-only float/normalized int texture.
depth = GL_DEPTH_COMPONENT,
# The stencil component is sampled, acting like a Red-only uint texture.
stencil = GL_STENCIL_INDEX
)
export DepthStencilSources, E_DepthStencilSources
####################################
# TexSampler Service Interface #
####################################
"
Samplers can be re-used between textures, so you only need to define a few sampler objects
across an entire rendering context.
This service provides re-usable sampler objects
for all possible configurations of sampler parameters.
"
@bp_service SamplerProvider(force_unique) begin
lookup::Dict{TexSampler{3}, Ptr_Sampler}
INIT() = new(Dict{TexSampler{3}, Ptr_Sampler}())
SHUTDOWN(service, is_context_closing::Bool) = begin
if !is_context_closing
error("You should not close the SamplerProvider service early!")
# OpenGL cleanup code is left here for completeness.
for handle in values(service.lookup)
glDeleteSamplers(1, Ref(gl_type(handle)))
end
end
empty!(service.lookup)
end
"Gets an OpenGL sampler object matching the given settings"
function get_sampler(service, settings::TexSampler{N})::Ptr_Sampler where {N}
if N < 3
return get_sampler(convert(TexSampler{3}, settings))
else
return get!(service.lookup, settings) do
handle = Ptr_Sampler(get_from_ogl(gl_type(Ptr_Sampler), glCreateSamplers, 1))
apply(settings, handle)
return handle
end
end
end
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 40112 | "
Some kind of organized color data which can be 'sampled'.
This includes regular images, as well as 1D and 3D textures and 'cubemaps'.
Note that mip levels are counted from 1, not from 0,
to match Julia's convention.
"
mutable struct Texture <: AbstractResource
handle::Ptr_Texture
type::E_TexTypes
format::TexFormat
n_mips::Int
# 3D textures have a full 3-dimensional size.
# 2D/Cubemap textures have a constant Z size of 1.
# 1D textures have a contant YZ size of 1.
size::v3u
# 3D textures have a full 3D sampler.
# Other textures ignore the higher dimensions which don't apply to them.
sampler::TexSampler{3}
# If this is a hybrid depth/stencil texture,
# only one of those two components can be sampled at a time.
depth_stencil_sampling::Optional{E_DepthStencilSources}
# The mixing of this texture's channels when it's being sampled by a shader.
swizzle::SwizzleRGBA
# This texture's cached view handles.
known_views::Dict{ViewParams, View}
end
export Texture
function Base.close(t::Texture)
# Release the texture's Views.
for view::View in values(t.known_views)
service_ViewDebugging_remove_view(view.handle)
view.handle = Ptr_View()
end
glDeleteTextures(1, Ref(gl_type(t.handle)))
setfield!(t, :handle, Ptr_Texture())
end
############################
# Constructors #
############################
"Creates a 1D texture"
function Texture( format::TexFormat,
width::Union{Integer, Vec{1, <:Integer}}
;
sampler::TexSampler{1} = TexSampler{1}(),
n_mips::Integer = get_n_mips(width isa Integer ? width : width.x),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
width = (width isa Integer) ? width : width.x
return generate_texture(
TexTypes.oneD, format, v3u(width, 1, 1),
convert(TexSampler{3}, sampler),
n_mips,
depth_stencil_sampling,
swizzling,
nothing
)
end
function Texture( format::TexFormat,
initial_data::PixelBufferD{1},
data_bgr_ordering::Bool = false
;
sampler::TexSampler{1} = TexSampler{1}(),
n_mips::Integer = get_n_mips(length(initial_data)),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
return generate_texture(
TexTypes.oneD, format, v3u(length(initial_data), 1, 1),
convert(TexSampler{3}, sampler),
n_mips,
depth_stencil_sampling,
swizzling,
(initial_data, data_bgr_ordering)
)
end
"Creates a 2D texture"
function Texture( format::TexFormat,
size::Vec2{<:Integer}
;
sampler::TexSampler{2} = TexSampler{2}(),
n_mips::Integer = get_n_mips(size),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
return generate_texture(
TexTypes.twoD, format, v3u(size..., 1),
convert(TexSampler{3}, sampler),
n_mips,
depth_stencil_sampling,
swizzling,
nothing
)
end
function Texture( format::TexFormat,
initial_data::PixelBufferD{2},
data_bgr_ordering::Bool = false
;
sampler::TexSampler{2} = TexSampler{2}(),
n_mips::Integer = get_n_mips(Vec(size(initial_data))),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
return generate_texture(
TexTypes.twoD, format,
v3u(size(initial_data)..., 1),
convert(TexSampler{3}, sampler),
n_mips,
depth_stencil_sampling,
swizzling,
(initial_data, data_bgr_ordering)
)
end
"Creates a 3D texture"
function Texture( format::TexFormat,
size::Vec3{<:Integer}
;
sampler::TexSampler{3} = TexSampler{3}(),
n_mips::Integer = get_n_mips(size),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
return generate_texture(
TexTypes.threeD, format, convert(v3u, size),
sampler,
n_mips,
depth_stencil_sampling,
swizzling,
nothing
)
end
function Texture( format::TexFormat,
initial_data::PixelBufferD{3},
data_bgr_ordering::Bool = false
;
sampler::TexSampler{3} = TexSampler{3}(),
n_mips::Integer = get_n_mips(Vec(size(initial_data))),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
return generate_texture(
TexTypes.threeD, format,
v3u(size(initial_data)),
sampler,
n_mips,
depth_stencil_sampling,
swizzling,
(initial_data, data_bgr_ordering)
)
end
"Creates a Cubemap texture"
function Texture_cube( format::TexFormat,
square_length::Integer,
initial_value = # Needed to get around an apparent driver bug
# where non-layered images of a cubemap don't accept writes
# until the pixels have been cleared.
if format isa E_CompressedFormats
# Nobody needs images of compressed textures anyway; let them go.
nothing
elseif is_color(format)
if is_signed(format)
zero(vRGBAu)
elseif is_integer(format)
zero(vRGBAi)
else
zero(vRGBAf)
end
elseif is_depth_only(format)
zero(Float32)
elseif is_stencil_only(format)
zero(UInt8)
elseif is_depth_and_stencil(format)
zero(Depth32fStencil8u)
else
error("Unexpected format: ", format)
end
;
sampler::TexSampler{1} = TexSampler{1}(),
n_mips::Integer = get_n_mips(square_length),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
tex = generate_texture(
TexTypes.cube_map, format,
v3u(square_length, square_length, 1),
convert(TexSampler{3}, sampler),
n_mips, depth_stencil_sampling, swizzling,
nothing
)
if exists(initial_value)
clear_tex_pixels(tex, initial_value)
end
return tex
end
function Texture_cube( format::TexFormat,
initial_faces_data::PixelBufferD{3},
data_bgr_ordering::Bool = false
;
sampler::TexSampler{1} = TexSampler{1}(),
n_mips::Integer = get_n_mips(Vec(size(initial_faces_data[1:2]))),
depth_stencil_sampling::Optional{E_DepthStencilSources} = nothing,
swizzling::SwizzleRGBA = SwizzleRGBA()
)::Texture
return generate_texture(
TexTypes.cube_map, format,
v3u(size(initial_faces_data)[1:2]..., 1),
convert(TexSampler{3}, sampler),
n_mips, depth_stencil_sampling, swizzling,
(initial_faces_data, data_bgr_ordering)
)
end
export Texture_cube
"
Creates a texture similar to the given one, but with a different format.
The new texture's data will not be initialized to anything.
"
Texture(template::Texture, format::TexFormat) = generate_texture(
template.type, format, template.size, template.sampler, template.n_mips,
(format isa E_DepthStencilFormats) ? template.depth_stencil_sampling : nothing,
template.swizzle, nothing
)
################################
# Private Implementation #
################################
"
Processes data representing a subset of a texture,
checking it for errors and returning the final pixel range and mip-level.
For simplicity, the returned range is always 3D.
Cubemap textures use Z to represent the cube faces.
"
function process_tex_subset(tex::Texture, subset::TexSubset)::Tuple{Box3Du, UInt}
# Check the dimensionality of the subset.
if tex.type == TexTypes.oneD
@bp_check(subset isa TexSubset{1},
"Expected a 1D subset for 1D textures; got ", typeof(subset))
elseif tex.type == TexTypes.twoD
@bp_check(subset isa TexSubset{2},
"Expected a 2D subset for 2D textures and cubemaps; got ", typeof(subset))
elseif tex.type in (TexTypes.threeD, TexTypes.cube_map)
@bp_check(subset isa TexSubset{3},
"Expected a 3D subset for Cubemap and 3D textures; got ", typeof(subset))
else
error("Unimplemented: ", tex.type)
end
# Check the mip index.
legal_mips = IntervalU(min=1, max=tex.n_mips)
@bp_check(is_touching(legal_mips, subset.mip),
"Texture's mip range is ", legal_mips, " but you requested mip ", subset.mip)
# Get the 3D size of the texture.
# 1D tex has Y=Z=1, 2D tex has Z=1, and Cubemap tex has Z=6.
tex_size::v3u = get_mip_size(tex.size, subset.mip)
if tex.type == TexTypes.oneD
@set! tex_size.y = 1
@set! tex_size.z = 1
elseif tex.type == TexTypes.twoD
@set! tex_size.z = 1
elseif tex.type == TexTypes.cube_map
@set! tex_size.z = 6
end
# Make sure the subset is fully inside the texture.
tex_pixel_range = Box3Du(min=one(v3u), size=tex_size)
subset_pixel_range::Box3Du = reshape(get_subset_range(subset, tex_size),
3,
new_dims_size=UInt32(1),
new_dims_min=UInt32(1))
@bp_check(contains(tex_pixel_range, subset_pixel_range),
"Texture at mip level ", subset.mip, " is size ", tex_size,
", and your subset is out of those bounds: ", subset_pixel_range)
return subset_pixel_range, subset.mip
end
function generate_texture( type::E_TexTypes,
format::TexFormat,
size::v3u,
sampler::TexSampler{3},
n_mips::Integer,
depth_stencil_sampling::Optional{E_DepthStencilSources},
swizzling::SwizzleRGBA,
initial_data::Optional{Tuple{PixelBuffer, Bool}}
)::Texture
# Verify the format/sampling settings are valid for this texture.
@bp_check(exists(get_ogl_enum(format)),
"Texture format isn't valid: ", sprint(show, format))
if is_depth_and_stencil(format)
@bp_check(exists(depth_stencil_sampling),
"Using a hybrid depth/stencil texture but didn't provide a depth_stencil_sampling mode")
else
@bp_check(isnothing(depth_stencil_sampling),
"Can't provide a depth_stencil_sampling mode to a texture that isn't hybrid depth/stencil")
end
if !(format isa E_DepthStencilFormats) || is_stencil_only(format)
@bp_check(isnothing(sampler.depth_comparison_mode),
"Can't use a 'shadow sampler' for a non-depth texture")
end
@bp_check(is_supported(format, type),
"Texture type ", type, " doesn't support the format ", sprint(show, format))
# Make sure the global store of samplers has been initialized.
if !service_SamplerProvider_exists()
service_SamplerProvider_init()
end
# Construct the Texture instance.
tex::Texture = Texture(Ptr_Texture(get_from_ogl(gl_type(Ptr_Texture),
glCreateTextures, GLenum(type), 1)),
type, format, n_mips, size,
sampler, depth_stencil_sampling, swizzling,
Dict{ViewParams, View}())
# Configure the texture with OpenGL calls.
set_tex_swizzling(tex, swizzling)
if exists(depth_stencil_sampling)
set_tex_depthstencil_source(tex, depth_stencil_sampling)
end
apply(sampler, tex.handle)
# Set up the texture with non-reallocatable storage.
if tex.type == TexTypes.oneD
glTextureStorage1D(tex.handle, n_mips, get_ogl_enum(tex.format), size.x)
elseif (tex.type == TexTypes.twoD) || (tex.type == TexTypes.cube_map)
glTextureStorage2D(tex.handle, n_mips, get_ogl_enum(tex.format), size.xy...)
elseif tex.type == TexTypes.threeD
glTextureStorage3D(tex.handle, n_mips, get_ogl_enum(tex.format), size.xyz...)
else
error("Unhandled case: ", tex.type)
end
# Upload the initial data, if given.
if exists(initial_data)
set_tex_pixels(tex, initial_data[1];
@optionalkw(is_color(format), bgr_ordering, initial_data[2]),
recompute_mips=true)
end
return tex
end
"Helper to generate the default 'subset' of a texture"
default_tex_subset(tex::Texture)::@unionspec(TexSubset{_}, 1, 2, 3) =
if tex.type == TexTypes.oneD
TexSubset{1}()
elseif tex.type == TexTypes.twoD
TexSubset{2}()
elseif tex.type in (TexTypes.cube_map, TexTypes.threeD)
TexSubset{3}()
else
error("Unhandled case: ", tex.type)
end
#
"Internal helper to get, set, or clear texture data"
function texture_op_impl( tex::Texture,
component_type::GLenum,
components::GLenum,
subset::TexSubset,
value::Ref,
recompute_mips::Bool,
mode::@ano_enum(Set, Get, Clear),
# Get/Set ops would like to ensure that the array passed in
# matches the size of the texture subset.
known_subset_data_size::Optional{VecT{<:Integer}} = nothing
;
get_buf_pixel_byte_size::Int = -1 # Only for Get ops
)
(subset_pixels_3D::Box3Du, mip::UInt) = process_tex_subset(tex, subset)
# If requested, check the size of the actual array data
# against the size we are telling OpenGL.
if exists(known_subset_data_size)
@bp_check(prod(known_subset_data_size) >= prod(size(subset_pixels_3D)),
"Your pixel data array is size ", known_subset_data_size,
", but the texture (or subset/mip) you are working with is larger: ", subset_pixels_3D)
end
# Perform the requested operation.
if mode isa Val{:Set}
@bp_gl_assert(get_buf_pixel_byte_size == -1,
"Internal field 'get_buf_pixel_byte_size' shouldn't be passed for a Set op")
if tex.type == TexTypes.oneD
glTextureSubImage1D(tex.handle, mip - 1,
min_inclusive(subset_pixels_3D).x - 1,
size(subset_pixels_3D).x,
components, component_type,
value)
elseif tex.type == TexTypes.twoD
glTextureSubImage2D(tex.handle, mip - 1,
(min_inclusive(subset_pixels_3D).xy - 1)...,
size(subset_pixels_3D).xy...,
components, component_type,
value)
elseif (tex.type == TexTypes.threeD) || (tex.type == TexTypes.cube_map)
glTextureSubImage3D(tex.handle, mip - 1,
(min_inclusive(subset_pixels_3D) - 1)...,
size(subset_pixels_3D)...,
components, component_type,
value)
else
error("Unhandled case: ", tex.type)
end
elseif mode isa Val{:Get}
@bp_gl_assert(get_buf_pixel_byte_size > 0,
"Internal field 'get_buf_pixel_byte_size' not passed for a Get operation like it should have been")
@bp_gl_assert(!recompute_mips,
"Asked to recompute mips after getting a texture's pixels, which is pointless")
glGetTextureSubImage(tex.handle, mip - 1,
(min_inclusive(subset_pixels_3D) - 1)...,
size(subset_pixels_3D)...,
components, component_type,
prod(size(subset_pixels_3D)) * get_buf_pixel_byte_size,
value)
elseif mode isa Val{:Clear}
@bp_gl_assert(get_buf_pixel_byte_size == -1,
"Internal field 'get_buf_pixel_byte_size' shouldn't be passed for a Clear op")
glClearTexSubImage(tex.handle, mip - 1,
(min_inclusive(subset_pixels_3D) - 1)...,
size(subset_pixels_3D)...,
components, component_type,
value)
end
if recompute_mips
glGenerateTextureMipmap(tex.handle)
end
end
##########################
# Public Interface #
##########################
get_ogl_handle(t::Texture) = t.handle
"
Gets a view of this texture, using the given sampler
(or the texture's built-in sampler settings).
"
function get_view(t::Texture, sampler::Optional{TexSampler} = nothing)::View
return get!(() -> View(t, sampler),
t.known_views, sampler)
end
"
Gets a view of this texture's pixels without sampling,
which allows for other uses like writing to the pixels.
"
function get_view(t::Texture, view::SimpleViewParams)::View
return get!(() -> View(t, t.format, view),
t.known_views, view)
end
# Overload some view functions to work with a texture's default view.
view_activate(tex::Texture) = view_activate(get_view(tex))
view_deactivate(tex::Texture) = view_deactivate(get_view(tex))
"
Gets a type-unstable texture size based on its type.
Cube-maps are treated as 3D with a Z-size of 6.
1D textures are returned as 1D vectors for consistency.
"
function tex_size(tex::Texture)::Union{v1u, v2u, v3u}
if tex.type == TexTypes.oneD
return v1u(tex.size.x)
elseif tex.type == TexTypes.twoD
return tex.size.xy
elseif tex.type == TexTypes.threeD
return tex.size
elseif tex.type == TexTypes.cube_map
return v3u(tex.size.xy..., 6)
else
error("Unhandled: ", tex.type)
end
end
"Changes how a texture's pixels are mixed when it's sampled on the GPU"
function set_tex_swizzling(t::Texture, new::SwizzleRGBA)
new_as_ints = reinterpret(Vec4{GLint}, new)
glTextureParameteriv(t.handle, GL_TEXTURE_SWIZZLE_RGBA, Ref(new_as_ints.data))
setfield!(t, :swizzle, new)
end
"Changes the data that can be sampled from this texture, assuming it's a depth/stencil hybrid"
function set_tex_depthstencil_source(t::Texture, source::E_DepthStencilSources)
@bp_check(is_depth_and_stencil(t.format),
"Can only set depth/stencil source for a depth/stencil hybrid texture")
if source != t.depth_stencil_sampling
glTextureParameteri(t.handle, GL_DEPTH_STENCIL_TEXTURE_MODE, GLint(source))
setfield!(t, :depth_stencil_sampling, source)
end
end
"Gets the byte size of a specific texture mip level"
function get_mip_byte_size(t::Texture, level::Integer)
if t.type == TexTypes.cube
return get_byte_size(t.format, t.size.xy * Vec(6, 1))
else
return get_byte_size(t.format, t.size)
end
end
"Gets the total byte-size of this texture's pixels, including all mips"
function get_gpu_byte_size(t::Texture)
return sum(get_mip_byte_size(t, mip) for mip in 1:t.n_mips)
end
"
Clears a texture to a given value, without knowing yet what kind of texture it is.
The dimensionality of the `subset` parameter must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function clear_tex_pixels(t::Texture, values...; kw...)
if is_color(t.format)
clear_tex_color(t, values...; kw...)
elseif is_depth_only(t.format)
clear_tex_depth(t, values...; kw...)
elseif is_stencil_only(t.format)
clear_tex_stencil(t, values...; kw...)
elseif is_depth_and_stencil(t.format)
clear_tex_depthstencil(t, values...; kw...)
else
error("Unexpected format: ", t.format)
end
end
"Clears a color texture to a given value.
The dimensionality of the `subset` parameter must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function clear_tex_color( t::Texture,
color::PixelIOValue,
subset::TexSubset = default_tex_subset(t)
;
bgr_ordering::Bool = false,
single_component::E_PixelIOChannels = PixelIOChannels.red,
recompute_mips::Bool = true
)
T = get_component_type(typeof(color))
N = get_component_count(typeof(color))
@bp_check(!(t.format isa E_CompressedFormats),
"Can't clear compressed textures")
@bp_check(is_color(t.format), "Can't clear a non-color texture with a color")
@bp_check(!is_integer(t.format) || T<:Integer,
"Can't clear an integer texture with a non-integer value")
@bp_check(!bgr_ordering || N >= 3,
"Supplied the 'bgr_ordering' parameter but the data only has 1 or 2 components")
texture_op_impl(
t,
GLenum(get_pixel_io_type(T)),
get_ogl_enum(get_pixel_io_channels(Val(N), bgr_ordering, single_component),
is_integer(t.format)),
subset,
contiguous_ref(color, T),
recompute_mips, Val(:Clear)
)
end
"Clears a depth texture to a given value.
The dimensionality of the `subset` parameter must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function clear_tex_depth( t::Texture,
depth::T,
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
) where {T<:PixelIOComponent}
@bp_check(is_depth_only(t.format),
"Can't clear depth in a texture of format ", t.format)
texture_op_impl(
t,
GLenum(get_pixel_io_type(T)),
GL_DEPTH_COMPONENT,
subset,
Ref(depth),
recompute_mips, Val(:Clear)
)
end
"Clears a stencil texture to a given value.
The dimensionality of the `subset` parameter must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function clear_tex_stencil( t::Texture,
stencil::UInt8,
subset::TexSubset = default_tex_subset(t)
)
@bp_check(is_stencil_only(t.format),
"Can't clear stencil in a texture of format ", t.format)
texture_op_impl(
t,
GLenum(get_pixel_io_type(UInt8)),
GL_STENCIL_INDEX,
subset,
Ref(stencil),
false,
Val(:Clear)
)
end
"
Clears a depth/stencil hybrid texture to a given value with 24 depth bits and 8 stencil bits.
The dimensionality of the `subset` parameter must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function clear_tex_depthstencil( t::Texture,
depth::Float32,
stencil::UInt8,
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
)
if t.format == DepthStencilFormats.depth24u_stencil8
return clear_tex_depthstencil(t, Depth24uStencil8u(depth, stencil),
subset,
recompute_mips=recompute_mips)
elseif t.format == DepthStencilFormats.depth32f_stencil8
return clear_tex_depthstencil(t, Depth32fStencil8u(depth, stencil),
subset,
recompute_mips=recompute_mips)
else
error("Texture doesn't appear to be a depth/stencil hybrid format: ", t.format)
end
end
function clear_tex_depthstencil( t::Texture,
value::Depth24uStencil8u,
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
)
@bp_check(t.format == DepthStencilFormats.depth24u_stencil8,
"Trying to clear a texture with a hybrid 24u-depth/8-stencil value, on a texture of a different format: ", t.format)
texture_op_impl(
t,
GL_UNSIGNED_INT_24_8,
GL_DEPTH_STENCIL,
subset,
Ref(value),
recompute_mips,
Val(:Clear)
)
end
function clear_tex_depthstencil( t::Texture,
value::Depth32fStencil8u,
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
)
@bp_check(t.format == DepthStencilFormats.depth32f_stencil8,
"Trying to clear a texture with a hybrid 32f-depth/8-stencil value, on a texture of a different format: ", t.format)
texture_op_impl(
t,
GL_FLOAT_32_UNSIGNED_INT_24_8_REV,
GL_DEPTH_STENCIL,
subset,
Ref(value),
recompute_mips,
Val(:Clear)
)
end
"
Sets a texture's pixels, figuring out dynamically whether they're color, depth, etc.
For specific overloads based on texture format, see `set_tex_color()`, `set_tex_depth()`, etc respectively.
The dimensionality of the input array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function set_tex_pixels(t::Texture, args...; kw_args...)
if is_color(t.format)
set_tex_color(t, args...; kw_args...)
else
if is_depth_only(t.format)
set_tex_depth(t, args...; kw_args...)
elseif is_stencil_only(t.format)
set_tex_stencil(t, args...; kw_args...)
elseif is_depth_and_stencil(t.format)
set_tex_depthstencil(t, args...; kw_args...)
else
error("Unhandled case: ", t.format)
end
end
end
"
Sets the data for a color texture.
The dimensionality of the input array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function set_tex_color( t::Texture,
pixels::TBuf,
subset::TexSubset = default_tex_subset(t)
;
bgr_ordering::Bool = false,
single_component::E_PixelIOChannels = PixelIOChannels.red,
recompute_mips::Bool = true
) where {TBuf <: PixelBuffer}
T = get_component_type(TBuf)
N = get_component_count(TBuf)
@bp_check(!(t.format isa E_CompressedFormats),
"Can't set compressed texture data as if it's normal color data! ",
"(technically you can, but driver implementations for the compression are usually quite bad)")
@bp_check(is_color(t.format), "Can't set a non-color texture with a color")
@bp_check(!is_integer(t.format) || T<:Integer,
"Can't set an integer texture with a non-integer value")
@bp_check(!bgr_ordering || N >= 3,
"Supplied the 'bgr_ordering' parameter but the data only has 1 or 2 components")
texture_op_impl(
t,
GLenum(get_pixel_io_type(T)),
get_ogl_enum(get_pixel_io_channels(Val(N), bgr_ordering, single_component),
is_integer(t.format)),
subset,
Ref(pixels, 1),
recompute_mips,
Val(:Set), vsize(pixels)
)
end
"
Sets the data for a depth texture.
The dimensionality of the input array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function set_tex_depth( t::Texture,
pixels::PixelBuffer{T},
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
) where {T}
@bp_check(is_depth_only(t.format),
"Can't set depth values in a texture of format ", t.format)
texture_op_impl(
t,
GLenum(get_pixel_io_type(T)),
GL_DEPTH_COMPONENT,
subset,
Ref(pixels, 1),
recompute_mips,
Val(:Set),
vsize(pixels)
)
end
"
Sets the data for a stencil texture.
The dimensionality of the input array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function set_tex_stencil( t::Texture,
pixels::PixelBuffer{<:Union{UInt8, Vec{1, UInt8}}},
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
)
@bp_check(is_stencil_only(t.format),
"Can't set stencil values in a texture of format ", t.format)
texture_op_impl(
t,
GLenum(get_pixel_io_type(UInt8)),
GL_STENCIL_INDEX,
subset,
Ref(pixels, 1),
recompute_mips,
Val(:Set),
vsize(pixels)
)
end
"
Sets the data for a depth/stencil hybrid texture.
The dimensionality of the input array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function set_tex_depthstencil( t::Texture,
pixels::PixelBuffer{T},
subset::TexSubset = default_tex_subset(t)
;
recompute_mips::Bool = true
) where {T <: Union{Depth24uStencil8u, Depth32fStencil8u}}
local component_type::GLenum
if T == Depth24uStencil8u
@bp_check(t.format == DepthStencilFormats.depth24u_stencil8,
"Trying to give hybrid depth24u/stencil8 data to a texture of format ", t.format)
component_type = GL_UNSIGNED_INT_24_8
elseif T == Depth32fStencil8u
@bp_check(t.format == DepthStencilFormats.depth32f_stencil8,
"Trying to give hybrid depth32f/stencil8 data to a texture of format ", t.format)
component_type = GL_FLOAT_32_UNSIGNED_INT_24_8_REV
else
error("Unhandled case: ", T)
end
texture_op_impl(
t,
component_type,
GL_STENCIL_INDEX,
subset,
Ref(pixels, 1),
recompute_mips,
Val(:Set),
vsize(pixels)
)
end
"
Gets a texture's pixels, figuring out dynamically whether they're color, depth, etc.
For specific overloads based on texture format, see `get_tex_color()`, `get_tex_depth()`, etc, respectively.
The dimensionality of the array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function get_tex_pixels(t::Texture, args...; kw_args...)
if is_color(t.format)
get_tex_color(t, args...; kw_args...)
else
if is_depth_only(t.format)
get_tex_depth(t, args...; kw_args...)
elseif is_stencil_only(t.format)
get_tex_stencil(t, args...; kw_args...)
elseif is_depth_and_stencil(t.format)
get_tex_depthstencil(t, args...; kw_args...)
else
error("Unhandled case: ", t.format)
end
end
end
"
Gets the data for a color texture and writes them into the given array.
The dimensionality of the array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function get_tex_color( t::Texture,
out_pixels::TBuf,
subset::TexSubset = default_tex_subset(t)
;
bgr_ordering::Bool = false,
single_component::E_PixelIOChannels = PixelIOChannels.red
) where {TBuf <: PixelBuffer}
T = get_component_type(TBuf)
N = get_component_count(TBuf)
@bp_check(!(t.format isa E_CompressedFormats),
"Can't get compressed texture data as if it's normal color data!")
@bp_check(is_color(t.format),
"Can't get color data from a texture of format ", t.format)
@bp_check(!is_integer(t.format) || T<:Integer,
"Can't set an integer texture with a non-integer value")
@bp_check(!bgr_ordering || N >= 3,
"Supplied the 'bgr_ordering' parameter but the data only has 1 or 2 components")
texture_op_impl(
t,
GLenum(get_pixel_io_type(T)),
get_ogl_enum(get_pixel_io_channels(Val(N), bgr_ordering, single_component),
is_integer(t.format)),
subset,
Ref(out_pixels, 1),
false,
Val(:Get),
vsize(out_pixels),
;
get_buf_pixel_byte_size = N * sizeof(T)
)
end
"
Gets the data for a depth texture and writes them into the given array.
The dimensionality of the array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function get_tex_depth( t::Texture,
out_pixels::PixelBuffer{T},
subset::TexSubset = default_tex_subset(t)
) where {T <: Union{Number, Vec{1, <:Number}}}
@bp_check(is_depth_only(t.format), "Can't get depth data from a texture of format ", t.format)
texture_op_impl(
t,
GLenum(get_pixel_io_type(T)),
GL_DEPTH_COMPONENT,
subset,
Ref(out_pixels, 1),
false,
Val(:Get),
vsize(out_pixels),
;
get_buf_pixel_byte_size = sizeof(T)
)
end
"
Gets the data for a stencil texture and writes them into the given array.
The dimensionality of the array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function get_tex_stencil( t::Texture,
out_pixels::PixelBuffer{<:Union{UInt8, Vec{1, UInt8}}},
subset::TexSubset = default_tex_subset(t)
)
@bp_check(is_stencil_only(t.format), "Can't get stencil data from a texture of format ", t.format)
texture_op_impl(
t,
GLenum(get_pixel_io_type(UInt8)),
GL_STENCIL_INDEX,
subset,
Ref(out_pixels, 1),
false,
Val(:Get),
vsize(out_pixels),
;
get_buf_pixel_byte_size = sizeof(UInt8)
)
end
"
Gets the data for a depth-stencil hybrid texture and writes them into the given array.
The dimensionality of the array and `subset` parameter
must match the dimensionality of the texture.
Cubemaps textures are 3D, where Z spans the 6 faces.
"
function get_tex_depthstencil( t::Texture,
out_pixels::PixelBuffer{T},
subset::TexSubset = default_tex_subset(t)
) where {T <: Union{Depth24uStencil8u, Depth32fStencil8u}}
local component_type::GLenum
if T == Depth24uStencil8u
@bp_check(t.format == DepthStencilFormats.depth24u_stencil8,
"Trying to get hybrid depth24u/stencil8 data from a texture of format ", t.format)
component_type = GL_UNSIGNED_INT_24_8
elseif T == Depth32fStencil8u
@bp_check(t.format == DepthStencilFormats.depth32f_stencil8,
"Trying to get hybrid depth32f/stencil8 data from a texture of format ", t.format)
component_type = GL_FLOAT_32_UNSIGNED_INT_24_8_REV
else
error("Unhandled case: ", T)
end
texture_op_impl(
t,
component_type,
GL_DEPTH_STENCIL,
subset, Ref(out_pixels, 1),
false,
Val(:Get),
vsize(out_pixels)
;
get_buf_pixel_byte_size = sizeof(T)
)
end
#TODO: Texture getters can also return an array rather than writing into an existing one.
"
Copies between two textures.
The operation is comparable to `memcpy()`, in that the bit data is directly transferred over
without casting or normalizing.
The only format requirement is that the bit size of a pixel is the same for each texture.
When copying between a compressed and uncompressed texture, the requirement is slightly different:
the bit size of a *block* of the compressed texture must match
the bit size of a *pixel* from the uncompressed texture.
For simplicity, the `dest_min` parameter can have more dimensions than the texture itself;
extra dimensions are ignored.
As with other texture operations, cubemaps are treated as 3D with 6 Z-slices.
"
function copy_tex_pixels(src::Texture, dest::Texture,
src_subset::TexSubset = default_tex_subset(src),
dest_min::VecU = one(v3u),
dest_mip::Int = 1
)::Nothing
@bp_check(get_pixel_bit_size(src.format) == get_pixel_bit_size(dest.format),
"Trying to copy a texture with ", get_pixel_bit_size(src.format), "-bit pixels ",
"to a texture with ", get_pixel_bit_size(dest.format), "-bit pixels. ",
"The bit sizes must match!")
(src_range, src_mip) = process_tex_subset(src, src_subset)
(dest_range, dest_mip) = process_tex_subset(dest, TexSubset(
Box(
min=dest_min,
size=size(src_range)
),
dest_mip
))
#TODO: For compressed<=>uncompressed copies, the compressed texture should have its pixel range multiplied by the block size.
glCopyImageSubData(
get_ogl_handle(src), GLenum(src.type),
src_mip - 1,
(min_inclusive(src_range) - 1)...,
get_ogl_handle(dest), GLenum(dest.type),
dest_mip - 1,
(min_inclusive(dest_range) - 1)...,
size(src_range)...
)
end
export get_view, tex_size,
set_tex_swizzling, set_tex_depthstencil_source,
get_mip_byte_size, get_gpu_byte_size,
clear_tex_pixels, clear_tex_color, clear_tex_depth, clear_tex_stencil, clear_tex_depthstencil,
set_tex_pixels, set_tex_color, set_tex_depth, set_tex_stencil,
get_tex_pixels, get_tex_color, get_tex_depth, get_tex_stencil, get_tex_depthstencil,
copy_tex_pixels | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 5053 | "Raised in debug builds if a View is used in a Program without being activated."
struct InactiveViewsException <: Exception
program::Ptr_Program
offenders::Vector{Pair{Ptr_Uniform, View}}
end
function Base.showerror(io::IO, e::InactiveViewsException)
print(io,
"Shader Program ", Int(gl_type(e.program)),
" is about to be used, but it has ", length(e.offenders),
" texture uniforms with an inactive View, which is Undefined Behavior! ["
)
for offender in e.offenders
print(io, "\n\t\"", offender[1], "\" (view ", offender[2].handle, ")")
end
print(io, "\n]")
end
view_debugger_service_enabled() = @bp_gl_debug() || get_context().debug_mode
"""
Provides a Context service in debug builds which checks that a program's Views
are properly activated before use.
Note that this can't catch them in all circumstances!
View handles are just a plain uint64, so you can sneak them into a shader
in all sorts of ways.
In particular, reading the handle from mesh data
isn't something this service can notice.
"""
@bp_service ViewDebugging(force_unique, lazy) begin
view_lookup::Dict{Ptr_View, View}
uniform_lookup::Dict{Ptr_Program, Dict{Ptr_Uniform, Ptr_View}}
INIT() = new(
Dict{Ptr_View, View}(),
Dict{Ptr_Program, Dict{Ptr_Uniform, Ptr_View}}()
)
SHUTDOWN(service, is_context) = nothing
"Registers a new view instance"
function service_ViewDebugging_add_view(service, ptr::Ptr_View, instance::View)
if view_debugger_service_enabled()
@bp_gl_assert(!haskey(service.view_lookup, ptr),
"Pointer already exists for view: ", ptr)
service.view_lookup[ptr] = instance
end
end
"Registers a new shader program"
function service_ViewDebugging_add_program(service, ptr::Ptr_Program)
if view_debugger_service_enabled()
@bp_gl_assert(!haskey(service.uniform_lookup, ptr),
"Pointer already exists for program: ", ptr)
service.uniform_lookup[ptr] = Dict{Ptr_Uniform, Ptr_View}()
end
end
"Un-registers a shader program from this service"
function service_ViewDebugging_remove_program(service, program::Ptr_Program)
if view_debugger_service_enabled()
@bp_gl_assert(haskey(service.uniform_lookup, program),
"Program ", program, " is missing from the View Debugger service")
delete!(service.uniform_lookup, program)
end
end
"Un-registers a View from this service"
function service_ViewDebugging_remove_view(service, view::Ptr_View)
if view_debugger_service_enabled()
@bp_gl_assert(haskey(service.view_lookup, view),
"View ", view, " is missing from the View Debugger service")
delete!(service.view_lookup, view)
end
end
"Registers a new texture view for a given program's uniform."
function service_ViewDebugging_set_view(service,
program::Ptr_Program,
u_ptr::Ptr_Uniform, u_value::Ptr_View)
if view_debugger_service_enabled()
if !haskey(service.uniform_lookup, program)
service.uniform_lookup[program] = Dict{Ptr_Uniform, View}()
end
service.uniform_lookup[program][u_ptr] = u_value
end
end
"Registers a set of texture views for a given program's uniform array."
function service_ViewDebugging_set_views(service,
program::Ptr_Program,
u_start_ptr::Ptr_Uniform,
u_values::Vector{<:Union{Ptr_View, gl_type(Ptr_View)}})
if view_debugger_service_enabled()
if !haskey(service.uniform_lookup, program)
service.uniform_lookup[program] = Dict{Ptr_Uniform, View}()
end
for i::Int in 1:length(u_values)
service.uniform_lookup[program][u_start_ptr + i - 1] = u_values[i]
end
end
end
"Checks a program to make sure its Views are all activated."
function service_ViewDebugging_check(service, program::Ptr_Program)
if view_debugger_service_enabled()
@bp_gl_assert(haskey(service.uniform_lookup, program),
"Program ", program, " is missing from the View Debugger service")
# Gather the inactive views used by the program,
# and raise an error if any exist.
views = (
(u_ptr => service.view_lookup[v_ptr])
for (u_ptr, v_ptr) in service.uniform_lookup[program]
if !service.view_lookup[v_ptr].is_active
)
if !isempty(views)
throw(InactiveViewsException(program, collect(views)))
end
end
end
end
# Not exported, because it's an internal debugging service. | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 8812 | "
Some kind of view into a texture's data, which can be passed into a shader
as a simple 64-bit integer handle, or one of the opaque sampler types.
Assumes the OpenGL extension `ARB_bindless_texture`.
This is much easier to manage than the old-school texture units and binding.
You can even pass an array of unrelated textures, as an array of uint64 (or uvec2)!
You should never create these yourself; they're generated by their owning Texture.
IMPORTANT: you must `view_activate()` an instance before it's used in a shader,
and it should be `view_deactivate()`-d when not in use
to free up GPU resources for other render passes.
Using an inactive handle leads to Undefined Behavior (a.k.a. wacky crashes).
The lifetime of this resource is managed by its owning Texture,
which is why this type does not inherit from `AbstractResource`.
"
mutable struct View
handle::Ptr_View
owner::AbstractResource # Can't type it as `Texture`, because that type doesn't exist yet
is_active::Bool
is_sampling::Bool # True if this is a 'Texture' view,
# false if this is an 'Image' view.
end
"
Tells the GPU to activate this handle so it can be used in a shader.
Simple Views are activated with an access type (read, write, read_write).
"
function view_activate(view::View, simple_access::E_ImageAccessModes = ImageAccessModes.read_write)
# It's not clear at all in the standard what happens if you make an ImageView resident
# more than once, with different access modes.
# So I just forbid duplicate activations altogether.
@bp_check(!view.is_active, "Can't activate a view twice!")
@bp_check(get_ogl_handle(view.owner) != Ptr_Texture(),
"This view's owning texture has been destroyed")
if !view.is_active
view.is_active = true
if view.is_sampling
glMakeTextureHandleResidentARB(view.handle)
else
glMakeImageHandleResidentARB(view.handle, simple_access)
end
end
end
"Tells the GPU to deactivate this handle, potentially freeing up resources for other data to be loaded."
function view_deactivate(view::View)
# Ideally we should check that the owning texture hasn't been destroyed, as with `view_activate()`,
# but in practice it's not as important and I feel that
# it will lead to a lot of initialization-order pain.
if view.is_active
view.is_active = false
if view.is_sampling
glMakeTextureHandleNonResidentARB(view.handle)
else
glMakeImageHandleNonResidentARB(view.handle)
end
end
end
get_ogl_handle(view::View) = view.handle
# Unfortunately, OpenGL allows implementations to re-use the handles of destroyed views;
# otherwise, I'd use that for hashing/equality.
export View, view_activate, view_deactivate
##################
## Parameters ##
##################
"
The parameters defining a 'simple' View.
Note that mip levels start at 1, not 0, to reflect Julia's 1-based indexing convention.
The 'layer' field allows you to pick a single layer of a 3D or cubemap texture,
causing the view to act like a 2D texture.
The 'apparent_format' field changes how the texture is interpreted in the shader;
it defaults to the texture's actual format.
"
Base.@kwdef struct SimpleViewParams
mip_level::Int = 1
layer::Optional{Int} = nothing
apparent_format::Optional{TexFormat} = nothing
end
"
Maps every possible format for a simple texture view to its type-name in the shader.
Comes from this reference: https://registry.khronos.org/OpenGL-Refpages/gl4/html/glBindImageTexture.xhtml#Description
"
const LEGAL_APPARENT_SIMPLEVIEW_FORMATS = Dict{Union{SimpleFormat, E_SpecialFormats}, String}(
# Float/uint/int textures can be rgba/rg/r and 8/16/32 bits.
# With the exception of 8-bit floats.
begin
formats = [ FormatTypes.float => "f",
FormatTypes.uint => "ui",
FormatTypes.int => "i" ]
components = [ SimpleFormatComponents.RGBA => "rgba",
SimpleFormatComponents.RG => "rg",
SimpleFormatComponents.R => "r" ]
bit_depths = [ SimpleFormatBitDepths.B32 => "32",
SimpleFormatBitDepths.B16 => "16",
SimpleFormatBitDepths.B8 => "8" ]
everything = Iterators.product(formats, components, bit_depths)
filtered = Iterators.filter(everything) do ((format, format_str),
(component, comp_str),
(bit_depth, bit_str), )
(format != FormatTypes.float) || (bit_depths != SimpleFormatBitDepths.B8)
end
constructed = Iterators.map(filtered) do ((format, format_str),
(component, comp_str),
(bit_depth, bit_str), )
SimpleFormat(format, component, bit_depth) => string(comp_str, bit_str, format_str)
end
constructed
end...,
# Normalized uint/int textures can be rgba/rg/r and 8/16 bits.
begin
formats = [ FormatTypes.normalized_uint => "",
FormatTypes.normalized_int => "_snorm" ]
components = [ SimpleFormatComponents.RGBA => "rgba",
SimpleFormatComponents.RG => "rg",
SimpleFormatComponents.R => "r" ]
bit_depths = [ SimpleFormatBitDepths.B16 => "16",
SimpleFormatBitDepths.B8 => "8" ]
everything = Iterators.product(formats, components, bit_depths)
constructed = Iterators.map(everything) do ((format, format_str),
(component, comp_str),
(bit_depth, bit_str), )
SimpleFormat(format, component, bit_depth) => string(comp_str, bit_str, format_str)
end
constructed
end...,
# A few special formats are supported.
SpecialFormats.rgb_tiny_ufloats => "r11f_g11f_b10f",
SpecialFormats.rgb10_a2_uint => "rgb10_a2ui",
SpecialFormats.rgb10_a2 => "rgb10_a2",
)
"
Gets whether a texture of format `src` can appear in a shader
as a 'simple view' texture of format `dest`
"
function is_format_compatible_in_tex_simpleview(src::TexFormat, dest::TexFormat)
return haskey(LEGAL_APPARENT_SIMPLEVIEW_FORMATS, dest) &&
get_pixel_bit_size(src) == get_pixel_bit_size(dest)
end
"The parameters that uniquely define a texture's view."
const ViewParams = Union{Optional{TexSampler}, SimpleViewParams}
export SimpleViewParams, ViewParams,
LEGAL_APPARENT_SIMPLEVIEW_FORMATS, is_format_compatible_in_tex_simpleview
#####################
## Constructors ##
#####################
"
Creates a new sampled view from the given texture and optional sampler.
If no sampler is given, the texture's default sampler settings are used.
IMPORTANT: users shouldn't ever be creating these by hand;
they should come from the Texture interfae.
"
function View(owner::AbstractResource, sampler::Optional{TexSampler})
local handle::gl_type(Ptr_View)
if exists(sampler)
handle = glGetTextureSamplerHandleARB(get_ogl_handle(owner), get_sampler(sampler))
else
handle = glGetTextureHandleARB(get_ogl_handle(owner))
end
# Create the instance, and register it with the View-Debugger.
instance = View(Ptr_View(handle), owner,
glIsTextureHandleResidentARB(handle),
true)
service_ViewDebugging_add_view(instance.handle, instance)
return instance
end
"
Creates a new simple view on a texture.
IMPORTANT: users shouldn't ever be creating these by hand;
they should come from the Texture interface.
"
function View(owner::AbstractResource, owner_format::TexFormat, params::SimpleViewParams)
apparent_format = isnothing(params.apparent_format) ? owner_format : params.apparent_format
@bp_check(is_format_compatible_in_tex_simpleview(owner_format, apparent_format),
"Simple View with format ", apparent_format, " is not legal ",
"with a texture of true format ", owner_format)
handle::gl_type(Ptr_View) = glGetImageHandleARB(
get_ogl_handle(owner),
params.mip_level - 1,
exists(params.layer) ? GL_FALSE : GL_TRUE,
isnothing(params.layer) ? 0 : params.layer-1,
get_ogl_enum(apparent_format)
)
# Create the instance, and register it with the View-Debugger.
instance = View(Ptr_View(handle), owner,
glIsImageHandleResidentARB(handle),
false)
service_ViewDebugging_add_view(instance.handle, instance)
return instance
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 557 | "Implementation of a Dear IMGUI renderer/controller within B+, plus various helpers."
module GUI
# External dependencies
using Dates, Setfield
using CImGui, LibCImGui, GLFW, CSyntax, StructTypes
# B+ dependencies
using BplusCore; @using_bplus_core
using ..GL
# Needed for 'clipboard()' :(
using InteractiveUtils
# Define @bp_gui_assert and related stuff.
@make_toggleable_asserts bp_gui_
@decentralized_module_init
include("aliases.jl")
include("gui_service.jl")
include("simple_helpers.jl")
include("text.jl")
include("file_dialog.jl")
end # module | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 554 | const gVec2 = CImGui.LibCImGui.ImVec2
const gVec4 = CImGui.LibCImGui.ImVec4
const gColor = CImGui.LibCImGui.ImColor
Base.convert(::Type{gVec2}, v::Vec2) = gVec2(v.data...)
Base.convert(::Type{gVec4}, v::Vec4) = gVec4(v.data...)
Base.convert(::Type{gColor}, v::Vec4) = gColor(v.data...)
Base.convert(::Type{Vec{2, F}}, v::gVec2) where {F} = Vec{2, F}(v.x, v.y)
Base.convert(::Type{Vec{4, F}}, v::gVec4) where {F} = Vec{4, F}(v.x, v.y, v.z, v.w)
Base.convert(::Type{Vec{4, F}}, v::gColor) where {F} = Vec{4, F}(v.Value.x, v.Value.y, v.Value.z, v.Value.w) | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 5053 | #=
UI layout:
------------------------------------------------------------------------------
| [[Path tab]] [Favorites tab] [Search tab] [x] Show Un- |
| |---------------------------------------------------| selectable |
| | Path: [ C:\Users\manni\Documents\ ] | |
| |---------------------------------------------------| [Refresh] |
| |
| | Name ^ | Last Modified | Type | Size | Selectable |
| |
| MyDir/ 10/11/1992 10:00am DIR 43 MB... |
| MyTinyDir/ 10/11/1992 10:00am DIR 1 MB |
| a.txt 10/11/1992 9:00am .txt 43 MB |
| b.txt 10/12/1992 9:00am .txt 42 MB |
| |
| |
| New name: [ a.txt ] [Open] [Cancel] |
------------------------------------------------------------------------------
=#
@bp_enum(FileDialogColumns,
name, last_modified, type, size, selectable
)
@bp_enum(FileDialogTabs,
path, favorites, search
)
"A file or folder in the file dialog GUI"
struct Entry
name::AbstractString
last_modified::Float64
type::AbstractString
size::Int
selectable::Bool
is_folder::Bool
end
"Persistent user settings for file dialogs. Serializable with JSON3/StructTypes."
Base.@kwdef mutable struct FileDialogSettings
directory::AbstractString
file_name::AbstractString
sort_column::E_FileDialogColumns = FileDialogColumns.name
sort_is_descending::Bool = true
show_unselectable_options::Bool = false
end
StructTypes.StructType(::Type{FileDialogSettings}) = StructTypes.Mutable()
"Configuration for a specific file dialog instance."
Base.@kwdef struct FileDialogParams
is_writing::Bool
is_folder_mode::Bool = false
confirm_button_label::Optional{AbstractString} = "OK"
cancel_button_label::Optional{AbstractString} = "Cancel"
allowed_tabs::Set{E_FileDialogTabs} = Set(FileDialogTabs.instances())
reading_pattern::Optional{Regex} = nothing
end
"The current state of a specific file dialog instance."
Base.@kwdef mutable struct FileDialogState
current_tab::Optional{E_FileDialogTabs} = nothing
entries::Vector{Entry} = [ ]
end
@bp_enum(FileDialogResult,
confirmed, canceled
)
function gui_file_dialog(settings::FileDialogSettings,
params::FileDialogParams,
state::FileDialogState
)::Optional{E_FileDialogResult}
gui_within_group() do # The tabs
#TODO: Implement tabs
end
CImGui.SameLine()
gui_within_group() do # Side buttons
@c CImGui.Checkbox("Show unselectable", &settings.show_unselectable_options)
if CImGui.Button("Refresh")
state.entries = map(readdir(settings.directory, sort=false)) do name::AbstractString
info = stat(name)
is_folder = isfile(joinpath(settings.directory, name))
return Entry(
name,
info.mtime,
is_folder ? "DIR" : string(name[findlast('.', name):end]),
info.size,
isnothing(params.reading_pattern) ||
exists(matches(params.reading_pattern, name)),
is_folder
)
end
end
end
CImGui.Dummy(gVec2(0, 40))
#TODO: File scroll
CImGui.Dummy(gVec2(0, 20))
#TODO: File name, Confirm, Cancel
end
#TODO: Helper to try loading FileDialogSettings from disk
export FileDialogColumns, E_FileDialogColumns, FileDialogSettings,
FileDialogParams,
FileDialogTabs, E_FileDialogTabs, FileDialogState,
FileDialogResult, gui_file_dialog
## Helper functions ##
function sort_files(file_names::Vector{AbstractString}, sort_column::E_FileDialogColumns, descending::Bool)
sort!(
file_names, rev=descending,
by = if sort_column == FileDialogColumns.name
data -> (data.is_folder, data.name)
elseif sort_column == FileDialogColumns.last_modified
data -> (data.is_folder, data.last_modified)
elseif sort_column == FileDialogColumns.type
data -> (data.is_folder, data.type)
elseif sort_column == FileDialogColumns.size
data -> (data.is_folder, data.size)
elseif sort_column == FileDialogColumns.selectable
data -> (data.is_folder, data.selectable)
else
error("Unhandled column: ", sort_column)
end
)
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 34452 | #############################
## Implementation data ##
#############################
const IMGUI_KEY_TO_GLFW = Dict(
#TODO: Why do so many keys seem to be missing?
CImGui.ImGuiKey_Tab => GLFW.KEY_TAB,
CImGui.ImGuiKey_LeftArrow => GLFW.KEY_LEFT,
CImGui.ImGuiKey_RightArrow => GLFW.KEY_RIGHT,
CImGui.ImGuiKey_UpArrow => GLFW.KEY_UP,
CImGui.ImGuiKey_DownArrow => GLFW.KEY_DOWN,
CImGui.ImGuiKey_PageUp => GLFW.KEY_PAGE_UP,
CImGui.ImGuiKey_PageDown => GLFW.KEY_PAGE_DOWN,
CImGui.ImGuiKey_Home => GLFW.KEY_HOME,
CImGui.ImGuiKey_End => GLFW.KEY_END,
CImGui.ImGuiKey_Insert => GLFW.KEY_INSERT,
CImGui.ImGuiKey_Delete => GLFW.KEY_DELETE,
CImGui.ImGuiKey_Backspace => GLFW.KEY_BACKSPACE,
CImGui.ImGuiKey_Space => GLFW.KEY_SPACE,
CImGui.ImGuiKey_Enter => GLFW.KEY_ENTER,
CImGui.ImGuiKey_Escape => GLFW.KEY_ESCAPE,
# CImGui.ImGuiKey_Apostrophe => GLFW.KEY_APOSTROPHE,
# CImGui.ImGuiKey_Comma => GLFW.KEY_COMMA,
# CImGui.ImGuiKey_Minus => GLFW.KEY_MINUS,
# CImGui.ImGuiKey_Period => GLFW.KEY_PERIOD,
# CImGui.ImGuiKey_Slash => GLFW.KEY_SLASH,
# CImGui.ImGuiKey_Semicolon => GLFW.KEY_SEMICOLON,
# CImGui.ImGuiKey_Equal => GLFW.KEY_EQUAL,
# CImGui.ImGuiKey_LeftBracket => GLFW.KEY_LEFT_BRACKET,
# CImGui.ImGuiKey_Backslash => GLFW.KEY_BACKSLASH,
# CImGui.ImGuiKey_RightBracket => GLFW.KEY_RIGHT_BRACKET,
# CImGui.ImGuiKey_GraveAccent => GLFW.KEY_GRAVE_ACCENT,
# CImGui.ImGuiKey_CapsLock => GLFW.KEY_CAPS_LOCK,
# CImGui.ImGuiKey_ScrollLock => GLFW.KEY_SCROLL_LOCK,
# CImGui.ImGuiKey_NumLock => GLFW.KEY_NUM_LOCK,
# CImGui.ImGuiKey_PrintScreen => GLFW.KEY_PRINT_SCREEN,
# CImGui.ImGuiKey_Pause => GLFW.KEY_PAUSE,
# CImGui.ImGuiKey_Keypad0 => GLFW.KEY_KP_0,
# CImGui.ImGuiKey_Keypad1 => GLFW.KEY_KP_1,
# CImGui.ImGuiKey_Keypad2 => GLFW.KEY_KP_2,
# CImGui.ImGuiKey_Keypad3 => GLFW.KEY_KP_3,
# CImGui.ImGuiKey_Keypad4 => GLFW.KEY_KP_4,
# CImGui.ImGuiKey_Keypad5 => GLFW.KEY_KP_5,
# CImGui.ImGuiKey_Keypad6 => GLFW.KEY_KP_6,
# CImGui.ImGuiKey_Keypad7 => GLFW.KEY_KP_7,
# CImGui.ImGuiKey_Keypad8 => GLFW.KEY_KP_8,
# CImGui.ImGuiKey_Keypad9 => GLFW.KEY_KP_9,
# CImGui.ImGuiKey_KeypadDecimal => GLFW.KEY_KP_DECIMAL,
# CImGui.ImGuiKey_KeypadDivide => GLFW.KEY_KP_DIVIDE,
# CImGui.ImGuiKey_KeypadMultiply => GLFW.KEY_KP_MULTIPLY,
# CImGui.ImGuiKey_KeypadSubtract => GLFW.KEY_KP_SUBTRACT,
# CImGui.ImGuiKey_KeypadAdd => GLFW.KEY_KP_ADD,
CImGui.ImGuiKey_KeyPadEnter => GLFW.KEY_KP_ENTER,
# CImGui.ImGuiKey_KeypadEqual => GLFW.KEY_KP_EQUAL,
# CImGui.ImGuiKey_LeftShift => GLFW.KEY_LEFT_SHIFT,
# CImGui.ImGuiKey_LeftCtrl => GLFW.KEY_LEFT_CONTROL,
# CImGui.ImGuiKey_LeftAlt => GLFW.KEY_LEFT_ALT,
# CImGui.ImGuiKey_LeftSuper => GLFW.KEY_LEFT_SUPER,
# CImGui.ImGuiKey_RightShift => GLFW.KEY_RIGHT_SHIFT,
# CImGui.ImGuiKey_RightCtrl => GLFW.KEY_RIGHT_CONTROL,
# CImGui.ImGuiKey_RightAlt => GLFW.KEY_RIGHT_ALT,
# CImGui.ImGuiKey_RightSuper => GLFW.KEY_RIGHT_SUPER,
# CImGui.ImGuiKey_Menu => GLFW.KEY_MENU,
# CImGui.ImGuiKey_0 => GLFW.KEY_0,
# CImGui.ImGuiKey_1 => GLFW.KEY_1,
# CImGui.ImGuiKey_2 => GLFW.KEY_2,
# CImGui.ImGuiKey_3 => GLFW.KEY_3,
# CImGui.ImGuiKey_4 => GLFW.KEY_4,
# CImGui.ImGuiKey_5 => GLFW.KEY_5,
# CImGui.ImGuiKey_6 => GLFW.KEY_6,
# CImGui.ImGuiKey_7 => GLFW.KEY_7,
# CImGui.ImGuiKey_8 => GLFW.KEY_8,
# CImGui.ImGuiKey_9 => GLFW.KEY_9,
CImGui.ImGuiKey_A => GLFW.KEY_A,
# CImGui.ImGuiKey_B => GLFW.KEY_B,
CImGui.ImGuiKey_C => GLFW.KEY_C,
# CImGui.ImGuiKey_D => GLFW.KEY_D,
# CImGui.ImGuiKey_E => GLFW.KEY_E,
# CImGui.ImGuiKey_F => GLFW.KEY_F,
# CImGui.ImGuiKey_G => GLFW.KEY_G,
# CImGui.ImGuiKey_H => GLFW.KEY_H,
# CImGui.ImGuiKey_I => GLFW.KEY_I,
# CImGui.ImGuiKey_J => GLFW.KEY_J,
# CImGui.ImGuiKey_K => GLFW.KEY_K,
# CImGui.ImGuiKey_L => GLFW.KEY_L,
# CImGui.ImGuiKey_M => GLFW.KEY_M,
# CImGui.ImGuiKey_N => GLFW.KEY_N,
# CImGui.ImGuiKey_O => GLFW.KEY_O,
# CImGui.ImGuiKey_P => GLFW.KEY_P,
# CImGui.ImGuiKey_Q => GLFW.KEY_Q,
# CImGui.ImGuiKey_R => GLFW.KEY_R,
# CImGui.ImGuiKey_S => GLFW.KEY_S,
# CImGui.ImGuiKey_T => GLFW.KEY_T,
# CImGui.ImGuiKey_U => GLFW.KEY_U,
CImGui.ImGuiKey_V => GLFW.KEY_V,
# CImGui.ImGuiKey_W => GLFW.KEY_W,
CImGui.ImGuiKey_X => GLFW.KEY_X,
CImGui.ImGuiKey_Y => GLFW.KEY_Y,
CImGui.ImGuiKey_Z => GLFW.KEY_Z,
# CImGui.ImGuiKey_F1 => GLFW.KEY_F1,
# CImGui.ImGuiKey_F2 => GLFW.KEY_F2,
# CImGui.ImGuiKey_F3 => GLFW.KEY_F3,
# CImGui.ImGuiKey_F4 => GLFW.KEY_F4,
# CImGui.ImGuiKey_F5 => GLFW.KEY_F5,
# CImGui.ImGuiKey_F6 => GLFW.KEY_F6,
# CImGui.ImGuiKey_F7 => GLFW.KEY_F7,
# CImGui.ImGuiKey_F8 => GLFW.KEY_F8,
# CImGui.ImGuiKey_F9 => GLFW.KEY_F9,
# CImGui.ImGuiKey_F10 => GLFW.KEY_F10,
# CImGui.ImGuiKey_F11 => GLFW.KEY_F11,
# CImGui.ImGuiKey_F12 => GLFW.KEY_F12
)
#TODO: Is it more performant to keep the CImGui mesh data on the CPU?
const KEEP_MESH_DATA_ON_CPU = false
gui_generate_mesh(verts::Buffer, indices::Buffer) = Mesh(
PrimitiveTypes.triangle,
[ VertexDataSource(verts, sizeof(CImGui.ImDrawVert)) ],
# The vertex data is interleaved, and equivalent to the struct CImGui.ImDrawVert.
[
VertexAttribute(1, fieldoffset(CImGui.ImDrawVert, 1), VSInput(v2f)),
VertexAttribute(1, fieldoffset(CImGui.ImDrawVert, 2), VSInput(v2f)),
VertexAttribute(1, fieldoffset(CImGui.ImDrawVert, 3), VSInput_FVector(Vec4{UInt8}, true))
],
MeshIndexData(indices, CImGui.ImDrawIdx)
)
const FAIL_CLIPBOARD_DATA = ""
function gui_clipboard_get(::Ptr{Cvoid})::Ptr{UInt8}
# Throwing within a C callback is UB.
try
gui_service = service_GUI()
clip = clipboard()
if !isa(clip, String)
clip = String(clip)
end
#NOTE: if getting nondeterministic crashes, then maybe the GC is moving these Strings around.
push!(gui_service.clipboard_buffer, clip)
#NOTE: another potential source of crashes is that this array doesn't have a long-enough memory.
if length(gui_service.clipboard_buffer) > 5
deleteat!(gui_service.clipboard_buffer, 1)
end
return Base.unsafe_convert(Cstring, gui_service.clipboard_buffer[end])
catch e
try
print(stderr, "Failed to read clipboard: ")
showerror(stderr, e, catch_backtrace())
return Base.unsafe_convert(Cstring, FAIL_CLIPBOARD_DATA)
catch
exit(666)
end
end
end
function gui_clipboard_set(::Ptr{Cvoid}, chars::Cstring)::Cvoid
# Throwing within a C callback is UB.
try
str = unsafe_string(chars)
clipboard(str)
return nothing
catch e
try
print(stderr, "Failed to set clipboard: ")
showerror(stderr, e, catch_backtrace())
return ""
catch
exit(667)
end
end
end
# Make C function pointers for ImGUI.
# Being raw pointers, they must be created at runtime.
const GUI_CLIPBOARD_GET = Ref{Ptr{Cvoid}}()
const GUI_CLIPBOARD_SET = Ref{Ptr{Cvoid}}()
push!(RUN_ON_INIT, () -> begin
#NOTE: Apparently @cfunction doesn't work on 32-bit Windows with the 'stdcall' convention.
# Shouldn't ever affect us, because no 32-bit Windows platform could run OpenGL 4.6+
GUI_CLIPBOARD_SET[] = @cfunction(gui_clipboard_set, Cvoid, (Ptr{Cvoid}, Cstring))
GUI_CLIPBOARD_GET[] = @cfunction(gui_clipboard_get, Ptr{UInt8}, (Ptr{Cvoid}, ))
end)
const IM_GUI_CONTEXT_REF = Ref{Ptr{CImGui.ImGuiContext}}(C_NULL)
const IM_GUI_CONTEXT_COUNTER = Ref(0)
const IM_GUI_CONTEXT_LOCKER = ReentrantLock()
const IM_GUI_BACKEND_NAME_RENDERER = "B+ GL"
const IM_GUI_BACKEND_NAME_PLATFORM = "B+ and GLFW"
const TEX_ID_FONT = CImGui.ImTextureID(1)
function make_gui_font_texture_atlas()::Texture
gui_fonts = unsafe_load(CImGui.GetIO().Fonts)
CImGui.Build(gui_fonts) #TODO: Remove this, shouldn't be necessary
font_pixels = Ptr{Cuchar}(C_NULL)
font_size_x = Cint(-1)
font_size_y = Cint(-1)
@c CImGui.GetTexDataAsRGBA32(gui_fonts, &font_pixels, &font_size_x, &font_size_y)
# After rebuilding the font texture, the font texture ID is nulled out by Dear ImGUI.
# So we have to tell it again.
CImGui.SetTexID(unsafe_load(CImGui.GetIO().Fonts), TEX_ID_FONT)
font_pixels_casted = Ptr{vRGBAu8}(font_pixels)
font_pixels_managed = unsafe_wrap(Matrix{vRGBAu8}, font_pixels_casted,
(font_size_x, font_size_y))
return Texture(
SimpleFormat(FormatTypes.normalized_uint,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B8),
font_pixels_managed,
sampler = TexSampler{2}(
wrapping = WrapModes.clamp
)
)
end
# Getting and setting values within an NTuple, through raw pointers.
# Taken from ImGuiGLFWBackend.jl.
function c_get(x::Ptr{NTuple{N,T}}, i) where {N,T}
unsafe_load(Ptr{T}(x), Integer(i)+1)
end
function c_set!(x::Ptr{NTuple{N,T}}, i, v) where {N,T}
unsafe_store!(Ptr{T}(x), T(v), Integer(i)+1)
end
###################
## Interface ##
###################
"
A CImGui (Dear IMGUI) backend, implemented as a B+ GL Service.
To use a `GL.Texture` or `GL.View` in CImGui, wrap it with `gui_tex_handle()`.
"
@bp_service GUI(force_unique) begin
window::GLFW.Window
last_time_ns::UInt64
# Rendering assets.
render_program::Program
font_texture::Texture
buffer_vertices::Buffer
buffer_indices::Buffer
buffer::Mesh
# Buffers for C calls.
clipboard_buffer::Vector{String}
# User textures, indexed by a unique handle.
# Needed to use bindless textures with CImGui.
user_textures_by_handle::Dict{CImGui.ImTextureID,
Union{GL.Texture, GL.View}}
user_texture_handles::Dict{Union{GL.Texture, GL.View},
CImGui.ImTextureID}
# This service periodically prunes destroyed textures from the above lookups.
max_tex_handle::CImGui.ImTextureID
next_tex_handle_to_prune::CImGui.ImTextureID
# Mouse button events.
mouse_buttons_just_pressed::Vector{Bool}
# Mouse cursor images.
mouse_cursors::Vector{GLFW.Cursor}
# Stored GLFW callback closures.
callback_closures_char::Base.Callable
callback_closures_key::Base.Callable
callback_closures_mouse_button::Base.Callable
callback_closures_scroll::Base.Callable
function INIT(; initial_vertex_capacity::Int = 1024,
initial_index_capacity::Int = (initial_vertex_capacity * 2) ÷ 3)
context = get_context()
# Create/get the CImGui context.
#TODO: Throw error if another thread already made the context
@lock IM_GUI_CONTEXT_LOCKER begin
if IM_GUI_CONTEXT_COUNTER[] < 1
IM_GUI_CONTEXT_REF[] = CImGui.CreateContext()
end
IM_GUI_CONTEXT_COUNTER[] += 1
end
@bp_check(IM_GUI_CONTEXT_REF[] != C_NULL)
gui_io::Ptr{CImGui.ImGuiIO} = CImGui.GetIO()
gui_fonts = unsafe_load(gui_io.Fonts)
CImGui.AddFontDefault(gui_fonts)
# Report capabilities to CImGUI.
gui_io.BackendPlatformName = pointer(IM_GUI_BACKEND_NAME_PLATFORM)
gui_io.BackendRendererName = pointer(IM_GUI_BACKEND_NAME_RENDERER)
gui_io.BackendFlags = |(
unsafe_load(gui_io.BackendFlags),
CImGui.ImGuiBackendFlags_HasMouseCursors,
CImGui.ImGuiBackendFlags_HasSetMousePos,
CImGui.ImGuiBackendFlags_RendererHasVtxOffset
)
# Set up keybindings.
for (imgui_key, glfw_key) in IMGUI_KEY_TO_GLFW
c_set!(gui_io.KeyMap, imgui_key, glfw_key)
end
# Set up the clipboard.
gui_io.GetClipboardTextFn = GUI_CLIPBOARD_GET[]
gui_io.SetClipboardTextFn = GUI_CLIPBOARD_SET[]
# Create renderer assets.
render_program = bp_glsl"""
#START_VERTEX
layout (location = 0) in vec2 vIn_pos;
layout (location = 1) in vec2 vIn_uv;
layout (location = 2) in vec4 vIn_color;
uniform mat4 u_transform;
out vec2 fIn_uv;
out vec4 fIn_color;
void main() {
fIn_uv = vIn_uv;
fIn_color = vIn_color;
vec4 pos = u_transform * vec4(vIn_pos, 0, 1);
gl_Position = vec4(pos.x, pos.y, pos.zw);
}
#START_FRAGMENT
in vec2 fIn_uv;
in vec4 fIn_color;
uniform sampler2D u_texture;
layout (location = 0) out vec4 fOut_color;
void main() {
fOut_color = fIn_color * texture(u_texture, fIn_uv);
}
"""
# Generate an initial font texture with just the default font.
#NOTE: Skipping this initial texture build leads to a weird issue
# where drawing commands come in with null texture ID's.
font_texture = make_gui_font_texture_atlas()
# Mesh vertex/index data is generated procedurally, into a single mesh object.
buffer_vertices = Buffer(sizeof(CImGui.ImDrawVert) * initial_vertex_capacity,
true, KEEP_MESH_DATA_ON_CPU)
buffer_indices = Buffer(sizeof(CImGui.ImDrawIdx) * initial_index_capacity,
true, KEEP_MESH_DATA_ON_CPU)
mesh = gui_generate_mesh(buffer_vertices, buffer_indices)
# Create the service instance.
serv = new(
context.window,
time_ns(),
render_program,
font_texture,
buffer_vertices,
buffer_indices,
mesh,
[ ],
Dict{CImGui.ImTextureID, Union{GL.Texture, GL.View}}(
TEX_ID_FONT => font_texture
),
Dict{Union{GL.Texture, GL.View}, CImGui.ImTextureID}(
font_texture => TEX_ID_FONT
),
TEX_ID_FONT,
TEX_ID_FONT,
fill(false, Int(CImGui.ImGuiMouseButton_COUNT)),
fill(GLFW.Cursor(C_NULL), Int(CImGui.ImGuiMouseCursor_COUNT)),
(_...) -> nothing,
(_...) -> nothing,
(_...) -> nothing,
(_...) -> nothing
)
# Tell ImGui how to manipulate/query data.
serv.callback_closures_char = (c::Char) -> begin
# Why this range? The example code doesn't explain.
# It limits the char to a 2-byte range, and ignores the null terminator.
if UInt(c) in 0x1:0xffff
CImGui.AddInputCharacter(gui_io, c)
end
return nothing
end
serv.callback_closures_key = (key::GLFW.Key, scancode::Int,
action::GLFW.Action, mods::Int) -> begin
if action == GLFW.PRESS
c_set!(gui_io.KeysDown, key, true)
elseif action == GLFW.RELEASE
c_set!(gui_io.KeysDown, key, false)
end
# Calculate modifiers.
# (note from the original implementation: "modifiers are not reliable across systems")
gui_io.KeyCtrl = any(c_get.(Ref(gui_io.KeysDown), (GLFW.KEY_LEFT_CONTROL, GLFW.KEY_RIGHT_CONTROL)))
gui_io.KeyShift = any(c_get.(Ref(gui_io.KeysDown), (GLFW.KEY_LEFT_SHIFT, GLFW.KEY_RIGHT_SHIFT)))
gui_io.KeyAlt = any(c_get.(Ref(gui_io.KeysDown), (GLFW.KEY_LEFT_ALT, GLFW.KEY_RIGHT_ALT)))
gui_io.KeySuper = any(c_get.(Ref(gui_io.KeysDown), (GLFW.KEY_LEFT_SUPER, GLFW.KEY_RIGHT_SUPER)))
return nothing
end
serv.callback_closures_mouse_button = (button::GLFW.MouseButton,
action::GLFW.Action,
mods::Int) -> begin
button_i = Int(button) + 1
if button_i in 1:length(serv.mouse_buttons_just_pressed)
if action == GLFW.PRESS
serv.mouse_buttons_just_pressed[button_i] = true
end
else
@warn "Mouse button idx too large" button
end
return nothing
end
serv.callback_closures_scroll = pos::v2f -> begin
unsafe_store!(gui_io.MouseWheelH,
Cfloat(pos.x) + unsafe_load(gui_io.MouseWheelH))
unsafe_store!(gui_io.MouseWheel,
Cfloat(pos.y) + unsafe_load(gui_io.MouseWheel))
return nothing
end
push!(context.glfw_callbacks_char, serv.callback_closures_char)
push!(context.glfw_callbacks_key, serv.callback_closures_key)
push!(context.glfw_callbacks_mouse_button, serv.callback_closures_mouse_button)
push!(context.glfw_callbacks_scroll, serv.callback_closures_scroll)
# Configure the cursors to use.
cursors = [
(CImGui.ImGuiMouseCursor_Arrow, GLFW.ARROW_CURSOR),
(CImGui.ImGuiMouseCursor_TextInput, GLFW.IBEAM_CURSOR),
(CImGui.ImGuiMouseCursor_ResizeNS, GLFW.VRESIZE_CURSOR),
(CImGui.ImGuiMouseCursor_ResizeEW, GLFW.HRESIZE_CURSOR),
(CImGui.ImGuiMouseCursor_Hand, GLFW.HAND_CURSOR),
# In GLFW 3.4, there are new cursor images we could use.
# However, that version isn't supported.
(CImGui.ImGuiMouseCursor_ResizeAll, GLFW.ARROW_CURSOR), # GLFW.RESIZE_ALL_CURSOR
(CImGui.ImGuiMouseCursor_ResizeNESW, GLFW.ARROW_CURSOR), # GLFW.RESIZE_NESW_CURSOR
(CImGui.ImGuiMouseCursor_ResizeNWSE, GLFW.ARROW_CURSOR), # GLFW.RESIZE_NWSE_CURSOR
(CImGui.ImGuiMouseCursor_NotAllowed, GLFW.ARROW_CURSOR) # GLFW.NOT_ALLOWED_CURSOR
]
for (slot, type) in cursors
# GLFW is a C lib, using 0-based indices.
slot += 1
serv.mouse_cursors[slot] = GLFW.CreateStandardCursor(type)
end
return serv
end
function SHUTDOWN(s, is_context_closing::Bool)
# Clean up mouse cursors.
for cursor in s.mouse_cursors
GLFW.DestroyCursor(cursor)
end
empty!(s.mouse_cursors)
# Clean up GL resources and Context callbacks.
if !is_context_closing
close(s.render_program)
close(s.font_texture)
close(s.buffer)
close(s.buffer_indices)
close(s.buffer_vertices)
delete!(context.glfw_callbacks_char, serv.callback_closures_char)
delete!(context.glfw_callbacks_key, serv.callback_closures_key)
delete!(context.glfw_callbacks_mouse_button, serv.callback_closures_mouse_button)
delete!(context.callback_closures_scroll, serv.callback_closures_scroll)
end
# Clean up the CImGui context if nobody else needs it.
@lock IM_GUI_CONTEXT_LOCKER begin
IM_GUI_CONTEXT_COUNTER[] -= 1
if IM_GUI_CONTEXT_COUNTER[] < 1
CImGui.DestroyContext(IM_GUI_CONTEXT_REF[])
IM_GUI_CONTEXT_REF[] = C_NULL
end
end
end
"Call after changing the set of available fonts for ImGui"
function service_GUI_rebuild_fonts(serv)
new_font_texture = make_gui_font_texture_atlas()
old_font_texture = serv.font_texture
serv.font_texture = new_font_texture
serv.user_texture_handles[new_font_texture] = TEX_ID_FONT
serv.user_textures_by_handle[TEX_ID_FONT] = new_font_texture
delete!(serv.user_texture_handles, old_font_texture)
close(old_font_texture)
end
"
Call before doing any GUI in each frame.
Must be followed by a call to `service_GUI_end_frame()` when it's time to render the GUI.
"
function service_GUI_start_frame(serv)
io::Ptr{CImGui.ImGuiIO} = CImGui.GetIO()
if !CImGui.ImFontAtlas_IsBuilt(unsafe_load(io.Fonts))
service_GUI_rebuild_fonts()
end
# Set up the display size.
window_size::v2i = get_window_size(serv.window)
render_size::v2i = let render_size_glfw = GLFW.GetFramebufferSize(serv.window)
v2i(render_size_glfw.width, render_size_glfw.height)
end
io.DisplaySize = CImGui.ImVec2(Cfloat(window_size.x), Cfloat(window_size.y))
render_scale::Vec2{Cfloat} = render_size / max(one(v2i), window_size)
io.DisplayFramebufferScale = CImGui.ImVec2(render_scale...)
# Update the frame time.
last_time = serv.last_time_ns
serv.last_time_ns = time_ns()
io.DeltaTime = (serv.last_time_ns - last_time) / 1e9
# Update mouse buttons.
for i in 1:length(serv.mouse_buttons_just_pressed)
# If a mouse press happened, always pass it as "mouse held this frame";
# otherwise we'd miss fast clicks.
is_down::Bool = serv.mouse_buttons_just_pressed[i] ||
GLFW.GetMouseButton(serv.window, GLFW.MouseButton(i - 1))
c_set!(io.MouseDown, i - 1, is_down)
serv.mouse_buttons_just_pressed[i] = false
end
# Update mouse position.
prev_mouse_pos = io.MousePos
io.MousePos = CImGui.ImVec2(-CImGui.FLT_MAX, -CImGui.FLT_MAX)
if GLFW.GetWindowAttrib(serv.window, GLFW.FOCUSED) != 0
if unsafe_load(io.WantSetMousePos)
GLFW.SetCursorPos(serv.window,
Cdouble(prev_mouse_pos.x), Cdouble(prev_mouse_pos.y))
else
(cursor_x, cursor_y) = GLFW.GetCursorPos(serv.window)
io.MousePos = CImGui.ImVec2(Cfloat(cursor_x), Cfloat(cursor_y))
end
end
# Update the mouse cursor's image.
if ((unsafe_load(io.ConfigFlags) & CImGui.ImGuiConfigFlags_NoMouseCursorChange) !=
CImGui.ImGuiConfigFlags_NoMouseCursorChange) &&
(GLFW.GetInputMode(serv.window, GLFW.CURSOR) != GLFW.CURSOR_DISABLED)
#begin
imgui_cursor::CImGui.ImGuiMouseCursor = CImGui.GetMouseCursor()
# Hide the OS mouse cursor if ImGui is drawing it, or if it wants no cursor.
if (imgui_cursor == CImGui.ImGuiMouseCursor_None) || unsafe_load(io.MouseDrawCursor)
GLFW.SetInputMode(serv.window, GLFW.CURSOR, GLFW.CURSOR_HIDDEN)
# Otherwise, make sure it's shown.
else
cursor = serv.mouse_cursors[imgui_cursor + 1]
cursor_img = (cursor.handle == C_NULL) ?
serv.mouse_cursors[imgui_cursor + 1] :
serv.mouse_cursors[CImGui.ImGuiMouseCursor_Arrow + 1]
GLFW.SetCursor(serv.window, cursor_img)
GLFW.SetInputMode(serv.window, GLFW.CURSOR, GLFW.CURSOR_NORMAL)
end
end
# Check for previously-used textures getting destroyed.
# Just check a few different textures every frame.
for _ in 1:3
if haskey(serv.user_textures_by_handle, serv.next_tex_handle_to_prune)
entry_to_prune = serv.user_textures_by_handle[serv.next_tex_handle_to_prune]
tex_to_prune::Texture = if entry_to_prune isa View
entry_to_prune.owner
else
entry_to_prune
end
if is_destroyed(tex_to_prune)
delete!(serv.user_textures_by_handle, serv.next_tex_handle_to_prune)
delete!(serv.user_texture_handles, entry_to_prune)
end
end
serv.next_tex_handle_to_prune = CImGui.ImTextureID(
(UInt64(serv.next_tex_handle_to_prune) + 1) %
UInt64(serv.max_tex_handle)
)
end
CImGui.NewFrame()
return nothing
end
"
Call at the end of a frame to render the GUI
into the current framebuffer (presumably the screen).
Must be preceded by a corresponding call to `service_GUI_start_frame()`.
"
function service_GUI_end_frame(serv)
context::GL.Context = get_context()
io::Ptr{CImGui.ImGuiIO} = CImGui.GetIO()
@bp_check(CImGui.ImFontAtlas_IsBuilt(unsafe_load(io.Fonts)),
"Font atlas isn't built! Make sure you've called `service_GUI_rebuild_fonts()`")
# Notify Dear ImGUI that drawing is starting.
CImGui.Render()
draw_data::Ptr{CImGui.ImDrawData} = CImGui.GetDrawData()
if draw_data == C_NULL
return nothing
end
# Compute coordinate transforms.
framebuffer_size = v2i(trunc(unsafe_load(draw_data.DisplaySize.x) *
unsafe_load(draw_data.FramebufferScale.x)),
trunc(unsafe_load(draw_data.DisplaySize.y) *
unsafe_load(draw_data.FramebufferScale.y)))
if any(framebuffer_size <= 0)
return nothing
end
draw_pos_min = v2f(unsafe_load(draw_data.DisplayPos.x),
unsafe_load(draw_data.DisplayPos.y))
draw_size = v2f(unsafe_load(draw_data.DisplaySize.x),
unsafe_load(draw_data.DisplaySize.y))
draw_pos_max = draw_pos_min + draw_size
# Flip the Y for the projection matrix.
mat_proj::fmat4 = m4_ortho(Box3Df(
min=v3f(draw_pos_min.x, draw_pos_max.y, -1),
max=v3f(draw_pos_max.x, draw_pos_min.y, 1)
))
set_uniform(serv.render_program, "u_transform", mat_proj)
# Pre-activate the font texture, which will be used in many GUI calls.
font_tex_id = unsafe_load(unsafe_load(io.Fonts).TexID)
@bp_gui_assert(serv.user_textures_by_handle[font_tex_id] ==
serv.font_texture,
"Font texture ID is not ", font_tex_id, " as reported. ",
"Full ImGUI texture map: ", serv.user_textures_by_handle)
@bp_gui_assert(font_tex_id == TEX_ID_FONT)
view_activate(serv.font_texture)
# Scissor/clip rectangles will come in projection space.
# We'll need to map them into framebuffer space.
# Clip offset is (0,0) unless using multi-viewports.
clip_offset = -draw_pos_min
# Clip scale is (1, 1) unless using retina display, which is often (2, 2).
clip_scale = v2f(unsafe_load(draw_data.FramebufferScale.x),
unsafe_load(draw_data.FramebufferScale.y))
# We need alpha blending, no culling (the safer option, and no difference in performance),
# no depth-testing (depth is determined by draw order), and no depth writes.
# Along with making sure all these are changed and then restored at the end,
# we also need to ensure that scissor rectangle state is restored at the end,
# because individual draw-command lists will change it.
# Other render state can remain unchanged.
gui_render_state = context.state
@set! gui_render_state.depth_test = ValueTests.pass
@set! gui_render_state.depth_write = false
@set! gui_render_state.blend_mode = (
rgb = make_blend_alpha(BlendStateRGB),
alpha = make_blend_alpha(BlendStateAlpha)
)
@set! gui_render_state.cull_mode = FaceCullModes.off
@set! gui_render_state.scissor = nothing
with_render_state(context, gui_render_state) do
cmd_lists::Vector{Ptr{CImGui.ImDrawList}} = unsafe_wrap(Vector{Ptr{CImGui.ImDrawList}},
unsafe_load(draw_data.CmdLists),
unsafe_load(draw_data.CmdListsCount))
for cmd_list_ptr in cmd_lists
# Upload the vertex/index data.
# We may have to reallocate the buffers if they're not large enough.
vertices_native::CImGui.ImVector_ImDrawVert = unsafe_load(cmd_list_ptr.VtxBuffer)
indices_native::CImGui.ImVector_ImDrawIdx = unsafe_load(cmd_list_ptr.IdxBuffer)
reallocated_buffers::Bool = false
let vertices = unsafe_wrap(Vector{CImGui.ImDrawVert},
vertices_native.Data, vertices_native.Size)
if serv.buffer_vertices.byte_size < (length(vertices) * sizeof(CImGui.ImDrawVert))
close(serv.buffer_vertices)
new_size = sizeof(CImGui.ImDrawVert) * length(vertices) * 2
serv.buffer_vertices = Buffer(new_size, true, KEEP_MESH_DATA_ON_CPU)
reallocated_buffers = true
end
set_buffer_data(serv.buffer_vertices, vertices)
end
let indices = unsafe_wrap(Vector{CImGui.ImDrawIdx},
indices_native.Data, indices_native.Size)
if serv.buffer_indices.byte_size < (length(indices) * sizeof(CImGui.ImDrawIdx))
close(serv.buffer_indices)
new_size = sizeof(CImGui.ImDrawIdx) * length(indices) * 2
serv.buffer_indices = Buffer(new_size, true, KEEP_MESH_DATA_ON_CPU)
reallocated_buffers = true
end
set_buffer_data(serv.buffer_indices, indices)
end
if reallocated_buffers
close(serv.buffer)
serv.buffer = gui_generate_mesh(serv.buffer_vertices, serv.buffer_indices)
end
# Execute the individual commands.
cmd_buffer = unsafe_load(cmd_list_ptr.CmdBuffer)
for cmd_i in 1:cmd_buffer.Size
cmd_ptr::Ptr{CImGui.ImDrawCmd} = cmd_buffer.Data +
((cmd_i - 1) * sizeof(CImGui.ImDrawCmd))
n_elements = unsafe_load(cmd_ptr.ElemCount)
# If the user provided a custom drawing function, use that.
if unsafe_load(cmd_ptr.UserCallback) != C_NULL
ccall(unsafe_load(cmd_ptr.UserCallback), Cvoid,
(Ptr{CImGui.ImDrawList}, Ptr{CImGui.ImDrawCmd}),
cmd_list_ptr, cmd_ptr)
# Otherwise, do a normal GUI draw.
else
# Set the scissor region.
clip_rect_projected = unsafe_load(cmd_ptr.ClipRect)
clip_minmax_projected = v4f(clip_rect_projected.x, clip_rect_projected.y,
clip_rect_projected.z, clip_rect_projected.w)
clip_min = clip_scale * (clip_minmax_projected.xy + clip_offset)
clip_max = clip_scale * (clip_minmax_projected.zw + clip_offset)
if all(clip_min < clip_max)
# The scissor min and max depend on the assumption
# of lower-left-corner clip-mode.
scissor_min = Vec(clip_min.x, framebuffer_size.y - clip_max.y)
scissor_max = Vec(clip_max.x, framebuffer_size.y - clip_min.y)
scissor_min_pixel = map(x -> trunc(Cint, x), scissor_min)
scissor_max_pixel = map(x -> trunc(Cint, x), scissor_max)
# ImGUI is using 0-based pixels, but B+ uses 1-based.
scissor_min_pixel += one(Int32)
scissor_max_pixel += one(Int32)
# Max pixel doesn't need to add 1, but I'm not quite sure why.
set_scissor(context, Box2Di(min=scissor_min_pixel, max=scissor_max_pixel))
# Draw the texture.
tex_id = unsafe_load(cmd_ptr.TextureId)
tex = haskey(serv.user_textures_by_handle, tex_id) ?
serv.user_textures_by_handle[tex_id] :
error("Unknown GUI texture handle: ", tex_id)
set_uniform(serv.render_program, "u_texture", tex)
(tex_id != font_tex_id) && view_activate(tex)
render_mesh(
serv.buffer, serv.render_program
;
indexed_params = DrawIndexed(
value_offset = UInt64(unsafe_load(cmd_ptr.VtxOffset))
),
elements = IntervalU((
min=unsafe_load(cmd_ptr.IdxOffset) + 1,
size=n_elements
))
)
if (tex_id != font_tex_id)
view_deactivate(tex)
end
end
end
end
end
view_deactivate(serv.font_texture)
end
return nothing
end
"Converts a B+ texture/view to something the GUI service can draw with"
function gui_tex_handle(service, tex::Union{Texture, View})
return get!(service.user_texture_handles, tex) do
@bp_gui_assert(!haskey(service.user_texture_handles, tex),
"The call to get!() invoked this lambda twice in a row")
next_handle = service.max_tex_handle + 1
service.max_tex_handle += 1
@bp_gui_assert(!haskey(service.user_textures_by_handle, next_handle))
service.user_textures_by_handle[next_handle] = tex
return CImGui.ImTextureID(next_handle)
end
end
end
export Service_GUI, service_GUI_init, service_GUI_shutdown,
service_GUI, service_GUI_exists,
service_GUI_start_frame, service_GUI_end_frame, service_GUI_rebuild_fonts,
gui_tex_handle | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 8553 | ## Blocks of temporary GUI state ##
"
Nests some GUI code within a window.
Extra arguments get passed directly into `CImGui.Begin()`.
Returns the output of your code block, or `nothing` if the UI was culled.
"
function gui_window(to_do, args...; kw_args...)::Optional
is_open = CImGui.Begin(args..., kw_args...)
try
if is_open
return to_do()
end
finally
CImGui.End()
end
return nothing
end
"
Executes some GUI code with a different item width.
See: https://pixtur.github.io/mkdocs-for-imgui/site/api-imgui/ImGui--Dear-ImGui-end-user/#PushItemWidth
* >0.0f: width in pixels
* <0.0f: align xx pixels to the right of window (so -1.0f always align width to the right side)
* ==0.0f: default to ~⅔ of windows width
"
function gui_with_item_width(to_do, width::Real)
CImGui.PushItemWidth(Float32(width))
try
return to_do()
finally
CImGui.PopItemWidth()
end
end
function gui_with_indentation(to_do, width::Optional{Real} = nothing)
CImGui.Indent(@optional(exists(width), width))
try
return to_do()
finally
CImGui.Unindent()
end
end
function gui_with_padding(to_do, padding...)
CImGui.PushStyleVar(CImGui.ImGuiStyleVar_WindowPadding, padding...)
try
return to_do()
finally
CImGui.PopStyleVar()
end
end
function gui_with_clip_rect(to_do,
rect::Box2Df, intersect_with_current_rect::Bool,
draw_list::Optional{Ptr{LibCImGui.ImDrawList}} = nothing
#TODO: Param for using world space (call different CImGui func)
)
CImGui.PushClipRect(@optional(exists(draw_list), draw_list),
CImGui.ImVec2(min_inclusive(rect)...),
CImGui.ImVec2(max_exclusive(rect)...),
intersect_with_current_rect)
try
return to_do()
finally
CImGui.PopClipRect()
end
end
function gui_with_font(to_do, font::Ptr)
CImGui.PushFont(font)
try
return to_do()
finally
CImGui.PopFont()
end
end
function gui_with_font(to_do, font_idx::Integer)
font_singleton = unsafe_load(CImGui.GetIO().Fonts)
font_list::CImGui.ImVector_ImFontPtr = unsafe_load(font_singleton.Fonts)
font::Ptr{CImGui.ImFont} = unsafe_load(font_list.Data, font_idx)
return gui_with_font(to_do, font)
end
"
Executes some GUI code without allowing the user to tab to different widgets
(so tabs get inserted into text editors).
"
function gui_with_unescaped_tabbing(to_do)
CImGui.PushAllowKeyboardFocus(false)
try
return to_do()
finally
CImGui.PopAllowKeyboardFocus()
end
end
"
Executes some GUI code with the given ID data (ptr, String, Integer, or begin + end Strings)
pushed onto the stack.
"
function gui_with_nested_id(to_do, values...)
CImGui.PushID(values...)
to_do()
CImGui.PopID()
end
"
Executes some GUI within a fold (what Dear ImGUI calls a 'tree node').
If it's open, returns the output of your lambda; otherwise returns `nothing`.
"
function gui_within_fold(to_do, label)
is_visible::Bool = CImGui.TreeNode(label)
if is_visible
try
return to_do()
finally
CImGui.TreePop()
end
end
return nothing
end
"Executes some GUI with a different 'style color'."
function gui_with_style_color(to_do,
index::CImGui.LibCImGui.ImGuiCol_,
color::Union{Integer, CImGui.ImVec4})
CImGui.PushStyleColor(index, color)
to_do()
CImGui.PopStyleColor()
end
"
Groups widgets together for placement within larger layouts
(such as a vertical group within a horizontal line).
"
function gui_within_group(to_do)
CImGui.BeginGroup()
try
return to_do()
finally
CImGui.EndGroup()
end
end
"""
Defines a set of tabs, and the contents underneath each.
Within this block you can create new tab views as follows:
````
gui_tab_views("Tab1") do
# GUI code for the tab's contents
end
gui_tab_views("Tab2") do
# GUI code for the other tab's contents
end
````
"""
function gui_tab_views(to_do, label, flags = CImGui.LibCImGui.ImGuiTabBarFlags_None)
if CImGui.BeginTabBar(label, flags)
try
return to_do()
finally
CImGui.EndTabBar()
end
else
return nothing
end
end
"Defines one tab, as part of a tab bar (see `gui_tab_views()`). Returns whether the tab view was open."
function gui_tab_item(to_do, label, flags = CImGui.LibCImGui.ImGuiTabItemFlags_None)
if CImGui.BeginTabItem(label, C_NULL, flags)
try
to_do()
return true
finally
CImGui.EndTabItem()
end
else
return false
end
end
"
Groups a GUI together into a smaller window.
Returns the output of 'to_do()', or `nothing` if the window is closed.
"
function gui_within_child_window(to_do, id, size, flags=0)::Optional
is_open = CImGui.BeginChildFrame(id, size, flags)
try
if is_open
return to_do()
end
finally
CImGui.EndChildFrame()
end
return nothing
end
export gui_with_item_width, gui_with_indentation, gui_with_clip_rect, gui_with_padding,
gui_with_unescaped_tabbing, gui_with_style_color, gui_with_font, gui_with_nested_id,
gui_window, gui_within_fold, gui_within_group, gui_tab_views, gui_tab_item, gui_within_child_window
#
## Custom editors ##
"Edits a vector with spherical coordinates; returns its new value."
function gui_spherical_vector( label, vec::v3f
;
stays_normalized::Bool = false,
fallback_yaw::Ref{Float32} = Ref(zero(Float32))
)::v3f
radius = vlength(vec)
vec /= radius
yawpitch = Float32.((atan(vec.y, vec.x), acos(vec.z)))
# Keep the editor stable when it reaches a straight-up or straight-down vector.
if yawpitch[2] in (Float32(-π), Float32(π))
yawpitch = (fallback_yaw[], yawpitch[2])
else
fallback_yaw[] = yawpitch[1]
end
if stays_normalized
# Remove floating-point error in the previous length calculation.
radius = one(Float32)
else
# Provide an editor for the radius.
@c CImGui.InputFloat("$label Length", &radius)
CImGui.SameLine()
end
# Show two sliders, but with different ranges so we can't use CImGui.SliderFloat2().
yaw, pitch = yawpitch
content_width = CImGui.GetContentRegionAvailWidth()
CImGui.SetNextItemWidth(content_width * 0.4)
@c CImGui.SliderFloat("##Yaw", &yaw, -π, π)
CImGui.SameLine()
CImGui.SetNextItemWidth(content_width * 0.4)
gui_with_nested_id("Slider 2") do
@c CImGui.SliderFloat(label, &pitch, 0, π - 0.00001)
end
yawpitch = (yaw, pitch)
# Convert back to cartesian coordinates.
pitch_sincos = sincos(yawpitch[2])
vec_2d = v2f(sincos(yawpitch[1])).yx * pitch_sincos[1]
vec_z = pitch_sincos[2]
return radius * vappend(vec_2d, vec_z)
end
export gui_spherical_vector
## Small helper functions ##
"
Sizes the next CImGui window in terms of a percentage of the actual window's size,
optionally with a pixel-space border padding it inwards.
"
function gui_next_window_space(uv_space::Box2Df,
min_and_max_pixel_border::v2i = zero(v2i),
min_only_pixel_border::v2i = zero(v2i)
;
window_size::v2i = get_window_size(get_context()))
# Remove the padding from the reported window size.
window_size -= min_and_max_pixel_border * v2i(2, 2)
window_size -= min_only_pixel_border
w_size::v2f = window_size * size(uv_space)
# Add the padding to the calculated position.
pos::v2f = (window_size * min_inclusive(uv_space)) +
convert(v2f, min_only_pixel_border + min_and_max_pixel_border)
CImGui.SetNextWindowPos(CImGui.ImVec2(pos...))
CImGui.SetNextWindowSize(CImGui.ImVec2(w_size...))
end
"Sizes the next CImGui window in terms of a pixel rectangle"
function gui_next_window_space(pixel_space::Box2Di; window_size::v2i = get_window_size(get_context()))
CImGui.SetNextWindowPos(CImGui.ImVec2(min_inclusive(pixel_space)...))
CImGui.SetNextWindowSize(CImGui.ImVec2(size(pixel_space...)))
end
export gui_next_window_space | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 3015 | "
Encapsulates a Dear ImGUI text editor.
Run the GUI with `gui_text!()` and get the current string with `string()`.
Update the value externally with `update!()`.
"
Base.@kwdef mutable struct GuiText
# Provided as the first argument to the constructor.
raw_value::InteropString
# Provided as named arguments to the constructor.
label::String = ""
is_multiline::Bool = false
multiline_requested_size::NTuple{2, Int} = (0, 0)
imgui_flags::Integer = 0x00000
# Internal; leave these alone
_buffer_has_been_updated = false
_edit_callback::Base.Callable = Nothing
_c_func_edit_callback::Optional{Base.CFunction} = nothing
#TODO: Dear ImGUI callbacks for resizing text buffer as needed
end
GuiText(initial_value::AbstractString; kw...) = GuiText(;
raw_value = InteropString(initial_value),
kw...
)
"
Displays a Dear ImGUI widget for the given text editor.
Returns whether the text has been edited on this frame.
"
function gui_text!(t::GuiText)::Bool
# Lazy-initialize the C callback for buffer resizing.
if isnothing(t._c_func_edit_callback)
t._edit_callback = (p::Ptr{CImGui.ImGuiInputTextCallbackData}) -> begin
data::CImGui.ImGuiInputTextCallbackData = unsafe_load(p)
if data.EventFlag == CImGui.ImGuiInputTextFlags_CallbackResize
desired_size::Int = data.BufSize
if length(t.raw_value.c_buffer) < desired_size
resize!(t.raw_value.c_buffer, desired_size * 2)
end
elseif data.EventFlag == CImGui.ImGuiInputTextFlags_CallbackCompletion
println("Completed!")
else
println("Other event: ", data.EventFlag)
end
return Cint(0) # Does anybody know if this value has any meaning?
end
t._c_func_edit_callback = @cfunction($(t._edit_callback), Cint, (Ptr{CImGui.ImGuiInputTextCallbackData}, ))
end
changed::Bool = false
if t.is_multiline
changed = @c CImGui.InputTextMultiline(
t.label,
&t.raw_value.c_buffer[0], length(t.raw_value.c_buffer),
t.multiline_requested_size,
t.imgui_flags |
CImGui.ImGuiInputTextFlags_CallbackResize |
CImGui.ImGuiInputTextFlags_CallbackCompletion,
t._c_func_edit_callback
)
else
changed = @c CImGui.InputText(
t.label,
&t.raw_value.c_buffer[0], length(t.raw_value.c_buffer),
t.imgui_flags
)
end
t._buffer_has_been_updated |= changed
return changed
end
"Gets the current value of a GUI-edited text."
function Base.string(t::GuiText)::String
if t._buffer_has_been_updated
update!(t.raw_value)
t._buffer_has_been_updated = false
end
return t.raw_value.julia
end
function Utilities.update!(t::GuiText, s::AbstractString)
update!(t.raw_value, s)
t._buffer_has_been_updated = false
end
export GuiText, gui_text! | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 298 | module Input
# External dependencies
using Setfield
using GLFW, StructTypes, MacroTools
# B+ dependencies
using BplusCore; @using_bplus_core
using ..GL
@make_toggleable_asserts bp_input_
@decentralized_module_init
include("mappings.jl")
include("inputs.jl")
include("service.jl")
end # module | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 4075 | "Computes an input's, next value, and returns the updated version of it"
function update_input end
## Buttons ##
@bp_enum(ButtonModes,
down, up,
just_pressed, just_released
)
struct ButtonInput
id::ButtonID
mode::E_ButtonModes
value::Bool
prev_raw::Bool
end
ButtonInput(id::ButtonID, mode::E_ButtonModes = ButtonModes.down) = ButtonInput(id, mode, false, false)
function raw_input(id::ButtonID, wnd::GLFW.Window)::Bool
if id isa GLFW.Key
return GLFW.GetKey(wnd, id)
elseif id isa GLFW.MouseButton
return GLFW.GetMouseButton(wnd, id)
elseif id isa Tuple{GLFW.Joystick, JoystickButtonID}
buttons = GLFW.GetJoystickButtons(id[1])
return exists(buttons) && (id[2].i <= length(buttons)) && buttons[id[2].i]
else
error("Unimplemented: ", typeof(id))
end
end
function update_input(input::ButtonInput, wnd::GLFW.Window)::ButtonInput
new_raw = raw_input(input.id, wnd)
@set! input.value = if input.mode == ButtonModes.down
new_raw
elseif input.mode == ButtonModes.up
!new_raw
elseif input.mode == ButtonModes.just_pressed
new_raw && !input.prev_raw
elseif input.mode == ButtonModes.just_released
!new_raw && input.prev_raw
else
error("Unimplemented: ", input.mode)
end
@set! input.prev_raw = new_raw
return input
end
export ButtonModes, E_ButtonModes, ButtonInput
## Axes ##
@bp_enum(AxisModes,
# The raw value.
value,
# The difference between the value this frame and its value last frame.
delta
)
struct AxisInput
id::AxisID
mode::E_AxisModes
value::Float32
prev_raw::Float32
value_scale::Float32
end
AxisInput(id::AxisID, mode::E_AxisModes = AxisModes.value
;
initial_value = 0,
initial_raw = initial_value,
value_scale = 1
) = AxisInput(id, mode, initial_value, initial_raw, value_scale)
function raw_input(id::AxisID, wnd::GLFW.Window, current_scroll::v2f)::Float32
if id isa E_MouseAxes
if id == MouseAxes.x
return GLFW.GetCursorPos(wnd).x
elseif id == MouseAxes.y
return GLFW.GetCursorPos(wnd).y
elseif id == MouseAxes.scroll_x
return current_scroll.x
elseif id == MouseAxes.scroll_y
return current_scroll.y
else
error("Unimplemented: MouseAxes.", id)
end
elseif id isa Tuple{GLFW.Joystick, JoystickAxisID}
let axes = GLFW.GetJoystickAxes(id[1])
if exists(axes) && (id[2].i <= length(axes))
return @f32(axes[id[2].i])
else
return @f32(0)
end
end
elseif id isa ButtonAsAxis
button_value = raw_input(id.id, wnd)
return button_value ? id.pressed : id.released
elseif id isa Vector{ButtonAsAxis}
total_value::Float32 = 0
for button::ButtonAsAxis in id
button_value::Bool = raw_input(button.id, wnd)
delta = (button_value ? button.pressed : button.released)
total_value += delta
end
return total_value
else
error("Unimplemented: ", typeof(id))
end
end
function update_input(input::AxisInput, wnd::GLFW.Window,
current_scroll::v2f)::AxisInput
new_raw = raw_input(input.id, wnd, current_scroll)
@set! input.value = input.value_scale *
if input.mode == AxisModes.value
new_raw
elseif input.mode == AxisModes.delta
new_raw - input.prev_raw
else
error("Unimplemented: ", typeof(input.mode))
end
@set! input.prev_raw = new_raw
return input
end
export AxisModes, E_AxisModes, AxisInput | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1060 | ## Buttons ##
struct JoystickButtonID
i::Int
end
"Some kind of binary input that GLFW tracks"
#NOTE: Make sure this has no overlap with `AxisID`!
const ButtonID = Union{GLFW.Key, GLFW.MouseButton, Tuple{GLFW.Joystick, JoystickButtonID}}
export JoystickButtonID, ButtonID
## Axes ##
@bp_enum(MouseAxes,
x, y, scroll_x, scroll_y
)
struct JoystickAxisID
i::Int
end
"Maps a key up/down to a value range"
struct ButtonAsAxis
id::ButtonID
released::Float32
pressed::Float32
end
ButtonAsAxis(id::ButtonID) = ButtonAsAxis(id, 0, 1)
ButtonAsAxis_Reflected(id::ButtonID) = ButtonAsAxis(id, 1, 0)
ButtonAsAxis_Negative(id::ButtonID) = ButtonAsAxis(id, 0, -1)
"Some kind of continuous input that GLFW tracks"
#NOTE: Make sure this has no overlap with `ButtonID`!
const AxisID = Union{E_MouseAxes,
Tuple{GLFW.Joystick, JoystickAxisID},
ButtonAsAxis, Vector{ButtonAsAxis}}
export MouseAxes, E_MouseAxes, JoystickAxisID, AxisID,
ButtonAsAxis, ButtonAsAxis_Reflected, ButtonAsAxis_Negative | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 5727 | "Manages all inputs for a GL context/window"
@bp_service Input(force_unique) begin
buttons::Dict{AbstractString, Vector{ButtonInput}}
axes::Dict{AbstractString, AxisInput}
current_scroll_pos::v2f
context_window::GLFW.Window
scroll_callback::Base.Callable
INIT() = begin
context = get_context()
service = new(
Dict{String, Vector{ButtonInput}}(),
Dict{String, AxisInput}(),
zero(v2f),
context.window,
_ -> nothing # Dummy callable, real one is below
)
service.scroll_callback = (delta::v2f -> (service.current_scroll_pos += delta))
# Use GLFW's 'sticky keys' mode to remember press/release events
# that start and end within a single frame.
GLFW.SetInputMode(context.window, GLFW.STICKY_MOUSE_BUTTONS, true)
# Register GLFW callbacks.
push!(context.glfw_callbacks_scroll, service.scroll_callback)
return service
end
SHUTDOWN(service, is_context_closing::Bool) = begin
if !is_context_closing
delete!(get_context().glfw_callbacks_scroll,
service.scroll_callback)
end
end
service_Input_update(s)::Nothing = begin
for button_list in values(s.buttons)
map!(b -> update_input(b, s.context_window),
button_list, button_list)
end
for axis_name in keys(s.axes)
s.axes[axis_name] = update_input(s.axes[axis_name],
s.context_window, s.current_scroll_pos)
end
end
"Removes all input bindings and resets all state"
service_Input_reset(s)::Nothing = begin
empty!(s.buttons)
empty!(s.axes)
s.current_scroll_pos = zero(v2f)
end
"
Creates a new button (throwing an error if it already exists), with the given inputs.
Returns the source list of button inputs, so you can further configure them at will.
All button inputs will be OR-ed together.
"
function create_button(service,
name::AbstractString,
inputs::ButtonInput...
)::Vector{ButtonInput}
if haskey(service.buttons, name)
error("Button already exists: '", name, "'")
else
service.buttons[name] = collect(inputs)
return service.buttons[name]
end
end
"
Deletes the given button.
Throws an error if it doesn't exist.
"
function remove_button(service, name::AbstractString)
if haskey(service.buttons, name)
delete!(service.buttons, name)
else
error("Button does not exist to be deleted: '", name, "'")
end
end
"Creates a new axis (throwing an error if it already exists), with the given input"
function create_axis(service,
name::AbstractString,
axis::AxisInput)
if haskey(service.axes, name)
error("Axis already exists: '", name, "'")
else
# If this input uses the mouse position, prepare it with the current state of the mouse.
# Otherwise there will be a big jump on the first frame's input.
if axis.id == MouseAxes.x
@set! axis.prev_raw = GLFW.GetCursorPos(service.context_window).x
elseif axis.id == MouseAxes.y
@set! axis.prev_raw = GLFW.GetCursorPos(service.context_window).y
end
service.axes[name] = axis
return nothing
end
end
"
Deletes the given axis.
Throws an error if it doesn't exist.
"
function remove_axis(service, name::AbstractString)
if haskey(service.axes, name)
delete!(service.axes, name)
else
error("Axis does not exist to be deleted: '", name, "'")
end
end
"Gets the current value of a button. Throws an error if it doesn't exist."
function get_button(service, name::AbstractString)::Bool
if haskey(service.buttons, name)
return any(b -> b.value, service.buttons[name])
else
error("No button named '", name, "'")
end
end
"Gets the current value of an axis. Throws an error if it doesn't exist."
function get_axis(service, name::AbstractString)::Float32
if haskey(service.axes, name)
return service.axes[name].value
else
error("No axis named '", name, "'")
end
end
"Gets the current value of a button or axis. Returns `nothing` if it doesn't exist."
function get_input(service, name::AbstractString)::Union{Bool, Float32, Nothing}
if haskey(service.buttons, name)
return any(b -> b.value, service.buttons[name])
elseif haskey(service.axes, name)
return service.axes[name].value
else
return nothing
end
end
"
Gets the source list of button inputs for a named button.
You can modify this list at will to reconfigure the button.
Throws an error if the button doesn't exist.
"
function get_button_inputs(service, name::AbstractString)::Vector{ButtonInput}
if haskey(service.buttons, name)
return service.buttons[name]
else
error("No button named '", name, "'")
end
end
end
export Service_Input, service_Input_init, service_Input_shutdown,
service_Input_get, service_Input_exists, service_Input_update, service_Input_reset,
create_button, create_axis,
remove_button, remove_axis,
get_input, get_button, get_axis,
get_button_inputs | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 190 | debug_level = lowercase(get(ENV, "MODERNGL_DEBUGGING", "false")) == "true"
open(joinpath(@__DIR__, "deps.jl"), "w") do io
println(io, "const enable_opengl_debugging = $debug_level")
end
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 4320 | module ModernGLbp
using Libdl
function glXGetProcAddress(glFuncName)
ccall((:glXGetProcAddress, "libGL.so.1"), Ptr{Cvoid}, (Ptr{UInt8},), glFuncName)
end
function NSGetProcAddress(glFuncName)
tmp = "_"*glFuncName
if ccall(:NSIsSymbolNameDefined, Cint, (Ptr{UInt8},), tmp) == 0
return convert(Ptr{Cvoid}, 0)
else
symbol = ccall(:NSLookupAndBindSymbol, Ptr{Cvoid}, (Ptr{UInt8},), tmp)
return ccall(:NSAddressOfSymbol, Ptr{Cvoid}, (Ptr{Cvoid},), symbol)
end
end
function wglGetProcAddress(glFuncName)
ccall((:wglGetProcAddress, "opengl32"), Ptr{Cvoid}, (Ptr{UInt8},), glFuncName)
end
if Sys.isapple()
getprocaddress(glFuncName) = NSGetProcAddress(glFuncName)
elseif Sys.isunix()
getprocaddress(glFuncName) = glXGetProcAddress(glFuncName)
end
if Sys.iswindows()
getprocaddress(glFuncName) = wglGetProcAddress(glFuncName)
end
struct ContextNotAvailable <: Exception
message::String
end
export ContextNotAvailable
function getprocaddress_e(glFuncName)
p = getprocaddress(glFuncName)
if !isavailable(p)
throw(ContextNotAvailable(
"$glFuncName, not available for your driver, or no valid OpenGL context available"
))
end
p
end
# Test, if an opengl function is available.
# Sadly, this doesn't work for Linux, as glxGetProcAddress
# always returns a non null function pointer, as the function pointers are not depending on an active context.
isavailable(name::Symbol) =
isavailable(ModernGLbp.getprocaddress(ascii(string(name))))
isavailable(ptr::Ptr{Cvoid}) = !(
ptr == C_NULL ||
ptr == convert(Ptr{Cvoid}, 1) ||
ptr == convert(Ptr{Cvoid}, 2) ||
ptr == convert(Ptr{Cvoid}, 3)
)
struct GLENUM{T}
number::T
name::Symbol
end
Base.print(io::IO, e::GLENUM) = print(io,
"GLENUM(",
e.name, ", ",
e.number,
")"
)
Base.show(io::IO, ::MIME"text/plain", e::GLENUM) = print(io,
e.name,
"<", e.number, ">"
)
const MGL_LOOKUP = Dict{Integer, Symbol}()
"Finds the GLENUM value matching the given number."
GLENUM(i::I) where {I<:Integer} = GLENUM(Val(UInt32(i)))
"Overload this method (with a Val(::UInt32) parameter) to change the name of specific GL constants"
function GLENUM(@nospecialize i::Val)
i_val::Integer = typeof(i).parameters[1]
if haskey(MGL_LOOKUP, i_val)
name::Symbol = MGL_LOOKUP[i_val]
original_type::Type{<:Integer} = typeof(getkey(MGL_LOOKUP, i_val, name))
return GLENUM{original_type}(convert(original_type, i_val), name)
else
error(i_val, " is not a valid GLenum value")
end
end
export GLENUM
macro GenEnums(list::Expr)
if !Meta.isexpr(list, :block)
error("Input to @GenEnums must be a block of expressions of the form 'GL_BLAH = value', optionally with a type if not GLenum.")
end
if length(MGL_LOOKUP) > 0
error("It appears that @GenEnums was invoked more than once. This is not allowed.")
end
entries = list.args
# For each entry, remap it into a more complete expression,
# including exports and a GLENUM() overload.
map!(entries, entries) do entry
if Meta.isexpr(entry, :(=))
value = entry.args[2]
# Find the 'name' and 'type' of the value.
name::Symbol = Symbol()
type::Symbol = Symbol()
if Meta.isexpr(entry.args[1], :(::))
name = entry.args[1].args[1]
type = entry.args[1].args[2]
else
name = entry.args[1]
type = :GLenum
end
# Generate the code.
str_name = string(name)
e_name = esc(name)
e_type = esc(type)
e_value = :(convert($e_type, $(esc(value))))
output = quote
const $e_name = $e_value
ModernGLbp.MGL_LOOKUP[$e_value] = Symbol($str_name)
export $e_name
end
return output
elseif entry isa LineNumberNode
return entry
else
error("Unexpected statement in block (expected 'GL_BLAH[::GLtype] = value'). \"",
entry, '"')
end
end
return Expr(:block, entries...)
end
include("glTypes.jl")
include("functionloading.jl")
include("glConstants.jl")
end # module
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 2631 | const depsfile = normpath(joinpath(@__DIR__, "..", "deps", "deps.jl"))
if isfile(depsfile)
include(depsfile)
else
const enable_opengl_debugging = get(ENV, "MODERNGL_DEBUGGING", "false") == "true"
end
gl_represent(x::GLenum) = GLENUM(x).name
gl_represent(x) = repr(x)
function debug_opengl_expr(func_name, args)
if enable_opengl_debugging && func_name != :glGetError
quote
err = glGetError()
if err != GL_NO_ERROR
arguments = gl_represent.(tuple($(args...)))
error("OpenGL call to $($func_name), with arguments: $(arguments)
Failed with error: $(GLENUM(err).name).")
end
end
else
:()
end
end
# based on getCFun macro
macro glfunc(opengl_func)
arguments = map(opengl_func.args[1].args[2:end]) do arg
isa(arg, Symbol) && return Expr(:(::), arg)
arg
end
# Get info out of arguments of `opengl_func`
arg_names = map(arg->arg.args[1], arguments)
return_type = opengl_func.args[2]
input_types = map(arg->arg.args[2], arguments)
func_name = opengl_func.args[1].args[1]
func_name_sym = Expr(:quote, func_name)
func_name_str = string(func_name)
ptr_expr = :(getprocaddress_e($func_name_str))
if Sys.iswindows() # windows has some function pointers statically available and some not, this is how we deal with it:
ptr = Libdl.dlsym_e(gl_lib, func_name)
if (ptr != C_NULL)
ptr_expr = :(($func_name_sym, "opengl32"))
ret = quote
function $func_name($(arg_names...))
result = ccall($ptr_expr, $return_type, ($(input_types...),), $(arg_names...))
$(debug_opengl_expr(func_name, arg_names))
result
end
$(Expr(:export, func_name))
end
return esc(ret)
end
end
ptr_sym = gensym("$(func_name)_func_pointer")
ret = quote
const $ptr_sym = Ref{Ptr{Cvoid}}(C_NULL)
function $func_name($(arg_names...))
if $ptr_sym[]::Ptr{Cvoid} == C_NULL
$ptr_sym[]::Ptr{Cvoid} = $ptr_expr
end
result = ccall($ptr_sym[]::Ptr{Cvoid}, $return_type, ($(input_types...),), $(arg_names...))
$(debug_opengl_expr(func_name, arg_names))
result
end
$(Expr(:export, func_name))
end
return esc(ret)
end
if Sys.iswindows()
const gl_lib = Libdl.dlopen("opengl32")
end
include("glFunctions.jl")
if Sys.iswindows()
Libdl.dlclose(gl_lib)
end
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 170814 | @GenEnums begin
GL_MAP1_GRID_SEGMENTS = 0x0DD1
GL_COMPILE = 0x1300
GL_SAMPLER_3D = 0x8B5F
GL_QUERY = 0x82E3
GL_INTENSITY = 0x8049
GL_FOG_HINT = 0x0C54
GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING = 0x889D
GL_DOUBLE_MAT2x3 = 0x8F49
GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER = 0x8CDC
GL_BUFFER_ACCESS = 0x88BB
GL_LUMINANCE12_ALPHA12 = 0x8047
GL_IMAGE_CUBE_MAP_ARRAY = 0x9054
GL_COMPRESSED_RG11_EAC = 0x9272
GL_RGBA32I = 0x8D82
GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS = 0x8E83
GL_FRAMEBUFFER_UNSUPPORTED = 0x8CDD
GL_SAMPLER_2D_ARRAY = 0x8DC1
GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS = 0x92D1
GL_IMAGE_CLASS_4_X_8 = 0x82BF
GL_UNSIGNED_INT_ATOMIC_COUNTER = 0x92DB
GL_UNPACK_LSB_FIRST = 0x0CF1
GL_ACCUM_RED_BITS = 0x0D58
GL_ELEMENT_ARRAY_BARRIER_BIT ::GLbitfield = 0x00000002
GL_LIGHT4 = 0x4004
GL_POINT_SPRITE = 0x8861
GL_PIXEL_BUFFER_BARRIER_BIT ::GLbitfield = 0x00000080
GL_MAX_GEOMETRY_OUTPUT_VERTICES = 0x8DE0
GL_READ_FRAMEBUFFER_BINDING = 0x8CAA
GL_LIGHT_MODEL_LOCAL_VIEWER = 0x0B51
GL_OBJECT_LINEAR = 0x2401
GL_COLOR_ARRAY_SIZE = 0x8081
GL_TEXTURE12 = 0x84CC
GL_MAX_COMPUTE_WORK_GROUP_SIZE = 0x91BF
GL_OPERAND1_RGB = 0x8591
GL_X3D = 0x0601
GL_TEXTURE_BINDING_3D = 0x806A
GL_SECONDARY_COLOR_ARRAY = 0x845E
GL_UNSIGNED_SHORT_5_6_5_REV = 0x8364
GL_BGRA_INTEGER = 0x8D9B
GL_PACK_ROW_LENGTH = 0x0D02
GL_INT_IMAGE_2D_RECT = 0x905A
GL_SET = 0x150F
GL_LAYER_PROVOKING_VERTEX = 0x825E
GL_FRACTIONAL_EVEN = 0x8E7C
GL_QUADS = 0x0007
GL_INFO_LOG_LENGTH = 0x8B84
GL_EYE_LINEAR = 0x2400
GL_POLYGON_OFFSET_POINT = 0x2A01
GL_TEXTURE = 0x1702
GL_BLEND_EQUATION_ALPHA = 0x883D
GL_CLIP_DISTANCE0 = 0x3000
GL_LINES = 0x0001
GL_MATRIX_STRIDE = 0x92FF
GL_COMPILE_STATUS = 0x8B81
GL_QUERY_RESULT = 0x8866
GL_MAX_FRAMEBUFFER_WIDTH = 0x9315
GL_RGB5 = 0x8050
GL_VERTEX_SHADER = 0x8B31
GL_LIST_BIT ::GLbitfield = 0x00020000
GL_PROXY_TEXTURE_2D_MULTISAMPLE = 0x9101
GL_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900E
GL_TEXTURE_PRIORITY = 0x8066
GL_EVAL_BIT ::GLbitfield = 0x00010000
GL_POINT_SPRITE_COORD_ORIGIN = 0x8CA0
GL_CCW = 0x0901
GL_TEXTURE26 = 0x84DA
GL_SMOOTH_LINE_WIDTH_GRANULARITY = 0x0B23
GL_MEDIUM_INT = 0x8DF4
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1
GL_SHADER_COMPILER = 0x8DFA
GL_BUFFER_MAP_LENGTH = 0x9120
GL_ATTACHED_SHADERS = 0x8B85
GL_CLIP_DISTANCE5 = 0x3005
GL_MAP_UNSYNCHRONIZED_BIT ::GLbitfield = 0x0020
GL_BLEND_SRC_ALPHA = 0x80CB
GL_MAX_UNIFORM_LOCATIONS = 0x826E
GL_COMPRESSED_RGB8_ETC2 = 0x9274
GL_R32F = 0x822E
GL_INT_SAMPLER_2D = 0x8DCA
GL_DOUBLE_MAT4x3 = 0x8F4E
GL_C3F_V3F = 0x2A24
GL_TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516
GL_MAP2_INDEX = 0x0DB1
GL_TEXTURE_FETCH_BARRIER_BIT ::GLbitfield = 0x00000008
GL_DEPTH_BUFFER_BIT ::GLbitfield = 0x00000100
GL_STENCIL_BITS = 0x0D57
GL_INTENSITY12 = 0x804C
GL_DEPTH_COMPONENT32 = 0x81A7
GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS = 0x8E86
GL_SYNC_FLUSH_COMMANDS_BIT ::GLbitfield = 0x00000001
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER = 0x92CB
GL_UNSIGNED_INT_IMAGE_CUBE = 0x9066
GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8A42
GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8C88
GL_LIST_BASE = 0x0B32
GL_DRAW_BUFFER7 = 0x882C
GL_INTERNALFORMAT_BLUE_SIZE = 0x8273
GL_POINT_SMOOTH = 0x0B10
GL_INT_SAMPLER_3D = 0x8DCB
GL_BUFFER_MAP_OFFSET = 0x9121
GL_MAX_GEOMETRY_SHADER_INVOCATIONS = 0x8E5A
GL_DEPTH_COMPONENTS = 0x8284
GL_REFERENCED_BY_TESS_CONTROL_SHADER = 0x9307
GL_HIGH_FLOAT = 0x8DF2
GL_PIXEL_MAP_S_TO_S = 0x0C71
GL_INT_SAMPLER_1D_ARRAY = 0x8DCE
GL_DOUBLE = 0x140A
GL_ACTIVE_SUBROUTINE_MAX_LENGTH = 0x8E48
GL_FOG_COORDINATE_ARRAY_STRIDE = 0x8455
GL_RG32F = 0x8230
GL_COMMAND_BARRIER_BIT ::GLbitfield = 0x00000040
GL_GENERATE_MIPMAP = 0x8191
GL_RGB10_A2UI = 0x906F
GL_T2F_C4UB_V3F = 0x2A29
GL_RGB16 = 0x8054
GL_TEXTURE_MATRIX = 0x0BA8
GL_IMAGE_2D_MULTISAMPLE_ARRAY = 0x9056
GL_SRGB8_ALPHA8 = 0x8C43
GL_LAST_VERTEX_CONVENTION = 0x8E4E
GL_COLOR_ARRAY_STRIDE = 0x8083
GL_MAX_DEBUG_LOGGED_MESSAGES = 0x9144
GL_VERTEX_SUBROUTINE = 0x92E8
GL_STENCIL_INDEX16 = 0x8D49
GL_TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515
GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS = 0x92C5
GL_BITMAP = 0x1A00
GL_CURRENT_INDEX = 0x0B01
GL_IMAGE_PIXEL_FORMAT = 0x82A9
GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS = 0x90D7
GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216
GL_MAP1_GRID_DOMAIN = 0x0DD0
GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642
GL_STENCIL_PASS_DEPTH_FAIL = 0x0B95
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518
GL_BLUE_INTEGER = 0x8D96
GL_STENCIL_BACK_FAIL = 0x8801
GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE = 0x92D8
GL_XOR = 0x1506
GL_GET_TEXTURE_IMAGE_TYPE = 0x8292
GL_VERTEX_PROGRAM_TWO_SIDE = 0x8643
GL_LIGHT_MODEL_AMBIENT = 0x0B53
GL_OPERAND0_ALPHA = 0x8598
GL_FOG_COORD_ARRAY_BUFFER_BINDING = 0x889D
GL_RGBA16UI = 0x8D76
GL_AMBIENT = 0x1200
GL_DEPTH_CLAMP = 0x864F
GL_DEBUG_SOURCE_SHADER_COMPILER = 0x8248
GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5F
GL_DYNAMIC_COPY = 0x88EA
GL_TEXTURE_1D_ARRAY = 0x8C18
GL_TEXTURE_GATHER = 0x82A2
GL_EQUIV = 0x1509
GL_CURRENT_RASTER_INDEX = 0x0B05
GL_POLYGON_OFFSET_FILL = 0x8037
GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS = 0x8266
GL_COLOR_WRITEMASK = 0x0C23
GL_POINT_TOKEN = 0x0701
GL_TEXTURE8 = 0x84C8
GL_EQUAL = 0x0202
GL_R32I = 0x8235
GL_MAX_ARRAY_TEXTURE_LAYERS = 0x88FF
GL_TEXTURE1 = 0x84C1
GL_MAX_NUM_ACTIVE_VARIABLES = 0x92F7
GL_SECONDARY_COLOR_ARRAY_STRIDE = 0x845C
GL_UNSIGNED_INT_10F_11F_11F_REV = 0x8C3B
GL_SRC1_RGB = 0x8581
GL_PROGRAM = 0x82E2
GL_RETURN = 0x0102
GL_RGBA16 = 0x805B
GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56
GL_TEXTURE_2D = 0x0DE1
GL_TEXTURE_BINDING_1D = 0x8068
GL_MAX_GEOMETRY_ATOMIC_COUNTERS = 0x92D5
GL_MAX_GEOMETRY_OUTPUT_COMPONENTS = 0x9124
GL_SHADER_STORAGE_BUFFER_START = 0x90D4
GL_LINE_WIDTH_RANGE = 0x0B22
GL_PIXEL_MAP_I_TO_B = 0x0C74
GL_TESS_CONTROL_SHADER_BIT ::GLbitfield = 0x00000008
GL_VIEW_CLASS_BPTC_UNORM = 0x82D2
GL_ACCUM_BUFFER_BIT ::GLbitfield = 0x00000200
GL_SAMPLES_PASSED = 0x8914
GL_MAP2_GRID_SEGMENTS = 0x0DD3
GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS = 0x90C9
GL_READ_FRAMEBUFFER = 0x8CA8
GL_INDEX_CLEAR_VALUE = 0x0C20
GL_ENABLE_BIT ::GLbitfield = 0x00002000
GL_OBJECT_TYPE = 0x9112
GL_MAP2_VERTEX_3 = 0x0DB7
GL_MAX_DEPTH = 0x8280
GL_OUT_OF_MEMORY = 0x0505
GL_MAX_COMPUTE_UNIFORM_BLOCKS = 0x91BB
GL_MAX_COMPUTE_ATOMIC_COUNTERS = 0x8265
GL_COLOR_ATTACHMENT12 = 0x8CEC
GL_UNSIGNED_SHORT_4_4_4_4 = 0x8033
GL_GEOMETRY_SHADER_INVOCATIONS = 0x887F
GL_STENCIL_INDEX8 = 0x8D48
GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS = 0x90DC
GL_RGB8I = 0x8D8F
GL_AUTO_GENERATE_MIPMAP = 0x8295
GL_MAP1_VERTEX_3 = 0x0D97
GL_CLIP_DISTANCE2 = 0x3002
GL_TEXTURE18 = 0x84D2
GL_INT_2_10_10_10_REV = 0x8D9F
GL_UNSIGNED_INT_SAMPLER_3D = 0x8DD3
GL_DEPTH_ATTACHMENT = 0x8D00
GL_IMAGE_CLASS_11_11_10 = 0x82C2
GL_COMPRESSED_RGBA8_ETC2_EAC = 0x9278
GL_UNPACK_ALIGNMENT = 0x0CF5
GL_PROVOKING_VERTEX = 0x8E4F
GL_ONE_MINUS_SRC_ALPHA = 0x0303
GL_PIXEL_MAP_I_TO_I = 0x0C70
GL_CURRENT_TEXTURE_COORDS = 0x0B03
GL_COORD_REPLACE = 0x8862
GL_DIFFUSE = 0x1201
GL_TEXTURE_INTENSITY_SIZE = 0x8061
GL_DRAW_BUFFER6 = 0x882B
GL_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9102
GL_DEBUG_TYPE_PERFORMANCE = 0x8250
GL_LOCATION_INDEX = 0x930F
GL_CLEAR_TEXTURE = 0x9365
GL_TEXTURE_GEN_R = 0x0C62
GL_FLOAT_MAT2 = 0x8B5A
GL_UNSIGNED_NORMALIZED = 0x8C17
GL_VIEW_CLASS_16_BITS = 0x82CA
GL_QUAD_STRIP = 0x0008
GL_DYNAMIC_DRAW = 0x88E8
GL_SYNC_FENCE = 0x9116
GL_ONE_MINUS_SRC1_ALPHA = 0x88FB
GL_MANUAL_GENERATE_MIPMAP = 0x8294
GL_DEPTH_FUNC = 0x0B74
GL_VERTEX_SUBROUTINE_UNIFORM = 0x92EE
GL_COMPUTE_TEXTURE = 0x82A0
GL_MAP2_VERTEX_4 = 0x0DB8
GL_ARRAY_SIZE = 0x92FB
GL_FLOAT_MAT3x2 = 0x8B67
GL_RGBA8I = 0x8D8E
GL_RENDERBUFFER_SAMPLES = 0x8CAB
GL_TEXTURE_VIEW = 0x82B5
GL_VIEW_CLASS_RGTC1_RED = 0x82D0
GL_PIXEL_MAP_G_TO_G = 0x0C77
GL_INTENSITY8 = 0x804B
GL_PIXEL_MAP_A_TO_A_SIZE = 0x0CB9
GL_MAP2_GRID_DOMAIN = 0x0DD2
GL_N3F_V3F = 0x2A25
GL_MAX_VIEWPORTS = 0x825B
GL_COMPRESSED_R11_EAC = 0x9270
GL_SRC0_ALPHA = 0x8588
GL_INTERNALFORMAT_RED_TYPE = 0x8278
GL_DOMAIN = 0x0A02
GL_IMAGE_CUBE = 0x9050
GL_TEXTURE_1D = 0x0DE0
GL_RENDERBUFFER_WIDTH = 0x8D42
GL_POINT_SIZE = 0x0B11
GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST = 0x82AC
GL_VIEWPORT = 0x0BA2
GL_R16_SNORM = 0x8F98
GL_RGBA = 0x1908
GL_DRAW_PIXEL_TOKEN = 0x0705
GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE = 0x906B
GL_TEXTURE_SWIZZLE_G = 0x8E43
GL_TEXTURE_IMMUTABLE_FORMAT = 0x912F
GL_CLAMP = 0x2900
GL_TEXTURE31 = 0x84DF
GL_TEXTURE_GEN_MODE = 0x2500
GL_FOG_COORD_ARRAY_STRIDE = 0x8455
GL_MAX_SUBROUTINES = 0x8DE7
GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS = 0x92CC
GL_TEXTURE3 = 0x84C3
GL_PIXEL_MAP_I_TO_R = 0x0C72
GL_COMBINE_ALPHA = 0x8572
GL_SUBTRACT = 0x84E7
GL_DRAW_BUFFER2 = 0x8827
GL_RGB4 = 0x804F
GL_UNSIGNED_INT_SAMPLER_2D = 0x8DD2
GL_COLOR_ARRAY_TYPE = 0x8082
GL_COMBINE_RGB = 0x8571
GL_MAP1_TEXTURE_COORD_3 = 0x0D95
GL_ELEMENT_ARRAY_BUFFER = 0x8893
GL_COMPRESSED_SLUMINANCE = 0x8C4A
GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824D
GL_FULL_SUPPORT = 0x82B7
GL_SUBPIXEL_BITS = 0x0D50
GL_UNPACK_SKIP_ROWS = 0x0CF3
GL_VIEW_CLASS_64_BITS = 0x82C6
GL_SOURCE0_RGB = 0x8580
GL_TEXTURE_SWIZZLE_RGBA = 0x8E46
GL_IMAGE_FORMAT_COMPATIBILITY_TYPE = 0x90C7
GL_UNIFORM_BLOCK_INDEX = 0x8A3A
GL_MAX_DUAL_SOURCE_DRAW_BUFFERS = 0x88FC
GL_RGBA_INTEGER = 0x8D99
GL_MAX_COMBINED_IMAGE_UNIFORMS = 0x90CF
GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS = 0x90D9
GL_RGB16F = 0x881B
GL_MAX_COMBINED_UNIFORM_BLOCKS = 0x8A2E
GL_TESS_GEN_POINT_MODE = 0x8E79
GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY = 0x9061
GL_FRAMEBUFFER_BARRIER_BIT ::GLbitfield = 0x00000400
GL_POINTS = 0x0000
GL_INCR_WRAP = 0x8507
GL_ACTIVE_ATTRIBUTES = 0x8B89
GL_FIXED_ONLY = 0x891D
GL_MAX_UNIFORM_BLOCK_SIZE = 0x8A30
GL_TEXTURE5 = 0x84C5
GL_ALPHA12 = 0x803D
GL_GREEN_SCALE = 0x0D18
GL_INT_IMAGE_2D = 0x9058
GL_INTERNALFORMAT_GREEN_SIZE = 0x8272
GL_CURRENT_FOG_COORD = 0x8453
GL_SRC1_ALPHA = 0x8589
GL_PROXY_TEXTURE_1D = 0x8063
GL_PROXY_TEXTURE_CUBE_MAP_ARRAY = 0x900B
GL_TEXTURE_WRAP_S = 0x2802
GL_COMPRESSED_SIGNED_RG11_EAC = 0x9273
GL_X2D = 0x0600
GL_SAMPLER_BUFFER = 0x8DC2
GL_SRGB = 0x8C40
GL_STATIC_DRAW = 0x88E4
GL_TEXTURE_COORD_ARRAY_POINTER = 0x8092
GL_TEXTURE_2D_MULTISAMPLE = 0x9100
GL_INDEX_ARRAY = 0x8077
GL_T = 0x2001
GL_R11F_G11F_B10F = 0x8C3A
GL_RENDERBUFFER_ALPHA_SIZE = 0x8D53
GL_LESS = 0x0201
GL_TEXTURE_SHARED_SIZE = 0x8C3F
GL_INCR = 0x1E02
GL_DISPLAY_LIST = 0x82E7
GL_MAX_TEXTURE_SIZE = 0x0D33
GL_MAX_DRAW_BUFFERS = 0x8824
GL_TEXTURE_COMPRESSED_BLOCK_WIDTH = 0x82B1
GL_TEXTURE_ENV_MODE = 0x2200
GL_LIGHT3 = 0x4003
GL_TEXTURE_BLUE_SIZE = 0x805E
GL_UNSIGNED_INT_SAMPLER_2D_RECT = 0x8DD5
GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS = 0x8E82
GL_EDGE_FLAG_ARRAY = 0x8079
GL_IMAGE_BUFFER = 0x9051
GL_TEXTURE_WRAP_R = 0x8072
GL_QUERY_COUNTER_BITS = 0x8864
GL_DECAL = 0x2101
GL_RG32I = 0x823B
GL_NUM_COMPATIBLE_SUBROUTINES = 0x8E4A
GL_ATOMIC_COUNTER_BARRIER_BIT ::GLbitfield = 0x00001000
GL_INTERNALFORMAT_PREFERRED = 0x8270
GL_ONE_MINUS_DST_ALPHA = 0x0305
GL_COLOR_ATTACHMENT8 = 0x8CE8
GL_VIEW_CLASS_24_BITS = 0x82C9
GL_RGB565 = 0x8D62
GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS = 0x90CB
GL_DEBUG_OUTPUT = 0x92E0
GL_COMPRESSED_SIGNED_RED_RGTC1 = 0x8DBC
GL_PACK_SKIP_PIXELS = 0x0D04
GL_SECONDARY_COLOR_ARRAY_TYPE = 0x845B
GL_TEXTURE_GREEN_SIZE = 0x805D
GL_EXP2 = 0x0801
GL_LIGHT1 = 0x4001
GL_INT_IMAGE_3D = 0x9059
GL_MAX_COMBINED_DIMENSIONS = 0x8282
GL_DRAW_BUFFER13 = 0x8832
GL_DEPTH = 0x1801
GL_MAX_PATCH_VERTICES = 0x8E7D
GL_CULL_FACE_MODE = 0x0B45
GL_CLIP_PLANE5 = 0x3005
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6
GL_COMPRESSED_RGB = 0x84ED
GL_ALPHA_BIAS = 0x0D1D
GL_TEXTURE_GEN_S = 0x0C60
GL_FRAGMENT_SHADER_BIT ::GLbitfield = 0x00000002
GL_SIGNALED = 0x9119
GL_INT_IMAGE_2D_ARRAY = 0x905E
GL_MAP2_TEXTURE_COORD_1 = 0x0DB3
GL_FLOAT_MAT4x3 = 0x8B6A
GL_ACTIVE_RESOURCES = 0x92F5
GL_SAMPLER_2D = 0x8B5E
GL_VERTEX_BINDING_DIVISOR = 0x82D6
GL_TEXTURE_DEPTH_SIZE = 0x884A
GL_SRC0_RGB = 0x8580
GL_AND_REVERSE = 0x1502
GL_UNPACK_COMPRESSED_BLOCK_WIDTH = 0x9127
GL_CLEAR = 0x1500
GL_DEPTH_TEXTURE_MODE = 0x884B
GL_TEXTURE_MAX_LOD = 0x813B
GL_MAX_CLIENT_ATTRIB_STACK_DEPTH = 0x0D3B
GL_SAMPLE_ALPHA_TO_ONE = 0x809F
GL_FLOAT_VEC4 = 0x8B52
GL_FOG_DENSITY = 0x0B62
GL_LINE_TOKEN = 0x0702
GL_TIMEOUT_IGNORED = 0xffffffff
GL_SLUMINANCE = 0x8C46
GL_TEXTURE_FIXED_SAMPLE_LOCATIONS = 0x9107
GL_C4UB_V3F = 0x2A23
GL_SAMPLE_BUFFERS = 0x80A8
GL_NEAREST = 0x2600
GL_TEXTURE_VIEW_NUM_LAYERS = 0x82DE
GL_RG8 = 0x822B
GL_LINE_LOOP = 0x0002
GL_RGB8UI = 0x8D7D
GL_PIXEL_PACK_BUFFER = 0x88EB
GL_GEOMETRY_VERTICES_OUT = 0x8916
GL_DEBUG_CALLBACK_FUNCTION = 0x8244
GL_COMPRESSED_ALPHA = 0x84E9
GL_FLOAT_MAT2x3 = 0x8B65
GL_ALPHA_TEST = 0x0BC0
GL_R16UI = 0x8234
GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E1E
GL_SYNC_CONDITION = 0x9113
GL_COLOR_ATTACHMENT11 = 0x8CEB
GL_BOOL_VEC2 = 0x8B57
GL_READ_ONLY = 0x88B8
GL_PROGRAM_BINARY_RETRIEVABLE_HINT = 0x8257
GL_COMPUTE_SHADER = 0x91B9
GL_VIEW_CLASS_BPTC_FLOAT = 0x82D3
GL_R16F = 0x822D
GL_LIGHT6 = 0x4006
GL_SECONDARY_COLOR_ARRAY_SIZE = 0x845A
GL_SAMPLER_CUBE_SHADOW = 0x8DC5
GL_VIEWPORT_SUBPIXEL_BITS = 0x825C
GL_RED_BITS = 0x0D52
GL_COMPARE_REF_TO_TEXTURE = 0x884E
GL_STENCIL_BACK_REF = 0x8CA3
GL_PREVIOUS = 0x8578
GL_STENCIL_BACK_FUNC = 0x8800
GL_COMPRESSED_LUMINANCE = 0x84EA
GL_BITMAP_TOKEN = 0x0704
GL_CLIP_DISTANCE7 = 0x3007
GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT = 0x82B2
GL_UNSIGNED_SHORT_4_4_4_4_REV = 0x8365
GL_VIEW_CLASS_96_BITS = 0x82C5
GL_TEXTURE4 = 0x84C4
GL_ACCUM_GREEN_BITS = 0x0D59
GL_POINT_SIZE_RANGE = 0x0B12
GL_UNSIGNED_BYTE_3_3_2 = 0x8032
GL_TEXTURE_SWIZZLE_A = 0x8E45
GL_FRACTIONAL_ODD = 0x8E7B
GL_MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122
GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS = 0x90D8
GL_WRITE_ONLY = 0x88B9
GL_IMPLEMENTATION_COLOR_READ_TYPE = 0x8B9A
GL_SHADER_BINARY_FORMATS = 0x8DF8
GL_COMPRESSED_RED = 0x8225
GL_PIXEL_MAP_A_TO_A = 0x0C79
GL_TEXTURE_COMPONENTS = 0x1003
GL_INVALID_VALUE = 0x0501
GL_GEOMETRY_SUBROUTINE_UNIFORM = 0x92F1
GL_CLAMP_READ_COLOR = 0x891C
GL_ACCUM = 0x0100
GL_RGB_SCALE = 0x8573
GL_PIXEL_MAP_S_TO_S_SIZE = 0x0CB1
GL_CURRENT_RASTER_SECONDARY_COLOR = 0x845F
GL_NUM_SAMPLE_COUNTS = 0x9380
GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST = 0x82AD
GL_RASTERIZER_DISCARD = 0x8C89
GL_VERTEX_ARRAY_TYPE = 0x807B
GL_SRGB8 = 0x8C41
GL_SINGLE_COLOR = 0x81F9
GL_RG_SNORM = 0x8F91
GL_UNSIGNED_INT_IMAGE_2D_RECT = 0x9065
GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8A33
GL_LUMINANCE = 0x1909
GL_RGB32F = 0x8815
GL_REPLACE = 0x1E01
GL_MATRIX_MODE = 0x0BA0
GL_DEPTH_COMPONENT = 0x1902
GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8A31
GL_OBJECT_PLANE = 0x2501
GL_WEIGHT_ARRAY_BUFFER_BINDING = 0x889E
GL_RGBA8 = 0x8058
GL_SAMPLE_SHADING = 0x8C36
GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS = 0x9314
GL_TEXTURE_GEN_Q = 0x0C63
GL_TEXTURE_DEPTH_TYPE = 0x8C16
GL_MAX_TESS_PATCH_COMPONENTS = 0x8E84
GL_SAMPLER_CUBE_MAP_ARRAY = 0x900C
GL_TEXTURE_STACK_DEPTH = 0x0BA5
GL_SCISSOR_TEST = 0x0C11
GL_LIGHT2 = 0x4002
GL_STEREO = 0x0C33
GL_TEXTURE_COMPRESSED_IMAGE_SIZE = 0x86A0
GL_AUTO_NORMAL = 0x0D80
GL_TEXTURE_LUMINANCE_TYPE = 0x8C14
GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS = 0x8DE1
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER = 0x92CA
GL_TEXTURE22 = 0x84D6
GL_IMAGE_CLASS_1_X_8 = 0x82C1
GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES = 0x92C6
GL_CLAMP_TO_EDGE = 0x812F
GL_CLIP_DISTANCE6 = 0x3006
GL_ZOOM_X = 0x0D16
GL_DRAW_BUFFER0 = 0x8825
GL_FRAGMENT_INTERPOLATION_OFFSET_BITS = 0x8E5D
GL_ACTIVE_TEXTURE = 0x84E0
GL_UNSIGNED_INT_VEC2 = 0x8DC6
GL_MAX_EVAL_ORDER = 0x0D30
GL_TEXTURE_DEPTH = 0x8071
GL_FRONT_RIGHT = 0x0401
GL_MAX_COMBINED_ATOMIC_COUNTERS = 0x92D7
GL_DEBUG_LOGGED_MESSAGES = 0x9145
GL_DEPTH_RANGE = 0x0B70
GL_ACTIVE_PROGRAM = 0x8259
GL_DEBUG_SOURCE_API = 0x8246
GL_X4_BYTES = 0x1409
GL_NORMAL_ARRAY = 0x8075
GL_BLEND_SRC_RGB = 0x80C9
GL_LINE_RESET_TOKEN = 0x0707
GL_MAP_INVALIDATE_BUFFER_BIT ::GLbitfield = 0x0008
GL_ONE = 1
GL_DEBUG_TYPE_MARKER = 0x8268
GL_STENCIL_PASS_DEPTH_PASS = 0x0B96
GL_NO_ERROR = 0
GL_SMOOTH_POINT_SIZE_RANGE = 0x0B12
GL_PROXY_TEXTURE_2D_ARRAY = 0x8C1B
GL_AUX_BUFFERS = 0x0C00
GL_MAX_TEXTURE_STACK_DEPTH = 0x0D39
GL_CLIP_DISTANCE4 = 0x3004
GL_DOUBLE_VEC3 = 0x8FFD
GL_LEQUAL = 0x0203
GL_TIMESTAMP = 0x8E28
GL_POINT_SIZE_MAX = 0x8127
GL_TESS_EVALUATION_SHADER_BIT ::GLbitfield = 0x00000010
GL_MAX_TEXTURE_COORDS = 0x8871
GL_IMAGE_BINDING_LAYER = 0x8F3D
GL_NONE = 0
GL_BUFFER_SIZE = 0x8764
GL_PIXEL_MAP_B_TO_B = 0x0C78
GL_INT_VEC4 = 0x8B55
GL_MAX_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5C
GL_RGB16_SNORM = 0x8F9A
GL_OR_INVERTED = 0x150D
GL_SAMPLE_MASK = 0x8E51
GL_INTERNALFORMAT_GREEN_TYPE = 0x8279
GL_TESS_GEN_VERTEX_ORDER = 0x8E78
GL_PACK_SKIP_ROWS = 0x0D03
GL_NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2
GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES = 0x8F39
GL_RESCALE_NORMAL = 0x803A
GL_DEPTH_COMPONENT24 = 0x81A6
GL_BACK_LEFT = 0x0402
GL_MAP2_TEXTURE_COORD_4 = 0x0DB6
GL_COLOR = 0x1800
GL_INVALID_INDEX = 0xFFFFFFFF
GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER = 0x84F0
GL_CONSTANT = 0x8576
GL_INT_VEC2 = 0x8B53
GL_PROGRAM_OUTPUT = 0x92E4
GL_UNSIGNED_SHORT = 0x1403
GL_VERTEX_ARRAY_BINDING = 0x85B5
GL_RED_SNORM = 0x8F90
GL_MODULATE = 0x2100
GL_UNSIGNED_INT = 0x1405
GL_LUMINANCE4_ALPHA4 = 0x8043
GL_X3D_COLOR = 0x0602
GL_COMPUTE_LOCAL_WORK_SIZE = 0x8267
GL_COMPUTE_WORK_GROUP_SIZE = 0x8267
GL_SHADER_STORAGE_BUFFER_SIZE = 0x90D5
GL_TEXTURE_BUFFER = 0x8C2A
GL_POSITION = 0x1203
GL_COMPRESSED_INTENSITY = 0x84EC
GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C
GL_COLOR_CLEAR_VALUE = 0x0C22
GL_R3_G3_B2 = 0x2A10
GL_MAX_VARYING_VECTORS = 0x8DFC
GL_IMAGE_CLASS_4_X_32 = 0x82B9
GL_NUM_SHADING_LANGUAGE_VERSIONS = 0x82E9
GL_MIN_MAP_BUFFER_ALIGNMENT = 0x90BC
GL_DELETE_STATUS = 0x8B80
GL_UNSIGNED_INT_VEC3 = 0x8DC7
GL_TESS_EVALUATION_SUBROUTINE = 0x92EA
GL_PIXEL_MAP_G_TO_G_SIZE = 0x0CB7
GL_FLOAT_MAT4 = 0x8B5C
GL_BACK_RIGHT = 0x0403
GL_LUMINANCE12_ALPHA4 = 0x8046
GL_GEOMETRY_SHADER_BIT ::GLbitfield = 0x00000004
GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS = 0x90CC
GL_VERTEX_TEXTURE = 0x829B
GL_FRONT_AND_BACK = 0x0408
GL_ACTIVE_UNIFORM_BLOCKS = 0x8A36
GL_RENDERER = 0x1F01
GL_COLOR_ATTACHMENT10 = 0x8CEA
GL_FOG_COORDINATE_SOURCE = 0x8450
GL_IMAGE_BINDING_LEVEL = 0x8F3B
GL_MAX_DEBUG_GROUP_STACK_DEPTH = 0x826C
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3
GL_ATTRIB_STACK_DEPTH = 0x0BB0
GL_LINE_STIPPLE_REPEAT = 0x0B26
GL_POLYGON_SMOOTH_HINT = 0x0C53
GL_LUMINANCE4 = 0x803F
GL_SMOOTH_POINT_SIZE_GRANULARITY = 0x0B13
GL_OR_REVERSE = 0x150B
GL_MAP2_TEXTURE_COORD_2 = 0x0DB4
GL_FOG_MODE = 0x0B65
GL_TOP_LEVEL_ARRAY_SIZE = 0x930C
GL_LUMINANCE16 = 0x8042
GL_OPERAND0_RGB = 0x8590
GL_STENCIL_BUFFER_BIT ::GLbitfield = 0x00000400
GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS = 0x8F39
GL_MAX_PROJECTION_STACK_DEPTH = 0x0D38
GL_ARRAY_BUFFER = 0x8892
GL_POLYGON_SMOOTH = 0x0B41
GL_FRAMEBUFFER_ATTACHMENT_LAYERED = 0x8DA7
GL_EDGE_FLAG_ARRAY_POINTER = 0x8093
GL_FOG_COORD = 0x8451
GL_TEXTURE23 = 0x84D7
GL_INDEX_LOGIC_OP = 0x0BF1
GL_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x9308
GL_SHADER_IMAGE_LOAD = 0x82A4
GL_DOT3_RGBA = 0x86AF
GL_VERTEX_ATTRIB_ARRAY_LONG = 0x874E
GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS = 0x91BC
GL_IMAGE_2D_ARRAY = 0x9053
GL_NORMAL_ARRAY_POINTER = 0x808F
GL_STENCIL_INDEX1 = 0x8D46
GL_TEXTURE11 = 0x84CB
GL_DRAW_INDIRECT_BUFFER = 0x8F3F
GL_COLOR_ATTACHMENT3 = 0x8CE3
GL_INT_IMAGE_CUBE_MAP_ARRAY = 0x905F
GL_BLUE_SCALE = 0x0D1A
GL_DEPTH_BITS = 0x0D56
GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803
GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS = 0x8DA8
GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212
GL_UNIFORM_SIZE = 0x8A38
GL_TESS_CONTROL_SUBROUTINE = 0x92E9
GL_PROGRAM_INPUT = 0x92E3
GL_TIMEOUT_EXPIRED = 0x911B
GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE = 0x90C8
GL_LIGHT_MODEL_TWO_SIDE = 0x0B52
GL_INT_SAMPLER_2D_ARRAY = 0x8DCF
GL_IMAGE_CLASS_2_X_16 = 0x82BD
GL_READ_BUFFER = 0x0C02
GL_SLUMINANCE_ALPHA = 0x8C44
GL_RGB16UI = 0x8D77
GL_MAX_DEBUG_MESSAGE_LENGTH = 0x9143
GL_NORMALIZE = 0x0BA1
GL_CURRENT_COLOR = 0x0B00
GL_FRAMEBUFFER_COMPLETE = 0x8CD5
GL_FASTEST = 0x1101
GL_INDEX_ARRAY_POINTER = 0x8091
GL_UNIFORM_BUFFER = 0x8A11
GL_MULTISAMPLE_BIT ::GLbitfield = 0x20000000
GL_CURRENT_SECONDARY_COLOR = 0x8459
GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8A44
GL_DEBUG_SOURCE_OTHER = 0x824B
GL_MAP1_TEXTURE_COORD_1 = 0x0D93
GL_SHADER_STORAGE_BLOCK = 0x92E6
GL_QUERY_NO_WAIT = 0x8E14
GL_C4UB_V2F = 0x2A22
GL_AUX2 = 0x040B
GL_CURRENT_RASTER_POSITION_VALID = 0x0B08
GL_MAX_COLOR_ATTACHMENTS = 0x8CDF
GL_COLOR_MATERIAL = 0x0B57
GL_OFFSET = 0x92FC
GL_R16I = 0x8233
GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER = 0x90EC
GL_NAME_STACK_DEPTH = 0x0D70
GL_PACK_COMPRESSED_BLOCK_HEIGHT = 0x912C
GL_AND_INVERTED = 0x1504
GL_LIGHT7 = 0x4007
GL_DRAW_BUFFER3 = 0x8828
GL_NICEST = 0x1102
GL_MAX_GEOMETRY_IMAGE_UNIFORMS = 0x90CD
GL_TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8C8F
GL_MAP_READ_BIT ::GLbitfield = 0x0001
GL_PIXEL_MAP_I_TO_G = 0x0C73
GL_MAX_VERTEX_UNIFORM_BLOCKS = 0x8A2B
GL_IMAGE_PIXEL_TYPE = 0x82AA
GL_KEEP = 0x1E00
GL_GEOMETRY_SUBROUTINE = 0x92EB
GL_SOURCE0_ALPHA = 0x8588
GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8C80
GL_MAX_CLIP_DISTANCES = 0x0D32
GL_INVALID_FRAMEBUFFER_OPERATION = 0x0506
GL_BUFFER_VARIABLE = 0x92E5
GL_ZERO = 0
GL_ACCUM_CLEAR_VALUE = 0x0B80
GL_FRAGMENT_SUBROUTINE = 0x92EC
GL_MAX_SAMPLES = 0x8D57
GL_INDEX_ARRAY_STRIDE = 0x8086
GL_MAX_HEIGHT = 0x827F
GL_PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69
GL_COLOR_ATTACHMENT4 = 0x8CE4
GL_AMBIENT_AND_DIFFUSE = 0x1602
GL_COLOR_ATTACHMENT9 = 0x8CE9
GL_DRAW_BUFFER = 0x0C01
GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x84F1
GL_BYTE = 0x1400
GL_COMPARE_R_TO_TEXTURE = 0x884E
GL_GREATER = 0x0204
GL_TEXTURE_GATHER_SHADOW = 0x82A3
GL_COPY = 0x1503
GL_NORMAL_ARRAY_BUFFER_BINDING = 0x8897
GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS = 0x90DA
GL_FRAMEBUFFER_SRGB = 0x8DB9
GL_ADD_SIGNED = 0x8574
GL_READ_PIXELS_TYPE = 0x828E
GL_DONT_CARE = 0x1100
GL_IMAGE_BINDING_NAME = 0x8F3A
GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211
GL_MAX_ELEMENTS_VERTICES = 0x80E8
GL_UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8DD7
GL_DEBUG_SEVERITY_HIGH = 0x9146
GL_DST_ALPHA = 0x0304
GL_INTERNALFORMAT_ALPHA_TYPE = 0x827B
GL_DEPTH_STENCIL_TEXTURE_MODE = 0x90EA
GL_IS_ROW_MAJOR = 0x9300
GL_RGBA32F = 0x8814
GL_ANY_SAMPLES_PASSED = 0x8C2F
GL_MAX_LIST_NESTING = 0x0B31
GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8A43
GL_POINT_DISTANCE_ATTENUATION = 0x8129
GL_COLOR_MATERIAL_PARAMETER = 0x0B56
GL_LIGHTING = 0x0B50
GL_UNIFORM_BLOCK = 0x92E2
GL_INTERNALFORMAT_SUPPORTED = 0x826F
GL_MAX_VERTEX_ATTRIB_BINDINGS = 0x82DA
GL_ELEMENT_ARRAY_BUFFER_BINDING = 0x8895
GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910C
GL_TOP_LEVEL_ARRAY_STRIDE = 0x930D
GL_AND = 0x1501
GL_SPOT_DIRECTION = 0x1204
GL_MAX_FRAMEBUFFER_LAYERS = 0x9317
GL_PIXEL_MAP_I_TO_B_SIZE = 0x0CB4
GL_ATOMIC_COUNTER_BUFFER_START = 0x92C2
GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS = 0x92DC
GL_UNSIGNED_INT_SAMPLER_BUFFER = 0x8DD8
GL_COPY_PIXEL_TOKEN = 0x0706
GL_TRIANGLE_FAN = 0x0006
GL_RENDERBUFFER_DEPTH_SIZE = 0x8D54
GL_DISPATCH_INDIRECT_BUFFER = 0x90EE
GL_MAX_SERVER_WAIT_TIMEOUT = 0x9111
GL_DEBUG_SOURCE_THIRD_PARTY = 0x8249
GL_FRAMEBUFFER_DEFAULT_HEIGHT = 0x9311
GL_TEXTURE_VIEW_MIN_LAYER = 0x82DD
GL_PATCH_VERTICES = 0x8E72
GL_DOUBLE_MAT3x4 = 0x8F4C
GL_UNSIGNED_BYTE_2_3_3_REV = 0x8362
GL_VIEW_CLASS_S3TC_DXT5_RGBA = 0x82CF
GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS = 0x92CE
GL_RG8UI = 0x8238
GL_SHADER_STORAGE_BUFFER = 0x90D2
GL_GREEN_BIAS = 0x0D19
GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT ::GLbitfield = 0x00000001
GL_RGB12 = 0x8053
GL_POINT_SIZE_GRANULARITY = 0x0B13
GL_FEEDBACK_BUFFER_SIZE = 0x0DF1
GL_TRUE = 1
GL_PACK_SKIP_IMAGES = 0x806B
GL_DOUBLE_MAT4 = 0x8F48
GL_INTERPOLATE = 0x8575
GL_RGB32I = 0x8D83
GL_NUM_PROGRAM_BINARY_FORMATS = 0x87FE
GL_RGB8 = 0x8051
GL_COMPRESSED_LUMINANCE_ALPHA = 0x84EB
GL_FRAMEBUFFER_DEFAULT_LAYERS = 0x9312
GL_T2F_C3F_V3F = 0x2A2A
GL_TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519
GL_FOG_COORD_ARRAY_POINTER = 0x8456
GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS = 0x8F9F
GL_RENDER_MODE = 0x0C40
GL_QUADRATIC_ATTENUATION = 0x1209
GL_T2F_N3F_V3F = 0x2A2B
GL_UNPACK_ROW_LENGTH = 0x0CF2
GL_LINE = 0x1B01
GL_LINE_SMOOTH_HINT = 0x0C52
GL_STREAM_DRAW = 0x88E0
GL_MAP1_COLOR_4 = 0x0D90
GL_ALPHA_SCALE = 0x0D1C
GL_COMPRESSED_TEXTURE_FORMATS = 0x86A3
GL_FRAGMENT_TEXTURE = 0x829F
GL_FRAMEBUFFER_BLEND = 0x828B
GL_MAX_TESS_GEN_LEVEL = 0x8E7E
GL_MAX_VERTEX_ATTRIBS = 0x8869
GL_LINE_STRIP = 0x0003
GL_VERSION = 0x1F02
GL_CLIENT_VERTEX_ARRAY_BIT ::GLbitfield = 0x00000002
GL_PROJECTION_STACK_DEPTH = 0x0BA4
GL_VERTEX_ATTRIB_BINDING = 0x82D4
GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE = 0x82AE
GL_TEXTURE25 = 0x84D9
GL_SAMPLE_COVERAGE_VALUE = 0x80AA
GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645
GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS = 0x92D4
GL_BUFFER_DATA_SIZE = 0x9303
GL_TEXTURE_RED_TYPE = 0x8C10
GL_TEXTURE_2D_ARRAY = 0x8C1A
GL_CURRENT_FOG_COORDINATE = 0x8453
GL_CURRENT_BIT ::GLbitfield = 0x00000001
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER = 0x92C8
GL_MAX_SHADER_STORAGE_BLOCK_SIZE = 0x90DE
GL_FLOAT_MAT3x4 = 0x8B68
GL_SHORT = 0x1402
GL_POINT_BIT ::GLbitfield = 0x00000002
GL_POLYGON_BIT ::GLbitfield = 0x00000008
GL_QUERY_WAIT = 0x8E13
GL_BOOL = 0x8B56
GL_FRAMEBUFFER_RENDERABLE = 0x8289
GL_TRANSFORM_FEEDBACK_BUFFER_START = 0x8C84
GL_BLUE_BIAS = 0x0D1B
GL_DYNAMIC_READ = 0x88E9
GL_IMAGE_COMPATIBILITY_CLASS = 0x82A8
GL_TEXTURE20 = 0x84D4
GL_ACTIVE_SUBROUTINE_UNIFORMS = 0x8DE6
GL_SPECULAR = 0x1202
GL_RENDER = 0x1C00
GL_MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C
GL_INT_IMAGE_BUFFER = 0x905C
GL_FIXED = 0x140C
GL_FRAGMENT_SUBROUTINE_UNIFORM = 0x92F2
GL_VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88FE
GL_X3D_COLOR_TEXTURE = 0x0603
GL_IMAGE_CLASS_1_X_32 = 0x82BB
GL_VIEWPORT_BOUNDS_RANGE = 0x825D
GL_POINT_SMOOTH_HINT = 0x0C51
GL_DOT3_RGB = 0x86AE
GL_MAX_PIXEL_MAP_TABLE = 0x0D34
GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802
GL_TEXTURE_BINDING_RECTANGLE = 0x84F6
GL_WAIT_FAILED = 0x911D
GL_SHADER_STORAGE_BUFFER_BINDING = 0x90D3
GL_IMAGE_TEXEL_SIZE = 0x82A7
GL_RG8I = 0x8237
GL_CLIP_PLANE0 = 0x3000
GL_INDEX_ARRAY_BUFFER_BINDING = 0x8899
GL_CLIP_DISTANCE1 = 0x3001
GL_CURRENT_RASTER_TEXTURE_COORDS = 0x0B06
GL_COMPILE_AND_EXECUTE = 0x1301
GL_UNIFORM_BLOCK_DATA_SIZE = 0x8A40
GL_BLEND_SRC = 0x0BE1
GL_NEAREST_MIPMAP_LINEAR = 0x2702
GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY = 0x900F
GL_LUMINANCE16_ALPHA16 = 0x8048
GL_TEXTURE_ALPHA_TYPE = 0x8C13
GL_SPOT_EXPONENT = 0x1205
GL_BLEND_DST = 0x0BE0
GL_SHADE_MODEL = 0x0B54
GL_TEXTURE_COMPRESSION_HINT = 0x84EF
GL_UNIFORM_BLOCK_NAME_LENGTH = 0x8A41
GL_RGBA8UI = 0x8D7C
GL_TESS_EVALUATION_SUBROUTINE_UNIFORM = 0x92F0
GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0
GL_TRANSPOSE_TEXTURE_MATRIX = 0x84E5
GL_SAMPLER_2D_RECT = 0x8B63
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2
GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276
GL_CLIP_PLANE1 = 0x3001
GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622
GL_FEEDBACK_BUFFER_POINTER = 0x0DF0
GL_UNIFORM_BLOCK_BINDING = 0x8A3F
GL_UNIFORM_NAME_LENGTH = 0x8A39
GL_TIME_ELAPSED = 0x88BF
GL_VERTEX_ARRAY_STRIDE = 0x807C
GL_NUM_EXTENSIONS = 0x821D
GL_MAX_CLIP_PLANES = 0x0D32
GL_READ_PIXELS = 0x828C
GL_DEPTH_WRITEMASK = 0x0B72
GL_LINEAR = 0x2601
GL_RGB10_A2 = 0x8059
GL_INDEX_WRITEMASK = 0x0C21
GL_MIN_SAMPLE_SHADING_VALUE = 0x8C37
GL_FOG_COORD_ARRAY = 0x8457
GL_UNIFORM_OFFSET = 0x8A3B
GL_SOURCE2_RGB = 0x8582
GL_TEXTURE_SWIZZLE_B = 0x8E44
GL_COMBINE = 0x8570
GL_FLOAT_VEC3 = 0x8B51
GL_DRAW_BUFFER5 = 0x882A
GL_TEXTURE_ENV_COLOR = 0x2201
GL_MEDIUM_FLOAT = 0x8DF1
GL_EXP = 0x0800
GL_DST_COLOR = 0x0306
GL_TEXTURE_WIDTH = 0x1000
GL_UNSIGNED_INT_2_10_10_10_REV = 0x8368
GL_MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49
GL_UNIFORM_BUFFER_BINDING = 0x8A28
GL_TEXTURE_BUFFER_SIZE = 0x919E
GL_TRANSFORM_FEEDBACK_VARYING = 0x92F4
GL_SRGB_ALPHA = 0x8C42
GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH = 0x8E49
GL_V2F = 0x2A20
GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING = 0x889C
GL_NEVER = 0x0200
GL_SLUMINANCE8 = 0x8C47
GL_RED_INTEGER = 0x8D94
GL_SAMPLER_2D_MULTISAMPLE = 0x9108
GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS = 0x8E8A
GL_RENDERBUFFER_INTERNAL_FORMAT = 0x8D44
GL_COLOR_ATTACHMENT13 = 0x8CED
GL_UNPACK_IMAGE_HEIGHT = 0x806E
GL_SYNC_GPU_COMMANDS_COMPLETE = 0x9117
GL_PROXY_TEXTURE_2D = 0x8064
GL_MAP_WRITE_BIT ::GLbitfield = 0x0002
GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277
GL_DEBUG_TYPE_OTHER = 0x8251
GL_VIEW_CLASS_RGTC2_RG = 0x82D1
GL_TEXTURE_COMPARE_MODE = 0x884C
GL_TEXTURE0 = 0x84C0
GL_ACTIVE_UNIFORMS = 0x8B86
GL_ALPHA4 = 0x803B
GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET = 0x8E5E
GL_MAP2_COLOR_4 = 0x0DB0
GL_CURRENT_QUERY = 0x8865
GL_SAMPLER_1D = 0x8B5D
GL_T2F_V3F = 0x2A27
GL_FEEDBACK = 0x1C01
GL_LINES_ADJACENCY = 0x000A
GL_INT_SAMPLER_CUBE = 0x8DCC
GL_STENCIL_RENDERABLE = 0x8288
GL_MAP2_NORMAL = 0x0DB2
GL_BACK = 0x0405
GL_SMOOTH = 0x1D01
GL_BGR = 0x80E0
GL_STENCIL = 0x1802
GL_REFERENCED_BY_VERTEX_SHADER = 0x9306
GL_TEXTURE_3D = 0x806F
GL_UNPACK_SWAP_BYTES = 0x0CF0
GL_PROGRAM_SEPARABLE = 0x8258
GL_ALWAYS = 0x0207
GL_UNSIGNED_INT_IMAGE_BUFFER = 0x9067
GL_RENDERBUFFER_HEIGHT = 0x8D43
GL_COLOR_SUM = 0x8458
GL_TESS_EVALUATION_TEXTURE = 0x829D
GL_LINEAR_ATTENUATION = 0x1208
GL_PIXEL_MAP_R_TO_R = 0x0C76
GL_DOUBLE_MAT4x2 = 0x8F4D
GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D
GL_AUX0 = 0x0409
GL_ZOOM_Y = 0x0D17
GL_UNIFORM_BUFFER_START = 0x8A29
GL_CONTEXT_PROFILE_MASK = 0x9126
GL_TEXTURE_VIEW_MIN_LEVEL = 0x82DB
GL_SRC2_ALPHA = 0x858A
GL_CURRENT_NORMAL = 0x0B02
GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243
GL_SELECT = 0x1C02
GL_MAX_TEXTURE_UNITS = 0x84E2
GL_COLOR_ARRAY_BUFFER_BINDING = 0x8898
GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS = 0x90D6
GL_TRANSFORM_FEEDBACK_BARRIER_BIT ::GLbitfield = 0x00000800
GL_SAMPLE_POSITION = 0x8E50
GL_UNSIGNED_INT_IMAGE_3D = 0x9064
GL_R8 = 0x8229
GL_LIST_INDEX = 0x0B33
GL_SHININESS = 0x1601
GL_CLAMP_FRAGMENT_COLOR = 0x891B
GL_TEXTURE_COMPARE_FUNC = 0x884D
GL_DECR = 0x1E03
GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER = 0x8CDB
GL_MAX_TESS_CONTROL_INPUT_COMPONENTS = 0x886C
GL_INTERNALFORMAT_RED_SIZE = 0x8271
GL_MAX_SAMPLE_MASK_WORDS = 0x8E59
GL_DISPATCH_INDIRECT_BUFFER_BINDING = 0x90EF
GL_AUX3 = 0x040C
GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210
GL_ALPHA_TEST_FUNC = 0x0BC1
GL_SAMPLER_1D_ARRAY = 0x8DC0
GL_PIXEL_MAP_I_TO_G_SIZE = 0x0CB3
GL_TEXTURE_BINDING_2D_ARRAY = 0x8C1D
GL_CLEAR_BUFFER = 0x82B4
GL_STENCIL_VALUE_MASK = 0x0B93
GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS = 0x886D
GL_RGB32UI = 0x8D71
GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872
GL_COLOR_ATTACHMENT15 = 0x8CEF
GL_PIXEL_UNPACK_BUFFER = 0x88EC
GL_UNIFORM_BARRIER_BIT ::GLbitfield = 0x00000004
GL_MAP2_TEXTURE_COORD_3 = 0x0DB5
GL_BLEND = 0x0BE2
GL_CONSTANT_COLOR = 0x8001
GL_ONE_MINUS_CONSTANT_COLOR = 0x8002
GL_CONSTANT_ALPHA = 0x8003
GL_ONE_MINUS_CONSTANT_ALPHA = 0x8004
GL_BLEND_COLOR = 0x8005
GL_FUNC_ADD = 0x8006
GL_MIN = 0x8007
GL_MAX = 0x8008
GL_FUNC_SUBTRACT = 0x800A
GL_FUNC_REVERSE_SUBTRACT = 0x800B
GL_IMAGE_BINDING_ACCESS = 0x8F3E
GL_GREEN = 0x1904
GL_IMAGE_BINDING_LAYERED = 0x8F3C
GL_PIXEL_PACK_BUFFER_BINDING = 0x88ED
GL_RGB = 0x1907
GL_MAX_COMPUTE_WORK_GROUP_COUNT = 0x91BE
GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS = 0x90EB
GL_ALPHA_INTEGER = 0x8D97
GL_DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247
GL_MAX_GEOMETRY_INPUT_COMPONENTS = 0x9123
GL_NORMAL_MAP = 0x8511
GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH = 0x8A35
GL_TEXTURE_MIN_FILTER = 0x2801
GL_UNSIGNED_INT_10_10_10_2 = 0x8036
GL_FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B
GL_RENDERBUFFER_GREEN_SIZE = 0x8D51
GL_SRC1_COLOR = 0x88F9
GL_CULL_FACE = 0x0B44
GL_STENCIL_FAIL = 0x0B94
GL_REFERENCED_BY_FRAGMENT_SHADER = 0x930A
GL_COMPRESSED_SRGB = 0x8C48
GL_DRAW_BUFFER1 = 0x8826
GL_ISOLINES = 0x8E7A
GL_TEXTURE_LUMINANCE_SIZE = 0x8060
GL_COLOR_ARRAY_POINTER = 0x8090
GL_ACTIVE_SUBROUTINES = 0x8DE5
GL_TEXTURE_BINDING_2D = 0x8069
GL_ALPHA = 0x1906
GL_ATOMIC_COUNTER_BUFFER_BINDING = 0x92C1
GL_UNSIGNED_INT_IMAGE_2D_ARRAY = 0x9069
GL_MAX_COMPUTE_LOCAL_INVOCATIONS = 0x90EB
GL_STREAM_READ = 0x88E1
GL_TEXTURE_WRAP_T = 0x2803
GL_ALL_ATTRIB_BITS = 0xFFFFFFFF
GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE = 0x92C4
GL_UNSIGNED_INT_8_8_8_8 = 0x8035
GL_TEXTURE29 = 0x84DD
GL_TEXTURE_UPDATE_BARRIER_BIT ::GLbitfield = 0x00000100
GL_INT_SAMPLER_BUFFER = 0x8DD0
GL_Q = 0x2003
GL_INDEX_BITS = 0x0D51
GL_SPOT_CUTOFF = 0x1206
GL_PACK_LSB_FIRST = 0x0D01
GL_BOOL_VEC4 = 0x8B59
GL_STENCIL_INDEX = 0x1901
GL_TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8C85
GL_SRC2_RGB = 0x8582
GL_MODELVIEW = 0x1700
GL_POLYGON_OFFSET_UNITS = 0x2A00
GL_PROXY_TEXTURE_1D_ARRAY = 0x8C19
GL_UNDEFINED_VERTEX = 0x8260
GL_UNPACK_COMPRESSED_BLOCK_HEIGHT = 0x9128
GL_TEXTURE9 = 0x84C9
GL_V3F = 0x2A21
GL_FRAGMENT_DEPTH = 0x8452
GL_DEPTH_RENDERABLE = 0x8287
GL_FOG_COLOR = 0x0B66
GL_PROGRAM_POINT_SIZE = 0x8642
GL_MAP_COLOR = 0x0D10
GL_DEBUG_SEVERITY_MEDIUM = 0x9147
GL_NORMAL_ARRAY_STRIDE = 0x807F
GL_TEXTURE_COORD_ARRAY_SIZE = 0x8088
GL_BLOCK_INDEX = 0x92FD
GL_IMAGE_BINDING_FORMAT = 0x906E
GL_STENCIL_REF = 0x0B97
GL_CLIENT_ALL_ATTRIB_BITS = 0xFFFFFFFF
GL_DOUBLE_VEC4 = 0x8FFE
GL_DEPTH_SCALE = 0x0D1E
GL_VIEWPORT_BIT ::GLbitfield = 0x00000800
GL_COMPRESSED_SIGNED_R11_EAC = 0x9271
GL_CLAMP_VERTEX_COLOR = 0x891A
GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION = 0x8E4C
GL_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D5
GL_UNSIGNED_INT_SAMPLER_1D_ARRAY = 0x8DD6
GL_UNSIGNED_SHORT_1_5_5_5_REV = 0x8366
GL_EMISSION = 0x1600
GL_CURRENT_RASTER_COLOR = 0x0B04
GL_TEXTURE_RESIDENT = 0x8067
GL_COMPRESSED_SRGB8_ETC2 = 0x9275
GL_MAX_NUM_COMPATIBLE_SUBROUTINES = 0x92F8
GL_TEXTURE17 = 0x84D1
GL_CONTEXT_FLAG_DEBUG_BIT ::GLbitfield = 0x00000002
GL_TEXTURE16 = 0x84D0
GL_DITHER = 0x0BD0
GL_MAP1_TEXTURE_COORD_2 = 0x0D94
GL_BLEND_DST_RGB = 0x80C8
GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215
GL_S = 0x2000
GL_COMPRESSED_RG = 0x8226
GL_NOTEQUAL = 0x0205
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A
GL_NOR = 0x1508
GL_ONE_MINUS_SRC1_COLOR = 0x88FA
GL_LINEAR_MIPMAP_NEAREST = 0x2701
GL_SEPARATE_ATTRIBS = 0x8C8D
GL_MAX_INTEGER_SAMPLES = 0x9110
GL_STENCIL_COMPONENTS = 0x8285
GL_FRAMEBUFFER_BINDING = 0x8CA6
GL_INTERLEAVED_ATTRIBS = 0x8C8C
GL_UNIFORM_MATRIX_STRIDE = 0x8A3D
GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE = 0x82AF
GL_T4F_C4F_N3F_V4F = 0x2A2D
GL_RED_BIAS = 0x0D15
GL_OPERAND2_ALPHA = 0x859A
GL_SRC_COLOR = 0x0300
GL_POLYGON_OFFSET_LINE = 0x2A02
GL_REFERENCED_BY_COMPUTE_SHADER = 0x930B
GL_TYPE = 0x92FA
GL_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87
GL_TEXTURE_BINDING_1D_ARRAY = 0x8C1C
GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS = 0x8E81
GL_POLYGON_STIPPLE_BIT ::GLbitfield = 0x00000010
GL_MAX_FRAMEBUFFER_SAMPLES = 0x9318
GL_PROJECTION_MATRIX = 0x0BA7
GL_TRIANGLE_STRIP_ADJACENCY = 0x000D
GL_MULTISAMPLE = 0x809D
GL_MAX_NAME_LENGTH = 0x92F6
GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS = 0x8C29
GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY = 0x9103
GL_STENCIL_BACK_VALUE_MASK = 0x8CA4
GL_RGBA16I = 0x8D88
GL_COLOR_INDEXES = 0x1603
GL_INVALID_ENUM = 0x0500
GL_UNSIGNED_INT_IMAGE_2D = 0x9063
GL_NOOP = 0x1505
GL_INDEX_SHIFT = 0x0D12
GL_INDEX_ARRAY_TYPE = 0x8085
GL_MAX_WIDTH = 0x827E
GL_ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A
GL_SAMPLES = 0x80A9
GL_TEXTURE14 = 0x84CE
GL_BUFFER_MAPPED = 0x88BC
GL_TRANSPOSE_COLOR_MATRIX = 0x84E6
GL_LOWER_LEFT = 0x8CA1
GL_COLOR_ATTACHMENT6 = 0x8CE6
GL_FRAMEBUFFER = 0x8D40
GL_MAX_COMPUTE_SHARED_MEMORY_SIZE = 0x8262
GL_TEXTURE_COMPRESSED = 0x86A1
GL_RG = 0x8227
GL_POINT = 0x1B00
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7
GL_PROGRAM_PIPELINE_BINDING = 0x825A
GL_SHADER = 0x82E1
GL_INT_IMAGE_1D_ARRAY = 0x905D
GL_PROXY_TEXTURE_RECTANGLE = 0x84F7
GL_ATOMIC_COUNTER_BUFFER_SIZE = 0x92C3
GL_SAMPLE_ALPHA_TO_COVERAGE = 0x809E
GL_FLOAT_MAT4x2 = 0x8B69
GL_MAX_LABEL_LENGTH = 0x82E8
GL_VIEW_CLASS_S3TC_DXT3_RGBA = 0x82CE
GL_UNSIGNED_INT_IMAGE_1D = 0x9062
GL_TEXTURE_COORD_ARRAY = 0x8078
GL_FOG = 0x0B60
GL_FRAGMENT_SHADER = 0x8B30
GL_RGB_INTEGER = 0x8D98
GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW = 0x900D
GL_CLIENT_PIXEL_STORE_BIT ::GLbitfield = 0x00000001
GL_ATOMIC_COUNTER_BUFFER_INDEX = 0x9301
GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS = 0x8DE8
GL_CAVEAT_SUPPORT = 0x82B8
GL_RGBA16_SNORM = 0x8F9B
GL_CLIP_DISTANCE3 = 0x3003
GL_SAMPLE_COVERAGE = 0x80A0
GL_INTERNALFORMAT_BLUE_TYPE = 0x827A
GL_SHADER_TYPE = 0x8B4F
GL_ONE_MINUS_DST_COLOR = 0x0307
GL_RG_INTEGER = 0x8228
GL_HALF_FLOAT = 0x140B
GL_SELECTION_BUFFER_POINTER = 0x0DF3
GL_CONTEXT_FLAGS = 0x821E
GL_UNPACK_SKIP_IMAGES = 0x806D
GL_MAX_MODELVIEW_STACK_DEPTH = 0x0D36
GL_STACK_UNDERFLOW = 0x0504
GL_READ_WRITE = 0x88BA
GL_LUMINANCE8 = 0x8040
GL_QUERY_BY_REGION_NO_WAIT = 0x8E16
GL_VIEWPORT_INDEX_PROVOKING_VERTEX = 0x825F
GL_INVERT = 0x150A
GL_LIGHT5 = 0x4005
GL_FLOAT_VEC2 = 0x8B50
GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS = 0x8E7F
GL_INTERNALFORMAT_DEPTH_SIZE = 0x8275
GL_SCISSOR_BIT ::GLbitfield = 0x00080000
GL_CLIENT_ATTRIB_STACK_DEPTH = 0x0BB1
GL_BUFFER_USAGE = 0x8765
GL_INT_IMAGE_1D = 0x9057
GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS = 0x90DB
GL_MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8A2D
GL_MIPMAP = 0x8293
GL_CURRENT_RASTER_POSITION = 0x0B07
GL_TEXTURE_SAMPLES = 0x9106
GL_MAX_RECTANGLE_TEXTURE_SIZE = 0x84F8
GL_VERTEX_BINDING_STRIDE = 0x82D8
GL_MAX_VARYING_COMPONENTS = 0x8B4B
GL_VIEW_COMPATIBILITY_CLASS = 0x82B6
GL_STENCIL_CLEAR_VALUE = 0x0B91
GL_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910B
GL_RG16 = 0x822C
GL_REPEAT = 0x2901
GL_UNSIGNED_SHORT_5_6_5 = 0x8363
GL_RENDERBUFFER_RED_SIZE = 0x8D50
GL_DEPTH_STENCIL_ATTACHMENT = 0x821A
GL_UNPACK_COMPRESSED_BLOCK_DEPTH = 0x9129
GL_FILL = 0x1B02
GL_ONE_MINUS_SRC_COLOR = 0x0301
GL_PACK_ALIGNMENT = 0x0D05
GL_DEBUG_TYPE_PORTABILITY = 0x824F
GL_UNSIGNED_INT_5_9_9_9_REV = 0x8C3E
GL_TEXTURE2 = 0x84C2
GL_PACK_COMPRESSED_BLOCK_WIDTH = 0x912B
GL_TEXTURE_ENV = 0x2300
GL_PIXEL_MODE_BIT ::GLbitfield = 0x00000020
GL_DOUBLE_MAT2x4 = 0x8F4A
GL_BUFFER_MAP_POINTER = 0x88BD
GL_GEQUAL = 0x0206
GL_UNSIGNALED = 0x9118
GL_UNPACK_COMPRESSED_BLOCK_SIZE = 0x912A
GL_RED = 0x1903
GL_BUFFER_BINDING = 0x9302
GL_MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD
GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213
GL_LUMINANCE8_ALPHA8 = 0x8045
GL_COLOR_ATTACHMENT14 = 0x8CEE
GL_RGBA32UI = 0x8D70
GL_PRIMARY_COLOR = 0x8577
GL_MIRRORED_REPEAT = 0x8370
GL_CLAMP_TO_BORDER = 0x812D
GL_VALIDATE_STATUS = 0x8B83
GL_COMPUTE_SUBROUTINE = 0x92ED
GL_RG8_SNORM = 0x8F95
GL_DRAW_FRAMEBUFFER_BINDING = 0x8CA6
GL_ALL_BARRIER_BITS = 0xFFFFFFFF
GL_COEFF = 0x0A00
GL_TEXTURE7 = 0x84C7
GL_TEXTURE6 = 0x84C6
GL_SRGB_WRITE = 0x8298
GL_COMPRESSED_SRGB_ALPHA = 0x8C49
GL_MAX_FRAGMENT_IMAGE_UNIFORMS = 0x90CE
GL_GEOMETRY_OUTPUT_TYPE = 0x8918
GL_CW = 0x0900
GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E80
GL_UNSIGNED_INT_VEC4 = 0x8DC8
GL_UNIFORM_IS_ROW_MAJOR = 0x8A3E
GL_TEXTURE_CUBE_MAP = 0x8513
GL_ALPHA_TEST_REF = 0x0BC2
GL_FOG_BIT ::GLbitfield = 0x00000080
GL_X3_BYTES = 0x1408
GL_TEXTURE_MAX_LEVEL = 0x813D
GL_REFERENCED_BY_GEOMETRY_SHADER = 0x9309
GL_TEXTURE_ALPHA_SIZE = 0x805F
GL_FOG_COORDINATE_ARRAY_TYPE = 0x8454
GL_TEXTURE_STENCIL_SIZE = 0x88F1
GL_MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125
GL_ALPHA_BITS = 0x0D55
GL_OR = 0x1507
GL_T2F_C4F_N3F_V3F = 0x2A2C
GL_TEXTURE19 = 0x84D3
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE = 0x910A
GL_TESS_GEN_MODE = 0x8E76
GL_MAX_LIGHTS = 0x0D31
GL_MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A
GL_MAX_VIEWPORT_DIMS = 0x0D3A
GL_POINT_SIZE_MIN = 0x8126
GL_MAX_VERTEX_IMAGE_UNIFORMS = 0x90CA
GL_CLIP_PLANE2 = 0x3002
GL_T4F_V4F = 0x2A28
GL_UNIFORM_TYPE = 0x8A37
GL_COMPUTE_SUBROUTINE_UNIFORM = 0x92F3
GL_LOCATION = 0x930E
GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET = 0x82D9
GL_CONTEXT_COMPATIBILITY_PROFILE_BIT ::GLbitfield = 0x00000002
GL_MAP1_INDEX = 0x0D91
GL_FOG_COORDINATE_ARRAY = 0x8457
GL_TEXTURE_COORD_ARRAY_STRIDE = 0x808A
GL_MAX_UNIFORM_BUFFER_BINDINGS = 0x8A2F
GL_PATCHES = 0x000E
GL_TESS_CONTROL_OUTPUT_VERTICES = 0x8E75
GL_LOW_FLOAT = 0x8DF0
GL_LINEAR_MIPMAP_LINEAR = 0x2703
GL_IMAGE_2D_MULTISAMPLE = 0x9055
GL_COLOR_COMPONENTS = 0x8283
GL_PRIMITIVE_RESTART = 0x8F9D
GL_SYNC_STATUS = 0x9114
GL_COMPRESSED_RGBA = 0x84EE
GL_MAX_ELEMENTS_INDICES = 0x80E9
GL_MAX_FRAGMENT_ATOMIC_COUNTERS = 0x92D6
GL_VIEW_CLASS_S3TC_DXT1_RGBA = 0x82CD
GL_COLOR_ATTACHMENT1 = 0x8CE1
GL_VERTEX_ATTRIB_ARRAY_INTEGER = 0x88FD
GL_DRAW_BUFFER10 = 0x882F
GL_TEXTURE21 = 0x84D5
GL_VIEW_CLASS_128_BITS = 0x82C4
GL_PACK_IMAGE_HEIGHT = 0x806C
GL_DEPTH32F_STENCIL8 = 0x8CAD
GL_MAP1_VERTEX_4 = 0x0D98
GL_SRC_ALPHA_SATURATE = 0x0308
GL_PROJECTION = 0x1701
GL_GENERATE_MIPMAP_HINT = 0x8192
GL_PROXY_TEXTURE_3D = 0x8070
GL_SHADER_SOURCE_LENGTH = 0x8B88
GL_RGBA8_SNORM = 0x8F97
GL_MAX_COMPUTE_IMAGE_UNIFORMS = 0x91BD
GL_C4F_N3F_V3F = 0x2A26
GL_BLEND_EQUATION_RGB = 0x8009
GL_INDEX_MODE = 0x0C30
GL_MAP_STENCIL = 0x0D11
GL_VERTEX_ARRAY_SIZE = 0x807A
GL_STATIC_COPY = 0x88E6
GL_UNSIGNED_INT_IMAGE_1D_ARRAY = 0x9068
GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT = 0x919F
GL_INTERNALFORMAT_SHARED_SIZE = 0x8277
GL_OPERAND1_ALPHA = 0x8599
GL_IMAGE_3D = 0x904E
GL_RG16UI = 0x823A
GL_TESS_EVALUATION_SHADER = 0x8E87
GL_PROGRAM_BINARY_FORMATS = 0x87FF
GL_PIXEL_MAP_B_TO_B_SIZE = 0x0CB8
GL_R32UI = 0x8236
GL_TEXTURE27 = 0x84DB
GL_RG16I = 0x8239
GL_MAX_TEXTURE_BUFFER_SIZE = 0x8C2B
GL_SIGNED_NORMALIZED = 0x8F9C
GL_VENDOR = 0x1F00
GL_DEPTH_TEST = 0x0B71
GL_TEXTURE_RED_SIZE = 0x805C
GL_TEXTURE_FILTER_CONTROL = 0x8500
GL_TEXTURE_BORDER = 0x1005
GL_TEXTURE_COORD_ARRAY_TYPE = 0x8089
GL_DEBUG_TYPE_PUSH_GROUP = 0x8269
GL_UNSIGNED_BYTE = 0x1401
GL_TRANSPOSE_MODELVIEW_MATRIX = 0x84E3
GL_UPPER_LEFT = 0x8CA2
GL_TEXTURE_COMPRESSED_BLOCK_SIZE = 0x82B3
GL_MAX_PROGRAM_TEXEL_OFFSET = 0x8905
GL_TEXTURE_BIT ::GLbitfield = 0x00040000
GL_STREAM_COPY = 0x88E2
GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX = 0x92DA
GL_MAP_FLUSH_EXPLICIT_BIT ::GLbitfield = 0x0010
GL_RGB9_E5 = 0x8C3D
GL_RGB5_A1 = 0x8057
GL_TEXTURE_VIEW_NUM_LEVELS = 0x82DC
GL_IMAGE_1D_ARRAY = 0x9052
GL_AUX1 = 0x040A
GL_DEPTH_COMPONENT32F = 0x8CAC
GL_FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8DAD
GL_TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8C7F
GL_FRAMEBUFFER_DEFAULT_SAMPLES = 0x9313
GL_BLUE_BITS = 0x0D54
GL_LOAD = 0x0101
GL_BUFFER_ACCESS_FLAGS = 0x911F
GL_COLOR_LOGIC_OP = 0x0BF2
GL_MAX_LAYERS = 0x8281
GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS = 0x90DD
GL_MINOR_VERSION = 0x821C
GL_UNIFORM = 0x92E1
GL_COLOR_ATTACHMENT2 = 0x8CE2
GL_HINT_BIT ::GLbitfield = 0x00008000
GL_TRANSPOSE_PROJECTION_MATRIX = 0x84E4
GL_DRAW_BUFFER14 = 0x8833
GL_FLOAT = 0x1406
GL_SPHERE_MAP = 0x2402
GL_COLOR_INDEX = 0x1900
GL_MAJOR_VERSION = 0x821B
GL_DOUBLE_VEC2 = 0x8FFC
GL_INTENSITY16 = 0x804D
GL_INT_SAMPLER_1D = 0x8DC9
GL_SOURCE1_RGB = 0x8581
GL_SCISSOR_BOX = 0x0C10
GL_MAX_3D_TEXTURE_SIZE = 0x8073
GL_CONDITION_SATISFIED = 0x911C
GL_TEXTURE_BUFFER_DATA_STORE_BINDING = 0x8C2D
GL_COPY_WRITE_BUFFER = 0x8F37
GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT = 0x90DF
GL_EDGE_FLAG_ARRAY_STRIDE = 0x808C
GL_UNSIGNED_INT_SAMPLER_1D = 0x8DD1
GL_PIXEL_MAP_I_TO_R_SIZE = 0x0CB2
GL_ATOMIC_COUNTER_BUFFER = 0x92C0
GL_SRGB_READ = 0x8297
GL_R8_SNORM = 0x8F94
GL_LEFT = 0x0406
GL_DEBUG_OUTPUT_SYNCHRONOUS = 0x8242
GL_COLOR_ENCODING = 0x8296
GL_INT_SAMPLER_2D_MULTISAMPLE = 0x9109
GL_PIXEL_MAP_I_TO_A_SIZE = 0x0CB5
GL_CLIP_PLANE4 = 0x3004
GL_TEXTURE_MAG_FILTER = 0x2800
GL_UNPACK_SKIP_PIXELS = 0x0CF4
GL_DOUBLE_MAT3x2 = 0x8F4B
GL_TEXTURE_LOD_BIAS = 0x8501
GL_COLOR_BUFFER_BIT ::GLbitfield = 0x00004000
GL_RGBA2 = 0x8055
GL_SAMPLE_MASK_VALUE = 0x8E52
GL_DEBUG_SOURCE_APPLICATION = 0x824A
GL_MAX_ATTRIB_STACK_DEPTH = 0x0D35
GL_SMOOTH_LINE_WIDTH_RANGE = 0x0B22
GL_SAMPLER_BINDING = 0x8919
GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS = 0x92CF
GL_DEBUG_SEVERITY_LOW = 0x9148
GL_TEXTURE_BINDING_CUBE_MAP_ARRAY = 0x900A
GL_SOURCE2_ALPHA = 0x858A
GL_SRC_ALPHA = 0x0302
GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS = 0x8E47
GL_REFLECTION_MAP = 0x8512
GL_CURRENT_VERTEX_ATTRIB = 0x8626
GL_FOG_COORDINATE = 0x8451
GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8A46
GL_FOG_START = 0x0B63
GL_LUMINANCE12 = 0x8041
GL_DRAW_BUFFER12 = 0x8831
GL_UNSIGNED_SHORT_5_5_5_1 = 0x8034
GL_FOG_COORD_ARRAY_TYPE = 0x8454
GL_MULT = 0x0103
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER = 0x92C9
GL_UNSIGNED_INT_24_8 = 0x84FA
GL_MAX_GEOMETRY_UNIFORM_COMPONENTS = 0x8DDF
GL_MAX_COMPUTE_UNIFORM_COMPONENTS = 0x8263
GL_MAX_VERTEX_ATOMIC_COUNTERS = 0x92D2
GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8A34
GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY = 0x9105
GL_PROGRAM_PIPELINE = 0x82E4
GL_GREEN_BITS = 0x0D53
GL_IMAGE_2D = 0x904D
GL_LIGHT_MODEL_COLOR_CONTROL = 0x81F8
GL_CURRENT_RASTER_DISTANCE = 0x0B09
GL_MIN_PROGRAM_TEXEL_OFFSET = 0x8904
GL_BGRA = 0x80E1
GL_STENCIL_WRITEMASK = 0x0B98
GL_VERTEX_BINDING_OFFSET = 0x82D7
GL_EYE_PLANE = 0x2502
GL_SAMPLER = 0x82E6
GL_IMAGE_CLASS_2_X_32 = 0x82BA
GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY = 0x906A
GL_LINE_WIDTH_GRANULARITY = 0x0B23
GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS = 0x8E1F
GL_MAX_IMAGE_UNITS = 0x8F38
GL_STENCIL_FUNC = 0x0B92
GL_TEXTURE_INTENSITY_TYPE = 0x8C15
GL_MAX_RENDERBUFFER_SIZE = 0x84E8
GL_TESS_CONTROL_SUBROUTINE_UNIFORM = 0x92EF
GL_ACTIVE_ATOMIC_COUNTER_BUFFERS = 0x92D9
GL_DEPTH_CLEAR_VALUE = 0x0B73
GL_BLUE = 0x1905
GL_VERTEX_ARRAY = 0x8074
GL_POLYGON_OFFSET_FACTOR = 0x8038
GL_TEXTURE10 = 0x84CA
GL_VIEW_CLASS_32_BITS = 0x82C8
GL_RIGHT = 0x0407
GL_FRAMEBUFFER_UNDEFINED = 0x8219
GL_FOG_COORDINATE_ARRAY_POINTER = 0x8456
GL_R8UI = 0x8232
GL_MAP1_NORMAL = 0x0D92
GL_TEXTURE28 = 0x84DC
GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214
GL_TEXTURE_CUBE_MAP_SEAMLESS = 0x884F
GL_BUFFER_UPDATE_BARRIER_BIT ::GLbitfield = 0x00000200
GL_FRONT_FACE = 0x0B46
GL_IMAGE_2D_RECT = 0x904F
GL_PRIMITIVES_GENERATED = 0x8C87
GL_RGBA12 = 0x805A
GL_IMPLEMENTATION_COLOR_READ_FORMAT = 0x8B9B
GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS = 0x8E85
GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824E
GL_PATCH_DEFAULT_INNER_LEVEL = 0x8E73
GL_FILTER = 0x829A
GL_R16 = 0x822A
GL_SAMPLER_2D_SHADOW = 0x8B62
GL_MAX_DEPTH_TEXTURE_SAMPLES = 0x910F
GL_PRIMITIVE_RESTART_INDEX = 0x8F9E
GL_INVALID_OPERATION = 0x0502
GL_MAX_TEXTURE_LOD_BIAS = 0x84FD
GL_TEXTURE_GEN_T = 0x0C61
GL_BUFFER = 0x82E0
GL_MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB
GL_VIEW_CLASS_S3TC_DXT1_RGB = 0x82CC
GL_RENDERBUFFER_STENCIL_SIZE = 0x8D55
GL_POLYGON_MODE = 0x0B40
GL_SHADER_IMAGE_ATOMIC = 0x82A6
GL_MAP1_TEXTURE_COORD_4 = 0x0D96
GL_LOGIC_OP_MODE = 0x0BF0
GL_DRAW_BUFFER9 = 0x882E
GL_SAMPLER_2D_RECT_SHADOW = 0x8B64
GL_LINE_WIDTH = 0x0B21
GL_INTENSITY4 = 0x804A
GL_TRANSFORM_FEEDBACK_VARYINGS = 0x8C83
GL_COLOR_ATTACHMENT7 = 0x8CE7
GL_VERTEX_SHADER_BIT ::GLbitfield = 0x00000001
GL_RENDERBUFFER_BINDING = 0x8CA7
GL_SOURCE1_ALPHA = 0x8589
GL_EDGE_FLAG_ARRAY_BUFFER_BINDING = 0x889B
GL_STATIC_READ = 0x88E5
GL_SHADER_STORAGE_BARRIER_BIT ::GLbitfield = 0x2000
GL_NAME_LENGTH = 0x92F9
GL_POLYGON = 0x0009
GL_PASS_THROUGH_TOKEN = 0x0700
GL_LIGHTING_BIT ::GLbitfield = 0x00000040
GL_LINE_BIT ::GLbitfield = 0x00000004
GL_POLYGON_STIPPLE = 0x0B42
GL_ALPHA8 = 0x803C
GL_FRONT = 0x0404
GL_ACTIVE_VARIABLES = 0x9305
GL_COMPRESSED_RG_RGTC2 = 0x8DBD
GL_TEXTURE24 = 0x84D8
GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING = 0x889A
GL_FLOAT_MAT3 = 0x8B5B
GL_DEBUG_TYPE_ERROR = 0x824C
GL_VIEW_CLASS_48_BITS = 0x82C7
GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8C8A
GL_PROGRAM_BINARY_LENGTH = 0x8741
GL_TEXTURE_IMMUTABLE_LEVELS = 0x82DF
GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY = 0x906C
GL_POINT_FADE_THRESHOLD_SIZE = 0x8128
GL_LOW_INT = 0x8DF3
GL_DEBUG_GROUP_STACK_DEPTH = 0x826D
GL_FRAMEBUFFER_DEFAULT = 0x8218
GL_MAX_NAME_STACK_DEPTH = 0x0D37
GL_COLOR_ARRAY = 0x8076
GL_CURRENT_PROGRAM = 0x8B8D
GL_COMPRESSED_SIGNED_RG_RGTC2 = 0x8DBE
GL_INT_IMAGE_CUBE = 0x905B
GL_DRAW_BUFFER4 = 0x8829
GL_FRONT_LEFT = 0x0400
GL_TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517
GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625
GL_GET_TEXTURE_IMAGE_FORMAT = 0x8291
GL_CLIENT_ACTIVE_TEXTURE = 0x84E1
GL_SAMPLER_2D_ARRAY_SHADOW = 0x8DC4
GL_RG32UI = 0x823C
GL_INTERNALFORMAT_STENCIL_SIZE = 0x8276
GL_X2_BYTES = 0x1407
GL_FEEDBACK_BUFFER_TYPE = 0x0DF2
GL_RGBA16F = 0x881A
GL_COPY_READ_BUFFER = 0x8F36
GL_CONSTANT_ATTENUATION = 0x1207
GL_DRAW_BUFFER15 = 0x8834
GL_RG16_SNORM = 0x8F99
GL_RGB8_SNORM = 0x8F96
GL_GEOMETRY_SHADER = 0x8DD9
GL_LUMINANCE_ALPHA = 0x190A
GL_COLOR_RENDERABLE = 0x8286
GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F
GL_TRIANGLES_ADJACENCY = 0x000C
GL_SAMPLER_CUBE = 0x8B60
GL_COLOR_ATTACHMENT0 = 0x8CE0
GL_FLAT = 0x1D00
GL_VIEW_CLASS_8_BITS = 0x82CB
GL_FIRST_VERTEX_CONVENTION = 0x8E4D
GL_SLUMINANCE8_ALPHA8 = 0x8C45
GL_SYNC_FLAGS = 0x9115
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER = 0x90ED
GL_SAMPLER_1D_SHADOW = 0x8B61
GL_BGR_INTEGER = 0x8D9A
GL_FLOAT_MAT2x4 = 0x8B66
GL_PATCH_DEFAULT_OUTER_LEVEL = 0x8E74
GL_READ_PIXELS_FORMAT = 0x828D
GL_INTERNALFORMAT_DEPTH_TYPE = 0x827C
GL_DRAW_INDIRECT_BUFFER_BINDING = 0x8F43
GL_GEOMETRY_INPUT_TYPE = 0x8917
GL_R8I = 0x8231
GL_TRANSFORM_FEEDBACK_BUFFER = 0x8C8E
GL_COPY_INVERTED = 0x150C
GL_LIST_MODE = 0x0B30
GL_FOG_END = 0x0B64
GL_MODELVIEW_STACK_DEPTH = 0x0BA3
GL_NORMAL_ARRAY_TYPE = 0x807E
GL_UNIFORM_BUFFER_SIZE = 0x8A2A
GL_LINK_STATUS = 0x8B82
GL_ARRAY_STRIDE = 0x92FE
GL_STENCIL_INDEX4 = 0x8D47
GL_MAX_IMAGE_SAMPLES = 0x906D
GL_IMAGE_CLASS_4_X_16 = 0x82BC
GL_COMPRESSED_SLUMINANCE_ALPHA = 0x8C4B
GL_RGB_SNORM = 0x8F92
GL_INT_VEC3 = 0x8B54
GL_MAX_ELEMENT_INDEX = 0x8D6B
GL_IMAGE_CLASS_1_X_16 = 0x82BE
GL_TEXTURE_RECTANGLE = 0x84F5
GL_TEXTURE_BINDING_2D_MULTISAMPLE = 0x9104
GL_TEXTURE_CUBE_MAP_ARRAY = 0x9009
GL_NEAREST_MIPMAP_NEAREST = 0x2700
GL_DRAW_FRAMEBUFFER = 0x8CA9
GL_TEXTURE_BLUE_TYPE = 0x8C12
GL_NUM_ACTIVE_VARIABLES = 0x9304
GL_DOUBLEBUFFER = 0x0C32
GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217
GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER = 0x92C7
GL_DEBUG_TYPE_POP_GROUP = 0x826A
GL_LINE_STRIP_ADJACENCY = 0x000B
GL_TRIANGLE_STRIP = 0x0005
GL_MODELVIEW_MATRIX = 0x0BA6
GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT ::GLbitfield = 0x0001
GL_TEXTURE_IMAGE_FORMAT = 0x828F
GL_RGBA_SNORM = 0x8F93
GL_ALIASED_POINT_SIZE_RANGE = 0x846D
GL_DOUBLE_MAT3 = 0x8F47
GL_TEXTURE13 = 0x84CD
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY = 0x910D
GL_TEXTURE_BASE_LEVEL = 0x813C
GL_RGB16I = 0x8D89
GL_HIGH_INT = 0x8DF5
GL_TEXTURE_MIN_LOD = 0x813A
GL_DEBUG_CALLBACK_USER_PARAM = 0x8245
GL_INDEX_OFFSET = 0x0D13
GL_SAMPLE_COVERAGE_INVERT = 0x80AB
GL_PACK_COMPRESSED_BLOCK_DEPTH = 0x912D
GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS = 0x92D3
GL_FRAMEBUFFER_RENDERABLE_LAYERED = 0x828A
GL_FOG_INDEX = 0x0B61
GL_BOOL_VEC3 = 0x8B58
GL_GEOMETRY_TEXTURE = 0x829E
GL_TEXTURE_BINDING_CUBE_MAP = 0x8514
GL_TESS_CONTROL_TEXTURE = 0x829C
GL_VERTEX_ARRAY_POINTER = 0x808E
GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS = 0x8E89
GL_UNSIGNED_INT_SAMPLER_CUBE = 0x8DD4
GL_COMPRESSED_RED_RGTC1 = 0x8DBB
GL_INDEX = 0x8222
GL_DRAW_BUFFER11 = 0x8830
GL_GREEN_INTEGER = 0x8D95
GL_MAX_FRAMEBUFFER_HEIGHT = 0x9316
GL_INT = 0x1404
GL_TRIANGLES = 0x0004
GL_ALIASED_LINE_WIDTH_RANGE = 0x846E
GL_DEBUG_SEVERITY_NOTIFICATION = 0x826B
GL_DEPTH_STENCIL = 0x84F9
GL_TEXTURE_SHADOW = 0x82A1
GL_MAP_INVALIDATE_RANGE_BIT ::GLbitfield = 0x0004
GL_DECR_WRAP = 0x8508
GL_NAND = 0x150E
GL_SEPARATE_SPECULAR_COLOR = 0x81FA
GL_SAMPLER_1D_ARRAY_SHADOW = 0x8DC3
GL_BLEND_DST_ALPHA = 0x80CA
GL_SELECTION_BUFFER_SIZE = 0x0DF4
GL_TEXTURE_IMAGE_TYPE = 0x8290
GL_RENDERBUFFER = 0x8D41
GL_RGB10 = 0x8052
GL_INT_IMAGE_2D_MULTISAMPLE = 0x9060
GL_DOUBLE_MAT2 = 0x8F46
GL_ACCUM_BLUE_BITS = 0x0D5A
GL_TEXTURE30 = 0x84DE
GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A
GL_INTERNALFORMAT_ALPHA_SIZE = 0x8274
GL_RENDERBUFFER_BLUE_SIZE = 0x8D52
GL_TEXTURE_BORDER_COLOR = 0x1004
GL_ALPHA16 = 0x803E
GL_ARRAY_BUFFER_BINDING = 0x8894
GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623
GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH = 0x8C76
GL_SHADER_IMAGE_STORE = 0x82A5
GL_SHADER_IMAGE_ACCESS_BARRIER_BIT ::GLbitfield = 0x00000020
GL_LINE_STIPPLE_PATTERN = 0x0B25
GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS = 0x92CD
GL_STENCIL_ATTACHMENT = 0x8D20
GL_ACCUM_ALPHA_BITS = 0x0D5B
GL_CLIP_PLANE3 = 0x3003
GL_DEPTH24_STENCIL8 = 0x88F0
GL_PIXEL_UNPACK_BUFFER_BINDING = 0x88EF
GL_RG16F = 0x822F
GL_TEXTURE_INTERNAL_FORMAT = 0x1003
GL_QUERY_BY_REGION_WAIT = 0x8E15
GL_EDGE_FLAG = 0x0B43
GL_INT_SAMPLER_2D_RECT = 0x8DCD
GL_FOG_COORD_SRC = 0x8450
GL_VERTEX_ARRAY_BUFFER_BINDING = 0x8896
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8CD4
GL_ALL_SHADER_BITS = 0xFFFFFFFF
GL_POLYGON_TOKEN = 0x0703
GL_PACK_COMPRESSED_BLOCK_SIZE = 0x912E
GL_X4D_COLOR_TEXTURE = 0x0604
GL_COLOR_ATTACHMENT5 = 0x8CE5
GL_DEPTH_BIAS = 0x0D1F
GL_UNIFORM_ARRAY_STRIDE = 0x8A3C
GL_IMAGE_CLASS_10_10_10_2 = 0x82C3
GL_FALSE = 0
GL_TEXTURE_BUFFER_OFFSET = 0x919D
GL_MAX_COLOR_TEXTURE_SAMPLES = 0x910E
GL_IS_PER_PATCH = 0x92E7
GL_INTERNALFORMAT_STENCIL_TYPE = 0x827D
GL_PROXY_TEXTURE_CUBE_MAP = 0x851B
GL_NUM_SHADER_BINARY_FORMATS = 0x8DF9
GL_TESS_CONTROL_SHADER = 0x8E88
GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS = 0x92D0
GL_CONTEXT_CORE_PROFILE_BIT ::GLbitfield = 0x00000001
GL_UNSIGNED_INT_8_8_8_8_REV = 0x8367
GL_STENCIL_TEST = 0x0B90
GL_LINE_STIPPLE = 0x0B24
GL_SECONDARY_COLOR_ARRAY_POINTER = 0x845D
GL_OPERAND2_RGB = 0x8592
GL_PERSPECTIVE_CORRECTION_HINT = 0x0C50
GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS = 0x8264
GL_QUERY_RESULT_AVAILABLE = 0x8867
GL_LIGHT0 = 0x4000
GL_STENCIL_BACK_WRITEMASK = 0x8CA5
GL_TESS_GEN_SPACING = 0x8E77
GL_MIN_FRAGMENT_INTERPOLATION_OFFSET = 0x8E5B
GL_IMAGE_CLASS_2_X_8 = 0x82C0
GL_R = 0x2002
GL_MAX_VARYING_FLOATS = 0x8B4B
GL_RGBA4 = 0x8056
GL_TEXTURE_BINDING_BUFFER = 0x8C2C
GL_RGBA_MODE = 0x0C31
GL_TEXTURE_GREEN_TYPE = 0x8C11
GL_TRANSFORM_BIT ::GLbitfield = 0x00001000
GL_LOGIC_OP = 0x0BF1
GL_ADD = 0x0104
GL_PACK_SWAP_BYTES = 0x0D00
GL_LINE_SMOOTH = 0x0B20
GL_FRAMEBUFFER_DEFAULT_WIDTH = 0x9310
GL_ALREADY_SIGNALED = 0x911A
GL_RED_SCALE = 0x0D14
GL_STACK_OVERFLOW = 0x0503
GL_DEPTH_COMPONENT16 = 0x81A5
GL_SHADING_LANGUAGE_VERSION = 0x8B8C
GL_IMAGE_1D = 0x904C
GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8C8B
GL_COLOR_MATERIAL_FACE = 0x0B55
GL_TEXTURE_HEIGHT = 0x1001
GL_COMPATIBLE_SUBROUTINES = 0x8E4B
GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279
GL_PIXEL_MAP_R_TO_R_SIZE = 0x0CB6
GL_EXTENSIONS = 0x1F03
GL_LUMINANCE6_ALPHA2 = 0x8044
GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624
GL_TEXTURE_SWIZZLE_R = 0x8E42
GL_TEXTURE15 = 0x84CF
GL_ORDER = 0x0A01
GL_PIXEL_MAP_I_TO_I_SIZE = 0x0CB0
GL_DRAW_BUFFER8 = 0x882D
GL_PIXEL_MAP_I_TO_A = 0x0C75
GL_NEGATIVE_ONE_TO_ONE = 0x935E
GL_ZERO_TO_ONE = 0x935F
GL_CLIP_ORIGIN = 0x935C
GL_CLIP_DEPTH_MODE = 0x935D
GL_MAX_CULL_DISTANCES = 0x82F9
GL_MAX_COMBINED_CLIP_AND_CULL_DISTANCES = 0x82FA
GL_QUERY_WAIT_INVERTED = 0x8E17
GL_QUERY_NO_WAIT_INVERTED = 0x8E18
GL_QUERY_BY_REGION_WAIT_INVERTED = 0x8E19
GL_QUERY_BY_REGION_NO_WAIT_INVERTED = 0x8E1A
GL_TEXTURE_TARGET = 0x1006
GL_QUERY_TARGET = 0x82EA
GL_GUILTY_CONTEXT_RESET = 0x8253
GL_INNOCENT_CONTEXT_RESET = 0x8254
GL_UNKNOWN_CONTEXT_RESET = 0x8255
GL_CONTEXT_ROBUST_ACCESS = 0x90F3
GL_RESET_NOTIFICATION_STRATEGY = 0x8256
GL_LOSE_CONTEXT_ON_RESET = 0x8252
GL_NO_RESET_NOTIFICATION = 0x8261
GL_CONTEXT_LOST = 0x0507
GL_QUERY_BUFFER = 0x9192
GL_LOCATION_COMPONENT = 0x934A
GL_TRANSFORM_FEEDBACK_BUFFER_INDEX = 0x934B
GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE = 0x934C
GL_QUERY_RESULT_NO_WAIT = 0x9194
GL_QUERY_BUFFER_BINDING = 0x9193
GL_QUERY_BUFFER_BARRIER_BIT ::GLbitfield = 0x000080000
GL_MIRROR_CLAMP_TO_EDGE = 0x8743
GL_SPIR_V_BINARY = 0x9552
GL_SPIR_V_EXTENSIONS = 0x9553
GL_NUM_SPIR_V_EXTENSIONS = 0x9554
GL_PARAMETER_BUFFER = 0x80EE
GL_PARAMETER_BUFFER_BINDING = 0x80EF
GL_VERTICES_SUBMITTED = 0x82EE
GL_PRIMITIVES_SUBMITTED = 0x82EF
GL_VERTEX_SHADER_INVOCATIONS = 0x82F0
GL_TESS_CONTROL_SHADER_PATCHES = 0x82F1
GL_TESS_EVALUATION_SHADER_INVOCATIONS = 0x82F2
GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED = 0x82F3
GL_FRAGMENT_SHADER_INVOCATIONS = 0x82F4
GL_COMPUTE_SHADER_INVOCATIONS = 0x82F5
GL_CLIPPING_INPUT_PRIMITIVES = 0x82F6
GL_CLIPPING_OUTPUT_PRIMITIVES = 0x82F7
GL_TRANSFORM_FEEDBACK_OVERFLOW = 0x82EC
GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW = 0x82ED
GL_TEXTURE_MAX_ANISOTROPY = 0x84FE
GL_MAX_TEXTURE_MAX_ANISOTROPY = 0x84FF
GL_POLYGON_OFFSET_CLAMP = 0x8E1B
GL_CONTEXT_FLAG_NO_ERROR_BIT ::GLbitfield = 0x00000008
GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 0x8E8E
GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 0x8E8F
GL_COMPRESSED_RGBA_BPTC_UNORM = 0x8E8C
GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 0x8E8D
GL_MAP_PERSISTENT_BIT ::GLbitfield = 0x0040
GL_MAP_COHERENT_BIT ::GLbitfield = 0x0080
GL_DYNAMIC_STORAGE_BIT ::GLbitfield = 0x0100
GL_CLIENT_STORAGE_BIT ::GLbitfield = 0x0200
GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT ::GLbitfield = 0x000004000
GL_BUFFER_IMMUTABLE_STORAGE = 0x821F
GL_BUFFER_STORAGE_FLAGS = 0x8220
GL_INT64_ARB = 0x140E
GL_INT64_VEC2_ARB = 0x8FE9
GL_INT64_VEC3_ARB = 0x8FEA
GL_INT64_VEC4_ARB = 0x8FEB
GL_UNSIGNED_INT64_ARB = 0x140F
GL_UNSIGNED_INT64_VEC2_ARB = 0x8FF5
GL_UNSIGNED_INT64_VEC3_ARB = 0x8FF6
GL_UNSIGNED_INT64_VEC4_ARB = 0x8FF7
end
# Define custom overloads for important constants, to make sure they print correctly.
macro custom_glenum(value::Integer, name::Symbol, real_type::DataType = GLenum)
e_name = :(Symbol($(string(name))))
return :(
ModernGLbp.GLENUM(::Val{UInt32($value)}) =
GLENUM{$real_type}(convert($real_type, $value), $e_name)
)
end
@custom_glenum 1 GL_TRUE
@custom_glenum 0 GL_FALSE
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 66089 | @glfunc glGetNamedFramebufferParameterivEXT(framebuffer::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glDrawElementsInstancedBaseVertexBaseInstance(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, instancecount::GLsizei, basevertex::GLint, baseinstance::GLuint)::Cvoid
@glfunc glReadBuffer(mode::GLenum)::Cvoid
@glfunc glBindBufferBase(target::GLenum, index::GLuint, buffer::GLuint)::Cvoid
@glfunc glClientWaitSync(sync::GLsync, flags::GLbitfield, timeout::GLuint64)::GLenum
@glfunc glGetIntegeri_v(target::GLenum, index::GLuint, data::Ptr{GLint})::Cvoid
@glfunc glTexCoordP2ui(type_::GLenum, coords::GLuint)::Cvoid
@glfunc glTexParameterIiv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glVertexAttribI2iv(index::GLuint, v::Ptr{GLint})::Cvoid
@glfunc glProgramUniformMatrix4fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glSamplerParameteri(sampler::GLuint, pname::GLenum, param::GLint)::Cvoid
@glfunc glStencilFuncSeparate(face::GLenum, func_::GLenum, ref::GLint, mask::GLuint)::Cvoid
@glfunc glResumeTransformFeedback()::Cvoid
@glfunc glProgramUniform1fv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glProgramUniform3uiv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glUniform1d(location::GLint, x::GLdouble)::Cvoid
@glfunc glUniformMatrix2x4dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glFinish()::Cvoid
@glfunc glProgramUniformMatrix2x3fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glClear(mask::GLbitfield)::Cvoid
@glfunc glBindTransformFeedback(target::GLenum, id::GLuint)::Cvoid
@glfunc glShaderSource(shader::GLuint, count::GLsizei, string_::Ptr{Ptr{GLchar}}, length::Ptr{GLint})::Cvoid
@glfunc glUniform2iv(location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glBindTexture(target::GLenum, texture::GLuint)::Cvoid
@glfunc glDrawElementsIndirect(mode::GLenum, type_::GLenum, indirect::Ptr{Cvoid})::Cvoid
@glfunc glUniformMatrix3dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glGetSamplerParameterIiv(sampler::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetPointerv(pname::GLenum, params::Ptr{Ptr{Cvoid}})::Cvoid
@glfunc glReleaseShaderCompiler()::Cvoid
@glfunc glGetQueryObjectui64v(id::GLuint, pname::GLenum, params::Ptr{GLuint64})::Cvoid
@glfunc glVertexAttribDivisor(index::GLuint, divisor::GLuint)::Cvoid
@glfunc glVertexAttribP4ui(index::GLuint, type_::GLenum, normalized::GLboolean, value::GLuint)::Cvoid
@glfunc glDeleteProgram(program::GLuint)::Cvoid
@glfunc glSamplerParameterIuiv(sampler::GLuint, pname::GLenum, param::Ptr{GLuint})::Cvoid
@glfunc glGetProgramiv(program::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glUniform3dv(location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glProgramUniform4fv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glDrawTransformFeedbackInstanced(mode::GLenum, id::GLuint, instancecount::GLsizei)::Cvoid
@glfunc glScissorArrayv(first::GLuint, count::GLsizei, v::Ptr{GLint})::Cvoid
@glfunc glGenerateMipmap(target::GLenum)::Cvoid
@glfunc glProgramUniform2dv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glUniform4d(location::GLint, x::GLdouble, y::GLdouble, z::GLdouble, w::GLdouble)::Cvoid
@glfunc glDeleteRenderbuffers(n::GLsizei, renderbuffers::Ptr{GLuint})::Cvoid
@glfunc glPopDebugGroup()::Cvoid
@glfunc glGetShaderSource(shader::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, source::Ptr{GLchar})::Cvoid
@glfunc glIsBuffer(buffer::GLuint)::Bool
@glfunc glGetAttachedShaders(program::GLuint, maxCount::GLsizei, count::Ptr{GLsizei}, obj::Ptr{GLuint})::Cvoid
@glfunc glVertexAttribI1uiv(index::GLuint, v::Ptr{GLuint})::Cvoid
@glfunc glMultiTexCoordP1ui(texture::GLenum, type_::GLenum, coords::GLuint)::Cvoid
@glfunc glTextureView(texture::GLuint, target::GLenum, origtexture::GLuint, internalformat::GLenum, minlevel::GLuint, numlevels::GLuint, minlayer::GLuint, numlayers::GLuint)::Cvoid
@glfunc glProgramUniform4uiv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glSecondaryColorP3uiv(type_::GLenum, color::Ptr{GLuint})::Cvoid
@glfunc glQueryCounter(id::GLuint, target::GLenum)::Cvoid
@glfunc glTexStorage3DMultisample(target::GLenum, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glDrawArraysIndirect(mode::GLenum, indirect::Ptr{Cvoid})::Cvoid
@glfunc glUniform4ui(location::GLint, v0::GLuint, v1::GLuint, v2::GLuint, v3::GLuint)::Cvoid
@glfunc glProgramUniform4f(program::GLuint, location::GLint, v0::GLfloat, v1::GLfloat, v2::GLfloat, v3::GLfloat)::Cvoid
@glfunc glCompressedTexSubImage1D(target::GLenum, level::GLint, xoffset::GLint, width::GLsizei, format::GLenum, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glProgramUniformMatrix2dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glTexParameterf(target::GLenum, pname::GLenum, param::GLfloat)::Cvoid
@glfunc glShaderBinary(count::GLsizei, shaders::Ptr{GLuint}, binaryformat::GLenum, binary::Ptr{Cvoid}, length::GLsizei)::Cvoid
@glfunc glPauseTransformFeedback()::Cvoid
@glfunc glMultiDrawElements(mode::GLenum, count::Ptr{GLsizei}, type_::GLenum, indices::Ptr{Ptr{Cvoid}}, drawcount::GLsizei)::Cvoid
@glfunc glGetBufferPointerv(target::GLenum, pname::GLenum, params::Ptr{Ptr{Cvoid}})::Cvoid
@glfunc glVertexAttribP4uiv(index::GLuint, type_::GLenum, normalized::GLboolean, value::Ptr{GLuint})::Cvoid
@glfunc glVertexArrayVertexAttribIFormatEXT(vaobj::GLuint, attribindex::GLuint, size::GLint, type_::GLenum, relativeoffset::GLuint)::Cvoid
@glfunc glEndConditionalRender()::Cvoid
@glfunc glFlush()::Cvoid
@glfunc glBlendFuncSeparatei(buf::GLuint, srcRGB::GLenum, dstRGB::GLenum, srcAlpha::GLenum, dstAlpha::GLenum)::Cvoid
@glfunc glProgramUniform1dv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glProgramUniform2ui(program::GLuint, location::GLint, v0::GLuint, v1::GLuint)::Cvoid
@glfunc glActiveTexture(texture::GLenum)::Cvoid
@glfunc glSecondaryColorP3ui(type_::GLenum, color::GLuint)::Cvoid
@glfunc glProgramUniformMatrix3dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glBlendEquationi(buf::GLuint, mode::GLenum)::Cvoid
@glfunc glPolygonOffset(factor::GLfloat, units::GLfloat)::Cvoid
@glfunc glDetachShader(program::GLuint, shader::GLuint)::Cvoid
@glfunc glUniform4uiv(location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glTexParameteriv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetIntegerv(pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glEnable(cap::GLenum)::Cvoid
@glfunc glClearBufferData(target::GLenum, internalformat::GLenum, format::GLenum, type_::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glMapBufferRange(target::GLenum, offset::GLintptr, length::GLsizeiptr, access::GLbitfield)::Ptr{Cvoid}
@glfunc glTexCoordP4uiv(type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glDepthRangeArrayv(first::GLuint, count::GLsizei, v::Ptr{GLdouble})::Cvoid
@glfunc glGetCompressedTexImage(target::GLenum, level::GLint, img::Ptr{Cvoid})::Cvoid
@glfunc glProgramUniformMatrix4x2fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glIsTransformFeedback(id::GLuint)::Bool
@glfunc glMultiTexCoordP1uiv(texture::GLenum, type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glSamplerParameterIiv(sampler::GLuint, pname::GLenum, param::Ptr{GLint})::Cvoid
@glfunc glProgramUniform2i(program::GLuint, location::GLint, v0::GLint, v1::GLint)::Cvoid
@glfunc glUniform4dv(location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glGetDoublev(pname::GLenum, params::Ptr{GLdouble})::Cvoid
@glfunc glTexCoordP1uiv(type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glProgramUniform1f(program::GLuint, location::GLint, v0::GLfloat)::Cvoid
@glfunc glTexParameterIuiv(target::GLenum, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glUniformMatrix2x3dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glPixelStorei(pname::GLenum, param::GLint)::Cvoid
@glfunc glUniform3ui(location::GLint, v0::GLuint, v1::GLuint, v2::GLuint)::Cvoid
@glfunc glGetTexParameterIuiv(target::GLenum, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glGetShaderiv(shader::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glTexCoordP4ui(type_::GLenum, coords::GLuint)::Cvoid
@glfunc glPointParameteri(pname::GLenum, param::GLint)::Cvoid
@glfunc glTextureStorage1DEXT(texture::GLuint, target::GLenum, levels::GLsizei, internalformat::GLenum, width::GLsizei)::Cvoid
@glfunc glEnablei(target::GLenum, index::GLuint)::Cvoid
@glfunc glTexCoordP3uiv(type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glGetRenderbufferParameteriv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glVertexAttribI4sv(index::GLuint, v::Ptr{GLshort})::Cvoid
@glfunc glGetActiveSubroutineName(program::GLuint, shadertype::GLenum, index::GLuint, bufsize::GLsizei, length::Ptr{GLsizei}, name::Ptr{GLchar})::Cvoid
@glfunc glCompileShader(shader::GLuint)::Cvoid
@glfunc glLinkProgram(program::GLuint)::Cvoid
@glfunc glReadPixels(x::GLint, y::GLint, width::GLsizei, height::GLsizei, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glCreateShaderProgramv(type_::GLenum, count::GLsizei, strings::Ptr{GLchar})::GLuint
@glfunc glBufferData(target::GLenum, size::GLsizeiptr, data::Ptr{Cvoid}, usage::GLenum)::Cvoid
@glfunc glBufferStorage(target::GLenum, size::GLsizeiptr, data::Ptr{Cvoid}, flags::GLbitfield)::Cvoid
@glfunc glPointParameteriv(pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glUniform2fv(location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glDrawTransformFeedbackStream(mode::GLenum, id::GLuint, stream::GLuint)::Cvoid
@glfunc glUniform2dv(location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glTexSubImage1D(target::GLenum, level::GLint, xoffset::GLint, width::GLsizei, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glDispatchCompute(num_groups_x::GLuint, num_groups_y::GLuint, num_groups_z::GLuint)::Cvoid
@glfunc glGetBufferSubData(target::GLenum, offset::GLintptr, size::GLsizeiptr, data::Ptr{Cvoid})::Cvoid
@glfunc glVertexP2uiv(type_::GLenum, value::Ptr{GLuint})::Cvoid
@glfunc glUniform4fv(location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glGetProgramResourceLocation(program::GLuint, programCinterface::GLenum, name::Ptr{GLchar})::GLint
@glfunc glVertexArrayVertexAttribLFormatEXT(vaobj::GLuint, attribindex::GLuint, size::GLint, type_::GLenum, relativeoffset::GLuint)::Cvoid
@glfunc glGetUniformuiv(program::GLuint, location::GLint, params::Ptr{GLuint})::Cvoid
@glfunc glBindImageTexture(unit::GLuint, texture::GLuint, level::GLint, layered::GLboolean, layer::GLint, access::GLenum, format::GLenum)::Cvoid
@glfunc glVertexAttribL4dv(index::GLuint, v::Ptr{GLdouble})::Cvoid
@glfunc glColorP4ui(type_::GLenum, color::GLuint)::Cvoid
@glfunc glUniform2f(location::GLint, v0::GLfloat, v1::GLfloat)::Cvoid
@glfunc glColorP4uiv(type_::GLenum, color::Ptr{GLuint})::Cvoid
@glfunc glVertexAttribIPointer(index::GLuint, size::GLint, type_::GLenum, stride::GLsizei, pointer::Ptr{Cvoid})::Cvoid
@glfunc glGetProgramPipelineiv(pipeline::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glMultiTexCoordP3uiv(texture::GLenum, type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glGetProgramResourceName(program::GLuint, programInterface::GLenum, index::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, name::Ptr{GLchar})::Cvoid
@glfunc glVertexP4ui(type_::GLenum, value::GLuint)::Cvoid
@glfunc glFrontFace(mode::GLenum)::Cvoid
@glfunc glProgramUniform4i(program::GLuint, location::GLint, v0::GLint, v1::GLint, v2::GLint, v3::GLint)::Cvoid
@glfunc glPointParameterfv(pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glShaderStorageBlockBinding(program::GLuint, storageBlockIndex::GLuint, storageBlockBinding::GLuint)::Cvoid
@glfunc glClearStencil(s::GLint)::Cvoid
@glfunc glBlendEquation(mode::GLenum)::Cvoid
@glfunc glIsProgramPipeline(pipeline::GLuint)::Bool
@glfunc glUniform3f(location::GLint, v0::GLfloat, v1::GLfloat, v2::GLfloat)::Cvoid
@glfunc glVertexAttribI4usv(index::GLuint, v::Ptr{GLushort})::Cvoid
@glfunc glFramebufferParameteri(target::GLenum, pname::GLenum, param::GLint)::Cvoid
@glfunc glGenSamplers(count::GLsizei, samplers::Ptr{GLuint})::Cvoid
@glfunc glUniformMatrix4fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glBlendColor(red::GLfloat, green::GLfloat, blue::GLfloat, alpha::GLfloat)::Cvoid
@glfunc glInvalidateTexImage(texture::GLuint, level::GLint)::Cvoid
@glfunc glGetSubroutineIndex(program::GLuint, shadertype::GLenum, name::Ptr{GLchar})::GLuint
@glfunc glVertexAttribL3dv(index::GLuint, v::Ptr{GLdouble})::Cvoid
@glfunc glProgramUniformMatrix2fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glDrawElementsInstancedBaseInstance(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, instancecount::GLsizei, baseinstance::GLuint)::Cvoid
@glfunc glIndexub(c::GLubyte)::Cvoid
@glfunc glGenRenderbuffers(n::GLsizei, renderbuffers::Ptr{GLuint})::Cvoid
@glfunc glProgramUniform4dv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glProgramUniformMatrix2x3dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glTexImage3D(target::GLenum, level::GLint, internalformat::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, border::GLint, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetVertexAttribfv(index::GLuint, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glVertexAttribL4d(index::GLuint, x::GLdouble, y::GLdouble, z::GLdouble, w::GLdouble)::Cvoid
@glfunc glBindFramebuffer(target::GLenum, framebuffer::GLuint)::Cvoid
@glfunc glFramebufferTexture3D(target::GLenum, attachment::GLenum, textarget::GLenum, texture::GLuint, level::GLint, zoffset::GLint)::Cvoid
@glfunc glVertexArrayVertexAttribFormatEXT(vaobj::GLuint, attribindex::GLuint, size::GLint, type_::GLenum, normalized::GLboolean, relativeoffset::GLuint)::Cvoid
@glfunc glGetVertexAttribLdv(index::GLuint, pname::GLenum, params::Ptr{GLdouble})::Cvoid
@glfunc glVertexAttribBinding(attribindex::GLuint, bindingindex::GLuint)::Cvoid
@glfunc glUniformMatrix3fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glUniformMatrix4dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glProgramUniformMatrix4x3dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glProgramUniformMatrix3x4fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glGetDebugMessageLog(count::GLuint, bufsize::GLsizei, sources::Ptr{GLenum}, types::Ptr{GLenum}, ids::Ptr{GLuint}, severities::Ptr{GLenum}, lengths::Ptr{GLsizei}, messageLog::Ptr{GLchar})::GLuint
@glfunc glGetVertexAttribiv(index::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glDebugMessageInsert(source::GLenum, type_::GLenum, id::GLuint, severity::GLenum, length::GLsizei, buf::Ptr{GLchar})::Cvoid
@glfunc glNormalP3ui(type_::GLenum, coords::GLuint)::Cvoid
@glfunc glDrawArraysInstanced(mode::GLenum, first::GLint, count::GLsizei, instancecount::GLsizei)::Cvoid
@glfunc glCompressedTexImage2D(target::GLenum, level::GLint, internalformat::GLenum, width::GLsizei, height::GLsizei, border::GLint, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glPushDebugGroup(source::GLenum, id::GLuint, length::GLsizei, message::Ptr{GLchar})::Cvoid
@glfunc glGetUniformBlockIndex(program::GLuint, uniformBlockName::Ptr{GLchar})::GLuint
@glfunc glInvalidateFramebuffer(target::GLenum, numAttachments::GLsizei, attachments::Ptr{GLenum})::Cvoid
@glfunc glVertexAttribP2uiv(index::GLuint, type_::GLenum, normalized::GLboolean, value::Ptr{GLuint})::Cvoid
@glfunc glIsEnabledi(target::GLenum, index::GLuint)::Bool
@glfunc glVertexAttribP2ui(index::GLuint, type_::GLenum, normalized::GLboolean, value::GLuint)::Cvoid
@glfunc glDrawArrays(mode::GLenum, first::GLint, count::GLsizei)::Cvoid
@glfunc glGetActiveAttrib(program::GLuint, index::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, size::Ptr{GLint}, type_::Ptr{GLenum}, name::Ptr{GLchar})::Cvoid
@glfunc glCopyTexImage1D(target::GLenum, level::GLint, internalformat::GLenum, x::GLint, y::GLint, width::GLsizei, border::GLint)::Cvoid
@glfunc glProgramUniform2f(program::GLuint, location::GLint, v0::GLfloat, v1::GLfloat)::Cvoid
@glfunc glCopyImageSubData(srcName::GLuint, srcTarget::GLenum, srcLevel::GLint, srcX::GLint, srcY::GLint, srcZ::GLint, dstName::GLuint, dstTarget::GLenum, dstLevel::GLint, dstX::GLint, dstY::GLint, dstZ::GLint, srcWidth::GLsizei, srcHeight::GLsizei, srcDepth::GLsizei)::Cvoid
@glfunc glGetError()::GLenum
@glfunc glNormalP3uiv(type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glTexStorage2D(target::GLenum, levels::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glProgramUniformMatrix4x3fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glDrawRangeElementsBaseVertex(mode::GLenum, start::GLuint, END::GLuint, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, basevertex::GLint)::Cvoid
@glfunc glGenProgramPipelines(n::GLsizei, pipelines::Ptr{GLuint})::Cvoid
@glfunc glVertexAttribI4uiv(index::GLuint, v::Ptr{GLuint})::Cvoid
@glfunc glActiveShaderProgram(pipeline::GLuint, program::GLuint)::Cvoid
@glfunc glGetInteger64v(pname::GLenum, params::Ptr{GLint64})::Cvoid
@glfunc glPrimitiveRestartIndex(index::GLuint)::Cvoid
@glfunc glDeleteShader(shader::GLuint)::Cvoid
@glfunc glGenBuffers(n::GLsizei, buffers::Ptr{GLuint})::Cvoid
@glfunc glTexParameterfv(target::GLenum, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glGetSamplerParameteriv(sampler::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glProgramUniform3d(program::GLuint, location::GLint, v0::GLdouble, v1::GLdouble, v2::GLdouble)::Cvoid
@glfunc glVertexAttribI1iv(index::GLuint, v::Ptr{GLint})::Cvoid
@glfunc glUniform2uiv(location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glUniform1i(location::GLint, v0::GLint)::Cvoid
@glfunc glUniform3uiv(location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glProgramUniform1uiv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glUniform1iv(location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glUniform1fv(location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glScissorIndexedv(index::GLuint, v::Ptr{GLint})::Cvoid
@glfunc glIsTexture(texture::GLuint)::Bool
@glfunc glDrawArraysInstancedBaseInstance(mode::GLenum, first::GLint, count::GLsizei, instancecount::GLsizei, baseinstance::GLuint)::Cvoid
@glfunc glVertexAttribI1i(index::GLuint, x::GLint)::Cvoid
@glfunc glVertexAttribI3ui(index::GLuint, x::GLuint, y::GLuint, z::GLuint)::Cvoid
@glfunc glGetActiveUniformBlockiv(program::GLuint, uniformBlockIndex::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glVertexAttribI3i(index::GLuint, x::GLint, y::GLint, z::GLint)::Cvoid
@glfunc glBlendFunci(buf::GLuint, src::GLenum, dst::GLenum)::Cvoid
@glfunc glGetVertexAttribdv(index::GLuint, pname::GLenum, params::Ptr{GLdouble})::Cvoid
@glfunc glBlendEquationSeparate(modeRGB::GLenum, modeAlpha::GLenum)::Cvoid
@glfunc glFenceSync(condition::GLenum, flags::GLbitfield)::GLsync
@glfunc glSamplerParameterfv(sampler::GLuint, pname::GLenum, param::Ptr{GLfloat})::Cvoid
@glfunc glIsShader(shader::GLuint)::Bool
@glfunc glProgramUniform3f(program::GLuint, location::GLint, v0::GLfloat, v1::GLfloat, v2::GLfloat)::Cvoid
@glfunc glUniformMatrix4x3fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glGetQueryObjectuiv(id::GLuint, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glPointParameterf(pname::GLenum, param::GLfloat)::Cvoid
@glfunc glIndexubv(c::Ptr{GLubyte})::Cvoid
@glfunc glClearBufferiv(buffer::GLenum, drawbuffer::GLint, value::Ptr{GLint})::Cvoid
@glfunc glBindVertexArray(array::GLuint)::Cvoid
@glfunc glGetInternalformati64v(target::GLenum, internalformat::GLenum, pname::GLenum, bufSize::GLsizei, params::Ptr{GLint64})::Cvoid
@glfunc glVertexP4uiv(type_::GLenum, value::Ptr{GLuint})::Cvoid
@glfunc glVertexAttribI2uiv(index::GLuint, v::Ptr{GLuint})::Cvoid
@glfunc glGetProgramResourceiv(program::GLuint, programInterface::GLenum, index::GLuint, propCount::GLsizei, props::Ptr{GLenum}, bufSize::GLsizei, length::Ptr{GLsizei}, params::Ptr{GLint})::Cvoid
@glfunc glViewport(x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glTexImage1D(target::GLenum, level::GLint, internalformat::GLint, width::GLsizei, border::GLint, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glUniform1uiv(location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glProgramUniform4ui(program::GLuint, location::GLint, v0::GLuint, v1::GLuint, v2::GLuint, v3::GLuint)::Cvoid
@glfunc glUniform1f(location::GLint, v0::GLfloat)::Cvoid
@glfunc glVertexAttribP3uiv(index::GLuint, type_::GLenum, normalized::GLboolean, value::Ptr{GLuint})::Cvoid
@glfunc glBeginQuery(target::GLenum, id::GLuint)::Cvoid
@glfunc glMultiDrawArrays(mode::GLenum, first::Ptr{GLint}, count::Ptr{GLsizei}, drawcount::GLsizei)::Cvoid
@glfunc glDrawBuffer(mode::GLenum)::Cvoid
@glfunc glLogicOp(opcode::GLenum)::Cvoid
@glfunc glObjectLabel(identifier::GLenum, name::GLuint, length::GLsizei, label::Ptr{GLchar})::Cvoid
@glfunc glUniformMatrix3x2dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glUniform3d(location::GLint, x::GLdouble, y::GLdouble, z::GLdouble)::Cvoid
@glfunc glDepthRangeIndexed(index::GLuint, n::GLdouble, f::GLdouble)::Cvoid
@glfunc glGetProgramBinary(program::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, binaryFormat::Ptr{GLenum}, binary::Ptr{Cvoid})::Cvoid
@glfunc glPointSize(size::GLfloat)::Cvoid
@glfunc glGetUniformfv(program::GLuint, location::GLint, params::Ptr{GLfloat})::Cvoid
@glfunc glClearBufferfv(buffer::GLenum, drawbuffer::GLint, value::Ptr{GLfloat})::Cvoid
@glfunc glCopyTexSubImage1D(target::GLenum, level::GLint, xoffset::GLint, x::GLint, y::GLint, width::GLsizei)::Cvoid
@glfunc glIsEnabled(cap::GLenum)::Bool
@glfunc glCreateShader(type_::GLenum)::GLuint
@glfunc glTextureStorage2DEXT(texture::GLuint, target::GLenum, levels::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glPixelStoref(pname::GLenum, param::GLfloat)::Cvoid
@glfunc glGetMultisamplefv(pname::GLenum, index::GLuint, val::Ptr{GLfloat})::Cvoid
@glfunc glGetFragDataIndex(program::GLuint, name::Ptr{GLchar})::GLint
@glfunc glGetUniformIndices(program::GLuint, uniformCount::GLsizei, uniformNames::Ptr{Ptr{GLchar}}, uniformIndices::Ptr{GLuint})::Cvoid
@glfunc glUniform1dv(location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glGetFragDataLocation(program::GLuint, name::Ptr{GLchar})::GLint
@glfunc glMultiTexCoordP2ui(texture::GLenum, type_::GLenum, coords::GLuint)::Cvoid
@glfunc glDepthFunc(func_::GLenum)::Cvoid
@glfunc glVertexAttribI4iv(index::GLuint, v::Ptr{GLint})::Cvoid
@glfunc glUniformMatrix2x4fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glBufferSubData(target::GLenum, offset::GLintptr, size::GLsizeiptr, data::Ptr{Cvoid})::Cvoid
@glfunc glUniformMatrix3x4fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glBindBufferRange(target::GLenum, index::GLuint, buffer::GLuint, offset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glGenQueries(n::GLsizei, ids::Ptr{GLuint})::Cvoid
@glfunc glDebugMessageCallback(callback::Ptr{Cvoid}, userParam::Ptr{Cvoid})::Cvoid
@glfunc glDebugMessageCallbackARB(callback::Ptr{Cvoid}, userParam::Ptr{Cvoid})::Cvoid
@glfunc glInvalidateTexSubImage(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei)::Cvoid
@glfunc glColorP3uiv(type_::GLenum, color::Ptr{GLuint})::Cvoid
@glfunc glTexStorage1D(target::GLenum, levels::GLsizei, internalformat::GLenum, width::GLsizei)::Cvoid
@glfunc glBlendFunc(sfactor::GLenum, dfactor::GLenum)::Cvoid
@glfunc glGetBooleanv(pname::GLenum, params::Ptr{GLboolean})::Cvoid
@glfunc glUniformMatrix3x4dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glGetObjectLabel(identifier::GLenum, name::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, label::Ptr{GLchar})::Cvoid
@glfunc glSampleCoverage(value::GLfloat, invert::GLboolean)::Cvoid
@glfunc glProgramUniformMatrix3x2fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glVertexAttribL2dv(index::GLuint, v::Ptr{GLdouble})::Cvoid
@glfunc glGetFloatv(pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glProvokingVertex(mode::GLenum)::Cvoid
@glfunc glVertexAttribL3d(index::GLuint, x::GLdouble, y::GLdouble, z::GLdouble)::Cvoid
@glfunc glClearDepth(depth::GLdouble)::Cvoid
@glfunc glInvalidateBufferData(buffer::GLuint)::Cvoid
@glfunc glProgramParameteri(program::GLuint, pname::GLenum, value::GLint)::Cvoid
@glfunc glUniformMatrix3x2fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glDisable(cap::GLenum)::Cvoid
@glfunc glMultiDrawElementsIndirect(mode::GLenum, type_::GLenum, indirect::Ptr{Cvoid}, drawcount::GLsizei, stride::GLsizei)::Cvoid
@glfunc glMultiDrawElementsBaseVertex(mode::GLenum, count::Ptr{GLsizei}, type_::GLenum, indices::Ptr{Ptr{Cvoid}}, drawcount::GLsizei, basevertex::Ptr{GLint})::Cvoid
@glfunc glFlushMappedBufferRange(target::GLenum, offset::GLintptr, length::GLsizeiptr)::Cvoid
@glfunc glGetUniformdv(program::GLuint, location::GLint, params::Ptr{GLdouble})::Cvoid
@glfunc glGetProgramInterfaceiv(program::GLuint, programInterface::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glTransformFeedbackVaryings(program::GLuint, count::GLsizei, varyings::Ptr{Ptr{GLchar}}, bufferMode::GLenum)::Cvoid
@glfunc glGetVertexAttribIuiv(index::GLuint, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glGetShaderInfoLog(shader::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, infoLog::Ptr{GLchar})::Cvoid
@glfunc glRenderbufferStorageMultisample(target::GLenum, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glUniformMatrix2x3fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glUseProgramStages(pipeline::GLuint, stages::GLbitfield, program::GLuint)::Cvoid
@glfunc glVertexAttribLFormat(attribindex::GLuint, size::GLint, type_::GLenum, relativeoffset::GLuint)::Cvoid
@glfunc glProgramUniform1i(program::GLuint, location::GLint, v0::GLint)::Cvoid
@glfunc glGetFramebufferParameteriv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glDeleteProgramPipelines(n::GLsizei, pipelines::Ptr{GLuint})::Cvoid
@glfunc glProgramUniform2fv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glProgramUniform1iv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glBindBuffer(target::GLenum, buffer::GLuint)::Cvoid
@glfunc glGetAttribLocation(program::GLuint, name::Ptr{GLchar})::GLint
@glfunc glProgramUniform3ui(program::GLuint, location::GLint, v0::GLuint, v1::GLuint, v2::GLuint)::Cvoid
@glfunc glTexParameteri(target::GLenum, pname::GLenum, param::GLint)::Cvoid
@glfunc glWaitSync(sync::GLsync, flags::GLbitfield, timeout::GLuint64)::Cvoid
@glfunc glTextureStorage3DMultisampleEXT(texture::GLuint, target::GLenum, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glIsVertexArray(array::GLuint)::Bool
@glfunc glEnableVertexAttribArray(index::GLuint)::Cvoid
@glfunc glObjectPtrLabel(ptr::Ptr{Cvoid}, length::GLsizei, label::Ptr{GLchar})::Cvoid
@glfunc glProgramBinary(program::GLuint, binaryFormat::GLenum, binary::Ptr{Cvoid}, length::GLsizei)::Cvoid
@glfunc glCompressedTexImage1D(target::GLenum, level::GLint, internalformat::GLenum, width::GLsizei, border::GLint, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glTexCoordP2uiv(type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glUseProgram(program::GLuint)::Cvoid
@glfunc glProgramUniform3i(program::GLuint, location::GLint, v0::GLint, v1::GLint, v2::GLint)::Cvoid
@glfunc glVertexAttribI2ui(index::GLuint, x::GLuint, y::GLuint)::Cvoid
@glfunc glGetActiveSubroutineUniformiv(program::GLuint, shadertype::GLenum, index::GLuint, pname::GLenum, values::Ptr{GLint})::Cvoid
@glfunc glDepthMask(flag::GLboolean)::Cvoid
@glfunc glPolygonMode(face::GLenum, mode::GLenum)::Cvoid
@glfunc glVertexAttribI3uiv(index::GLuint, v::Ptr{GLuint})::Cvoid
@glfunc glFramebufferTexture1D(target::GLenum, attachment::GLenum, textarget::GLenum, texture::GLuint, level::GLint)::Cvoid
@glfunc glGetActiveSubroutineUniformName(program::GLuint, shadertype::GLenum, index::GLuint, bufsize::GLsizei, length::Ptr{GLsizei}, name::Ptr{GLchar})::Cvoid
@glfunc glGenFramebuffers(n::GLsizei, framebuffers::Ptr{GLuint})::Cvoid
@glfunc glFramebufferTextureLayer(target::GLenum, attachment::GLenum, texture::GLuint, level::GLint, layer::GLint)::Cvoid
@glfunc glViewportArrayv(first::GLuint, count::GLsizei, v::Ptr{GLfloat})::Cvoid
@glfunc glDrawRangeElements(mode::GLenum, start::GLuint, END::GLuint, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid})::Cvoid
@glfunc glCopyTexSubImage3D(target::GLenum, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glStencilMaskSeparate(face::GLenum, mask::GLuint)::Cvoid
@glfunc glGetProgramInfoLog(program::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, infoLog::Ptr{GLchar})::Cvoid
@glfunc glGetProgramResourceIndex(program::GLuint, programCinterface::GLenum, name::Ptr{GLchar})::GLuint
@glfunc glBlitFramebuffer(srcX0::GLint, srcY0::GLint, srcX1::GLint, srcY1::GLint, dstX0::GLint, dstY0::GLint, dstX1::GLint, dstY1::GLint, mask::GLbitfield, filter::GLenum)::Cvoid
@glfunc glBeginTransformFeedback(primitiveMode::GLenum)::Cvoid
@glfunc glVertexAttribI4bv(index::GLuint, v::Ptr{GLbyte})::Cvoid
@glfunc glIsSampler(sampler::GLuint)::Bool
@glfunc glVertexAttribI4ui(index::GLuint, x::GLuint, y::GLuint, z::GLuint, w::GLuint)::Cvoid
@glfunc glProgramUniformMatrix3x4dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glCheckFramebufferStatus(target::GLenum)::GLenum
@glfunc glProgramUniformMatrix3fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glTextureBufferRangeEXT(texture::GLuint, target::GLenum, internalformat::GLenum, buffer::GLuint, offset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glInvalidateSubFramebuffer(target::GLenum, numAttachments::GLsizei, attachments::Ptr{GLenum}, x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glDeleteTransformFeedbacks(n::GLsizei, ids::Ptr{GLuint})::Cvoid
@glfunc glGetActiveUniformName(program::GLuint, uniformIndex::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, uniformName::Ptr{GLchar})::Cvoid
@glfunc glPatchParameterfv(pname::GLenum, values::Ptr{GLfloat})::Cvoid
@glfunc glProgramUniform4d(program::GLuint, location::GLint, v0::GLdouble, v1::GLdouble, v2::GLdouble, v3::GLdouble)::Cvoid
@glfunc glSamplerParameteriv(sampler::GLuint, pname::GLenum, param::Ptr{GLint})::Cvoid
@glfunc glTextureStorage2DMultisampleEXT(texture::GLuint, target::GLenum, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glStencilOpSeparate(face::GLenum, sfail::GLenum, dpfail::GLenum, dppass::GLenum)::Cvoid
@glfunc glScissorIndexed(index::GLuint, left::GLint, bottom::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glVertexAttribI3iv(index::GLuint, v::Ptr{GLint})::Cvoid
@glfunc glBeginQueryIndexed(target::GLenum, index::GLuint, id::GLuint)::Cvoid
@glfunc glValidateProgramPipeline(pipeline::GLuint)::Cvoid
@glfunc glUnmapBuffer(target::GLenum)::Bool
@glfunc glEndQuery(target::GLenum)::Cvoid
@glfunc glStencilOp(fail::GLenum, zfail::GLenum, zpass::GLenum)::Cvoid
@glfunc glCompressedTexImage3D(target::GLenum, level::GLint, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei, border::GLint, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glSampleMaski(index::GLuint, mask::GLbitfield)::Cvoid
@glfunc glDisableVertexAttribArray(index::GLuint)::Cvoid
@glfunc glVertexAttribI2i(index::GLuint, x::GLint, y::GLint)::Cvoid
@glfunc glCompressedTexSubImage2D(target::GLenum, level::GLint, xoffset::GLint, yoffset::GLint, width::GLsizei, height::GLsizei, format::GLenum, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glGetVertexAttribPointerv(index::GLuint, pname::GLenum, pointer::Ptr{Ptr{Cvoid}})::Cvoid
@glfunc glDeleteFramebuffers(n::GLsizei, framebuffers::Ptr{GLuint})::Cvoid
@glfunc glUniformMatrix4x2dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glInvalidateBufferSubData(buffer::GLuint, offset::GLintptr, length::GLsizeiptr)::Cvoid
@glfunc glFramebufferTexture(target::GLenum, attachment::GLenum, texture::GLuint, level::GLint)::Cvoid
@glfunc glTexImage3DMultisample(target::GLenum, samples::GLsizei, internalformat::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glVertexAttribL1d(index::GLuint, x::GLdouble)::Cvoid
@glfunc glTextureStorage3DEXT(texture::GLuint, target::GLenum, levels::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei)::Cvoid
@glfunc glGetBufferParameteriv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glCopyBufferSubData(readTarget::GLenum, writeTarget::GLenum, readOffset::GLintptr, writeOffset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glSamplerParameterf(sampler::GLuint, pname::GLenum, param::GLfloat)::Cvoid
@glfunc glColorMask(red::GLboolean, green::GLboolean, blue::GLboolean, alpha::GLboolean)::Cvoid
@glfunc glBlendFuncSeparate(sfactorRGB::GLenum, dfactorRGB::GLenum, sfactorAlpha::GLenum, dfactorAlpha::GLenum)::Cvoid
@glfunc glUniform3fv(location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glVertexAttribL1dv(index::GLuint, v::Ptr{GLdouble})::Cvoid
@glfunc glUniform4i(location::GLint, v0::GLint, v1::GLint, v2::GLint, v3::GLint)::Cvoid
@glfunc glMultiTexCoordP3ui(texture::GLenum, type_::GLenum, coords::GLuint)::Cvoid
@glfunc glDrawBuffers(n::GLsizei, bufs::Ptr{GLenum})::Cvoid
@glfunc glColorP3ui(type_::GLenum, color::GLuint)::Cvoid
@glfunc glProgramUniformMatrix2x4dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glVertexP2ui(type_::GLenum, value::GLuint)::Cvoid
@glfunc glDrawElementsInstanced(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, instancecount::GLsizei)::Cvoid
@glfunc glDrawElementsInstancedEXT(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, instancecount::GLsizei)::Cvoid
@glfunc glGetUniformiv(program::GLuint, location::GLint, params::Ptr{GLint})::Cvoid
@glfunc glTexImage2D(target::GLenum, level::GLint, internalformat::GLint, width::GLsizei, height::GLsizei, border::GLint, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetQueryObjecti64v(id::GLuint, pname::GLenum, params::Ptr{GLint64})::Cvoid
@glfunc glGetTexImage(target::GLenum, level::GLint, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetTexLevelParameteriv(target::GLenum, level::GLint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glTexSubImage2D(target::GLenum, level::GLint, xoffset::GLint, yoffset::GLint, width::GLsizei, height::GLsizei, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glDeleteVertexArrays(n::GLsizei, arrays::Ptr{GLuint})::Cvoid
@glfunc glIsRenderbuffer(renderbuffer::GLuint)::Bool
@glfunc glGetProgramResourceLocationIndex(program::GLuint, programCinterface::GLenum, name::Ptr{GLchar})::GLint
@glfunc glGetInteger64i_v(target::GLenum, index::GLuint, data::Ptr{GLint64})::Cvoid
@glfunc glProgramUniform1ui(program::GLuint, location::GLint, v0::GLuint)::Cvoid
@glfunc glUniform4iv(location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glProgramUniform3fv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLfloat})::Cvoid
@glfunc glVertexAttribL2d(index::GLuint, x::GLdouble, y::GLdouble)::Cvoid
@glfunc glUniform2d(location::GLint, x::GLdouble, y::GLdouble)::Cvoid
@glfunc glGetBufferParameteri64v(target::GLenum, pname::GLenum, params::Ptr{GLint64})::Cvoid
@glfunc glTexCoordP1ui(type_::GLenum, coords::GLuint)::Cvoid
@glfunc glDeleteBuffers(n::GLsizei, buffers::Ptr{GLuint})::Cvoid
@glfunc glProgramUniformMatrix2x4fv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glMultiTexCoordP4uiv(texture::GLenum, type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glVertexAttribPointer(index::GLuint, size::GLint, type_::GLenum, normalized::GLboolean, stride::GLsizei, pointer::Ptr{Cvoid})::Cvoid
@glfunc glVertexP3uiv(type_::GLenum, value::Ptr{GLuint})::Cvoid
@glfunc glDispatchComputeIndirect(indirect::GLintptr)::Cvoid
@glfunc glProgramUniform1d(program::GLuint, location::GLint, v0::GLdouble)::Cvoid
@glfunc glGetFloati_v(target::GLenum, index::GLuint, data::Ptr{GLfloat})::Cvoid
@glfunc glDebugMessageControl(source::GLenum, type_::GLenum, severity::GLenum, count::GLsizei, ids::Ptr{GLuint}, enabled::GLboolean)::Cvoid
@glfunc glVertexAttribFormat(attribindex::GLuint, size::GLint, type_::GLenum, normalized::GLboolean, relativeoffset::GLuint)::Cvoid
@glfunc glClearColor(red::GLfloat, green::GLfloat, blue::GLfloat, alpha::GLfloat)::Cvoid
@glfunc glClearTexImage(texture::GLuint, level::GLint, format::GLenum, type::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glClearTexSubImage(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, format::GLenum, type::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glIsFramebuffer(framebuffer::GLuint)::Bool
@glfunc glVertexAttribP1uiv(index::GLuint, type_::GLenum, normalized::GLboolean, value::Ptr{GLuint})::Cvoid
@glfunc glUniform3i(location::GLint, v0::GLint, v1::GLint, v2::GLint)::Cvoid
@glfunc glGetString(name::GLenum)::Ptr{GLchar}
@glfunc glGenTextures(n::GLsizei, textures::Ptr{GLuint})::Cvoid
@glfunc glFramebufferRenderbuffer(target::GLenum, attachment::GLenum, renderbuffertarget::GLenum, renderbuffer::GLuint)::Cvoid
@glfunc glGetQueryObjectiv(id::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glBindProgramPipeline(pipeline::GLuint)::Cvoid
@glfunc glGetActiveUniformBlockName(program::GLuint, uniformBlockIndex::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, uniformBlockName::Ptr{GLchar})::Cvoid
@glfunc glUniformMatrix2fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glTexStorage3D(target::GLenum, levels::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei)::Cvoid
@glfunc glTexCoordP3ui(type_::GLenum, coords::GLuint)::Cvoid
@glfunc glDeleteSync(sync::GLsync)::Cvoid
@glfunc glBindFragDataLocation(program::GLuint, color::GLuint, name::Ptr{GLchar})::Cvoid
@glfunc glGetShaderPrecisionFormat(shadertype::GLenum, precisiontype::GLenum, range_::Ptr{GLint}, precision::Ptr{GLint})::Cvoid
@glfunc glGenTransformFeedbacks(n::GLsizei, ids::Ptr{GLuint})::Cvoid
@glfunc glProgramUniform4iv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glHint(target::GLenum, mode::GLenum)::Cvoid
@glfunc glVertexArrayVertexAttribBindingEXT(vaobj::GLuint, attribindex::GLuint, bindingindex::GLuint)::Cvoid
@glfunc glDrawTransformFeedback(mode::GLenum, id::GLuint)::Cvoid
@glfunc glUniform1ui(location::GLint, v0::GLuint)::Cvoid
@glfunc glTexSubImage3D(target::GLenum, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, format::GLenum, type_::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glBeginConditionalRender(id::GLuint, mode::GLenum)::Cvoid
@glfunc glGetActiveUniformsiv(program::GLuint, uniformCount::GLsizei, uniformIndices::Ptr{GLuint}, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetStringi(name::GLenum, index::GLuint)::Ptr{GLchar}
@glfunc glMultiDrawArraysIndirect(mode::GLenum, indirect::Ptr{Cvoid}, drawcount::GLsizei, stride::GLsizei)::Cvoid
@glfunc glDepthRange(near_::GLdouble, far_::GLdouble)::Cvoid
@glfunc glUniform2ui(location::GLint, v0::GLuint, v1::GLuint)::Cvoid
@glfunc glBindFragDataLocationIndexed(program::GLuint, colorNumber::GLuint, index::GLuint, name::Ptr{GLchar})::Cvoid
@glfunc glDrawElementsBaseVertex(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, basevertex::GLint)::Cvoid
@glfunc glMultiTexCoordP4ui(texture::GLenum, type_::GLenum, coords::GLuint)::Cvoid
@glfunc glGetTexParameterfv(target::GLenum, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glVertexArrayBindVertexBufferEXT(vaobj::GLuint, bindingindex::GLuint, buffer::GLuint, offset::GLintptr, stride::GLsizei)::Cvoid
@glfunc glScissor(x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glClearDepthf(d::GLfloat)::Cvoid
@glfunc glProgramUniformMatrix4x2dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glDrawElementsInstancedBaseVertex(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid}, instancecount::GLsizei, basevertex::GLint)::Cvoid
@glfunc glClearNamedBufferDataEXT(buffer::GLuint, internalformat::GLenum, format::GLenum, type_::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glProgramUniform2iv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glStencilMask(mask::GLuint)::Cvoid
@glfunc glCopyTexSubImage2D(target::GLenum, level::GLint, xoffset::GLint, yoffset::GLint, x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glGetTexLevelParameterfv(target::GLenum, level::GLint, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glColorMaski(index::GLuint, r::GLboolean, g::GLboolean, b::GLboolean, a::GLboolean)::Cvoid
@glfunc glVertexP3ui(type_::GLenum, value::GLuint)::Cvoid
@glfunc glUniformMatrix2dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glGetProgramPipelineInfoLog(pipeline::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, infoLog::Ptr{GLchar})::Cvoid
@glfunc glVertexAttribP1ui(index::GLuint, type_::GLenum, normalized::GLboolean, value::GLuint)::Cvoid
@glfunc glUniform3iv(location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glUniformSubroutinesuiv(shadertype::GLenum, count::GLsizei, indices::Ptr{GLuint})::Cvoid
@glfunc glPatchParameteri(pname::GLenum, value::GLint)::Cvoid
@glfunc glGenVertexArrays(n::GLsizei, arrays::Ptr{GLuint})::Cvoid
@glfunc glStencilFunc(func_::GLenum, ref::GLint, mask::GLuint)::Cvoid
@glfunc glGetInternalformativ(target::GLenum, internalformat::GLenum, pname::GLenum, bufSize::GLsizei, params::Ptr{GLint})::Cvoid
@glfunc glMinSampleShading(value::GLfloat)::Cvoid
@glfunc glProgramUniform2uiv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLuint})::Cvoid
@glfunc glGetActiveUniform(program::GLuint, index::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, size::Ptr{GLint}, type_::Ptr{GLenum}, name::Ptr{GLchar})::Cvoid
@glfunc glVertexAttribI4i(index::GLuint, x::GLint, y::GLint, z::GLint, w::GLint)::Cvoid
@glfunc glClearNamedBufferSubDataEXT(buffer::GLuint, internalformat::GLenum, offset::GLsizeiptr, size::GLsizeiptr, format::GLenum, type_::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glUniformMatrix4x2fv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLfloat})::Cvoid
@glfunc glDeleteTextures(n::GLsizei, textures::Ptr{GLuint})::Cvoid
@glfunc glProgramUniformMatrix4dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glCullFace(mode::GLenum)::Cvoid
@glfunc glProgramUniformMatrix3x2dv(program::GLuint, location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glTexBufferRange(target::GLenum, internalformat::GLenum, buffer::GLuint, offset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glClearBufferSubData(target::GLenum, internalformat::GLenum, offset::GLintptr, size::GLsizeiptr, format::GLenum, type_::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glLineWidth(width::GLfloat)::Cvoid
@glfunc glCompressedTexSubImage3D(target::GLenum, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, format::GLenum, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glVertexArrayVertexBindingDivisorEXT(vaobj::GLuint, bindingindex::GLuint, divisor::GLuint)::Cvoid
@glfunc glClearBufferfi(buffer::GLenum, drawbuffer::GLint, depth::GLfloat, stencil::GLint)::Cvoid
@glfunc glIsProgram(program::GLuint)::Bool
@glfunc glGetVertexAttribIiv(index::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetTransformFeedbackVarying(program::GLuint, index::GLuint, bufSize::GLsizei, length::Ptr{GLsizei}, size::Ptr{GLsizei}, type_::Ptr{GLenum}, name::Ptr{GLchar})::Cvoid
@glfunc glVertexAttribLPointer(index::GLuint, size::GLint, type_::GLenum, stride::GLsizei, pointer::Ptr{Cvoid})::Cvoid
@glfunc glGetFramebufferAttachmentParameteriv(target::GLenum, attachment::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetActiveAtomicCounterBufferiv(program::GLuint, bufferIndex::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glProgramUniform3dv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLdouble})::Cvoid
@glfunc glUniformMatrix4x3dv(location::GLint, count::GLsizei, transpose::GLboolean, value::Ptr{GLdouble})::Cvoid
@glfunc glVertexAttribI4ubv(index::GLuint, v::Ptr{GLubyte})::Cvoid
@glfunc glCreateProgram()::GLuint
@glfunc glUniformBlockBinding(program::GLuint, uniformBlockIndex::GLuint, uniformBlockBinding::GLuint)::Cvoid
@glfunc glEndQueryIndexed(target::GLenum, index::GLuint)::Cvoid
@glfunc glTexStorage2DMultisample(target::GLenum, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glGetSynciv(sync::GLsync, pname::GLenum, bufSize::GLsizei, length::Ptr{GLsizei}, values::Ptr{GLint})::Cvoid
@glfunc glClampColor(target::GLenum, clamp::GLenum)::Cvoid
@glfunc glVertexAttribP3ui(index::GLuint, type_::GLenum, normalized::GLboolean, value::GLuint)::Cvoid
@glfunc glBindAttribLocation(program::GLuint, index::GLuint, name::Ptr{GLchar})::Cvoid
@glfunc glBindVertexBuffer(bindingindex::GLuint, buffer::GLuint, offset::GLintptr, stride::GLsizei)::Cvoid
@glfunc glValidateProgram(program::GLuint)::Cvoid
@glfunc glGetSamplerParameterfv(sampler::GLuint, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glGetBooleani_v(target::GLenum, index::GLuint, data::Ptr{GLboolean})::Cvoid
@glfunc glMultiTexCoordP2uiv(texture::GLenum, type_::GLenum, coords::Ptr{GLuint})::Cvoid
@glfunc glFramebufferTexture2D(target::GLenum, attachment::GLenum, textarget::GLenum, texture::GLuint, level::GLint)::Cvoid
@glfunc glEndTransformFeedback()::Cvoid
@glfunc glGetSubroutineUniformLocation(program::GLuint, shadertype::GLenum, name::Ptr{GLchar})::GLint
@glfunc glGetQueryiv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glProgramUniform2d(program::GLuint, location::GLint, v0::GLdouble, v1::GLdouble)::Cvoid
@glfunc glProgramUniform3iv(program::GLuint, location::GLint, count::GLsizei, value::Ptr{GLint})::Cvoid
@glfunc glIsSync(sync::GLsync)::Bool
@glfunc glGetTexParameterIiv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetObjectPtrLabel(ptr::Ptr{Cvoid}, bufSize::GLsizei, length::Ptr{GLsizei}, label::Ptr{GLchar})::Cvoid
@glfunc glGetUniformSubroutineuiv(shadertype::GLenum, location::GLint, params::Ptr{GLuint})::Cvoid
@glfunc glTexBuffer(target::GLenum, internalformat::GLenum, buffer::GLuint)::Cvoid
@glfunc glDeleteQueries(n::GLsizei, ids::Ptr{GLuint})::Cvoid
@glfunc glDisablei(target::GLenum, index::GLuint)::Cvoid
@glfunc glNamedFramebufferParameteriEXT(framebuffer::GLuint, pname::GLenum, param::GLint)::Cvoid
@glfunc glGetUniformLocation(program::GLuint, name::Ptr{GLchar})::GLint
@glfunc glMemoryBarrier(barriers::GLbitfield)::Cvoid
@glfunc glGetDoublei_v(target::GLenum, index::GLuint, data::Ptr{GLdouble})::Cvoid
@glfunc glClearBufferuiv(buffer::GLenum, drawbuffer::GLint, value::Ptr{GLuint})::Cvoid
@glfunc glRenderbufferStorage(target::GLenum, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glViewportIndexedf(index::GLuint, x::GLfloat, y::GLfloat, w::GLfloat, h::GLfloat)::Cvoid
@glfunc glDrawElements(mode::GLenum, count::GLsizei, type_::GLenum, indices::Ptr{Cvoid})::Cvoid
@glfunc glVertexAttribI1ui(index::GLuint, x::GLuint)::Cvoid
@glfunc glUniform2i(location::GLint, v0::GLint, v1::GLint)::Cvoid
@glfunc glGetQueryIndexediv(target::GLenum, index::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glAttachShader(program::GLuint, shader::GLuint)::Cvoid
@glfunc glDrawTransformFeedbackStreamInstanced(mode::GLenum, id::GLuint, stream::GLuint, instancecount::GLsizei)::Cvoid
@glfunc glIsQuery(id::GLuint)::Bool
@glfunc glViewportIndexedfv(index::GLuint, v::Ptr{GLfloat})::Cvoid
@glfunc glVertexBindingDivisor(bindingindex::GLuint, divisor::GLuint)::Cvoid
@glfunc glCopyTexImage2D(target::GLenum, level::GLint, internalformat::GLenum, x::GLint, y::GLint, width::GLsizei, height::GLsizei, border::GLint)::Cvoid
@glfunc glDeleteSamplers(count::GLsizei, samplers::Ptr{GLuint})::Cvoid
@glfunc glGetProgramStageiv(program::GLuint, shadertype::GLenum, pname::GLenum, values::Ptr{GLint})::Cvoid
@glfunc glBindSampler(unit::GLuint, sampler::GLuint)::Cvoid
@glfunc glBindRenderbuffer(target::GLenum, renderbuffer::GLuint)::Cvoid
@glfunc glGetSamplerParameterIuiv(sampler::GLuint, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glGetTexParameteriv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glVertexAttribIFormat(attribindex::GLuint, size::GLint, type_::GLenum, relativeoffset::GLuint)::Cvoid
@glfunc glBlendEquationSeparatei(buf::GLuint, modeRGB::GLenum, modeAlpha::GLenum)::Cvoid
@glfunc glTexImage2DMultisample(target::GLenum, samples::GLsizei, internalformat::GLint, width::GLsizei, height::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glDepthRangef(n::GLfloat, f::GLfloat)::Cvoid
@glfunc glUniform4f(location::GLint, v0::GLfloat, v1::GLfloat, v2::GLfloat, v3::GLfloat)::Cvoid
@glfunc glMapBuffer(target::GLenum, access::GLenum)::Ptr{Cvoid}
@glfunc glClipControl(origin::GLenum, depth::GLenum)::Cvoid
@glfunc glMemoryBarrierByRegion(barriers::GLbitfield)::Cvoid
@glfunc glCreateTransformFeedbacks(n::GLsizei, ids::Ptr{GLuint})::Cvoid
@glfunc glTransformFeedbackBufferBase(xfb::GLuint, index::GLuint, buffer::GLuint)::Cvoid
@glfunc glTransformFeedbackBufferRange(xfb::GLuint, index::GLuint, buffer::GLuint, offset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glGetTransformFeedbackiv(xfb::GLuint, pname::GLenum, param::Ptr{GLint})::Cvoid
@glfunc glGetTransformFeedbacki_v(xfb::GLuint, pname::GLenum, index::GLuint, param::Ptr{GLint})::Cvoid
@glfunc glGetTransformFeedbacki64_v(xfb::GLuint, pname::GLenum, index::GLuint, param::Ptr{GLint64})::Cvoid
@glfunc glCreateBuffers(n::GLsizei, buffers::Ptr{GLuint})::Cvoid
@glfunc glNamedBufferStorage(buffer::GLuint, size::GLsizeiptr, data::Ptr{Cvoid}, flags::GLbitfield)::Cvoid
@glfunc glNamedBufferData(buffer::GLuint, size::GLsizeiptr, data::Ptr{Cvoid}, usage::GLenum)::Cvoid
@glfunc glNamedBufferSubData(buffer::GLuint, offset::GLintptr, size::GLsizeiptr, data::Ptr{Cvoid})::Cvoid
@glfunc glCopyNamedBufferSubData(readBuffer::GLuint, writeBuffer::GLuint, readOffset::GLintptr, writeOffset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glClearNamedBufferData(buffer::GLuint, internalformat::GLenum, format::GLenum, type::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glClearNamedBufferSubData(buffer::GLuint, internalformat::GLenum, offset::GLintptr, size::GLsizeiptr, format::GLenum, type::GLenum, data::Ptr{Cvoid})::Cvoid
@glfunc glMapNamedBuffer(buffer::GLuint, access::GLenum)::Ptr{Cvoid}
@glfunc glMapNamedBufferRange(buffer::GLuint, offset::GLintptr, length::GLsizeiptr, access::GLbitfield)::Ptr{Cvoid}
@glfunc glUnmapNamedBuffer(buffer::GLuint)::GLboolean
@glfunc glFlushMappedNamedBufferRange(buffer::GLuint, offset::GLintptr, length::GLsizeiptr)::Cvoid
@glfunc glGetNamedBufferParameteriv(buffer::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetNamedBufferParameteri64v(buffer::GLuint, pname::GLenum, params::Ptr{GLint64})::Cvoid
@glfunc glGetNamedBufferPointerv(buffer::GLuint, pname::GLenum, params::Ptr{Ptr{Cvoid}})::Cvoid
@glfunc glGetNamedBufferSubData(buffer::GLuint, offset::GLintptr, size::GLsizeiptr, data::Ptr{Cvoid})::Cvoid
@glfunc glCreateFramebuffers(n::GLsizei, framebuffers::Ptr{GLuint})::Cvoid
@glfunc glNamedFramebufferRenderbuffer(framebuffer::GLuint, attachment::GLenum, renderbuffertarget::GLenum, renderbuffer::GLuint)::Cvoid
@glfunc glNamedFramebufferParameteri(framebuffer::GLuint, pname::GLenum, param::GLint)::Cvoid
@glfunc glNamedFramebufferTexture(framebuffer::GLuint, attachment::GLenum, texture::GLuint, level::GLint)::Cvoid
@glfunc glNamedFramebufferTextureLayer(framebuffer::GLuint, attachment::GLenum, texture::GLuint, level::GLint, layer::GLint)::Cvoid
@glfunc glNamedFramebufferDrawBuffer(framebuffer::GLuint, mode::GLenum)::Cvoid
@glfunc glNamedFramebufferDrawBuffers(framebuffer::GLuint, n::GLsizei, bufs::Ptr{GLenum})::Cvoid
@glfunc glNamedFramebufferReadBuffer(framebuffer::GLuint, mode::GLenum)::Cvoid
@glfunc glInvalidateNamedFramebufferData(framebuffer::GLuint, numAttachments::GLsizei, attachments::Ptr{GLenum})::Cvoid
@glfunc glInvalidateNamedFramebufferSubData(framebuffer::GLuint, numAttachments::GLsizei, attachments::Ptr{GLenum}, x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glClearNamedFramebufferiv(framebuffer::GLuint, buffer::GLenum, drawbuffer::GLint, value::Ptr{GLint})::Cvoid
@glfunc glClearNamedFramebufferuiv(framebuffer::GLuint, buffer::GLenum, drawbuffer::GLint, value::Ptr{GLuint})::Cvoid
@glfunc glClearNamedFramebufferfv(framebuffer::GLuint, buffer::GLenum, drawbuffer::GLint, value::Ptr{GLfloat})::Cvoid
@glfunc glClearNamedFramebufferfi(framebuffer::GLuint, buffer::GLenum, drawbuffer::GLint, depth::GLfloat, stencil::GLint)::Cvoid
@glfunc glBlitNamedFramebuffer(readFramebuffer::GLuint, drawFramebuffer::GLuint, srcX0::GLint, srcY0::GLint, srcX1::GLint, srcY1::GLint, dstX0::GLint, dstY0::GLint, dstX1::GLint, dstY1::GLint, mask::GLbitfield, filter::GLenum)::Cvoid
@glfunc glCheckNamedFramebufferStatus(framebuffer::GLuint, target::GLenum)::GLenum
@glfunc glGetNamedFramebufferParameteriv(framebuffer::GLuint, pname::GLenum, param::Ptr{GLint})::Cvoid
@glfunc glGetNamedFramebufferAttachmentParameteriv(framebuffer::GLuint, attachment::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glCreateRenderbuffers(n::GLsizei, renderbuffers::Ptr{GLuint})::Cvoid
@glfunc glNamedRenderbufferStorage(renderbuffer::GLuint, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glNamedRenderbufferStorageMultisample(renderbuffer::GLuint, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glGetNamedRenderbufferParameteriv(renderbuffer::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glCreateTextures(target::GLenum, n::GLsizei, textures::Ptr{GLuint})::Cvoid
@glfunc glTextureBuffer(texture::GLuint, internalformat::GLenum, buffer::GLuint)::Cvoid
@glfunc glTextureBufferRange(texture::GLuint, internalformat::GLenum, buffer::GLuint, offset::GLintptr, size::GLsizeiptr)::Cvoid
@glfunc glTextureStorage1D(texture::GLuint, levels::GLsizei, internalformat::GLenum, width::GLsizei)::Cvoid
@glfunc glTextureStorage2D(texture::GLuint, levels::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glTextureStorage3D(texture::GLuint, levels::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei)::Cvoid
@glfunc glTextureStorage2DMultisample(texture::GLuint, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, fixedsamplelocations::GLboolean)::Cvoid
@glfunc glTextureStorage3DMultisample(texture::GLuint, samples::GLsizei, internalformat::GLenum, width::GLsizei, height::GLsizei, depth::GLsizei,
fixedsamplelocations::GLboolean)::Cvoid
@glfunc glTextureSubImage1D(texture::GLuint, level::GLint, xoffset::GLint, width::GLsizei, format::GLenum, type::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glTextureSubImage2D(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, width::GLsizei, height::GLsizei, format::GLenum, type::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glTextureSubImage3D(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, format::GLenum, type::GLenum, pixels::Ptr{Cvoid})::Cvoid
@glfunc glCompressedTextureSubImage1D(texture::GLuint, level::GLint, xoffset::GLint, width::GLsizei, format::GLenum, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glCompressedTextureSubImage2D(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, width::GLsizei, height::GLsizei, format::GLenum, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glCompressedTextureSubImage3D(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, format::GLenum, imageSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glCopyTextureSubImage1D(texture::GLuint, level::GLint, xoffset::GLint, x::GLint, y::GLint, width::GLsizei)::Cvoid
@glfunc glCopyTextureSubImage2D(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glCopyTextureSubImage3D(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, x::GLint, y::GLint, width::GLsizei, height::GLsizei)::Cvoid
@glfunc glTextureParameterf(texture::GLuint, pname::GLenum, param::GLfloat)::Cvoid
@glfunc glTextureParameterfv(texture::GLuint, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glTextureParameteri(texture::GLuint, pname::GLenum, param::GLint)::Cvoid
@glfunc glTextureParameterIiv(texture::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glTextureParameterIuiv(texture::GLuint, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glTextureParameteriv(texture::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGenerateTextureMipmap(texture::GLuint)::Cvoid
@glfunc glBindTextureUnit(unit::GLuint, texture::GLuint)::Cvoid
@glfunc glGetTextureImage(texture::GLuint, level::GLint, format::GLenum, type::GLenum, bufSize::GLsizei, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetCompressedTextureImage(texture::GLuint, level::GLint, bufSize::GLsizei, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetTextureLevelParameterfv(texture::GLuint, level::GLint, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glGetTextureLevelParameteriv(texture::GLuint, level::GLint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetTextureParameterfv(texture::GLuint, pname::GLenum, params::Ptr{GLfloat})::Cvoid
@glfunc glGetTextureParameterIiv(texture::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glGetTextureParameterIuiv(texture::GLuint, pname::GLenum, params::Ptr{GLuint})::Cvoid
@glfunc glGetTextureParameteriv(texture::GLuint, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glCreateVertexArrays(n::GLsizei, arrays::Ptr{GLuint})::Cvoid
@glfunc glDisableVertexArrayAttrib(vaobj::GLuint, index::GLuint)::Cvoid
@glfunc glEnableVertexArrayAttrib(vaobj::GLuint, index::GLuint)::Cvoid
@glfunc glVertexArrayElementBuffer(vaobj::GLuint, buffer::GLuint)::Cvoid
@glfunc glVertexArrayVertexBuffer(vaobj::GLuint, bindingindex::GLuint, buffer::GLuint, offset::GLintptr, stride::GLsizei)::Cvoid
@glfunc glVertexArrayVertexBuffers(vaobj::GLuint, first::GLuint, count::GLsizei, buffers::Ptr{GLuint}, offsets::Ptr{GLintptr}, strides::Ptr{GLsizei})::Cvoid
@glfunc glVertexArrayAttribFormat(vaobj::GLuint, attribindex::GLuint, size::GLint, type::GLenum, normalized::GLboolean, relativeoffset::GLuint)::Cvoid
@glfunc glVertexArrayAttribIFormat(vaobj::GLuint, attribindex::GLuint, size::GLint, type::GLenum, relativeoffset::GLuint)::Cvoid
@glfunc glVertexArrayAttribLFormat(vaobj::GLuint, attribindex::GLuint, size::GLint, type::GLenum, relativeoffset::GLuint)::Cvoid
@glfunc glVertexArrayAttribBinding(vaobj::GLuint, attribindex::GLuint, bindingindex::GLuint)::Cvoid
@glfunc glVertexArrayBindingDivisor(vaobj::GLuint, bindingindex::GLuint, divisor::GLuint)::Cvoid
@glfunc glGetVertexArrayiv(vaobj::GLuint, pname::GLenum, param::Ptr{GLint})::Cvoid
@glfunc glGetVertexArrayIndexediv(vaobj::GLuint, index::GLuint, pname::GLenum, param::Ptr{GLint})::Cvoid
@glfunc glGetVertexArrayIndexed64iv(vaobj::GLuint, index::GLuint, pname::GLenum, param::Ptr{GLint64})::Cvoid
@glfunc glCreateSamplers(n::GLsizei, samplers::Ptr{GLuint})::Cvoid
@glfunc glCreateProgramPipelines(n::GLsizei, pipelines::Ptr{GLuint})::Cvoid
@glfunc glCreateQueries(target::GLenum, n::GLsizei, ids::Ptr{GLuint})::Cvoid
@glfunc glGetQueryBufferObjectiv(id::GLuint, buffer::GLuint, pname::GLenum, offset::GLintptr)::Cvoid
@glfunc glGetQueryBufferObjectuiv(id::GLuint, buffer::GLuint, pname::GLenum, offset::GLintptr)::Cvoid
@glfunc glGetQueryBufferObjecti64v(id::GLuint, buffer::GLuint, pname::GLenum, offset::GLintptr)::Cvoid
@glfunc glGetQueryBufferObjectui64v(id::GLuint, buffer::GLuint, pname::GLenum, offset::GLintptr)::Cvoid
@glfunc glGetTextureSubImage(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, format::GLenum, type::GLenum, bufSize::GLsizei, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetCompressedTextureSubImage(texture::GLuint, level::GLint, xoffset::GLint, yoffset::GLint, zoffset::GLint, width::GLsizei, height::GLsizei, depth::GLsizei, bufSize::GLsizei, pixels::Ptr{Cvoid})::Cvoid
@glfunc glGetGraphicsResetStatus()::GLenum
@glfunc glReadnPixels(x::GLint, y::GLint, width::GLsizei, height::GLsizei, format::GLenum, type::GLenum, bufSize::GLsizei, data::Ptr{Cvoid})::Cvoid
@glfunc glGetnUniformfv(program::GLuint, location::GLint, bufSize::GLsizei, params::Ptr{GLfloat})::Cvoid
@glfunc glGetnUniformiv(program::GLuint, location::GLint, bufSize::GLsizei, params::Ptr{GLint})::Cvoid
@glfunc glGetnUniformuiv(program::GLuint, location::GLint, bufSize::GLsizei, params::Ptr{GLuint})::Cvoid
@glfunc glTextureBarrier()::Cvoid
@glfunc glSpecializeShader(shader::GLuint, pEntryPoint::Ptr{GLchar}, numSpecializationConstants::GLuint, pConstantIndex::Ptr{GLuint}, pConstantValue::Ptr{GLuint})::Cvoid
@glfunc glMultiDrawArraysIndirectCount(mode::GLenum, indirect::Ptr{Cvoid}, drawcount::GLsizei, maxdrawcount::GLsizei, stride::GLsizei)::Cvoid
@glfunc glMultiDrawElementsIndirectCount(mode::GLenum, type::GLenum, indirect::Ptr{Cvoid}, drawcount::GLsizei, maxdrawcount::GLsizei, stride::GLsizei)::Cvoid
@glfunc glPolygonOffsetClamp(factor::GLfloat, units::GLfloat, clamp::GLfloat)::Cvoid
@glfunc glGetTexEnviv(target::GLenum, pname::GLenum, params::Ptr{GLint})::Cvoid
@glfunc glTexEnvi(target::GLenum, pname::GLenum, param::GLint)::Cvoid
@glfunc glPushAttrib(mask::GLbitfield)::Cvoid
@glfunc glPopAttrib()::Cvoid
@glfunc glEnableClientState(cap::GLenum)::Cvoid
@glfunc glDisableClientState(cap::GLenum)::Cvoid
@glfunc glShadeModel(mode::GLenum)::Cvoid
@glfunc glMatrixMode(mode::GLenum)::Cvoid
@glfunc glPushMatrix()::Cvoid
@glfunc glPopMatrix()::Cvoid
@glfunc glLoadIdentity()::Cvoid
@glfunc glOrtho(left::GLdouble, right::GLdouble, bottom::GLdouble, top::GLdouble, nearVal::GLdouble, farVal::GLdouble)::Cvoid
@glfunc glVertexPointer(size::GLint, type::GLenum, stride::GLsizei, pointer::Ptr{Cvoid})::Cvoid
@glfunc glTexCoordPointer(size::GLint, type::GLenum, stride::GLsizei, pointer::Ptr{Cvoid})::Cvoid
@glfunc glColorPointer(size::GLint, type::GLenum, stride::GLsizei, pointer::Ptr{Cvoid})::Cvoid
# ARB_bindless_texture:
@glfunc glGetTextureHandleARB(texture::GLuint)::GLuint64
@glfunc glGetTextureSamplerHandleARB(texture::GLuint, sampler::GLuint)::GLuint64
@glfunc glMakeTextureHandleResidentARB(handle::GLuint64)::Cvoid
@glfunc glMakeTextureHandleNonResidentARB(handle::GLuint64)::Cvoid
@glfunc glGetImageHandleARB(texture::GLuint, level::GLint, layered::GLboolean, layer::GLint, format::GLenum)::GLuint64
@glfunc glMakeImageHandleResidentARB(handle::GLuint64, access::GLenum)::Cvoid
@glfunc glMakeImageHandleNonResidentARB(handle::GLuint64)::Cvoid
@glfunc glUniformHandleui64ARB(location::GLint, value::GLuint64)::Cvoid
@glfunc glUniformHandleui64vARB(location::GLint, count::GLsizei, value::Ptr{GLuint64})::Cvoid
@glfunc glProgramUniformHandleui64ARB(program::GLuint, location::GLint, value::GLuint64)::Cvoid
@glfunc glProgramUniformHandleui64vARB(program::GLuint, location::GLint, count::GLsizei, values::Ptr{GLuint64})::Cvoid
@glfunc glIsTextureHandleResidentARB(handle::GLuint64)::GLboolean
@glfunc glIsImageHandleResidentARB(handle::GLuint64)::GLboolean
@glfunc glVertexAttribL1ui64ARB(index::GLuint, x::GLuint64)::Cvoid
@glfunc glVertexAttribL1ui64vARB(index::GLuint, v::Ptr{GLuint64})::Cvoid
@glfunc glGetVertexAttribLui64vARB(index::GLuint, pname::GLenum, params::Ptr{GLuint64})::Cvoid | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1004 | #all OpenGL Types
const GLCvoid = Cvoid
const GLint = Cint
const GLsizeiptr = Cssize_t
const Pointer = Ptr{Cvoid}
const GLhalfNV = Cushort
const GLshort = Cshort
const GLdouble = Cdouble
const GLushort = Cushort
const GLuint = Cuint
const GLint64 = Clonglong
const GLbyte = Int8
const GLchar = Cuchar
const GLubyte = Cuchar
const GLintptr = Cptrdiff_t
const GLfloat = Cfloat
const GLhalfARB = Cushort
const GLhalf = Cushort
const GLenum = Cuint
const GLboolean = Cuchar
const GLclampf = Cfloat
const GLsizei = Cint
const GLsync = Ptr{Cvoid}
const GLuint64 = Culonglong
const GLclampd = Cdouble
const GLbitfield = Cuint
export GLCvoid
export GLint
export GLsizeiptr
export Pointer
export GLhalfNV
export GLshort
export GLdouble
export GLushort
export GLuint
export GLint64
export GLbyte
export GLchar
export GLubyte
export GLintptr
export GLfloat
export GLhalfARB
export GLhalf
export GLenum
export GLboolean
export GLclampf
export GLsizei
export GLsync
export GLuint64
export GLclampd
export GLbitfield
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 3016 | import GLFW
using ModernGLbp
include("util.jl")
# Check the name/type of the GLENUM constants.
function test_gl_enum(i::Integer, name::Symbol, expected_type::DataType = GLenum)
e = GLENUM(i)
if e.name != name
error("GLENUM(", i, ") should be :", name, " but is :", e.name)
end
if typeof(e.number) != expected_type
error(e, " should be a ", expected_type, ", but it's a ", typeof(e.number))
end
end
test_gl_enum(0x82EE, :GL_VERTICES_SUBMITTED)
test_gl_enum(0x000080000, :GL_QUERY_BUFFER_BARRIER_BIT, GLbitfield)
test_gl_enum(Int(1), :GL_TRUE)
test_gl_enum(Int8(1), :GL_TRUE)
test_gl_enum(UInt(1), :GL_TRUE)
test_gl_enum(UInt8(1), :GL_TRUE)
test_gl_enum(Int(0), :GL_FALSE)
test_gl_enum(Int8(0), :GL_FALSE)
test_gl_enum(UInt(0), :GL_FALSE)
test_gl_enum(UInt8(0), :GL_FALSE)
is_ci() = lowercase(get(ENV, "CI", "false")) == "true"
if !is_ci() # only do test if not CI... this is for automated testing environments which fail for OpenGL stuff, but I'd like to test if at least including works
GLFW.Init()
# OS X-specific GLFW hints to initialize the correct version of OpenGL
wh = 600
# Create a windowed mode window and its OpenGL context
window = GLFW.CreateWindow(wh, wh, "OpenGL Example")
# Make the window's context current
GLFW.MakeContextCurrent(window)
GLFW.ShowWindow(window)
GLFW.SetWindowSize(window, wh, wh) # Seems to be necessary to guarantee that window > 0
glViewport(0, 0, wh, wh)
println(createcontextinfo())
# The data for our triangle
data = GLfloat[
0.0, 0.5,
0.5, -0.5,
-0.5,-0.5
]
# Generate a vertex array and array buffer for our data
vao = glGenVertexArray()
glBindVertexArray(vao)
vbo = glGenBuffer()
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW)
# Create and initialize shaders
const vsh = """
$(get_glsl_version_string())
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}
"""
const fsh = """
$(get_glsl_version_string())
out vec4 outColor;
void main() {
outColor = vec4(1.0, 1.0, 1.0, 1.0);
}
"""
vertexShader = createShader(vsh, GL_VERTEX_SHADER)
fragmentShader = createShader(fsh, GL_FRAGMENT_SHADER)
program = createShaderProgram(vertexShader, fragmentShader)
glUseProgram(program)
positionAttribute = glGetAttribLocation(program, "position");
glEnableVertexAttribArray(positionAttribute)
glVertexAttribPointer(positionAttribute, 2, GL_FLOAT, false, 0, C_NULL)
# Loop until the user closes the window
for i=1:500
# Pulse the background blue
glClearColor(0.0, 0.0, 0.5 * (1 + sin(i * 0.02)), 1.0)
glClear(GL_COLOR_BUFFER_BIT)
# Draw our triangle
glDrawArrays(GL_TRIANGLES, 0, 3)
# Swap front and back buffers
GLFW.SwapBuffers(window)
# Poll for and process events
GLFW.PollEvents()
end
GLFW.Terminate()
end
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 5060 | function glGenOne(glGenFn)
id = GLuint[0]
glGenFn(1, id)
glCheckError("generating a buffer, array, or texture")
id[]
end
glGenBuffer() = glGenOne(glGenBuffers)
glGenVertexArray() = glGenOne(glGenVertexArrays)
glGenTexture() = glGenOne(glGenTextures)
function getInfoLog(obj::GLuint)
# Return the info log for obj, whether it be a shader or a program.
isShader = glIsShader(obj)
getiv = isShader == GL_TRUE ? glGetShaderiv : glGetProgramiv
getInfo = isShader == GL_TRUE ? glGetShaderInfoLog : glGetProgramInfoLog
# Get the maximum possible length for the descriptive error message
len = GLint[0]
getiv(obj, GL_INFO_LOG_LENGTH, len)
maxlength = len[]
# TODO: Create a macro that turns the following into the above:
# maxlength = @glPointer getiv(obj, GL_INFO_LOG_LENGTH, GLint)
# Return the text of the message if there is any
if maxlength > 0
buffer = zeros(GLchar, maxlength)
sizei = GLsizei[0]
getInfo(obj, maxlength, sizei, buffer)
len = sizei[]
unsafe_string(pointer(buffer), len)
else
""
end
end
function validateShader(shader)
success = GLint[0]
glGetShaderiv(shader, GL_COMPILE_STATUS, success)
success[] == GL_TRUE
end
function glErrorMessage()
# Return a string representing the current OpenGL error flag, or the empty string if there's no error.
err = glGetError()
err == GL_NO_ERROR ? "" :
err == GL_INVALID_ENUM ? "GL_INVALID_ENUM: An unacceptable value is specified for an enumerated argument. The offending command is ignored and has no other side effect than to set the error flag." :
err == GL_INVALID_VALUE ? "GL_INVALID_VALUE: A numeric argument is out of range. The offending command is ignored and has no other side effect than to set the error flag." :
err == GL_INVALID_OPERATION ? "GL_INVALID_OPERATION: The specified operation is not allowed in the current state. The offending command is ignored and has no other side effect than to set the error flag." :
err == GL_INVALID_FRAMEBUFFER_OPERATION ? "GL_INVALID_FRAMEBUFFER_OPERATION: The framebuffer object is not complete. The offending command is ignored and has no other side effect than to set the error flag." :
err == GL_OUT_OF_MEMORY ? "GL_OUT_OF_MEMORY: There is not enough memory left to execute the command. The state of the GL is undefined, except for the state of the error flags, after this error is recorded." : "Unknown OpenGL error with error code $err."
end
function glCheckError(actionName="")
message = glErrorMessage()
if length(message) > 0
if length(actionName) > 0
error("Error ", actionName, ": ", message)
else
error("Error: ", message)
end
end
end
function createShader(source, typ)
# Create the shader
shader = glCreateShader(typ)::GLuint
if shader == 0
error("Error creating shader: ", glErrorMessage())
end
# Compile the shader
glShaderSource(shader, 1, convert(Ptr{UInt8}, pointer([convert(Ptr{GLchar}, pointer(source))])), C_NULL)
glCompileShader(shader)
# Check for errors
!validateShader(shader) && error("Shader creation error: ", getInfoLog(shader))
shader
end
function createShaderProgram(f, vertexShader, fragmentShader)
# Create, link then return a shader program for the given shaders.
# Create the shader program
prog = glCreateProgram()
if prog == 0
error("Error creating shader program: ", glErrorMessage())
end
# Attach the vertex shader
glAttachShader(prog, vertexShader)
glCheckError("attaching vertex shader")
# Attach the fragment shader
glAttachShader(prog, fragmentShader)
glCheckError("attaching fragment shader")
f(prog)
# Finally, link the program and check for errors.
glLinkProgram(prog)
status = GLint[0]
glGetProgramiv(prog, GL_LINK_STATUS, status)
if status[] == GL_FALSE then
glDeleteProgram(prog)
error("Error linking shader: ", glGetInfoLog(prog))
end
prog
end
createShaderProgram(vertexShader, fragmentShader) = createShaderProgram(prog->0, vertexShader, fragmentShader)
global GLSL_VERSION = ""
function createcontextinfo()
global GLSL_VERSION
glsl = split(unsafe_string(glGetString(GL_SHADING_LANGUAGE_VERSION)), ['.', ' '])
if length(glsl) >= 2
glsl = VersionNumber(parse(Int, glsl[1]), parse(Int, glsl[2]))
GLSL_VERSION = string(glsl.major) * rpad(string(glsl.minor),2,"0")
else
error("Unexpected version number string. Please report this bug! GLSL version string: $(glsl)")
end
glv = split(unsafe_string(glGetString(GL_VERSION)), ['.', ' '])
if length(glv) >= 2
glv = VersionNumber(parse(Int, glv[1]), parse(Int, glv[2]))
else
error("Unexpected version number string. Please report this bug! OpenGL version string: $(glv)")
end
dict = Dict{Symbol,Any}(
:glsl_version => glsl,
:gl_version => glv,
:gl_vendor => unsafe_string(glGetString(GL_VENDOR)),
:gl_renderer => unsafe_string(glGetString(GL_RENDERER)),
#:gl_extensions => split(unsafe_string(glGetString(GL_EXTENSIONS))),
)
end
function get_glsl_version_string()
if isempty(GLSL_VERSION)
error("couldn't get GLSL version, GLUTils not initialized, or context not created?")
end
return "#version $(GLSL_VERSION)\n"
end
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 16161 | # Runs a test on buffers.
function test_buffers()
# Initialize one with some data.
buf::Buffer = Buffer(true, [ 0x1, 0x2, 0x3, 0x4 ])
data = get_buffer_data(buf, (UInt8, 4))
@bp_check(data isa Vector{UInt8}, "Actual type: ", data)
@bp_check(data == [ 0x1, 0x2, 0x3, 0x4 ],
"Expected data: ", map(bitstring, [ 0x1, 0x2, 0x3, 0x4 ]),
"\n\tActual data: ", map(bitstring, data))
# Try setting its data after creation.
set_buffer_data(buf, [ 0x5, 0x7, 0x9, 0x19])
@bp_check(get_buffer_data(buf, (UInt8, 4)) == [ 0x5, 0x7, 0x9, 0x19 ])
# Try reading the data into an existing array.
buf_actual = UInt8[ 0x0, 0x0, 0x0, 0x0 ]
get_buffer_data(buf, buf_actual)
@bp_check(buf_actual == [ 0x5, 0x7, 0x9, 0x19 ])
# Try setting the buffer to contain one big int, make sure there's no endianness issues.
set_buffer_data(buf, [ 0b11110000000000111000001000100101 ])
buf_actual = get_buffer_data(buf, UInt32)
@bp_check(buf_actual == 0b11110000000000111000001000100101,
"Actual data: ", buf_actual)
# Try setting and getting with offsets.
set_buffer_data(buf, [ 0x5, 0x7, 0x9, 0x19])
buf_actual = get_buffer_data(buf, (UInt8, 2), 2)
@bp_check(buf_actual == [ 0x7, 0x9 ], map(bitstring, buf_actual))
buf_actual = get_buffer_data(buf, (UInt8, 2), 3)
@bp_check(buf_actual == [ 0x9, 0x19 ], map(bitstring, buf_actual))
buf_actual = UInt8[ 0x2, 0x0, 0x0, 0x0, 0x0, 0x4 ]
get_buffer_data( buf, @view(buf_actual[2:end-1]))
@bp_check(buf_actual == [ 0x2, 0x5, 0x7, 0x9, 0x19, 0x4 ],
buf_actual)
# Try copying.
buf2 = Buffer(30, true, true)
copy_buffer(buf, buf2;
src_byte_offset = UInt(2),
dest_byte_offset = UInt(11),
byte_size = UInt(2))
buf_actual = get_buffer_data(buf2, (UInt8, 2), 12)
@bp_check(buf_actual == [ 0x9, 0x19 ],
"Copying buffers with offsets: expected [ 0x9, 0x19 ], got ", buf_actual)
# Clean up.
close(buf2)
close(buf)
@bp_check(buf.handle == GL.Ptr_Buffer(),
"Buffer 1's handle isn't zeroed out after closing")
@bp_check(buf2.handle == GL.Ptr_Buffer(),
"Buffer 2's handle isn't zeroed out after closing")
end
# Create a GL Context and window, and put the GL library through its paces.
bp_gl_context( v2i(800, 500), "Running tests...press Enter to finish once rendering starts";
vsync=VsyncModes.on,
debug_mode=true
) do context::Context
@bp_check(context === GL.get_context(),
"Just started this Context, but another one is the singleton")
check_gl_logs("just starting up")
println("Device: ", context.device.gpu_name)
# Run some basic tests with GL resources.
test_buffers()
check_gl_logs("running test battery")
# Keep track of the resources to clean up, in the order they should be cleaned up.
to_clean_up = AbstractResource[ ]
# Set up a mesh with some triangles.
# Each triangle has position, color, and "IDs".
# The position data is in its own buffer.
buf_tris_poses = Buffer(false, [ v4f(-0.75, -0.75, -0.35, 1.0),
v4f(-0.75, 0.75, 0.25, 1.0),
v4f(0.75, 0.75, 0.75, 1.0) ])
# The color and IDs are together in a second buffer.
buf_tris_color_and_IDs = Buffer(false, Tuple{vRGBu8, Vec{2, UInt8}}[
(vRGBu8(128, 128, 128), Vec{2, UInt8}(1, 0)),
(vRGBu8(0, 255, 0), Vec{2, UInt8}(0, 1)),
(vRGBu8(255, 0, 255), Vec{2, UInt8}(0, 0))
])
mesh_triangles = Mesh(PrimitiveTypes.triangle,
[ VertexDataSource(buf_tris_poses, sizeof(v4f)),
VertexDataSource(buf_tris_color_and_IDs,
sizeof(Tuple{vRGBu8, Vec{2, UInt8}}))
],
[ VertexAttribute(1, 0x0, VSInput(v4f)), # The positions, pulled directly from a v4f
VertexAttribute(2, 0x0, VSInput_FVector(Vec3{UInt8}, true)), # The colors, normalized from [0,255] to [0,1]
VertexAttribute(2, sizeof(vRGBu8), VSInput(Vec2{UInt8})) # The IDs, left as integers
])
check_gl_logs("creating the simple triangle mesh")
@bp_check(count_mesh_vertices(mesh_triangles) == 3,
"The mesh has 3 vertices, but thinks it has ", count_mesh_vertices(mesh_triangles))
@bp_check(count_mesh_elements(mesh_triangles) == count_mesh_vertices(mesh_triangles),
"The mesh isn't indexed, yet it gives a different result for 'count vertices' (",
count_mesh_vertices(mesh_triangles), ") vs 'count elements' (",
count_mesh_elements(mesh_triangles), ")")
push!(to_clean_up, mesh_triangles, buf_tris_poses, buf_tris_color_and_IDs)
#TODO: Add another indexed mesh to test indexed rendering.
# Set up a shader to render the triangles.
# Use a variety of uniforms and vertex attributes to mix up the colors.
draw_triangles::Program = bp_glsl"""
uniform ivec3 u_colorMask = ivec3(1, 1, 1);
#START_VERTEX
in vec4 vIn_pos;
in vec3 vIn_color;
in ivec2 vIn_IDs; // Expected to be (1,0) for the first point,
// (0,1) for the second,
// (0,0) for the third.
out vec3 vOut_color;
void main() {
gl_Position = vIn_pos;
ivec3 ids = ivec3(vIn_IDs, all(vIn_IDs == 0) ? 1 : 0);
vOut_color = vIn_color * vec3(ids);
}
#START_FRAGMENT
uniform mat3 u_colorTransform = mat3(1, 0, 0, 0, 1, 0, 0, 0, 1);
uniform dmat2x4 u_colorCurveAt512[10];
uniform sampler2D u_tex;
in vec3 vOut_color;
out vec4 fOut_color;
void main() {
fOut_color = vec4(vOut_color * u_colorMask, 1.0);
fOut_color.rgb = clamp(u_colorTransform * fOut_color.rgb, 0.0, 1.0);
float scale = float(u_colorCurveAt512[3][1][2]);
fOut_color.rgb = pow(fOut_color.rgb, vec3(scale));
fOut_color.rgb *= texture(u_tex, gl_FragCoord.xy / vec2(800, 500)).rgb;
}
"""
function check_uniform(name::String, type, array_size)
@bp_check(haskey(draw_triangles.uniforms, name),
"Program is missing uniform '", name, "': ", draw_triangles.uniforms)
@bp_check(draw_triangles.uniforms[name].type == type,
"Wrong uniform data for '", name, "': ", draw_triangles.uniforms[name])
@bp_check(draw_triangles.uniforms[name].array_size == array_size,
"Wrong uniform data for '", name, "': ", draw_triangles.uniforms[name])
end
@bp_check(Set(keys(draw_triangles.uniforms)) ==
Set([ "u_colorMask", "u_colorTransform", "u_colorCurveAt512", "u_tex" ]),
"Unexpected set of uniforms: ", collect(keys(draw_triangles.uniforms)))
check_uniform("u_colorMask", Vec3{Int32}, 1)
check_uniform("u_colorTransform", fmat3x3, 1)
check_uniform("u_colorCurveAt512", dmat2x4, 10)
check_uniform("u_tex", GL.Ptr_View, 1)
push!(to_clean_up, draw_triangles)
check_gl_logs("creating the simple triangle shader")
# Set up the texture used to draw the triangles.
T_SIZE::Int = 512
tex_data = Array{vRGBf, 2}(undef, (T_SIZE, T_SIZE))
for x in 1:T_SIZE
for y in 1:T_SIZE
perlin_pos::v2f = v2f(x, y) / @f32(T_SIZE)
perlin_pos *= 20
tex_data[y, x] = vRGBf(
perlin(perlin_pos, tuple(0x90843277)),
perlin(perlin_pos, tuple(0xabfbcce2)),
perlin(perlin_pos, tuple(0x5678cbef))
)
end
end
tex = Texture(SimpleFormat(FormatTypes.normalized_uint,
SimpleFormatComponents.RGB,
SimpleFormatBitDepths.B8),
tex_data;
sampler = TexSampler{2}(wrapping = Vec(WrapModes.repeat, WrapModes.repeat)))
push!(to_clean_up, tex)
check_gl_logs("creating the simple triangles' texture")
set_uniform(draw_triangles, "u_tex", tex)
check_gl_logs("giving the texture to the simple triangles' shader")
resources::Service_BasicGraphics = service_BasicGraphics_init()
@assert(GL.count_mesh_vertices(resources.screen_triangle) == 3)
@assert(GL.count_mesh_vertices(resources.screen_quad) == 4)
# Draw the skybox as a full-screen triangle with some in-shader projection math.
# Set up a shader for the "skybox",
# which takes a yaw angle and aspect ratio to map the screen quad to a 3D view range.
draw_skybox::Program = bp_glsl"""
#START_VERTEX
in vec2 vIn_corner;
uniform float u_yaw_radians = 0.0,
u_width_over_height = 1.0,
u_fov_width = 1.0;
out vec3 vOut_cubeUV;
vec2 Rot(vec2 v, float radians) {
vec2 cossin = vec2(cos(radians), sin(radians));
vec4 cossin4 = vec4(cossin, -cossin);
return vec2(dot(v, cossin4.xw),
dot(v, cossin4.yx));
}
void main() {
gl_Position = vec4(vIn_corner, 0.9999, 1.0);
vec2 uvHorzMin = Rot(vec2(-u_fov_width, 1.0), u_yaw_radians),
uvHorzMax = Rot(vec2(u_fov_width, 1.0), u_yaw_radians);
vec3 uvMax = vec3(uvHorzMax, u_fov_width * u_width_over_height),
uvMin = vec3(uvHorzMin, -u_fov_width * u_width_over_height);
vec3 t = vec3(0.5 + (0.5 * vIn_corner.xxy));
vOut_cubeUV = mix(uvMin, uvMax, t);
}
#START_FRAGMENT
in vec3 vOut_cubeUV;
uniform samplerCube u_tex;
out vec4 fOut_color;
void main() {
fOut_color = vec4(texture(u_tex, normalize(vOut_cubeUV)).rgb,
1.0);
}
"""
push!(to_clean_up, draw_skybox)
check_gl_logs("compiling the 'skybox' shader")
# Create the skybox texture.
SKYBOX_TEX_LENGTH = 512
NOISE_SCALE = Float32(17)
pixels_skybox = Array{Float32, 3}(undef, (SKYBOX_TEX_LENGTH, SKYBOX_TEX_LENGTH, 6))
for face in 1:6
for y in 1:SKYBOX_TEX_LENGTH
for x in 1:SKYBOX_TEX_LENGTH
uv::v2f = (v2f(x, y) - @f32(0.5)) / SKYBOX_TEX_LENGTH
cube_dir::v3f = vnorm(get_cube_dir(CUBEMAP_MEMORY_LAYOUT[face], uv))
pixels_skybox[x, y, face] = perlin(cube_dir * NOISE_SCALE)
end
end
end
tex_skybox = Texture_cube(SimpleFormat(FormatTypes.normalized_uint,
SimpleFormatComponents.R,
SimpleFormatBitDepths.B8),
pixels_skybox
;
swizzling=SwizzleRGBA(
SwizzleSources.red,
SwizzleSources.red,
SwizzleSources.red,
SwizzleSources.one
))
push!(to_clean_up, tex_skybox)
check_gl_logs("creating the 'skybox' texture")
set_uniform(draw_skybox, "u_tex", tex_skybox)
check_gl_logs("giving the 'skybox' texture to its shader")
# Set up a Target for rendering into.
target = Target(v2u(800, 600),
SimpleFormat(FormatTypes.normalized_uint,
SimpleFormatComponents.RGB,
SimpleFormatBitDepths.B8),
DepthStencilFormats.depth_24u)
push!(to_clean_up, target)
check_gl_logs("creating the Target")
# Configure the render state.
set_culling(context, FaceCullModes.off)
set_depth_writes(context, true)
set_depth_test(context, ValueTests.less_than)
set_blending(context, make_blend_opaque(BlendStateRGBA))
camera_yaw_radians::Float32 = 0
timer::Int = 8 * 60 #Vsync is on, assume 60fps
while !GLFW.WindowShouldClose(context.window)
window_size::v2i = get_window_size(context)
check_gl_logs("starting a new tick")
# Clear the screen.
clear_col = lerp(vRGBAf(0.4, 0.4, 0.2, 1.0),
vRGBAf(0.6, 0.45, 0.6, 1.0),
rand(Float32))
GL.clear_screen(clear_col)
GL.clear_screen(@f32 1.0)
check_gl_logs("clearing the screen")
# Randomly shift some uniforms every N ticks.
if timer % 30 == 0
# Set 'u_colorMask' as an array of 1 element, just to test that code path.
set_uniforms(draw_triangles, "u_colorMask",
[ Vec{Int32}(rand(0:1), rand(0:1), rand(0:1)) ])
set_uniform(draw_triangles, "u_colorTransform",
fmat3x3(ntuple(i->rand(), 9)...))
end
# Continuously vary another uniform.
pow_val = lerp(0.3, 1/0.3,
abs(mod(timer / 30, 2) - 1) ^ 5)
set_uniform(draw_triangles, "u_colorCurveAt512",
dmat2x4(0, 0, 0, 0,
0, 0, pow_val, 0),
4)
check_gl_logs("setting uniforms during tick")
# Render the triangles into the render-target,
# then we'll re-render them while sampling from that target
# to create a trippy effect.
function draw_scene(triangle_tex, msg_context...)
set_depth_test(context, ValueTests.less_than)
# Update the triangle uniforms.
set_uniform(draw_triangles, "u_tex", triangle_tex)
# Draw the triangles.
view_activate(get_view(triangle_tex))
render_mesh(mesh_triangles, draw_triangles,
elements = IntervalU(min=1, size=3))
view_deactivate(get_view(triangle_tex))
check_gl_logs(string("drawing the triangles ", msg_context...))
# Update the skybox uniforms.
camera_yaw_radians += deg2rad(.05)
set_uniform(draw_skybox, "u_yaw_radians", camera_yaw_radians)
set_uniform(draw_skybox, "u_fov_width", @f32(1))
set_uniform(draw_skybox, "u_width_over_height", @f32(window_size.x / window_size.y))
check_gl_logs(string("setting the skybox's uniforms ", msg_context...))
# Draw the skybox.
view_activate(get_view(tex_skybox))
render_mesh(resources.screen_triangle, draw_skybox)
view_deactivate(get_view(tex_skybox))
check_gl_logs(string("drawing the skybox ", msg_context...))
end
target_activate(target)
target_clear(target, vRGBAf(1, 0, 1, 0))
target_clear(target, @f32 1.0)
draw_scene(tex, "into a Target")
# Draw the Target's data onto the screen.
target_activate(nothing)
clear_screen(vRGBAf(0, 1, 0, 0))
clear_screen(@f32 1.0)
set_depth_test(context, ValueTests.pass)
check_gl_logs("clearing the screen")
target_tex = target.attachment_colors[1].tex
simple_blit(target_tex)
GLFW.SwapBuffers(context.window)
GLFW.PollEvents()
timer -= 1
if (timer <= 0) || GLFW.GetKey(context.window, GLFW.KEY_ENTER)
break
end
end
# Clean up the resources.
for rs::AbstractResource in to_clean_up
close(rs)
# Make sure the resource's handle is nulled out, to prevent potential errors.
closed_handle = get_ogl_handle(rs)
null_handle = typeof(closed_handle)()
@bp_check(closed_handle == null_handle,
"After closing a ", typeof(rs), " its handle wasn't nulled out: ",
closed_handle, " vs ", null_handle)
check_gl_logs("cleaning up $(typeof(rs))")
end
end
# Make sure the Context got cleaned up.
@bp_check(isnothing(GL.get_context()),
"Just closed the context, but it still exists") | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 2368 | # Test OpenGL handle types.
@bp_check(GL.gl_type(GL.Ptr_Uniform) === GLint,
"GL.Ptr_Uniform's original type is not GLint, but ",
GL.gl_type(GL.Ptr_Uniform))
@bp_check(GL.gl_type(GL.Ptr_Buffer) === GLuint)
# Test get_mip_size()
@bp_test_no_allocations(get_mip_size(32, 1), 32)
@bp_test_no_allocations(get_mip_size(32, 1), 32)
@bp_test_no_allocations(get_mip_size(32, 2), 16)
@bp_test_no_allocations(get_mip_size(32, 4), 4)
@bp_test_no_allocations(get_mip_size(32, 6), 1)
@bp_test_no_allocations(get_mip_size(v2i(32, 32), 1), v2i(32, 32))
@bp_test_no_allocations(get_mip_size(v2i(32, 32), 4), v2i(4, 4))
@bp_test_no_allocations(get_mip_size(v2i(32, 4), 4), v2i(4, 1))
# Test get_n_mips()
@bp_test_no_allocations(get_n_mips(1), 1)
@bp_test_no_allocations(get_n_mips(3), 2)
@bp_test_no_allocations(get_n_mips(4), 3)
@bp_test_no_allocations(get_n_mips(4), 3)
@bp_test_no_allocations(get_n_mips(v2u(129, 40)), 8)
# Test pixel buffer type data.
@bp_test_no_allocations(get_component_type(Int8), Int8)
@bp_test_no_allocations(get_component_type(PixelBufferD{3, Vec{2, Float32}}), Float32)
@bp_test_no_allocations(get_component_count(Int8), 1)
@bp_test_no_allocations(get_component_count(PixelBufferD{3, Vec{2, Float32}}), 2)
@bp_test_no_allocations(TexSampler{2}(
wrapping = Vec(WrapModes.clamp, WrapModes.repeat),
pixel_filter = PixelFilters.smooth,
depth_comparison_mode = ValueTests.less_than_or_equal
),
TexSampler{2}(
wrapping = Vec(WrapModes.clamp, WrapModes.repeat),
pixel_filter = PixelFilters.smooth,
depth_comparison_mode = ValueTests.less_than_or_equal
))
@bp_check(JSON3.read(JSON3.write(TexSampler{2}(wrapping = WrapModes.mirrored_repeat)), TexSampler{2}) ==
TexSampler{2}(wrapping = WrapModes.mirrored_repeat))
@bp_check(JSON3.read(JSON3.write(TexSampler{2}(wrapping = Vec(WrapModes.repeat, WrapModes.mirrored_repeat))), TexSampler{2}) !=
TexSampler{2}(wrapping = WrapModes.repeat))
@bp_check(JSON3.read("{ \"pixel_filter\":\"rough\" }", TexSampler{2}) ==
TexSampler{2}(pixel_filter = PixelFilters.rough))
#TODO: Test packed depth/stencil primitive types. | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 22080 | bp_gl_context(v2i(800, 500), "Test: GLtextures") do context::Context
function try_getting_texture(tex::Texture, subset::TexSubset,
expected_flattened::AbstractVector
;
atol=0,
single_component::E_PixelIOChannels=PixelIOChannels.red)
subset_area::Box = BplusApp.GL.get_subset_range(subset, tex.size)
pixels_buffer = Array{eltype(expected_flattened)}(undef, size(subset_area)...)
get_tex_pixels(tex, pixels_buffer, subset, single_component=single_component)
actual_flattened = reshape(pixels_buffer, (length(pixels_buffer), ))
has_failed::Bool = false
for (idx, expected, actual) in zip(1:typemax(Int), expected_flattened, actual_flattened)
if !isapprox(expected, actual, atol=atol, rtol=0, nans=true)
pixel = min_inclusive(subset_area) + vindex(idx, size(subset_area)) - 1
has_failed = true
println("ERROR: Pixel mismatch when reading texture!\n",
"\tTexture:\n",
"\t\tFormat: ", tex.format, "\n",
"\t\tType: ", tex.type, "\n",
"\t\tFullSize: ", tex.size, "\n",
"\tSubset:\n",
"\t\tMin: ", min_inclusive(subset_area), "\n",
"\t\tMax: ", max_inclusive(subset_area), "\n",
"\t\tSize: ", size(subset_area), "\n",
"\tPixel: ", pixel, "\n",
"\t\tArray index: ", idx, "\n",
"\tExpected: ", expected, "\n",
"\tActual : ", actual, "\n",
"\tDelta to Expected: ", expected-actual)
end
end
if has_failed
error("See above test failures.")
end
end
function try_setting_texture(tex::Texture, subset::TexSubset,
data::Array,
expected_data::Array = data
;
atol=0,
single_component::E_PixelIOChannels=PixelIOChannels.red)
set_tex_color(tex, data, subset, single_component=single_component)
try_getting_texture(
tex,
subset,
reshape(expected_data, prod(size(expected_data))),
atol=atol,
single_component=single_component
)
end
function try_clearing_texture(tex::Texture,
initial_value::TClear,
clear_ops::Vector{<:Pair{<:Box, TClear}},
expected_result::AbstractArray{TResult},
mip_level::Int = 1
;
atol=0
) where {TClear, TResult}
initial_clear_subset = BplusApp.GL.default_tex_subset(tex)
initial_clear_subset = typeof(initial_clear_subset)( # @set! breaks for some reason :(
initial_clear_subset.area,
mip_level
)
clear_tex_pixels(tex, initial_value, initial_clear_subset)
for (pixel_range, clear_value) in clear_ops
clear_subset = typeof(initial_clear_subset)(
pixel_range,
mip_level
)
clear_tex_pixels(tex, clear_value, clear_subset)
end
try_getting_texture(
tex,
typeof(initial_clear_subset)(
nothing,
mip_level
),
reshape(expected_result, prod(size(expected_result))),
atol=atol
)
end
function try_copying_texture(src::Texture, dest::Texture,
src_subset, dest_min, dest_mip,
src_foreground_value, dest_background_value)
dest_subset = TexSubset(
Box(
min=dest_min,
size=size(src_subset.area)
),
dest_mip
)
dest_full_subset = TexSubset{BplusApp.GL.get_subset_dims(dest_subset)}(nothing, dest_mip)
clear_tex_color(dest, dest_background_value)
clear_tex_color(src, src_foreground_value)
copy_tex_pixels(src, dest, src_subset, dest_min, dest_mip)
try_getting_texture(
dest, dest_full_subset,
let expected = Array{typeof(dest_background_value)}(undef, tex_size(dest)...)
expected .= dest_background_value
for i in min_inclusive(dest_subset.area):max_inclusive(dest_subset.area)
expected[i] = reinterpret(typeof(dest_background_value), src_foreground_value)
end
reshape(expected, (prod(size(expected)), ))
end
)
end
# Pixel data converters that match the OpenGL standard:
println("#TODO: Move these into B+ proper")
ogl_pixel_convert(T::Type{<:AbstractFloat}, u::Unsigned) = convert(T, u / typemax(u))
ogl_pixel_convert(T::Type{<:AbstractFloat}, i::Signed) =
#NOTE: The correct function according to the OpenGL spec should be this:
# max(-one(T), convert(T, i / typemax(i)))
# However, in practice that doesn't seem to work.
# Is the driver violating spec here?
# Or is the read back into float resulting in a different number than was passed in originally?
lerp(-one(T), one(T),
inv_lerp(convert(T, typemin(i)),
convert(T, typemax(i)),
i))
ogl_pixel_convert(T::Type{<:Unsigned}, f::AbstractFloat) = round(T, saturate(f) * typemax(T))
ogl_pixel_convert(T::Type{<:Signed}, f::AbstractFloat) = begin
f = clamp(f, -one(typeof(f)), one(typeof(f)))
fi = f * typemax(T)
fi = clamp(fi,
convert(typeof(f), typemin(T)),
convert(typeof(f), typemax(T)))
return round(T, fi)
end
ogl_pixel_convert(T::Type{Vec{N, F}}, v::Vec{N}) where {N, F} = map(f -> ogl_pixel_convert(F, f), v)
TEX_SIZE_3D = v3u(3, 4, 5)
TEX_SIZE_CUBE = TEX_SIZE_3D.x
tex_1D_r32f = Texture(
SimpleFormat(
FormatTypes.float,
SimpleFormatComponents.R,
SimpleFormatBitDepths.B32
),
TEX_SIZE_3D.x
)
tex_3D_r32f = Texture(
SimpleFormat(
FormatTypes.float,
SimpleFormatComponents.R,
SimpleFormatBitDepths.B32
),
TEX_SIZE_3D
)
tex_cube_r32f = Texture_cube(
SimpleFormat(
FormatTypes.float,
SimpleFormatComponents.R,
SimpleFormatBitDepths.B32
),
TEX_SIZE_CUBE
)
tex_1D_rg16in = Texture(
SimpleFormat(
FormatTypes.normalized_int,
SimpleFormatComponents.RG,
SimpleFormatBitDepths.B16
),
TEX_SIZE_3D.x
)
tex_3D_rg16in = Texture(
SimpleFormat(
FormatTypes.normalized_int,
SimpleFormatComponents.RG,
SimpleFormatBitDepths.B16
),
TEX_SIZE_3D
)
tex_cube_rg16in = Texture_cube(
SimpleFormat(
FormatTypes.normalized_int,
SimpleFormatComponents.RG,
SimpleFormatBitDepths.B16
),
TEX_SIZE_CUBE
)
tex_1D_rgba8u = Texture(
SimpleFormat(
FormatTypes.uint,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B8
),
TEX_SIZE_3D.x
)
tex_3D_rgba8u = Texture(
SimpleFormat(
FormatTypes.uint,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B8
),
TEX_SIZE_3D
)
tex_cube_rgba8u = Texture_cube(
SimpleFormat(
FormatTypes.uint,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B8
),
TEX_SIZE_CUBE
)
tex_1D_d16u = Texture(
DepthStencilFormats.depth_16u,
TEX_SIZE_3D.x
)
tex_cube_d16u = Texture_cube(
DepthStencilFormats.depth_16u,
TEX_SIZE_CUBE
)
tex_1D_d32f = Texture(
DepthStencilFormats.depth_32f,
TEX_SIZE_3D.x
)
tex_cube_d32f = Texture_cube(
DepthStencilFormats.depth_32f,
TEX_SIZE_CUBE
)
tex_1D_s8u = Texture(
DepthStencilFormats.stencil_8,
TEX_SIZE_3D.x
)
tex_cube_s8u = Texture_cube(
DepthStencilFormats.stencil_8,
TEX_SIZE_CUBE
)
tex_1D_d32fs8 = Texture(
DepthStencilFormats.depth32f_stencil8,
TEX_SIZE_3D.x,
depth_stencil_sampling = DepthStencilSources.depth
)
tex_cube_d32fs8 = Texture_cube(
DepthStencilFormats.depth32f_stencil8,
TEX_SIZE_CUBE,
depth_stencil_sampling = DepthStencilSources.stencil
)
check_gl_logs("After creating textures")
#IMPORTANT NOTE: IN Julia multidimensional array literals, the X and Y axes are flipped.
# So the array [ 1 2 3 (line break) 4 5 6 ] has two elements along X and 3 along Y.
# Z slices are separated with `;;;`.
#IMPORTANT NOTE: When setting a subset of a color texture's channels,
# the missing color channels are set to 0 and the missing alpha channel is set to 1.
# R32F textures:
# 1D:
# Write and read as Float32:
try_setting_texture(
tex_1D_r32f,
TexSubset(Box1Du(
min=Vec(1),
max=Vec(3)
)),
Float32[ 2.4, 5.5, 6.6 ]
)
# Write as UInt8, read as Float32:
try_setting_texture(
tex_1D_r32f,
TexSubset(Box1Du(
min=Vec(1),
max=Vec(3)
)),
let raw = UInt8[ 128, 255, 17 ]
(
raw,
ogl_pixel_convert.(Ref(Float32), raw)
)
end...
)
# Write as Int8, read as Float32:
try_setting_texture(
tex_1D_r32f,
TexSubset(Box1Du(
min=Vec(1),
max=Vec(3)
)),
let raw = Int8[ -126, 32, -17 ]
(
raw,
ogl_pixel_convert.(Ref(Float32), raw)
)
end...,
atol=0.000001
)
# Write and read as Float32:
try_setting_texture(
tex_1D_r32f,
TexSubset(Box1Du(
min=Vec(2),
max=Vec(2)
)),
Float32[ 3.3 ]
)
# 3D:
# Write and read as Float32:
try_setting_texture(
tex_3D_r32f,
TexSubset(Box(
min=v3u(2, 1, 4),
max=v3u(2, 2, 5)
)),
Float32[
1.1
1.2
;;;
1.3
1.4
]
)
# Write and read as Float32:
try_setting_texture(
tex_3D_r32f,
TexSubset(Box(
min=one(v3u),
max=TEX_SIZE_3D
)),
Float32[
111 121 131 141
211 221 231 241
311 321 331 341
;;;
112 122 132 142
212 222 232 242
312 322 332 342
;;;
113 123 133 143
213 223 233 243
313 323 333 343
;;;
114 124 134 144
214 224 234 244
314 324 334 344
;;;
115 125 135 145
215 225 235 245
315 325 335 345
]
)
# Write as UInt16, read as Float32:
try_setting_texture(
tex_3D_r32f,
TexSubset(Box(
min=one(v3u),
max=TEX_SIZE_3D
)),
let raws = UInt16[
11100 12100 13100 14100
21100 22100 23100 24100
31100 32100 33100 34100
;;;
11200 12200 13200 14200
21200 22200 23200 24200
31200 32200 33200 34200
;;;
11300 12300 13300 14300
21300 22300 23300 24300
31300 32300 33300 34300
;;;
11400 12400 13400 14400
21400 22400 23400 24400
31400 32400 33400 34400
;;;
11500 12500 13500 14500
21500 22500 23500 24500
31500 32500 33500 34500
]
(
raws,
ogl_pixel_convert.(Ref(Float32), raws)
)
end...
)
# Write as Int16, read as Float32:
try_setting_texture(
tex_3D_r32f,
TexSubset(Box(
min=one(v3u),
max=TEX_SIZE_3D
)),
let raws = Int16[
1110 1210 1310 1410
2110 2210 2310 2410
-3110 -3210 -3310 -3410
;;;
1120 1220 1320 1420
-2120 -2220 -2320 -2420
3120 3220 3320 3420
;;;
-1130 -1230 -1330 -1430
2130 2230 2330 2430
3130 3230 3330 3430
;;;
1140 1240 1340 1440
-2140 -2240 2340 2440
-3140 -3240 3340 3440
;;;
1150 1250 -1350 -1450
2150 2250 -2350 -2450
3150 3250 3350 3450
]
(
raws,
ogl_pixel_convert.(Ref(Float32), raws)
)
end...,
atol=0.0000001
)
# Cubemap:
# Write and read as Float32:
try_setting_texture(
tex_cube_r32f,
TexSubset(Box(
min=v3u(1, 2, 4),
max=v3u(1, 3, 5)
)),
Float32[
124 134
;;;
125 135
]
)
# Write and read as Float32:
try_setting_texture(
tex_cube_r32f,
TexSubset(Box(
min=v3u(1, 2, 4),
max=v3u(1, 3, 5)
)),
Float32[
124 134
;;;
125 135
]
)
# RG16inorm textures:
# 1D:
# Write and read Vec{2, Int16}:
try_setting_texture(
tex_1D_rg16in,
TexSubset(Box(
min=v1u(1),
max=v1u(3)
)),
Vec{2, Int16}[ Vec(120, -34),
Vec(27, -80),
Vec(-125, 100) ]
)
# Write Vec{2, Int16}, read back as v2f:
try_setting_texture(
tex_1D_rg16in,
TexSubset(Box(
min=v1u(1),
max=v1u(3)
)),
let raws = Vec{2, Int16}[ Vec(-5, 50), Vec(27, -2), Vec(-125, 12) ]
(
raws,
ogl_pixel_convert.(Ref(v2f), raws)
)
end...,
atol=0.0000001
)
# Write and read as v2f:
try_setting_texture(
tex_1D_rg16in,
TexSubset(Box(
min=v1u(1),
max=v1u(3)
)),
let raws = [ v2f(-0.5, 0.7),
v2f(0.1, 0.9),
v2f(0.852, -0.99) ]
(
raws,
ogl_pixel_convert.(Ref(v2f),
ogl_pixel_convert.(Ref(Vec{2, Int16}), raws))
)
end...,
atol=0.00005
)
# 3D:
# Write and read as v2f:
try_setting_texture(
tex_3D_rg16in,
TexSubset(Box(
min=v3u(1, 2, 3),
max=v3u(2, 3, 4),
)),
let raws = [
v2f(0.5111, 0.6111) v2f(0.5121, 0.6121)
v2f(0.5211, 0.6211) v2f(0.5221, 0.6221)
;;;
v2f(0.5112, 0.6112) v2f(0.5122, 0.6122)
v2f(0.5212, 0.6212) v2f(0.5222, 0.6222)
]
(raws, raws)
end...,
atol=0.00005
)
# Cubemap:
# Write and read as v2f:
try_setting_texture(
tex_cube_rg16in,
TexSubset(Box(
min=v3u(1, 2, 3),
max=v3u(2, 3, 4),
)),
let raws = [
v2f(0.5111, 0.6111) v2f(0.5121, 0.6121)
v2f(0.5211, 0.6211) v2f(0.5221, 0.6221)
;;;
v2f(0.5112, 0.6112) v2f(0.5122, 0.6122)
v2f(0.5212, 0.6212) v2f(0.5222, 0.6222)
]
(raws, raws)
end...,
atol=0.00005
)
# Write Green as Float32, then read RG values as v2f:
try_setting_texture(
tex_cube_rg16in,
TexSubset(Box(
min=v3u(1, 2, 3),
max=v3u(2, 3, 4)
)),
Float32[
0.01 0.02
0.03 0.04
;;;
0.05 0.06
0.07 0.08
],
v2f[
v2f(0, 0.01) v2f(0, 0.02)
v2f(0, 0.03) v2f(0, 0.04)
;;;
v2f(0, 0.05) v2f(0, 0.06)
v2f(0, 0.07) v2f(0, 0.08)
],
atol=0.00005,
single_component=PixelIOChannels.green
)
# RGBA8uint textures:
# 1D:
# Get and set RGBAu8
try_setting_texture(
tex_1D_rgba8u,
TexSubset(Box(
min=v1u(2),
max=v1u(2)
)),
Vec{4, UInt8}[ Vec(2, 3, 4, 5) ]
)
# Get and set RGBAu8
try_setting_texture(
tex_1D_rgba8u,
TexSubset(Box(
min=v1u(2),
max=v1u(3)
)),
Vec{4, UInt8}[ Vec(255, 8, 1, 2), Vec(38, 19, 20, 18) ]
)
# Set RGu8 and get RGBAu8
try_setting_texture(
tex_1D_rgba8u,
TexSubset(Box(
min=v1u(2),
max=v1u(3)
)),
Vec{2, UInt8}[ Vec(1, 2), Vec(20, 18) ],
Vec{4, UInt8}[ Vec(1, 2, 0, 1), Vec(20, 18, 0, 1) ]
)
# Set Ru8 and get RGBAu8
try_setting_texture(
tex_1D_rgba8u,
TexSubset(Box(
min=v1u(1),
max=v1u(3)
)),
UInt8[ 5, 17, 56 ],
Vec{4, UInt8}[ Vec(5, 0, 0, 1), Vec(17, 0, 0, 1), Vec(56, 0, 0, 1) ]
)
# Set Gu8 and get RGBAu8
try_setting_texture(
tex_1D_rgba8u,
TexSubset(Box(
min=v1u(1),
max=v1u(3)
)),
UInt8[ 5, 17, 56 ],
Vec{4, UInt8}[ Vec(0, 5, 0, 1), Vec(0, 17, 0, 1), Vec(0, 56, 0, 1) ],
single_component=PixelIOChannels.green
)
# Set Bu8 and get RGBAu8
try_setting_texture(
tex_1D_rgba8u,
TexSubset(Box(
min=v1u(1),
max=v1u(3)
)),
UInt8[ 5, 17, 56 ],
Vec{4, UInt8}[ Vec(0, 0, 5, 1), Vec(0, 0, 17, 1), Vec(0, 0, 56, 1) ],
single_component=PixelIOChannels.blue
)
# 3D:
# Set RGBu8 and get RGBAu8
try_setting_texture(
tex_3D_rgba8u,
TexSubset(Box(
min=v3u(2, 1, 5),
max=v3u(3, 3, 5)
)),
Vec{3, UInt8}[
Vec(8, 9, 1) Vec(5, 6, 7)
Vec(20, 30, 40) Vec(50, 100, 0)
Vec(111, 112, 114) Vec(115, 116, 118)
;;;
],
Vec{4, UInt8}[
Vec(8, 9, 1, 1) Vec(5, 6, 7, 1)
Vec(20, 30, 40, 1) Vec(50, 100, 0, 1)
Vec(111, 112, 114, 1) Vec(115, 116, 118, 1)
;;;
]
)
# Cube:
# Set RGBu8 and get RGBAu8
try_setting_texture(
tex_cube_rgba8u,
TexSubset(Box(
min=v3u(2, 1, 1),
max=v3u(3, 3, 1)
)),
Vec{3, UInt8}[
Vec(8, 9, 1) Vec(5, 6, 7)
Vec(20, 30, 40) Vec(50, 100, 0)
Vec(111, 112, 114) Vec(115, 116, 118)
;;;
],
Vec{4, UInt8}[
Vec(8, 9, 1, 1) Vec(5, 6, 7, 1)
Vec(20, 30, 40, 1) Vec(50, 100, 0, 1)
Vec(111, 112, 114, 1) Vec(115, 116, 118, 1)
;;;
]
)
#TODO: Test the depth/stencil textures
#TODO: Try setting other mip levels (check the top mip level is unchanged)
# Test texture-clearing.
try_clearing_texture(
tex_3D_r32f,
Float32(-4.5),
[
Box(
min=v3u(1, 1, 1),
max=v3u(3, 3, 3)
) => Float32(1.0),
Box(
min=v3u(3, 2, 3),
max=v3u(3, 4, 4)
) => Float32(2.4),
Box(
min=v3u(2, 3, 1),
max=v3u(2, 3, 5)
) => Float32(-999)
],
let output = Array{Float32, 3}(undef, TEX_SIZE_3D...)
output .= -4.5
for i in one(v3u):3
output[i] = 1.0
end
for i in v3u(3, 2, 3):v3u(3, 4, 4)
output[i] = 2.4
end
for i in v3u(2, 3, 1):v3u(2, 3, 5)
output[i] = -999
end
output
end
)
#TODO: Test that clearing subsets of the full 4 color components works as expected.
#TODO: Test recalculation of mips after setting the top mip (OpenGL mip calc always happens using the top mip's data)
# Set an R32u texture, copy_tex_pixels() to R32f, then check the pixels of the R32f texture.
tex_3D_r32u = Texture(
SimpleFormat(
FormatTypes.uint,
SimpleFormatComponents.R,
SimpleFormatBitDepths.B32
),
TEX_SIZE_3D
)
try_copying_texture(
tex_3D_r32u, tex_3D_r32f,
TexSubset(
Box(
min=v3u(2, 4, 5),
max=v3u(3, 4, 5)
),
1
),
v3u(2, 1, 3), 1,
let foreground_src_value = reinterpret(UInt32, @f32(9.251854)),
background_src_value = ~foreground_src_value,
background_dest_value = reinterpret(Float32, background_src_value)
(foreground_src_value, background_dest_value)
end...
)
#TODO: Try copying depth and/or stencil into a color texture
#TODO: Try copying at different mip levels
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 44521 | # Run sequences of compute operations on some data, and make sure it has the expected result.
bp_gl_context( v2i(800, 500), "Compute tests: SSBO",
vsync=VsyncModes.off,
debug_mode=true
) do context::Context
check_gl_logs("Before doing anything")
# 1. Generate color based on UV's.
compute1 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
layout(std430) buffer Output {
vec2 pixels[];
};
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * gl_WorkGroupSize.xy;
vec2 uv = vec2(pixel) / vec2(totalSize);
uint idx = pixel.x + (totalSize.x * pixel.y);
pixels[idx] = uv;
}
"; flexible_mode=false)
check_gl_logs("After compiling compute1")
@bp_check(compute1.compute_work_group_size == v3i(8, 8, 1))
# 2. Raise color to an exponent.
POWERS = Float32.((1.2, 0.4, 1.5, 0.9))
compute2 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
layout(std430) buffer InOut {
vec2 pixels[];
};
uniform float Power = 2.0;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = uvec2(gl_NumWorkGroups.xy * gl_WorkGroupSize.xy);
uint idx = pixel.x + (totalSize.x * pixel.y);
pixels[idx] = pow(pixels[idx], vec2(Power));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute2")
@bp_check(compute2.compute_work_group_size == v3i(8, 8, 1))
# 3. Multiply by a "work group uv" value.
compute3 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
layout(std430) buffer InOut {
vec2 pixels[];
};
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = uvec2(gl_NumWorkGroups.xy * gl_WorkGroupSize.xy);
uint idx = pixel.x + (totalSize.x * pixel.y);
vec2 groupUV = gl_LocalInvocationID.xy / vec2(gl_WorkGroupSize.xy);
pixels[idx] *= groupUV;
}
"; flexible_mode=false)
check_gl_logs("After compiling compute3")
@bp_check(compute3.compute_work_group_size == v3i(8, 8, 1))
# We're going to execute the above compute shaders, and a CPU equivalent,
# then check that they line up.
GROUP_SIZE = v2u(8, 8)
RESOLUTION = GROUP_SIZE * v2u(5, 8)
zero_based_idcs = 0 : convert(v2u, RESOLUTION - 1)
array = fill(zero(v2f), (RESOLUTION.data...))
buf = Buffer(false, fill(-one(v2f), (prod(RESOLUTION), )))
check_gl_logs("After creating compute Buffer")
function run_tests(context_msg...)
gl_catch_up_before(MemoryActions.texture_upload_or_download)
expected::Vector{v2f} = reshape(array, (prod(RESOLUTION), ))
actual::Vector{v2f} = get_buffer_data(buf, (v2f, length(expected)))
check_gl_logs("After reading compute buffer $(context_msg...)")
axis_difference::Vector{v2f} = abs.(expected .- actual)
total_difference::Vector{Float32} = vlength.(axis_difference)
MAX_ERROR = @f32(0.001)
biggest_error = maximum(total_difference)
if biggest_error >= MAX_ERROR
# Grab a few representative samples.
# Use a spacing that doesn't line up with work-group size.
logging_pixel_poses = UInt32(0):(GROUP_SIZE+UInt32(3)):(RESOLUTION-UInt32(1))
logging_pixel_idcs = map(logging_pixel_poses) do pos
pos.x + (pos.y * RESOLUTION.x)
end
logging_global_uv = map(logging_pixel_poses) do pos
pos / convert(v2f, RESOLUTION)
end
logging_powers_1 = map(logging_global_uv) do uv
uv ^ POWERS[1]
end
logging_powers_2 = map(logging_powers_1) do p
p ^ POWERS[2]
end
logging_powers_3 = map(logging_powers_2) do p
p ^ POWERS[3]
end
logging_powers_4 = map(logging_powers_3) do p
p ^ POWERS[4]
end
logging_workgroup_uv = map(logging_pixel_poses) do pos
(pos % GROUP_SIZE) / convert(v2f, GROUP_SIZE)
end
logging_calculated = map(*, logging_powers_4, logging_workgroup_uv)
logging_expected = getindex.(Ref(expected), logging_pixel_idcs .+ 1)
logging_actual = getindex.(Ref(actual), logging_pixel_idcs .+ 1)
data_msg = "Log: <\n"
for (pos, idx, g_uv, p1, p2, p3, p4, w_uv, c, e, a) in zip(logging_pixel_poses,
logging_pixel_idcs,
logging_global_uv,
logging_powers_1,
logging_powers_2,
logging_powers_3,
logging_powers_4,
logging_workgroup_uv,
logging_calculated,
logging_expected,
logging_actual)
data_msg *= "\tPixel (0-based):$pos {\n"
data_msg *= "\t\tIdx: $idx\n"
data_msg *= "\t\tGlobal UV: $g_uv\n"
data_msg *= "\t\tP1: $p1\n"
data_msg *= "\t\tP2: $p2\n"
data_msg *= "\t\tP3: $p3\n"
data_msg *= "\t\tP4: $p4\n"
data_msg *= "\t\tWorkgroup UV: $w_uv\n"
data_msg *= "\t\tFinal Calculated: $c\n"
data_msg *= "\t\tCurrent CPU: $e\n"
data_msg *= "\t\tCurrent GPU: $a\n"
data_msg *= "\t}\n"
end
data_msg *= ">\n"
data_msg *= "Flat run: [ "
data_msg *= join(actual[1:11], ", ")
data_msg *= "]"
error("SSBO compute tests: ", context_msg..., ". Compute shader output has a max error of ", biggest_error, "! ",
"There are ", count(e -> e>=MAX_ERROR, total_difference), " / ",
prod(RESOLUTION), " pixels which have this much error. Resolution ", RESOLUTION,
"\nBig log is below:\n", data_msg, "\n\n")
end
end
# 1:
# a. CPU array:
texel = @f32(1) / vsize(array)
map!(pixel::Vec2 -> (pixel * texel)::v2f, array, zero_based_idcs)
# b. GPU buffer:
set_storage_block(buf, 1)
check_gl_logs("After setting SSBO slot 1")
set_storage_block(compute1, "Output", 1)
check_gl_logs("After pointing compute1 to SSBO slot 1")
gl_catch_up_before(MemoryActions.buffer_storage)
dispatch_compute_threads(compute1, vappend(RESOLUTION, 1))
check_gl_logs("After running compute1")
set_storage_block(1)
check_gl_logs("After clearing compute1 SSBO slot")
check_gl_logs("After running compute1")
run_tests("After compute1")
# 2:
for power in POWERS
# a. CPU array:
array .^= power
# b. GPU buffer:
set_storage_block(buf, 3)
set_storage_block(compute2, "InOut", 3)
set_uniform(compute2, "Power", power)
gl_catch_up_before(MemoryActions.buffer_storage)
dispatch_compute_threads(compute2, vappend(RESOLUTION, 1))
set_storage_block(3)
check_gl_logs("After running compute2 with $power")
run_tests("After compute2($power)")
end
# 3:
# a. CPU array:
map!(array, zero_based_idcs) do pixel_idx
work_group_uv = (pixel_idx % GROUP_SIZE) / convert(v2f, GROUP_SIZE)
return array[pixel_idx + 1] * work_group_uv
end
# b. GPU buffer:
set_storage_block(buf, 2)
set_storage_block(compute3, "InOut", 2)
gl_catch_up_before(MemoryActions.buffer_storage)
dispatch_compute_threads(compute3, vappend(RESOLUTION, 1))
set_storage_block(2)
check_gl_logs("After running compute3")
run_tests("After compute3")
end
# Run a sequence of compute operations on a 3D texture.
bp_gl_context( v2i(800, 500), "Compute tests: 3D layered Image View",
vsync=VsyncModes.off,
debug_mode=true
) do context::Context
check_gl_logs("Before doing anything")
GROUP_SIZE = v3u(8, 4, 2)
RESOLUTION = GROUP_SIZE * v3u(5, 8, 1)
zero_based_idcs = UInt32(0) : (RESOLUTION - UInt32(1))
# 1. Generate color based on global and local UV's.
cpu_compute1(idcs_zero) = let arr = fill(zero(v4f), RESOLUTION...)
map!(arr, idcs_zero) do pixel
global_uv = convert(v3f, pixel) / convert(v3f, RESOLUTION)
local_uv = (pixel % GROUP_SIZE) / convert(v3f, GROUP_SIZE)
return convert(v4f,
lerp(-1, 1, vappend(global_uv.xz, local_uv.yz))
)
end
arr
end
compute1 = Program("
layout(local_size_x = 8, local_size_y = 4, local_size_z = 2) in;
uniform layout(rgba16_snorm) writeonly image3D Output;
void main() {
uvec3 pixel = gl_GlobalInvocationID;
uvec3 totalSize = gl_NumWorkGroups * gl_WorkGroupSize;
vec3 globalUV = vec3(pixel) / vec3(totalSize);
vec3 localUV = gl_LocalInvocationID / vec3(gl_WorkGroupSize.xyz);
//NOTE: Nvidia driver's shader compiler seems to crash
// when I don't add '.xyz' to gl_WorkGroupSize in the denominator.
imageStore(Output, ivec3(pixel),
mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
vec4(globalUV.xz, localUV.yz)));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute1")
@bp_check(compute1.compute_work_group_size == v3i(8, 4, 2))
# 2. Pass through a triangle wave (sine waves are simpler but prone to numeric error).
PERIOD = v4f(1, 2, 3, 4)
cpu_compute2(array, idcs_zero) = map!(array, idcs_zero) do pixel
weighted_value = array[pixel + 1] / convert(v4f, PERIOD)
triangle_wave_t = 2 * abs(weighted_value - floor(weighted_value + 0.5))
return convert(v4f, lerp(-1, 1, triangle_wave_t))
end
compute2 = Program("
layout(local_size_x = 8, local_size_y = 4, local_size_z = 2) in;
uniform vec4 Period;
uniform layout(rgba16_snorm) image3D InOut;
void main() {
uvec3 pixel = gl_GlobalInvocationID;
uvec3 totalSize = gl_NumWorkGroups * gl_WorkGroupSize;
vec4 imgValue = imageLoad(InOut, ivec3(pixel));
vec4 weightedValue = imgValue / Period;
vec4 triangleWaveT = 2 * abs(weightedValue - floor(weightedValue + 0.5));
vec4 outValue = mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
triangleWaveT);
imageStore(InOut, ivec3(pixel), outValue);
}
"; flexible_mode=false)
check_gl_logs("After compiling compute2")
@bp_check(compute2.compute_work_group_size == v3i(8, 4, 2))
# 3. Scale and fract() the data.
SCALE = v4f(1.5, 3.8, -1.2, -4.6) #NOTE: Large values magnify the error from the 16bit_snorm format,
# so keep them small
cpu_compute3(array, idcs_zero) = map!(array, idcs_zero) do pixel
return fract(array[pixel + 1] * SCALE)
end
compute3 = Program("
layout(local_size_x = 8, local_size_y = 4, local_size_z = 2) in;
uniform layout(rgba16_snorm) image3D InOut;
void main() {
uvec3 pixel = gl_GlobalInvocationID;
uvec3 totalSize = gl_NumWorkGroups * gl_WorkGroupSize;
vec4 imgValue = imageLoad(InOut, ivec3(pixel));
#define SCALE vec4( $(join(SCALE, ", ")) )
imageStore(InOut, ivec3(pixel), fract(imgValue * SCALE));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute3")
@bp_check(compute3.compute_work_group_size == v3i(8, 4, 2))
# We're going to execute the above compute shaders, and a CPU equivalent,
# then check that they line up.
tex = Texture(
SimpleFormat(
FormatTypes.normalized_int,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B16
),
fill(-one(v4f), RESOLUTION...)
)
check_gl_logs("After creating texture")
tex_view = get_view(tex, SimpleViewParams())
view_activate(tex_view)
check_gl_logs("After creating/activating texture view")
function run_tests(context_msg...)
gl_catch_up_before(MemoryActions.texture_upload_or_download)
expected = array
actual = fill(zero(v4f), RESOLUTION...)
get_tex_color(tex, actual)
check_gl_logs("After reading image $(context_msg...)")
axis_difference::Array{v4f} = abs.(expected .- actual)
total_difference::Array{Float32} = max.(axis_difference)
MAX_ERROR = @f32(0.01) # Large error margins due to 16_Snorm format
biggest_error = maximum(total_difference)
if biggest_error >= MAX_ERROR
BplusCore.Math.VEC_N_DIGITS = 5
# Grab a few representative samples.
# Use a spacing that doesn't line up with work-group size.
logging_pixel_poses = UInt32(0):(GROUP_SIZE+UInt32(3)):(RESOLUTION-UInt32(1))
logging_pixel_idcs = map(p -> vindex(p+1, RESOLUTION), logging_pixel_poses)
logging_output1 = cpu_compute1(zero_based_idcs)
logging_output1 = getindex.(Ref(logging_output1), logging_pixel_idcs)
logging_output2 = copy(logging_output1); cpu_compute2(logging_output2, 0:length(logging_output2)-1)
logging_calculated = copy(logging_output2); cpu_compute3(logging_calculated, 0:length(logging_calculated)-1)
logging_expected = getindex.(Ref(expected), logging_pixel_idcs)
logging_actual = getindex.(Ref(actual), logging_pixel_idcs)
data_msg = "Log: <\n"
for (pos, o1, o2, c, e, a) in zip(logging_pixel_poses,
logging_output1,
logging_output2,
logging_calculated,
logging_expected,
logging_actual
)
data_msg *= "\tPixel (0-based):$pos {\n"
data_msg *= "\t\tO1: $o1\n"
data_msg *= "\t\tO2: $o2\n"
data_msg *= "\t\tFinal Calculated: $c\n"
data_msg *= "\t\tCurrent CPU: $e\n"
data_msg *= "\t\tCurrent GPU: $a\n"
data_msg *= "\t}\n"
end
data_msg *= ">\n"
data_msg *= "Flat run: [ "
data_msg *= join(actual[1:11], ", ")
data_msg *= "]\n"
data_msg *= "Corners: [\n"
for corner::NTuple{3, Int} in Iterators.product((0, 1), (0, 1), (0, 1))
corner = corner .* RESOLUTION.data
corner = map(i -> (i==0) ? 1 : i, corner)
idx = vindex(Vec(corner), RESOLUTION)
data_msg *= "\t$(Vec(corner...)) : Expected $(expected[idx]) : Got $(actual[idx])\n"
end
data_msg *= "]"
error("Layered 3D image compute tests: ", context_msg..., ". Compute shader output has a max error of ", biggest_error, "! ",
"There are ", count(e -> e>=MAX_ERROR, total_difference), " / ",
prod(RESOLUTION), " pixels which have this much error. Resolution ", RESOLUTION,
"\nBig log is below:\n", data_msg, "\n\n")
end
end
# Execute step 1.
array = cpu_compute1(zero_based_idcs)
set_uniform(compute1, "Output", tex_view)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute1, RESOLUTION)
check_gl_logs("After running compute1")
run_tests("After compute1")
# Execute step 2.
cpu_compute2(array, zero_based_idcs)
set_uniform(compute2, "InOut", tex_view)
set_uniform(compute2, "Period", PERIOD)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute2, RESOLUTION)
check_gl_logs("After running compute2")
run_tests("After compute2")
# Execute step 3.
cpu_compute3(array, zero_based_idcs)
set_uniform(compute3, "InOut", tex_view)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute3, RESOLUTION)
check_gl_logs("After running compute3")
run_tests("After compute3")
end
# Run a sequence of compute operations on one face of a cubemap texture.
bp_gl_context( v2i(800, 500), "Compute tests: 3D non-layered Image View",
vsync=VsyncModes.off,
debug_mode=true
) do context::Context
check_gl_logs("Before doing anything")
GROUP_SIZE = 8
GROUP_SIZE_2D = Vec(GROUP_SIZE, GROUP_SIZE)
RESOLUTION = GROUP_SIZE * 4
RESOLUTION_2D = Vec(RESOLUTION, RESOLUTION)
zero_based_idcs = UInt32(0) : vappend(RESOLUTION_2D - UInt32(1), UInt32(0))
# 1. Generate color based on global and local UV's.
cpu_compute1(idcs_zero) = let arr = fill(v4f(i->NaN32), RESOLUTION_2D..., 1)
map!(arr, idcs_zero) do _pixel
pixel = _pixel.xy
global_uv = convert(v2f, pixel) / convert(v2f, RESOLUTION_2D)
local_uv = (pixel % GROUP_SIZE_2D) / convert(v2f, GROUP_SIZE_2D)
return convert(v4f,
lerp(-1, 1, vappend(global_uv, local_uv))
)
end
arr
end
compute1 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) writeonly image2D Output;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * uvec2($GROUP_SIZE, $GROUP_SIZE);
vec2 globalUV = vec2(pixel) / vec2($RESOLUTION, $RESOLUTION);
vec2 localUV = gl_LocalInvocationID.xy / vec2($GROUP_SIZE, $GROUP_SIZE);
//NOTE: Nvidia driver's shader compiler seems to crash
// when I don't add '.xy' to gl_WorkGroupSize in the denominator.
imageStore(Output, ivec2(pixel),
mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
vec4(globalUV, localUV)));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute1")
@bp_check(compute1.compute_work_group_size == v3i(8, 8, 1))
# 2. Pass through a triangle wave (sine waves are simpler but prone to numeric error).
PERIOD = v4f(1.234, 4.253, 8.532, -4.4368)
cpu_compute2(array, idcs_zero) = map!(array, idcs_zero) do _pixel
pixel = _pixel.xy
weighted_value = array[pixel + 1] / PERIOD
triangle_wave_t = 2 * abs(weighted_value - floor(weighted_value + 0.5))
return convert(v4f, lerp(-1, 1, triangle_wave_t))
end
compute2 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) image2D InOut;
uniform vec4 Period;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * uvec2($GROUP_SIZE, $GROUP_SIZE);
vec4 imgValue = imageLoad(InOut, ivec2(pixel));
vec4 weightedValue = imgValue / Period;
vec4 triangleWaveT = 2 * abs(weightedValue - floor(weightedValue + 0.5));
vec4 outValue = mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
triangleWaveT);
imageStore(InOut, ivec2(pixel), outValue);
}
"; flexible_mode=false)
check_gl_logs("After compiling compute2")
@bp_check(compute2.compute_work_group_size == v3i(8, 8, 1))
# 3. Scale and fract() the data.
SCALE = v4f(13.5, 31.8, -16.2, -48.6)
cpu_compute3(array, idcs_zero) = map!(array, idcs_zero) do _pixel
pixel = _pixel.xy
return fract(array[pixel + 1] * SCALE)
end
compute3 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) image2D InOut;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * gl_WorkGroupSize.xy;
vec4 imgValue = imageLoad(InOut, ivec2(pixel));
#define SCALE vec4( $(join(SCALE, ", ")) )
imageStore(InOut, ivec2(pixel), fract(imgValue * SCALE));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute3")
@bp_check(compute3.compute_work_group_size == v3i(8, 8, 1))
# We're going to execute the above compute shaders, and a CPU equivalent,
# then check that they line up.
tex = Texture(
SimpleFormat(
FormatTypes.float,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B32
),
vappend(RESOLUTION_2D, 256)
)
check_gl_logs("After creating texture")
Z_SLICE = 3
tex_view = get_view(tex, SimpleViewParams(
layer = Z_SLICE
))
view_activate(tex_view)
check_gl_logs("After creating/activating texture view")
function run_tests(context_msg...)
view_deactivate(tex_view)
gl_catch_up_before(MemoryActions.texture_upload_or_download)
expected::Array{v4f} = array
actual::Array{v4f} = fill(v4f(i->NaN32), RESOLUTION_2D..., 1)
get_tex_color(tex, actual, TexSubset(Box(
min = v3u(1, 1, Z_SLICE),
size = v3u(tex.size.xy..., 1)
)))
check_gl_logs("After reading image $(context_msg...)")
axis_difference::Array{v4f} = abs.(expected .- actual)
total_difference::Array{Float32} = max.(axis_difference)
MAX_ERROR = @f32(0.001)
biggest_error = maximum(total_difference)
if biggest_error >= MAX_ERROR
BplusCore.Math.VEC_N_DIGITS = 5
# Grab a few representative samples.
# Use a spacing that doesn't line up with work-group size.
logging_pixel_poses = v2u(0, 0, Z_SLICE):vappend(GROUP_SIZE_2D+UInt32(3), UInt32(1)):vappend(RESOLUTION_2D-UInt32(1), Z_SLICE)
logging_pixel_idcs = map(p -> vindex(p+1, vappend(RESOLUTION_2D, 1)), logging_pixel_poses)
logging_output1 = cpu_compute1(zero_based_idcs)
logging_output1 = getindex.(Ref(logging_output1), logging_pixel_idcs)
logging_output2 = copy(logging_output1); cpu_compute2(logging_output2, 0:length(logging_output2)-1)
logging_calculated = copy(logging_output2); cpu_compute3(logging_calculated, 0:length(logging_calculated)-1)
logging_expected = getindex.(Ref(expected), logging_pixel_idcs)
logging_actual = getindex.(Ref(actual), logging_pixel_idcs)
data_msg = "Log: <\n"
for (pos, o1, o2, c, e, a) in zip(logging_pixel_poses,
logging_output1,
logging_output2,
logging_calculated,
logging_expected,
logging_actual
)
data_msg *= "\tPixel (0-based):$pos {\n"
data_msg *= "\t\tO1: $o1\n"
data_msg *= "\t\tO2: $o2\n"
data_msg *= "\t\tFinal Calculated: $c\n"
data_msg *= "\t\tCurrent CPU: $e\n"
data_msg *= "\t\tCurrent GPU: $a\n"
data_msg *= "\t}\n"
end
data_msg *= ">\n"
data_msg *= "Flat run: [ "
data_msg *= join(actual[1:11], ", ")
data_msg *= "]\n"
data_msg *= "Corners: [\n"
for corner::NTuple{2, Int} in Iterators.product((0, 1), (0, 1))
corner = corner .* RESOLUTION_2D.data
corner = map(i -> (i==0) ? 1 : i, corner)
idx = vindex(Vec(corner), RESOLUTION_2D)
data_msg *= "\t$(Vec(corner...)) : Expected $(expected[idx]) : Got $(actual[idx])\n"
end
data_msg *= "]\n"
error("Non-layered 3D compute tests: ", context_msg..., ". Compute shader output has a max error of ", biggest_error, "! ",
"There are ", count(e -> e>=MAX_ERROR, total_difference), " / ",
prod(RESOLUTION_2D), " pixels which have this much error. Resolution ", RESOLUTION_2D,
"\nBig log is below:\n", data_msg, "\n\n")
else
view_activate(tex_view)
end
end
# Execute step 1.
array = cpu_compute1(zero_based_idcs)
set_uniform(compute1, "Output", tex_view)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute1, vappend(RESOLUTION_2D, 1))
check_gl_logs("After running compute1")
run_tests("After compute1")
# Execute step 2.
cpu_compute2(array, zero_based_idcs)
set_uniform(compute2, "InOut", tex_view)
set_uniform(compute2, "Period", PERIOD)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute2, vappend(RESOLUTION_2D, 1))
check_gl_logs("After running compute2")
run_tests("After compute2")
# Execute step 3.
cpu_compute3(array, zero_based_idcs)
set_uniform(compute3, "InOut", tex_view)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute3, vappend(RESOLUTION_2D, 1))
check_gl_logs("After running compute3")
run_tests("After compute3")
end
# Run a sequence of compute operations on all faces of a cubemap texture.
bp_gl_context( v2i(800, 500), "Compute tests: Cubemap layered Image View",
vsync=VsyncModes.off,
debug_mode=true
) do context::Context
check_gl_logs("Before doing anything")
GROUP_SIZE = 8
GROUP_SIZE_3D = Vec(GROUP_SIZE, GROUP_SIZE, 1)
RESOLUTION = GROUP_SIZE * 4
RESOLUTION_2D = Vec(RESOLUTION, RESOLUTION)
RESOLUTION_3D = Vec(RESOLUTION, RESOLUTION, 6)
zero_based_idcs = UInt32(0) : (RESOLUTION_3D - UInt32(1))
# 1. Generate color based on global and local UV's.
cpu_compute1(idcs_zero) = let arr = fill(zero(v4f), RESOLUTION_3D...)
map!(arr, idcs_zero) do pixel
global_uv = convert(v3f, pixel) / convert(v3f, RESOLUTION_3D)
local_uv = (pixel % GROUP_SIZE_3D) / convert(v3f, GROUP_SIZE_3D)
return convert(v4f,
lerp(-1, 1, vappend(global_uv.xz, local_uv.yz))
)
end
arr
end
compute1 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) writeonly imageCube Output;
void main() {
uvec3 pixel = gl_GlobalInvocationID.xyz;
uvec3 totalSize = gl_NumWorkGroups.xyz * gl_WorkGroupSize.xyz;
vec3 globalUV = vec3(pixel) / vec3(totalSize);
vec3 localUV = gl_LocalInvocationID.xyz / vec3(gl_WorkGroupSize.xyz);
//NOTE: Nvidia driver's shader compiler seems to crash
// when I don't add '.xyz' to gl_WorkGroupSize in the denominator.
imageStore(Output, ivec3(pixel),
mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
vec4(globalUV.xz, localUV.yz)));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute1")
@bp_check(compute1.compute_work_group_size == GROUP_SIZE_3D)
# 2. Pass through a triangle wave (sine waves are simpler but prone to numeric error).
PERIOD = v4f(2.2, 3.8, 5.8, 9.2)
cpu_compute2(array, idcs_zero) = map!(array, idcs_zero) do pixel
weighted_value = array[pixel + 1] / convert(v4f, PERIOD)
triangle_wave_t = 2 * abs(weighted_value - floor(weighted_value + 0.5))
return convert(v4f, lerp(-1, 1, triangle_wave_t))
end
compute2 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) imageCube InOut;
uniform vec4 Period;
void main() {
uvec3 pixel = gl_GlobalInvocationID.xyz;
uvec3 totalSize = gl_NumWorkGroups.xyz * gl_WorkGroupSize.xyz;
vec4 imgValue = imageLoad(InOut, ivec3(pixel));
vec4 weightedValue = imgValue / Period;
vec4 triangleWaveT = 2 * abs(weightedValue - floor(weightedValue + 0.5));
vec4 outValue = mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
triangleWaveT);
imageStore(InOut, ivec3(pixel), outValue);
}
"; flexible_mode=false)
check_gl_logs("After compiling compute2")
@bp_check(compute2.compute_work_group_size == GROUP_SIZE_3D)
# 3. Scale and fract() the data.
SCALE = v4f(13.5, 31.8, -16.2, -48.6)
cpu_compute3(array, idcs_zero) = map!(array, idcs_zero) do pixel
return fract(array[pixel + 1] * SCALE)
end
compute3 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) imageCube InOut;
void main() {
uvec3 pixel = gl_GlobalInvocationID.xyz;
uvec3 totalSize = gl_NumWorkGroups.xyz * gl_WorkGroupSize.xyz;
vec4 imgValue = imageLoad(InOut, ivec3(pixel));
#define SCALE vec4( $(join(SCALE, ", ")) )
imageStore(InOut, ivec3(pixel), fract(imgValue * SCALE));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute3")
@bp_check(compute3.compute_work_group_size == GROUP_SIZE_3D)
# We're going to execute the above compute shaders, and a CPU equivalent,
# then check that they line up.
tex = Texture_cube(
SimpleFormat(
FormatTypes.float,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B32
),
RESOLUTION
)
check_gl_logs("After creating texture")
tex_view = get_view(tex, SimpleViewParams())
view_activate(tex_view)
check_gl_logs("After creating/activating texture view")
function run_tests(context_msg...)
view_deactivate(tex_view)
gl_catch_up_before(MemoryActions.texture_upload_or_download)
expected = array
actual = fill(v4f(i->NaN32), RESOLUTION_3D...)
get_tex_color(tex, actual)
check_gl_logs("After reading image $(context_msg...)")
axis_difference::Array{v4f} = abs.(expected .- actual)
total_difference::Array{Float32} = max.(axis_difference)
MAX_ERROR = @f32(0.001)
biggest_error = maximum(total_difference)
if biggest_error >= MAX_ERROR
BplusCore.Math.VEC_N_DIGITS = 5
# Grab a few representative samples.
# Use a spacing that doesn't line up with work-group size.
logging_pixel_poses = UInt32(0):(GROUP_SIZE_3D+v3u(3, 3, 0)):(RESOLUTION_3D-UInt32(1))
logging_pixel_idcs = map(p -> vindex(p+1, RESOLUTION_3D), logging_pixel_poses)
logging_output1 = cpu_compute1(zero_based_idcs)
logging_output1 = getindex.(Ref(logging_output1), logging_pixel_idcs)
logging_output2 = copy(logging_output1); cpu_compute2(logging_output2, 0:length(logging_output2)-1)
logging_calculated = copy(logging_output2); cpu_compute3(logging_calculated, 0:length(logging_calculated)-1)
logging_expected = getindex.(Ref(expected), logging_pixel_idcs)
logging_actual = getindex.(Ref(actual), logging_pixel_idcs)
data_msg = "Log: <\n"
for (pos, o1, o2, c, e, a) in zip(logging_pixel_poses,
logging_output1,
logging_output2,
logging_calculated,
logging_expected,
logging_actual
)
data_msg *= "\tPixel (0-based):$pos {\n"
data_msg *= "\t\tO1: $o1\n"
data_msg *= "\t\tO2: $o2\n"
data_msg *= "\t\tFinal Calculated: $c\n"
data_msg *= "\t\tCurrent CPU: $e\n"
data_msg *= "\t\tCurrent GPU: $a\n"
data_msg *= "\t}\n"
end
data_msg *= ">\n"
data_msg *= "Flat run: [ "
data_msg *= join(actual[1:11], ", ")
data_msg *= "]\n"
data_msg *= "Corners: [\n"
for corner::NTuple{3, Int} in Iterators.product((0, 1), (0, 1), (0, 1))
corner = corner .* RESOLUTION_3D.data
corner = map(i -> (i==0) ? 1 : i, corner)
idx = vindex(Vec(corner), RESOLUTION_3D)
data_msg *= "\t$(Vec(corner...)) : Expected $(expected[idx]) : Got $(actual[idx])\n"
end
data_msg *= "]\n"
error("Layered Cubemap image view compute tests: ", context_msg...,
". Compute shader output has a max error of ", biggest_error, "! ",
"There are ", count(e -> e>=MAX_ERROR, total_difference), " / ",
prod(RESOLUTION_3D), " pixels which have this much error. Resolution ", RESOLUTION_2D,
"\nBig log is below:\n", data_msg, "\n\n")
else
view_activate(tex_view)
end
end
# Execute step 1.
array = cpu_compute1(zero_based_idcs)
set_uniform(compute1, "Output", tex_view)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute1, RESOLUTION_3D)
check_gl_logs("After running compute1")
run_tests("After compute1")
# Execute step 2.
cpu_compute2(array, zero_based_idcs)
set_uniform(compute2, "InOut", tex_view)
set_uniform(compute2, "Period", PERIOD)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute2, RESOLUTION_3D)
check_gl_logs("After running compute2")
run_tests("After compute2")
# Execute step 3.
cpu_compute3(array, zero_based_idcs)
set_uniform(compute3, "InOut", tex_view)
gl_catch_up_before(MemoryActions.texture_simple_views)
dispatch_compute_threads(compute3, RESOLUTION_3D)
check_gl_logs("After running compute3")
run_tests("After compute3")
end
# Run a sequence of compute operations on one face of a cubemap texture.
bp_gl_context( v2i(800, 500), "Compute tests: Cubemap non-layered Image View",
vsync=VsyncModes.off,
debug_mode=true
) do context::Context
check_gl_logs("Before doing anything")
GROUP_SIZE = 8
GROUP_SIZE_2D = Vec(GROUP_SIZE, GROUP_SIZE)
RESOLUTION = GROUP_SIZE * 4
RESOLUTION_2D = Vec(RESOLUTION, RESOLUTION)
zero_based_idcs = UInt32(0) : (RESOLUTION_2D - UInt32(1))
# 1. Generate color based on global and local UV's.
cpu_compute1(idcs_zero) = let arr = fill(v4f(i->NaN32), RESOLUTION_2D...)
map!(arr, idcs_zero) do pixel
global_uv = convert(v2f, pixel) / convert(v2f, RESOLUTION_2D)
local_uv = (pixel % GROUP_SIZE_2D) / convert(v2f, GROUP_SIZE_2D)
return convert(v4f,
lerp(v4f(-23, -6, 10, 13),
v4f(6, 22, -4.54645, -8.4568),
vappend(global_uv, local_uv))
)
end
arr
end
compute1 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) writeonly image2D Output;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * uvec2($GROUP_SIZE, $GROUP_SIZE);
vec2 globalUV = vec2(pixel) / vec2($RESOLUTION, $RESOLUTION);
vec2 localUV = gl_LocalInvocationID.xy / vec2($GROUP_SIZE, $GROUP_SIZE);
//NOTE: Nvidia driver's shader compiler seems to crash
// when I don't add '.xy' to gl_WorkGroupSize in the denominator.
imageStore(Output, ivec2(pixel),
mix(vec4(-23, -6, 10, 13),
vec4(6, 22, -4.54645, -8.4568),
vec4(globalUV, localUV)));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute1")
@bp_check(compute1.compute_work_group_size == v3i(8, 8, 1))
# 2. Pass through a triangle wave (sine waves are simpler but prone to numeric error).
PERIOD = v4f(1.234, 4.253, 8.532, -4.4368)
cpu_compute2(array, idcs_zero) = map!(array, idcs_zero) do pixel
weighted_value = array[pixel + 1] / PERIOD
triangle_wave_t = 2 * abs(weighted_value - floor(weighted_value + 0.5))
return convert(v4f, lerp(-1, 1, triangle_wave_t))
end
compute2 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) image2D InOut;
uniform vec4 Period;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * uvec2($GROUP_SIZE, $GROUP_SIZE);
vec4 imgValue = imageLoad(InOut, ivec2(pixel));
vec4 weightedValue = imgValue / Period;
vec4 triangleWaveT = 2 * abs(weightedValue - floor(weightedValue + 0.5));
vec4 outValue = mix(vec4(-1, -1, -1, -1),
vec4(1, 1, 1, 1),
triangleWaveT);
imageStore(InOut, ivec2(pixel), outValue);
}
"; flexible_mode=false)
check_gl_logs("After compiling compute2")
@bp_check(compute2.compute_work_group_size == v3i(8, 8, 1))
# 3. Scale and fract() the data.
SCALE = v4f(13.5, 31.8, -16.2, -48.6)
cpu_compute3(array, idcs_zero) = map!(array, idcs_zero) do pixel
return fract(array[pixel + 1] * SCALE)
end
compute3 = Program("
layout(local_size_x = 8, local_size_y = 8) in;
uniform layout(rgba32f) image2D InOut;
void main() {
uvec2 pixel = gl_GlobalInvocationID.xy;
uvec2 totalSize = gl_NumWorkGroups.xy * gl_WorkGroupSize.xy;
vec4 imgValue = imageLoad(InOut, ivec2(pixel));
#define SCALE vec4( $(join(SCALE, ", ")) )
imageStore(InOut, ivec2(pixel), fract(imgValue * SCALE));
}
"; flexible_mode=false)
check_gl_logs("After compiling compute3")
@bp_check(compute3.compute_work_group_size == v3i(8, 8, 1))
# We're going to execute the above compute shaders, and a CPU equivalent,
# then check that they line up.
tex = Texture_cube(
SimpleFormat(
FormatTypes.float,
SimpleFormatComponents.RGBA,
SimpleFormatBitDepths.B32
),
RESOLUTION
)
check_gl_logs("After creating texture")
CUBE_FACE = 3
tex_view = get_view(tex, SimpleViewParams(
layer = CUBE_FACE
))
view_activate(tex_view)
check_gl_logs("After creating/activating texture view")
function run_tests(context_msg...)
view_deactivate(tex_view)
gl_catch_up_before(MemoryActions.texture_upload_or_download)
expected = array
actual = fill(v4f(i->NaN32), RESOLUTION_2D..., 1)
get_tex_color(tex, actual, TexSubset(Box(
min=v3u(1, 1, CUBE_FACE),
size=v3u(RESOLUTION_2D..., 1)
)))
check_gl_logs("After reading image $(context_msg...)")
axis_difference::Array{v4f} = abs.(expected .- actual)
total_difference::Array{Float32} = max.(axis_difference)
MAX_ERROR = @f32(0.001)
biggest_error = maximum(total_difference)
if biggest_error >= MAX_ERROR
BplusCore.Math.VEC_N_DIGITS = 5
# Grab a few representative samples.
# Use a spacing that doesn't line up with work-group size.
logging_pixel_poses = UInt32(0):(GROUP_SIZE_2D+UInt32(3)):(RESOLUTION_2D-UInt32(1))
logging_pixel_idcs = map(p -> vindex(p+1, RESOLUTION_2D), logging_pixel_poses)
logging_output1 = cpu_compute1(zero_based_idcs)
logging_output1 = getindex.(Ref(logging_output1), logging_pixel_idcs)
logging_output2 = copy(logging_output1); cpu_compute2(logging_output2, 0:length(logging_output2)-1)
logging_calculated = copy(logging_output2); cpu_compute3(logging_calculated, 0:length(logging_calculated)-1)
logging_expected = getindex.(Ref(expected), logging_pixel_idcs)
logging_actual = getindex.(Ref(actual), logging_pixel_idcs)
data_msg = "Log: <\n"
for (pos, o1, o2, c, e, a) in zip(logging_pixel_poses,
logging_output1,
logging_output2,
logging_calculated,
logging_expected,
logging_actual
)
data_msg *= "\tPixel (0-based):$pos {\n"
data_msg *= "\t\tO1: $o1\n"
data_msg *= "\t\tO2: $o2\n"
data_msg *= "\t\tFinal Calculated: $c\n"
data_msg *= "\t\tCurrent CPU: $e\n"
data_msg *= "\t\tCurrent GPU: $a\n"
data_msg *= "\t}\n"
end
data_msg *= ">\n"
data_msg *= "Flat run: [ "
data_msg *= join(actual[1:11], ", ")
data_msg *= "]\n"
data_msg *= "Corners: [\n"
for corner::NTuple{2, Int} in Iterators.product((0, 1), (0, 1))
corner = corner .* RESOLUTION_2D.data
corner = map(i -> (i==0) ? 1 : i, corner)
idx = vindex(Vec(corner), RESOLUTION_2D)
data_msg *= "\t$(Vec(corner...)) : Expected $(expected[idx]) : Got $(actual[idx])\n"
end
data_msg *= "]\n"
error("Non-layered Cubemap compute tests: ", context_msg..., ". Compute shader output has a max error of ", biggest_error, "! ",
"There are ", count(e -> e>=MAX_ERROR, total_difference), " / ",
prod(RESOLUTION_2D), " pixels which have this much error. Resolution ", RESOLUTION_2D,
"\nBig log is below:\n", data_msg, "\n\n")
else
view_activate(tex_view)
end
end
# Execute step 1.
array = cpu_compute1(zero_based_idcs)
gl_catch_up_before(MemoryActions.texture_simple_views)
set_uniform(compute1, "Output", tex_view)
dispatch_compute_threads(compute1, vappend(RESOLUTION_2D, 1))
check_gl_logs("After running compute1")
run_tests("After compute1")
# Execute step 2.
cpu_compute2(array, zero_based_idcs)
gl_catch_up_before(MemoryActions.USE_TEXTURES) # Gets around a potential driver bug. See B+ issue #111
set_uniform(compute2, "InOut", tex_view)
set_uniform(compute2, "Period", PERIOD)
dispatch_compute_threads(compute2, vappend(RESOLUTION_2D, 1))
check_gl_logs("After running compute2")
run_tests("After compute2")
# Execute step 3.
cpu_compute3(array, zero_based_idcs)
gl_catch_up_before(MemoryActions.USE_TEXTURES)
set_uniform(compute3, "InOut", tex_view)
dispatch_compute_threads(compute3, vappend(RESOLUTION_2D, 1))
check_gl_logs("After running compute3")
run_tests("After compute3")
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 1605 | # Make sure the test is always running for *this* project.
using Pkg
cd(joinpath(@__DIR__, ".."))
Pkg.activate(".")
using BplusCore; @using_bplus_core
using BplusApp; @using_bplus_app
# Enable asserts for B+ App.
BplusApp.GL.bp_gl_asserts_enabled() = true
BplusApp.Input.bp_input_asserts_enabled() = true
BplusApp.GUI.bp_gui_asserts_enabled() = true
# Execute the tests.
const TEST_HEADER_EXTRA = quote
using Dates, Random, Setfield, InteractiveUtils
using JSON3, CSyntax, StructTypes
using CImGui, GLFW
# Sadly, the macros to auto-import B+ do not work right in here.
using BplusCore, BplusApp
for use in (BplusCore.MODULES_USING_STATEMENTS...,
BplusApp.MODULES_USING_STATEMENTS...)
eval(use)
end
"Checks for OpenGL error messages, and prints less-severe messages"
function check_gl_logs(context::String)
logs = pull_gl_logs()
for log in logs
msg = sprint(show, log)
if log.severity in (DebugEventSeverities.high, DebugEventSeverities.medium)
@warn "$context. $msg"
println("Stacktrace:\n--------------------")
display(stacktrace())
println("-------------------\n\n")
elseif log.severity == DebugEventSeverities.low
@warn "$context. $msg"
elseif log.severity == DebugEventSeverities.none
@info "$context. $msg"
else
@error "Message, UNEXPECTED SEVERITY $(log.severity): $msg"
end
end
end
end
include(BplusCore.TEST_RUNNER_PATH) | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 10779 | # BplusApp.GL.BUFFER_LAYOUT_MACRO_DEBUG_STREAM = stdout
@std140 struct A
f::Float32 # 1-4
b::Bool # 5-8
# Pad 9-16
vf::v3f # 17 - 28
i::Int32 # 29 - 32
vi::v2i # 33 - 40
# Pad 41-48
bs::StaticBlockArray{25, Bool} # 49 - 448
m::@Mat(3, 2, Float64) # 449 - 496
# Struct alignment: 16
end
# For debugging, make a very clear to-string function for A.
# show() is tested and should not be changed.
function pretty_print(io::IO, a::A; indentation="")
println(io, "A(")
println(io, indentation, "\tf = ", a.f)
println(io, indentation, "\tb = ", a.b)
println(io, indentation, "\tvf = ", a.vf)
println(io, indentation, "\ti = ", a.i)
println(io, indentation, "\tvi = ", a.vi)
println(io, indentation, "\tbs = ...")
println(io, indentation, "\tm = ", a.m)
print(io, indentation, ")")
end
# Test struct A:
@bp_test_no_allocations(block_byte_size(A),
496,
"Struct 'A' in std140 layout is ", block_byte_size(A), " bytes")
@bp_test_no_allocations(block_alignment(A), 16)
@bp_test_no_allocations(block_padding_size(A), 16, "Struct 'A' in std140 layout")
function check_A_field(name::Symbol, type::Type, first_byte::Int)
@bp_test_no_allocations(type <: block_property_type(A, Val(name)), true,
"Type of A's field '$name' should be $type but was $(block_property_type(A, Val(name)))")
@bp_test_no_allocations(BplusApp.GL.block_property_first_byte(A, Val(name)), first_byte,
"First byte of A's field '$name'")
end
check_A_field(:f, Float32, 1)
check_A_field(:b, Bool, 5)
check_A_field(:vf, v3f, 17)
check_A_field(:i, Int32, 29)
check_A_field(:vi, v2i, 33)
check_A_field(:bs, StaticBlockArray{25, Bool, BplusApp.GL.OglBlock_std140}, 49)
check_A_field(:m, @Mat(3, 2, Float64), 449)
@bp_test_no_allocations(propertynames(A), (:f, :b, :vf, :i, :vi, :bs, :m))
@bp_test_no_allocations(block_property_types(A), (Float32, Bool, v3f, Int32, v2i, StaticBlockArray{25, Bool}, @Mat(3, 2, Float64)))
const A1_ARRAY = [(i%3)==0 for i in 1:25]
a1_args() = (@f32(1.4), true, v3f(4.4, 5.5, 6.6), 4, v2i(-3, -200),
A1_ARRAY,
@Mat(3, 2, Float64)(1, 2, 3, 4, 5, 6))
make_a_1() = A(a1_args()...)
@bp_check(make_a_1() isa A{Vector{UInt8}})
@bp_test_no_allocations(getproperty.(Ref(make_a_1()), propertynames(A)),
a1_args())
let sprinted = sprint(show, make_a_1()),
sprinted_args = sprint.(Ref(show), a1_args())
@bp_check(sprinted == "A($(join(sprinted_args, ", ")))",
"Actual value: ", sprinted, "\n")
end
# This struct has only 3 floats, so it should have 12 bytes (padded to 16) and 16-byte alignment.
@std140 struct B
f1::Float32
f2::Float32
f3::Float32
end
@bp_test_no_allocations(block_byte_size(B), 16, "@std140 struct B")
@bp_test_no_allocations(block_padding_size(B), 4, "@std140 struct B")
@bp_test_no_allocations(block_alignment(B), 16, "@std140 struct B")
function check_B_field(name::Symbol, type::Type, first_byte::Int)
@bp_test_no_allocations(block_property_type(B, Val(name)), type, "Type of B's field '$name'")
@bp_test_no_allocations(BplusApp.GL.block_property_first_byte(B, Val(name)), first_byte,
"First byte of B's field '$name'")
end
check_B_field(:f1, Float32, 1)
check_B_field(:f2, Float32, 5)
check_B_field(:f3, Float32, 9)
@bp_test_no_allocations(propertynames(B), (:f1, :f2, :f3))
@bp_test_no_allocations(block_property_types(B), (Float32, Float32, Float32))
const TEST_B_ARGS = Float32.((1, 2, 3))
const TEST_B = B(1, 2, 3)
@bp_check(TEST_B isa B{Vector{UInt8}})
@bp_test_no_allocations(getproperty.(Ref(TEST_B), propertynames(B)),
TEST_B_ARGS)
let sprinted = sprint(show, TEST_B),
sprinted_args = sprint.(Ref(show), TEST_B_ARGS)
@bp_check(sprinted == "B($(join(sprinted_args, ", ")))",
"Actual value: ", sprinted, "\n")
end
# C tests nested structs and some other types.
@std140 struct C
b::B # 1-16
as::StaticBlockArray{3, A} # 17 - 1504
f::Float32 # 1505 - 1508
# Pad 12 bytes, 1509 - 1520
bs::StaticBlockArray{500, B} # 1521 - 9520
a::A # 9521 - 10016
m64::@Mat(4, 3, Float64) # v3d, size 24, alignment 32
# Total size 128
# 10017 - 10144
m32s::StaticBlockArray{11, @Mat(2, 4, Float32)} # v4f, size 16, alignment 16
# Total size 22*16=352
# 10145 - 10496
# Struct alignment: 32
end
@bp_test_no_allocations(block_byte_size(C), 10496)
@bp_test_no_allocations(block_padding_size(C), 12)
@bp_test_no_allocations(block_alignment(C), 32)
function check_C_field(name::Symbol, type::Type, first_byte::Int)
@bp_test_no_allocations(type <: block_property_type(C, Val(name)), true,
"Type of C's field '$name' should be $type but was $(block_property_type(C, Val(name)))")
@bp_test_no_allocations(BplusApp.GL.block_property_first_byte(C, Val(name)), first_byte,
"First byte of C's field '$name'")
end
check_C_field(:b, B, 1)
check_C_field(:as, StaticBlockArray{3, A, BplusApp.GL.OglBlock_std140}, 17)
check_C_field(:f, Float32, 1505)
check_C_field(:bs, StaticBlockArray{500, B, BplusApp.GL.OglBlock_std140}, 1521)
check_C_field(:a, A, 9521)
check_C_field(:m64, dmat4x3, 10017)
check_C_field(:m32s, StaticBlockArray{11, fmat2x4, BplusApp.GL.OglBlock_std140}, 10145)
@bp_test_no_allocations(propertynames(C), (:b, :as, :f, :bs, :a, :m64, :m32s))
@bp_test_no_allocations(block_property_types(C), (B, StaticBlockArray{3, A}, Float32, StaticBlockArray{500, B}, A, dmat4x3, StaticBlockArray{11, fmat2x4}))
const TEST_C_ARGS = (
B(3, 4, 5),
[A(
i*0.5f0,
(i%5)==0,
v3f(i/2.0f0, i*30.0f0, -i),
-i*10,
v2i(i, i+1),
[((j*i)%4)==0 for j in 1:25],
dmat3x2(i-1, i-2, i-3, i-4, i-5, i-6)
) for i in 1:3],
20.02f0,
[B(i * -3.4, i, i + 7.53) for i in 1:500],
A(
23.231f0,
false,
v3f(10, 22, 13),
111111,
v2u(899, 888),
[((i%10) == 1) for i in 1:25],
dmat3x2(
81, 82, 83,
944, 05, 96
)
),
dmat4x3(
111, 112, 113, 114,
222, 223, 224, 225,
335, 366, 454, 666
),
[fmat2x4(i-10, i-100, i-1000, i-10000, i+11, i+111, i+1111, i+11111) for i in 1:11]
)
const TEST_C = C(TEST_C_ARGS...)
@bp_check(TEST_C isa C{Vector{UInt8}})
for (f, T, expected, actual) in zip(propertynames(C), block_property_types(C), TEST_C_ARGS, getproperty.(Ref(TEST_C), propertynames(C)))
@bp_check(expected == actual,
"C.", f, "::", T, " should be:\n", expected, "\n\n but is\n", actual)
end
@bp_test_no_allocations(getproperty.(Ref(TEST_C), propertynames(C)),
TEST_C_ARGS)
# Testing show() on a struct this big is impractical.
# Test the generated GLSL code and that the layout matches up with OpenGL,
# by writing a compute shader that reads/writes the data.
function compare_blocks(block_expected::T, block_actual::T, T_name) where {T<:AbstractOglBlock}
for f in propertynames(T)
expected = getproperty(block_expected, f)
actual = getproperty(block_actual, f)
@bp_check(typeof(expected) == typeof(actual),
T_name, ".", f, ": Type: ", typeof(expected), " vs ", typeof(actual))
if (expected isa AbstractArray) && !isa(expected, Vec)
@bp_check(length(expected) == length(actual),
T_name, ".", f, ": Count: ", length(expected), " vs ", length(actual))
for (i, el_expected, el_actual) in zip(1:length(expected), expected, actual)
@bp_check(el_expected == el_actual,
T_name, ".", f, "[", i, "]: ",
el_expected, " vs ", el_actual)
end
else
@bp_check(expected == actual,
T_name, ".", f, ": ", expected, " vs ", actual)
end
end
end
function run_block_compute_test(test_value::Union{AbstractOglBlock, BlockArray},
type_name, shader_src)
BlockType = block_simple_type(typeof(test_value))
gpu_in = Buffer(true, test_value)
gpu_out = Buffer(true, BlockType)
set_uniform_block(gpu_in, 1)
set_storage_block(gpu_out, 2)
shader = BplusApp.GL.bp_glsl_str(shader_src)#, debug_out = stderr)
dispatch_compute_groups(shader, one(v3i))
gl_catch_up_before(MemoryActions.buffer_download_or_upload)
cpu_expected = test_value
cpu_actual = get_buffer_data(gpu_out, BlockType)
compare_blocks(cpu_expected, cpu_actual, type_name)
@bp_test_no_allocations(cpu_expected, cpu_actual)
end
bp_gl_context( v2i(300, 300), "std140 test with compute shader";
vsync=VsyncModes.on,
debug_mode=true
) do context::Context
# Test B, the simplest struct, first.
# Test C, the most complex struct, last.
#TODO: Test BlockArray{A}, BlockArray{B}, and BlockArray{C} as well
#TODO: Test passing true for the 'recommend_storage_on_cpu' flag
run_block_compute_test(TEST_B, :B, """
#START_COMPUTE
layout(local_size_x = 1) in;
layout(std140, binding = 0) uniform Bin {
$(glsl_decl(B))
} u_in;
layout(std140, binding = 1) buffer Bout {
$(glsl_decl(B))
} u_out;
void main() {
$((
"u_out.$f = u_in.$f;"
for f in propertynames(B)
)...)
}
""")
run_block_compute_test(make_a_1(), :A, """
#START_COMPUTE
layout(local_size_x = 1) in;
layout(std140, binding = 0) uniform Ain {
$(glsl_decl(A))
} u_in;
layout(std140, binding = 1) buffer Aout {
$(glsl_decl(A))
} u_out;
void main() {
$((
"u_out.$f = u_in.$f;"
for f in propertynames(A)
)...)
}
""")
run_block_compute_test(TEST_C, :C, """
#START_COMPUTE
layout(local_size_x = 1) in;
struct A {
$(glsl_decl(A))
};
struct B {
$(glsl_decl(B))
};
layout(std140, binding = 0) uniform Cin {
$(glsl_decl(C))
} u_in;
layout(std140, binding = 1) buffer Cout {
$(glsl_decl(C))
} u_out;
void main() {
$((
"u_out.$f = u_in.$f;"
for f in propertynames(C)
)...)
}
""")
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | code | 10591 | # BplusApp.GL.BUFFER_LAYOUT_MACRO_DEBUG_STREAM = stdout
@std430 struct A
f::Float32 # 1-4
b::Bool # 5-8
# Pad 9-16
vf::v3f # 17 - 28
i::Int32 # 29 - 32
vi::v2i # 33 - 40
bs::StaticBlockArray{25, Bool} # 41 - 140
# Pad 141-144
m::@Mat(3, 2, Float64) # 145 - 192
# Struct alignment: 16
end
# For debugging, make a very clear to-string function for A.
# show() is tested and should not be changed.
function pretty_print(io::IO, a::A; indentation="")
println(io, "A(")
println(io, indentation, "\tf = ", a.f)
println(io, indentation, "\tb = ", a.b)
println(io, indentation, "\tvf = ", a.vf)
println(io, indentation, "\ti = ", a.i)
println(io, indentation, "\tvi = ", a.vi)
println(io, indentation, "\tbs = ...")
println(io, indentation, "\tm = ", a.m)
print(io, indentation, ")")
end
# Test struct A:
@bp_test_no_allocations(block_alignment(A), 16)
@bp_test_no_allocations(block_byte_size(A), 192)
@bp_test_no_allocations(block_padding_size(A), 12)
function check_A_field(name::Symbol, type::Type, first_byte::Int)
@bp_test_no_allocations(type <: block_property_type(A, Val(name)), true,
"Type of A's field '$name' should be $type but was $(block_property_type(A, Val(name)))")
@bp_test_no_allocations(BplusApp.GL.block_property_first_byte(A, Val(name)), first_byte,
"First byte of A's field '$name'")
end
check_A_field(:f, Float32, 1)
check_A_field(:b, Bool, 5)
check_A_field(:vf, v3f, 17)
check_A_field(:i, Int32, 29)
check_A_field(:vi, v2i, 33)
check_A_field(:bs, StaticBlockArray{25, Bool, BplusApp.GL.OglBlock_std430}, 41)
check_A_field(:m, @Mat(3, 2, Float64), 145)
@bp_test_no_allocations(propertynames(A), (:f, :b, :vf, :i, :vi, :bs, :m))
@bp_test_no_allocations(block_property_types(A), (Float32, Bool, v3f, Int32, v2i, StaticBlockArray{25, Bool}, @Mat(3, 2, Float64)))
const A1_ARRAY = [(i%3)==0 for i in 1:25]
a1_args() = (@f32(1.4), true, v3f(4.4, 5.5, 6.6), 4, v2i(-3, -200),
A1_ARRAY,
@Mat(3, 2, Float64)(1, 2, 3, 4, 5, 6))
make_a_1() = A(a1_args()...)
@bp_check(make_a_1() isa A{Vector{UInt8}})
@bp_test_no_allocations(getproperty.(Ref(make_a_1()), propertynames(A)),
a1_args())
let sprinted = sprint(show, make_a_1()),
sprinted_args = sprint.(Ref(show), a1_args())
@bp_check(sprinted == "A($(join(sprinted_args, ", ")))",
"Actual value: ", sprinted, "\n")
end
# This struct has only 3 floats, so it should have 12 bytes and 4-byte alignment.
@std430 struct B
f1::Float32
f2::Float32
f3::Float32
end
@bp_test_no_allocations(block_byte_size(B), 12)
@bp_test_no_allocations(block_padding_size(B), 0)
@bp_test_no_allocations(block_alignment(B), 4)
function check_B_field(name::Symbol, type::Type, first_byte::Int)
@bp_test_no_allocations(block_property_type(B, Val(name)), type, "Type of B's field '$name'")
@bp_test_no_allocations(BplusApp.GL.block_property_first_byte(B, Val(name)), first_byte,
"First byte of B's field '$name'")
end
check_B_field(:f1, Float32, 1)
check_B_field(:f2, Float32, 5)
check_B_field(:f3, Float32, 9)
@bp_test_no_allocations(propertynames(B), (:f1, :f2, :f3))
@bp_test_no_allocations(block_property_types(B), (Float32, Float32, Float32))
const TEST_B_ARGS = Float32.((1, 2, 3))
const TEST_B = B(1, 2, 3)
@bp_check(TEST_B isa B{Vector{UInt8}})
@bp_test_no_allocations(getproperty.(Ref(TEST_B), propertynames(B)),
TEST_B_ARGS)
let sprinted = sprint(show, TEST_B),
sprinted_args = sprint.(Ref(show), TEST_B_ARGS)
@bp_check(sprinted == "B($(join(sprinted_args, ", ")))",
"Actual value: ", sprinted, "\n")
end
# C tests nested structs and some other types.
@std430 struct C
b::B # 1-12
# Pad 4, to 13 - 16
as::StaticBlockArray{3, A} # 17 - 592
f::Float32 # 593 - 596
bs::StaticBlockArray{500, B} # 597 - 6596
# Pad 12, to 6597-6608
a::A # 6609 - 6800
# Pad 16, to 6801 - 6816
m64::@Mat(4, 3, Float64) # v3d, size 24, alignment 32
# Total size 128
# 6817 - 6944
m32s::StaticBlockArray{11, @Mat(2, 4, Float32)} # v4f, size 16, alignment 16
# Total size 22*16=352
# 6945 - 7296
# Struct alignment: 32
end
@bp_test_no_allocations(block_alignment(C), 32)
@bp_test_no_allocations(block_padding_size(C), 32)
@bp_test_no_allocations(block_byte_size(C), 7296)
function check_C_field(name::Symbol, type::Type, first_byte::Int)
@bp_test_no_allocations(type <: block_property_type(C, Val(name)), true,
"Type of C's field '$name' should be $type but was $(block_property_type(C, Val(name)))")
@bp_test_no_allocations(BplusApp.GL.block_property_first_byte(C, Val(name)), first_byte,
"First byte of C's field '$name'")
end
check_C_field(:b, B, 1)
check_C_field(:as, StaticBlockArray{3, A, BplusApp.GL.OglBlock_std430}, 17)
check_C_field(:f, Float32, 593)
check_C_field(:bs, StaticBlockArray{500, B, BplusApp.GL.OglBlock_std430}, 597)
check_C_field(:a, A, 6609)
check_C_field(:m64, dmat4x3, 6817)
check_C_field(:m32s, StaticBlockArray{11, fmat2x4, BplusApp.GL.OglBlock_std430}, 6945)
@bp_test_no_allocations(propertynames(C), (:b, :as, :f, :bs, :a, :m64, :m32s))
@bp_test_no_allocations(block_property_types(C), (B, StaticBlockArray{3, A}, Float32, StaticBlockArray{500, B}, A, dmat4x3, StaticBlockArray{11, fmat2x4}))
const TEST_C_ARGS = (
B(3, 4, 5),
[A(
i*0.5f0,
(i%5)==0,
v3f(i/2.0f0, i*30.0f0, -i),
-i*10,
v2i(i, i+1),
[((j*i)%4)==0 for j in 1:25],
dmat3x2(i-1, i-2, i-3, i-4, i-5, i-6)
) for i in 1:3],
20.02f0,
[B(i * -3.4, i, i + 7.53) for i in 1:500],
A(
23.231f0,
false,
v3f(10, 22, 13),
111111,
v2u(899, 888),
[((i%10) == 1) for i in 1:25],
dmat3x2(
81, 82, 83,
944, 05, 96
)
),
dmat4x3(
111, 112, 113, 114,
222, 223, 224, 225,
335, 366, 454, 666
),
[fmat2x4(i-10, i-100, i-1000, i-10000, i+11, i+111, i+1111, i+11111) for i in 1:11]
)
const TEST_C = C(TEST_C_ARGS...)
@bp_check(TEST_C isa C{Vector{UInt8}})
for (f, T, expected, actual) in zip(propertynames(C), block_property_types(C), TEST_C_ARGS, getproperty.(Ref(TEST_C), propertynames(C)))
@bp_check(expected == actual,
"C.", f, "::", T, " should be:\n", expected, "\n\n but is\n", actual)
end
@bp_test_no_allocations(getproperty.(Ref(TEST_C), propertynames(C)),
TEST_C_ARGS)
# Testing show() on a struct this big is impractical.
# Test the generated GLSL code and that the layout matches up with OpenGL,
# by writing a compute shader that reads/writes the data.
function compare_blocks(block_expected::T, block_actual::T, T_name) where {T<:AbstractOglBlock}
for f in propertynames(T)
expected = getproperty(block_expected, f)
actual = getproperty(block_actual, f)
@bp_check(typeof(expected) == typeof(actual),
T_name, ".", f, ": Type: ", typeof(expected), " vs ", typeof(actual))
if (expected isa AbstractArray) && !isa(expected, Vec)
@bp_check(length(expected) == length(actual),
T_name, ".", f, ": Count: ", length(expected), " vs ", length(actual))
for (i, el_expected, el_actual) in zip(1:length(expected), expected, actual)
@bp_check(el_expected == el_actual,
T_name, ".", f, "[", i, "]: ",
el_expected, " vs ", el_actual)
end
else
@bp_check(expected == actual,
T_name, ".", f, ": ", expected, " vs ", actual)
end
end
end
function run_block_compute_test(test_value::Union{AbstractOglBlock, BlockArray},
type_name, shader_src)
BlockType = block_simple_type(typeof(test_value))
gpu_in = Buffer(true, test_value)
gpu_out = Buffer(true, BlockType)
set_storage_block(gpu_in, 1)
set_storage_block(gpu_out, 2)
shader = BplusApp.GL.bp_glsl_str(shader_src)#, debug_out = stderr)
dispatch_compute_groups(shader, one(v3i))
gl_catch_up_before(MemoryActions.buffer_download_or_upload)
cpu_expected = test_value
cpu_actual = get_buffer_data(gpu_out, BlockType)
compare_blocks(cpu_expected, cpu_actual, type_name)
@bp_test_no_allocations(cpu_expected, cpu_actual)
end
bp_gl_context( v2i(300, 300), "std430 test with compute shader";
vsync=VsyncModes.on,
debug_mode=true
) do context::Context
# Test B, the simplest struct, first.
# Test C, the most complex struct, last.
#TODO: Test BlockArray{A}, BlockArray{B}, and BlockArray{C} as well
#TODO: Test passing true for the 'recommend_storage_on_cpu' flag
run_block_compute_test(TEST_B, :B, """
#START_COMPUTE
layout(local_size_x = 1) in;
layout(std430, binding = 0) buffer Bin {
$(glsl_decl(B))
} u_in;
layout(std430, binding = 1) buffer Bout {
$(glsl_decl(B))
} u_out;
void main() {
$((
"u_out.$f = u_in.$f;"
for f in propertynames(B)
)...)
}
""")
run_block_compute_test(make_a_1(), :A, """
#START_COMPUTE
layout(local_size_x = 1) in;
layout(std430, binding = 0) buffer Ain {
$(glsl_decl(A))
} u_in;
layout(std430, binding = 1) buffer Aout {
$(glsl_decl(A))
} u_out;
void main() {
$((
"u_out.$f = u_in.$f;"
for f in propertynames(A)
)...)
}
""")
run_block_compute_test(TEST_C, :C, """
#START_COMPUTE
layout(local_size_x = 1) in;
struct A {
$(glsl_decl(A))
};
struct B {
$(glsl_decl(B))
};
layout(std430, binding = 0) buffer Cin {
$(glsl_decl(C))
} u_in;
layout(std430, binding = 1) buffer Cout {
$(glsl_decl(C))
} u_out;
void main() {
$((
"u_out.$f = u_in.$f;"
for f in propertynames(C)
)...)
}
""")
end | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | docs | 1042 | # v0.2.1
* Fix numerous bugs within `GL`
* Cosmetic/debug-time improvements
* GUI helper functions:
* Add more flexible parameters
* Fix API bugs
* `service_Input_reset()` to reset the service to a blank slate
# v0.2.0
* Add GUI helpers:
* `gui_tab_views()`
* `gui_tab_item()`
* Add `convert_pixel()` to translate `ImageIO` data into B+ terms
* Fix bug when using `View` instead of `Texture` in CImGui/GuiService
* Allow getting the handle of a `View` with `get_ogl_handle(v)`
* **[Breaking]** Improve the getting and setting of Buffer data
* **[Breaking]** Completely rewrite `@std140` and `@std430`
* They must be mutable to avoid Julia JIT dying on crazy immutable types like `NTuple{16400, UInt8}`
* Now they are backed by a mutable byte array rather than an `NTuple` of bytes
* Nested structs and static-arrays are views of the outermost struct's byte array
# v0.1.1
* Made OpenGL extension loading more flexible.
* Allowed for Intel integrated GPU support by making shader_int64 optional!
# v0.1.0
Initial version | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | docs | 1347 | The graphics, input, and GUI packages for [B+](https://github.com/heyx3/B-plus). Refer to the main repo for documentation.
The modules contained here are:
* GL
* Input
* GUI
* ModernGL fork (see below for explanation)
If you only want this package, without the rest of B+, you can add `BplusApp` to your project and then do `using BplusApp; @using_bplus_app` to import all modules.
## ModernGL fork
This project keeps a fork of [ModernGL](https://github.com/JuliaGL/ModernGL.jl), called `ModernGLbp`, which adds ARB extensions and some UX improvements.
It is technically kept as a copy rather than a git submodule, because I don't know if Yggdrasil (Julia's package build system) can handle git submodules. However, `ModernGLbp` is also maintained as a true fork [here on Github](https://github.com/heyx3/ModernGL.jl), and if you're working on `BplusApp` you can quite easily treat this in-repo copy like a git submodule, with the following steps:
1. Clone the ModernGL fork somewhere else.
2. Copy *.git/* from that cloned repo, into this repo at *BplusApp/src/ModernGL_fork/*
This project's *.gitignore* file is configured to ignore the inner *.git/* folder.
The forked code will belong to both repos, BplusApp and ModernGL.
`cd` into *BplusApp/src/ModernGL_fork/* to work within ModernGL, and move outside there to work within BplusApp. | BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c6b68d12ed01e3c05e9cccaa2cee72d6653b379 | docs | 3158 | **Forked** from the official repo, for use in B+. Mainly done to get ARB extensions, but also to improve the internal macros and `GLENUM` utility.
# ModernGL
OpenGL bindings for OpenGL 3.0 through 4.6. As OpenGL 3.0 has a lot of overlaps with OpenGL 2.1, OpenGL 2.1 is partly supported as well.
The philosophy is to keep this library strictly a low-level wrapper, so you won't find any error handling (besides for the function loading itself) or abstractions in this package.
### Debugging
You can rebuild ModernGL to include debug error checks:
```Julia
ENV["MODERNGL_DEBUGGING"] = "true"; Pkg.build("ModernGL")
# or to get back the default behaviour:
ENV["MODERNGL_DEBUGGING"] = "false"; Pkg.build("ModernGL")
```
OpenGL constants are wrapped as enums, which allows you to print the name of a constant like this:
GLENUM(x::GLenum).name
This works pretty well, but keep in mind some constants actually have the same value, and only one name will be stored for each value. This leads to counterintuitive behavior in some cases, such as `GLENUM(GL_SYNC_FLUSH_COMMANDS_BIT).name == :GL_TRUE`.
The behavior of GLENUM is manually overridden to return specific names for important constants, like `GL_TRUE` for 1 and `GL_FALSE` for 0. You can force other names using the macro `ModernGL.@custom_glenum [value] [name]`.
### Installation notes
There are no dependencies, besides the graphic driver. If you have any problems, you should consider updating the driver first.
An OpenGL context is needed for OpenGL, which is created with [GLFW.jl](https://github.com/JuliaGL/GLFW.jl).
Other OpenGL abstraction packages, which make it easier to get started with OpenGL, include:
- [GLAbstraction](https://github.com/JuliaGL/GLAbstraction.jl) is a library, that offers Julian wrappers around often used OpenGL functions and types.
### Known problems
There might be a few problems with older platforms and video cards, since it's not heavily tested on them.
### Some more details
getProcAddress can be changed like this:
```Julia
using ModernGL
function ModernGL.getprocaddress(name::ASCIIString)
# for example change it to GLUT
glutGetProcAddress(name)
end
```
If the OpenGL driver doesn't support any of the functions that you call, ModernGL should detect this and throw an error.
Same happens, if you call a function before initializing an OpenGL context.
This behaviour is not guaranteed though, as for example linux platforms always returns valid pointers, even if the function is not implemented by the driver.
It seems, that there is actually no good way of testing if a function is supported on linux.
# Credit
Credits go certainly to the OpenGL.jl ([rennis250](https://github.com/rennis250) && [o-jasper](https://github.com/o-jasper)) package, where I have all the OpenGL definitions from.
Special thanks to rennis250 for all the support! :)
Also, I have to thank for the constructive discussion on Julia-Users, where I got a good solution for the function pointer loading (final solution was from [vtjnash](https://github.com/vtjnash) and got replaced by [aaalexandrov's](https://github.com/aaalexandrov/) solution which doubled the speed).
| BplusApp | https://github.com/heyx3/BplusApp.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 543 | using Documenter, ArgParse
CIbuild = get(ENV, "CI", nothing) == "true"
makedocs(
modules = [ArgParse],
format = Documenter.HTML(prettyurls = CIbuild),
sitename = "ArgParse.jl",
pages = Any[
"Home" => "index.md",
"Manual" => [
"parse_args.md",
"settings.md",
"arg_table.md",
"import.md",
"conflicts.md",
"custom.md",
"details.md"
]
]
)
deploydocs(
repo = "github.com/carlobaldassi/ArgParse.jl.git",
)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 682 | # example 1: minimal options/arguments, auto-generated help/version
using ArgParse
function main(args)
# initialize the settings (the description is for the help screen)
s = ArgParseSettings(description = "Example 1 for argparse.jl: minimal usage.")
@add_arg_table! s begin
"--opt1" # an option (will take an argument)
"--opt2", "-o" # another option, with short form
"arg1" # a positional argument
end
parsed_args = parse_args(s) # the result is a Dict{String,Any}
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 774 | # example 2: add some flags and the help lines for options
using ArgParse
function main(args)
s = ArgParseSettings("Example 2 for argparse.jl: " * # description
"flags, options help, " *
"required arguments.")
@add_arg_table! s begin
"--opt1"
help = "an option" # used by the help screen
"--opt2", "-o"
action = :store_true # this makes it a flag
help = "a flag"
"arg1"
help = "an argument"
required = true # makes the argument mandatory
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1910 | # example 3: version information, default values, options with
# types and variable number of arguments
using ArgParse
function main(args)
s = ArgParseSettings("Example 3 for argparse.jl: " *
"version info, default values, " *
"options with types, variable " *
"number of arguments.",
version = "Version 1.0", # version info
add_version = true) # audo-add version option
@add_arg_table! s begin
"--opt1"
nargs = '?' # '?' means optional argument
arg_type = Int # only Int arguments allowed
default = 0 # this is used when the option is not passed
constant = 1 # this is used if --opt1 is paseed with no argument
help = "an option"
"--karma", "-k"
action = :count_invocations # increase a counter each time the option is given
help = "increase karma"
"arg1"
nargs = 2 # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once"
required = true
"arg2"
nargs = '*' # eats up as many arguments as possible before an option
default = Any["no_arg_given"] # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
help = "second argument, eats up " *
"as many items as possible " *
"before an option"
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 3241 | # example 4: dest_name, metavar, range_tester, alternative
# actions, epilog with examples
using ArgParse
function main(args)
s = ArgParseSettings("Example 4 for argparse.jl: " *
"more tweaking of the arg fields: " *
"dest_name, metvar, range_tested, " *
"alternative actions.")
@add_arg_table! s begin
"--opt1"
action = :append_const # appends 'constant' to 'dest_name'
arg_type = String # the only utility of this is restricting the dest array type
constant = "O1"
dest_name = "O_stack" # this changes the destination
help = "append O1"
"--opt2"
action = :append_const
arg_type = String
constant = "O2"
dest_name = "O_stack" # same dest_name as opt1, different constant
help = "append O2"
"-k"
action = :store_const # stores constant if given, default otherwise
default = 0
constant = 42
help = "provide the answer"
"--awkward-option"
nargs = '+' # eats up as many argument as found (at least 1)
action = :append_arg # argument chunks are appended when the option is
# called repeatedly
arg_type = String
dest_name = "awk"
range_tester = (x->x=="X"||x=="Y") # each argument must be either "X" or "Y"
metavar = "XY"
help = "either X or Y; all XY's are " *
"stored in chunks"
end
# we add an epilog and provide usage examples, also demonstrating
# how to have some control on the formatting: we use additional '\n' at
# the end of lines to force newlines, and '\ua0' to put non-breakable spaces.
# Non-breakable spaces are not removed and are not used to split lines; they
# will be substituted with spaces in the final output.
s.epilog = """
examples:\n
\n
\ua0\ua0$(basename(Base.source_path())) --opt1 --opt2 --opt2 -k\n
\n
\ua0\ua0$(basename(Base.source_path())) --awkward X X --opt1 --awkward X Y X --opt2\n
\n
The first form takes option 1 once, than option 2, then activates the answer flag,
while the second form takes only option 1 and then 2, and intersperses them with "X\ua0X"
and "X\ua0Y\ua0X" groups, for no particular reason.
"""
# the epilog section will be displayed like this in the help screen:
#
# examples:
#
# argparse_example4.jl --opt1 --opt2 --opt2 -kkkkk
#
# argparse_example4.jl --awkward X X --opt1 --awkward X Y X --opt2
#
# The first form takes option 1 once, than option 2, then activates the
# answer flag, while the second form takes only option 1 and then 2, and
# intersperses them with "X X" and "X Y X" groups, for no particular
# reason.
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1994 | # example 5: manual help/version, import another parser
using ArgParse
function main(args)
s0 = ArgParseSettings() # a "parent" structure e.g. one with some useful set of rules
# which we want to extend
# So we just add a simple table
@add_arg_table! s0 begin
"--parent-flag", "-o"
action=>"store_true"
help=>"parent flag"
"--flag"
action=>"store_true"
help=>"another parent flag"
"parent-argument"
help = "parent argument"
end
s = ArgParseSettings("Example 5 for argparse.jl: " *
"importing another parser, " *
"manual help and version.",
add_help = false, # disable auto-add of --help option
version = "Version 1.0") # we set the version info, but --version won't be added
import_settings!(s, s0) # now s has all of s0 arguments (except help/version)
s.error_on_conflict = false # do not error-out when trying to override an option
@add_arg_table! s begin
"-o" # this will partially override s0's --parent-flag
action = :store_true
help = "child flag"
"--flag" # this will fully override s0's --flag
action = :store_true
help = "another child flag"
"-?", "--HELP", "--¡ḧëļṕ" # (almost) all characters allowed
action = :show_help # will invoke the help generator
help = "this will help you"
"-v", "--VERSION"
action = :show_version # will show version information
help = "show version information" *
"and exit"
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 2688 | # example 6: commands & subtables
using ArgParse
function main(args)
s = ArgParseSettings("Example 6 for argparse.jl: " *
"commands and their associated sub-tables.")
@add_arg_table! s begin
"run"
action = :command # adds a command which will be read from an argument
help = "start running mode"
"jump", "ju", "J" # another one, this one has two aliases
action = :command
help = "start jumping mode"
end
@add_arg_table! s["run"] begin # add command arg_table: same as usual, but invoked on s["cmd"]
"--speed"
arg_type = Float64
default = 10.
help = "running speed, in Å/month"
end
s["jump"].description = "Jump mode for example 6" # this is how settings are tweaked
# for commands
s["jump"].commands_are_required = false # this makes the sub-commands optional
s["jump"].autofix_names = true # this uses dashes in long options, underscores
# in auto-generated dest_names
@add_arg_table! s["jump"] begin
"--higher"
action = :store_true
help = "enhance jumping"
"--somersault"
action = :command # this adds a sub-command (passed via an option instead)
dest_name = "som" # flag commands can set a dest_name
help = "somersault jumping mode"
"--clap-feet" # dest_name will be "clap_feet" (see the "autofix_names" settings")
action = :command
help = "clap feet jumping mode"
end
s["jump"]["som"].description = "Somersault jump " * # this is how settings are tweaked
"mode for example 6" # for sub-commands
s["jump"]["clap_feet"].description = "Clap-feet jump " * # notice the underscore in the name
"mode for example 6"
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
println()
# parsed_args will have a special field "%COMMAND%"
# which will hold the executed command name (or 'nothing')
println("Command: ", parsed_args["%COMMAND%"])
# thus, the command args are in parsed_args[parsed_args["%COMMAND%]]
println("Parsed command args:")
command_args = parsed_args[parsed_args["%COMMAND%"]]
for (key,val) in command_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 2223 | # example 7: argument groups
using ArgParse
function main(args)
s = ArgParseSettings("Example 7 for argparse.jl: " *
"argument groups.")
add_arg_group!(s, "stack options") # add a group and sets it as the default
@add_arg_table! s begin # all options (and arguments) in this table
# will be assigned to the newly added group
"--opt1"
action = :append_const
arg_type = String
constant = "O1"
dest_name = "O_stack"
help = "append O1 to the stack"
"--opt2"
action = :append_const
arg_type = String
constant = "O2"
dest_name = "O_stack"
help = "append O2 to the stack"
end
add_arg_group!(s, "weird options", "weird") # another group, this time with a tag which allows
# to refer to it
set_default_arg_group!(s, "weird") # set the default group (useless here, since we just added it)
@add_arg_table! s begin
"--awkward-option"
nargs = '+'
action = :append_arg
dest_name = "awk"
arg_type = String
range_tester = (x->x=="X"||x=="Y")
metavar = "XY"
help = "either X or Y; all XY's are " *
"stored in chunks"
end
set_default_arg_group!(s) # reset the default arg group (which means arguments
# are automatically assigned to commands/options/pos.args
# groups)
@add_arg_table! s begin
"-k"
action = :store_const
default = 0
constant = 42
help = "provide the answer"
"--şİłłÿ"
action = :store_true
help = "an option with a silly name"
group = "weird" # this overrides the default group: this option
# will be grouped together with --awkward-option
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1475 | # example 8: mutually exculsive and required groups
using ArgParse
function main(args)
s = ArgParseSettings("Example 8 for argparse.jl: " *
"mutually exclusive and requiredd groups.")
add_arg_group!(s, "Mutually exclusive options", exclusive=true)
@add_arg_table! s begin
"--maybe", "-M"
action = :store_true
help = "maybe..."
"--maybe-not", "-N"
action = :store_true
help = "maybe not..."
end
add_arg_group!(s, "Required mutually exclusive options", exclusive=true, required=true)
@add_arg_table! s begin
"--either", "-E"
action = :store_true
help = "choose the `either` option"
"--or", "-O"
action = :store_arg
arg_type = Int
help = "set the `or` option"
end
add_arg_group!(s, "Required arguments", required=true)
@add_arg_table! s begin
"--enhance", "-+"
action = :store_const
default = 0
constant = 42
help = "set the enhancement option"
"arg1"
nargs = 2 # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once"
end
parsed_args = parse_args(args, s)
println("Parsed args:")
for (key,val) in parsed_args
println(" $key => $(repr(val))")
end
end
main(ARGS)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1175 | """
ArgParse
This module allows the creation of user-friendly command-line interfaces to Julia programs:
the program defines which arguments, options and sub-commands it accepts, and the `ArgParse` module
does the actual parsing, issues errors when the input is invalid, and automatically generates help
and usage messages.
Users familiar with Python's `argparse` module will find many similarities, but some important
differences as well.
"""
module ArgParse
import TextWrap
if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@compiler_options"))
@eval Base.Experimental.@compiler_options compile=min optimize=0 infer=false
end
export
# types
ArgParseSettings,
ArgParseSettingsError,
ArgParseError,
# functions & macros
add_arg_table!,
@add_arg_table!,
add_arg_group!,
set_default_arg_group!,
import_settings!,
usage_string,
parse_args,
@project_version
import Base: show, getindex, setindex!, haskey
@nospecialize # use only declared type signatures, helps with compile time
include("common.jl")
include("settings.jl")
include("parsing.jl")
include("deprecated.jl")
end # module ArgParse
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1206 | ## Some common functions, constants, macros
# auxiliary functions/constants
found_a_bug() = error("you just found a bug in the ArgParse module, please report it.")
const nbspc = '\u00a0'
const nbsps = "$nbspc"
println_unnbsp(io::IO, args...) = println(io, map(s->replace(s, nbspc => ' '), args)...)
macro defaults(opts, ex)
@assert ex.head == :block
lines = filter(x->!(x isa LineNumberNode), ex.args)
@assert all(x->Meta.isexpr(x, :(=)), lines)
opts = esc(opts)
# Transform the opts array into a Dict
exret = :($opts = Dict{Symbol,Any}($opts))
# Initialize the checks
found = esc(gensym("found"))
exret = quote
$exret
$found = Dict{Symbol,Bool}(k => false for (k,v) in $opts)
end
for y in lines
sym = y.args[1]
qsym = Expr(:quote, sym)
exret = quote
$exret
if haskey($opts, $qsym)
$(esc(sym)) = $opts[$qsym]
$found[$qsym] = true
else
$(esc(y))
end
end
end
exret = quote
$exret
for (k,v) in $found
v || serror("unknown description field: $k")
end
end
exret
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1401 |
@deprecate add_arg_table add_arg_table!
@deprecate import_settings(settings, other) import_settings!(settings, other)
@deprecate import_settings(settings, other, ao) import_settings!(settings, other; args_only=ao)
@deprecate add_arg_group(args...; kw...) add_arg_group!(args...; kw...)
@deprecate set_default_arg_group set_default_arg_group!
# The Base.@deprecate macro doesn't work with macros
# Here's an attempt at mimicking most of what that does
# and deprecate @add_arg_table -> @add_arg_table!
using Base: JLOptions, CoreLogging
using Logging: @logmsg
function callframe(st, name)
found = false
for sf in st
sf == StackTraces.UNKNOWN && continue
if found && sf.func == Symbol("top-level scope")
return sf
end
sf.func == name && (found = true)
end
return StackTraces.UNKNOWN
end
export @add_arg_table
macro add_arg_table(s, x...)
opts = JLOptions()
msg = "`@add_arg_table` is deprecated, use `@add_arg_table!` instead"
opts.depwarn == 2 && throw(ErrorException(msg))
deplevel = opts.depwarn == 1 ? CoreLogging.Warn : CoreLogging.BelowMinLevel
st = stacktrace()
caller = callframe(st, Symbol("@add_arg_table"))
@logmsg(deplevel, msg,
_file = String(caller.file),
_line = caller.line,
_group = :depwarn,
maxlog = 1)
return _add_arg_table!(s, x...)
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 34269 | ## All types, functions and constants related to the actual process of
## parsing the arguments
# ArgParseError
struct ArgParseError <: Exception
text::AbstractString
end
argparse_error(x...) = throw(ArgParseError(string(x...)))
# parsing checks
function test_range(range_tester::Function, arg, name::AbstractString)
local rng_chk::Bool
try
rng_chk = range_tester(arg)
catch
rng_chk = false
end
rng_chk || argparse_error("out of range input for $name: $arg")
return
end
function test_exclusive_groups!(exc_groups::Dict{ArgParseGroup,AbstractString},
settings::ArgParseSettings,
f::ArgParseField,
name::AbstractString)
arg_group = get_group(f.group, f, settings)
if haskey(exc_groups, arg_group)
prev_id = exc_groups[arg_group]
if isempty(prev_id)
exc_groups[arg_group] = idstring(f)
elseif prev_id != idstring(f)
argparse_error("option $name not allowed with $prev_id")
end
end
return
end
function test_required_args(settings::ArgParseSettings, found_args::Set{AbstractString})
req_groups = Dict{ArgParseGroup,Bool}(g=>false for g in settings.args_groups if g.required)
fields = settings.args_table.fields
for f in fields
found = idstring(f) ∈ found_args
!is_cmd(f) && f.required && !found &&
argparse_error("required $(idstring(f)) was not provided")
found && (req_groups[get_group(f.group, f, settings)] = true)
end
for (g,found) in req_groups
found && continue
ids = String[idstring(f) for f in fields if get_group(f.group, f, settings) ≡ g]
argparse_error("one of these is required: " * join(ids, ", "))
end
return true
end
function check_settings_can_use_symbols(settings::ArgParseSettings)
args_table = settings.args_table
if !isempty(args_table.subsettings)
for f in args_table.fields
if f.dest_name == string(scmd_dest_name)
serror("the dest_name $scmd_dest_name cannot be used with the as_symbols option")
end
end
for subs in values(args_table.subsettings)
check_settings_can_use_symbols(subs)
end
end
settings.suppress_warnings && return true
for f in args_table.fields
if '-' in f.dest_name
@warn "dest_name=$(f.dest_name) contains a hyphen; use the autofix_names=true setting to have it converted to an underscore"
end
end
return true
end
# parsing aux functions
function parse_item_wrapper(::Type{T}, x::AbstractString) where {T}
local r::T
try
r = parse_item(T, x)
catch err
argparse_error("""
invalid argument: $x (conversion to type $T failed; you may need to overload
ArgParse.parse_item; the error was: $err)""")
end
return r
end
parse_item(::Type{Any}, x::AbstractString) = x
parse_item(::Type{T}, x::AbstractString) where {T<:Number} = parse(T, x)
parse_item(::Type{T}, x::AbstractString) where {T} = applicable(convert, T, x) ? convert(T, x) : T(x)
function parse_item_eval(::Type{T}, x::AbstractString) where {T}
local r::T
try
r = convert(T, eval(Meta.parse(x)))
catch err
argparse_error("""
invalid argument: $x (must evaluate or convert to type $T;
the error was: $err)""")
end
return r
end
const number_regex =
r"^[+-]? # optional sign
(
0x[0-9a-fA-F](_?[0-9a-fA-F])* | # hex
0o[0-7](_?[0-7])* | # oct
0b[01](_?[01])* | # bin
( # float mantissa
[0-9](_?[0-9])*(\.([0-9](_?[0-9])*)?)? | # start with digit
\.[0-9](_?[0-9])* # start with dot
)([eEf][-+]?[0-9]+)? # float optional exp
)
$"x
function looks_like_an_option(arg::AbstractString, settings::ArgParseSettings)
arg == "-" && return false
startswith(arg, "--") && return true
startswith(arg, '-') || return false
# begins with '-'
# check if it's a number:
occursin(number_regex, arg) || return true
# looks like a number; but is it overridden by an option?
d = arg[2:2]
for a in settings.args_table.fields, s in a.short_opt_name
s == d && return true
end
# it's a number
return false
end
function usage_string(settings::ArgParseSettings)
isempty(settings.usage) || return settings.usage
usage_pre = "usage: " * (isempty(settings.prog) ? "<PROGRAM>" : settings.prog)
lc_len_limit = settings.help_alignment_width
cmd_lst = String[]
pos_lst = String[]
opt_lst = String[]
exc_lst = Dict{String,Tuple{Bool,Vector{String}}}()
for f in settings.args_table.fields
arg_group = get_group(f.group, f, settings)
if arg_group.exclusive
(is_cmd(f) || is_arg(f)) && found_a_bug()
_, tgt_opt_lst = get!(exc_lst, arg_group.name, (arg_group.required, String[]))
else
tgt_opt_lst = opt_lst
end
if is_cmd(f)
if !isempty(f.short_opt_name)
idstr = "-" * f.short_opt_name[1]
elseif !isempty(f.long_opt_name)
idstr = "--" * f.long_opt_name[1]
else
idstr = f.metavar
end
push!(cmd_lst, idstr)
elseif is_arg(f)
bra_pre, bra_post = f.required ? ("","") : ("[","]")
if isa(f.nargs.desc, Int)
if f.metavar isa AbstractString
arg_str = join(repeat([f.metavar], f.nargs.desc), nbsps)
else
found_a_bug()
end
elseif f.nargs.desc == :A
arg_str = f.metavar
elseif f.nargs.desc == :?
found_a_bug()
elseif f.nargs.desc == :* || f.nargs.desc == :R || f.nargs.desc == :+
arg_str = f.metavar * "..."
else
found_a_bug()
end
push!(pos_lst, bra_pre * arg_str * bra_post)
else
bra_pre, bra_post = (f.required || arg_group.exclusive) ? ("","") : ("[","]")
if !isempty(f.short_opt_name)
opt_str1 = "-" * f.short_opt_name[1]
else
opt_str1 = "--" * f.long_opt_name[1]
end
if is_flag(f)
opt_str2 = ""
else
if f.nargs.desc isa Int
if f.metavar isa AbstractString
opt_str2 = string(ntuple(i->(nbsps * f.metavar), f.nargs.desc)...)
elseif f.metavar isa Vector
opt_str2 = string(ntuple(i->(nbsps * f.metavar[i]), f.nargs.desc)...)
else
found_a_bug()
end
elseif f.nargs.desc == :A
opt_str2 = nbsps * f.metavar
elseif f.nargs.desc == :?
opt_str2 = nbsps * "[" * f.metavar * "]"
elseif f.nargs.desc == :* || f.nargs.desc == :R
opt_str2 = nbsps * "[" * f.metavar * "...]"
elseif f.nargs.desc == :+
opt_str2 = nbsps * f.metavar * nbsps * "[" * f.metavar * "...]"
else
found_a_bug()
end
end
new_opt = bra_pre * opt_str1 * opt_str2 * bra_post
push!(tgt_opt_lst, new_opt)
end
end
excl_str = ""
for (req,lst) in values(exc_lst)
pre, post = req ? ("{","}") : ("[","]")
excl_str *= " " * pre * join(lst, " | ") * post
end
if isempty(opt_lst)
optl_str = ""
else
optl_str = " " * join(opt_lst, " ")
end
if isempty(pos_lst)
posl_str = ""
else
posl_str = " " * join(pos_lst, " ")
end
if isempty(cmd_lst)
cmdl_str = ""
else
bra_pre, bra_post = settings.commands_are_required ? ("{","}") : ("[","]")
cmdl_str = " " * bra_pre * join(cmd_lst, "|") * bra_post
end
usage_len = length(usage_pre) + 1
str_nonwrapped = usage_pre * excl_str * optl_str * posl_str * cmdl_str
str_wrapped = TextWrap.wrap(str_nonwrapped, break_long_words = false, break_on_hyphens = false,
subsequent_indent = min(usage_len, lc_len_limit),
width = settings.help_width)
out_str = replace(str_wrapped, nbspc => ' ')
return out_str
end
function string_compact(x...)
io = IOBuffer()
show(IOContext(io, :compact=>true), x...)
return String(take!(io))
end
function gen_help_text(arg::ArgParseField, settings::ArgParseSettings)
is_flag(arg) && return arg.help
pre = isempty(arg.help) ? "" : " "
type_str = ""
default_str = ""
const_str = ""
alias_str = ""
if !is_command_action(arg.action)
if arg.arg_type ≠ Any && !(arg.arg_type <: AbstractString)
type_str = pre * "(type: " * string_compact(arg.arg_type)
end
if arg.default ≢ nothing && !isequal(arg.default, [])
mid = isempty(type_str) ? " (" : ", "
default_str = mid * "default: " * string_compact(arg.default)
end
if arg.nargs.desc == :?
mid = isempty(type_str) && isempty(default_str) ? " (" : ", "
const_str = mid * "without arg: " * string_compact(arg.constant)
end
else
is_arg(arg) || found_a_bug()
if !isempty(arg.cmd_aliases)
alias_str = pre * "(aliases: " * join(arg.cmd_aliases, ", ")
end
end
post = all(isempty, (type_str, default_str, const_str, alias_str)) ? "" : ")"
return arg.help * type_str * default_str * const_str * alias_str * post
end
function print_group(io::IO, lst::Vector, desc::AbstractString, lc_usable_len::Int, lc_len::Int,
lmargin::AbstractString, rmargin::AbstractString, sindent::AbstractString,
width::Int)
isempty(lst) && return
println(io, desc, ":")
for l in lst
l1len = length(l[1])
if l1len ≤ lc_usable_len
rfill = " "^(lc_len - l1len)
ll_nonwrapped = l[1] * rfill * rmargin * l[2]
ll_wrapped = TextWrap.wrap(ll_nonwrapped, break_long_words = false, break_on_hyphens = false,
initial_indent = lmargin, subsequent_indent = sindent, width = width)
println_unnbsp(io, ll_wrapped)
else
println_unnbsp(io, lmargin, l[1])
l2_wrapped = TextWrap.wrap(l[2], break_long_words = false, break_on_hyphens = false,
initial_indent = sindent, subsequent_indent = sindent, width = width)
println_unnbsp(io, l2_wrapped)
end
end
println(io)
end
show_help(settings::ArgParseSettings; kw...) = show_help(stdout, settings; kw...)
function show_help(io::IO, settings::ArgParseSettings; exit_when_done = !isinteractive())
lc_len_limit = settings.help_alignment_width
lc_left_indent = 2
lc_right_margin = 2
lc_usable_len = lc_len_limit - lc_left_indent - lc_right_margin
max_lc_len = 0
usage_str = usage_string(settings)
group_lists = Dict{AbstractString,Vector{Any}}()
for ag in settings.args_groups
group_lists[ag.name] = Any[]
end
for f in settings.args_table.fields
dest_lst = group_lists[f.group]
if is_arg(f)
push!(dest_lst, Any[f.metavar, gen_help_text(f, settings)])
max_lc_len = max(max_lc_len, length(f.metavar))
else
opt_str1 = join([["-"*x for x in f.short_opt_name];
["--"*x for x in f.long_opt_name]],
", ")
if is_flag(f)
opt_str2 = ""
else
if f.nargs.desc isa Int
if f.metavar isa AbstractString
opt_str2 = string(ntuple(i->(nbsps * f.metavar), f.nargs.desc)...)
elseif isa(f.metavar, Vector)
opt_str2 = string(ntuple(i->(nbsps * f.metavar[i]), f.nargs.desc)...)
else
found_a_bug()
end
elseif f.nargs.desc == :A
opt_str2 = nbsps * f.metavar
elseif f.nargs.desc == :?
opt_str2 = nbsps * "[" * f.metavar * "]"
elseif f.nargs.desc == :* || f.nargs.desc == :R
opt_str2 = nbsps * "[" * f.metavar * "...]"
elseif f.nargs.desc == :+
opt_str2 = nbsps * f.metavar * nbsps * "[" * f.metavar * "...]"
else
found_a_bug()
end
end
new_opt = Any[opt_str1 * opt_str2, gen_help_text(f, settings)]
push!(dest_lst, new_opt)
max_lc_len = max(max_lc_len, length(new_opt[1]))
end
end
lc_len = min(lc_usable_len, max_lc_len)
lmargin = " "^lc_left_indent
rmargin = " "^lc_right_margin
sindent = lmargin * " "^lc_len * rmargin
println(io, usage_str)
println(io)
show_message(io, settings.description, settings.preformatted_description, settings.help_width)
for ag in settings.args_groups
print_group(io, group_lists[ag.name], ag.desc, lc_usable_len, lc_len,
lmargin, rmargin, sindent, settings.help_width)
end
show_message(io, settings.epilog, settings.preformatted_epilog, settings.help_width)
exit_when_done && exit(0)
return
end
function show_message(io::IO, message::AbstractString, preformatted::Bool, width::Int)
if !isempty(message)
if preformatted
print(io, message)
else
for l in split(message, "\n\n")
message_wrapped = TextWrap.wrap(l, break_long_words = false, break_on_hyphens = false, width = width)
println_unnbsp(io, message_wrapped)
end
end
println(io)
end
end
show_version(settings::ArgParseSettings; kw...) = show_version(stdout, settings; kw...)
function show_version(io::IO, settings::ArgParseSettings; exit_when_done = !isinteractive())
println(io, settings.version)
exit_when_done && exit(0)
return
end
has_cmd(settings::ArgParseSettings) = any(is_cmd, settings.args_table.fields)
# parse_args & friends
function default_handler(settings::ArgParseSettings, err, err_code::Int = 1)
isinteractive() ? debug_handler(settings, err) : cmdline_handler(settings, err, err_code)
end
function cmdline_handler(settings::ArgParseSettings, err, err_code::Int = 1)
println(stderr, err.text)
println(stderr, usage_string(settings))
exit(err_code)
end
function debug_handler(settings::ArgParseSettings, err)
rethrow(err)
end
parse_args(settings::ArgParseSettings; kw...) = parse_args(ARGS, settings; kw...)
"""
parse_args([args,] settings; as_symbols::Bool = false)
This is the central function of the `ArgParse` module. It takes a `Vector` of arguments and an
[`ArgParseSettings`](@ref) object, and returns a `Dict{String,Any}`. If `args` is not provided, the
global variable `ARGS` will be used.
When the keyword argument `as_symbols` is `true`, the function will return a `Dict{Symbol,Any}`
instead.
The returned `Dict` keys are defined (possibly implicitly) in `settings`, and their associated
values are parsed from `args`. Special keys are used for more advanced purposes; at the moment, one
such key exists: `%COMMAND%` (`_COMMAND_` when using `as_symbols=true`; see the [Commands](@ref)
section).
Arguments are parsed in sequence and matched against the argument table in `settings` to determine
whether they are long options, short options, option arguments or positional arguments:
* long options begin with a double dash `"--"`; if a `'='` character is found, the remainder is
the option argument; therefore, `["--opt=arg"]` and `["--opt", "arg"]` are equivalent if `--opt`
takes at least one argument. Long options can be abbreviated (e.g. `--opt` instead of
`--option`) as long as there is no ambiguity.
* short options begin with a single dash `"-"` and their name consists of a single character; they
can be grouped together (e.g. `["-x", "-y"]` can become `["-xy"]`), but in that case only the
last option in the group can take an argument (which can also be grouped, e.g.
`["-a", "-f", "file.txt"]` can be passed as `["-affile.txt"]` if `-a` does not take an argument
and `-f` does). The `'='` character can be used to separate option names from option arguments
as well (e.g. `-af=file.txt`).
* positional arguments are anything else; they can appear anywhere.
The special string `"--"` can be used to signal the end of all options; after that, everything is
considered as a positional argument (e.g. if `args = ["--opt1", "--", "--opt2"]`, the parser will
recognize `--opt1` as a long option without argument, and `--opt2` as a positional argument).
The special string `"-"` is always parsed as a positional argument.
The parsing can stop early if a `:show_help` or `:show_version` action is triggered, or if a parsing
error is found.
Some ambiguities can arise in parsing, see the [Parsing details](@ref) section for a detailed
description of how they're solved.
"""
function parse_args(args_list::Vector, settings::ArgParseSettings; as_symbols::Bool = false)
as_symbols && check_settings_can_use_symbols(settings)
local parsed_args
try
parsed_args = parse_args_unhandled(args_list, settings)
catch err
err isa ArgParseError || rethrow()
settings.exc_handler(settings, err)
end
as_symbols && (parsed_args = convert_to_symbols(parsed_args))
return parsed_args
end
mutable struct ParserState
args_list::Vector
arg_delim_found::Bool
token::Union{AbstractString,Nothing}
token_arg::Union{AbstractString,Nothing}
arg_consumed::Bool
last_arg::Int
found_args::Set{AbstractString}
command::Union{AbstractString,Nothing}
truncated_shopts::Bool
abort::Bool
exc_groups::Dict{ArgParseGroup,AbstractString}
out_dict::Dict{String,Any}
function ParserState(args_list::Vector, settings::ArgParseSettings, truncated_shopts::Bool)
exc_groups = Dict{ArgParseGroup,AbstractString}(
g=>"" for g in settings.args_groups if g.exclusive)
out_dict = Dict{String,Any}()
for f in settings.args_table.fields
f.action ∈ (:show_help, :show_version) && continue
out_dict[f.dest_name] = deepcopy(f.default)
end
return new(deepcopy(args_list), false, nothing, nothing, false, 0, Set{AbstractString}(),
nothing, truncated_shopts, false, exc_groups, out_dict)
end
end
found_command(state::ParserState) = state.command ≢ nothing
function parse_command_args!(state::ParserState, settings::ArgParseSettings)
cmd = state.command
haskey(settings, cmd) || argparse_error("unknown command: $cmd")
#state.out_dict[cmd] = parse_args(state.args_list, settings[cmd])
try
state.out_dict[cmd] =
parse_args_unhandled(state.args_list, settings[cmd], state.truncated_shopts)
catch err
err isa ArgParseError || rethrow(err)
settings[cmd].exc_handler(settings[cmd], err)
finally
state.truncated_shopts = false
end
return state.out_dict[cmd]
end
function preparse!(c::Channel, state::ParserState, settings::ArgParseSettings)
args_list = state.args_list
while !isempty(args_list)
state.arg_delim_found && (put!(c, :pos_arg); continue)
arg = args_list[1]
if state.truncated_shopts
@assert arg[1] == '-'
looks_like_an_option(arg, settings) ||
argparse_error("illegal short options sequence after command: $arg")
state.truncated_shopts = false
end
if arg == "--"
state.arg_delim_found = true
state.token = nothing
state.token_arg = nothing
popfirst!(args_list)
continue
elseif startswith(arg, "--")
eq = findfirst(isequal('='), arg)
if eq ≢ nothing
opt_name = arg[3:prevind(arg,eq)]
arg_after_eq = arg[nextind(arg,eq):end]
else
opt_name = arg[3:end]
arg_after_eq = nothing
end
isempty(opt_name) && argparse_error("illegal option: $arg")
popfirst!(args_list)
state.token = opt_name
state.token_arg = arg_after_eq
put!(c, :long_option)
elseif looks_like_an_option(arg, settings)
shopts_lst = arg[2:end]
popfirst!(args_list)
state.token = shopts_lst
state.token_arg = nothing
put!(c, :short_option_list)
else
state.token = nothing
state.token_arg = nothing
put!(c, :pos_arg)
end
end
end
# faithful reproduction of Python 3.5.1 argparse.py
# partially Copyright © 2001-2016 Python Software Foundation; All Rights Reserved
function read_args_from_files(arg_strings, prefixes)
new_arg_strings = AbstractString[]
for arg_string in arg_strings
if isempty(arg_string) || arg_string[1] ∉ prefixes
# for regular arguments, just add them back into the list
push!(new_arg_strings, arg_string)
else
# replace arguments referencing files with the file content
open(arg_string[nextind(arg_string, 1):end]) do args_file
arg_strings = AbstractString[]
for arg_line in readlines(args_file)
push!(arg_strings, rstrip(arg_line, '\n'))
end
arg_strings = read_args_from_files(arg_strings, prefixes)
append!(new_arg_strings, arg_strings)
end
end
end
# return the modified argument list
return new_arg_strings
end
function parse_args_unhandled(args_list::Vector,
settings::ArgParseSettings,
truncated_shopts::Bool=false)
all(x->(x isa AbstractString), args_list) || error("malformed args_list")
if !isempty(settings.fromfile_prefix_chars)
args_list = read_args_from_files(args_list, settings.fromfile_prefix_chars)
end
version_added = false
help_added = false
if settings.add_version
settings.add_version = false
add_arg_field!(settings, "--version",
action = :show_version,
help = "show version information and exit",
group = ""
)
version_added = true
end
if settings.add_help
settings.add_help = false
add_arg_field!(settings, ["--help", "-h"],
action = :show_help,
help = "show this help message and exit",
group = ""
)
help_added = true
end
state = ParserState(args_list, settings, truncated_shopts)
preparser = Channel(c->preparse!(c, state, settings))
try
for tag in preparser
if tag == :long_option
parse_long_opt!(state, settings)
elseif tag == :short_option_list
parse_short_opt!(state, settings)
elseif tag == :pos_arg
parse_arg!(state, settings)
else
found_a_bug()
end
state.abort && return nothing
found_command(state) && break
end
test_required_args(settings, state.found_args)
if found_command(state)
cmd_dict = parse_command_args!(state, settings)
cmd_dict ≡ nothing && return nothing
elseif settings.commands_are_required && has_cmd(settings)
argparse_error("no command given")
end
catch err
rethrow()
finally
if help_added
pop!(settings.args_table.fields)
settings.add_help = true
end
if version_added
pop!(settings.args_table.fields)
settings.add_version = true
end
end
return state.out_dict
end
# common parse functions
function parse1_flag!(state::ParserState, settings::ArgParseSettings, f::ArgParseField,
has_arg::Bool, opt_name::AbstractString)
has_arg && argparse_error("option $opt_name takes no arguments")
test_exclusive_groups!(state.exc_groups, settings, f, opt_name)
command = nothing
out_dict = state.out_dict
if f.action == :store_true
out_dict[f.dest_name] = true
elseif f.action == :store_false
out_dict[f.dest_name] = false
elseif f.action == :store_const
out_dict[f.dest_name] = f.constant
elseif f.action == :append_const
push!(out_dict[f.dest_name], f.constant)
elseif f.action == :count_invocations
out_dict[f.dest_name] += 1
elseif f.action == :command_flag
out_dict[f.dest_name] = f.constant
command = f.constant
elseif f.action == :show_help
show_help(settings, exit_when_done = settings.exit_after_help)
state.abort = true
elseif f.action == :show_version
show_version(settings, exit_when_done = settings.exit_after_help)
state.abort = true
end
state.command = command
return
end
function parse1_optarg!(state::ParserState, settings::ArgParseSettings, f::ArgParseField,
rest, name::AbstractString)
args_list = state.args_list
arg_delim_found = state.arg_delim_found
out_dict = state.out_dict
test_exclusive_groups!(state.exc_groups, settings, f, name)
arg_consumed = false
parse_function = f.eval_arg ? parse_item_eval : parse_item_wrapper
command = nothing
is_multi_nargs(f.nargs) && (opt_arg = Array{f.arg_type}(undef, 0))
if f.nargs.desc isa Int
num::Int = f.nargs.desc
num > 0 || found_a_bug()
corr = (rest ≡ nothing) ? 0 : 1
if length(args_list) + corr < num
argparse_error("$name requires $num argument", num > 1 ? "s" : "")
end
if rest ≢ nothing
a = parse_function(f.arg_type, rest)
test_range(f.range_tester, a, name)
push!(opt_arg, a)
arg_consumed = true
end
for i = (1+corr):num
a = parse_function(f.arg_type, popfirst!(args_list))
test_range(f.range_tester, a, name)
push!(opt_arg, a)
end
elseif f.nargs.desc == :A
if rest ≢ nothing
a = parse_function(f.arg_type, rest)
test_range(f.range_tester, a, name)
opt_arg = a
arg_consumed = true
else
isempty(args_list) && argparse_error("option $name requires an argument")
a = parse_function(f.arg_type, popfirst!(args_list))
test_range(f.range_tester, a, name)
opt_arg = a
end
elseif f.nargs.desc == :?
if rest ≢ nothing
a = parse_function(f.arg_type, rest)
test_range(f.range_tester, a, name)
opt_arg = a
arg_consumed = true
else
if isempty(args_list) || looks_like_an_option(args_list[1], settings)
opt_arg = deepcopy(f.constant)
else
a = parse_function(f.arg_type, popfirst!(args_list))
test_range(f.range_tester, a, name)
opt_arg = a
end
end
elseif f.nargs.desc == :* || f.nargs.desc == :+
arg_found = false
if rest ≢ nothing
a = parse_function(f.arg_type, rest)
test_range(f.range_tester, a, name)
push!(opt_arg, a)
arg_consumed = true
arg_found = true
end
while !isempty(args_list)
if !arg_delim_found && looks_like_an_option(args_list[1], settings)
break
end
a = parse_function(f.arg_type, popfirst!(args_list))
test_range(f.range_tester, a, name)
push!(opt_arg, a)
arg_found = true
end
if f.nargs.desc == :+ && !arg_found
argparse_error("option $name requires at least one not-option-looking argument")
end
elseif f.nargs.desc == :R
if rest ≢ nothing
a = parse_function(f.arg_type, rest)
test_range(f.range_tester, a, name)
push!(opt_arg, a)
arg_consumed = true
end
while !isempty(args_list)
a = parse_function(f.arg_type, popfirst!(args_list))
test_range(f.range_tester, a, name)
push!(opt_arg, a)
end
else
found_a_bug()
end
if f.action == :store_arg
out_dict[f.dest_name] = opt_arg
elseif f.action == :append_arg
push!(out_dict[f.dest_name], opt_arg)
elseif f.action == :command_arg
if !haskey(settings, opt_arg)
found = false
for f1 in settings.args_table.fields
(is_cmd(f1) && is_arg(f1)) || continue
for al in f1.cmd_aliases
if opt_arg == al
found = true
opt_arg = f1.constant
break
end
end
found && break
end
!found && argparse_error("unknown command: $opt_arg")
haskey(settings, opt_arg) || found_a_bug()
end
out_dict[f.dest_name] = opt_arg
command = opt_arg
else
found_a_bug()
end
state.arg_consumed = arg_consumed
state.command = command
return
end
# parse long opts
function parse_long_opt!(state::ParserState, settings::ArgParseSettings)
opt_name = state.token
arg_after_eq = state.token_arg
local f::ArgParseField
local fln::AbstractString
exact_match = false
nfound = 0
for g in settings.args_table.fields
for ln in g.long_opt_name
if ln == opt_name
exact_match = true
nfound = 1
f = g
fln = ln
break
elseif startswith(ln, opt_name)
nfound += 1
f = g
fln = ln
end
end
exact_match && break
end
nfound == 0 && argparse_error("unrecognized option --$opt_name")
nfound > 1 && argparse_error("long option --$opt_name is ambiguous ($nfound partial matches)")
opt_name = fln
if is_flag(f)
parse1_flag!(state, settings, f, arg_after_eq ≢ nothing, "--"*opt_name)
else
parse1_optarg!(state, settings, f, arg_after_eq, "--"*opt_name)
end
push!(state.found_args, idstring(f))
return
end
# parse short opts
function parse_short_opt!(state::ParserState, settings::ArgParseSettings)
shopts_lst = state.token
rest_as_arg = nothing
sind = firstindex(shopts_lst)
while sind ≤ ncodeunits(shopts_lst)
opt_char, next_sind = iterate(shopts_lst, sind)
if next_sind ≤ ncodeunits(shopts_lst)
next_opt_char, next2_sind = iterate(shopts_lst, next_sind)
if next_opt_char == '='
next_is_eq = true
rest_as_arg = shopts_lst[next2_sind:end]
else
next_is_eq = false
rest_as_arg = shopts_lst[next_sind:end]
end
else
next_is_eq = false
rest_as_arg = nothing
end
opt_name = string(opt_char)
local f::ArgParseField
found = false
for outer f in settings.args_table.fields
found |= any(sn->sn==opt_name, f.short_opt_name)
found && break
end
found || argparse_error("unrecognized option -$opt_name")
if is_flag(f)
parse1_flag!(state, settings, f, next_is_eq, "-"*opt_name)
else
parse1_optarg!(state, settings, f, rest_as_arg, "-"*opt_name)
end
push!(state.found_args, idstring(f))
state.arg_consumed && break
if found_command(state)
if rest_as_arg ≢ nothing && !isempty(rest_as_arg)
startswith(rest_as_arg, '-') &&
argparse_error("illegal short options sequence after command " *
"$(state.command): $rest_as_arg")
pushfirst!(state.args_list, "-" * rest_as_arg)
state.truncated_shopts = true
end
return
end
sind = next_sind
end
end
# parse arg
function parse_arg!(state::ParserState, settings::ArgParseSettings)
found = false
local f::ArgParseField
for new_arg_ind = state.last_arg+1:length(settings.args_table.fields)
f = settings.args_table.fields[new_arg_ind]
if is_arg(f) && !f.fake
found = true
state.last_arg = new_arg_ind
break
end
end
found || argparse_error("too many arguments")
parse1_optarg!(state, settings, f, nothing, f.dest_name)
push!(state.found_args, idstring(f))
return
end
# convert_to_symbols
convert_to_symbols(::Nothing) = nothing
function convert_to_symbols(parsed_args::Dict{String,Any})
new_parsed_args = Dict{Symbol,Any}()
cmd = nothing
if haskey(parsed_args, cmd_dest_name)
cmd = parsed_args[cmd_dest_name]
if cmd ≡ nothing
scmd = nothing
else
scmd = Symbol(cmd)
new_parsed_args[scmd] = convert_to_symbols(parsed_args[cmd])
end
new_parsed_args[scmd_dest_name] = scmd
end
for (k,v) in parsed_args
(k == cmd_dest_name || k == cmd) && continue
new_parsed_args[Symbol(k)] = v
end
return new_parsed_args
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 59409 | ## All types, functions and constants related to the specification of the arguments
# actions
const all_actions = [:store_arg, :store_true, :store_false, :store_const,
:append_arg, :append_const, :count_invocations,
:command, :show_help, :show_version]
const internal_actions = [:store_arg, :store_true, :store_false, :store_const,
:append_arg, :append_const, :count_invocations,
:command_arg, :command_flag,
:show_help, :show_version]
const nonflag_actions = [:store_arg, :append_arg, :command_arg]
is_flag_action(a::Symbol) = a ∉ nonflag_actions
const multi_actions = [:append_arg, :append_const]
is_multi_action(a::Symbol) = a ∈ multi_actions
const command_actions = [:command_arg, :command_flag]
is_command_action(a::Symbol) = a ∈ command_actions
# ArgParseSettingsError
struct ArgParseSettingsError <: Exception
text::AbstractString
end
serror(x...) = throw(ArgParseSettingsError(string(x...)))
# ArgConsumerType
struct ArgConsumerType
desc::Union{Int,Symbol}
function ArgConsumerType(n::Integer)
n ≥ 0 || serror("nargs can't be negative")
new(n)
end
function ArgConsumerType(s::Symbol)
s ∈ [:A, :?, :*, :+, :R] ||
serror("nargs must be an integer or one of 'A', '?', '*', '+', 'R'")
new(s)
end
end
ArgConsumerType(c::Char) = ArgConsumerType(Symbol(c))
ArgConsumerType() = ArgConsumerType(:A)
function show(io::IO, nargs::ArgConsumerType)
print(io, nargs.desc isa Int ? nargs.desc : "'" * string(nargs.desc) * "'")
end
is_multi_nargs(nargs::ArgConsumerType) = nargs.desc ∉ (0, :A, :?)
default_action(nargs::Integer) = nargs == 0 ? :store_true : :store_arg
default_action(nargs::Char) = :store_arg
default_action(nargs::Symbol) = :store_arg
default_action(nargs::ArgConsumerType) = default_action(nargs.desc)
# ArgParseGroup
mutable struct ArgParseGroup
name::AbstractString
desc::AbstractString
exclusive::Bool
required::Bool
function ArgParseGroup(name::AbstractString,
desc::AbstractString,
exclusive::Bool = false,
required::Bool = false
)
new(name, desc, exclusive, required)
end
end
const cmd_group = ArgParseGroup("commands", "commands")
const pos_group = ArgParseGroup("positional", "positional arguments")
const opt_group = ArgParseGroup("optional", "optional arguments")
const std_groups = [cmd_group, pos_group, opt_group]
# ArgParseField
mutable struct ArgParseField
dest_name::AbstractString
long_opt_name::Vector{AbstractString}
short_opt_name::Vector{AbstractString}
arg_type::Type
action::Symbol
nargs::ArgConsumerType
default
constant
range_tester::Function
required::Bool
eval_arg::Bool
help::AbstractString
metavar::Union{AbstractString,Vector{<:AbstractString}}
cmd_aliases::Vector{AbstractString}
group::AbstractString
fake::Bool
ArgParseField() = new("", AbstractString[], AbstractString[], Any, :store_true,
ArgConsumerType(), nothing, nothing, _->true, false, false, "", "",
AbstractString[], "", false)
end
is_flag(arg::ArgParseField) = is_flag_action(arg.action)
is_arg(arg::ArgParseField) = isempty(arg.long_opt_name) && isempty(arg.short_opt_name)
is_cmd(arg::ArgParseField) = is_command_action(arg.action)
const cmd_dest_name = "%COMMAND%"
const scmd_dest_name = :_COMMAND_
function show(io::IO, s::ArgParseField)
println(io, "ArgParseField(")
for f in fieldnames(ArgParseField)
println(io, " ", f, "=", getfield(s, f))
end
print(io, " )")
end
# ArgParseTable
mutable struct ArgParseTable
fields::Vector{ArgParseField}
subsettings::Dict{AbstractString,Any} # will actually be a Dict{AbstractString,ArgParseSettings}
ArgParseTable() = new(ArgParseField[], Dict{AbstractString,Any}())
end
# disallow alphanumeric, -
function check_prefix_chars(chars)
result = Set{Char}()
for c in chars
if isletter(c) || isnumeric(c) || c == '-'
throw(ArgParseError("‘$(c)’ is not allowed as prefix character"))
end
push!(result, c)
end
result
end
# ArgParseSettings
"""
ArgParseSettings
The `ArgParseSettings` object contains all the settings to be used during argument parsing. Settings
are divided in two groups: general settings and argument-table-related settings.
While the argument table requires specialized functions such as [`@add_arg_table!`](@ref) to be
defined and manipulated, general settings are simply object fields (most of them are `Bool` or
`String`) and can be passed to the constructor as keyword arguments, or directly set at any time.
This is the list of general settings currently available:
* `prog` (default = `""`): the name of the program, as displayed in the auto-generated help and
usage screens. If left empty, the source file name will be used.
* `description` (default = `""`): a description of what the program does, to be displayed in the
auto-generated help-screen, between the usage lines and the arguments description. If
`preformatted_description` is `false` (see below), it will be automatically formatted, but you can
still force newlines by using two consecutive newlines in the string, and manually control spaces
by using non-breakable spaces (the character `'\\ua0'`).
* `preformatted_description` (default = `false`): disable automatic formatting of `description`.
* `epilog` (default = `""`): like `description`, but will be displayed at the end of the
help-screen, after the arguments description. The same formatting rules also apply.
* `preformatted_epilog` (default = `false`): disable automatic formatting of `epilog`.
* `usage` (default = `""`): the usage line(s) to be displayed in the help screen and when an error
is found during parsing. If left empty, it will be auto-generated.
* `version` (default = `"Unknown version"`): version information. It's used by the `:show_version`
action.
* `add_help` (default = `true`): if `true`, a `--help, -h` option (triggering the `:show_help`
action) is added to the argument table.
* `add_version` (default = `false`): if `true`, a `--version` option (triggering the `:show_version`
action) is added to the argument table.
* `help_width` (default = `70`): set the width of the help text. This does not affect the
`usage` line if it is provided by the user rather than being auto-generated; it also does not
affect the `description/epilog` lines if the `preformatted_description/epilog` options are set to
`false`.
* `help_alignment_width` (default = `24`): set the maximum width of the left column of the help
text, where options and arguments names are listed. This also affects the indentation of the usage
line when it is auto-generated. It must be ≥ 4 and should be less than `help_width`.
* `fromfile_prefix_chars` (default = `Set{Char}()`): an argument beginning with one of these
characters will specify a file from which arguments will be read, one argument read per line.
Alphanumeric characters and the hyphen-minus (`'-'`) are prohibited.
* `autofix_names` (default = `false`): if `true`, will try to automatically fix the uses of dashes
(`'-'`) and underscores (`'_'`) in option names and destinations: all underscores will be
converted to dashes in long option names; also, associated destination names, if auto-generated
(see the [Argument names](@ref) section), will have dashes replaced with underscores, both for
long options and for positional arguments. For example, an option declared as `"--my-opt"` will be
associated with the key `"my_opt"` by default. It is especially advisable to turn this option on
then parsing with the `as_symbols=true` argument to `parse_args`.
* `error_on_conflict` (default = `true`): if `true`, throw an error in case conflicting entries are
added to the argument table; if `false`, later entries will silently take precedence. See the
[Conflicts and overrides](@ref) srction for a detailed description of what conflicts are and what
is the exact behavior when this setting is `false`.
* `suppress_warnings` (default = `false`): if `true`, all warnings will be suppressed.
* `allow_ambiguous_opts` (default = `false`): if `true`, ambiguous options such as `-1` will be
accepted.
* `commands_are_required` (default = `true`): if `true`, commands will be mandatory. See the
[Commands](@ref) section.
* `exc_handler` (default = `ArgParse.default_handler`): this is a function which is invoked when an
error is detected during parsing (e.g. an option is not recognized, a required argument is not
passed etc.). It takes two arguments: the `settings::ArgParseSettings` object and the
`err::ArgParseError` exception. The default handler behaves differently depending on whether it's
invoked from a script or in an interactive environment (e.g. REPL/IJulia). In non-interactive
(script) mode, it calls `ArgParse.cmdline_handler`, which prints the error text and the usage
screen on standard error and exits Julia with error code 1:
```julia
function cmdline_handler(settings::ArgParseSettings, err, err_code::Int = 1)
println(stderr, err.text)
println(stderr, usage_string(settings))
exit(err_code)
end
```
In interactive mode instead it calls the function `ArgParse.debug_handler`, which just rethrows
the error.
* `exit_after_help` (default = `!isinteractive()`): exit Julia (with error code `0`) when the
`:show_help` or `:show_version` actions are triggered. If `false`, those actions will just stop
the parsing and make `parse_args` return `nothing`.
Here is a usage example:
```julia
settings = ArgParseSettings(description = "This program does something",
commands_are_required = false,
version = "1.0",
add_version = true)
```
which is also equivalent to:
```julia
settings = ArgParseSettings()
settings.description = "This program does something."
settings.commands_are_required = false
settings.version = "1.0"
settings.add_version = true
```
As a shorthand, the `description` field can be passed without keyword, which makes this equivalent
to the above:
```julia
settings = ArgParseSettings("This program does something",
commands_are_required = false,
version = "1.0",
add_version = true)
```
Most settings won't take effect until `parse_args` is invoked, but a few will have immediate
effects: `autofix_names`, `error_on_conflict`, `suppress_warnings`, `allow_ambiguous_opts`.
"""
mutable struct ArgParseSettings
prog::AbstractString
description::AbstractString
epilog::AbstractString
usage::AbstractString
version::AbstractString
add_help::Bool
add_version::Bool
help_width::Int
help_alignment_width::Int
fromfile_prefix_chars::Set{Char}
autofix_names::Bool
error_on_conflict::Bool
suppress_warnings::Bool
allow_ambiguous_opts::Bool
commands_are_required::Bool
args_groups::Vector{ArgParseGroup}
default_group::AbstractString
args_table::ArgParseTable
exc_handler::Function
preformatted_description::Bool
preformatted_epilog::Bool
exit_after_help::Bool
function ArgParseSettings(;prog::AbstractString = Base.source_path() ≢ nothing ?
basename(Base.source_path()) :
"",
description::AbstractString = "",
epilog::AbstractString = "",
usage::AbstractString = "",
version::AbstractString = "Unspecified version",
add_help::Bool = true,
add_version::Bool = false,
help_width::Integer = 70,
help_alignment_width::Integer = 24,
fromfile_prefix_chars = Set{Char}(),
autofix_names::Bool = false,
error_on_conflict::Bool = true,
suppress_warnings::Bool = false,
allow_ambiguous_opts::Bool = false,
commands_are_required::Bool = true,
exc_handler::Function = default_handler,
preformatted_description::Bool = false,
preformatted_epilog::Bool = false,
exit_after_help::Bool = !isinteractive()
)
fromfile_prefix_chars = check_prefix_chars(fromfile_prefix_chars)
return new(
prog, description, epilog, usage, version, add_help, add_version,
help_width, help_alignment_width, fromfile_prefix_chars, autofix_names,
error_on_conflict, suppress_warnings, allow_ambiguous_opts, commands_are_required,
copy(std_groups), "", ArgParseTable(), exc_handler,
preformatted_description, preformatted_epilog,
exit_after_help
)
end
end
ArgParseSettings(desc::AbstractString; kw...) = ArgParseSettings(; description = desc, kw...)
function show(io::IO, s::ArgParseSettings)
println(io, "ArgParseSettings(")
for f in fieldnames(ArgParseSettings)
f ∈ (:args_groups, :args_table) && continue
println(io, " ", f, "=", getfield(s, f))
end
println(io, " >> ", usage_string(s))
print(io, " )")
end
ArgName{T<:AbstractString} = Union{T, Vector{T}}
getindex(s::ArgParseSettings, c::AbstractString) = s.args_table.subsettings[c]
haskey(s::ArgParseSettings, c::AbstractString) = haskey(s.args_table.subsettings, c)
setindex!(s::ArgParseSettings, x::ArgParseSettings, c::AbstractString) =
setindex!(s.args_table.subsettings, x, c)
# fields declarations sanity checks
function check_name_format(name::ArgName)
isempty(name) && serror("empty name")
name isa Vector || return true
allopts = true
allargs = true
for n in name
isempty(n) && serror("empty name")
if startswith(n, '-')
allargs = false
else
allopts = false
end
end
!(allargs || allopts) && serror("multiple names must be either all options or all non-options")
for i1 = 1:length(name), i2 = i1+1:length(name)
name[i1] == name[i2] && serror("duplicate name $(name[i1])")
end
return true
end
function check_type(opt, T::Type, message::AbstractString)
opt isa T || serror(message)
return true
end
function check_eltype(opt, T::Type, message::AbstractString)
eltype(opt) <: T || serror(message)
return true
end
function warn_extra_opts(opts, valid_keys::Vector{Symbol})
for k in opts
k ∈ valid_keys || @warn "ignored option: $k"
end
return true
end
function check_action_is_valid(action::Symbol)
action ∈ all_actions || serror("invalid action: $action")
end
function check_nargs_and_action(nargs::ArgConsumerType, action::Symbol)
is_flag_action(action) && nargs.desc ≠ 0 && nargs.desc ≠ :A &&
serror("incompatible nargs and action (flag-action $action, nargs=$nargs)")
is_command_action(action) && nargs.desc ≠ :A &&
serror("incompatible nargs and action (command action, nargs=$nargs)")
!is_flag_action(action) && nargs.desc == 0 &&
serror("incompatible nargs and action (non-flag-action $action, nargs=$nargs)")
return true
end
function check_long_opt_name(name::AbstractString, settings::ArgParseSettings)
'=' ∈ name && serror("illegal option name: $name (contains '=')")
occursin(r"\s", name) && serror("illegal option name: $name (contains whitespace)")
settings.add_help &&
name == "help" && serror("option --help is reserved in the current settings")
settings.add_version &&
name == "version" && serror("option --version is reserved in the current settings")
return true
end
function check_short_opt_name(name::AbstractString, settings::ArgParseSettings)
length(name) ≠ 1 && serror("short options must use a single character")
name == "=" && serror("illegal short option name: $name")
occursin(r"\s", name) && serror("illegal option name: $name (contains whitespace)")
!settings.allow_ambiguous_opts && occursin(r"[0-9.(]", name) &&
serror("ambiguous option name: $name (disabled in current settings)")
settings.add_help && name == "h" &&
serror("option -h is reserved for help in the current settings")
return true
end
function check_arg_name(name::AbstractString)
occursin(r"^%[A-Z]*%$", name) && serror("invalid positional arg name: $name (is reserved)")
return true
end
function check_cmd_name(name::AbstractString)
isempty(name) && found_a_bug()
startswith(name, '-') && found_a_bug()
occursin(r"\s", name) && serror("invalid command name: $name (contains whitespace)")
occursin(r"^%[A-Z]*%$", name) && serror("invalid command name: $name (is reserved)")
return true
end
function check_dest_name(name::AbstractString)
occursin(r"^%[A-Z]*%$", name) && serror("invalid dest_name: $name (is reserved)")
return true
end
function idstring(arg::ArgParseField)
if is_arg(arg)
return "argument $(arg.metavar)"
elseif !isempty(arg.long_opt_name)
return "option --$(arg.long_opt_name[1])"
else
return "option -$(arg.short_opt_name[1])"
end
end
# TODO improve (test more nonsensical cases)
function check_arg_makes_sense(settings::ArgParseSettings, arg::ArgParseField)
is_arg(arg) || return true
is_command_action(arg.action) && return true
for f in settings.args_table.fields
is_arg(f) || continue
is_command_action(f.action) && serror("non-command $(idstring(arg)) can't follow commands")
!f.required && arg.required &&
serror("required $(idstring(arg)) can't follow non-required arguments")
end
return true
end
function check_conflicts_with_commands(settings::ArgParseSettings,
new_arg::ArgParseField,
allow_future_merge::Bool)
for cmd in keys(settings.args_table.subsettings)
cmd == new_arg.dest_name &&
serror("$(idstring(new_arg)) has the same destination of a command: $cmd")
end
for a in settings.args_table.fields
if is_cmd(a) && !is_cmd(new_arg)
for l1 in a.long_opt_name, l2 in new_arg.long_opt_name
# TODO be less strict here and below, and allow partial override?
l1 == l2 && serror("long opt name --$(l1) already in use by command $(a.constant)")
end
for s1 in a.short_opt_name, s2 in new_arg.short_opt_name
s1 == s2 && serror("short opt name -$(s1) already in use by command $(a.constant)")
end
elseif is_cmd(a) && is_cmd(new_arg)
if a.constant == new_arg.constant
allow_future_merge || serror("command $(a.constant) already in use")
is_arg(a) ≠ is_arg(new_arg) &&
serror("$(idstring(a)) and $(idstring(new_arg)) are incompatible")
else
for al in new_arg.cmd_aliases
al == a.constant && serror("invalid alias $al, command already in use")
end
end
end
end
return true
end
function check_conflicts_with_commands(settings::ArgParseSettings, new_cmd::AbstractString)
for a in settings.args_table.fields
new_cmd == a.dest_name &&
serror("command $new_cmd has the same destination of $(idstring(a))")
end
return true
end
function check_for_duplicates(args::Vector{ArgParseField}, new_arg::ArgParseField)
for a in args
for l1 in a.long_opt_name, l2 in new_arg.long_opt_name
l1 == l2 && serror("duplicate long opt name $l1")
end
for s1 in a.short_opt_name, s2 in new_arg.short_opt_name
s1 == s2 && serror("duplicate short opt name $s1")
end
if is_arg(a) && is_arg(new_arg) && a.metavar == new_arg.metavar
serror("two arguments have the same metavar: $(a.metavar)")
end
if is_cmd(a) && is_cmd(new_arg)
for al1 in a.cmd_aliases, al2 in new_arg.cmd_aliases
al1 == al2 &&
serror("both commands $(a.constant) and $(new_arg.constant) use the same alias $al1")
end
for al1 in a.cmd_aliases
al1 == new_arg.constant &&
serror("$al1 already in use as an alias command $(a.constant)")
end
for al2 in new_arg.cmd_aliases
al2 == a.constant && serror("invalid alias $al2, command already in use")
end
end
if a.dest_name == new_arg.dest_name
a.arg_type == new_arg.arg_type ||
serror("$(idstring(a)) and $(idstring(new_arg)) have the same destination but different arg types")
if (is_multi_action(a.action) && !is_multi_action(new_arg.action)) ||
(!is_multi_action(a.action) && is_multi_action(new_arg.action))
serror("$(idstring(a)) and $(idstring(new_arg)) have the same destination but incompatible actions")
end
end
end
return true
end
function typecompatible(default::D, arg_type::Type) where D
D <: arg_type && return true
try
applicable(convert, arg_type, default) ? convert(arg_type, default) : arg_type(default)
return true
catch
end
return false
end
check_default_type(default::Nothing, arg_type::Type) = true
function check_default_type(default::D, arg_type::Type) where D
typecompatible(default, arg_type) || serror("typeof(default)=$D is incompatible with arg_type=$arg_type)")
return true
end
check_default_type_multi(default::Nothing, arg_type::Type) = true
function check_default_type_multi(default::Vector, arg_type::Type)
all(x->typecompatible(x, arg_type), default) || serror("all elements of the default value must be of type $arg_type or convertible to it")
return true
end
check_default_type_multi(default::D, arg_type::Type) where D =
serror("typeof(default)=$D is incompatible with nargs, it should be a Vector")
check_default_type_multi2(default::Nothing, arg_type::Type) = true
function check_default_type_multi2(default::Vector{D}, arg_type::Type) where D
all(y->(y isa Vector), default) ||
serror("the default $(default) is incompatible with the action and nargs, it should be a Vector of Vectors")
all(y->all(x->typecompatible(x, arg_type), y), default) || serror("all elements of the default value must be of type $arg_type or convertible to it")
return true
end
check_default_type_multi2(default::D, arg_type::Type) where D =
serror("the default $(default) is incompatible with the action and nargs, it should be a Vector of Vectors")
function _convert_default(arg_type::Type, default::D) where D
D <: arg_type && return default
applicable(convert, arg_type, default) ? convert(arg_type, default) : arg_type(default)
end
convert_default(arg_type::Type, default::Nothing) = nothing
convert_default(arg_type::Type, default) = _convert_default(arg_type, default)
convert_default_multi(arg_type::Type, default::Nothing) = Array{arg_type}(undef, 0)
convert_default_multi(arg_type::Type, default::Vector) = arg_type[_convert_default(arg_type, x) for x in default]
convert_default_multi2(arg_type::Type, default::Nothing) = Array{Vector{arg_type}}(undef, 0)
convert_default_multi2(arg_type::Type, default::Vector) = Vector{arg_type}[arg_type[_convert_default(arg_type, x) for x in y] for y in default]
check_range_default(default::Nothing, range_tester::Function) = true
function check_range_default(default, range_tester::Function)
local res::Bool
try
res = range_tester(default)
catch err
serror("the range_tester function must be defined for the default value, and return a Bool")
end
res || serror("the default value must pass the range_tester function")
return true
end
check_range_default_multi(default::Nothing, range_tester::Function) = true
function check_range_default_multi(default::Vector, range_tester::Function)
for d in default
local res::Bool
try
res = range_tester(d)
catch err
serror("the range_tester function must be defined for all the default values, and return a Bool")
end
res || serror("all of the default values must pass the range_tester function")
end
return true
end
check_range_default_multi2(default::Nothing, range_tester::Function) = true
function check_range_default_multi2(default::Vector, range_tester::Function)
for dl in default, d in dl
local res::Bool
try
res = range_tester(d)
catch err
serror("the range_tester function must be defined for all the default values, and return a Bool")
end
res || serror("all of the default values must pass the range_tester function")
end
return true
end
function check_metavar(metavar::AbstractString)
isempty(metavar) && serror("empty metavar")
startswith(metavar, '-') && serror("metavars cannot begin with -")
occursin(r"\s", metavar) && serror("illegal metavar name: $metavar (contains whitespace)")
return true
end
function check_metavar(metavar::Vector{<:AbstractString})
foreach(check_metavar, metavar)
return true
end
function check_group_name(name::AbstractString)
isempty(name) && serror("empty group name")
startswith(name, '#') && serror("invalid group name (starts with #)")
return true
end
# add_arg_table! and related
function name_to_fieldnames!(settings::ArgParseSettings, name::ArgName)
pos_arg = ""
long_opts = AbstractString[]
short_opts = AbstractString[]
aliases = AbstractString[]
r(n) = settings.autofix_names ? replace(n, '_' => '-') : n
function do_one(n, cmd_check = true)
if startswith(n, "--")
n == "--" && serror("illegal option name: --")
long_opt_name = r(n[3:end])
check_long_opt_name(long_opt_name, settings)
push!(long_opts, long_opt_name)
elseif startswith(n, '-')
n == "-" && serror("illegal option name: -")
short_opt_name = n[2:end]
check_short_opt_name(short_opt_name, settings)
push!(short_opts, short_opt_name)
else
if cmd_check
check_cmd_name(n)
else
check_arg_name(n)
end
if isempty(pos_arg)
pos_arg = n
else
push!(aliases, n)
end
end
end
if name isa Vector
foreach(do_one, name)
else
do_one(name, false)
end
return pos_arg, long_opts, short_opts, aliases
end
function auto_dest_name(pos_arg::AbstractString,
long_opts::Vector{AbstractString},
short_opts::Vector{AbstractString},
autofix_names::Bool)
r(n) = autofix_names ? replace(n, '-' => '_') : n
isempty(pos_arg) || return r(pos_arg)
isempty(long_opts) || return r(long_opts[1])
@assert !isempty(short_opts)
return short_opts[1]
end
function auto_metavar(dest_name::AbstractString, is_opt::Bool)
is_opt || return dest_name
prefix = occursin(r"^[[:alpha:]_]", dest_name) ? "" : "_"
return prefix * uppercase(dest_name)
end
function get_cmd_prog_hint(arg::ArgParseField)
isempty(arg.short_opt_name) || return "-" * arg.short_opt_name[1]
isempty(arg.long_opt_name) || return "--" * arg.long_opt_name[1]
return arg.constant
end
"""
add_arg_table!(settings, [arg_name [,arg_options]]...)
This function is very similar to the macro version [`@add_arg_table!`](@ref). Its syntax is stricter:
tuples and blocks are not allowed and argument options are explicitly specified as `Dict` objects.
However, since it doesn't involve macros, it offers more flexibility in other respects, e.g. the
`arg_name` entries need not be explicit, they can be anything which evaluates to a `String` or a
`Vector{String}`.
Example:
```julia
add_arg_table!(settings,
["--opt1", "-o"],
Dict(
:help => "an option with an argument"
),
"--opt2",
"arg1",
Dict(
:help => "a positional argument"
:required => true
))
```
"""
function add_arg_table!(settings::ArgParseSettings, table::Union{ArgName,Vector,Dict}...)
has_name = false
for i = 1:length(table)
!has_name && !(table[i] isa ArgName) &&
serror("option field must be preceded by the arg name")
has_name = true
end
i = 1
while i ≤ length(table)
if i+1 ≤ length(table) && !(table[i+1] isa ArgName)
add_arg_field!(settings, table[i]; table[i+1]...)
i += 2
else
add_arg_field!(settings, table[i])
i += 1
end
end
return settings
end
"""
@add_arg_table!(settings, table...)
This macro adds a table of arguments and options to the given `settings`. It can be invoked multiple
times. The arguments groups are determined automatically, or the current default group is used if
specified (see the [Argument groups](@ref) section for more details).
The `table` is a list in which each element can be either `String`, or a tuple or a vector of
`String`, or an assigmment expression, or a block:
* a `String`, a tuple or a vector introduces a new positional argument or option. Tuples and vectors
are only allowed for options or commands, and provide alternative names (e.g. `["--opt", "-o"]` or
`["checkout", "co"]`)
* assignment expressions (i.e. expressions using `=`, `:=` or `=>`) describe the previous argument
behavior (e.g. `help = "an option"` or `required => false`). See the
[Argument entry settings](@ref) section for a complete description
* blocks (`begin...end` or lists of expressions in parentheses separated by semicolons) are useful
to group entries and span multiple lines.
These rules allow for a variety usage styles, which are discussed in the
[Argument table styles](@ref) section. In the rest of the documentation, we will mostly use this
style:
```julia
@add_arg_table! settings begin
"--opt1", "-o"
help = "an option with an argument"
"--opt2"
"arg1"
help = "a positional argument"
required = true
end
```
In the above example, the `table` is put in a single `begin...end` block and the line
`"--opt1", "-o"` is parsed as a tuple; indentation is used to help readability.
See also the function [`add_arg_table!`](@ref).
"""
macro add_arg_table!(s, x...)
_add_arg_table!(s, x...)
end
# Moved all the code to a function just to make the deprecation work
function _add_arg_table!(s, x...)
# transform the tuple into a vector, so that
# we can manipulate it
x = Any[x...]
# escape the ArgParseSettings
s = esc(s)
z = esc(gensym())
# start building the return expression
exret = quote
$z = $s
$z isa ArgParseSettings ||
serror("first argument to @add_arg_table! must be of type ArgParseSettings")
end
# initialize the name and the options expression
name = nothing
exopt = Any[:Dict]
# iterate over the arguments
i = 1
while i ≤ length(x)
y = x[i]
if Meta.isexpr(y, :block)
# found a begin..end block: expand its contents
# in-place and restart from the same position
splice!(x, i, y.args)
continue
elseif Meta.isexpr(y, :macrocall) &&
((y.args[1] == GlobalRef(Core, Symbol("@doc"))) ||
(Meta.isexpr(y.args[1], :core) && y.args[1].args[1] == Symbol("@doc")))
# Was parsed as doc syntax. Split into components
splice!(x, i, y.args[2:end])
continue
elseif (y isa AbstractString) || Meta.isexpr(y, (:vect, :tuple))
Meta.isexpr(y, :tuple) && (y.head = :vect) # transform tuples into vectors
if Meta.isexpr(y, :vect) && (isempty(y.args) || !all(x->x isa AbstractString, y.args))
# heterogeneous elements: splice it in place, just like blocks
splice!(x, i, y.args)
continue
end
# found a string, or a vector/tuple of strings:
# this must be the option name
if name ≢ nothing
# there was a previous arg field on hold
# first, concretely build the options
opt = Expr(:call, exopt...)
kopts = Expr(:parameters, Expr(:(...), opt))
# then, call add_arg_field!
aaf = Expr(:call, :add_arg_field!, kopts, z, name)
# store it in the output expression
exret = quote
$exret
$aaf
end
end
# put the name on hold, reinitialize the options expression
name = y
exopt = Any[:Dict]
i += 1
elseif Meta.isexpr(y, (:(=), :(:=), :kw))
# found an assignment: add it to the current options expression
name ≢ nothing ||
serror("malformed table: description fields must be preceded by the arg name")
push!(exopt, Expr(:call, :(=>), Expr(:quote, y.args[1]), esc(y.args[2])))
i += 1
elseif Meta.isexpr(y, :call) && y.args[1] == :(=>)
# found an assignment: add it to the current options expression
name ≢ nothing ||
serror("malformed table: description fields must be preceded by the arg name")
push!(exopt, Expr(:call, :(=>), Expr(:quote, y.args[2]), esc(y.args[3])))
i += 1
elseif (y isa LineNumberNode) || Meta.isexpr(y, :line)
# a line number node, ignore
i += 1
continue
else
# anything else: ignore, but issue a warning
@warn "@add_arg_table!: ignoring expression $y"
i += 1
end
end
if name ≢ nothing
# there is an arg field on hold
# same as above
opt = Expr(:call, exopt...)
kopts = Expr(:parameters, Expr(:(...), opt))
aaf = Expr(:call, :add_arg_field!, kopts, z, name)
exret = quote
$exret
$aaf
end
end
# the return value when invoking the macro
# will be the ArgParseSettings object
exret = quote
$exret
$z
end
# return the resulting expression
exret
end
function get_group(group::AbstractString, arg::ArgParseField, settings::ArgParseSettings)
if isempty(group)
is_cmd(arg) && return cmd_group
is_arg(arg) && return pos_group
return opt_group
else
for ag in settings.args_groups
group == ag.name && return ag
end
serror("group $group not found, use add_arg_group! to add it")
end
found_a_bug()
end
function add_arg_field!(settings::ArgParseSettings, name::ArgName; desc...)
check_name_format(name)
supplied_opts = keys(desc)
@defaults desc begin
nargs = ArgConsumerType()
action = default_action(nargs)
arg_type = Any
default = nothing
constant = nothing
required = false
range_tester = x->true
eval_arg = false
dest_name = ""
help = ""
metavar = ""
force_override = !settings.error_on_conflict
group = settings.default_group
end
check_type(nargs, Union{ArgConsumerType,Int,Char}, "nargs must be an Int or a Char")
check_type(action, Union{AbstractString,Symbol}, "action must be an AbstractString or a Symbol")
check_type(arg_type, Type, "invalid arg_type")
check_type(required, Bool, "required must be a Bool")
check_type(range_tester, Function, "range_tester must be a Function")
check_type(dest_name, AbstractString, "dest_name must be an AbstractString")
check_type(help, AbstractString, "help must be an AbstractString")
# Check metavar's type to be either an AbstractString or a
# Vector{T<:AbstractString}
metavar_error = "metavar must be an AbstractString or a Vector{<:AbstractString}"
if !(metavar isa AbstractString)
check_type(metavar, Vector, metavar_error)
check_eltype(metavar, AbstractString, metavar_error)
check_type(nargs, Integer, "nargs must be an integer for multiple metavars")
length(metavar) == nargs || serror("metavar array must have length of nargs")
end
check_type(force_override, Bool, "force_override must be a Bool")
check_type(group, Union{AbstractString,Symbol}, "group must be an AbstractString or a Symbol")
nargs isa ArgConsumerType || (nargs = ArgConsumerType(nargs))
action isa Symbol || (action = Symbol(action))
is_opt = name isa Vector ?
startswith(first(name), '-') :
startswith(name, '-')
check_action_is_valid(action)
action == :command && (action = is_opt ? :command_flag : :command_arg)
check_nargs_and_action(nargs, action)
new_arg = ArgParseField()
is_flag = is_flag_action(action)
if !is_opt
is_flag && serror("invalid action for positional argument: $action")
nargs.desc == :? && serror("invalid 'nargs' for positional argument: '?'")
metavar isa Vector && serror("multiple metavars only supported for optional arguments")
end
pos_arg, long_opts, short_opts, cmd_aliases = name_to_fieldnames!(settings, name)
if !isempty(cmd_aliases)
is_command_action(action) || serror("only command arguments can have multiple names (aliases)")
end
new_arg.dest_name = auto_dest_name(pos_arg, long_opts, short_opts, settings.autofix_names)
new_arg.long_opt_name = long_opts
new_arg.short_opt_name = short_opts
new_arg.cmd_aliases = cmd_aliases
new_arg.nargs = nargs
new_arg.action = action
group = string(group)
if :group ∈ supplied_opts && !isempty(group)
check_group_name(group)
end
arg_group = get_group(group, new_arg, settings)
new_arg.group = arg_group.name
if arg_group.exclusive && (!is_opt || is_command_action(action))
serror("group $(new_arg.group) is mutually-exclusive, actions and commands are not allowed")
end
if action ∈ (:store_const, :append_const) && :constant ∉ supplied_opts
serror("action $action requires the 'constant' field")
end
valid_keys = [:nargs, :action, :help, :force_override, :group]
if is_flag
if action ∈ (:store_const, :append_const)
append!(valid_keys, [:default, :constant, :arg_type, :dest_name])
elseif action ∈ (:store_true, :store_false, :count_invocations, :command_flag)
push!(valid_keys, :dest_name)
else
action ∈ (:show_help, :show_version) || found_a_bug()
end
elseif is_opt
append!(valid_keys,
[:arg_type, :default, :range_tester, :dest_name, :required, :metavar, :eval_arg])
nargs.desc == :? && push!(valid_keys, :constant)
elseif action ≠ :command_arg
append!(valid_keys, [:arg_type, :default, :range_tester, :required, :metavar])
end
settings.suppress_warnings || warn_extra_opts(supplied_opts, valid_keys)
if is_command_action(action)
if (:dest_name ∈ supplied_opts) && (:dest_name ∈ valid_keys)
cmd_name = dest_name
else
cmd_name = new_arg.dest_name
end
end
if (:dest_name ∈ supplied_opts) && (:dest_name ∈ valid_keys) && (action ≠ :command_flag)
new_arg.dest_name = dest_name
end
check_dest_name(dest_name)
set_if_valid(k, x) = k ∈ valid_keys && setfield!(new_arg, k, x)
set_if_valid(:arg_type, arg_type)
set_if_valid(:default, deepcopy(default))
set_if_valid(:constant, deepcopy(constant))
set_if_valid(:range_tester, range_tester)
set_if_valid(:required, required)
set_if_valid(:help, help)
set_if_valid(:metavar, metavar)
set_if_valid(:eval_arg, eval_arg)
if !is_flag
isempty(new_arg.metavar) && (new_arg.metavar = auto_metavar(new_arg.dest_name, is_opt))
check_metavar(new_arg.metavar)
end
if is_command_action(action)
new_arg.dest_name = cmd_dest_name
new_arg.arg_type = AbstractString
new_arg.constant = cmd_name
new_arg.metavar = cmd_name
cmd_prog_hint = get_cmd_prog_hint(new_arg)
end
if is_flag
if action == :store_true
new_arg.arg_type = Bool
new_arg.default = false
new_arg.constant = true
elseif action == :store_false
new_arg.arg_type = Bool
new_arg.default = true
new_arg.constant = false
elseif action == :count_invocations
new_arg.arg_type = Int
new_arg.default = 0
elseif action == :store_const
check_default_type(new_arg.default, new_arg.arg_type)
check_default_type(new_arg.constant, new_arg.arg_type)
new_arg.default = convert_default(new_arg.arg_type, new_arg.default)
elseif action == :append_const
check_default_type(new_arg.constant, new_arg.arg_type)
if :arg_type ∉ supplied_opts
new_arg.arg_type = typeof(new_arg.constant)
end
check_default_type_multi(new_arg.default, new_arg.arg_type)
new_arg.default = convert_default_multi(new_arg.arg_type, new_arg.default)
elseif action == :command_flag
# nothing to do
elseif action == :show_help || action == :show_version
# nothing to do
else
found_a_bug()
end
else
arg_type = new_arg.arg_type
range_tester = new_arg.range_tester
default = new_arg.default
if !is_multi_action(new_arg.action) && !is_multi_nargs(new_arg.nargs)
check_default_type(default, arg_type)
check_range_default(default, range_tester)
new_arg.default = convert_default(arg_type, default)
elseif !is_multi_action(new_arg.action) || !is_multi_nargs(new_arg.nargs)
check_default_type_multi(default, arg_type)
check_range_default_multi(default, range_tester)
new_arg.default = convert_default_multi(arg_type, default)
else
check_default_type_multi2(default, arg_type)
check_range_default_multi2(default, range_tester)
new_arg.default = convert_default_multi2(arg_type, default)
end
if is_opt && nargs.desc == :?
constant = new_arg.constant
check_default_type(constant, arg_type)
check_range_default(constant, range_tester)
new_arg.constant = convert_default(arg_type, constant)
end
end
if action == :command_arg
for f in settings.args_table.fields
if f.action == :command_arg
new_arg.fake = true
break
end
end
end
check_arg_makes_sense(settings, new_arg)
check_conflicts_with_commands(settings, new_arg, false)
if force_override
override_duplicates!(settings.args_table.fields, new_arg)
else
check_for_duplicates(settings.args_table.fields, new_arg)
end
push!(settings.args_table.fields, new_arg)
is_command_action(action) && add_command!(settings, cmd_name, cmd_prog_hint, force_override)
return
end
function add_command!(settings::ArgParseSettings,
command::AbstractString,
prog_hint::AbstractString,
force_override::Bool)
haskey(settings, command) && serror("command $command already added")
if force_override
override_conflicts_with_commands!(settings, command)
else
check_conflicts_with_commands(settings, command)
end
settings[command] = ArgParseSettings()
ss = settings[command]
ss.prog = "$(isempty(settings.prog) ? "<PROGRAM>" : settings.prog) $prog_hint"
ss.description = ""
ss.preformatted_description = settings.preformatted_description
ss.epilog = ""
ss.preformatted_epilog = settings.preformatted_epilog
ss.usage = ""
ss.version = settings.version
ss.add_help = settings.add_help
ss.add_version = settings.add_version
ss.autofix_names = settings.autofix_names
ss.fromfile_prefix_chars = settings.fromfile_prefix_chars
ss.error_on_conflict = settings.error_on_conflict
ss.suppress_warnings = settings.suppress_warnings
ss.allow_ambiguous_opts = settings.allow_ambiguous_opts
ss.exc_handler = settings.exc_handler
ss.exit_after_help = settings.exit_after_help
return ss
end
autogen_group_name(desc::AbstractString) = "#$(hash(desc))"
add_arg_group!(settings::ArgParseSettings, desc::AbstractString;
exclusive::Bool = false, required::Bool = false) =
_add_arg_group!(settings, desc, autogen_group_name(desc), true, exclusive, required)
"""
add_arg_group!(settings, description, [name , [set_as_default]]; keywords...)
This function adds an argument group to the argument table in `settings`. The `description` is a
`String` used in the help screen as a title for that group. The `name` is a unique name which can be
provided to refer to that group at a later time.
Groups can be declared to be mutually exclusive and/or required, see below.
After invoking this function, all subsequent invocations of the [`@add_arg_table!`](@ref) macro and
[`add_arg_table!`](@ref) function will use the new group as the default, unless `set_as_default` is
set to `false` (the default is `true`, and the option can only be set if providing a `name`).
Therefore, the most obvious usage pattern is: for each group, add it and populate the argument
table of that group. Example:
```julia-repl
julia> settings = ArgParseSettings();
julia> add_arg_group!(settings, "custom group");
julia> @add_arg_table! settings begin
"--opt"
"arg"
end;
julia> parse_args(["--help"], settings)
usage: <command> [--opt OPT] [-h] [arg]
optional arguments:
-h, --help show this help message and exit
custom group:
--opt OPT
arg
```
As seen from the example, new groups are always added at the end of existing ones.
The `name` can also be passed as a `Symbol`. Forbidden names are the standard groups names
(`"command"`, `"positional"` and `"optional"`) and those beginning with a hash character `'#'`.
In order to declare a group as mutually exclusive, use the keyword `exclusive = true`. Mutually
exclusive groups can only contain options, not arguments nor commands, and parsing will fail if more
than one option from the group is provided.
A group can be declared as required using the `required = true` keyword, in which case at least one
option or positional argument or command from the group must be provided.
"""
function add_arg_group!(settings::ArgParseSettings,
desc::AbstractString,
tag::Union{AbstractString,Symbol},
set_as_default::Bool = true;
exclusive::Bool = false,
required::Bool = false
)
name = string(tag)
check_group_name(name)
_add_arg_group!(settings, desc, name, set_as_default, exclusive, required)
end
function _add_arg_group!(settings::ArgParseSettings,
desc::AbstractString,
name::AbstractString,
set_as_default::Bool,
exclusive::Bool,
required::Bool
)
already_added = any(ag->ag.name==name, settings.args_groups)
already_added || push!(settings.args_groups, ArgParseGroup(name, desc, exclusive, required))
set_as_default && (settings.default_group = name)
return settings
end
"""
set_default_arg_group!(settings, [name])
Set the default group for subsequent invocations of the [`@add_arg_table!`](@ref) macro and
[`add_arg_table!`](@ref) function. `name` is a `String`, and must be one of the standard group names
(`"command"`, `"positional"` or `"optional"`) or one of the user-defined names given in
`add_arg_group!` (groups with no assigned name cannot be used with this function).
If `name` is not provided or is the empty string `""`, then the default behavior is reset (i.e.
arguments will be automatically assigned to the standard groups). The `name` can also be passed as a
`Symbol`.
"""
function set_default_arg_group!(settings::ArgParseSettings, name::Union{AbstractString,Symbol} = "")
name = string(name)
startswith(name, '#') && serror("invalid group name: $name (begins with #)")
isempty(name) && (settings.default_group = ""; return)
found = any(ag->ag.name==name, settings.args_groups)
found || serror("group $name not found")
settings.default_group = name
return
end
# import_settings! & friends
function override_conflicts_with_commands!(settings::ArgParseSettings, new_cmd::AbstractString)
ids0 = Int[]
for ia in 1:length(settings.args_table.fields)
a = settings.args_table.fields[ia]
new_cmd == a.dest_name && push!(ids0, ia)
end
while !isempty(ids0)
splice!(settings.args_table.fields, pop!(ids0))
end
end
function override_duplicates!(args::Vector{ArgParseField}, new_arg::ArgParseField)
ids0 = Int[]
for (ia,a) in enumerate(args)
if (a.dest_name == new_arg.dest_name) &&
((a.arg_type ≠ new_arg.arg_type) ||
(is_multi_action(a.action) && !is_multi_action(new_arg.action)) ||
(!is_multi_action(a.action) && is_multi_action(new_arg.action)))
# unsolvable conflict, mark for deletion
push!(ids0, ia)
continue
end
if is_arg(a) && is_arg(new_arg) && !(is_cmd(a) && is_cmd(new_arg)) &&
a.metavar == new_arg.metavar
# unsolvable conflict, mark for deletion
push!(ids0, ia)
continue
end
# delete conflicting command aliases for different commands
if is_cmd(a) && is_cmd(new_arg) && a.constant ≠ new_arg.constant
ids = Int[]
for (ial1, al1) in enumerate(a.cmd_aliases)
if al1 == new_arg.constant
push!(ids, ial1)
else
for al2 in new_arg.cmd_aliases
al1 == al2 && push!(ids, ial1)
end
end
end
while !isempty(ids)
splice!(a.cmd_aliases, pop!(ids))
end
end
if is_arg(a) || is_arg(new_arg)
# not an option, skip
continue
end
if is_cmd(a) && is_cmd(new_arg) && a.constant == new_arg.constant && !is_arg(a)
is_arg(new_arg) && found_a_bug() # this is ensured by check_settings_are_compatible
# two command flags with the same command -> should have already been taken care of,
# by either check_settings_are_compatible or merge_commands!
continue
end
# delete conflicting long options
ids = Int[]
for il1 = 1:length(a.long_opt_name), l2 in new_arg.long_opt_name
l1 = a.long_opt_name[il1]
l1 == l2 && push!(ids, il1)
end
while !isempty(ids)
splice!(a.long_opt_name, pop!(ids))
end
# delete conflicting short options
ids = Int[]
for is1 in 1:length(a.short_opt_name), s2 in new_arg.short_opt_name
s1 = a.short_opt_name[is1]
s1 == s2 && push!(ids, is1)
end
while !isempty(ids)
splice!(a.short_opt_name, pop!(ids))
end
# if everything was deleted, remove the field altogether
# (i.e. mark it for deletion)
isempty(a.long_opt_name) && isempty(a.short_opt_name) && push!(ids0, ia)
end
# actually remove the marked fields
while !isempty(ids0)
splice!(args, pop!(ids0))
end
end
function check_settings_are_compatible(settings::ArgParseSettings, other::ArgParseSettings)
table = settings.args_table
otable = other.args_table
for a in otable.fields
check_conflicts_with_commands(settings, a, true)
settings.error_on_conflict && check_for_duplicates(table.fields, a)
end
for (subk, subs) in otable.subsettings
settings.error_on_conflict && check_conflicts_with_commands(settings, subk)
haskey(settings, subk) && check_settings_are_compatible(settings[subk], subs)
end
return true
end
function merge_commands!(fields::Vector{ArgParseField}, ofields::Vector{ArgParseField})
oids = Int[]
for a in fields, ioa = 1:length(ofields)
oa = ofields[ioa]
if is_cmd(a) && is_cmd(oa) && a.constant == oa.constant
is_arg(a) ≠ is_arg(oa) && found_a_bug() # ensured by check_settings_are_compatible
for l in oa.long_opt_name
l ∈ a.long_opt_name || push!(a.long_opt_name, l)
end
for s in oa.short_opt_name
s ∈ a.short_opt_name || push!(a.short_opt_name, s)
end
for al in oa.cmd_aliases
al ∈ a.cmd_aliases || push!(a.cmd_aliases, al)
end
a.group = oa.group # note: the group may not be present yet, but it will be
# added later
push!(oids, ioa)
end
end
# we return the merged ofields indices, since we still need to use them for overriding options
# before we actually remove them
return oids
end
function fix_commands_fields!(fields::Vector{ArgParseField})
cmd_found = false
for a in fields
if is_arg(a) && is_cmd(a)
a.fake = cmd_found
cmd_found = true
end
end
end
"""
import_settings!(settings, other_settings [,args_only])
Imports `other_settings` into `settings`, where both are [`ArgParseSettings`](@ref) objects. If
`args_only` is `true` (this is the default), only the argument table will be imported; otherwise,
the default argument group will also be imported, and all general settings except `prog`,
`description`, `epilog`, `usage` and `version`.
Sub-settings associated with commands will also be imported recursively; the `args_only` setting
applies to those as well. If there are common commands, their sub-settings will be merged.
While importing, conflicts may arise: if `settings.error_on_conflict` is `true`, this will result in
an error, otherwise conflicts will be resolved in favor of `other_settings` (see the
[Conflicts and overrides](@ref) section for a detailed discussion of how conflicts are handled).
Argument groups will also be imported; if two groups in `settings` and `other_settings` match, they
are merged (groups match either by name, or, if unnamed, by their description).
Note that the import will have effect immediately: any subsequent modification of `other_settings`
will not have any effect on `settings`.
This function can be used at any time.
"""
function import_settings!(settings::ArgParseSettings,
other::ArgParseSettings;
args_only::Bool = true)
check_settings_are_compatible(settings, other)
fields = settings.args_table.fields
ofields = deepcopy(other.args_table.fields)
merged_oids = merge_commands!(fields, ofields)
if !settings.error_on_conflict
for a in ofields
override_duplicates!(fields, a)
end
for (subk, subs) in other.args_table.subsettings
override_conflicts_with_commands!(settings, subk)
end
end
while !isempty(merged_oids)
splice!(ofields, pop!(merged_oids))
end
append!(fields, ofields)
for oag in other.args_groups
skip = false
for ag in settings.args_groups
# TODO: merge groups in some cases
if oag.name == ag.name
skip = true
break
end
end
skip && continue
push!(settings.args_groups, deepcopy(oag))
end
fix_commands_fields!(fields)
if !args_only
settings.add_help = other.add_help
settings.add_version = other.add_version
settings.error_on_conflict = other.error_on_conflict
settings.suppress_warnings = other.suppress_warnings
settings.exc_handler = other.exc_handler
settings.allow_ambiguous_opts = other.allow_ambiguous_opts
settings.commands_are_required = other.commands_are_required
settings.default_group = other.default_group
settings.preformatted_description = other.preformatted_description
settings.preformatted_epilog = other.preformatted_epilog
settings.fromfile_prefix_chars = other.fromfile_prefix_chars
settings.autofix_names = other.autofix_names
settings.exit_after_help = other.exit_after_help
end
for (subk, subs) in other.args_table.subsettings
cmd_prog_hint = ""
for oa in other.args_table.fields
if is_cmd(oa) && oa.constant == subk
cmd_prog_hint = get_cmd_prog_hint(oa)
break
end
end
if !haskey(settings, subk)
add_command!(settings, subk, cmd_prog_hint, !settings.error_on_conflict)
elseif !isempty(cmd_prog_hint)
settings[subk].prog = "$(settings.prog) $cmd_prog_hint"
end
import_settings!(settings[subk], subs, args_only=args_only)
end
return settings
end
"""
@project_version
@project_version(filename::String...)
Reads the version from the Project.toml file at the given filename, at compile time.
If no filename is given, defaults to `Base.current_project()`.
If multiple strings are given, they will be joined with `joinpath`.
Intended for use with the [`ArgParseSettings`](@ref) constructor,
to keep the settings version in sync with the project version.
## Example
```julia
ArgParseSettings(add_version = true, version = @project_version)
```
"""
macro project_version(filename::Vararg{String})
project_version(isempty(filename) ? Base.current_project() : joinpath(filename...))
end
function project_version(filename::AbstractString)::String
re = r"^version\s*=\s*\"(.*)\"\s*$"
for line in eachline(filename)
if startswith(line, "[")
break
end
if !occursin(re, line)
continue
end
return match(re, line)[1]
end
throw(ArgumentError("Could not find a version in the file at $(filename)"))
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 2583 | # test 01: minimal options/arguments, auto-generated help/version;
# function version of add_arg_table!
@testset "test 01" begin
function ap_settings1()
s = ArgParseSettings()
@add_arg_table! s begin
"--opt1" # an option (will take an argument)
"--opt2", "-o" # another option, with short form
"arg1" # a positional argument
end
s.exc_handler = ArgParse.debug_handler
return s
end
function ap_settings1b()
s = ArgParseSettings(exc_handler = ArgParse.debug_handler)
add_arg_table!(s,
"--opt1",
["--opt2", "-o"],
"arg1")
return s
end
for s = [ap_settings1(), ap_settings1b()]
ap_test1(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--opt1 OPT1] [-o OPT2] [arg1]
positional arguments:
arg1
optional arguments:
--opt1 OPT1
-o, --opt2 OPT2
"""
@test ap_test1([]) == Dict{String,Any}("opt1"=>nothing, "opt2"=>nothing, "arg1"=>nothing)
@test ap_test1(["arg"]) == Dict{String,Any}("opt1"=>nothing, "opt2"=>nothing, "arg1"=>"arg")
@test ap_test1(["--opt1", "X", "-o=5", "--", "-arg"]) == Dict{String,Any}("opt1"=>"X", "opt2"=>"5", "arg1"=>"-arg")
@test ap_test1(["--opt1", ""]) == Dict{String,Any}("opt1"=>"", "opt2"=>nothing, "arg1"=>nothing)
@ap_test_throws ap_test1(["--opt1", "X", "-o=5", "-arg"])
@test ap_test1(["--opt1=", "--opt2=5"]) == Dict{String,Any}("opt1"=>"", "opt2"=>"5", "arg1"=>nothing)
@test ap_test1(["-o", "-2"]) == Dict{String,Any}("opt1"=>nothing, "opt2"=>"-2", "arg1"=>nothing)
@ap_test_throws ap_test1(["--opt", "3"]) # ambiguous
@ap_test_throws ap_test1(["-o"])
@ap_test_throws ap_test1(["--opt1"])
@aps_test_throws @add_arg_table!(s, "--opt1") # long option already added
@aps_test_throws @add_arg_table!(s, "-o") # short option already added
end
# test malformed tables
function ap_settings1c()
@aps_test_throws @add_arg_table! begin
"-a"
end
s = ArgParseSettings(exc_handler = ArgParse.debug_handler)
@aps_test_throws add_arg_table!(s, Dict(:action => :store_true), "-a")
@test_addtable_failure s begin
action = :store_true
"-a"
end
@test_addtable_failure s begin
action => :store_true
end
@aps_test_throws add_arg_table!(s, "-a", Dict(:wat => :store_true))
@aps_test_throws @add_arg_table! s begin
"-a"
wat => :store_true
end
end
ap_settings1c()
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 11941 | # test 02: version information, default values, flags,
# options with types, optional arguments, variable
# number of arguments;
# function version of add_arg_table!
@testset "test 02" begin
function ap_settings2()
s = ArgParseSettings(description = "Test 2 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--opt1"
nargs = '?' # '?' means optional argument
arg_type = Int # only Int arguments allowed
default = 0 # this is used when the option is not passed
constant = 1 # this is used if --opt1 is paseed with no argument
help = "an option"
"-O"
arg_type = Symbol
default = :xyz
help = "another option"
"--flag", "-f"
action = :store_true # this makes it a flag
help = "a flag"
"--karma", "-k"
action = :count_invocations # increase a counter each time the option is given
help = "increase karma"
"arg1"
nargs = 2 # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once"
required = true
"arg2"
nargs = '*' # eats up as many arguments as possible before an option
default = Any["no_arg_given"] # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
help = "second argument, eats up " *
"as many items as possible " *
"before an option"
end
return s
end
function ap_settings2b()
s = ArgParseSettings(description = "Test 2 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
add_arg_table!(s,
"--opt1", Dict(
:nargs => '?', # '?' means optional argument
:arg_type => Int, # only Int arguments allowed
:default => 0, # this is used when the option is not passed
:constant => 1, # this is used if --opt1 is paseed with no argument
:help => "an option"),
["-O"], Dict(
:arg_type => Symbol,
:default => :xyz,
:help => "another option"),
["--flag", "-f"], Dict(
:action => :store_true, # this makes it a flag
:help => "a flag"),
["--karma", "-k"], Dict(
:action => :count_invocations, # increase a counter each time the option is given
:help => "increase karma"),
"arg1", Dict(
:nargs => 2, # eats up two arguments; puts the result in a Vector
:help => "first argument, two " *
"entries at once",
:required => true),
"arg2", Dict(
:nargs => '*', # eats up as many arguments as possible before an option
:default => Any["no_arg_given"], # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
:help => "second argument, eats up " *
"as many items as possible " *
"before an option")
)
return s
end
function ap_settings2c()
s = ArgParseSettings(description = "Test 2 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
@add_arg_table!(s
, "--opt1"
, nargs = '?' # '?' means optional argument
, arg_type = Int # only Int arguments allowed
, default = 0 # this is used when the option is not passed
, constant = 1 # this is used if --opt1 is paseed with no argument
, help = "an option"
, "-O"
, arg_type = Symbol
, default = :xyz
, help = "another option"
, ["--flag", "-f"]
, action = :store_true # this makes it a flag
, help = "a flag"
, ["--karma", "-k"]
, action = :count_invocations # increase a counter each time the option is given
, help = "increase karma"
, "arg1"
, nargs = 2 # eats up two arguments; puts the result in a Vector
, help = "first argument, two " *
"entries at once"
, required = true
, "arg2"
, nargs = '*' # eats up as many arguments as possible before an option
, default = Any["no_arg_given"] # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
, help = "second argument, eats up " *
"as many items as possible " *
"before an option"
)
return s
end
function ap_settings2d()
s = ArgParseSettings(description = "Test 2 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
("--opt1";
nargs = '?'; # '?' means optional argument
arg_type = Int; # only Int arguments allowed
default = 0; # this is used when the option is not passed
constant = 1; # this is used if --opt1 is paseed with no argument
help = "an option"),
("-O";
arg_type = Symbol;
default = :xyz;
help = "another option"),
(["--flag", "-f"];
action = :store_true; # this makes it a flag
help = "a flag")
(["--karma", "-k"];
action = :count_invocations; # increase a counter each time the option is given
help = "increase karma")
("arg1";
nargs = 2; # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once";
required = true)
("arg2";
nargs = '*'; # eats up as many arguments as possible before an option
default = Any["no_arg_given"]; # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
help = "second argument, eats up " *
"as many items as possible " *
"before an option")
end
return s
end
function ap_settings2e()
s = ArgParseSettings(description = "Test 2 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
@add_arg_table!(s,
"--opt1",
begin
nargs = '?' # '?' means optional argument
arg_type = Int # only Int arguments allowed
default = 0 # this is used when the option is not passed
constant = 1 # this is used if --opt1 is paseed with no argument
help = "an option"
end,
"-O",
begin
arg_type = Symbol
default = :xyz
help = "another option"
end,
["--flag", "-f"],
begin
action = :store_true # this makes it a flag
help = "a flag"
end,
["--karma", "-k"],
begin
action = :count_invocations # increase a counter each time the option is given
help = "increase karma"
end,
"arg1",
begin
nargs = 2 # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once"
required = true
end,
"arg2",
begin
nargs = '*' # eats up as many arguments as possible before an option
default = Any["no_arg_given"] # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
help = "second argument, eats up " *
"as many items as possible " *
"before an option"
end)
return s
end
for s = [ap_settings2(), ap_settings2b(), ap_settings2c(), ap_settings2d(), ap_settings2e()]
ap_test2(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--opt1 [OPT1]] [-O O] [-f] [-k] arg1 arg1
[arg2...]
Test 2 for ArgParse.jl
positional arguments:
arg1 first argument, two entries at once
arg2 second argument, eats up as many items as possible
before an option (default: Any["no_arg_given"])
optional arguments:
--opt1 [OPT1] an option (type: $Int, default: 0, without arg: 1)
-O O another option (type: $Symbol, default: :xyz)
-f, --flag a flag
-k, --karma increase karma
Have fun!
"""
@test stringversion(s) == "Version 1.0\n"
@ap_test_throws ap_test2([])
@test ap_test2(["X", "Y"]) == Dict{String,Any}("opt1"=>0, "O"=>:xyz, "flag"=>false, "karma"=>0, "arg1"=>Any["X", "Y"], "arg2"=>Any["no_arg_given"])
@test ap_test2(["X", "Y", "-k", "-f", "Z", "--karma", "--opt"]) == Dict{String,Any}("opt1"=>1, "O"=>:xyz, "flag"=>true, "karma"=>2, "arg1"=>Any["X", "Y"], "arg2"=>Any["Z"])
@test ap_test2(["X", "Y", "--opt", "-k", "-f", "Z", "--karma"]) == Dict{String,Any}("opt1"=>1, "O"=>:xyz, "flag"=>true, "karma"=>2, "arg1"=>Any["X", "Y"], "arg2"=>Any["Z"])
@test ap_test2(["X", "Y", "--opt", "--karma", "-O", "XYZ", "-f", "Z", "-k"]) == Dict{String,Any}("opt1"=>1, "O"=>:XYZ, "flag"=>true, "karma"=>2, "arg1"=>Any["X", "Y"], "arg2"=>Any["Z"])
@test ap_test2(["--opt", "-3", "X", "Y", "-k", "-f", "Z", "-O", "a b c", "--karma"]) == Dict{String,Any}("opt1"=>-3, "O"=>Symbol("a b c"), "flag"=>true, "karma"=>2, "arg1"=>Any["X", "Y"], "arg2"=>Any["Z"])
@ap_test_throws ap_test2(["--opt"])
@ap_test_throws ap_test2(["--opt="])
@ap_test_throws ap_test2(["--opt", "", "X", "Y"])
@ap_test_throws ap_test2(["--opt", "1e-2", "X", "Y"])
@aps_test_throws @add_arg_table!(s, "required_arg_after_optional_args", required = true)
# wrong default
@aps_test_throws @add_arg_table!(s, "--opt", arg_type = Int, default = 1.5)
@aps_test_throws @add_arg_table!(s, "--opt3", arg_type = Function, default = "string")
# wrong range tester
@aps_test_throws @add_arg_table!(s, "--opt", arg_type = Int, range_tester = x->string(x), default = 1)
@aps_test_throws @add_arg_table!(s, "--opt", arg_type = Int, range_tester = x->sqrt(x)<1, default = -1)
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 8501 | # test 03: dest_name, metavar, range_tester, alternative
# actions, custom parser
struct CustomType
end
@testset "test 03" begin
function ArgParse.parse_item(::Type{CustomType}, x::AbstractString)
@assert x == "custom"
return CustomType()
end
Base.show(io::IO, ::Type{CustomType}) = print(io, "CustomType")
Base.show(io::IO, c::CustomType) = print(io, "CustomType()")
function ap_settings3()
s = ArgParseSettings("Test 3 for ArgParse.jl",
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--opt1"
action = :append_const # appends 'constant' to 'dest_name'
arg_type = String
constant = "O1"
dest_name = "O_stack" # this changes the destination
help = "append O1"
"--opt2"
action = :append_const
arg_type = String
constant = "O2"
dest_name = "O_stack" # same dest_name as opt1, different constant
help = "append O2"
"-k"
action = :store_const # stores constant if given, default otherwise
default = 0
constant = 42
help = "provide the answer"
"-u"
action = :store_const # stores constant if given, default otherwise
default = 0
constant = 42.0
help = "provide the answer as floating point"
"--array"
default = [7, 3, 2]
arg_type = Vector{Int}
eval_arg = true # enables evaluation of the argument. NOTE: security risk!
help = "create an array"
"--custom"
default = CustomType()
arg_type = CustomType # uses the user-defined version of ArgParse.parse_item
help = "the only accepted argument is \"custom\""
"--oddint"
default = 1
arg_type = Int
range_tester = x->(isodd(x) || error("not odd")) # range error ≡ false
help = "an odd integer"
"--collect"
action = :append_arg
arg_type = Int
metavar = "C"
help = "collect things"
"--awkward-option"
nargs = '+' # eats up as many argument as found (at least 1)
action = :append_arg # argument chunks are appended when the option is
# called repeatedly
dest_name = "awk"
range_tester = (x->x=="X"||x=="Y") # each argument must be either "X" or "Y"
default = [["X"]]
metavar = "XY"
help = "either X or Y; all XY's are " *
"stored in chunks"
end
return s
end
let s = ap_settings3()
ap_test3(args) = parse_args(args, s)
## ugly workaround for the change of printing Vectors in julia 1.6,
## from Array{Int,1} to Vector{Int}
array_help_lines = if string(Vector{Any}) == "Vector{Any}"
"""
--array ARRAY create an array (type: Vector{$Int}, default:
$([7, 3, 2]))
"""
else
"""
--array ARRAY create an array (type: Array{$Int,1},
default: $([7, 3, 2]))
"""
end
array_help_lines = array_help_lines[1:end-1] # remove an extra newline
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--opt1] [--opt2] [-k] [-u] [--array ARRAY]
[--custom CUSTOM] [--oddint ODDINT]
[--collect C] [--awkward-option XY [XY...]]
Test 3 for ArgParse.jl
optional arguments:
--opt1 append O1
--opt2 append O2
-k provide the answer
-u provide the answer as floating point
$array_help_lines
--custom CUSTOM the only accepted argument is "custom" (type:
CustomType, default: CustomType())
--oddint ODDINT an odd integer (type: $Int, default: 1)
--collect C collect things (type: $Int)
--awkward-option XY [XY...]
either X or Y; all XY's are stored in chunks
(default: $(Vector{Any})[["X"]])
"""
@test ap_test3([]) == Dict{String,Any}("O_stack"=>String[], "k"=>0, "u"=>0, "array"=>[7, 3, 2], "custom"=>CustomType(), "oddint"=>1, "collect"=>[], "awk"=>Any[Any["X"]])
@test ap_test3(["--opt1", "--awk", "X", "X", "--opt2", "--opt2", "-k", "--coll", "5", "-u", "--array=[4]", "--custom", "custom", "--collect", "3", "--awkward-option=Y", "X", "--opt1", "--oddint", "-1"]) ==
Dict{String,Any}("O_stack"=>String["O1", "O2", "O2", "O1"], "k"=>42, "u"=>42.0, "array"=>[4], "custom"=>CustomType(), "oddint"=>-1, "collect"=>[5, 3], "awk"=>Any[Any["X"], Any["X", "X"], Any["Y", "X"]])
@ap_test_throws ap_test3(["X"])
@ap_test_throws ap_test3(["--awk", "Z"])
@ap_test_throws ap_test3(["--awk", "-2"])
@ap_test_throws ap_test3(["--array", "7"])
@ap_test_throws ap_test3(["--custom", "default"])
@ap_test_throws ap_test3(["--oddint", "0"])
@ap_test_throws ap_test3(["--collect", "0.5"])
# invalid option name
@aps_test_throws @add_arg_table!(s, "-2", action = :store_true)
# wrong constants
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_const, arg_type = Int, default = 1, constant = 1.5)
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_const, arg_type = Int, constant = 1.5)
# wrong defaults
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, arg_type = Int, default = String["hello"])
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, nargs = '+', arg_type = Int, default = Vector{Float64}[[1.5]])
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_arg, nargs = '+', arg_type = Int, default = [1.5])
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_arg, nargs = '+', arg_type = Int, default = 1)
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, arg_type = Int, range_tester=x->x<=1, default = Int[0, 1, 2])
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, nargs = '+', arg_type = Int, range_tester=x->x<=1, default = Vector{Int}[[1,1],[0,2]])
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_arg, nargs = '+', range_tester = x->x<=1, default = [1.5])
# no constants
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_const, arg_type = Int, default = 1)
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_const, arg_type = Int)
# incompatible action
@aps_test_throws @add_arg_table!(s, "--opt3", action = :store_const, arg_type = String, constant = "O3", dest_name = "O_stack", help = "append O3")
# wrong range tester
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, arg_type = Int, range_tester=x->string(x), default = Int[0, 1, 2])
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, nargs = '+', arg_type = Int, range_tester=x->string(x), default = Vector{Int}[[1,1],[0,2]])
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_arg, nargs = '+', range_tester = x->string(x), default = [1.5])
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_arg, nargs = '+', range_tester = x->sqrt(x)<2, default = [-1.5])
@aps_test_throws @add_arg_table!(s, "--opt", action = :append_arg, nargs = '+', arg_type = Int, range_tester=x->sqrt(x)<2, default = Vector{Int}[[1,1],[0,-2]])
# allow ambiguous options
s.allow_ambiguous_opts = true
@add_arg_table!(s, "-2", action = :store_true)
@test ap_test3([]) == Dict{String,Any}("O_stack"=>String[], "k"=>0, "u"=>0, "array"=>[7, 3, 2], "custom"=>CustomType(), "oddint"=>1, "collect"=>[], "awk"=>Vector{Any}[["X"]], "2"=>false)
@test ap_test3(["-2"]) == Dict{String,Any}("O_stack"=>String[], "k"=>0, "u"=>0, "array"=>[7, 3, 2], "custom"=>CustomType(), "oddint"=>1, "collect"=>[], "awk"=>Vector{Any}[["X"]], "2"=>true)
@test ap_test3(["--awk", "X", "-2"]) == Dict{String,Any}("O_stack"=>String[], "k"=>0, "u"=>0, "array"=>[7, 3, 2], "custom"=>CustomType(), "oddint"=>1, "collect"=>[], "awk"=>Vector{Any}[["X"], ["X"]], "2"=>true)
@ap_test_throws ap_test3(["--awk", "X", "-3"])
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 5660 | # test 04: manual help/version, import another parser
@testset "test 04" begin
function ap_settings4()
s0 = ArgParseSettings() # a "parent" structure e.g. one with some useful set of rules
# which we want to extend
# So we just add a simple table
@add_arg_table! s0 begin
"--parent-flag", "-o"
action = "store_true"
help = "parent flag"
"--flag"
action = "store_true"
help = "another parent flag"
"parent-argument"
help = "parent argument"
"will-be-overridden"
metavar = "ARG"
end
s = ArgParseSettings("Test 4 for ArgParse.jl",
add_help = false, # disable auto-add of --help option
version = "Version 1.0", # we set the version info, but --version won't be added
error_on_conflict = false, # do not error-out when trying to override an option
exc_handler = ArgParse.debug_handler)
import_settings!(s, s0) # now s has all of s0 arguments (except help/version)
@add_arg_table! s begin
"-o" # this will partially override s0's --parent-flag
action = :store_true
help = "child flag"
"--flag" # this will fully override s0's --flag
action = :store_true
help = "another child flag"
"-?", "--HELP", "--¡ḧëļṕ" # (almost) all characters allowed
action = :show_help # will invoke the help generator
help = "this will help you"
"-v", "--VERSION"
action = :show_version # will show version information
help = "show version information " *
"and exit"
"child-argument" # same metavar as "will-be-overridden"
metavar = "ARG"
help = "child argument"
end
return s
end
function ap_settings4b()
# same as ap_settings4(), but imports all settings
s0 = ArgParseSettings(add_help = false,
error_on_conflict = false,
exc_handler = ArgParse.debug_handler)
# So we just add a simple table
@add_arg_table! s0 begin
"--parent-flag", "-o"
action = "store_true"
help = "parent flag"
"--flag"
action = "store_true"
help = "another parent flag"
"parent-argument"
help = "parent argument"
"will-be-overridden"
metavar = "ARG"
end
s = ArgParseSettings("Test 4 for ArgParse.jl",
version = "Version 1.0")
import_settings!(s, s0, args_only=false)
@add_arg_table! s begin
"-o"
action = :store_true
help = "child flag"
"--flag"
action = :store_true
help = "another child flag"
"-?", "--HELP", "--¡ḧëļṕ"
action = :show_help
help = "this will help you"
"-v", "--VERSION"
action = :show_version
help = "show version information " *
"and exit"
"child-argument"
metavar = "ARG"
help = "child argument"
end
return s
end
for s = [ap_settings4(), ap_settings4b()]
ap_test4(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--parent-flag] [-o] [--flag] [-?] [-v]
[parent-argument] [ARG]
Test 4 for ArgParse.jl
positional arguments:
parent-argument parent argument
ARG child argument
optional arguments:
--parent-flag parent flag
-o child flag
--flag another child flag
-?, --HELP, --¡ḧëļṕ this will help you
-v, --VERSION show version information and exit
"""
@test stringversion(s) == "Version 1.0\n"
@test ap_test4([]) == Dict{String,Any}("parent-flag"=>false, "o"=>false, "flag"=>false, "parent-argument"=>nothing, "child-argument"=>nothing)
@test ap_test4(["-o", "X"]) == Dict{String,Any}("parent-flag"=>false, "o"=>true, "flag"=>false, "parent-argument"=>"X", "child-argument"=>nothing)
@ap_test_throws ap_test4(["-h"])
# same metavar as another argument
s.error_on_conflict = true
@aps_test_throws @add_arg_table!(s, "other-arg", metavar="parent-argument")
end
function ap_settings4_base()
s = ArgParseSettings("Test 4 for ArgParse.jl",
add_help = false,
version = "Version 1.0",
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"-o"
action = :store_true
help = "child flag"
"--flag"
action = :store_true
help = "another child flag"
end
return s
end
function ap_settings4_conflict1()
s0 = ArgParseSettings()
@add_arg_table! s0 begin
"--parent-flag", "-o"
action = "store_true"
help = "parent flag"
end
return s0
end
function ap_settings4_conflict2()
s0 = ArgParseSettings()
@add_arg_table! s0 begin
"--flag"
action = "store_true"
help = "another parent flag"
end
return s0
end
let s = ap_settings4_base()
for s0 = [ap_settings4_conflict1(), ap_settings4_conflict2()]
@aps_test_throws import_settings!(s, s0)
end
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 14687 | # test 05: commands & subtables
@testset "test 05" begin
function ap_settings5()
s = ArgParseSettings("Test 5 for ArgParse.jl",
exc_handler = ArgParse.debug_handler,
exit_after_help = false)
@add_arg_table! s begin
"run"
action = :command
help = "start running mode"
"jump", "ju", "J"
action = :command
help = "start jumping mode"
end
@add_arg_table! s["run"] begin
"--speed"
arg_type = Float64
default = 10.0
help = "running speed, in Å/month"
end
s["jump"].description = "Jump mode"
s["jump"].commands_are_required = false
s["jump"].autofix_names = true
@add_arg_table! s["jump"] begin
"--higher"
action = :store_true
help = "enhance jumping"
"--somersault", "-s"
action = :command
dest_name = "som"
help = "somersault jumping mode"
"--clap-feet", "-c"
action = :command
help = "clap feet jumping mode"
end
s["jump"]["som"].description = "Somersault jump mode"
@add_arg_table! s["jump"]["som"] begin
"-t"
nargs = '?'
arg_type = Int
default = 1
constant = 1
help = "twist a number of times"
"-b"
action = :store_true
help = "blink"
end
return s
end
let s = ap_settings5()
ap_test5(args; kw...) = parse_args(args, s; kw...)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) {run|jump}
Test 5 for ArgParse.jl
commands:
run start running mode
jump start jumping mode (aliases: ju, J)
"""
@test stringhelp(s["run"]) == """
usage: $(basename(Base.source_path())) run [--speed SPEED]
optional arguments:
--speed SPEED running speed, in Å/month (type: Float64, default:
10.0)
"""
@test stringhelp(s["jump"]) == """
usage: $(basename(Base.source_path())) jump [--higher] [-s|-c]
Jump mode
commands:
-s, --somersault somersault jumping mode
-c, --clap-feet clap feet jumping mode
optional arguments:
--higher enhance jumping
"""
@test stringhelp(s["jump"]["som"]) == """
usage: $(basename(Base.source_path())) jump -s [-t [T]] [-b]
Somersault jump mode
optional arguments:
-t [T] twist a number of times (type: $Int, default: 1, without
arg: 1)
-b blink
"""
@ap_test_throws ap_test5([])
@noout_test ap_test5(["--help"]) ≡ nothing
@test ap_test5(["run", "--speed", "3"]) == Dict{String,Any}("%COMMAND%"=>"run", "run"=>Dict{String,Any}("speed"=>3.0))
@noout_test ap_test5(["jump", "--help"]) ≡ nothing
@test ap_test5(["jump"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>nothing))
@test ap_test5(["jump", "--higher", "--clap"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>true, "%COMMAND%"=>"clap_feet", "clap_feet"=>Dict{String,Any}()))
@test ap_test5(["ju", "--higher", "--clap"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>true, "%COMMAND%"=>"clap_feet", "clap_feet"=>Dict{String,Any}()))
@test ap_test5(["J", "--higher", "--clap"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>true, "%COMMAND%"=>"clap_feet", "clap_feet"=>Dict{String,Any}()))
@noout_test ap_test5(["jump", "--higher", "--clap", "--help"]) ≡ nothing
@noout_test ap_test5(["jump", "--higher", "--clap", "--help"], as_symbols = true) ≡ nothing
@ap_test_throws ap_test5(["jump", "--clap", "--higher"])
@test ap_test5(["jump", "--somersault"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>1, "b"=>false)))
@test ap_test5(["jump", "-s", "-t"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>1, "b"=>false)))
@test ap_test5(["jump", "-st"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>1, "b"=>false)))
@test ap_test5(["jump", "-sbt"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>1, "b"=>true)))
@test ap_test5(["jump", "-s", "-t2"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>2, "b"=>false)))
@test ap_test5(["jump", "-sbt2"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>2, "b"=>true)))
@test ap_test5(["ju", "-sbt2"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>2, "b"=>true)))
@test ap_test5(["J", "-sbt2"]) == Dict{String,Any}("%COMMAND%"=>"jump", "jump"=>Dict{String,Any}("higher"=>false, "%COMMAND%"=>"som", "som"=>Dict{String,Any}("t"=>2, "b"=>true)))
@noout_test ap_test5(["jump", "-sbht2"]) ≡ nothing
@ap_test_throws ap_test5(["jump", "-st2b"])
@ap_test_throws ap_test5(["jump", "-stb"])
@ap_test_throws ap_test5(["jump", "-sb-"])
@ap_test_throws ap_test5(["jump", "-s-b"])
@ap_test_throws ap_test5(["ju", "-s-b"])
@test ap_test5(["jump", "--higher"], as_symbols = true) == Dict{Symbol,Any}(:_COMMAND_=>:jump, :jump=>Dict{Symbol,Any}(:higher=>true, :_COMMAND_=>nothing))
@test ap_test5(["run", "--speed", "3"], as_symbols = true) == Dict{Symbol,Any}(:_COMMAND_=>:run, :run=>Dict{Symbol,Any}(:speed=>3.0))
# argument after command
@aps_test_throws @add_arg_table!(s, "arg_after_command")
# same name as command
@aps_test_throws @add_arg_table!(s, "run")
@aps_test_throws @add_arg_table!(s["jump"], "-c")
@aps_test_throws @add_arg_table!(s["jump"], "--somersault")
# same dest_name as command
@aps_test_throws @add_arg_table!(s["jump"], "--som")
@aps_test_throws @add_arg_table!(s["jump"], "-s", dest_name = "som")
# same name as command alias
@aps_test_throws @add_arg_table!(s, "ju")
@aps_test_throws @add_arg_table!(s, "J")
# new command with the same name as another one
@aps_test_throws @add_arg_table!(s, ["run", "R"], action = :command)
@aps_test_throws @add_arg_table!(s, "jump", action = :command)
# new command with the same name as another one's alias
@aps_test_throws @add_arg_table!(s, "ju", action = :command)
@aps_test_throws @add_arg_table!(s, "J", action = :command)
# new command with an alias which is the same as another command
@aps_test_throws @add_arg_table!(s, ["fast", "run"], action = :command)
@aps_test_throws @add_arg_table!(s, ["R", "jump"], action = :command)
# new command with an alias which is already in use
@aps_test_throws @add_arg_table!(s, ["R", "ju"], action = :command)
@aps_test_throws @add_arg_table!(s, ["R", "S", "J"], action = :command)
# alias overriding by a command name
@add_arg_table!(s, "J", action = :command, force_override = true, help = "the J command")
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) {run|jump|J}
Test 5 for ArgParse.jl
commands:
run start running mode
jump start jumping mode (aliases: ju)
J the J command
"""
# alias overriding by a command alias
@add_arg_table!(s, ["S", "ju"], action = :command, force_override = true, help = "the S command")
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) {run|jump|J|S}
Test 5 for ArgParse.jl
commands:
run start running mode
jump start jumping mode
J the J command
S the S command (aliases: ju)
"""
# cannot override a command name
@aps_test_throws @add_arg_table!(s, ["J", "R"], action = :command, force_override = true)
@aps_test_throws @add_arg_table!(s, ["R", "J"], action = :command, force_override = true)
# conflict between dest_name and a reserved Symbol
@add_arg_table!(s, "--COMMAND", dest_name="_COMMAND_")
@aps_test_throws ap_test5(["run", "--speed", "3"], as_symbols = true)
end
function ap_settings5b()
s0 = ArgParseSettings()
s = ArgParseSettings(error_on_conflict = false,
exc_handler = ArgParse.debug_handler,
exit_after_help = false)
@add_arg_table! s0 begin
"run", "R"
action = :command
help = "start running mode"
"jump", "ju"
action = :command
help = "start jumping mode"
"--time"
arg_type = String
default = "now"
metavar = "T"
help = "time at which to " *
"perform the command"
end
@add_arg_table! s0["run"] begin
"--speed"
arg_type = Float64
default = 10.
help = "running speed, in Å/month"
end
s0["jump"].description = "Jump mode"
s0["jump"].commands_are_required = false
s0["jump"].autofix_names = true
s0["jump"].add_help = false
add_arg_group!(s0["jump"], "modifiers", "modifiers")
set_default_arg_group!(s0["jump"])
@add_arg_table! s0["jump"] begin
"--higher"
action = :store_true
help = "enhance jumping"
group = "modifiers"
"--somersault"
action = :command
dest_name = "som"
help = "somersault jumping mode"
"--clap-feet", "-c"
action = :command
help = "clap feet jumping mode"
end
add_arg_group!(s0["jump"], "other")
@add_arg_table! s0["jump"] begin
"--help"
action = :show_help
help = "show this help message " *
"and exit"
end
s0["jump"]["som"].description = "Somersault jump mode"
@add_arg_table! s begin
"jump", "run", "J" # The "run" alias will be overridden
action = :command
help = "start jumping mode"
"fly", "R" # The "R" alias will be overridden
action = :command
help = "start flying mode"
# next opt will be overridden (same dest_name as s0's --time,
# incompatible arg_type)
"-T"
dest_name = "time"
arg_type = Int
end
s["jump"].autofix_names = true
s["jump"].add_help = false
add_arg_group!(s["jump"], "modifiers", "modifiers")
@add_arg_table! s["jump"] begin
"--lower"
action = :store_false
dest_name = "higher"
help = "reduce jumping"
end
set_default_arg_group!(s["jump"])
@add_arg_table! s["jump"] begin
"--clap-feet"
action = :command
help = "clap feet jumping mode"
"--som", "-s" # will be overridden (same dest_name as s0 command)
action = :store_true
help = "overridden"
"--somersault" # will be overridden (same option as s0 command)
action = :store_true
help = "overridden"
end
@add_arg_table! s["fly"] begin
"--glade"
action = :store_true
help = "glade mode"
end
s["jump"]["clap_feet"].add_version = true
@add_arg_table! s["jump"]["clap_feet"] begin
"--whistle"
action = :store_true
end
import_settings!(s, s0)
return s
end
let s = ap_settings5b()
ap_test5b(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--time T] {jump|fly|run}
commands:
jump start jumping mode (aliases: J, ju)
fly start flying mode
run start running mode (aliases: R)
optional arguments:
--time T time at which to perform the command (default: "now")
"""
@test stringhelp(s["jump"]) == """
usage: $(basename(Base.source_path())) jump [--lower] [--higher] [--help]
{-c|--somersault}
commands:
-c, --clap-feet clap feet jumping mode
--somersault somersault jumping mode
modifiers:
--lower reduce jumping
--higher enhance jumping
other:
--help show this help message and exit
"""
@ap_test_throws ap_test5b([])
@test ap_test5b(["fly"]) == Dict{String,Any}("%COMMAND%"=>"fly", "time"=>"now", "fly"=>Dict{String,Any}("glade"=>false))
@test ap_test5b(["jump", "--lower", "--clap"]) == Dict{String,Any}("%COMMAND%"=>"jump", "time"=>"now",
"jump"=>Dict{String,Any}("%COMMAND%"=>"clap_feet", "higher"=>false, "clap_feet"=>Dict{String,Any}("whistle"=>false)))
@test ap_test5b(["ju", "--lower", "--clap"]) == Dict{String,Any}("%COMMAND%"=>"jump", "time"=>"now",
"jump"=>Dict{String,Any}("%COMMAND%"=>"clap_feet", "higher"=>false, "clap_feet"=>Dict{String,Any}("whistle"=>false)))
@test ap_test5b(["J", "--lower", "--clap"]) == Dict{String,Any}("%COMMAND%"=>"jump", "time"=>"now",
"jump"=>Dict{String,Any}("%COMMAND%"=>"clap_feet", "higher"=>false, "clap_feet"=>Dict{String,Any}("whistle"=>false)))
@noout_test ap_test5b(["jump", "--lower", "--help"]) ≡ nothing
@noout_test ap_test5b(["jump", "--lower", "--clap", "--version"]) ≡ nothing
@ap_test_throws ap_test5b(["jump"])
@test ap_test5b(["run", "--speed=3"]) == Dict{String,Any}("%COMMAND%"=>"run", "time"=>"now", "run"=>Dict{String,Any}("speed"=>3.0))
@test ap_test5b(["R", "--speed=3"]) == Dict{String,Any}("%COMMAND%"=>"run", "time"=>"now", "run"=>Dict{String,Any}("speed"=>3.0))
end
let
s1 = @add_arg_table!(ArgParseSettings(), "run", action = :command)
s2 = @add_arg_table!(ArgParseSettings(), "--run", action = :store_true)
@aps_test_throws import_settings!(s1, s2)
@aps_test_throws import_settings!(s2, s1) # this fails since error_on_conflict=true
s2 = @add_arg_table!(ArgParseSettings(), ["R", "run"], action = :command)
@aps_test_throws import_settings!(s1, s2)
@aps_test_throws import_settings!(s2, s1) # this fails since error_on_conflict=true
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 4237 | # test 06: argument groups
@testset "test 06" begin
function ap_settings6()
s = ArgParseSettings("Test 6 for ArgParse.jl",
exc_handler = ArgParse.debug_handler)
add_arg_group!(s, "stack options")
@add_arg_table! s begin
"--opt1"
action = :append_const
arg_type = String
constant = "O1"
dest_name = "O_stack"
help = "append O1 to the stack"
"--opt2"
action = :append_const
arg_type = String
constant = "O2"
dest_name = "O_stack"
help = "append O2 to the stack"
end
add_arg_group!(s, "weird options", "weird")
set_default_arg_group!(s, "weird")
@add_arg_table! s begin
"--awkward-option"
nargs = '+'
action = :append_arg
dest_name = "awk"
arg_type = String
range_tester = (x->x=="X"||x=="Y")
metavar = "XY"
help = "either X or Y; all XY's are " *
"stored in chunks"
end
set_default_arg_group!(s)
@add_arg_table! s begin
"-k"
action = :store_const
default = 0
constant = 42
help = "provide the answer"
"--şİłłÿ"
nargs = 3
help = "an option with a silly name, " *
"which expects 3 arguments"
metavar = "☺"
group = "weird"
end
set_default_arg_group!(s, "weird")
@add_arg_table! s begin
"--rest"
nargs = 'R'
help = "an option which will consume " *
"all following arguments"
end
return s
end
let s = ap_settings6()
ap_test6(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--opt1] [--opt2]
[--awkward-option XY [XY...]] [-k]
[--şİłłÿ ☺ ☺ ☺] [--rest [REST...]]
Test 6 for ArgParse.jl
optional arguments:
-k provide the answer
stack options:
--opt1 append O1 to the stack
--opt2 append O2 to the stack
weird options:
--awkward-option XY [XY...]
either X or Y; all XY's are stored in chunks
--şİłłÿ ☺ ☺ ☺ an option with a silly name, which expects 3
arguments
--rest [REST...] an option which will consume all following
arguments
"""
@test ap_test6([]) == Dict{String,Any}("O_stack"=>String[], "k"=>0, "awk"=>Vector{Any}[], "şİłłÿ"=>Any[], "rest"=>[])
@test ap_test6(["--opt1", "--awk", "X", "X", "--opt2", "--opt2", "-k", "--awkward-option=Y", "X", "--opt1", "--şİł=-1", "-2", "-3"]) ==
Dict{String,Any}("O_stack"=>String["O1", "O2", "O2", "O1"], "k"=>42, "awk"=>Any[Any["X", "X"], Any["Y", "X"]], "şİłłÿ"=>["-1", "-2", "-3"], "rest"=>[])
@test ap_test6(["--opt1", "--awk", "X", "X", "--opt2", "--opt2", "--r", "-k", "--awkward-option=Y", "X", "--opt1", "--şİł", "-1", "-2", "-3"]) ==
Dict{String,Any}("O_stack"=>String["O1", "O2", "O2"], "k"=>0, "awk"=>Any[Any["X", "X"]], "şİłłÿ"=>[], "rest"=>Any["-k", "--awkward-option=Y", "X", "--opt1", "--şİł", "-1", "-2", "-3"])
@test ap_test6(["--opt1", "--awk", "X", "X", "--opt2", "--opt2", "--r=-k", "--awkward-option=Y", "X", "--opt1", "--şİł", "-1", "-2", "-3"]) ==
Dict{String,Any}("O_stack"=>String["O1", "O2", "O2"], "k"=>0, "awk"=>Any[Any["X", "X"]], "şİłłÿ"=>[], "rest"=>Any["-k", "--awkward-option=Y", "X", "--opt1", "--şİł", "-1", "-2", "-3"])
@ap_test_throws ap_test6(["X"])
@ap_test_throws ap_test6(["--awk"])
@ap_test_throws ap_test6(["--awk", "Z"])
@ap_test_throws ap_test6(["--şİł", "-1", "-2"])
@ap_test_throws ap_test6(["--şİł", "-1", "-2", "-3", "-4"])
# invalid groups
@aps_test_throws add_arg_group!(s, "invalid commands", "")
@aps_test_throws add_arg_group!(s, "invalid commands", "#invalid")
@aps_test_throws @add_arg_table!(s, "--opt", action = :store_true, group = "none")
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 2163 | # test 07: required options, line breaks in desc/epilog
@testset "test 07" begin
function ap_settings7()
s = ArgParseSettings(description = "Test 7 for ArgParse.jl\n\nTesting oxymoronic options",
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--oxymoronic", "-x"
required = true
help = "a required option"
"--opt"
required = false
help = "a true option"
"--flag", "-f"
action = :store_true
help = "a flag"
"-o"
required = true
help = "yet another oxymoronic option"
end
s.epilog = """
Example:\n
\n
\ua0\ua0<program> --oxymoronic X -o 1\n
\n
Not a particularly enlightening example, but
on the other hand this program does not really
do anything useful.
"""
return s
end
let s = ap_settings7()
ap_test7(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) -x OXYMORONIC [--opt OPT] [-f] -o O
Test 7 for ArgParse.jl
Testing oxymoronic options
optional arguments:
-x, --oxymoronic OXYMORONIC
a required option
--opt OPT a true option
-f, --flag a flag
-o O yet another oxymoronic option
Example:
<program> --oxymoronic X -o 1
Not a particularly enlightening example, but on the other hand this
program does not really do anything useful.
"""
@ap_test_throws ap_test7([])
@test ap_test7(["--oxymoronic=A", "-o=B"]) == Dict{String,Any}("oxymoronic"=>"A", "opt"=>nothing, "o"=>"B", "flag"=>false)
@ap_test_throws ap_test7(["--oxymoronic=A", "--opt=B"])
@ap_test_throws ap_test7(["--opt=A, -o=B"])
s.suppress_warnings = true
add_arg_table!(s, "-g", Dict(:action=>:store_true, :required=>true))
@test ap_test7(["--oxymoronic=A", "-o=B"]) == Dict{String,Any}("oxymoronic"=>"A", "opt"=>nothing, "o"=>"B", "flag"=>false, "g"=>false)
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 2588 | # test 08: read args from file, read version from project
@testset "test 08" begin
function ap_settings8a()
s = ArgParseSettings(fromfile_prefix_chars=['@'])
@add_arg_table! s begin
"--opt1" # an option (will take an argument)
"--opt2", "-o" # another option, with short form
"arg1" # a positional argument
end
s.exc_handler = ArgParse.debug_handler
return s
end
function ap_settings8b() # unicode
s = ArgParseSettings(fromfile_prefix_chars="@∘")
@add_arg_table! s begin
"--opt1" # an option (will take an argument)
"--opt2", "-o" # another option, with short form
"arg1" # a positional argument
end
s.exc_handler = ArgParse.debug_handler
return s
end
let s = ap_settings8a()
ap_test8(args) = parse_args(args, s)
@test ap_test8(["@args-file1"]) == Dict(
"opt1"=>nothing, "opt2"=>"y", "arg1"=>nothing)
@test ap_test8(["@args-file1", "arg"]) == Dict(
"opt1"=>nothing, "opt2"=>"y", "arg1"=>"arg")
@test ap_test8(["@args-file2"]) == Dict(
"opt1"=>"x", "opt2"=>"y", "arg1"=>nothing)
@test ap_test8(["@args-file2", "arg"]) == Dict(
"opt1"=>"x", "opt2"=>"y", "arg1"=>"arg")
end
let s = ap_settings8b()
ap_test8(args) = parse_args(args, s)
@test ap_test8(["∘args-file1"]) == Dict(
"opt1"=>nothing, "opt2"=>"y", "arg1"=>nothing)
@test ap_test8(["@args-file1", "arg"]) == Dict(
"opt1"=>nothing, "opt2"=>"y", "arg1"=>"arg")
@test ap_test8(["∘args-file2"]) == Dict(
"opt1"=>"x", "opt2"=>"y", "arg1"=>nothing)
@test ap_test8(["@args-file2", "arg"]) == Dict(
"opt1"=>"x", "opt2"=>"y", "arg1"=>"arg")
end
# not allowed
@ap_test_throws ArgParseSettings(fromfile_prefix_chars=['-'])
@ap_test_throws ArgParseSettings(fromfile_prefix_chars=['Å'])
@ap_test_throws ArgParseSettings(fromfile_prefix_chars=['8'])
# default project version
@test stringversion(ArgParseSettings(
add_version = true,
version = @project_version
)) == "1.0.0\n"
# project version from filepath
@test stringversion(ArgParseSettings(
add_version = true,
version = @project_version "Project.toml"
)) == "1.0.0\n"
# project version from expression that returns a filepath
@test stringversion(ArgParseSettings(
add_version = true,
version = @project_version(".", "Project.toml")
)) == "1.0.0\n"
# throws an error if the file doesn't contain a version
@test_throws ArgumentError ArgParse.project_version("args-file1")
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1722 | # test 09: preformatted desc/epilog
@testset "test 09" begin
function ap_settings9()
s = ArgParseSettings(description = """
Test 9 for ArgParse.jl
Testing preformatted description/epilog
1
1 1
1 2 1
1 3 3 1
""",
preformatted_description=true,
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--opt"
required = true
help = "a required option"
end
s.epilog = """
Example:
<program> --opt X
- one
- two
- three
"""
s.preformatted_epilog = true
return s
end
let s = ap_settings9()
ap_test7(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) --opt OPT
Test 9 for ArgParse.jl
Testing preformatted description/epilog
1
1 1
1 2 1
1 3 3 1
optional arguments:
--opt OPT a required option
Example:
<program> --opt X
- one
- two
- three
"""
@ap_test_throws ap_test7([])
@test ap_test7(["--opt=A"]) == Dict{String,Any}("opt"=>"A")
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 7125 | # test 10: multiple metavars
# function version of add_arg_table!
@testset "test 10" begin
function ap_settings10()
s = ArgParseSettings(description = "Test 10 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--opt1"
nargs => 2 # exactly 2 arguments must be specified
arg_type => Int # only Int arguments allowed
default => [0, 1] # this is used when the option is not passed
metavar => ["A", "B"] # two metavars for two arguments
help => "an option"
"--flag", "-f"
action := :store_true # this makes it a flag
help := "a flag"
"--karma", "-k"
action => :count_invocations # increase a counter each time the option is given
help => "increase karma"
"arg1"
nargs => 2 # eats up two arguments; puts the result in a Vector
help => "first argument, two " *
"entries at once"
required => true
"arg2"
nargs => '*' # eats up as many arguments as possible before an option
default => Any["no_arg_given"] # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
help => "second argument, eats up " *
"as many items as possible " *
"before an option"
end
return s
end
function ap_settings10b()
s = ArgParseSettings(description = "Test 10 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
add_arg_table!(s,
"--opt1", Dict(
:nargs => 2, # exactly 2 arguments
:arg_type => Int, # only Int arguments allowed
:default => [0, 1], # this is used when the option is not passed
:metavar => ["A", "B"], # two metavars for two arguments
:help => "an option"),
["--flag", "-f"], Dict(
:action => :store_true, # this makes it a flag
:help => "a flag"),
["--karma", "-k"], Dict(
:action => :count_invocations, # increase a counter each time the option is given
:help => "increase karma"),
"arg1", Dict(
:nargs => 2, # eats up two arguments; puts the result in a Vector
:help => "first argument, two " *
"entries at once",
:required => true),
"arg2", Dict(
:nargs => '*', # eats up as many arguments as possible before an option
:default => Any["no_arg_given"], # since the result will be a Vector{Any}, the default must
# also be (or it can be [] or nothing)
:help => "second argument, eats up " *
"as many items as possible " *
"before an option")
)
return s
end
# test to ensure length of vector is the same as nargs
function ap_settings10c(in_nargs)
s = ArgParseSettings(description = "Test 10 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
add_arg_table!(s,
"--opt1", Dict(
:nargs => in_nargs,
:arg_type => Int,
:default => [0, 1],
:metavar => ["A", "B"])
)
return true
end
@test ap_settings10c(2)
@aps_test_throws ap_settings10c(1)
@aps_test_throws ap_settings10c(3)
@aps_test_throws ap_settings10c('*')
@aps_test_throws ap_settings10c('?')
@aps_test_throws ap_settings10c('+')
@aps_test_throws ap_settings10c('A')
@aps_test_throws ap_settings10c('R')
@aps_test_throws ap_settings10c('0')
# Test to ensure multiple metavars cannot be used on positional args
function ap_settings10d()
s = ArgParseSettings(description = "Test 10 for ArgParse.jl",
epilog = "Have fun!",
version = "Version 1.0",
add_version = true,
exc_handler = ArgParse.debug_handler)
add_arg_table!(s,
"opt1", Dict(
:nargs => 2,
:arg_type => Int,
:metavar => ["A", "B"])
)
return true
end
@aps_test_throws ap_settings10d()
for s = [ap_settings10(), ap_settings10b()]
ap_test10(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--opt1 A B] [-f] [-k] arg1 arg1 [arg2...]
Test 10 for ArgParse.jl
positional arguments:
arg1 first argument, two entries at once
arg2 second argument, eats up as many items as possible
before an option (default: Any["no_arg_given"])
optional arguments:
--opt1 A B an option (type: $Int, default: $([0, 1]))
-f, --flag a flag
-k, --karma increase karma
Have fun!
"""
@test stringversion(s) == "Version 1.0\n"
@ap_test_throws ap_test10([])
@test ap_test10(["X", "Y"]) == Dict{String,Any}("opt1"=>[0, 1], "flag"=>false, "karma"=>0, "arg1"=>Any["X", "Y"], "arg2"=>Any["no_arg_given"])
@test ap_test10(["X", "Y", "-k", "-f", "Z", "--karma", "--opt1", "2", "3"]) == Dict{String,Any}("opt1"=>[2, 3], "flag"=>true, "karma"=>2, "arg1"=>Any["X", "Y"], "arg2"=>Any["Z"])
@test ap_test10(["--opt1", "-3", "-5", "X", "Y", "-k", "-f", "Z", "--karma"]) == Dict{String,Any}("opt1"=>[-3, -5], "flag"=>true, "karma"=>2, "arg1"=>Any["X", "Y"], "arg2"=>Any["Z"])
@ap_test_throws ap_test10(["--opt"])
@ap_test_throws ap_test10(["--opt="])
@ap_test_throws ap_test10(["--opt", "", "X", "Y"])
@ap_test_throws ap_test10(["--opt", "1e-2", "X", "Y"])
@ap_test_throws ap_test10(["X", "Y", "--opt1", "1", "a"])
@ap_test_throws ap_test10(["X", "Y", "--opt1", "1"])
@ap_test_throws ap_test10(["X", "Y", "--opt1", "a", "b"])
@aps_test_throws @add_arg_table!(s, "required_arg_after_optional_args", required = true)
# wrong default
@aps_test_throws @add_arg_table!(s, "--opt", arg_type = Int, default = 1.5)
# wrong range tester
@aps_test_throws @add_arg_table!(s, "--opt", arg_type = Int, range_tester = x->string(x), default = 1)
@aps_test_throws @add_arg_table!(s, "--opt", arg_type = Int, range_tester = x->sqrt(x)<1, default = -1)
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 587 | @testset "test 11" begin
ARGS = split("say hello --to world")
s = ArgParseSettings()
@add_arg_table! s begin
"say"
action = :command
end
@add_arg_table! s["say"] begin
"what"
help = "a positional argument"
required = true
"--to"
help = "an option with an argument"
end
args = parse_args(ARGS, s, as_symbols=true)
# make sure keys in args[:say] dict are of type Symbol
# when as_symbols=true
for (arg, val) in args[:say]
@test typeof(arg) == Symbol
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 5193 | # test 12: mutually exclusive and required argument groups
@testset "test 12" begin
function ap_settings12()
s = ArgParseSettings("Test 12 for ArgParse.jl",
exc_handler = ArgParse.debug_handler)
add_arg_group!(s, "mutually exclusive options", exclusive=true)
@add_arg_table! s begin
"--maybe", "-M"
action = :store_true
help = "maybe..."
"--maybe-not", "-N"
action = :store_true
help = "maybe not..."
end
add_arg_group!(s, "required mutually exclusive options", "reqexc", exclusive=true, required=true)
@add_arg_table! s begin
"--either", "-E"
action = :store_true
help = "choose the `either` option"
end
add_arg_group!(s, "required arguments", required=true)
@add_arg_table! s begin
"--enhance", "-+"
action = :store_true
help = "set the enhancement option"
"arg1"
nargs = 2 # eats up two arguments; puts the result in a Vector
help = "first argument, two " *
"entries at once"
end
set_default_arg_group!(s, "reqexc")
@add_arg_table! s begin
"--or", "-O"
action = :store_arg
arg_type = Int
default = 0
help = "set the `or` option"
end
set_default_arg_group!(s)
@add_arg_table! s begin
"-k"
action = :store_const
default = 0
constant = 42
help = "provide the answer"
"--or-perhaps"
action = :store_arg
arg_type = String
default = ""
help = "set the `or-perhaps` option"
group = "reqexc"
end
return s
end
let s = ap_settings12()
ap_test12(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) {-E | -O OR | --or-perhaps OR-PERHAPS} [-M |
-N] [-+] [-k] [arg1 arg1]
Test 12 for ArgParse.jl
optional arguments:
-k provide the answer
mutually exclusive options:
-M, --maybe maybe...
-N, --maybe-not maybe not...
required mutually exclusive options:
-E, --either choose the `either` option
-O, --or OR set the `or` option (type: $(Int), default: 0)
--or-perhaps OR-PERHAPS
set the `or-perhaps` option (default: \"\")
required arguments:
-+, --enhance set the enhancement option
arg1 first argument, two entries at once
"""
@ap_test_throws ap_test12([])
@test ap_test12(["-E", "-+"]) ==
Dict{String,Any}("k"=>0, "maybe"=>false, "maybe-not"=>false, "either"=>true, "or"=>0, "or-perhaps"=>"", "enhance"=>true, "arg1"=>[])
@test ap_test12(["-E", "-+", "--either"]) ==
Dict{String,Any}("k"=>0, "maybe"=>false, "maybe-not"=>false, "either"=>true, "or"=>0, "or-perhaps"=>"", "enhance"=>true, "arg1"=>[])
@test ap_test12(["A", "B", "--either"]) ==
Dict{String,Any}("k"=>0, "maybe"=>false, "maybe-not"=>false, "either"=>true, "or"=>0, "or-perhaps"=>"", "enhance"=>false, "arg1"=>["A", "B"])
@test ap_test12(["--enhance", "A", "B", "--or", "55", "-k"]) ==
Dict{String,Any}("k"=>42, "maybe"=>false, "maybe-not"=>false, "either"=>false, "or"=>55, "or-perhaps"=>"", "enhance"=>true, "arg1"=>["A", "B"])
@test ap_test12(["A", "B", "-Mk+O55", "-M"]) ==
Dict{String,Any}("k"=>42, "maybe"=>true, "maybe-not"=>false, "either"=>false, "or"=>55, "or-perhaps"=>"", "enhance"=>true, "arg1"=>["A", "B"])
@test ap_test12(["--enhance", "A", "B", "--or=55", "-k", "--maybe-not"]) ==
Dict{String,Any}("k"=>42, "maybe"=>false, "maybe-not"=>true, "either"=>false, "or"=>55, "or-perhaps"=>"", "enhance"=>true, "arg1"=>["A", "B"])
@test ap_test12(["--enhance", "A", "B", "--or-perhaps", "--either", "-k", "--maybe-not"]) ==
Dict{String,Any}("k"=>42, "maybe"=>false, "maybe-not"=>true, "either"=>false, "or"=>0, "or-perhaps"=>"--either", "enhance"=>true, "arg1"=>["A", "B"])
# combinations of missing arguments and too many arguments from the same group
@ap_test_throws ap_test12(["-M", "--enhance", "A", "B", "--or", "55", "-k", "--maybe-not"])
@ap_test_throws ap_test12(["--maybe", "--enhance", "A", "B", "--or", "55", "-k", "-N"])
@ap_test_throws ap_test12(["--enhance", "A", "B", "-MkNO=55"])
@ap_test_throws ap_test12(["--maybe", "--enhance", "A", "B", "-N"])
@ap_test_throws ap_test12(["-+NE", "--or-perhaps=?"])
@ap_test_throws ap_test12(["-ME", "A", "A", "--or-perhaps=?"])
@ap_test_throws ap_test12(["-MO55", "A", "A", "--or-perhaps=?"])
@ap_test_throws ap_test12(["--enhanced", "-+MkO55", "A", "A", "--or-perhaps=?"])
# invalid arguments in mutually exclusive groups
@aps_test_throws @add_arg_table!(s, "arg2", action = :store_arg, group = "reqexc")
set_default_arg_group!(s, "reqexc")
@aps_test_throws @add_arg_table!(s, "arg2", action = :store_arg)
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 7113 | # test 13: help_width and help_alignment_width settings
@testset "test 13" begin
function ap_settings13()
s = ArgParseSettings(description = "Test 13 for ArgParse.jl. This description is made unnecessarily long for the sake of testing the help_text_width setting.",
epilog = "This epilog is also made unnecessarily long for the same reason as the description, i.e., testing the help_text_width setting.",
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--option1"
arg_type = Int
default = 0
help = "an option, not used for much really, " *
"indeed it is not actually used for anything. " *
"That is why its name is so undescriptive."
"-O", "--long-option"
arg_type = Symbol
default = :xyz
help = "another option, this time it has a fancy name " *
"and yet it is still completely useless."
"arg1"
help = "first argument"
required = true
"arg2"
default = "no arg2 given"
help = "second argument"
end
return s
end
let s = ap_settings13()
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--option1 OPTION1] [-O LONG-OPTION] arg1
[arg2]
Test 13 for ArgParse.jl. This description is made unnecessarily long
for the sake of testing the help_text_width setting.
positional arguments:
arg1 first argument
arg2 second argument (default: "no arg2 given")
optional arguments:
--option1 OPTION1 an option, not used for much really, indeed it
is not actually used for anything. That is why
its name is so undescriptive. (type: $Int,
default: 0)
-O, --long-option LONG-OPTION
another option, this time it has a fancy name
and yet it is still completely useless. (type:
Symbol, default: :xyz)
This epilog is also made unnecessarily long for the same reason as the
description, i.e., testing the help_text_width setting.
"""
s.help_width = 120
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--option1 OPTION1] [-O LONG-OPTION] arg1 [arg2]
Test 13 for ArgParse.jl. This description is made unnecessarily long for the sake of testing the help_text_width
setting.
positional arguments:
arg1 first argument
arg2 second argument (default: "no arg2 given")
optional arguments:
--option1 OPTION1 an option, not used for much really, indeed it is not actually used for anything. That is why
its name is so undescriptive. (type: $Int, default: 0)
-O, --long-option LONG-OPTION
another option, this time it has a fancy name and yet it is still completely useless. (type:
Symbol, default: :xyz)
This epilog is also made unnecessarily long for the same reason as the description, i.e., testing the help_text_width
setting.
"""
s.help_width = 50
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--option1 OPTION1]
[-O LONG-OPTION] arg1
[arg2]
Test 13 for ArgParse.jl. This description is made
unnecessarily long for the sake of testing the
help_text_width setting.
positional arguments:
arg1 first argument
arg2 second argument (default:
"no arg2 given")
optional arguments:
--option1 OPTION1 an option, not used for
much really, indeed it is
not actually used for
anything. That is why its
name is so undescriptive.
(type: $Int, default: 0)
-O, --long-option LONG-OPTION
another option, this time
it has a fancy name and
yet it is still completely
useless. (type: Symbol,
default: :xyz)
This epilog is also made unnecessarily long for
the same reason as the description, i.e., testing
the help_text_width setting.
"""
s.help_width = 100
s.help_alignment_width = 50
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--option1 OPTION1] [-O LONG-OPTION] arg1 [arg2]
Test 13 for ArgParse.jl. This description is made unnecessarily long for the sake of testing the
help_text_width setting.
positional arguments:
arg1 first argument
arg2 second argument (default: "no arg2 given")
optional arguments:
--option1 OPTION1 an option, not used for much really, indeed it is not actually used
for anything. That is why its name is so undescriptive. (type:
$Int, default: 0)
-O, --long-option LONG-OPTION another option, this time it has a fancy name and yet it is still
completely useless. (type: Symbol, default: :xyz)
This epilog is also made unnecessarily long for the same reason as the description, i.e., testing
the help_text_width setting.
"""
s.help_width = 50
s.help_alignment_width = 4
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--option1 OPTION1]
[-O LONG-OPTION] arg1 [arg2]
Test 13 for ArgParse.jl. This description is made
unnecessarily long for the sake of testing the
help_text_width setting.
positional arguments:
arg1
first argument
arg2
second argument (default: "no arg2 given")
optional arguments:
--option1 OPTION1
an option, not used for much really, indeed it
is not actually used for anything. That is why
its name is so undescriptive. (type: $Int,
default: 0)
-O, --long-option LONG-OPTION
another option, this time it has a fancy name
and yet it is still completely useless. (type:
Symbol, default: :xyz)
This epilog is also made unnecessarily long for
the same reason as the description, i.e., testing
the help_text_width setting.
"""
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 2720 | # test 14: default values converted to arg_type
@testset "test 14" begin
function ap_settings14()
s = ArgParseSettings(description = "Test 14 for ArgParse.jl",
exc_handler = ArgParse.debug_handler)
@add_arg_table! s begin
"--opt1"
nargs = '?'
arg_type = Int
default = 0.0
constant = 1.0
help = "an option"
"-O"
arg_type = Symbol
default = "xyz"
help = "another option"
"--opt2"
nargs = '+'
arg_type = Int
default = [0.0]
help = "another option, many args"
"--opt3"
action = :append_arg
arg_type = Int
default = [0.0]
help = "another option, appends arg"
"--opt4"
action = :append_arg
nargs = '+'
arg_type = Int
default = [[0.0]]
help = "another option, appends many args"
end
return s
end
let s = ap_settings14()
ap_test14(args) = parse_args(args, s)
@test stringhelp(s) == """
usage: $(basename(Base.source_path())) [--opt1 [OPT1]] [-O O]
[--opt2 OPT2 [OPT2...]] [--opt3 OPT3]
[--opt4 OPT4 [OPT4...]]
Test 14 for ArgParse.jl
optional arguments:
--opt1 [OPT1] an option (type: $(Int), default: 0, without
arg: 1)
-O O another option (type: Symbol, default: :xyz)
--opt2 OPT2 [OPT2...]
another option, many args (type: $(Int),
default: [0])
--opt3 OPT3 another option, appends arg (type: $(Int),
default: [0])
--opt4 OPT4 [OPT4...]
another option, appends many args (type:
$(Int), default: $([[0]]))
"""
@test ap_test14([]) == Dict{String,Any}("opt1"=>0, "O"=>:xyz, "opt2"=>[0], "opt3"=>[0], "opt4"=>[[0]])
@test ap_test14(["--opt1"]) == Dict{String,Any}("opt1"=>1, "O"=>:xyz, "opt2"=>[0], "opt3"=>[0], "opt4"=>[[0]])
@test ap_test14(["--opt1", "33", "--opt2", "5", "7"]) == Dict{String,Any}("opt1"=>33, "O"=>:xyz, "opt2"=>[5, 7], "opt3"=>[0], "opt4"=>[[0]])
@test ap_test14(["--opt3", "5", "--opt3", "7"]) == Dict{String,Any}("opt1"=>0, "O"=>:xyz, "opt2"=>[0], "opt3"=>[0, 5, 7], "opt4"=>[[0]])
@test ap_test14(["--opt4", "5", "7", "--opt4", "11", "13", "17"]) == Dict{String,Any}("opt1"=>0, "O"=>:xyz, "opt2"=>[0], "opt3"=>[0], "opt4"=>[[0], [5, 7], [11, 13, 17]])
end
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 1093 | using ArgParse
using Test
macro ap_test_throws(args)
:(@test_throws ArgParseError $(esc(args)))
end
macro aps_test_throws(args)
:(@test_throws ArgParseSettingsError $(esc(args)))
end
macro noout_test(args)
quote
mktemp() do _,io
redirect_stdout(io) do
@test $(esc(args))
end
end
end
end
macro test_addtable_failure(ex...)
ex = [nothing, ex...]
ex = Expr(:call, :macroexpand, @__MODULE__, Expr(:quote, Expr(:macrocall, Symbol("@add_arg_table!"), ex...)))
err = @static VERSION ≥ v"1.7.0-DEV.937" ? ArgParseSettingsError : LoadError
quote
@test_throws $err $ex
end
end
macro tostring(ex)
@assert ex.head == :call
f = esc(ex.args[1])
a = map(esc, ex.args[2:end])
newcall = Expr(:call, f, :io, a...)
quote
io = IOBuffer()
$newcall
String(take!(io))
end
end
stringhelp(s::ArgParseSettings) = @tostring ArgParse.show_help(s, exit_when_done = false)
stringversion(s::ArgParseSettings) = @tostring ArgParse.show_version(s, exit_when_done = false)
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | code | 223 | module ArgParseTests
include("common.jl")
for i = 1:14
try
s_i = lpad(string(i), 2, "0")
include("argparse_test$s_i.jl")
catch err
println()
rethrow(err)
end
end
println()
end
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 5118 | # ArgParse.jl
[![DOCS][docs-img]][docs-url] [![CI][CI-img]][CI-url] [![CODECOV][codecov-img]][codecov-url]
ArgParse.jl is a package for parsing command-line arguments to [Julia][julia] programs.
### Installation and usage
To install the module, use Julia's package manager: start pkg mode by pressing `]` and then enter:
```
(v1.5) pkg> add ArgParse
```
The module can then be loaded like any other Julia module:
```
julia> using ArgParse
```
### Documentation
- The manual is [HERE][docs-url].
- See also the examples in the [examples directory](examples).
## Changes in release 1.2.0
* Add options to control the help text formatting ([#132][PR132])
* Allow defaults that can be converted into the target argument type ([#133][PR133])
## Changes in release 1.1.5
* Fix ambiguity with julia 1.11 new `wrap` function (see [#128][PR128])
* Throw a new `ArgParseSettingError` for all settings-related errors
* Fixed some tests
## Changes in release 1.1.4
* Fix in @project_version macro (see [#107][PR107])
## Changes in release 1.1.3
* Added a @project_version macro (see [#106][PR106])
## Changes in release 1.1.2
* Faster startup time by disabling optimizations/inference (see [#104][PR104])
## Changes in release 1.1.1
* Fixed the case when using symbol keys, commands are not required, no command is provided
## Changes in release 1.1.0
* Try using the constructor for types that don't define a `convert` method from `AbstractString`
## Changes in release 1.0.1
* Small fixes in docs
## Changes in release 1.0.0
* Drop support for Julia versions v0.6/v0.7
* Renamed a few functions and macros (old versions can be used but produce deprecation warnings):
+ `@add_arg_table` → `@add_arg_table!`
+ `add_arg_table` → `add_arg_table!`
+ `add_arg_group` → `add_arg_group!`
+ `set_default_arg_group` → `set_default_arg_group!`
+ `import_settings` → `import_settings!`. The signature of this function has also changed:
`args_only` is now a keyword argument
* Parsing does not exit julia by default when in interactive mode now
* Added mutually-exclusive and/or required argument groups
* Added command aliases
## Changes in release 0.6.2
* Fix a remaining compatibility issue (`@warn`)
## Changes in release 0.6.1
* Testing infrastructure update, tiny docs fixes
## Changes in release 0.6.0
* Added support for Julia v0.7, dropped support for Julia v0.5.
* Added `exit_after_help` setting to control whether to exit julia after help/version info is displayed
(which is still the defult) or to just abort the parsing and return `nothing` instead.
## Changes in release 0.5.0
* Added support for Julia v0.6, dropped support for Julia v0.4.
* The default output type is now `Dict{String,Any}`, as stated in the docs,
rather than `Dict{AbstractString,Any}`.
* Added docstrings, moved documentation to Documenter.jl
## Changes in release 0.4.0
### New features
* Added support for vectors of METAVAR names (see [#33][PR33])
### Other changes
* Support for Julia v0.3 was dropped.
## Changes in release 0.3.1
### New available settings
* `fromfile_prexif_chars` (see [#27][PR27])
* `preformatted_desciption`/`preformatted_epilog` (see [#28][PR28])
## Changes in release 0.3.0
### Breaking changes
Upgrading from versions 0.2.X to 0.3.X, the following API changes were made,
which may break existing code:
* Option arguments are no longer evaluated by default. This is for security
reasons. Evaluation can be forced on a per-option basis with the
`eval_arg=true` setting (although this is discuraged).
* The syntax of the `add_arg_table` function has changed, it now takes a `Dict`
object instead of an `@options` opbject, since the dependency on the
Options.jl module was removed. (The `@add_arg_table` macro is unchanged
though.)
### Other changes
* Documented that overloading the function `ArgParse.parse_item` can be used to
instruct ArgParse on how to parse custom types. Parse error reporting was
also improved
* Removed dependecy on the Options.jl module
* Enabled precompilation on Julia 0.4
[Julia]: http://julialang.org
[docs-img]: https://img.shields.io/badge/docs-stable-blue.svg
[docs-url]: https://carlobaldassi.github.io/ArgParse.jl/stable
[codecov-img]: https://codecov.io/gh/carlobaldassi/ArgParse.jl/branch/master/graph/badge.svg
[codecov-url]: https://codecov.io/gh/carlobaldassi/ArgParse.jl
[CI-img]: https://github.com/carlobaldassi/ArgParse.jl/actions/workflows/ci.yml/badge.svg
[CI-url]: https://github.com/carlobaldassi/ArgParse.jl/actions/workflows/ci.yml
[PR27]: https://github.com/carlobaldassi/ArgParse.jl/pull/27
[PR28]: https://github.com/carlobaldassi/ArgParse.jl/pull/28
[PR33]: https://github.com/carlobaldassi/ArgParse.jl/pull/33
[PR104]: https://github.com/carlobaldassi/ArgParse.jl/pull/104
[PR106]: https://github.com/carlobaldassi/ArgParse.jl/pull/106
[PR107]: https://github.com/carlobaldassi/ArgParse.jl/pull/107
[PR128]: https://github.com/carlobaldassi/ArgParse.jl/pull/128
[PR132]: https://github.com/carlobaldassi/ArgParse.jl/pull/132
[PR133]: https://github.com/carlobaldassi/ArgParse.jl/pull/133
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 19322 | # Argument table
The argument table is used to store allowed arguments and options in an [`ArgParseSettings`](@ref) object.
Each entry of the table consist of an argument name and a list of argument settings, e.g.:
```julia
"--verbose"
help = "verbose output"
action = :store_true
```
There are two very similar methods to populate a table:
```@docs
@add_arg_table!
```
```@docs
add_arg_table!
```
## Argument names
Argument names are strings or, in the case of options, lists of strings. An argument is an option if it begins with a `'-'`
character, otherwise it'a positional argument. A single `'-'` introduces a short option, which must consist of a single
character; long options begin with `"--"` instead.
Positional argument names can be any string, except all-uppercase strings between `'%'` characters, which are reserved
(e.g. `"%COMMAND%"`).
Option names can contain any character except `'='`, whitespaces and non-breakable spaces.
Depending on the value of the `add_help` and `add_version` settings, options `--help`, `-h` and `--version` may
be reserved.
If the `allow_ambiguous_opts` setting is `false`, some characters are not allowed as short options: all digits, the dot,
the underscore and the opening parethesis (e.g. `-1`, `-.`, `-_`, `-(`).
For positional arguments, the argument name will be used as the key in the `Dict` object returned by the [`parse_args`](@ref)
function. For options, it will be used to produce a default key in case a `dest_name` is not explicitly specified in the table
entry, using either the first long option name in the list or the first short option name if no long options are present.
For example:
| argument name | default `dest_name` |
|:-----------------------------|:------------------------|
| `"--long"` | `"long"` |
| `"--long", "-s"` | `"long"` |
| `"-s", "--long1", "--long2"` | `"long1"` |
| `"-s", "-x"` | `"s"` |
In case the `autofix_names` setting is `true` (it is `false` by default), dashes in the names of arguments and long options will be
converted to underscores: for example, `"--my-opt"` will yield `"my_opt"` as the default `dest_name`.
The argument name is also used to generate a default metavar in case `metavar` is not explicitly set in the table entry. The rules
are the same used to determine the default `dest_name`, but for options the result will be uppercased (e.g. `"--long"` will
become `LONG`). Note that this poses additional constraints on the positional argument names (e.g. whitespace is not allowed in
metavars).
## Argument entry settings
Argument entry settings determine all aspects of an argument's behavior. Some settings combinations are contradictory and will produce
an error (e.g. using both `action = :store_true` and `nargs = 1`, or using `action = :store_true` with a positional argument).
Also, some settings are only meaningful under some conditions (e.g. passing a `metavar` to a flag-like option does not make sense)
and will be ignored with a warning (unless the `suppress_warnings` general setting is `true`).
This is the list of all available settings:
* `nargs` (default = `'A'`): the number of extra command-line tokens parsed with the entry. See
the section [Available actions and nargs values](@ref) for a complete desctiption.
* `action`: the action performed when the argument is parsed. It can be passed as a `String` or as a `Symbol` (e.g. both
`:store_arg` and `"store_arg"` are accepted). The default action is `:store_arg` unless `nargs` is `0`, in which case the
default is `:store_true`. See the section [Available actions and nargs values](@ref) for a list of all available actions and a
detailed explanation.
* `arg_type` (default = `Any`): the type of the argument. Only makes sense with non-flag arguments. Only works out-of-the-box with
string, symbol and number types, but see the section [Parsing to custom types](@ref) for details on how to make it work for
general types (including user-defined ones).
* `default` (default = `nothing`): the default value if the option or positional argument is not parsed. Only makes sense with
non-flag arguments, or when the action is `:store_const` or `:append_const`. Unless it's `nothing`, it must be consistent with
`arg_type` and `range_tester`.
* `constant` (default = `nothing`): this value is used by the `:store_const` and `:append_const` actions, or when `nargs = '?'`
and the option argument is not provided.
* `required` (default = `false`): determines if an argument is required (this setting is ignored by flags, which are always
optional, and in general should be avoided for options if possible).
* `range_tester` (default = `x->true`): a function returning `true` if an argument is allowed and otherwise returning `false` (e.g. you could use `arg_type = Integer` and `range_tester = isodd` to allow only odd integer values)
* `dest_name` (default = auto-generated): the key which will be associated with the argument in the `Dict` object returned by
`parse_args`. The auto-generation rules are explained in the [Argument names](@ref) section. Multiple arguments can share
the same destination, provided their actions and types are compatible.
* `help` (default = `""`): the help string which will be shown in the auto-generated help screen. It's a `String` which will
be automaticaly formatted; also, `arg_type` and `default` will be automatically appended to it if provided.
* `metavar` (default = auto-generated): a token which will be used in usage and help screens to describe the argument syntax. For
positional arguments, it will also be used as an identifier in all other messages (e.g. in reporting errors), therefore it must
be unique. For optional arguments, if `nargs > 1` then `metavar` can be a `Vector` of `String`s of length `nargs`. The
auto-generations rules are explained in the [Argument names](@ref) section.
* `force_override`: if `true`, conflicts are ignored when adding this entry in the argument table (see also the
[Conflicts and overrides](@ref) section). By default, it follows the general `error_on_conflict` settings.
* `group`: the option group to which the argument will be assigned to (see the [Argument groups](@ref) section). By default, the
current default group is used if specified, otherwise the assignment is automatic.
* `eval_arg` (default: `false`): if `true`, the argument will be parsed as a Julia expression and evaluated, which means that
for example `"2+2"` will yield the integer `4` rather than a string. Note that this is a security risk for outside-facing
programs and should generally be avoided: overload `ArgParse.parse_item` instead (see the section [Parsing to custom types](@ref)).
Only makes sense for non-flag arguments.
## Available actions and nargs values
The `nargs` and `action` argument entry settings are used together to determine how many tokens will be parsed from the command
line and what action will be performed on them.
The `nargs` setting can be a number or a character; the possible values are:
* `'A'`: automatic, i.e. inferred from the action (this is the default). In practice, it means `0` for options with flag actions
(see the actions categorization below, in this section) and `1` for options with non-flag actions (but it's different from
using an explicit `1` because the result is not stored in a `Vector`).
* `0`: this is the only possibility (besides `'A'`) for flag actions, and it means no extra tokens will be parsed from
the command line. If `action` is not specified, setting `nargs` to `0` will make `action` default to `:store_true`.
* a positive integer number `N`: exactly `N` tokens will be parsed from the command-line, and stored into a `Vector`
of length `N`. Note that `nargs=1` produces a `Vector` of one item.
* `'?'`: optional, i.e. a token will only be parsed if it does not look like an option (see the [Parsing details](@ref) section
for a discussion of how exactly this is established). If the option string is not given, the `default` argument value will be
used. If the option string is given but not followed by an option parameter, the `constant` argument value will be used
instead. This only makes sense with options.
* `'*'`: any number, i.e. all subsequent tokens are stored into a `Vector`, up until a token which looks like an option is
encountered, or all tokens are consumed.
* `'+'`: like `'*'`, but at least one token is required.
* `'R'`: all remainder tokens, i.e. like `'*'` but it does not stop at options.
Actions can be categorized in many ways; one prominent distinction is flag vs. non-flag: some actions are for options which take no
argument (i.e. flags), all others (except `command`, which is special) are for other options and positional arguments:
* flag actions are only compatible with `nargs = 0` or `nargs = 'A'`
* non-flag actions are not compatible with `nargs = 0`.
In other words, all flags (takes no argument) are options (starts with a dash), but not all options (starts with a dash)
are flags (takes no argument).
This is the list of all available actions (in each example, suppose we defined `settings = ArgParseSettings()`):
* `store_arg` (non-flag): store the argument. This is the default unless `nargs` is `0`. Example:
```julia-repl
julia> @add_arg_table!(settings, "arg", action => :store_arg);
julia> parse_args(["x"], settings)
Dict{String,Any} with 1 entry:
"arg" => "x"
```
The result is a vector if `nargs` is a non-zero number, or one of `'*'`, `'+'`, `'R'`:
```julia-repl
julia> @add_arg_table!(settings, "arg", action => :store_arg, nargs => 2);
julia> parse_args(["x", "y"], settings)
Dict{String,Any} with 1 entry:
"arg" => Any["x","y"]
```
* `store_true` (flag): store `true` if given, otherwise `false`. Example:
```julia-repl
julia> @add_arg_table!(settings, "-v", action => :store_true);
julia> parse_args([], settings)
Dict{String,Any} with 1 entry:
"v" => false
julia> parse_args(["-v"], settings)
Dict{String,Any} with 1 entry:
"v" => true
```
* `store_false` (flag): store `false` if given, otherwise `true`. Example:
```julia-repl
julia> @add_arg_table!(settings, "-v", action => :store_false);
julia> parse_args([], settings)
Dict{String,Any} with 1 entry:
"v" => true
julia> parse_args(["-v"], settings)
Dict{String,Any} with 1 entry:
"v" => false
```
* `store_const` (flag): store the value passed as `constant` in the entry settings if given, otherwise `default`.
Example:
```julia-repl
julia> @add_arg_table!(settings, "-v", action => :store_const,
constant => 1,
default => 0);
julia> parse_args([], settings)
Dict{String,Any} with 1 entry:
"v" => 0
julia> parse_args(["-v"], settings)
Dict{String,Any} with 1 entry:
"v" => 1
```
* `append_arg` (non-flag): append the argument to the result. Example:
```julia-repl
julia> @add_arg_table!(settings, "-x", action => :append_arg);
julia> parse_args(["-x", "1", "-x", "2"], settings)
Dict{String,Any} with 1 entry:
"x" => Any["1","2"]
```
The result will be a `Vector{Vector}` if `nargs` is a non-zero number, or one of `'*'`, `'+'`, `'R'`:
```julia-repl
julia> @add_arg_table!(settings, "-x", action => :append_arg, nargs => '*');
julia> parse_args(["-x", "1", "2", "-x", "3"], settings)
Dict{String,Any} with 1 entry:
"x" => Array{Any,1}[Any["1","2"],Any["3"]]
```
* `append_const` (flag): append the value passed as `constant` in the entry settings. Example:
```julia-repl
julia> @add_arg_table!(settings, "-x", action => :append_const, constant => 1);
julia> parse_args(["-x", "-x", "-x"], settings)
Dict{String,Any} with 1 entry:
"x" => Any[1,1,1]
```
* `count_invocations` (flag): increase a counter; the final result will be the number of times the option was
invoked. Example:
```julia-repl
julia> @add_arg_table!(settings, "-x", action => :count_invocations);
julia> parse_args(["-x", "-x", "-x"], settings)
Dict{String,Any} with 1 entry:
"x" => 3
```
* `show_help` (flag): show the help screen and exit. This is useful if the `add_help` general setting is
`false`. Example:
```julia-repl
julia> @add_arg_table!(settings, "-x", action => :show_help);
julia> parse_args(["-x"], settings)
usage: <PROGRAM> [-x]
optional arguments:
-x
```
* `show_version` (flag): show the version information and exit. This is useful if the `add_version` general
setting is `false`. Example:
```julia-repl
julia> settings.version = "1.0";
julia> @add_arg_table!(settings, "-v", action => :show_version);
julia> parse_args(["-v"], settings)
1.0
```
* `command` (special): the argument or option is a command, i.e. it starts a sub-parsing session (see the
[Commands](@ref) section).
## Commands
Commands are a special kind of arguments which introduce sub-parsing sessions as soon as they are encountered by `parse_args`
(and are therefore mutually exclusive).
The `ArgParse` module allows commands to look both as positional arguments or as options, with minor differences between the two.
Unlike actual positional arguments, commands that *look* like positional arguments can have extra names (aliases).
Commands are introduced by the `action = :command` setting in the argument table. Suppose we save the following script in
a file called `cmd_example.jl`:
```julia
using ArgParse
function parse_commandline()
s = ArgParseSettings()
@add_arg_table! s begin
"cmd1", "C"
help = "first command"
action = :command
"cmd2", "K"
help = "second command"
action = :command
end
return parse_args(s)
end
parsed_args = parse_commandline()
println(parsed_args)
```
Invoking the script from the command line, we would get the following help screen:
```text
$ julia cmd_example.jl --help
usage: cmd_example.jl [-h] {cmd1|cmd2}
commands:
cmd1 first command (aliases: C)
cmd2 second command (aliases: K)
optional arguments:
-h, --help show this help message and exit
```
If commands are present in the argument table, `parse_args` will set the special key `"%COMMAND%"` in the returned `Dict` and
fill it with the invoked command (or `nothing` if no command was given):
```text
$ julia cmd_example.jl cmd1
Dict("%COMMAND%"=>"cmd1", "cmd1"=>Dict())
```
This is unless `parse_args` is invoked with `as_symbols=true`, in which case the special key becomes `:_COMMAND_`. (In that case,
no other argument is allowed to use `_COMMAND_` as its `dest_name`, or an error will be raised.)
Aliases are recognized when parsing, but the returned `Dict` will always use the command's name (the first entry in the
table):
```text
$ julia cmd_example.jl C
Dict("%COMMAND%"=>"cmd1", "cmd1"=>Dict())
```
Since commands introduce sub-parsing sessions, an additional key will be added for the called command (`"cmd1"` in this case) whose
associated value is another `Dict{String, Any}` containing the result of the sub-parsing (in the above case it's empty). In fact,
with the default settings, commands have their own help screens:
```text
$ julia cmd_example.jl cmd1 --help
usage: cmd_example.jl cmd1 [-h]
optional arguments:
-h, --help show this help message and exit
```
The argument settings and tables for commands can be accessed by using a dict-like notation, i.e. `settings["cmd1"]` is an
`ArgParseSettings` object specific to the `"cmd1"` command. Therefore, to populate a command sub-argument-table, simply
use `@add_arg_table!(settings["cmd1"], table...)` and similar.
These sub-settings are created when a command is added to the argument table, and by default they inherit their parent general
settings except for the `prog` setting (which is auto-generated, as can be seen in the above example) and the
`description`, `epilog` and `usage` settings (which are left empty).
Commands can also have sub-commands.
By default, if commands exist, they are required; this can be avoided by setting the `commands_are_required = false` general setting.
The only meaningful settings for commands in an argument entry besides `action` are `help`, `force_override`, `group` and
(for flags only) `dest_name`.
The only differences between positional-arguments-like and option-like commands are in the way they are parsed, and the fact
that options accept a `dest_name` setting.
Note that short-form option-like commands will be still be recognized in the middle of a short options group and trigger a sub-parsing
session: for example, if an option `-c` is associated to a command, then `-xch` will parse option `-x` according to the parent
settings, and option `-h` according to the command sub-settings.
## Argument groups
By default, the auto-generated help screen divides arguments into three groups: commands, positional arguments and optional
arguments, displayed in that order. Example:
```@setup args
using ArgParse
```
```@repl args
settings = ArgParseSettings();
@add_arg_table! settings begin
"--opt"
"arg"
required = true
"cmd1"
action = :command
"cmd2"
action = :command
end;
settings.exit_after_help = false # hide
parse_args(["--help"], settings)
```
It is possible to partition the arguments differently by defining and using customized argument groups.
Groups of options can also be declared to be mutually exclusive, meaning that no more than one of the
options in the group can be provided. A group can also be declared to be required, meaning that at least
one argument in the group needs to be provided.
```@docs
add_arg_group!
```
```@docs
set_default_arg_group!
```
Besides setting a default group with `add_arg_group!` and `set_default_group!`, it's also possible to assign individual arguments
to a group by using the `group` setting in the argument table entry, which follows the same rules as `set_default_group!`.
Note that if the `add_help` or `add_version` general settings are `true`, the `--help, -h` and `--version` options
will always be added to the `optional` group.
## Argument table styles
Here are some examples of styles for the [`@add_arg_table!`](@ref) marco and [`add_arg_table!`](@ref) function invocation:
```julia
@add_arg_table! settings begin
"--opt", "-o"
help = "an option"
"arg"
help = "a positional argument"
end
@add_arg_table!(settings
, ["--opt", "-o"]
, help => "an option"
, "arg"
, help => "a positional argument"
)
@add_arg_table! settings begin
(["--opt", "-o"]; help = an option)
("arg"; help = "a positional argument")
end
@add_arg_table!(settings,
["-opt", "-o"],
begin
help = "an option"
end,
"arg",
begin
help = "a positional argument"
end)
add_arg_table!(settings,
["-opt", "-o"], Dict(:help => "an option"),
"arg" , Dict(:help => "a positional argument")
)
```
One restriction is that groups introduced by `begin...end` blocks or semicolon-separated lists between parentheses
cannot introduce argument names unless the first item in the block is an argument name.
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 1873 | # Conflicts and overrides
Conflicts between arguments, be them options, positional arguments or commands, can arise for a variety of reasons:
* Two options have the same name (either long or short)
* Two arguments have the same destination key, but different types (e.g. one is `Any` and the other `String`)
* Two arguments have the same destination key, but incompatible actions (e.g. one does `:store_arg` and the other
`:append_arg`)
* Two positional arguments have the same metavar (and are therefore indistinguishable in the usage and help screens
and in error messages)
* An argument's destination key is the same as a command name
* Two commands with the same name are given, but one has a long-option form (e.g. `test` and `--test`)
* A command alias is equal to another command's name or alias
When the general setting `error_on_conflict` is `true`, or any time the specific `force_override` table entry
setting is `false`, any of the above conditions leads to an error.
On the other hand, setting `error_on_conflict` to `false`, or `force_override` to `true`, will try to force
the resolution of most of the conflicts in favor of the newest added entry. The general rules are the following:
* In case of duplicate options, all conflicting forms of the older options are removed; if all forms of an
option are removed, the option is deleted entirely
* In case of duplicate destination key and incompatible types or actions, the older argument is deleted
* In case of duplicate positional arguments metavars, the older argument is deleted
* A command can override an argument with the same destination key
* However, an argument can never override a command; neither can a command override another command when added
with `@add_arg_table!` (compatible commands are merged by [`import_settings!`](@ref) though)
* Conflicting command aliases are removed
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 1018 | # Parsing to custom types
If you specify an `arg_type` setting (see the [Argument entry settings](@ref) section) for an
option or an argument, `parse_args` will try to parse it, i.e. to convert the string to the
specified type. For `Number` types, Julia's built-in `parse` function will be used. For other
types, first `convert` and then the type's constructor will be tried. In order to extend this
functionality, e.g. to user-defined custom types, without adding methods to `convert` or the
constructor, you can overload the `ArgParse.parse_item` function. Example:
```julia
struct CustomType
val::Int
end
function ArgParse.parse_item(::Type{CustomType}, x::AbstractString)
return CustomType(parse(Int, x))
end
```
Note that the second argument needs to be of type `AbstractString` to avoid ambiguity errors. Also
note that if your type is parametric (e.g. `CustomType{T}`), you need to overload the function like
this: `function ArgParse.parse_item(::Type{CustomType{T}}, x::AbstractString) where {T}`.
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 2227 | # Parsing details
During parsing, `parse_args` must determine whether an argument is an option, an option argument, a positional
argument, or a command. The general rules are explained in the [`parse_args`](@ref) documentation, but
ambiguities may arise under particular circumstances. In particular, negative numbers like `-1` or `-.1e5`
may look like options. Under the default settings, such options are forbidden, and therefore those tokens are
always recognized as non-options. However, if the `allow_ambiguous_opts` general setting is `true`, existing
options in the argument table will take precedence: for example, if the option `-1` is added, and it takes an
argument, then `-123` will be parsed as that option, and `23` will be its argument.
Some ambiguities still remains though, because the `ArgParse` module can actually accept and parse expressions,
not only numbers (although this is not the default), and therefore one may try to pass arguments like `-e` or
`-pi`; in that case, these will always be at risk of being recognized as options. The easiest workaround is to
put them in parentheses, e.g. `(-e)`.
When an option is declared to accept a fixed positive number of arguments or the remainder of the command line
(i.e. if `nargs` is a non-zero number, or `'A'`, or `'R'`), `parse_args` will not try to check if the
argument(s) looks like an option.
If `nargs` is one of `'?'` or `'*'` or `'+'`, then `parse_args` will take in only arguments which do not
look like options.
When `nargs` is `'+'` or `'*'` and an option is being parsed, then using the `'='` character will mark what
follows as an argument (i.e. not an option); all which follows goes under the rules explained above. The same is true
when short option groups are being parsed. For example, if the option in question is `-x`, then both
`-y -x=-2 4 -y` and `-yx-2 4 -y` will parse `"-2"` and `"4"` as the arguments of `-x`.
Finally, note that with the `eval_arg` setting expressions are evaluated during parsing, which means that there is no
safeguard against passing things like ```run(`rm -rf someimportantthing`)``` and seeing your data evaporate
(don't try that!). Be careful and generally try to avoid using the `eval_arg` setting.
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 212 | # Importing settings
It may be useful in some cases to import an argument table into the one which is to be used, for example to create
specialized versions of a common interface.
```@docs
import_settings!
```
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 6165 | # ArgParse.jl documentation
```@meta
CurrentModule = ArgParse
```
This [Julia](http://julialang.org) package allows the creation of user-friendly command-line interfaces
to Julia programs: the program defines which arguments, options and sub-commands it accepts, and the
`ArgParse` module does the actual parsing, issues errors when the input is invalid, and automatically
generates help and usage messages.
Users familiar with Python's `argparse` module will find many similarities, but some important differences
as well.
## Installation
To install the module, use Julia's package manager: start pkg mode by pressing `]` and then enter:
```
(v1.5) pkg> add ArgParse
```
Dependencies will be installed automatically.
## Quick overview and a simple example
First of all, the module needs to be loaded:
```julia
using ArgParse
```
There are two main steps for defining a command-line interface: creating an [`ArgParseSettings`](@ref) object, and
populating it with allowed arguments and options using either the macro [`@add_arg_table!`](@ref) or the
function [`add_arg_table!`](@ref) (see the [Argument table](@ref) section):
```julia
s = ArgParseSettings()
@add_arg_table! s begin
"--opt1"
help = "an option with an argument"
"--opt2", "-o"
help = "another option with an argument"
arg_type = Int
default = 0
"--flag1"
help = "an option without argument, i.e. a flag"
action = :store_true
"arg1"
help = "a positional argument"
required = true
end
```
In the macro, options and positional arguments are specified within a `begin...end` block, by one or more names
in a line, optionally followed by a list of settings.
So, in the above example, there are three options:
* the first one, `"--opt1"` takes an argument, but doesn't check for its type, and it doesn't have a default value
* the second one can be invoked in two different forms (`"--opt2"` and `"-o"`); it also takes an argument, but
it must be of `Int` type (or convertible to it) and its default value is `0`
* the third one, `--flag1`, is a flag, i.e. it doesn't take any argument.
There is also only one positional argument, `"arg1"`, which is declared as mandatory.
When the settings are in place, the actual argument parsing is performed via the [`parse_args`](@ref) function:
```julia
parsed_args = parse_args(ARGS, s)
```
The parameter `ARGS` can be omitted. In case no errors are found, the result will be a `Dict{String,Any}` object.
In the above example, it will contain the keys `"opt1"`, `"opt2"`, `"flag1"` and `"arg1"`, so that e.g.
`parsed_args["arg1"]` will yield the value associated with the positional argument.
(The `parse_args` function also accepts an optional `as_symbols` keyword argument: when set to `true`, the
result of the parsing will be a `Dict{Symbol,Any}`, which can be useful e.g. for passing it as the keywords to a Julia
function.)
Putting all this together in a file, we can see how a basic command-line interface is created:
```julia
using ArgParse
function parse_commandline()
s = ArgParseSettings()
@add_arg_table! s begin
"--opt1"
help = "an option with an argument"
"--opt2", "-o"
help = "another option with an argument"
arg_type = Int
default = 0
"--flag1"
help = "an option without argument, i.e. a flag"
action = :store_true
"arg1"
help = "a positional argument"
required = true
end
return parse_args(s)
end
function main()
parsed_args = parse_commandline()
println("Parsed args:")
for (arg,val) in parsed_args
println(" $arg => $val")
end
end
main()
```
If we save this as a file called `myprog1.jl`, we can see how a `--help` option is added by default,
and a help message is automatically generated and formatted:
```text
$ julia myprog1.jl --help
usage: myprog1.jl [--opt1 OPT1] [-o OPT2] [--flag1] [-h] arg1
positional arguments:
arg1 a positional argument
optional arguments:
--opt1 OPT1 an option with an argument
-o, --opt2 OPT2 another option with an argument (type: Int64,
default: 0)
--flag1 an option without argument, i.e. a flag
-h, --help show this help message and exit
```
Also, we can see how invoking it with the wrong arguments produces errors:
```text
$ julia myprog1.jl
required argument arg1 was not provided
usage: myprog1.jl [--opt1 OPT1] [-o OPT2] [--flag1] [-h] arg1
$ julia myprog1.jl somearg anotherarg
too many arguments
usage: myprog1.jl [--opt1 OPT1] [-o OPT2] [--flag1] [-h] arg1
$ julia myprog1.jl --opt2 1.5 somearg
invalid argument: 1.5 (conversion to type Int64 failed; you may need to overload ArgParse.parse_item;
the error was: ArgumentError("invalid base 10 digit '.' in \"1.5\""))
usage: myprog1.jl [--opt1 OPT1] [-o OPT2] [--flag1] arg1
```
When everything goes fine instead, our program will print the resulting `Dict`:
```text
$ julia myprog1.jl somearg
Parsed args:
arg1 => somearg
opt2 => 0
opt1 => nothing
flag1 => false
$ julia myprog1.jl --opt1 "2+2" --opt2 "4" somearg --flag
Parsed args:
arg1 => somearg
opt2 => 4
opt1 => 2+2
flag1 => true
```
From these examples, a number of things can be noticed:
* `opt1` defaults to `nothing`, since no `default` setting was used for it in `@add_arg_table!`
* `opt1` argument type, begin unspecified, defaults to `Any`, but in practice it's parsed as a
string (e.g. `"2+2"`)
* `opt2` instead has `Int` argument type, so `"4"` will be parsed and converted to an integer,
an error is emitted if the conversion fails
* positional arguments can be passed in between options
* long options can be passed in abbreviated form (e.g. `--flag` instead of `--flag1`) as long as
there's no ambiguity
More examples can be found in the `examples` directory, and the complete documentation in the
manual pages.
## Contents
```@contents
Pages = [
"parse_args.md",
"settings.md",
"arg_table.md",
"import.md",
"conflicts.md",
"custom.md",
"details.md"
]
```
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 54 | # The `parse_args` function
```@docs
parse_args
```
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 1.2.0 | 22cf435ac22956a7b45b0168abbc871176e7eecc | docs | 59 | # Settings
```@docs
ArgParseSettings
@project_version
```
| ArgParse | https://github.com/carlobaldassi/ArgParse.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 1305 | import StatsBase
function bootstrap_filter(
rng::AbstractRNG,
ys::AbstractVecOrMat,
init::AbstractDistribution,
fw_kernel::AbstractMarkovKernel,
m_kernel::AbstractMarkovKernel,
K::Integer,
)
# initialize
X = [rand(rng, init) for k in 1:K]
P = ParticleSystem(zeros(K), X)
loglike = 0.0
L = Likelihood(m_kernel, ys[1, :])
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
Ps = [P]
sizehint!(Ps, size(ys, 1))
for m in 2:size(ys, 1)
L = Likelihood(m_kernel, ys[m, :])
P = predict(rng, P, fw_kernel)
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
push!(Ps, P)
end
return Ps, loglike
end
function resample!(rng::AbstractRNG, P::ParticleSystem{T,U,<:AbstractVector}) where {T,U}
idx = StatsBase.wsample(rng, eachindex(logweights(P)), weights(P), nparticles(P))
logweights(P)[:] .= zero(logweights(P))
particles(P)[:] .= particles(P)[idx]
end
function predict(
rng::AbstractRNG,
P::ParticleSystem{T,U,<:AbstractVector},
K::AbstractMarkovKernel,
) where {T,U}
X = [rand(rng, K, particles(P)[i]) for i in eachindex(particles(P))]
return ParticleSystem(copy(logweights(P)), X)
end
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 1257 | function bootstrap_smoother(
rng::AbstractRNG,
ys::AbstractVecOrMat,
init::AbstractDistribution,
fw_kernel::AbstractMarkovKernel,
m_kernel::AbstractMarkovKernel,
K::Integer,
)
# initialize
X = permutedims([rand(rng, init) for k in 1:K])
P = ParticleSystem(zeros(K), X)
loglike = 0.0
L = Likelihood(m_kernel, ys[1, :])
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
for m in 2:size(ys, 1)
L = Likelihood(m_kernel, ys[m, :])
P = predict(rng, P, fw_kernel)
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
end
return P, loglike
end
function resample!(rng::AbstractRNG, P::ParticleSystem{T,U,<:AbstractMatrix}) where {T,U}
idx = wsample(rng, eachindex(logweights(P)), weights(P), nparticles(P))
logweights(P)[:] .= zero(logweights(P))
particles(P)[:, :] .= particles(P)[:, idx]
end
function predict(
rng::AbstractRNG,
P::ParticleSystem{T,U,<:AbstractMatrix},
K::AbstractMarkovKernel,
) where {T,U}
X = [rand(rng, K, particles(P)[end, i]) for i in 1:nparticles(P)]
return ParticleSystem(logweights(P), vcat(particles(P), permutedims(X)))
end
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 4085 | using MarkovKernels
using LinearAlgebra, Plots, Random, IterTools
## sample a partially observed Gauss-Markov process
rng = MersenneTwister(1991)
function sample(rng, init, K, nstep)
it = Iterators.take(iterated(z -> rand(rng, K, z), rand(rng, init)), nstep + 1)
return mapreduce(permutedims, vcat, collect(it))
end
# time grid
m = 200
T = 5.0
ts = collect(LinRange(0.0, T, m))
dt = T / (m - 1)
# define transtion kernel
λ = 2.0
Φ = exp(-λ * dt) .* [1.0 0.0; -2*λ*dt 1.0]
Q = 1.0I - exp(-2 * λ * dt) .* [1.0 -2*λ*dt; -2*λ*dt 1.0+(2*λ*dt)^2]
fw_kernel = NormalKernel(Φ, Q)
# initial distribution
init = Normal(zeros(2), diagm(ones(2)))
# sample state
xs = sample(rng, init, fw_kernel, m - 1)
# output kernel and measurement kernel
C = 1.0 / sqrt(2) * [1.0 -1.0]
output_kernel = DiracKernel(C)
R = fill(0.1, 1, 1)
m_kernel = compose(NormalKernel(1.0I(1), R), output_kernel)
# sample output and its measurements
zs = mapreduce(z -> rand(rng, output_kernel, xs[z, :]), vcat, 1:m)
ys = mapreduce(z -> rand(rng, m_kernel, xs[z, :]), vcat, 1:m)
## implement a the Kalman filter
function kalman_filter(
ys::AbstractVecOrMat,
init::AbstractNormal,
fw_kernel::AbstractNormalKernel,
m_kernel::AbstractNormalKernel,
)
# initialise recursion
filter_distribution = init
filter_distributions = typeof(init)[]
# initial measurement update
likelihood = Likelihood(m_kernel, ys[1, :])
filter_distribution, loglike_increment = bayes_rule(filter_distribution, likelihood)
push!(filter_distributions, filter_distribution)
loglike = loglike_increment
for m in 2:size(ys, 1)
# predict
filter_distribution = marginalize(filter_distribution, fw_kernel)
# measurement update
likelihood = Likelihood(m_kernel, ys[m, :])
filter_distribution, loglike_increment = bayes_rule(filter_distribution, likelihood)
push!(filter_distributions, filter_distribution)
loglike = loglike + loglike_increment
end
return filter_distributions, loglike
end
## run Kalman filter and plot the results
filter_distributions, loglike = kalman_filter(ys, init, fw_kernel, m_kernel)
state_filter_plt = plot(
ts,
xs,
layout = (2, 1),
xlabel = ["" "t"],
label = ["x1" "x2"],
title = ["Filter estimates of the state" ""],
)
plot!(ts, filter_distributions, layout = (2, 1), label = ["x1filter" "x2filter"])
display(state_filter_plt)
## computing the output estimates
output_filter_estimate = map(z -> marginalize(z, output_kernel), filter_distributions)
output_filter_plt = plot(ts, zs, label = "output", xlabel = "t")
scatter!(ts, ys, label = "measurement", color = "black")
plot!(ts, output_filter_estimate, label = "filter estimate")
display(output_filter_plt)
## implement Rauch-Tung-Striebel recursion
function rts(filter_distributions, fw_kernel)
smoother_distribution = filter_distributions[end]
smoother_distributions = similar(filter_distributions)
smoother_distributions[end] = smoother_distribution
for m in length(smoother_distributions)-1:-1:1
pred, bw_kernel = invert(filter_distributions[m], fw_kernel)
smoother_distribution = marginalize(smoother_distribution, bw_kernel)
smoother_distributions[m] = smoother_distribution
end
return smoother_distributions
end
## Computing the snmoothed state estimate
smoother_distributions = rts(filter_distributions, fw_kernel)
state_smoother_plt = plot(
ts,
xs,
layout = (2, 1),
xlabel = ["" "t"],
label = ["x1" "x2"],
title = ["Smoother estimates of the state" ""],
)
plot!(ts, smoother_distributions, layout = (2, 1), label = ["x1smoother" "x2smoother"])
display(state_smoother_plt)
## Computing the smoothed output estimate
output_smoother_estimate = map(z -> marginalize(z, output_kernel), smoother_distributions)
output_smoother_plt = plot(ts, zs, label = "output", xlabel = "t")
scatter!(ts, ys, label = "measurement", color = "black")
plot!(ts, output_smoother_estimate, label = "smoother estimate")
display(output_smoother_plt)
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 1346 | """
kalman_filter(
ys::AbstractVecOrMat,
init::AbstractNormal,
fw_kernel::AbstractNormalKernel,
m_kernel::AbstractNormalKernel,
)
Computes the filtering distributions and loglikelihood
in the following state-space model
x_1 ∼ init
x_m | x_{m-1} ∼ fw_kernel(·, x_{m-1})
y_m | x_m ∼ m_kernel(·, x_m)
for the masurements y_1, ..., y_n.
"""
function kalman_filter(
ys::AbstractVecOrMat,
init::AbstractNormal,
fw_kernel::AbstractNormalKernel,
m_kernel::AbstractNormalKernel,
)
# initialise recursion
filter_distribution = init
filter_distributions = typeof(init)[]
# initial measurement update
likelihood = Likelihood(m_kernel, ys[1, :])
filter_distribution, loglike_increment = bayes_rule(filter_distribution, likelihood)
push!(filter_distributions, filter_distribution)
loglike = loglike_increment
for m in 2:size(ys, 1)
# predict
filter_distribution = marginalize(filter_distribution, fw_kernel)
# measurement update
likelihood = Likelihood(m_kernel, ys[m, :])
filter_distribution, loglike_increment = bayes_rule(filter_distribution, likelihood)
push!(filter_distributions, filter_distribution)
loglike = loglike + loglike_increment
end
return filter_distributions, loglike
end
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 5588 | # Bootstrap filtering and smoothing
## Setting up the environment and generating some data
using MarkovKernels
using Plots, Random
using IterTools
import StatsBase: wsample
rng = MersenneTwister(1991)
function sample(rng, init, K, nstep)
it = Iterators.take(iterated(z -> rand(rng, K, z), rand(rng, init)), nstep + 1)
return mapreduce(permutedims, vcat, collect(it))
end
# time grid
m = 50
T = 5
ts = collect(LinRange(0, T, m))
dt = T / (m - 1)
# define transtion kernel
λ = 1.0
Φ = exp(-λ * dt) .* [1.0 0.0; -2*λ*dt 1.0]
Q = I - exp(-2 * λ * dt) .* [1.0 -2*λ*dt; -2*λ*dt 1+(2*λ*dt)^2]
fw_kernel = NormalKernel(Φ, Q)
# initial distribution
init = Normal(zeros(2), 1.0I(2))
# sample state
xs = sample(rng, init, fw_kernel, m - 1)
# output kernel
σ = 5.0
C = σ / sqrt(2) * [1.0 -1.0]
output_kernel = DiracKernel(C)
variance(x) = fill(exp.(x)[1], 1, 1)
m_kernel = compose(NormalKernel(zeros(1, 1), variance), output_kernel)
# sample output
zs = mapreduce(z -> rand(rng, output_kernel, xs[z, :]), vcat, 1:m)
ys = mapreduce(z -> rand(rng, m_kernel, xs[z, :]), vcat, 1:m)
measurement_plt = scatter(ts, ys, label = "measurements", color = "black")
display(measurement_plt)
## Implementing a bootstrap filter
function bootstrap_filter(
rng::AbstractRNG,
ys::AbstractVecOrMat,
init::AbstractDistribution,
fw_kernel::AbstractMarkovKernel,
m_kernel::AbstractMarkovKernel,
K::Integer,
)
# initialize
X = [rand(rng, init) for k in 1:K]
P = ParticleSystem(zeros(K), X)
loglike = 0.0
L = Likelihood(m_kernel, ys[1, :])
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
Ps = [P]
sizehint!(Ps, size(ys, 1))
for m in 2:size(ys, 1)
L = Likelihood(m_kernel, ys[m, :])
P = predict(rng, P, fw_kernel)
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
push!(Ps, P)
end
return Ps, loglike
end
function resample!(rng::AbstractRNG, P::ParticleSystem{T,U,<:AbstractVector}) where {T,U}
idx = wsample(rng, eachindex(logweights(P)), weights(P), nparticles(P))
logweights(P)[:] .= zero(logweights(P))
particles(P)[:] .= particles(P)[idx]
end
function predict(
rng::AbstractRNG,
P::ParticleSystem{T,U,<:AbstractVector},
K::AbstractMarkovKernel,
) where {T,U}
X = [rand(rng, K, particles(P)[i]) for i in eachindex(particles(P))]
return ParticleSystem(copy(logweights(P)), X)
end
## Computing the filtered state estimates
K = 500
Pfilt, loglike_filt = bootstrap_filter(rng, ys, init, fw_kernel, m_kernel, K)
Xfilt = mapreduce(permutedims, vcat, particles.(Pfilt))
state_filt_plt = plot(
ts,
xs,
layout = (2, 1),
xlabel = "t",
labels = ["x1" "x2"],
title = ["Latent Gauss-Markov process" ""],
)
for k in 1:K
scatter!(
ts,
mapreduce(permutedims, vcat, Xfilt[:, k]),
markersize = 1,
color = "red",
alpha = 0.025,
label = "",
)
end
display(state_filt_plt)
## Computing the filtered output estimates
bf_output_filt = [marginalize(Pfilt[i], output_kernel) for i in eachindex(Pfilt)]
Zfilt = getindex.(mapreduce(permutedims, vcat, particles.(bf_output_filt)), 1)
output_filt_plt = plot(ts, zs, label = "output", xlabel = "t", title = "log-variance")
scatter!(ts, Zfilt, markersize = 1, color = "red", alpha = 0.01, label = "")
display(output_filt_plt)
## Implementing a bootstrap smoother
function bootstrap_smoother(
rng::AbstractRNG,
ys::AbstractVecOrMat,
init::AbstractDistribution,
fw_kernel::AbstractMarkovKernel,
m_kernel::AbstractMarkovKernel,
K::Integer,
)
# initialize
X = permutedims([rand(rng, init) for k in 1:K])
P = ParticleSystem(zeros(K), X)
loglike = 0.0
L = Likelihood(m_kernel, ys[1, :])
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
for m in 2:size(ys, 1)
L = Likelihood(m_kernel, ys[m, :])
P = predict(rng, P, fw_kernel)
loglike_incr = bayes_rule!(P, L)
loglike = loglike + loglike_incr
resample!(rng, P)
end
return P, loglike
end
function resample!(rng::AbstractRNG, P::ParticleSystem{T,U,<:AbstractMatrix}) where {T,U}
idx = wsample(rng, eachindex(logweights(P)), weights(P), nparticles(P))
logweights(P)[:] .= zero(logweights(P))
particles(P)[:, :] .= particles(P)[:, idx]
end
function predict(
rng::AbstractRNG,
P::ParticleSystem{T,U,<:AbstractMatrix},
K::AbstractMarkovKernel,
) where {T,U}
X = [rand(rng, K, particles(P)[end, i]) for i in 1:nparticles(P)]
return ParticleSystem(logweights(P), vcat(particles(P), permutedims(X)))
end
## Computing the smoothed state estimates
Psmooth, loglike_smooth = bootstrap_smoother(rng, ys, init, fw_kernel, m_kernel, K)
Xsmooth = particles(Psmooth)
state_smooth_plt = plot(
ts,
xs,
layout = (2, 1),
xlabel = "t",
labels = ["x1" "x2"],
title = ["Latent Gauss-Markov process" ""],
)
for k in 1:K
plot!(
ts,
mapreduce(permutedims, vcat, Xsmooth[:, k]),
color = "green",
alpha = 0.025,
label = "",
)
end
display(state_smooth_plt)
## Computing the smoothed output estimate
bf_output_smooth = marginalize(Psmooth, output_kernel)
Zsmooth = getindex.(particles(bf_output_smooth), 1)
output_smooth_plt = plot(ts, zs, label = "output", xlabel = "t", title = "log-variance")
plot!(ts, Zsmooth, color = "green", alpha = 0.025, label = "")
display(output_smooth_plt)
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 1376 | """
kalman_smoother(
ys::AbstractVecOrMat,
init::AbstractNormal,
fw_kernel::AbstractNormalKernel,
m_kernel::AbstractNormalKernel,
)
Computes the smoothing, filtering distributions and loglikelihood
in the following state-space model
x_1 ∼ init
x_m | x_{m-1} ∼ fw_kernel(·, x_{m-1})
y_m | x_m ∼ m_kernel(·, x_m)
for the masurements y_1, ..., y_n.
"""
function rts(
ys::AbstractVecOrMat,
init::AbstractNormal,
fw_kernel::AbstractNormalKernel,
m_kernel::AbstractNormalKernel,
)
# run a Kalman filter
filter_distributions, loglike = kalman_filter(ys, init, fw_kernel, m_kernel)
# compute the backward kenrles for the Rauch-Tung-Striebel recursion
bw_kernels = NormalKernel[]
for m in 1:length(filter_distributions)-1
pred, bw_kernel = invert(filter_distributions[m], fw_kernel)
push!(bw_kernels, bw_kernel)
end
# compute the smoother estimates
smoother_distributions = Normal[]
smoother_distribution = filter_distributions[end]
pushfirst!(smoother_distributions, smoother_distribution)
for m in length(filter_distributions)-1:-1:1
smoother_distribution = marginalize(smoother_distribution, bw_kernels[m])
pushfirst!(smoother_distributions, smoother_distribution)
end
return smoother_distributions, filter_distributions, loglike
end
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
|
[
"MIT"
] | 0.2.1 | 2c9e22a885139350915b03316eba735174d4eb13 | code | 1346 | using MarkovKernels
using Plots, Random, LinearAlgebra, IterTools
# sample a homogeneous Markov model
function sample(rng, init, K, nstep)
x = rand(rng, init)
it = Iterators.take(iterated(z -> rand(rng, K, z), x), nstep + 1)
return mapreduce(permutedims, vcat, collect(it))
end
# set rng
rng = MersenneTwister(1991)
# time grid
m = 200
T = 5
ts = collect(LinRange(0, T, m))
dt = T / (m - 1)
# transtion kernel
λ = 2.0
Φ = exp(-λ * dt) .* [1.0 0.0; -2*λ*dt 1.0]
Q = I - exp(-2 * λ * dt) .* [1.0 -2*λ*dt; -2*λ*dt 1+(2*λ*dt)^2]
fw_kernel = NormalKernel(Φ, Q)
# initial distribution
init = Normal(zeros(2), 1.0I(2))
# sample state
xs = sample(rng, init, fw_kernel, m - 1)
state_plt = plot(
ts,
xs,
layout = (2, 1),
xlabel = "t",
labels = ["x1" "x2"],
title = ["Latent Gauss-Markov process" ""],
)
display(state_plt)
# output kernel and measurement kernel
C = 1.0 / sqrt(2) * [1.0 -1.0]
output_kernel = DiracKernel(C)
R = fill(0.1, 1, 1)
m_kernel = compose(NormalKernel(1.0I(1), R), output_kernel)
# sample output and its measurements
outs = mapreduce(z -> rand(rng, output_kernel, xs[z, :]), vcat, 1:m)
ys = mapreduce(z -> rand(rng, m_kernel, xs[z, :]), vcat, 1:m)
output_plot = plot(ts, outs, label = "output", xlabel = "t")
scatter!(ts, ys, label = "measurement", color = "black")
display(output_plot)
| MarkovKernels | https://github.com/filtron/MarkovKernels.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.