Skip to content

Instantly share code, notes, and snippets.

@lazalong
Last active November 26, 2023 01:14
Show Gist options
  • Save lazalong/d99d73dca40470be372c2deebc262c4a to your computer and use it in GitHub Desktop.
Save lazalong/d99d73dca40470be372c2deebc262c4a to your computer and use it in GitHub Desktop.
Snippet to draw a 3D object in a v ui.CanvasLayout
// Interface `ui.GGApplication`
fn (mut app AppState) on_draw() {
window_size := app.gg.window_size()
mut cc := app.win.get_or_panic[ui.CanvasLayout](ui.component_id('canvaslayout', 'layout'))
sgl.viewport(cc.x, cc.y, cc.width, cc.height, true)
mut ctx := app.gg
// Draw a triangle
ctx.draw_triangle_filled(450, 142, 530, 280, 370, 280, gx.red)
// Draw 3D stuff
sgl.defaults()
sgl.load_pipeline(pip_3d)
sgl.perspective(sgl.rad(45.0), 1.0, 0.1, 100.0)
sgl.translate(0.0, 0.0, -12.0)
rot := [f32(0.0), f32(30.0)]
sgl.rotate(sgl.rad(rot[0]), 1.0, 0.0, 0.0)
sgl.rotate(sgl.rad(rot[1]), 0.0, 1.0, 0.0)
draw_cube()
// Set back settings for the ui to draw correctly
sgl.defaults()
sgl.ortho(0.0, window_size.width, window_size.height, 0.0, 0.1, 100.0)
sgl.viewport(0, 0, window_size.width, window_size.height, true)
sgl.translate(0.0, 0.0, -1.0) // Super critical !!! Wihout this nothing shows
}
// Set the ui.window.win_init with this to set the 3D pipeline
fn win_init(w &ui.Window) {
println("ui.Window init")
// 3d pipeline
mut pipdesc := gfx.PipelineDesc{}
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
color_state := gfx.ColorTargetState{
blend: gfx.BlendState{
enabled: true
src_factor_rgb: .src_alpha
dst_factor_rgb: .one_minus_src_alpha
}
}
pipdesc.colors[0] = color_state
pipdesc.depth = gfx.DepthState{
write_enabled: true
compare: .less_equal
}
pipdesc.cull_mode = .back
//- app.pip_3d = sgl.make_pipeline(&pipdesc)
pip_3d = sgl.make_pipeline(&pipdesc) // stored as global
}
fn draw_cube() {
sgl.begin_qu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)
sgl.v3f_t2f(1.0, 1.0, -1.0, -1.0, -1.0)
sgl.end()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment