examples: make `v -prod build-examples` pass without warnings/errors

pull/6640/head
Delyan Angelov 2020-10-18 09:48:13 +03:00
parent 67ecc04580
commit 8b2e704741
9 changed files with 594 additions and 512 deletions

View File

@ -5,13 +5,13 @@ import gx
import os import os
const ( const (
win_width = 600 win_width = 600
win_height = 700 win_height = 700
bg_color = gx.white bg_color = gx.white
) )
const ( const (
text = ' text = '
Once upon a midnight dreary, while I pondered, weak and weary, Once upon a midnight dreary, while I pondered, weak and weary,
Over many a quaint and curious volume of forgotten lore Over many a quaint and curious volume of forgotten lore
While I nodded, nearly napping, suddenly there came a tapping, While I nodded, nearly napping, suddenly there came a tapping,
@ -54,17 +54,18 @@ Soon again I heard a tapping somewhat louder than before.
Let my heart be still a moment and this mystery explore; Let my heart be still a moment and this mystery explore;
Tis the wind and nothing more! Tis the wind and nothing more!
' '
lines = text.split('\n') lines = text.split('\n')
) )
struct App { struct App {
mut: mut:
gg &gg.Context gg &gg.Context
} }
fn main() { fn main() {
mut app := &App{} mut app := &App{
gg: 0
}
app.gg = gg.new_context({ app.gg = gg.new_context({
width: win_width width: win_width
height: win_height height: win_height
@ -74,8 +75,7 @@ fn main() {
user_data: app user_data: app
bg_color: bg_color bg_color: bg_color
frame_fn: frame frame_fn: frame
font_path: os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf') font_path: os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf') // window_user_ptr: ctx
//window_user_ptr: ctx
}) })
app.gg.run() app.gg.run()
} }
@ -89,4 +89,3 @@ fn frame(mut app App) {
} }
app.gg.end() app.gg.end()
} }

View File

@ -5,19 +5,21 @@ import gx
import os import os
const ( const (
win_width = 600 win_width = 600
win_height = 300 win_height = 300
) )
struct App { struct App {
mut: mut:
gg &gg.Context gg &gg.Context
image gg.Image image gg.Image
} }
fn main() { fn main() {
mut app := &App{} mut app := &App{
app.gg = gg.new_context( gg: 0
}
app.gg = gg.new_context({
bg_color: gx.white bg_color: gx.white
width: win_width width: win_width
height: win_height height: win_height
@ -27,13 +29,13 @@ fn main() {
frame_fn: frame frame_fn: frame
user_data: app user_data: app
init_fn: init_images init_fn: init_images
) })
app.image = app.gg.create_image(os.resource_abs_path('logo.png')) app.image = app.gg.create_image(os.resource_abs_path('logo.png'))
app.gg.run() app.gg.run()
} }
fn init_images(mut app App) { fn init_images(mut app App) {
//app.image = gg.create_image('logo.png') // app.image = gg.create_image('logo.png')
} }
fn frame(app &App) { fn frame(app &App) {
@ -43,9 +45,9 @@ fn frame(app &App) {
} }
fn (app &App) draw() { fn (app &App) draw() {
//app.gg.draw_text_def(200,20, 'hello world!') // app.gg.draw_text_def(200,20, 'hello world!')
//app.gg.draw_text_def(300,300, 'привет') // app.gg.draw_text_def(300,300, 'привет')
app.gg.draw_rect(10, 10, 100, 30, gx.blue) app.gg.draw_rect(10, 10, 100, 30, gx.blue)
app.gg.draw_empty_rect(110, 150, 80, 40, gx.black) app.gg.draw_empty_rect(110, 150, 80, 40, gx.black)
app.gg.draw_image(230,30,app.image.width,app.image.height, app.image) app.gg.draw_image(230, 30, app.image.width, app.image.height, app.image)
} }

View File

@ -1,7 +1,6 @@
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved. // Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license // Use of this source code is governed by an MIT license
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
module main module main
import os import os
@ -12,27 +11,27 @@ import gg
import sokol.sapp import sokol.sapp
const ( const (
block_size = 20 // pixels block_size = 20 // pixels
field_height = 20 // # of blocks field_height = 20 // # of blocks
field_width = 10 field_width = 10
tetro_size = 4 tetro_size = 4
win_width = block_size * field_width win_width = block_size * field_width
win_height = block_size * field_height win_height = block_size * field_height
timer_period = 250 // ms timer_period = 250 // ms
text_size = 24 text_size = 24
limit_thickness = 3 limit_thickness = 3
) )
const ( const (
text_cfg = gx.TextCfg{ text_cfg = gx.TextCfg{
align:.left align: .left
size:text_size size: text_size
color:gx.rgb(0, 0, 0) color: gx.rgb(0, 0, 0)
} }
over_cfg = gx.TextCfg{ over_cfg = gx.TextCfg{
align:.left align: .left
size:text_size size: text_size
color:gx.white color: gx.white
} }
) )
@ -43,7 +42,7 @@ const (
// 0110 6 0010 2 0011 3 0110 6 0001 1 0010 2 // 0110 6 0010 2 0011 3 0110 6 0001 1 0010 2
// 0110 6 0111 7 0110 6 0011 3 0001 1 0010 2 // 0110 6 0111 7 0110 6 0011 3 0001 1 0010 2
// There is a special case 1111, since 15 can't be used. // There is a special case 1111, since 15 can't be used.
b_tetros = [ b_tetros = [
[66, 66, 66, 66], [66, 66, 66, 66],
[27, 131, 72, 232], [27, 131, 72, 232],
[36, 231, 36, 231], [36, 231, 36, 231],
@ -53,80 +52,84 @@ const (
[1111, 9, 1111, 9], [1111, 9, 1111, 9],
] ]
// Each tetro has its unique color // Each tetro has its unique color
colors = [ colors = [
gx.rgb(0, 0, 0), // unused ? gx.rgb(0, 0, 0), // unused ?
gx.rgb(255, 242, 0), // yellow quad gx.rgb(255, 242, 0), // yellow quad
gx.rgb(174, 0, 255), // purple triple gx.rgb(174, 0, 255), // purple triple
gx.rgb(60, 255, 0), // green short topright gx.rgb(60, 255, 0), // green short topright
gx.rgb(255, 0, 0), // red short topleft gx.rgb(255, 0, 0), // red short topleft
gx.rgb(255, 180, 31), // orange long topleft gx.rgb(255, 180, 31), // orange long topleft
gx.rgb(33, 66, 255), // blue long topright gx.rgb(33, 66, 255), // blue long topright
gx.rgb(74, 198, 255), // lightblue longest gx.rgb(74, 198, 255), // lightblue longest
gx.rgb(0, 170, 170), // unused ? gx.rgb(0, 170, 170), // unused ?
] ]
background_color = gx.white background_color = gx.white
ui_color = gx.rgba(255,0,0, 210) ui_color = gx.rgba(255, 0, 0, 210)
) )
// TODO: type Tetro [tetro_size]struct{ x, y int } // TODO: type Tetro [tetro_size]struct{ x, y int }
struct Block { struct Block {
mut: mut:
x int x int
y int y int
} }
enum GameState { enum GameState {
paused running gameover paused
running
gameover
} }
struct Game { struct Game {
mut: mut:
// Score of the current game // Score of the current game
score int score int
// Lines of the current game // Lines of the current game
lines int lines int
// State of the current game // State of the current game
state GameState state GameState
// Position of the current tetro // Position of the current tetro
pos_x int pos_x int
pos_y int pos_y int
// field[y][x] contains the color of the block with (x,y) coordinates // field[y][x] contains the color of the block with (x,y) coordinates
// "-1" border is to avoid bounds checking. // "-1" border is to avoid bounds checking.
// -1 -1 -1 -1 // -1 -1 -1 -1
// -1 0 0 -1 // -1 0 0 -1
// -1 0 0 -1 // -1 0 0 -1
// -1 -1 -1 -1 // -1 -1 -1 -1
field [][]int field [][]int
// TODO: tetro Tetro // TODO: tetro Tetro
tetro []Block tetro []Block
// TODO: tetros_cache []Tetro // TODO: tetros_cache []Tetro
tetros_cache []Block tetros_cache []Block
// Index of the current tetro. Refers to its color. // Index of the current tetro. Refers to its color.
tetro_idx int tetro_idx int
// Idem for the next tetro // Idem for the next tetro
next_tetro_idx int next_tetro_idx int
// Index of the rotation (0-3) // Index of the rotation (0-3)
rotation_idx int rotation_idx int
// gg context for drawing // gg context for drawing
gg &gg.Context = voidptr(0) gg &gg.Context = voidptr(0)
font_loaded bool font_loaded bool
show_ghost bool show_ghost bool
// frame/time counters: // frame/time counters:
frame int frame int
frame_old int frame_old int
frame_sw time.StopWatch = time.new_stopwatch({}) frame_sw time.StopWatch = time.new_stopwatch({})
second_sw time.StopWatch = time.new_stopwatch({}) second_sw time.StopWatch = time.new_stopwatch({})
} }
const ( fpath = os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf') ) const (
fpath = os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf')
)
[if showfps] [if showfps]
fn (mut game Game) showfps() { fn (mut game Game) showfps() {
game.frame++ game.frame++
last_frame_ms := f64(game.frame_sw.elapsed().microseconds())/1000.0 last_frame_ms := f64(game.frame_sw.elapsed().microseconds()) / 1000.0
ticks := f64(game.second_sw.elapsed().microseconds())/1000.0 ticks := f64(game.second_sw.elapsed().microseconds()) / 1000.0
if ticks > 999.0 { if ticks > 999.0 {
fps := f64(game.frame - game.frame_old)*ticks/1000.0 fps := f64(game.frame - game.frame_old) * ticks / 1000.0
$if debug { $if debug {
eprintln('fps: ${fps:5.1f} | last frame took: ${last_frame_ms:6.3f}ms | frame: ${game.frame:6} ') eprintln('fps: ${fps:5.1f} | last frame took: ${last_frame_ms:6.3f}ms | frame: ${game.frame:6} ')
} }
@ -143,25 +146,22 @@ fn frame(mut game Game) {
game.gg.end() game.gg.end()
} }
fn main() { fn main() {
mut game := &Game{ mut game := &Game{
gg: 0 gg: 0
} }
game.gg = gg.new_context( game.gg = gg.new_context({
bg_color: gx.white bg_color: gx.white
width: win_width width: win_width
height: win_height height: win_height
use_ortho: true // This is needed for 2D drawing use_ortho: true // This is needed for 2D drawing
create_window: true create_window: true
window_title: 'V Tetris' window_title: 'V Tetris' //
//
user_data: game user_data: game
frame_fn: frame frame_fn: frame
event_fn: on_event event_fn: on_event
font_path: fpath font_path: fpath // wait_events: true
//wait_events: true })
)
game.init_game() game.init_game()
go game.run() // Run the game loop in a new thread go game.run() // Run the game loop in a new thread
game.gg.run() // Run the render loop in the main thread game.gg.run() // Run the render loop in the main thread
@ -169,21 +169,21 @@ fn main() {
fn (mut g Game) init_game() { fn (mut g Game) init_game() {
g.parse_tetros() g.parse_tetros()
g.next_tetro_idx = rand.intn(b_tetros.len) // generate initial "next" g.next_tetro_idx = rand.intn(b_tetros.len) // generate initial "next"
g.generate_tetro() g.generate_tetro()
g.field = [] g.field = []
// Generate the field, fill it with 0's, add -1's on each edge // Generate the field, fill it with 0's, add -1's on each edge
for _ in 0..field_height + 2 { for _ in 0 .. field_height + 2 {
mut row := [0].repeat(field_width + 2) mut row := [0].repeat(field_width + 2)
row[0] = - 1 row[0] = -1
row[field_width + 1] = - 1 row[field_width + 1] = -1
g.field << row g.field << row
} }
mut first_row := g.field[0] mut first_row := g.field[0]
mut last_row := g.field[field_height + 1] mut last_row := g.field[field_height + 1]
for j in 0..field_width + 2 { for j in 0 .. field_width + 2 {
first_row[j] = - 1 first_row[j] = -1
last_row[j] = - 1 last_row[j] = -1
} }
g.score = 0 g.score = 0
g.lines = 0 g.lines = 0
@ -206,7 +206,7 @@ fn (mut g Game) run() {
g.move_tetro() g.move_tetro()
g.delete_completed_lines() g.delete_completed_lines()
} }
//glfw.post_empty_event() // force window redraw // glfw.post_empty_event() // force window redraw
time.sleep_ms(timer_period) time.sleep_ms(timer_period)
} }
} }
@ -214,7 +214,7 @@ fn (mut g Game) run() {
fn (g &Game) draw_ghost() { fn (g &Game) draw_ghost() {
if g.state != .gameover && g.show_ghost { if g.state != .gameover && g.show_ghost {
pos_y := g.move_ghost() pos_y := g.move_ghost()
for i in 0..tetro_size { for i in 0 .. tetro_size {
tetro := g.tetro[i] tetro := g.tetro[i]
g.draw_block_color(pos_y + tetro.y, g.pos_x + tetro.x, gx.gray) g.draw_block_color(pos_y + tetro.y, g.pos_x + tetro.x, gx.gray)
} }
@ -262,7 +262,7 @@ fn (mut g Game) move_tetro() bool {
fn (mut g Game) move_right(dx int) bool { fn (mut g Game) move_right(dx int) bool {
// Reached left/right edge or another tetro? // Reached left/right edge or another tetro?
for i in 0..tetro_size { for i in 0 .. tetro_size {
tetro := g.tetro[i] tetro := g.tetro[i]
y := tetro.y + g.pos_y y := tetro.y + g.pos_y
x := tetro.x + g.pos_x + dx x := tetro.x + g.pos_x + dx
@ -314,12 +314,12 @@ fn (mut g Game) generate_tetro() {
// Get the right tetro from cache // Get the right tetro from cache
fn (mut g Game) get_tetro() { fn (mut g Game) get_tetro() {
idx := g.tetro_idx * tetro_size * tetro_size + g.rotation_idx * tetro_size idx := g.tetro_idx * tetro_size * tetro_size + g.rotation_idx * tetro_size
g.tetro = g.tetros_cache[idx..idx+tetro_size] g.tetro = g.tetros_cache[idx..idx + tetro_size]
} }
// TODO mut // TODO mut
fn (mut g Game) drop_tetro() { fn (mut g Game) drop_tetro() {
for i in 0..tetro_size{ for i in 0 .. tetro_size {
tetro := g.tetro[i] tetro := g.tetro[i]
x := tetro.x + g.pos_x x := tetro.x + g.pos_x
y := tetro.y + g.pos_y y := tetro.y + g.pos_y
@ -329,7 +329,7 @@ fn (mut g Game) drop_tetro() {
} }
fn (g &Game) draw_tetro() { fn (g &Game) draw_tetro() {
for i in 0..tetro_size { for i in 0 .. tetro_size {
tetro := g.tetro[i] tetro := g.tetro[i]
g.draw_block(g.pos_y + tetro.y, g.pos_x + tetro.x, g.tetro_idx + 1) g.draw_block(g.pos_y + tetro.y, g.pos_x + tetro.x, g.tetro_idx + 1)
} }
@ -338,25 +338,26 @@ fn (g &Game) draw_tetro() {
fn (g &Game) draw_next_tetro() { fn (g &Game) draw_next_tetro() {
if g.state != .gameover { if g.state != .gameover {
idx := g.next_tetro_idx * tetro_size * tetro_size idx := g.next_tetro_idx * tetro_size * tetro_size
next_tetro := g.tetros_cache[idx..idx+tetro_size] next_tetro := g.tetros_cache[idx..idx + tetro_size]
pos_y := 0 pos_y := 0
pos_x := field_width / 2 - tetro_size / 2 pos_x := field_width / 2 - tetro_size / 2
for i in 0..tetro_size { for i in 0 .. tetro_size {
block := next_tetro[i] block := next_tetro[i]
g.draw_block_color(pos_y + block.y, pos_x + block.x, gx.rgb(220, 220, 220)) g.draw_block_color(pos_y + block.y, pos_x + block.x, gx.rgb(220, 220, 220))
} }
} }
} }
fn (g &Game) draw_block_color(i, j int, color gx.Color) { fn (g &Game) draw_block_color(i int, j int, color gx.Color) {
g.gg.draw_rect(f32((j - 1) * block_size), f32((i - 1) * block_size), g.gg.draw_rect(f32((j - 1) * block_size), f32((i - 1) * block_size), f32(block_size - 1),
f32(block_size - 1), f32(block_size - 1), color) f32(block_size - 1), color)
} }
fn (g &Game) draw_block(i, j, color_idx int) { fn (g &Game) draw_block(i int, j int, color_idx int) {
color := if g.state == .gameover { gx.gray } else { colors[color_idx] } color := if g.state == .gameover { gx.gray } else { colors[color_idx] }
g.draw_block_color(i, j, color) g.draw_block_color(i, j, color)
} }
fn (g &Game) draw_field() { fn (g &Game) draw_field() {
for i := 1; i < field_height + 1; i++ { for i := 1; i < field_height + 1; i++ {
for j := 1; j < field_width + 1; j++ { for j := 1; j < field_width + 1; j++ {
@ -373,17 +374,15 @@ fn (mut g Game) draw_ui() {
lines := g.lines.str() lines := g.lines.str()
g.gg.draw_text(win_width - lines.len * text_size, 3, lines, text_cfg) g.gg.draw_text(win_width - lines.len * text_size, 3, lines, text_cfg)
if g.state == .gameover { if g.state == .gameover {
g.gg.draw_rect(0, win_height / 2 - text_size, win_width, g.gg.draw_rect(0, win_height / 2 - text_size, win_width, 5 * text_size, ui_color)
5 * text_size, ui_color)
g.gg.draw_text(1, win_height / 2 + 0 * text_size, 'Game Over', over_cfg) g.gg.draw_text(1, win_height / 2 + 0 * text_size, 'Game Over', over_cfg)
g.gg.draw_text(1, win_height / 2 + 2 * text_size, 'Space to restart', over_cfg) g.gg.draw_text(1, win_height / 2 + 2 * text_size, 'Space to restart', over_cfg)
} else if g.state == .paused { } else if g.state == .paused {
g.gg.draw_rect(0, win_height / 2 - text_size, win_width, g.gg.draw_rect(0, win_height / 2 - text_size, win_width, 5 * text_size, ui_color)
5 * text_size, ui_color)
g.gg.draw_text(1, win_height / 2 + 0 * text_size, 'Game Paused', text_cfg) g.gg.draw_text(1, win_height / 2 + 0 * text_size, 'Game Paused', text_cfg)
g.gg.draw_text(1, win_height / 2 + 2 * text_size, 'SPACE to resume', text_cfg) g.gg.draw_text(1, win_height / 2 + 2 * text_size, 'SPACE to resume', text_cfg)
} }
//g.gg.draw_rect(0, block_size, win_width, limit_thickness, ui_color) // g.gg.draw_rect(0, block_size, win_width, limit_thickness, ui_color)
} }
fn (mut g Game) draw_scene() { fn (mut g Game) draw_scene() {
@ -398,8 +397,8 @@ fn parse_binary_tetro(t_ int) []Block {
mut t := t_ mut t := t_
mut res := [Block{}].repeat(4) mut res := [Block{}].repeat(4)
mut cnt := 0 mut cnt := 0
horizontal := t == 9// special case for the horizontal line horizontal := t == 9 // special case for the horizontal line
ten_powers := [1000,100,10,1] ten_powers := [1000, 100, 10, 1]
for i := 0; i <= 3; i++ { for i := 0; i <= 3; i++ {
// Get ith digit of t // Get ith digit of t
p := ten_powers[i] p := ten_powers[i]
@ -420,7 +419,7 @@ fn parse_binary_tetro(t_ int) []Block {
} }
fn on_event(e &sapp.Event, mut game Game) { fn on_event(e &sapp.Event, mut game Game) {
//println('code=$e.char_code') // println('code=$e.char_code')
if e.typ == .key_down { if e.typ == .key_down {
game.key_down(e.key_code) game.key_down(e.key_code)
} }
@ -444,7 +443,6 @@ fn (mut game Game) key_down(key sapp.KeyCode) {
} }
else {} else {}
} }
if game.state != .running { if game.state != .running {
return return
} }
@ -463,7 +461,7 @@ fn (mut game Game) key_down(key sapp.KeyCode) {
game.get_tetro() game.get_tetro()
} }
if game.pos_x < 0 { if game.pos_x < 0 {
//game.pos_x = 1 // game.pos_x = 1
} }
} }
.left { .left {
@ -476,11 +474,12 @@ fn (mut game Game) key_down(key sapp.KeyCode) {
game.move_tetro() // drop faster when the player presses <down> game.move_tetro() // drop faster when the player presses <down>
} }
.d { .d {
for game.move_tetro() {} for game.move_tetro() {
}
} }
.g { .g {
game.show_ghost = !game.show_ghost game.show_ghost = !game.show_ghost
} }
else { } else {}
} }
} }

View File

@ -13,13 +13,13 @@ import math
// import time // import time
pub type FNCb = fn (x voidptr) pub type FNCb = fn (x voidptr)
pub type FNEvent = fn (e, x voidptr) pub type FNEvent = fn (e voidptr, x voidptr)
pub type FNFail = fn (msg string, x voidptr) pub type FNFail = fn (msg string, x voidptr)
pub type FNKeyDown = fn (c sapp.KeyCode, m sapp.Modifier, x voidptr) pub type FNKeyDown = fn (c sapp.KeyCode, m sapp.Modifier, x voidptr)
pub type FNMove = fn (x, y f32, z voidptr) pub type FNMove = fn (x f32, y f32, z voidptr)
pub type FNChar = fn (c u32, x voidptr) pub type FNChar = fn (c u32, x voidptr)
@ -43,13 +43,18 @@ pub:
cleanup_fn FNCb = voidptr(0) cleanup_fn FNCb = voidptr(0)
fail_fn FNFail = voidptr(0) fail_fn FNFail = voidptr(0)
event_fn FNEvent = voidptr(0) event_fn FNEvent = voidptr(0)
keydown_fn FNKeyDown = voidptr(0) // special case of event_fn keydown_fn FNKeyDown = voidptr(0)
char_fn FNChar = voidptr(0) // special case of event_fn // special case of event_fn
move_fn FNMove = voidptr(0) // special case of event_fn char_fn FNChar = voidptr(0)
click_fn FNMove = voidptr(0) // special case of event_fn // special case of event_fn
move_fn FNMove = voidptr(0)
// special case of event_fn
click_fn FNMove = voidptr(0)
// special case of event_fn
wait_events bool // set this to true for UIs, to save power wait_events bool // set this to true for UIs, to save power
fullscreen bool fullscreen bool
scale f32 = 1.0 // vid needs this scale f32 = 1.0
// vid needs this
// init_text bool // init_text bool
font_path string font_path string
} }
@ -61,7 +66,8 @@ mut:
// (so that the user can store image ids, not entire Image objects) // (so that the user can store image ids, not entire Image objects)
image_cache []Image image_cache []Image
pub mut: pub mut:
scale f32 = 1.0 // will get set to 2.0 for retina, will remain 1.0 for normal scale f32 = 1.0
// will get set to 2.0 for retina, will remain 1.0 for normal
width int width int
height int height int
clear_pass C.sg_pass_action clear_pass C.sg_pass_action
@ -237,7 +243,7 @@ pub fn (mut ctx Context) set_bg_color(c gx.Color) {
} }
// TODO: Fix alpha // TODO: Fix alpha
pub fn (ctx &Context) draw_rect(x, y, w, h f32, c gx.Color) { pub fn (ctx &Context) draw_rect(x f32, y f32, w f32, h f32, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -250,7 +256,7 @@ pub fn (ctx &Context) draw_rect(x, y, w, h f32, c gx.Color) {
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_triangle(x, y, x2, y2, x3, y3 f32, c gx.Color) { pub fn (ctx &Context) draw_triangle(x f32, y f32, x2 f32, y2 f32, x3 f32, y3 f32, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -262,7 +268,7 @@ pub fn (ctx &Context) draw_triangle(x, y, x2, y2, x3, y3 f32, c gx.Color) {
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_empty_rect(x, y, w, h f32, c gx.Color) { pub fn (ctx &Context) draw_empty_rect(x f32, y f32, w f32, h f32, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -284,7 +290,7 @@ pub fn (ctx &Context) draw_empty_rect(x, y, w, h f32, c gx.Color) {
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_circle_line(x, y f32, r, segments int, c gx.Color) { pub fn (ctx &Context) draw_circle_line(x f32, y f32, r int, segments int, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -302,8 +308,7 @@ pub fn (ctx &Context) draw_circle_line(x, y f32, r, segments int, c gx.Color) {
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_circle(x f32, y f32, r int, segments int, c gx.Color) {
pub fn (ctx &Context) draw_circle(x, y f32, r, segments int, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -322,7 +327,7 @@ pub fn (ctx &Context) draw_circle(x, y f32, r, segments int, c gx.Color) {
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_arc_line(x, y f32, r int, start_angle, arc_angle f32, segments int, c gx.Color) { pub fn (ctx &Context) draw_arc_line(x f32, y f32, r int, start_angle f32, arc_angle f32, segments int, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -345,7 +350,7 @@ pub fn (ctx &Context) draw_arc_line(x, y f32, r int, start_angle, arc_angle f32,
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_arc(x, y f32, r int, start_angle, arc_angle f32, segments int, c gx.Color) { pub fn (ctx &Context) draw_arc(x f32, y f32, r int, start_angle f32, arc_angle f32, segments int, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -396,7 +401,7 @@ fn abs(a f32) f32 {
return -a return -a
} }
pub fn (ctx &Context) draw_line(x, y, x2, y2 f32, c gx.Color) { pub fn (ctx &Context) draw_line(x f32, y f32, x2 f32, y2 f32, c gx.Color) {
if c.a != 255 { if c.a != 255 {
sgl.load_pipeline(ctx.timage_pip) sgl.load_pipeline(ctx.timage_pip)
} }
@ -419,10 +424,10 @@ pub fn (ctx &Context) draw_line(x, y, x2, y2 f32, c gx.Color) {
sgl.end() sgl.end()
} }
pub fn (ctx &Context) draw_rounded_rect(x, y, width, height, radius f32, color gx.Color) { pub fn (ctx &Context) draw_rounded_rect(x f32, y f32, width f32, height f32, radius f32, color gx.Color) {
} }
pub fn (ctx &Context) draw_empty_rounded_rect(x, y, width, height, radius f32, border_color gx.Color) { pub fn (ctx &Context) draw_empty_rounded_rect(x f32, y f32, width f32, height f32, radius f32, border_color gx.Color) {
} }
fn C.WaitMessage() fn C.WaitMessage()

View File

@ -2,17 +2,17 @@
// Use of this source code is governed by an MIT license that can be found in the LICENSE file. // Use of this source code is governed by an MIT license that can be found in the LICENSE file.
module gg module gg
//import gx // import gx
// import sokol.sapp
// import sokol.gfx
import os import os
import sokol import sokol
//import sokol.sapp
import sokol.sgl import sokol.sgl
//import sokol.gfx
import stbi import stbi
pub struct Image { pub struct Image {
pub mut: pub mut:
id int id int
width int width int
height int height int
nr_channels int nr_channels int
@ -21,7 +21,7 @@ pub mut:
ext string ext string
simg_ok bool simg_ok bool
simg C.sg_image simg C.sg_image
path string path string
} }
fn C.sg_isvalid() bool fn C.sg_isvalid() bool
@ -30,8 +30,10 @@ fn C.sg_isvalid() bool
pub fn (mut ctx Context) create_image(file string) Image { pub fn (mut ctx Context) create_image(file string) Image {
if !C.sg_isvalid() { if !C.sg_isvalid() {
// Sokol is not initialized yet, add stbi object to a queue/cache // Sokol is not initialized yet, add stbi object to a queue/cache
//ctx.image_queue << file // ctx.image_queue << file
stb_img := stbi.load(file) or { return Image{} } stb_img := stbi.load(file) or {
return Image{}
}
img := Image{ img := Image{
width: stb_img.width width: stb_img.width
height: stb_img.height height: stb_img.height
@ -57,7 +59,9 @@ fn create_image(file string) Image {
println('gg.create_image(): file not found: $file') println('gg.create_image(): file not found: $file')
return Image{} // none return Image{} // none
} }
stb_img := stbi.load(file) or { return Image{} } stb_img := stbi.load(file) or {
return Image{}
}
mut img := Image{ mut img := Image{
width: stb_img.width width: stb_img.width
height: stb_img.height height: stb_img.height
@ -72,7 +76,9 @@ fn create_image(file string) Image {
} }
pub fn create_image_from_memory(buf byteptr, bufsize int) Image { pub fn create_image_from_memory(buf byteptr, bufsize int) Image {
stb_img := stbi.load_from_memory(buf, bufsize) or { return Image{} } stb_img := stbi.load_from_memory(buf, bufsize) or {
return Image{}
}
mut img := Image{ mut img := Image{
width: stb_img.width width: stb_img.width
height: stb_img.height height: stb_img.height
@ -89,7 +95,7 @@ pub fn create_image_from_byte_array(b []byte) Image {
} }
pub fn (mut img Image) init_sokol_image() &Image { pub fn (mut img Image) init_sokol_image() &Image {
//println('\n init sokol image $img.path ok=$img.simg_ok') // println('\n init sokol image $img.path ok=$img.simg_ok')
mut img_desc := C.sg_image_desc{ mut img_desc := C.sg_image_desc{
width: img.width width: img.width
height: img.height height: img.height
@ -109,7 +115,7 @@ pub fn (mut img Image) init_sokol_image() &Image {
return img return img
} }
pub fn (ctx &Context) draw_image(x, y, width, height f32, img_ &Image) { pub fn (ctx &Context) draw_image(x f32, y f32, width f32, height f32, img_ &Image) {
if img_.id >= ctx.image_cache.len { if img_.id >= ctx.image_cache.len {
eprintln('gg: draw_image() bad img id $img_.id (img cache len = $ctx.image_cache.len)') eprintln('gg: draw_image() bad img id $img_.id (img cache len = $ctx.image_cache.len)')
return return
@ -132,16 +138,16 @@ pub fn (ctx &Context) draw_image(x, y, width, height f32, img_ &Image) {
sgl.texture(img.simg) sgl.texture(img.simg)
sgl.begin_quads() sgl.begin_quads()
sgl.c4b(255, 255, 255, 255) sgl.c4b(255, 255, 255, 255)
sgl.v2f_t2f(x0, y0, u0, v0) sgl.v2f_t2f(x0, y0, u0, v0)
sgl.v2f_t2f(x1, y0, u1, v0) sgl.v2f_t2f(x1, y0, u1, v0)
sgl.v2f_t2f(x1, y1, u1, v1) sgl.v2f_t2f(x1, y1, u1, v1)
sgl.v2f_t2f(x0, y1, u0, v1) sgl.v2f_t2f(x0, y1, u0, v1)
sgl.end() sgl.end()
sgl.disable_texture() sgl.disable_texture()
} }
// TODO remove copy pasta, merge the functions // TODO remove copy pasta, merge the functions
pub fn (ctx &Context) draw_image_flipped(x, y, width, height f32, img_ &Image) { pub fn (ctx &Context) draw_image_flipped(x f32, y f32, width f32, height f32, img_ &Image) {
if img_.id >= ctx.image_cache.len { if img_.id >= ctx.image_cache.len {
eprintln('gg: draw_image() bad img id $img_.id (img cache len = $ctx.image_cache.len)') eprintln('gg: draw_image() bad img id $img_.id (img cache len = $ctx.image_cache.len)')
return return
@ -164,17 +170,15 @@ pub fn (ctx &Context) draw_image_flipped(x, y, width, height f32, img_ &Image) {
sgl.texture(img.simg) sgl.texture(img.simg)
sgl.begin_quads() sgl.begin_quads()
sgl.c4b(255, 255, 255, 255) sgl.c4b(255, 255, 255, 255)
sgl.v2f_t2f(x0, y0, u1, v0) sgl.v2f_t2f(x0, y0, u1, v0)
sgl.v2f_t2f(x1, y0, u0, v0) sgl.v2f_t2f(x1, y0, u0, v0)
sgl.v2f_t2f(x1, y1, u0, v1) sgl.v2f_t2f(x1, y1, u0, v1)
sgl.v2f_t2f(x0, y1, u1, v1) sgl.v2f_t2f(x0, y1, u1, v1)
sgl.end() sgl.end()
sgl.disable_texture() sgl.disable_texture()
} }
pub fn (ctx &Context) draw_image_by_id(x, y, width, height f32, id int) { pub fn (ctx &Context) draw_image_by_id(x f32, y f32, width f32, height f32, id int) {
img := ctx.image_cache[id] img := ctx.image_cache[id]
ctx.draw_image(x,y,width,height,img) ctx.draw_image(x, y, width, height, img)
} }

View File

@ -16,22 +16,21 @@ enum FontVariant {
struct FT { struct FT {
pub: pub:
fons &C.FONScontext fons &C.FONScontext
font_normal int font_normal int
font_bold int font_bold int
font_mono int font_mono int
font_italic int font_italic int
scale f32 = 1.0 scale f32 = 1.0
} }
struct FTConfig { struct FTConfig {
font_path string font_path string
scale f32 = 1.0 scale f32 = 1.0
font_size int font_size int
} }
fn new_ft(c FTConfig) ?&FT{ fn new_ft(c FTConfig) ?&FT {
if c.font_path == '' { if c.font_path == '' {
// Load default font // Load default font
} }
@ -41,7 +40,6 @@ fn new_ft(c FTConfig) ?&FT{
return none return none
} }
} }
mut bytes := []byte{} mut bytes := []byte{}
$if android { $if android {
bytes = os.read_apk_asset(c.font_path) or { bytes = os.read_apk_asset(c.font_path) or {
@ -60,40 +58,38 @@ fn new_ft(c FTConfig) ?&FT{
bytes bytes
} }
mono_path := get_font_path_variant(c.font_path, .mono) mono_path := get_font_path_variant(c.font_path, .mono)
bytes_mono:= os.read_bytes(mono_path) or { bytes_mono := os.read_bytes(mono_path) or {
debug_font_println('failed to load font "$mono_path"') debug_font_println('failed to load font "$mono_path"')
bytes bytes
} }
italic_path := get_font_path_variant(c.font_path, .italic) italic_path := get_font_path_variant(c.font_path, .italic)
bytes_italic:= os.read_bytes(italic_path) or { bytes_italic := os.read_bytes(italic_path) or {
debug_font_println('failed to load font "$italic_path"') debug_font_println('failed to load font "$italic_path"')
bytes bytes
} }
fons := sfons.create(512, 512, 1) fons := sfons.create(512, 512, 1)
return &FT{ return &FT{
fons : fons fons: fons
font_normal: C.fonsAddFontMem(fons, 'sans', bytes.data, bytes.len, false) font_normal: C.fonsAddFontMem(fons, 'sans', bytes.data, bytes.len, false)
font_bold: C.fonsAddFontMem(fons, 'sans', bytes_bold.data, bytes_bold.len, false) font_bold: C.fonsAddFontMem(fons, 'sans', bytes_bold.data, bytes_bold.len, false)
font_mono: C.fonsAddFontMem(fons, 'sans', bytes_mono.data, bytes_mono.len, false) font_mono: C.fonsAddFontMem(fons, 'sans', bytes_mono.data, bytes_mono.len, false)
font_italic: C.fonsAddFontMem(fons, 'sans', bytes_italic.data, bytes_italic.len, false) font_italic: C.fonsAddFontMem(fons, 'sans', bytes_italic.data, bytes_italic.len,
false)
scale: c.scale scale: c.scale
} }
} }
fn (ctx &Context) set_cfg(cfg gx.TextCfg) { fn (ctx &Context) set_cfg(cfg gx.TextCfg) {
if !ctx.font_inited { if !ctx.font_inited {
return return
} }
if cfg.bold { if cfg.bold {
ctx.ft.fons.set_font(ctx.ft.font_bold) ctx.ft.fons.set_font(ctx.ft.font_bold)
} } else if cfg.mono {
else if cfg.mono {
ctx.ft.fons.set_font(ctx.ft.font_mono) ctx.ft.fons.set_font(ctx.ft.font_mono)
} } else if cfg.italic {
else if cfg.italic {
ctx.ft.fons.set_font(ctx.ft.font_italic) ctx.ft.fons.set_font(ctx.ft.font_italic)
} } else {
else {
ctx.ft.fons.set_font(ctx.ft.font_normal) ctx.ft.fons.set_font(ctx.ft.font_normal)
} }
scale := if ctx.ft.scale == 0 { f32(1) } else { ctx.ft.scale } scale := if ctx.ft.scale == 0 { f32(1) } else { ctx.ft.scale }
@ -111,12 +107,12 @@ fn (ctx &Context) set_cfg(cfg gx.TextCfg) {
ctx.ft.fons.vert_metrics(&ascender, &descender, &lh) ctx.ft.fons.vert_metrics(&ascender, &descender, &lh)
} }
pub fn (ctx &Context) draw_text(x, y int, text_ string, cfg gx.TextCfg) { pub fn (ctx &Context) draw_text(x int, y int, text_ string, cfg gx.TextCfg) {
if !ctx.font_inited { if !ctx.font_inited {
eprintln('gg: draw_text(): font not initialized') eprintln('gg: draw_text(): font not initialized')
return return
} }
//text := text_.trim_space() // TODO remove/optimize // text := text_.trim_space() // TODO remove/optimize
mut text := text_ mut text := text_
if text.contains('\t') { if text.contains('\t') {
text = text.replace('\t', ' ') text = text.replace('\t', ' ')
@ -126,7 +122,7 @@ pub fn (ctx &Context) draw_text(x, y int, text_ string, cfg gx.TextCfg) {
C.fonsDrawText(ctx.ft.fons, x * scale, y * scale, text.str, 0) // TODO: check offsets/alignment C.fonsDrawText(ctx.ft.fons, x * scale, y * scale, text.str, 0) // TODO: check offsets/alignment
} }
pub fn (ctx &Context) draw_text_def(x, y int, text string) { pub fn (ctx &Context) draw_text_def(x int, y int, text string) {
ctx.draw_text(x, y, text, {}) ctx.draw_text(x, y, text, {})
} }
@ -134,8 +130,7 @@ pub fn (ctx &Context) draw_text_def(x, y int, text string) {
pub fn (mut gg FT) init_font() { pub fn (mut gg FT) init_font() {
} }
*/ */
pub fn (ft &FT) flush() {
pub fn (ft &FT) flush(){
sfons.flush(ft.fons) sfons.flush(ft.fons)
} }
@ -165,14 +160,13 @@ pub fn (ctx &Context) text_height(s string) int {
pub fn (ctx &Context) text_size(s string) (int, int) { pub fn (ctx &Context) text_size(s string) (int, int) {
// ctx.set_cfg(cfg) TODO // ctx.set_cfg(cfg) TODO
if !ctx.font_inited { if !ctx.font_inited {
return 0,0 return 0, 0
} }
mut buf := [4]f32{} mut buf := [4]f32{}
C.fonsTextBounds(ctx.ft.fons, 0, 0, s.str, 0, buf) C.fonsTextBounds(ctx.ft.fons, 0, 0, s.str, 0, buf)
return int((buf[2] - buf[0]) / ctx.scale), int((buf[3] - buf[1]) / ctx.scale) return int((buf[2] - buf[0]) / ctx.scale), int((buf[3] - buf[1]) / ctx.scale)
} }
pub fn system_font_path() string { pub fn system_font_path() string {
env_font := os.getenv('VUI_FONT') env_font := os.getenv('VUI_FONT')
if env_font != '' && os.exists(env_font) { if env_font != '' && os.exists(env_font) {
@ -182,7 +176,7 @@ pub fn system_font_path() string {
return 'C:\\Windows\\Fonts\\arial.ttf' return 'C:\\Windows\\Fonts\\arial.ttf'
} }
mut fonts := ['Ubuntu-R.ttf', 'Arial.ttf', 'LiberationSans-Regular.ttf', 'NotoSans-Regular.ttf', mut fonts := ['Ubuntu-R.ttf', 'Arial.ttf', 'LiberationSans-Regular.ttf', 'NotoSans-Regular.ttf',
'FreeSans.ttf', 'DejaVuSans.ttf'] 'FreeSans.ttf', 'DejaVuSans.ttf']
$if macos { $if macos {
fonts = ['/System/Library/Fonts/SFNS.ttf', '/System/Library/Fonts/SFNSText.ttf', '/Library/Fonts/Arial.ttf'] fonts = ['/System/Library/Fonts/SFNS.ttf', '/System/Library/Fonts/SFNSText.ttf', '/Library/Fonts/Arial.ttf']
for font in fonts { for font in fonts {
@ -191,7 +185,9 @@ pub fn system_font_path() string {
} }
} }
} }
s := os.exec('fc-list') or { panic('failed to fetch system fonts') } s := os.exec('fc-list') or {
panic('failed to fetch system fonts')
}
system_fonts := s.output.split('\n') system_fonts := s.output.split('\n')
for line in system_fonts { for line in system_fonts {
for font in fonts { for font in fonts {
@ -247,7 +243,7 @@ fn get_font_path_variant(font_path string, variant FontVariant) string {
} }
fn debug_font_println(s string) { fn debug_font_println(s string) {
$if debug_font? { $if debug_font ? {
println(s) println(s)
} }
} }

View File

@ -1,29 +1,106 @@
module gx module gx
pub const ( pub const (
blue = Color { r: 0, g: 0, b: 255 } blue = Color{
red = Color { r: 255, g: 0, b: 0 } r: 0
green = Color { r: 0, g: 255, b: 0 } g: 0
yellow = Color { r: 255, g: 255, b: 0 } b: 255
}
orange = Color { r: 255, g: 165, b: 0 } red = Color{
purple = Color { r: 128, g: 0, b: 128 } r: 255
g: 0
black = Color { r: 0, g: 0, b: 0 } b: 0
gray = Color { r: 128, g: 128, b: 128 } }
indigo = Color { r: 75, g: 0, b: 130 } green = Color{
pink = Color { r: 255, g: 192, b: 203 } r: 0
violet = Color { r: 238, g: 130, b: 238 } g: 255
white = Color { r: 255, g: 255, b: 255 } b: 0
}
dark_blue = Color { r: 0, g: 0, b: 139 } yellow = Color{
dark_gray = Color { r: 169, g: 169, b: 169 } r: 255
dark_green = Color { r: 0, g: 100, b: 0 } g: 255
dark_red = Color { r: 139, g: 0, b: 0 } b: 0
light_blue = Color { r: 173, g: 216, b: 230 } }
light_gray = Color { r: 211, g: 211, b: 211 } orange = Color{
light_green = Color { r: 144, g: 238, b: 144 } r: 255
light_red = Color { r: 255, g: 204, b: 203 } g: 165
b: 0
}
purple = Color{
r: 128
g: 0
b: 128
}
black = Color{
r: 0
g: 0
b: 0
}
gray = Color{
r: 128
g: 128
b: 128
}
indigo = Color{
r: 75
g: 0
b: 130
}
pink = Color{
r: 255
g: 192
b: 203
}
violet = Color{
r: 238
g: 130
b: 238
}
white = Color{
r: 255
g: 255
b: 255
}
dark_blue = Color{
r: 0
g: 0
b: 139
}
dark_gray = Color{
r: 169
g: 169
b: 169
}
dark_green = Color{
r: 0
g: 100
b: 0
}
dark_red = Color{
r: 139
g: 0
b: 0
}
light_blue = Color{
r: 173
g: 216
b: 230
}
light_gray = Color{
r: 211
g: 211
b: 211
}
light_green = Color{
r: 144
g: 238
b: 144
}
light_red = Color{
r: 255
g: 204
b: 203
}
) )
// Color represents a 32 bit color value in sRGB format // Color represents a 32 bit color value in sRGB format
@ -37,63 +114,63 @@ pub mut:
// hex takes in a 32 bit integer and splits it into 4 byte values // hex takes in a 32 bit integer and splits it into 4 byte values
pub fn hex(color int) Color { pub fn hex(color int) Color {
return Color { return Color{
r: byte((color >> 24) & 0xFF), r: byte((color >> 24) & 0xFF)
g: byte((color >> 16) & 0xFF), g: byte((color >> 16) & 0xFF)
b: byte((color >> 8) & 0xFF), b: byte((color >> 8) & 0xFF)
a: byte((color ) & 0xFF) a: byte((color) & 0xFF)
} }
} }
pub fn rgb(r, g, b byte) Color { pub fn rgb(r byte, g byte, b byte) Color {
return Color{ return Color{
r: r, r: r
g: g, g: g
b: b b: b
} }
} }
pub fn rgba(r, g, b, a byte) Color { pub fn rgba(r byte, g byte, b byte, a byte) Color {
return Color{ return Color{
r: r, r: r
g: g, g: g
b: b, b: b
a: a a: a
} }
} }
pub fn (c Color) + (c2 Color) Color { pub fn (c Color) +(c2 Color) Color {
return Color { return Color{
r: c.r + c2.r, r: c.r + c2.r
g: c.g + c2.g, g: c.g + c2.g
b: c.b + c2.b, b: c.b + c2.b
a: c.b + c2.a a: c.b + c2.a
} }
} }
pub fn (c Color) - (c2 Color) Color { pub fn (c Color) -(c2 Color) Color {
return Color { return Color{
r: c.r - c2.r, r: c.r - c2.r
g: c.g - c2.g, g: c.g - c2.g
b: c.b - c2.b, b: c.b - c2.b
a: c.b - c2.a a: c.b - c2.a
} }
} }
pub fn (c Color) * (c2 Color) Color { pub fn (c Color) *(c2 Color) Color {
return Color { return Color{
r: c.r * c2.r, r: c.r * c2.r
g: c.g * c2.g, g: c.g * c2.g
b: c.b * c2.b, b: c.b * c2.b
a: c.b * c2.a a: c.b * c2.a
} }
} }
pub fn (c Color) / (c2 Color) Color { pub fn (c Color) /(c2 Color) Color {
return Color { return Color{
r: c.r / c2.r, r: c.r / c2.r
g: c.g / c2.g, g: c.g / c2.g
b: c.b / c2.b, b: c.b / c2.b
a: c.b / c2.a a: c.b / c2.a
} }
} }
@ -107,11 +184,11 @@ pub fn (c Color) str() string {
} }
const ( const (
string_colors = { string_colors = {
'black': black 'black': black
'blue': blue 'blue': blue
'red': red 'red': red
} }
) )
pub fn color_from_string(s string) Color { pub fn color_from_string(s string) Color {

View File

@ -1,16 +1,16 @@
module gfx module gfx
pub struct C.sg_desc { pub struct C.sg_desc {
_start_canary u32 _start_canary u32
buffer_pool_size int buffer_pool_size int
image_pool_size int image_pool_size int
shader_pool_size int shader_pool_size int
pipeline_pool_size int pipeline_pool_size int
pass_pool_size int pass_pool_size int
context_pool_size int context_pool_size int
context C.sg_context_desc context C.sg_context_desc
/* /*
// GL specific // GL specific
gl_force_gles2 bool gl_force_gles2 bool
// Metal-specific // Metal-specific
mtl_device voidptr mtl_device voidptr
@ -23,435 +23,438 @@ pub struct C.sg_desc {
d3d11_device_context voidptr d3d11_device_context voidptr
d3d11_render_target_view_cb fn() voidptr d3d11_render_target_view_cb fn() voidptr
d3d11_depth_stencil_view_cb fn() voidptr d3d11_depth_stencil_view_cb fn() voidptr
*/ */
_end_canary u32 _end_canary u32
} }
pub struct C.sg_context_desc { pub struct C.sg_context_desc {
/* /*
sg_pixel_format color_format; sg_pixel_format color_format;
sg_pixel_format depth_format; sg_pixel_format depth_format;
int sample_count; int sample_count;
sg_wgpu_context_desc wgpu; sg_wgpu_context_desc wgpu;
*/ */
sample_count int sample_count int
gl C.sg_gl_context_desc gl C.sg_gl_context_desc
metal C.sg_mtl_context_desc metal C.sg_mtl_context_desc
d3d11 C.sg_d3d11_context_desc d3d11 C.sg_d3d11_context_desc
color_format PixelFormat
color_format PixelFormat depth_format PixelFormat
depth_format PixelFormat
} }
pub struct C.sg_gl_context_desc { pub struct C.sg_gl_context_desc {
gl_force_gles2 bool gl_force_gles2 bool
} }
pub struct C.sg_mtl_context_desc { pub struct C.sg_mtl_context_desc {
device voidptr device voidptr
renderpass_descriptor_cb fn() voidptr renderpass_descriptor_cb fn () voidptr
drawable_cb fn() voidptr drawable_cb fn () voidptr
} }
pub struct C.sg_d3d11_context_desc { pub struct C.sg_d3d11_context_desc {
device voidptr device voidptr
device_context voidptr device_context voidptr
render_target_view_cb fn() voidptr render_target_view_cb fn () voidptr
depth_stencil_view_cb fn() voidptr depth_stencil_view_cb fn () voidptr
} }
pub struct C.sg_pipeline_desc { pub struct C.sg_pipeline_desc {
pub mut: pub mut:
_start_canary u32 _start_canary u32
layout C.sg_layout_desc layout C.sg_layout_desc
shader C.sg_shader shader C.sg_shader
primitive_type PrimitiveType primitive_type PrimitiveType
index_type IndexType index_type IndexType
depth_stencil C.sg_depth_stencil_state depth_stencil C.sg_depth_stencil_state
blend C.sg_blend_state blend C.sg_blend_state
rasterizer C.sg_rasterizer_state rasterizer C.sg_rasterizer_state
label byteptr label byteptr
_end_canary u32 _end_canary u32
} }
pub struct C.sg_pipeline_info { pub struct C.sg_pipeline_info {
} }
pub struct C.sg_pipeline { pub struct C.sg_pipeline {
pub: pub:
id u32 id u32
} }
pub fn (p C.sg_pipeline) free() { C.sg_destroy_pipeline(p) }
pub fn (p C.sg_pipeline) free() {
C.sg_destroy_pipeline(p)
}
pub struct C.sg_bindings { pub struct C.sg_bindings {
pub mut: pub mut:
_start_canary u32 _start_canary u32
vertex_buffers [8]C.sg_buffer vertex_buffers [8]C.sg_buffer
vertex_buffer_offsets [8]int vertex_buffer_offsets [8]int
index_buffer C.sg_buffer index_buffer C.sg_buffer
index_buffer_offset int index_buffer_offset int
vs_images [8]C.sg_image vs_images [8]C.sg_image
fs_images [8]C.sg_image fs_images [8]C.sg_image
_end_canary u32 _end_canary u32
} }
pub fn (mut b C.sg_bindings) set_vert_image(index int, img C.sg_image) { pub fn (mut b C.sg_bindings) set_vert_image(index int, img C.sg_image) {
b.vs_images[index] = img b.vs_images[index] = img
} }
pub fn (mut b C.sg_bindings) set_frag_image(index int, img C.sg_image) { pub fn (mut b C.sg_bindings) set_frag_image(index int, img C.sg_image) {
b.fs_images[index] = img b.fs_images[index] = img
} }
pub fn (b &C.sg_bindings) update_vert_buffer(index int, data voidptr, element_size int, element_count int) { pub fn (b &C.sg_bindings) update_vert_buffer(index int, data voidptr, element_size int, element_count int) {
C.sg_update_buffer(b.vertex_buffers[index], data, element_size * element_count) C.sg_update_buffer(b.vertex_buffers[index], data, element_size * element_count)
} }
pub fn (b &C.sg_bindings) append_vert_buffer(index int, data voidptr, element_size int, element_count int) int { pub fn (b &C.sg_bindings) append_vert_buffer(index int, data voidptr, element_size int, element_count int) int {
return C.sg_append_buffer(b.vertex_buffers[index], data, element_size * element_count) return C.sg_append_buffer(b.vertex_buffers[index], data, element_size * element_count)
} }
pub fn (b &C.sg_bindings) update_index_buffer(data voidptr, element_size int, element_count int) { pub fn (b &C.sg_bindings) update_index_buffer(data voidptr, element_size int, element_count int) {
C.sg_update_buffer(b.index_buffer, data, element_size * element_count) C.sg_update_buffer(b.index_buffer, data, element_size * element_count)
} }
pub fn (b &C.sg_bindings) append_index_buffer(data voidptr, element_size int, element_count int) int { pub fn (b &C.sg_bindings) append_index_buffer(data voidptr, element_size int, element_count int) int {
return C.sg_append_buffer(b.index_buffer, data, element_size * element_count) return C.sg_append_buffer(b.index_buffer, data, element_size * element_count)
} }
pub struct C.sg_shader_desc { pub struct C.sg_shader_desc {
pub mut: pub mut:
_start_canary u32 _start_canary u32
attrs [16]C.sg_shader_attr_desc attrs [16]C.sg_shader_attr_desc
vs C.sg_shader_stage_desc vs C.sg_shader_stage_desc
fs C.sg_shader_stage_desc fs C.sg_shader_stage_desc
label byteptr label byteptr
_end_canary u32 _end_canary u32
} }
pub fn (mut desc C.sg_shader_desc) set_vert_src(src string) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_vert_src(src string) &C.sg_shader_desc {
desc.vs.source = src.str desc.vs.source = src.str
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_frag_src(src string) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_frag_src(src string) &C.sg_shader_desc {
desc.fs.source = src.str desc.fs.source = src.str
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_vert_image(index int, name string) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_vert_image(index int, name string) &C.sg_shader_desc {
desc.vs.images[index].name = name.str desc.vs.images[index].name = name.str
desc.vs.images[index].@type = ._2d desc.vs.images[index].@type = ._2d
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_frag_image(index int, name string) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_frag_image(index int, name string) &C.sg_shader_desc {
desc.fs.images[index].name = name.str desc.fs.images[index].name = name.str
desc.fs.images[index].@type = ._2d desc.fs.images[index].@type = ._2d
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_vert_uniform_block_size(block_index, size int) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_vert_uniform_block_size(block_index int, size int) &C.sg_shader_desc {
desc.vs.uniform_blocks[block_index].size = size desc.vs.uniform_blocks[block_index].size = size
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_frag_uniform_block_size(block_index, size int) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_frag_uniform_block_size(block_index int, size int) &C.sg_shader_desc {
desc.fs.uniform_blocks[block_index].size = size desc.fs.uniform_blocks[block_index].size = size
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_vert_uniform(block_index int, uniform_index int, name string, @type UniformType, array_count int) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_vert_uniform(block_index int, uniform_index int, name string, @type UniformType, array_count int) &C.sg_shader_desc {
desc.vs.uniform_blocks[block_index].uniforms[uniform_index].name = name.str desc.vs.uniform_blocks[block_index].uniforms[uniform_index].name = name.str
desc.vs.uniform_blocks[block_index].uniforms[uniform_index].@type = @type desc.vs.uniform_blocks[block_index].uniforms[uniform_index].@type = @type
return desc return desc
} }
pub fn (mut desc C.sg_shader_desc) set_frag_uniform(block_index int, uniform_index int, name string, @type UniformType, array_count int) &C.sg_shader_desc { pub fn (mut desc C.sg_shader_desc) set_frag_uniform(block_index int, uniform_index int, name string, @type UniformType, array_count int) &C.sg_shader_desc {
desc.fs.uniform_blocks[block_index].uniforms[uniform_index].name = name.str desc.fs.uniform_blocks[block_index].uniforms[uniform_index].name = name.str
desc.fs.uniform_blocks[block_index].uniforms[uniform_index].@type = @type desc.fs.uniform_blocks[block_index].uniforms[uniform_index].@type = @type
return desc return desc
} }
pub fn (desc &C.sg_shader_desc) make_shader() C.sg_shader { pub fn (desc &C.sg_shader_desc) make_shader() C.sg_shader {
return C.sg_make_shader(desc) return C.sg_make_shader(desc)
} }
pub struct C.sg_shader_attr_desc { pub struct C.sg_shader_attr_desc {
pub mut: pub mut:
name byteptr /* GLSL vertex attribute name (only required for GLES2) */ name byteptr // GLSL vertex attribute name (only required for GLES2)
sem_name byteptr /* HLSL semantic name */ sem_name byteptr // HLSL semantic name
sem_index int /* HLSL semantic index */ sem_index int // HLSL semantic index
} }
pub struct C.sg_shader_stage_desc { pub struct C.sg_shader_stage_desc {
pub mut: pub mut:
source byteptr source byteptr
byte_code &byte byte_code &byte
byte_code_size int byte_code_size int
entry byteptr entry byteptr
uniform_blocks [4]C.sg_shader_uniform_block_desc uniform_blocks [4]C.sg_shader_uniform_block_desc
images [12]C.sg_shader_image_desc images [12]C.sg_shader_image_desc
} }
pub fn (mut desc C.sg_shader_stage_desc) set_image(index int, name string) C.sg_shader_stage_desc { pub fn (mut desc C.sg_shader_stage_desc) set_image(index int, name string) C.sg_shader_stage_desc {
desc.images[index].name = name.str desc.images[index].name = name.str
desc.images[index].@type = ._2d desc.images[index].@type = ._2d
return *desc return *desc
} }
pub struct C.sg_shader_uniform_block_desc { pub struct C.sg_shader_uniform_block_desc {
pub mut: pub mut:
size int size int
uniforms [16]C.sg_shader_uniform_desc uniforms [16]C.sg_shader_uniform_desc
} }
pub struct C.sg_shader_uniform_desc { pub struct C.sg_shader_uniform_desc {
pub mut: pub mut:
name byteptr name byteptr
@type UniformType @type UniformType
array_count int array_count int
} }
pub struct C.sg_shader_image_desc { pub struct C.sg_shader_image_desc {
pub mut: pub mut:
name byteptr name byteptr
@type ImageType @type ImageType
} }
pub struct C.sg_shader_info {} pub struct C.sg_shader_info {
}
pub struct C.sg_context { pub struct C.sg_context {
id u32 id u32
} }
pub struct C.sg_shader { pub struct C.sg_shader {
pub: pub:
id u32 id u32
} }
pub fn (s C.sg_shader) free() { C.sg_destroy_shader(s) }
pub fn (s C.sg_shader) free() {
C.sg_destroy_shader(s)
}
pub struct C.sg_pass_desc { pub struct C.sg_pass_desc {
pub mut: pub mut:
_start_canary u32 _start_canary u32
color_attachments [4]C.sg_attachment_desc color_attachments [4]C.sg_attachment_desc
depth_stencil_attachment C.sg_attachment_desc depth_stencil_attachment C.sg_attachment_desc
label byteptr label byteptr
_end_canary u32 _end_canary u32
} }
pub struct C.sg_pass_info { pub struct C.sg_pass_info {
info C.sg_slot_info info C.sg_slot_info
} }
pub struct C.sg_pass_action { pub struct C.sg_pass_action {
pub mut: pub mut:
_start_canary u32 _start_canary u32
colors [4]C.sg_color_attachment_action colors [4]C.sg_color_attachment_action
depth C.sg_depth_attachment_action depth C.sg_depth_attachment_action
stencil C.sg_stencil_attachment_action stencil C.sg_stencil_attachment_action
_end_canary u32 _end_canary u32
} }
pub struct C.sg_pass { pub struct C.sg_pass {
id u32 id u32
} }
pub fn (p C.sg_pass) free() { C.sg_destroy_pass(p) }
pub fn (p C.sg_pass) free() {
C.sg_destroy_pass(p)
}
pub struct C.sg_buffer_desc { pub struct C.sg_buffer_desc {
pub mut: pub mut:
_start_canary u32 _start_canary u32
size int size int
@type BufferType @type BufferType
usage Usage usage Usage
content byteptr content byteptr
label byteptr label byteptr
/* GL specific */ // GL specific
gl_buffers [2]u32 gl_buffers [2]u32
/* Metal specific */ // Metal specific
mtl_buffers [2]voidptr mtl_buffers [2]voidptr
/* D3D11 specific */ // D3D11 specific
d3d11_buffer voidptr d3d11_buffer voidptr
_end_canary u32 _end_canary u32
} }
pub struct C.sg_buffer_info {} pub struct C.sg_buffer_info {
}
pub struct C.sg_buffer { pub struct C.sg_buffer {
id u32 id u32
} }
pub fn (b C.sg_buffer) free() { C.sg_destroy_buffer(b) }
pub fn (b C.sg_buffer) free() {
C.sg_destroy_buffer(b)
}
pub union DepthLayers { pub struct DepthLayers {
depth int depth int
layers int layers int
} }
pub struct C.sg_image_desc { pub struct C.sg_image_desc {
pub mut: pub mut:
_start_canary u32 _start_canary u32
@type ImageType @type ImageType
render_target bool render_target bool
width int width int
height int height int
depth DepthLayers
depth DepthLayers // depth int
// depth int // union {
// union { // int depth;
// int depth; // int layers;
// int layers; // };
// }; num_mipmaps int
num_mipmaps int usage Usage
usage Usage pixel_format PixelFormat
pixel_format PixelFormat sample_count int
sample_count int min_filter Filter
min_filter Filter mag_filter Filter
mag_filter Filter wrap_u Wrap
wrap_u Wrap wrap_v Wrap
wrap_v Wrap wrap_w Wrap
wrap_w Wrap border_color BorderColor
border_color BorderColor max_anisotropy u32
max_anisotropy u32 min_lod f32
min_lod f32 max_lod f32
max_lod f32 content C.sg_image_content
content C.sg_image_content label byteptr
label byteptr // GL specific
/* GL specific */ gl_textures [2]u32
gl_textures [2]u32 // Metal specific
/* Metal specific */ mtl_textures [2]voidptr
mtl_textures [2]voidptr // D3D11 specific
/* D3D11 specific */ d3d11_texture voidptr
d3d11_texture voidptr _end_canary u32
_end_canary u32
} }
pub struct C.sg_image_info { pub struct C.sg_image_info {
pub mut: pub mut:
slot C.sg_slot_info /* resource pool slot info */ slot C.sg_slot_info // resource pool slot info
upd_frame_index u32 /* frame index of last sg_update_image() */ upd_frame_index u32 // frame index of last sg_update_image()
num_slots int /* number of renaming-slots for dynamically updated images */ num_slots int // number of renaming-slots for dynamically updated images
active_slot int /* currently active write-slot for dynamically updated images */ active_slot int // currently active write-slot for dynamically updated images
} }
pub struct C.sg_image { pub struct C.sg_image {
pub: pub:
id u32 id u32
} }
pub fn (i C.sg_image) free() { C.sg_destroy_image(i) }
pub fn (i C.sg_image) free() {
C.sg_destroy_image(i)
}
pub struct C.sg_image_content { pub struct C.sg_image_content {
pub mut: pub mut:
subimage [6][16]C.sg_subimage_content subimage [6][16]C.sg_subimage_content
} }
pub struct C.sg_subimage_content { pub struct C.sg_subimage_content {
pub mut: pub mut:
ptr voidptr /* pointer to subimage data */ ptr voidptr // pointer to subimage data
size int /* size in bytes of pointed-to subimage data */ size int // size in bytes of pointed-to subimage data
} }
pub struct C.sg_features { pub struct C.sg_features {
pub: pub:
instancing bool /* hardware instancing supported */ instancing bool // hardware instancing supported
origin_top_left bool /* framebuffer and texture origin is in top left corner */ origin_top_left bool // framebuffer and texture origin is in top left corner
multiple_render_targets bool /* offscreen render passes can have multiple render targets attached */ multiple_render_targets bool // offscreen render passes can have multiple render targets attached
msaa_render_targets bool /* offscreen render passes support MSAA antialiasing */ msaa_render_targets bool // offscreen render passes support MSAA antialiasing
imagetype_3d bool /* creation of SG_IMAGETYPE_3D images is supported */ imagetype_3d bool // creation of SG_IMAGETYPE_3D images is supported
imagetype_array bool /* creation of SG_IMAGETYPE_ARRAY images is supported */ imagetype_array bool // creation of SG_IMAGETYPE_ARRAY images is supported
image_clamp_to_border bool /* border color and clamp-to-border UV-wrap mode is supported */ image_clamp_to_border bool // border color and clamp-to-border UV-wrap mode is supported
} }
pub struct C.sg_limits { pub struct C.sg_limits {
pub: pub:
max_image_size_2d u32 /* max width/height of SG_IMAGETYPE_2D images */ max_image_size_2d u32 // max width/height of SG_IMAGETYPE_2D images
max_image_size_cube u32 /* max width/height of SG_IMAGETYPE_CUBE images */ max_image_size_cube u32 // max width/height of SG_IMAGETYPE_CUBE images
max_image_size_3d u32 /* max width/height/depth of SG_IMAGETYPE_3D images */ max_image_size_3d u32 // max width/height/depth of SG_IMAGETYPE_3D images
max_image_size_array u32 /* max width/height pf SG_IMAGETYPE_ARRAY images */ max_image_size_array u32 // max width/height pf SG_IMAGETYPE_ARRAY images
max_image_array_layers u32 /* max number of layers in SG_IMAGETYPE_ARRAY images */ max_image_array_layers u32 // max number of layers in SG_IMAGETYPE_ARRAY images
max_vertex_attrs u32 /* <= SG_MAX_VERTEX_ATTRIBUTES (only on some GLES2 impls) */ max_vertex_attrs u32 // <= SG_MAX_VERTEX_ATTRIBUTES (only on some GLES2 impls)
} }
pub struct C.sg_layout_desc { pub struct C.sg_layout_desc {
pub mut: pub mut:
buffers [8]C.sg_buffer_layout_desc buffers [8]C.sg_buffer_layout_desc
attrs [16]C.sg_vertex_attr_desc attrs [16]C.sg_vertex_attr_desc
} }
pub struct C.sg_buffer_layout_desc { pub struct C.sg_buffer_layout_desc {
pub mut: pub mut:
stride int stride int
step_func VertexStep step_func VertexStep
step_rate int step_rate int
} }
pub struct C.sg_vertex_attr_desc { pub struct C.sg_vertex_attr_desc {
pub mut: pub mut:
buffer_index int buffer_index int
offset int offset int
format VertexFormat format VertexFormat
} }
pub struct C.sg_depth_stencil_state { pub struct C.sg_depth_stencil_state {
stencil_front sg_stencil_state stencil_front sg_stencil_state
stencil_back sg_stencil_state stencil_back sg_stencil_state
depth_compare_func CompareFunc depth_compare_func CompareFunc
depth_write_enabled bool depth_write_enabled bool
stencil_enabled bool stencil_enabled bool
stencil_read_mask byte stencil_read_mask byte
stencil_write_mask byte stencil_write_mask byte
stencil_ref byte stencil_ref byte
} }
pub struct C.sg_stencil_state { pub struct C.sg_stencil_state {
fail_op StencilOp fail_op StencilOp
depth_fail_op StencilOp depth_fail_op StencilOp
pass_op StencilOp pass_op StencilOp
compare_func CompareFunc compare_func CompareFunc
} }
pub struct C.sg_blend_state { pub struct C.sg_blend_state {
pub mut: pub mut:
enabled bool enabled bool
src_factor_rgb BlendFactor src_factor_rgb BlendFactor
dst_factor_rgb BlendFactor dst_factor_rgb BlendFactor
op_rgb BlendOp op_rgb BlendOp
src_factor_alpha BlendFactor src_factor_alpha BlendFactor
dst_factor_alpha BlendFactor dst_factor_alpha BlendFactor
op_alpha BlendOp op_alpha BlendOp
color_write_mask byte color_write_mask byte
color_attachment_count int color_attachment_count int
color_format PixelFormat color_format PixelFormat
depth_format PixelFormat depth_format PixelFormat
blend_color [4]f32 blend_color [4]f32
} }
pub struct C.sg_rasterizer_state { pub struct C.sg_rasterizer_state {
pub mut: pub mut:
alpha_to_coverage_enabled bool alpha_to_coverage_enabled bool
cull_mode CullMode cull_mode CullMode
face_winding FaceWinding face_winding FaceWinding
sample_count int sample_count int
depth_bias f32 depth_bias f32
depth_bias_slope_scale f32 depth_bias_slope_scale f32
depth_bias_clamp f32 depth_bias_clamp f32
} }
pub struct C.sg_color_attachment_action { pub struct C.sg_color_attachment_action {
pub mut: pub mut:
action Action action Action
val [4]f32 val [4]f32
} }
/* /*
@ -462,40 +465,38 @@ pub fn (mut action C.sg_color_attachment_action) set_color_values(r, g, b, a f32
action.val[3] = a action.val[3] = a
} }
*/ */
pub struct C.sg_depth_attachment_action { pub struct C.sg_depth_attachment_action {
pub mut: pub mut:
action Action action Action
val f32 val f32
} }
pub struct C.sg_stencil_attachment_action { pub struct C.sg_stencil_attachment_action {
pub mut: pub mut:
action Action action Action
val byte val byte
} }
pub struct C.sg_pixelformat_info { pub struct C.sg_pixelformat_info {
pub: pub:
sample bool /* pixel format can be sampled in shaders */ sample bool // pixel format can be sampled in shaders
filter bool /* pixel format can be sampled with filtering */ filter bool // pixel format can be sampled with filtering
render bool /* pixel format can be used as render target */ render bool // pixel format can be used as render target
blend bool /* alpha-blending is supported */ blend bool // alpha-blending is supported
msaa bool /* pixel format can be used as MSAA render target */ msaa bool // pixel format can be used as MSAA render target
depth bool /* pixel format is a depth format */ depth bool // pixel format is a depth format
} }
pub struct C.sg_attachment_desc { pub struct C.sg_attachment_desc {
pub mut: pub mut:
image C.sg_image image C.sg_image
mip_level int mip_level int
face int face int
// image sg_image
// image sg_image // mip_level int
// mip_level int // union {
// union { // face int
// face int // layer int
// layer int // slice int
// slice int // }
// }
} }

View File

@ -1,15 +1,14 @@
module gfx module gfx
pub fn create_clear_pass(r, g, b, a f32) C.sg_pass_action { pub fn create_clear_pass(r f32, g f32, b f32, a f32) C.sg_pass_action {
mut color_action := C.sg_color_attachment_action { mut color_action := C.sg_color_attachment_action{
action: C.SG_ACTION_CLEAR action: C.SG_ACTION_CLEAR
} }
//color_action.set_color_values(r, g, b, a) // color_action.set_color_values(r, g, b, a)
color_action.val[0] = r color_action.val[0] = r
color_action.val[1] = g color_action.val[1] = g
color_action.val[2] = b color_action.val[2] = b
color_action.val[3] = a color_action.val[3] = a
mut pass_action := C.sg_pass_action{} mut pass_action := C.sg_pass_action{}
pass_action.colors[0] = color_action pass_action.colors[0] = color_action
return pass_action return pass_action