├── earcut ├── v.mod ├── README.md ├── LICENSE └── earcut.v ├── img ├── logo.png └── screenshot.png ├── v.mod ├── LICENSE ├── README.md ├── .github └── workflows │ └── ci.yml ├── plot └── plot.v ├── draw.v ├── image.v ├── examples └── app.v └── shape.v /earcut/v.mod: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /img/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/larpon/sgldraw/HEAD/img/logo.png -------------------------------------------------------------------------------- /img/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/larpon/sgldraw/HEAD/img/screenshot.png -------------------------------------------------------------------------------- /v.mod: -------------------------------------------------------------------------------- 1 | Module { 2 | name: 'sgldraw' 3 | description: 'A module that that can draw stuff' 4 | version: '0.0.1' 5 | license: 'MIT' 6 | repo_url: 'https://github.com/larpon/sgldraw' 7 | dependencies: [] 8 | } 9 | -------------------------------------------------------------------------------- /earcut/README.md: -------------------------------------------------------------------------------- 1 | # earcut 2 | 3 | A hand-ported V version of [mapbox/earcut](https://github.com/mapbox/earcut). 4 | 5 | The implementation is currently based on commit [f40dd2](https://github.com/mapbox/earcut/tree/f40dd273cb8c6911581a01f9c8de2b22a591dffb) 6 | 7 | ## Example 8 | 9 | ```v 10 | module main 11 | 12 | import earcut 13 | 14 | fn main() { 15 | flat := earcut.flatten(v_logo) 16 | vertices := flat.vertices 17 | holes := flat.holes 18 | indicies := earcut.earcut(vertices, holes, 2) 19 | println(indicies) 20 | println(earcut.deviation(vertices, holes, 2, indicies)) 21 | } 22 | 23 | const ( 24 | v_logo = [[ 25 | [f32(1), 1], [f32(3.5), 1.4], 26 | [f32(5), 6], 27 | [f32(6.5), 1.4], [f32(9), 1], 28 | [f32(6), 9], [f32(4), 9], 29 | ]] 30 | ) 31 | ``` 32 | -------------------------------------------------------------------------------- /earcut/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2016, Mapbox 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any purpose 6 | with or without fee is hereby granted, provided that the above copyright notice 7 | and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 10 | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND 11 | FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 12 | INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS 13 | OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER 14 | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF 15 | THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020-2022 Lars Pontoppidan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sgldraw 2 | 3 | `sgldraw` is a GPU accelerated, fairly performant, V module for 4 | drawing vector shapes through `sokol.sgl`. 5 | 6 | The example can be run with: `v run examples/app.v`: 7 | ![screenshot](https://raw.githubusercontent.com/larpon/sgldraw/master/img/screenshot.png) 8 | 9 | The special thing about `sgldraw` is that it's real-time - meaning that it'll draw all 10 | shapes from scratch 60 frames per second. 11 | 12 | It also handles line widths > 1 - which makes the shapes look more like they'd do in 13 | e.g. Inkscape. All shapes can also be animated with `sgl` transforms or by changing 14 | each vertice coordinate the shapes is made up from. 15 | 16 | ## Why 17 | It was an experiment on doing real-time vector graphics and also 18 | to explore a way to package vector shape drawing into a self-contained 19 | and standalone module. 20 | 21 | `sgldraw` has served as a personal sandbox but 22 | I'm releasing it to the public in case some of the code might 23 | be of interest to anyone. 24 | 25 | ## Install 26 | 27 | ```bash 28 | git clone https://github.com/larpon/sgldraw.git ~/.vmodules/sgldraw 29 | ``` 30 | When `sgldraw` is in `~/.vmodules/` you can run the examples and import 31 | it as a normal V module with `import sgldraw`. 32 | 33 | ## Notes 34 | 35 | **Legacy project** 36 | 37 | It's not completely abandoned, but my focus is currently elsewhere 38 | in V-land. 39 | 40 | **Licenses** 41 | 42 | Some code found in this module is adapted from code originally written by 43 | Chris H.F. Tsang published under the [CPOL License](https://en.wikipedia.org/wiki/Code_Project_Open_License). 44 | 45 | Also note that the `earcut` module is based on work licenced under the [ISC License](https://github.com/mapbox/earcut/blob/master/LICENSE). 46 | The version of `earcut` is from [Larpon/earcut](https://github.com/larpon/earcut/)@[1790a9e](https://github.com/larpon/earcut/tree/1790a9e60dae09889b95b337acb205699fd4f51e). 47 | 48 | Both CPOL and ISC are very permissive licenses that ressembles MIT 49 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | paths-ignore: 7 | - "**.md" 8 | pull_request: 9 | branches: [master] 10 | paths-ignore: 11 | - "**.md" 12 | 13 | concurrency: 14 | group: build-ci-${{ github.event.pull_request.number || github.sha }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | build: 19 | strategy: 20 | matrix: 21 | os: ["ubuntu", "macos", "windows"] 22 | runs-on: ${{ matrix.os }}-latest 23 | 24 | steps: 25 | - name: Install V 26 | uses: vlang/setup-v@v1 27 | with: 28 | check-latest: true 29 | 30 | - name: Checkout ${{ github.event.repository.name }} 31 | uses: actions/checkout@v2 32 | with: 33 | path: sgldraw # Because of Windows multifile access *sigh* 34 | 35 | - name: Check if code is formatted 36 | if: startsWith(matrix.os,'ubuntu') || startsWith(matrix.os,'macos') 37 | run: | 38 | cd sgldraw 39 | v fmt -verify . || v fmt -diff . 40 | 41 | - name: Install as module 42 | if: startsWith(matrix.os,'ubuntu') || startsWith(matrix.os,'macos') 43 | run: | 44 | cd sgldraw 45 | mkdir -p ~/.vmodules 46 | ln -s $(pwd) ~/.vmodules/ 47 | 48 | - name: Install as module 49 | if: startsWith(matrix.os,'windows') 50 | run: | 51 | move-item -force sgldraw $home\.vmodules\ 52 | 53 | - name: Install dependencies 54 | if: startsWith(matrix.os,'ubuntu') 55 | run: | 56 | sudo apt-get update 57 | sudo apt-get install --quiet -y libfreetype6-dev libxi-dev libxcursor-dev libgl-dev 58 | 59 | - name: Build ${{ github.event.repository.name }} 60 | if: startsWith(matrix.os,'ubuntu') || startsWith(matrix.os,'macos') 61 | run: v sgldraw/examples 62 | 63 | - name: Build ${{ github.event.repository.name }} 64 | if: startsWith(matrix.os,'windows') 65 | run: v $home\.vmodules\sgldraw\examples 66 | -------------------------------------------------------------------------------- /plot/plot.v: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2021-2022 Lars Pontoppidan. All rights reserved. 2 | // Use of this source code is governed by an MIT license file distributed with this software package 3 | module plot 4 | 5 | import math 6 | import sokol.sgl 7 | 8 | pub enum Plot { 9 | outline 10 | solid 11 | } 12 | 13 | @[inline] 14 | pub fn point(x f32, y f32) { 15 | sgl.v2f(x, y) 16 | } 17 | 18 | @[inline] 19 | pub fn line(x1 f32, y1 f32, x2 f32, y2 f32) { 20 | sgl.v2f(x1, y1) 21 | sgl.v2f(x2, y2) 22 | } 23 | 24 | @[inline] 25 | pub fn rectangle(x f32, y f32, w f32, h f32) { 26 | sgl.v2f(x, y) 27 | sgl.v2f((x + w), y) 28 | sgl.v2f((x + w), (y + h)) 29 | sgl.v2f(x, (y + h)) 30 | } 31 | 32 | @[inline] 33 | pub fn arc(x f32, y f32, radius f32, start_angle_in_rad f32, angle_in_rad f32, steps u32, plot Plot) { 34 | theta := f32(angle_in_rad / f32(steps)) 35 | tan_factor := math.tanf(theta) 36 | rad_factor := math.cosf(theta) 37 | mut x1 := f32(radius * math.cosf(start_angle_in_rad)) 38 | mut y1 := f32(radius * math.sinf(start_angle_in_rad)) 39 | for i := 0; i < steps + 1; i++ { 40 | sgl.v2f(x1 + x, y1 + y) 41 | if plot == .solid { 42 | sgl.v2f(x, y) 43 | } 44 | tx := -y1 45 | ty := x1 46 | x1 += tx * tan_factor 47 | y1 += ty * tan_factor 48 | x1 *= rad_factor 49 | y1 *= rad_factor 50 | } 51 | } 52 | 53 | @[inline] 54 | pub fn arc_line(x f32, y f32, radius f32, width f32, start_angle_in_rad f32, angle_in_rad f32, steps u32) { 55 | mut theta := f32(0) 56 | for i := 0; i < steps; i++ { 57 | theta = start_angle_in_rad + angle_in_rad * f32(i) / f32(steps) 58 | mut x1 := (radius + width) * math.cosf(theta) 59 | mut y1 := (radius + width) * math.sinf(theta) 60 | mut x2 := (radius - width) * math.cosf(theta) 61 | mut y2 := (radius - width) * math.sinf(theta) 62 | sgl.v2f(x + x1, y + y1) 63 | sgl.v2f(x + x2, y + y2) 64 | theta = start_angle_in_rad + angle_in_rad * f32(i + 1) / f32(steps) 65 | mut nx1 := (radius + width) * math.cosf(theta) 66 | mut ny1 := (radius + width) * math.sinf(theta) 67 | mut nx2 := (radius - width) * math.cosf(theta) 68 | mut ny2 := (radius - width) * math.sinf(theta) 69 | sgl.v2f(x + nx1, y + ny1) 70 | sgl.v2f(x + nx2, y + ny2) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /draw.v: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2021-2022 Lars Pontoppidan. All rights reserved. 2 | // Use of this source code is governed by an MIT license file distributed with this software package 3 | module sgldraw 4 | 5 | import sokol.sgl 6 | import sokol.sapp 7 | 8 | const cache = &Cache{} 9 | 10 | pub const dpi_scale_factor = dpi_scale() 11 | 12 | // Color 13 | pub struct Color { 14 | pub mut: 15 | r u8 16 | g u8 17 | b u8 18 | a u8 19 | } 20 | 21 | pub struct Colors { 22 | pub mut: 23 | solid Color 24 | outline Color 25 | } 26 | 27 | @[flag] 28 | pub enum Fill { 29 | invisible 30 | outline 31 | solid 32 | debug 33 | } 34 | 35 | @[flag] 36 | pub enum Cap { 37 | butt 38 | round 39 | square 40 | } 41 | 42 | @[flag] 43 | pub enum Connect { 44 | miter 45 | bevel 46 | round 47 | } 48 | 49 | fn dpi_scale() f32 { 50 | mut s := sapp.dpi_scale() 51 | //$if android { 52 | // s *= android_dpi_scale() 53 | //} 54 | // NB: on older X11, `Xft.dpi` from ~/.Xresources, that sokol uses, 55 | // may not be set which leads to sapp.dpi_scale reporting incorrectly 0.0 56 | if s < 0.1 { 57 | s = 1.0 58 | } 59 | return s 60 | } 61 | 62 | @[inline] 63 | pub fn rgb(r u8, g u8, b u8) Color { 64 | return Color{r, g, b, u8(255)} 65 | } 66 | 67 | @[inline] 68 | pub fn rgba(r u8, g u8, b u8, a u8) Color { 69 | return Color{r, g, b, a} 70 | } 71 | 72 | @[inline] 73 | pub fn push_matrix() { 74 | sgl.push_matrix() 75 | } 76 | 77 | @[inline] 78 | pub fn pop_matrix() { 79 | sgl.pop_matrix() 80 | } 81 | 82 | @[inline] 83 | pub fn translate(x f32, y f32, z f32) { 84 | sgl.translate(x, y, z) 85 | } 86 | 87 | @[inline] 88 | pub fn rotate(angle_in_rad f32, x f32, y f32, z f32) { 89 | sgl.rotate(angle_in_rad, x, y, z) 90 | } 91 | 92 | @[inline] 93 | pub fn scale(x f32, y f32, z f32) { 94 | sgl.scale(x, y, z) 95 | } 96 | 97 | struct Cache { 98 | mut: 99 | images map[string]Image 100 | // fonts map[string]FontCache 101 | } 102 | 103 | fn (c Cache) has_image(id string) bool { 104 | return id in c.images.keys() 105 | } 106 | 107 | fn (c Cache) get_image(id string) Image { 108 | return c.images[id] or { panic('get_image failed to get ${id} from cache') } 109 | } 110 | 111 | fn (mut c Cache) free() { 112 | for _, mut img in c.images { 113 | img.free() 114 | } 115 | } 116 | 117 | pub fn free() { 118 | unsafe { 119 | mut c := cache 120 | c.free() 121 | } 122 | // unsafe { C.free(c) } 123 | } 124 | -------------------------------------------------------------------------------- /image.v: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2021-2022 Lars Pontoppidan. All rights reserved. 2 | // Use of this source code is governed by an MIT license file distributed with this software package 3 | module sgldraw 4 | 5 | import os 6 | import sokol.gfx 7 | import stbi 8 | 9 | pub struct ImageLoadOptions { 10 | mut: 11 | width int 12 | height int 13 | 14 | cache bool = true 15 | mipmaps int 16 | path string 17 | } 18 | 19 | @[heap] 20 | pub struct Image { 21 | pub: 22 | width int 23 | height int 24 | mut: 25 | cache bool 26 | 27 | path string 28 | 29 | channels int 30 | ready bool 31 | mipmaps int 32 | 33 | data voidptr 34 | ext string 35 | 36 | sg_image gfx.Image 37 | sg_sampler gfx.Sampler 38 | } 39 | 40 | fn load_image(opt ImageLoadOptions) !Image { 41 | // eprintln(@MOD+'.'+@STRUCT+'.'+@FN+' loading "${opt.path}" ...') 42 | 43 | mut image_path := opt.path 44 | 45 | uid := image_path 46 | if cache.has_image(uid) { 47 | // eprintln(@MOD+'.'+@STRUCT+'.'+@FN+' loading "$image_path" from cache') 48 | mut img := cache.get_image(uid) 49 | if !img.ready { 50 | mut buffer := []u8{} 51 | image_path = img.path 52 | $if android { 53 | image_path = image_path.replace('assets/', '') // TODO 54 | buffer = os.read_apk_asset(image_path) or { 55 | return error(@MOD + '.' + @FN + ' (Android) file "${image_path}" not found') 56 | } 57 | } $else { 58 | if !os.is_file(image_path) { 59 | return error(@MOD + '.' + @FN + ' file "${image_path}" not found') 60 | // return none 61 | } 62 | image_path = os.real_path(image_path) 63 | buffer = os.read_bytes(image_path) or { 64 | return error(@MOD + '.' + @FN + ' file "${image_path}" could not be read') 65 | } 66 | } 67 | 68 | // stb_img := stbi.load(opt.path) or { return err } 69 | stb_img := stbi.load_from_memory(buffer.data, buffer.len) or { 70 | return error(@MOD + '.' + @FN + ' stbi failed loading "${image_path}"') 71 | } 72 | 73 | img = Image{ 74 | width: stb_img.width 75 | height: stb_img.height 76 | channels: stb_img.nr_channels 77 | cache: opt.cache 78 | ready: stb_img.ok 79 | data: stb_img.data 80 | ext: stb_img.ext 81 | path: opt.path 82 | mipmaps: opt.mipmaps 83 | } 84 | img.init_sokol_image() 85 | // stb_img.free() // TODO ?? 86 | 87 | if img.cache { 88 | eprintln(@MOD + '.' + @STRUCT + '.' + @FN + ' caching "${uid}"') 89 | unsafe { 90 | mut c := cache 91 | c.images[uid] = img 92 | } 93 | } 94 | return img 95 | } 96 | return img 97 | } 98 | 99 | mut buffer := []u8{} 100 | $if android { 101 | image_path = image_path.replace('assets/', '') // TODO 102 | buffer = os.read_apk_asset(image_path) or { 103 | return error(@MOD + '.' + @FN + ' (Android) file "${image_path}" not found') 104 | } 105 | } $else { 106 | if !os.is_file(image_path) { 107 | return error(@MOD + '.' + @FN + ' file "${image_path}" not found') 108 | // return none 109 | } 110 | image_path = os.real_path(image_path) 111 | buffer = os.read_bytes(image_path) or { 112 | return error(@MOD + '.' + @FN + ' file "${image_path}" could not be read') 113 | } 114 | } 115 | 116 | stb_img := stbi.load_from_memory(buffer.data, buffer.len) or { 117 | return error(@MOD + '.' + @FN + ' stbi failed loading "${image_path}"') 118 | } 119 | 120 | mut img := Image{ 121 | width: stb_img.width 122 | height: stb_img.height 123 | channels: stb_img.nr_channels 124 | cache: opt.cache 125 | ready: stb_img.ok 126 | data: stb_img.data 127 | ext: stb_img.ext 128 | path: opt.path 129 | mipmaps: opt.mipmaps 130 | } 131 | img.init_sokol_image() 132 | // stb_img.free() // TODO ?? 133 | 134 | eprintln(@MOD + '.' + @FN + ' loaded "${img.path}" ...') 135 | 136 | if img.cache && !cache.has_image(uid) { 137 | eprintln(@MOD + '.' + @FN + ' caching "${uid}"') 138 | unsafe { 139 | mut c := cache 140 | c.images[uid] = img 141 | } 142 | } 143 | 144 | return img 145 | } 146 | 147 | fn (mut img Image) init_sokol_image() { 148 | // eprintln('\n init sokol image $img.path ok=$img.sg_image_ok') 149 | mut img_desc := gfx.ImageDesc{ 150 | width: img.width 151 | height: img.height 152 | num_mipmaps: img.mipmaps 153 | label: &u8(0) 154 | d3d11_texture: 0 155 | pixel_format: .rgba8 // C.SG_PIXELFORMAT_RGBA8 156 | } 157 | 158 | img_desc.data.subimage[0][0] = gfx.Range{ 159 | ptr: img.data 160 | size: usize(img.channels * img.width * img.height) 161 | } 162 | 163 | if img.mipmaps <= 0 { 164 | img.sg_image = gfx.make_image(&img_desc) 165 | } 166 | 167 | mut smp_desc := gfx.SamplerDesc{ 168 | min_filter: .linear 169 | mag_filter: .linear 170 | wrap_u: .clamp_to_edge 171 | wrap_v: .clamp_to_edge 172 | } 173 | 174 | img.sg_sampler = gfx.make_sampler(&smp_desc) 175 | } 176 | 177 | pub fn (mut img Image) free() { 178 | unsafe { 179 | gfx.destroy_image(img.sg_image) 180 | C.stbi_image_free(img.data) 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /examples/app.v: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2020-2022 Lars Pontoppidan. All rights reserved. 2 | // Use of this source code is governed by an MIT license file distributed with this software package 3 | module main 4 | 5 | import os 6 | import math 7 | import time 8 | import sokol.sapp 9 | import sokol.gfx 10 | import sokol.sgl 11 | import sgldraw as draw 12 | 13 | fn main() { 14 | mut app := &App{ 15 | width: 1000 16 | height: 600 17 | pass_action: gfx.create_clear_pass_action(0.6, 0.5, 0.4, 1.0) 18 | } 19 | app.run() 20 | } 21 | 22 | @[heap] 23 | struct App { 24 | pass_action gfx.PassAction 25 | mut: 26 | d Debug 27 | ticks i64 28 | dt f32 29 | width int 30 | height int 31 | frame i64 32 | last i64 33 | alpha_pip sgl.Pipeline 34 | keys_state map[sapp.KeyCode]bool 35 | ready bool 36 | canvas Canvas 37 | m_x f32 38 | m_y f32 39 | } 40 | 41 | struct Canvas { 42 | pub mut: 43 | x f32 44 | y f32 45 | zoom f32 = 1 46 | zp_x f32 47 | zp_y f32 48 | // Test values 49 | rx f32 50 | ry f32 51 | size_w f32 = 100 52 | size_h f32 = 100 53 | } 54 | 55 | fn (mut c Canvas) reset() { 56 | c.x = 0 57 | c.y = 0 58 | c.zoom = 1 59 | c.zp_x = 0 60 | c.zp_y = 0 61 | c.rx = 0 62 | c.ry = 0 63 | c.size_w = 100 64 | c.size_h = 100 65 | } 66 | 67 | fn (mut a App) init() { 68 | a.frame = 0 69 | a.last = time.ticks() 70 | 71 | sgl.load_pipeline(a.alpha_pip) 72 | 73 | a.ready = true 74 | } 75 | 76 | fn (mut a App) quit() { 77 | sapp.quit() 78 | } 79 | 80 | fn (mut a App) cleanup() { 81 | draw.free() 82 | } 83 | 84 | fn (mut a App) run() { 85 | title := 'sgldraw' 86 | desc := sapp.Desc{ 87 | width: a.width 88 | height: a.height 89 | user_data: a 90 | init_userdata_cb: init 91 | frame_userdata_cb: frame 92 | event_userdata_cb: event 93 | window_title: title.str 94 | html5_canvas_name: title.str 95 | cleanup_userdata_cb: cleanup 96 | sample_count: 4 97 | } 98 | sapp.run(&desc) 99 | } 100 | 101 | fn (mut a App) on_resized() { 102 | } 103 | 104 | fn (mut a App) on_mouse_wheel(x f32, y f32) { 105 | if a.key_is_held(.left_control) || a.key_is_held(.right_control) { 106 | a.canvas.zp_x = a.m_x //-a.canvas.x // TODO proper inverse matrix value 107 | a.canvas.zp_y = a.m_y //-a.canvas.y // TODO proper inverse matrix value 108 | a.canvas.zoom += y * 0.15 109 | } else if a.key_is_held(.right_shift) { 110 | a.canvas.x += -y * 10 * 4 111 | } else { 112 | a.canvas.y += y * 10 * 4 113 | } 114 | } 115 | 116 | fn (mut a App) handle_input() { 117 | if a.key_is_held(.right) { 118 | a.canvas.rx += 10 119 | } 120 | if a.key_is_held(.left) { 121 | a.canvas.rx -= 10 122 | } 123 | if a.key_is_held(.up) { 124 | a.canvas.ry -= 10 125 | } 126 | if a.key_is_held(.down) { 127 | a.canvas.ry += 10 128 | } 129 | } 130 | 131 | fn (a App) key_is_held(kc sapp.KeyCode) bool { 132 | return kc in a.keys_state.keys() && a.keys_state[kc] 133 | } 134 | 135 | fn (mut a App) on_key_down(ev &sapp.Event) { 136 | a.keys_state[ev.key_code] = true 137 | 138 | if ev.key_code == .r { 139 | a.canvas.reset() 140 | } 141 | 142 | if ev.key_code == .s { 143 | stamp := time.now().format_ss().replace(' ', '_').replace(':', '').replace('-', 144 | '') 145 | sapp.screenshot(os.join_path(os.temp_dir(), 'screenshot.${stamp}.png')) or { panic(err) } 146 | } 147 | 148 | // Debug input 149 | if a.key_is_held(.period) { 150 | if ev.key_code == .comma { 151 | eprintln(a.d.flags) 152 | return 153 | } 154 | 155 | if ev.key_code == .f { 156 | a.d.toggle(.flood) 157 | } 158 | 159 | // Debug draw control 160 | if a.key_is_held(.d) { 161 | a.d.on(.draw) 162 | if ev.key_code == .minus || a.key_is_held(.minus) { 163 | a.d.off(.draw) 164 | } else { 165 | } 166 | } 167 | 168 | // Debug print control 169 | if a.key_is_held(.p) { 170 | a.d.on(.print) 171 | 172 | if ev.key_code == .a { 173 | a.d.toggle(.app) 174 | } else if ev.key_code == .i { 175 | a.d.toggle(.input) 176 | } else if ev.key_code == .minus || a.key_is_held(.minus) { 177 | a.d.pln(.debug_state, 'print off') 178 | a.d.off(.print) 179 | } else { 180 | } 181 | } 182 | } 183 | } 184 | 185 | fn (mut a App) on_key_up(ev &sapp.Event) { 186 | a.keys_state[ev.key_code] = false 187 | 188 | // Handle quit event 189 | if ev.key_code == .escape || ev.key_code == .q { 190 | a.quit() 191 | return 192 | } 193 | 194 | // 195 | if ev.key_code == .f { 196 | sapp.toggle_fullscreen() 197 | return 198 | } 199 | } 200 | 201 | fn init(user_data voidptr) { 202 | mut app := unsafe { &App(user_data) } 203 | 204 | desc := sapp.create_desc() 205 | gfx.setup(&desc) 206 | sgl_desc := sgl.Desc{ 207 | max_vertices: 50 * 65536 208 | } 209 | sgl.setup(&sgl_desc) 210 | mut pipdesc := gfx.PipelineDesc{} 211 | unsafe { C.memset(&pipdesc, 0, sizeof(pipdesc)) } 212 | 213 | color_state := gfx.ColorTargetState{ 214 | blend: gfx.BlendState{ 215 | enabled: true 216 | src_factor_rgb: .src_alpha 217 | dst_factor_rgb: .one_minus_src_alpha 218 | } 219 | } 220 | pipdesc.colors[0] = color_state 221 | 222 | app.alpha_pip = sgl.make_pipeline(&pipdesc) 223 | 224 | app.init() 225 | } 226 | 227 | fn cleanup(user_data voidptr) { 228 | mut app := unsafe { &App(user_data) } 229 | app.cleanup() 230 | gfx.shutdown() 231 | } 232 | 233 | fn frame(user_data voidptr) { 234 | mut app := unsafe { &App(user_data) } 235 | app.frame++ 236 | 237 | t := time.ticks() 238 | app.ticks = t 239 | app.dt = f32(t - app.last) / 1000.0 240 | 241 | if app.width != sapp.width() || app.height != sapp.height() { 242 | app.d.pln(.app, 'resized from ${app.width}x${app.height} to ${sapp.width()}x${sapp.height()}') 243 | app.on_resized() 244 | app.width = sapp.width() 245 | app.height = sapp.height() 246 | } 247 | 248 | app.handle_input() 249 | app.draw() 250 | 251 | pass := sapp.create_default_pass(app.pass_action) 252 | gfx.begin_pass(&pass) 253 | sgl.default_pipeline() 254 | sgl.draw() 255 | gfx.end_pass() 256 | gfx.commit() 257 | 258 | app.last = t 259 | } 260 | 261 | fn event(ev &sapp.Event, mut a App) { 262 | if ev.@type == .mouse_move { 263 | a.m_x = ev.mouse_x 264 | a.m_y = ev.mouse_y 265 | } 266 | if ev.@type == .key_up { 267 | a.on_key_up(ev) 268 | } 269 | if ev.@type == .key_down { 270 | a.on_key_down(ev) 271 | } 272 | if ev.@type == .touches_began || ev.@type == .touches_moved { 273 | if ev.num_touches > 0 { 274 | touch_point := ev.touches[0] 275 | a.d.pln(.input, '${touch_point}') 276 | // 277 | } 278 | } 279 | if ev.scroll_x != 0 || ev.scroll_y != 0 { 280 | a.on_mouse_wheel(ev.scroll_x, ev.scroll_y) 281 | } 282 | } 283 | 284 | fn (a App) draw() { 285 | if !a.ready { 286 | return 287 | } 288 | a.d.plng(.draw | .flood, @STRUCT + '.' + @FN + '() called dT: ${a.dt} ...') 289 | 290 | sgl.defaults() 291 | 292 | sgl.load_pipeline(a.alpha_pip) 293 | 294 | sgl.ortho(0, f32(sapp.width()), f32(sapp.height()), 0.0, -100, 100.0) 295 | 296 | size_w := f32(100) 297 | size_h := f32(100) 298 | 299 | s := f32(a.canvas.zoom) 300 | bs := f32(1) 301 | 302 | t_x := a.canvas.x 303 | t_y := a.canvas.y 304 | 305 | draw.translate(t_x, t_y, 0) 306 | draw.translate(a.canvas.zp_x, a.canvas.zp_y, 0) 307 | draw.scale(s, s, 1) 308 | draw.translate(-a.canvas.zp_x, -a.canvas.zp_y, 0) 309 | 310 | wb := draw.Shape{ 311 | scale: bs 312 | // connect: .round 313 | } 314 | mut wbr := draw.Shape{ 315 | scale: bs 316 | connect: .round //.miter //.round //.bevel 317 | radius: 4.5 318 | colors: draw.Colors{draw.rgba(0, 0, 0, 127), draw.rgba(255, 255, 255, 127)} 319 | } 320 | 321 | grey_blue := draw.Shape{ 322 | scale: bs 323 | colors: draw.Colors{draw.rgb(127, 127, 127), draw.rgb(0, 0, 127)} 324 | } 325 | 326 | thick_line := draw.Shape{ 327 | scale: bs 328 | radius: 4 329 | colors: draw.Colors{draw.rgba(0, 127, 25, 127), draw.rgba(0, 127, 25, 127)} 330 | } 331 | 332 | dbgf := if a.d.all(.draw) { draw.Fill.debug } else { draw.Fill.invisible } 333 | debug_brush := draw.Shape{ 334 | scale: bs 335 | fill: dbgf 336 | colors: draw.Colors{draw.rgba(0, 0, 125, 25), draw.rgba(0, 0, 125, 25)} 337 | } 338 | 339 | arx := a.canvas.rx 340 | ary := a.canvas.ry 341 | 342 | grey_blue.rectangle(arx, ary, size_w, size_h) 343 | 344 | wbr.rounded_rectangle(arx * 1.1 + 50, ary * 1.1 + 50, size_w, size_h, 20) 345 | 346 | // 347 | sgl.push_matrix() 348 | 349 | circle_x := arx * 0.8 + 200 350 | circle_y := ary * 0.8 + 70 351 | 352 | draw.translate(circle_x, circle_y, 0) 353 | rot_y := loopf(f32(a.frame) * 0.02, sgl.rad(0), sgl.rad(360)) 354 | 355 | draw.rotate(rot_y, 0.0, 1.0, 0.0) 356 | draw.translate(-circle_x, -circle_y, 0) 357 | 358 | wbr.colors.solid = draw.rgba(225, 120, 0, 127) 359 | wbr.circle(circle_x, circle_y, 20, 40) 360 | sgl.pop_matrix() 361 | // 362 | 363 | wbr.colors.solid = draw.rgba(0, 0, 0, 127) 364 | wbr.ellipse(arx * 0.8 + 400, ary * 0.8 + 60, 40, 80, 50) 365 | 366 | wbr.arc(600, 500, 50, 0 * draw.deg2rad, 90 * draw.deg2rad) 367 | 368 | wbr.triangle(20, 20, 50, 30, 25, 65) 369 | 370 | wbr.rectangle(100 + arx * 1.1, 400 + ary * 1.1, size_w * 0.5, size_h * 0.5) 371 | wbr.line(arx + 280, ary + 200, arx + 500, ary + 200 + 200) 372 | 373 | wbr.poly([f32(0), 0, 100, 0, 150, 50, 110, 70, 80, 50, 40, 60, 0, 10], []int{}, arx + 150, 374 | ary + 100 * 1.1) 375 | 376 | wbr.poly([f32(0), 0, 40, -40, 100, 0, 150, 50, 110, 70, 80, 50, 40, 60, 0, 10, 20, 5, 40, -2, 377 | 70, 32, 32, 20], [8], arx + 150, ary + 300) 378 | 379 | wbr.convex_poly([f32(0), 0, 100, 0, 150, 50, 150, 80, 80, 100, 0, 50], arx + 400 * 1.1, 380 | ary + 400 * 1.1) 381 | 382 | wbr.uniform_segment_poly(800, 500, 60, 5) 383 | 384 | wbr.segment_poly(200, 550, 40, 60, 8) 385 | 386 | wb.image(arx + 200, ary, size_w * 0.5, size_h * 0.5, os.resource_abs_path(os.join_path('..', 387 | 'img', 'logo.png'))) 388 | 389 | thick_line.line(arx + 200, ary + 200, arx + 400, ary + 200 + 200 * ary * 0.051) 390 | wb.line(arx + 200, ary + 200, arx + 400, ary + 200 + 200 * ary * 0.051) 391 | 392 | thick_line.line(arx + 200, ary + 200, arx + 600, ary + 200) 393 | wb.line(arx + 200, ary + 200, arx + 600, ary + 200) 394 | 395 | // if a.d.all(.draw) { 396 | debug_brush.rectangle(arx, ary, size_w, size_h) 397 | //} 398 | } 399 | 400 | @[inline] 401 | fn loopf(value f32, from f32, to f32) f32 { 402 | range := to - from 403 | offset_value := value - from // value relative to 0 404 | // + `from` to reset back to start of original range 405 | return (offset_value - f32((math.floor(offset_value / range) * range))) + from 406 | } 407 | 408 | // Debug stuff 409 | 410 | @[flag] 411 | pub enum Flag { 412 | app 413 | print 414 | flood 415 | input 416 | draw 417 | debug_state 418 | } 419 | 420 | struct Debug { 421 | mut: 422 | flags Flag = .print | .input | .app | .debug_state 423 | } 424 | 425 | fn (d Debug) all(flags Flag) bool { 426 | return d.flags.all(flags) 427 | } 428 | 429 | fn (d Debug) has(flags Flag) bool { 430 | return d.flags.has(flags) 431 | } 432 | 433 | fn (mut d Debug) on(flag Flag) { 434 | if !d.has(flag) { 435 | d.flags.set(flag) 436 | d.pln(.debug_state, flag.str().all_after('.').trim_right('}') + ' ${d.state(flag)}') 437 | } 438 | } 439 | 440 | fn (mut d Debug) off(flag Flag) { 441 | if d.has(flag) { 442 | d.flags.clear(flag) 443 | d.pln(.debug_state, flag.str().all_after('.').trim_right('}') + ' ${d.state(flag)}') 444 | } 445 | } 446 | 447 | fn (mut d Debug) toggle(flag Flag) { 448 | d.flags.toggle(flag) 449 | d.pln(.debug_state, flag.str().all_after('.').trim_right('}') + ' ${d.state(flag)}') 450 | } 451 | 452 | fn (d Debug) state(flag Flag) string { 453 | return if d.has(flag) { 'on' } else { 'off' } 454 | } 455 | 456 | @[if !prod] 457 | fn (d Debug) pln(flag Flag, str string) { 458 | if !d.flags.has(.print) { 459 | return 460 | } 461 | if d.flags.has(flag) { 462 | f := flag.str().all_after('.').trim_right('}') 463 | println(f + ' ' + str) 464 | } 465 | } 466 | 467 | @[if !prod] 468 | fn (d Debug) plng(flag Flag, str string) { 469 | if !d.flags.has(.print) { 470 | return 471 | } 472 | if d.flags & flag == flag { 473 | f := flag.str().all_after('.').trim_right('}').split(' | ').join('') 474 | println(f + ' ' + str) 475 | } 476 | } 477 | -------------------------------------------------------------------------------- /earcut/earcut.v: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2020-2022 Lars Pontoppidan. All rights reserved. 2 | // Use of this source code is governed by MIT and ISC licenses (mapbox). 3 | // Both files are distributed with this software package. 4 | // 5 | // The following code is a near 1:1 hand-ported V version of https://github.com/mapbox/earcut 6 | // The module can be converted to use f64 precision by a simple /f32/f64/g 7 | module earcut 8 | 9 | import math 10 | 11 | @[direct_array_access; inline] 12 | pub fn earcut(data []f32, hole_indices []int, rdim int) []i64 { 13 | dim := if rdim > 0 { rdim } else { 2 } 14 | has_holes := hole_indices.len > 0 15 | outer_len := if has_holes { hole_indices[0] * dim } else { data.len } 16 | mut outer_node := linked_list(data, 0, outer_len, dim, true) 17 | mut triangles := []i64{} 18 | if isnil(outer_node) || equals(outer_node.next, outer_node.prev) { 19 | return triangles 20 | } 21 | mut min_x := f32(0) 22 | mut min_y := f32(0) 23 | mut max_x := f32(0) 24 | mut max_y := f32(0) 25 | mut x := f32(0) 26 | mut y := f32(0) 27 | mut inv_size := f32(0) 28 | if has_holes { 29 | outer_node = eliminate_holes(data, hole_indices, mut outer_node, dim) 30 | } 31 | // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox 32 | if data.len > 80 * dim { 33 | min_x = data[0] 34 | max_x = data[0] 35 | min_y = data[1] 36 | max_y = data[1] 37 | for i := dim; i < outer_len; i += dim { 38 | x = data[i] 39 | y = data[i + 1] 40 | if x < min_x { 41 | min_x = x 42 | } 43 | if y < min_y { 44 | min_y = y 45 | } 46 | if x > max_x { 47 | max_x = x 48 | } 49 | if y > max_y { 50 | max_y = y 51 | } 52 | } 53 | // min_x, min_y and inv_size are later used to transform coords into integers for z-order calculation 54 | inv_size = max_f32(max_x - min_x, max_y - min_y) 55 | inv_size = if inv_size != 0.0 { 1 / inv_size } else { 0 } 56 | } 57 | earcut_linked(mut outer_node, mut triangles, dim, min_x, min_y, inv_size, 0) 58 | return triangles 59 | } 60 | 61 | // linked_list create a circular doubly linked list from polygon points in the specified winding order 62 | @[direct_array_access; inline] 63 | fn linked_list(data []f32, start int, end int, dim int, clockwise bool) &Node { 64 | mut i := 0 65 | mut last := &Node(unsafe { nil }) 66 | 67 | if clockwise == (signed_area(data, start, end, dim) > 0) { 68 | for i = start; i < end; i += dim { 69 | last = insert_node(i, data[i], data[i + 1], mut last) 70 | } 71 | } else { 72 | for i = end - dim; i >= start; i -= dim { 73 | last = insert_node(i, data[i], data[i + 1], mut last) 74 | } 75 | } 76 | 77 | if !isnil(last) && equals(last, last.next) { 78 | remove_node(mut last) 79 | last = last.next 80 | } 81 | return last 82 | } 83 | 84 | // filter_points eliminate colinear or duplicate points 85 | @[inline] 86 | fn filter_points(mut start_ Node, mut end_ Node) &Node { 87 | // TODO BUG WORKAROUND 88 | mut start := &Node(unsafe { nil }) 89 | start = start_ 90 | 91 | // TODO BUG WORKAROUND 92 | mut end := &Node(unsafe { nil }) 93 | end = end_ 94 | 95 | if isnil(start) { 96 | return start 97 | } 98 | if isnil(end) { 99 | end = start 100 | } 101 | 102 | mut p := start 103 | mut again := false 104 | for { 105 | again = false 106 | if !p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) == 0) { 107 | remove_node(mut p) 108 | p = p.prev 109 | end = p.prev 110 | if equals(p, p.next) { 111 | break 112 | } 113 | again = true 114 | } else { 115 | p = p.next 116 | } 117 | if !(again || !equals(p, end)) { 118 | break 119 | } 120 | // while (again || p !== end);?? 121 | } 122 | 123 | return end 124 | } 125 | 126 | // earcut_linked main ear slicing loop which triangulates a polygon (given as a linked list) 127 | @[direct_array_access; inline] 128 | fn earcut_linked(mut ear_ Node, mut triangles []i64, dim int, min_x f32, min_y f32, inv_size f32, pass int) { 129 | // TODO BUG WORKAROUND 130 | mut ear := &Node(unsafe { nil }) 131 | ear = ear_ 132 | 133 | if isnil(ear) { 134 | return 135 | } 136 | // interlink polygon nodes in z-order 137 | if pass == 0 && inv_size > 0.0 { 138 | index_curve(ear, min_x, min_y, inv_size) 139 | } 140 | 141 | mut stop := ear 142 | mut prev := &Node(unsafe { nil }) 143 | mut next := &Node(unsafe { nil }) 144 | mut null := &Node(unsafe { nil }) 145 | // iterate through ears, slicing them one by one 146 | for !equals(ear.prev, ear.next) { 147 | prev = ear.prev 148 | next = ear.next 149 | cutoff := if inv_size > 0 { is_ear_hashed(ear, min_x, min_y, inv_size) } else { is_ear(ear) } 150 | if cutoff { 151 | // cut off the triangle 152 | triangles << prev.i / dim 153 | triangles << ear.i / dim 154 | triangles << next.i / dim 155 | remove_node(mut ear) 156 | // skipping the next vertex leads to less sliver triangles 157 | ear = next.next 158 | stop = next.next 159 | continue 160 | } 161 | ear = next 162 | // if we looped through the whole remaining polygon and can't find any more ears 163 | if equals(ear, stop) { 164 | // try filtering points and slicing again 165 | if pass == 0 { 166 | mut res := filter_points(mut ear, mut null) 167 | earcut_linked(mut res, mut triangles, dim, min_x, min_y, inv_size, 1) 168 | // if this didn't work, try curing all small self-intersections locally 169 | } else if pass == 1 { 170 | mut filtered := filter_points(mut ear, mut null) 171 | ear = cure_local_intersections(mut filtered, mut triangles, dim) 172 | earcut_linked(mut ear, mut triangles, dim, min_x, min_y, inv_size, 2) 173 | // as a last resort, try splitting the remaining polygon into two 174 | } else if pass == 2 { 175 | split_earcut(ear, mut triangles, dim, min_x, min_y, inv_size) 176 | } 177 | break 178 | } 179 | } 180 | } 181 | 182 | // is_ear check whether a polygon node forms a valid ear with adjacent nodes 183 | @[inline] 184 | fn is_ear(ear &Node) bool { 185 | a := ear.prev 186 | b := ear 187 | c := ear.next 188 | if area(a, b, c) >= 0 { 189 | return false 190 | } 191 | // reflex, can't be an ear 192 | // now make sure we don't have other points inside the potential ear 193 | mut p := ear.next.next 194 | for !equals(p, ear.prev) { 195 | if point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0 { 196 | return false 197 | } 198 | p = p.next 199 | } 200 | return true 201 | } 202 | 203 | @[inline] 204 | fn is_ear_hashed(ear &Node, min_x f32, min_y f32, inv_size f32) bool { 205 | a := ear.prev 206 | b := ear 207 | c := ear.next 208 | if area(a, b, c) >= 0 { 209 | return false 210 | } 211 | // reflex, can't be an ear 212 | // triangle bbox; min & max are calculated like this for speed 213 | min_tx := if a.x < b.x { 214 | if a.x < c.x { a.x } else { c.x } 215 | } else { 216 | if b.x < c.x { b.x } else { c.x } 217 | } 218 | min_ty := if a.y < b.y { 219 | if a.y < c.y { a.y } else { c.y } 220 | } else { 221 | if b.y < c.y { b.y } else { c.y } 222 | } 223 | max_tx := if a.x > b.x { 224 | if a.x > c.x { a.x } else { c.x } 225 | } else { 226 | if b.x > c.x { b.x } else { c.x } 227 | } 228 | max_ty := if a.y > b.y { 229 | if a.y > c.y { a.y } else { c.y } 230 | } else { 231 | if b.y > c.y { b.y } else { c.y } 232 | } 233 | // z-order range for the current triangle bbox; 234 | min_z := z_order(min_tx, min_ty, min_x, min_y, inv_size) 235 | max_z := z_order(max_tx, max_ty, min_x, min_y, inv_size) 236 | mut p := ear.prev_z 237 | mut n := ear.next_z 238 | // look for points inside the triangle in both directions 239 | for !isnil(p) && p.z >= min_z && !isnil(n) && n.z <= max_z { 240 | if !equals(p, ear.prev) && !equals(p, ear.next) 241 | && point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) 242 | && area(p.prev, p, p.next) >= 0 { 243 | return false 244 | } 245 | p = p.prev_z 246 | if !equals(n, ear.prev) && !equals(n, ear.next) 247 | && point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) 248 | && area(n.prev, n, n.next) >= 0 { 249 | return false 250 | } 251 | n = n.next_z 252 | } 253 | // look for remaining points in decreasing z-order 254 | for !isnil(p) && p.z >= min_z { 255 | if !equals(p, ear.prev) && !equals(p, ear.next) 256 | && point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) 257 | && area(p.prev, p, p.next) >= 0 { 258 | return false 259 | } 260 | p = p.prev_z 261 | } 262 | // look for remaining points in increasing z-order 263 | for !isnil(n) && n.z <= max_z { 264 | if !equals(n, ear.prev) && !equals(n, ear.next) 265 | && point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) 266 | && area(n.prev, n, n.next) >= 0 { 267 | return false 268 | } 269 | n = n.next_z 270 | } 271 | return true 272 | } 273 | 274 | // cure_local_intersections go through all polygon nodes and cure small local self-intersections 275 | @[direct_array_access; inline] 276 | fn cure_local_intersections(mut start_ Node, mut triangles []i64, dim int) &Node { 277 | // TODO BUG WORKAROUND 278 | mut start := &Node(unsafe { nil }) 279 | start = start_ 280 | 281 | mut p := start 282 | mut null := &Node(unsafe { nil }) 283 | for { 284 | a := p.prev 285 | 286 | // TODO BUG WORKAROUND 287 | // b := p.next.next 288 | mut p_next := p.next 289 | mut b := p_next 290 | 291 | if !equals(a, b) && intersects(a, p, p.next, b) && locally_inside(a, b) 292 | && locally_inside(b, a) { 293 | triangles << a.i / dim 294 | triangles << p.i / dim 295 | triangles << b.i / dim 296 | // remove two nodes involved 297 | remove_node(mut p) 298 | remove_node(mut p.next) 299 | p = b 300 | start = b 301 | } 302 | p = p.next 303 | if equals(p, start) { 304 | break 305 | } 306 | } 307 | return filter_points(mut p, mut null) 308 | } 309 | 310 | // split_earcut try splitting polygon into two and triangulate them independently 311 | @[direct_array_access; inline] 312 | fn split_earcut(start &Node, mut triangles []i64, dim int, min_x f32, min_y f32, inv_size f32) { 313 | // look for a valid diagonal that divides the polygon into two 314 | mut a := unsafe { start } 315 | for { 316 | mut b := a.next.next 317 | for !equals(b, a.prev) { 318 | if a.i != b.i && is_valid_diagonal(a, b) { 319 | // split the polygon in two by the diagonal 320 | mut c := split_polygon(mut a, mut b) 321 | // filter colinear points around the cuts 322 | a = filter_points(mut a, mut a.next) 323 | c = filter_points(mut c, mut c.next) 324 | // run earcut on each half 325 | earcut_linked(mut a, mut triangles, dim, min_x, min_y, inv_size, 0) 326 | earcut_linked(mut c, mut triangles, dim, min_x, min_y, inv_size, 0) 327 | return 328 | } 329 | b = b.next 330 | } 331 | a = a.next 332 | if equals(a, start) { 333 | break 334 | } 335 | } 336 | } 337 | 338 | // TODO 339 | fn sort_queue_by_x(a &&Node, b &&Node) int { 340 | return int(a.x - b.x) 341 | } 342 | 343 | // eliminate_holes link every hole into the outer loop, producing a single-ring polygon without holes 344 | @[direct_array_access; inline] 345 | fn eliminate_holes(data []f32, hole_indices []int, mut outer_node_ Node, dim int) &Node { 346 | // TODO BUG WORKAROUND 347 | mut outer_node := &Node(unsafe { nil }) 348 | outer_node = outer_node_ 349 | 350 | mut queue := []&Node{} 351 | len := hole_indices.len 352 | mut start := 0 353 | mut end := 0 354 | mut list := &Node(unsafe { nil }) 355 | for i := 0; i < len; i++ { 356 | start = hole_indices[i] * dim 357 | end = if i < len - 1 { hole_indices[i + 1] * dim } else { data.len } 358 | list = linked_list(data, start, end, dim, false) 359 | if equals(list, list.next) { 360 | list.steiner = true 361 | } 362 | queue << get_leftmost(list) 363 | } 364 | 365 | // queue.sort(a.x - b.x) // TODO C error: "error: ';' expected (got "*")" 366 | // queue.sort(fn(a &Node, b &Node) int { return a.x - b.x }) 367 | queue.sort_with_compare(sort_queue_by_x) 368 | 369 | // process holes from left to right 370 | list = &Node(unsafe { nil }) 371 | for i := 0; i < queue.len; i++ { 372 | list = queue[i] 373 | outer_node = eliminate_hole(mut list, mut outer_node) 374 | outer_node = filter_points(mut outer_node, mut outer_node.next) 375 | } 376 | return outer_node 377 | } 378 | 379 | // eliminate_hole find a bridge between vertices that connects hole with an outer ring and and link it 380 | @[inline] 381 | fn eliminate_hole(mut hole_ Node, mut outer_node_ Node) &Node { 382 | // TODO BUG WORKAROUND 383 | mut outer_node := &Node(unsafe { nil }) 384 | outer_node = outer_node_ 385 | 386 | // TODO BUG WORKAROUND 387 | mut hole := &Node(unsafe { nil }) 388 | hole = hole_ 389 | 390 | mut bridge := find_hole_bridge(hole, outer_node) 391 | if isnil(bridge) { 392 | return outer_node 393 | } 394 | 395 | mut bridge_reverse := split_polygon(mut bridge, mut hole) 396 | 397 | // filter collinear points around the cuts 398 | filtered_bridge := filter_points(mut bridge, mut bridge.next) 399 | filter_points(mut bridge_reverse, mut bridge_reverse.next) 400 | 401 | // Check if input node was removed by the filtering 402 | if equals(outer_node, bridge) { 403 | return filtered_bridge 404 | } 405 | return outer_node 406 | } 407 | 408 | // find_hole_bridge David Eberly's algorithm for finding a bridge between hole and outer polygon 409 | @[inline] 410 | fn find_hole_bridge(hole &Node, outer_node &Node) &Node { 411 | mut p := unsafe { outer_node } 412 | hx := hole.x 413 | hy := hole.y 414 | mut qx := -math.max_f32 415 | mut m := &Node(unsafe { nil }) 416 | // find a segment intersected by a ray from the hole's leftmost point to the left; 417 | // segment's endpoint with lesser x will be potential connection point 418 | mut x := f32(0) 419 | for { 420 | if hy <= p.y && hy >= p.next.y && p.next.y != p.y { 421 | x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y) 422 | if x <= hx && x > qx { 423 | qx = x 424 | if x == hx { 425 | if hy == p.y { 426 | return p 427 | } 428 | if hy == p.next.y { 429 | return p.next 430 | } 431 | } 432 | m = if p.x < p.next.x { p } else { p.next } 433 | } 434 | } 435 | p = p.next 436 | if equals(p, outer_node) { 437 | break 438 | } 439 | // while (p !== outerNode); 440 | } 441 | if isnil(m) { 442 | return m 443 | } 444 | if hx == qx { 445 | return m 446 | } 447 | // hole touches outer segment; pick leftmost endpoint 448 | // look for points inside the triangle of hole point, segment intersection and endpoint; 449 | // if there are no points found, we have a valid connection; 450 | // otherwise choose the point of the minimum angle with the ray as connection point 451 | stop := m 452 | mx := m.x 453 | my := m.y 454 | mut tan_min := math.max_f32 455 | mut tan := f32(0) 456 | p = m 457 | for { 458 | if hx >= p.x && p.x >= mx && hx != p.x 459 | && point_in_triangle(if hy < my { f32(hx) } else { f32(qx) }, hy, mx, my, if hy < my { f32(qx) } else { f32(hx) }, hy, p.x, p.y) { 460 | tan = f32(math.abs(hy - p.y) / (hx - p.x)) // tangential 461 | if locally_inside(p, hole) && (tan < tan_min || (tan == tan_min && (p.x > m.x 462 | || (p.x == m.x && sector_contains_sector(m, p))))) { 463 | m = p 464 | tan_min = tan 465 | } 466 | } 467 | p = p.next 468 | if equals(p, stop) { 469 | break 470 | } 471 | // while (p !== stop); 472 | } 473 | return m 474 | } 475 | 476 | // sector_contains_sector whether sector in vertex m contains sector in vertex p in the same coordinates 477 | @[inline] 478 | fn sector_contains_sector(m &Node, p &Node) bool { 479 | return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0 480 | } 481 | 482 | // index_curve interlink polygon nodes in z-order 483 | @[inline] 484 | fn index_curve(start &Node, min_x f32, min_y f32, inv_size f32) { 485 | mut p := unsafe { start } 486 | for { 487 | if p.z == 0 { 488 | p.z = z_order(p.x, p.y, min_x, min_y, inv_size) 489 | } 490 | p.prev_z = p.prev 491 | p.next_z = p.next 492 | p = p.next 493 | if equals(p, start) { 494 | break 495 | } 496 | } 497 | p.prev_z.next_z = &Node(unsafe { nil }) 498 | p.prev_z = &Node(unsafe { nil }) 499 | sort_linked(mut p) 500 | } 501 | 502 | // sort_linked Simon Tatham's linked list merge sort algorithm 503 | // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html 504 | @[inline] 505 | fn sort_linked(mut list_ Node) &Node { 506 | // TODO BUG WORKAROUND 507 | mut list := &Node(unsafe { nil }) 508 | list = list_ 509 | 510 | mut i := 0 511 | mut p := &Node(unsafe { nil }) 512 | mut q := &Node(unsafe { nil }) 513 | mut e := &Node(unsafe { nil }) 514 | mut tail := &Node(unsafe { nil }) 515 | mut num_merges := 0 516 | mut p_size := 0 517 | mut q_size := 0 518 | mut in_size := 1 519 | for { 520 | p = list 521 | list = &Node(unsafe { nil }) 522 | tail = &Node(unsafe { nil }) 523 | num_merges = 0 524 | for !isnil(p) { 525 | num_merges++ 526 | q = p 527 | p_size = 0 528 | for i = 0; i < in_size; i++ { 529 | p_size++ 530 | q = q.next_z 531 | if isnil(q) { 532 | break 533 | } 534 | } 535 | q_size = in_size 536 | for p_size > 0 || (q_size > 0 && !isnil(q)) { 537 | if p_size != 0 && (q_size == 0 || isnil(q) || p.z <= q.z) { 538 | e = p 539 | p = p.next_z 540 | p_size-- 541 | } else { 542 | e = q 543 | q = q.next_z 544 | q_size-- 545 | } 546 | if !isnil(tail) { 547 | tail.next_z = e 548 | } else { 549 | list = e 550 | } 551 | e.prev_z = tail 552 | tail = e 553 | } 554 | p = q 555 | } 556 | tail.next_z = &Node(unsafe { nil }) 557 | in_size *= 2 558 | if num_merges > 1 { 559 | break 560 | } 561 | } 562 | return list 563 | } 564 | 565 | // z_order z-order of a point given coords and inverse of the longer side of data bbox 566 | @[inline] 567 | fn z_order(x f32, y f32, min_x f32, min_y f32, inv_size f32) u16 { 568 | // coords are transformed into non-negative 15-bit integer range 569 | mut nx := 32767 * u16(x - min_x) * u16(inv_size) 570 | mut ny := 32767 * u16(y - min_y) * u16(inv_size) 571 | 572 | nx = (nx | (nx << 8)) & 0x00FF00FF 573 | nx = (nx | (nx << 4)) & 0x0F0F0F0F 574 | nx = (nx | (nx << 2)) & 0x33333333 575 | nx = (nx | (nx << 1)) & 0x55555555 576 | 577 | ny = (ny | (ny << 8)) & 0x00FF00FF 578 | ny = (ny | (ny << 4)) & 0x0F0F0F0F 579 | ny = (ny | (ny << 2)) & 0x33333333 580 | ny = (ny | (ny << 1)) & 0x55555555 581 | 582 | return nx | (ny << 1) 583 | } 584 | 585 | // get_leftmost find the leftmost node of a polygon ring 586 | @[inline] 587 | fn get_leftmost(start &Node) &Node { 588 | mut p := unsafe { start } 589 | mut leftmost := unsafe { start } 590 | for { 591 | if p.x < leftmost.x || (p.x == leftmost.x && p.y < leftmost.y) { 592 | leftmost = p 593 | } 594 | p = p.next 595 | if equals(p, start) { 596 | break 597 | } 598 | } 599 | return leftmost 600 | } 601 | 602 | // point_in_triangle check if a point lies within a convex triangle 603 | @[inline] 604 | fn point_in_triangle(ax f32, ay f32, bx f32, by f32, cx f32, cy f32, px f32, py f32) bool { 605 | return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 606 | && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 607 | && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0 608 | } 609 | 610 | // is_valid_diagonal check if a diagonal between two polygon nodes is valid (lies in polygon interior) 611 | @[inline] 612 | fn is_valid_diagonal(a &Node, b &Node) bool { 613 | doesnt_intersect := a.next.i != b.i && a.prev.i != b.i 614 | && !intersects_polygon(a, b) // dones't intersect other edges 615 | locally_visible := locally_inside(a, b) && locally_inside(b, a) 616 | && middle_inside(a, b) // locally visible 617 | not_opposite_facing := (area(a.prev, a, b.prev) != 0.0 || area(a, b.prev, b) != 0.0) // does not create opposite-facing sectors 618 | zero_length_case := equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0 // special zero-length case 619 | return doesnt_intersect && ((locally_visible && not_opposite_facing) || zero_length_case) 620 | } 621 | 622 | // area signed area of a triangle 623 | @[inline] 624 | fn area(p &Node, q &Node, r &Node) f32 { 625 | return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y) 626 | } 627 | 628 | // equals check if two points are equal 629 | @[inline] 630 | fn equals(p1 &Node, p2 &Node) bool { 631 | return p1.x == p2.x && p1.y == p2.y 632 | } 633 | 634 | // intersects check if two segments intersect 635 | @[inline] 636 | fn intersects(p1 &Node, q1 &Node, p2 &Node, q2 &Node) bool { 637 | o1 := sign(area(p1, q1, p2)) 638 | o2 := sign(area(p1, q1, q2)) 639 | o3 := sign(area(p2, q2, p1)) 640 | o4 := sign(area(p2, q2, q1)) 641 | if o1 != o2 && o3 != o4 { 642 | return true 643 | } 644 | // general case 645 | if o1 == 0 && on_segment(p1, p2, q1) { 646 | return true 647 | } 648 | // p1, q1 and p2 are collinear and p2 lies on p1q1 649 | if o2 == 0 && on_segment(p1, q2, q1) { 650 | return true 651 | } 652 | // p1, q1 and q2 are collinear and q2 lies on p1q1 653 | if o3 == 0 && on_segment(p2, p1, q2) { 654 | return true 655 | } 656 | // p2, q2 and p1 are collinear and p1 lies on p2q2 657 | if o4 == 0 && on_segment(p2, q1, q2) { 658 | return true 659 | } 660 | // p2, q2 and q1 are collinear and q1 lies on p2q2 661 | return false 662 | } 663 | 664 | // on_segment for collinear points p, q, r, check if point q lies on segment pr 665 | @[inline] 666 | fn on_segment(p &Node, q &Node, r &Node) bool { 667 | return q.x <= max_f32(p.x, r.x) && q.x >= min_f32(p.x, r.x) && q.y <= max_f32(p.y, r.y) 668 | && q.y >= min_f32(p.y, r.y) 669 | } 670 | 671 | @[inline] 672 | fn max_f32(a f32, b f32) f32 { 673 | if a > b { 674 | return a 675 | } 676 | return b 677 | } 678 | 679 | @[inline] 680 | fn min_f32(a f32, b f32) f32 { 681 | if a < b { 682 | return a 683 | } 684 | return b 685 | } 686 | 687 | @[inline] 688 | fn sign(num f32) int { 689 | if num > 0 { 690 | return 1 691 | } else if num < 0 { 692 | return -1 693 | } 694 | return 0 695 | } 696 | 697 | // intersects_polygon check if a polygon diagonal intersects any polygon segments 698 | @[inline] 699 | fn intersects_polygon(a &Node, b &Node) bool { 700 | // mut p := &Node(unsafe{nil}) 701 | mut p := unsafe { a } 702 | for { 703 | if p.i != a.i && p.next.i != a.i && p.i != b.i && p.next.i != b.i 704 | && intersects(p, p.next, a, b) { 705 | return true 706 | } 707 | p = p.next 708 | if equals(p, a) { 709 | break 710 | } 711 | } 712 | return false 713 | } 714 | 715 | // locally_inside check if a polygon diagonal is locally inside the polygon 716 | @[inline] 717 | fn locally_inside(a &Node, b &Node) bool { 718 | if area(a.prev, a, a.next) < 0 { 719 | return area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 720 | } else { 721 | return area(a, b, a.prev) < 0 || area(a, a.next, b) < 0 722 | } 723 | } 724 | 725 | // middle_inside check if the middle point of a polygon diagonal is inside the polygon 726 | @[inline] 727 | fn middle_inside(a &Node, b &Node) bool { 728 | mut p := unsafe { a } 729 | // mut p := &Node(unsafe{nil}) 730 | mut inside := false 731 | px := (a.x + b.x) / 2 732 | py := (a.y + b.y) / 2 733 | 734 | for { 735 | if (p.y > py) != (p.next.y > py) && p.next.y != p.y 736 | && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x { 737 | inside = !inside 738 | } 739 | p = p.next 740 | if equals(p, a) { 741 | break 742 | } 743 | } 744 | return inside 745 | } 746 | 747 | // split_polygon link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; 748 | // if one belongs to the outer ring and another to a hole, it merges it into a single ring 749 | @[inline] 750 | fn split_polygon(mut a Node, mut b Node) &Node { 751 | mut a2 := &Node{ 752 | i: a.i 753 | x: a.x 754 | y: a.y 755 | } 756 | mut b2 := &Node{ 757 | i: b.i 758 | x: b.x 759 | y: b.y 760 | } 761 | mut an := a.next 762 | mut bp := b.prev 763 | a.next = b 764 | b.prev = a 765 | // 766 | a2.next = an 767 | an.prev = a2 768 | // 769 | b2.next = a2 770 | a2.prev = b2 771 | // 772 | bp.next = b2 773 | b2.prev = bp 774 | return b2 775 | } 776 | 777 | // insert_node create a node and optionally link it with previous one (in a circular doubly linked list) 778 | @[inline] 779 | fn insert_node(i i64, x f32, y f32, mut last Node) &Node { 780 | mut p := &Node{ 781 | i: i 782 | x: x 783 | y: y 784 | } 785 | if isnil(last) { 786 | p.prev = p 787 | p.next = p 788 | } else { 789 | p.next = last.next 790 | p.prev = last 791 | last.next.prev = p 792 | last.next = p 793 | } 794 | return p 795 | } 796 | 797 | @[inline] 798 | fn remove_node(mut p Node) { 799 | p.next.prev = p.prev 800 | p.prev.next = p.next 801 | if !isnil(p.prev_z) { 802 | p.prev_z.next_z = p.next_z 803 | } 804 | if !isnil(p.next_z) { 805 | p.next_z.prev_z = p.prev_z 806 | } 807 | // TODO unsafe { free(p) } 808 | } 809 | 810 | @[heap] 811 | pub struct Node { 812 | mut: 813 | // vertex index in coordinates array 814 | i i64 815 | // vertex coordinates 816 | x f32 817 | y f32 818 | // previous and next vertex nodes in a polygon ring 819 | prev &Node = unsafe { nil } 820 | next &Node = unsafe { nil } 821 | // z-order curve value 822 | z f32 823 | // previous and next nodes in z-order 824 | prev_z &Node = unsafe { nil } 825 | next_z &Node = unsafe { nil } 826 | // indicates whether this is a steiner point 827 | steiner bool 828 | } 829 | 830 | fn (n &Node) str() string { 831 | return '&Node@${ptr_str(n)} { 832 | i: ${n.i}, 833 | x: ${n.x}, 834 | y: ${n.y}, 835 | z: ${n.z}, 836 | prev: *${ptr_str(n.prev)}, 837 | next: *${ptr_str(n.next)}, 838 | prev_z: *${ptr_str(n.prev_z)}, 839 | next_z: *${ptr_str(n.prev_z)} 840 | steiner: ${n.steiner} 841 | }' 842 | } 843 | 844 | // deviation return a percentage difference between the polygon area and its triangulation area; 845 | // used to verify correctness of triangulation 846 | @[direct_array_access; inline] 847 | pub fn deviation(data []f32, hole_indices []int, dim int, triangles []i64) f32 { 848 | has_holes := hole_indices.len > 0 849 | outer_len := if has_holes { hole_indices[0] * dim } else { data.len } 850 | mut polygon_area := f32(math.abs(signed_area(data, 0, outer_len, dim))) 851 | if has_holes { 852 | mut i := 0 853 | len := hole_indices.len 854 | mut start := hole_indices[0] * dim 855 | mut end := if i < len - 1 { hole_indices[i + 1] * dim } else { data.len } 856 | for ; i < len; i++ { 857 | start = hole_indices[i] * dim 858 | end = if i < len - 1 { hole_indices[i + 1] * dim } else { data.len } 859 | polygon_area -= f32(math.abs(signed_area(data, start, end, dim))) 860 | } 861 | } 862 | mut triangles_area := f32(0) 863 | for i := 0; i < triangles.len; i += 3 { 864 | a := i64(triangles[i] * dim) 865 | b := i64(triangles[i + 1] * dim) 866 | c := i64(triangles[i + 2] * dim) 867 | triangles_area += f32(math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[ 868 | c + 1] - data[a + 1]))) 869 | } 870 | if polygon_area == 0 && triangles_area == 0 { 871 | return 0 872 | } else { 873 | return f32(math.abs((triangles_area - polygon_area) / polygon_area)) 874 | } 875 | } 876 | 877 | @[direct_array_access; inline] 878 | fn signed_area(data []f32, start int, end int, dim int) f32 { 879 | mut sum := f32(0) 880 | mut j := end - dim 881 | mut i := start 882 | for ; i < end; i += dim { 883 | sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]) 884 | j = i 885 | } 886 | return sum 887 | } 888 | 889 | pub struct FlatResult { 890 | pub: 891 | dimensions int 892 | pub mut: 893 | vertices []f32 894 | holes []int 895 | } 896 | 897 | // flatten turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts 898 | @[direct_array_access; inline] 899 | pub fn flatten(data [][][]f32) FlatResult { 900 | dim := data[0][0].len 901 | mut result := FlatResult{ 902 | dimensions: dim 903 | } 904 | mut hole_index := 0 905 | for i := 0; i < data.len; i++ { 906 | for j := 0; j < data[i].len; j++ { 907 | for d := 0; d < dim; d++ { 908 | result.vertices << data[i][j][d] 909 | } 910 | } 911 | if i > 0 { 912 | hole_index += data[i - 1].len 913 | result.holes << hole_index 914 | } 915 | } 916 | return result 917 | } 918 | -------------------------------------------------------------------------------- /shape.v: -------------------------------------------------------------------------------- 1 | // Copyright(C) 2021-2022 Lars Pontoppidan. All rights reserved. 2 | // Use of this source code is governed by an MIT license file distributed with this software package 3 | module sgldraw 4 | 5 | import plot 6 | import sokol.sgl 7 | import math 8 | import sgldraw.earcut 9 | 10 | pub const deg2rad = f32((math.pi * 2) / 360) 11 | pub const rad2deg = f32(360 / (math.pi * 2)) 12 | 13 | const rad_max = 2 * math.pi 14 | const deg90rad = 90 * deg2rad 15 | const debug_shape = Shape{ 16 | colors: Colors{rgba(255, 0, 0, 55), rgba(255, 0, 0, 55)} 17 | } 18 | const no_indicies = []int{len: 0, cap: 0} 19 | 20 | pub struct Shape { 21 | pub mut: 22 | radius f32 = 1.0 23 | scale f32 = 1.0 24 | fill Fill = .solid | .outline 25 | cap Cap = .butt 26 | connect Connect = .bevel 27 | offset_x f32 = 0.0 28 | offset_y f32 = 0.0 29 | colors Colors = Colors{rgba(0, 0, 0, 255), rgba(255, 255, 255, 127)} 30 | } 31 | 32 | pub fn (mut b Shape) set_colors(outline Color, solid Color) { 33 | b.colors.outline = outline 34 | b.colors.solid = solid 35 | } 36 | 37 | @[inline] 38 | pub fn (b Shape) rectangle(x f32, y f32, w f32, h f32) { 39 | scale_factor := b.scale * dpi_scale() 40 | sx := x * scale_factor 41 | sy := y * scale_factor 42 | if scale_factor != 1 { 43 | push_matrix() 44 | translate(sx, sy, 0) 45 | scale(scale_factor, scale_factor, 1.0) 46 | translate(-sx, -sy, 0) 47 | } 48 | if b.fill.has(.solid) { 49 | c := b.colors.solid 50 | sgl.c4b(c.r, c.g, c.b, c.a) 51 | sgl.begin_quads() 52 | sgl.v2f(sx, sy) 53 | sgl.v2f((sx + w), sy) 54 | sgl.v2f((sx + w), (sy + h)) 55 | sgl.v2f(sx, (sy + h)) 56 | sgl.end() 57 | } 58 | if b.fill.has(.outline) { 59 | if b.radius > 1 { 60 | m12x, m12y := midpoint(sx, sy, sx + w, sy) 61 | m23x, m23y := midpoint(sx + w, sy, sx + w, sy + h) 62 | m34x, m34y := midpoint(sx + w, sy + h, sx, sy + h) 63 | m41x, m41y := midpoint(sx, sy + h, sx, sy) 64 | b.anchor(m12x, m12y, sx + w, sy, m23x, m23y) 65 | b.anchor(m23x, m23y, sx + w, sy + h, m34x, m34y) 66 | b.anchor(m34x, m34y, sx, sy + h, m41x, m41y) 67 | b.anchor(m41x, m41y, sx, sy, m12x, m12y) 68 | } else { 69 | sgl.c4b(b.colors.outline.r, b.colors.outline.g, b.colors.outline.b, b.colors.outline.a) 70 | sgl.begin_line_strip() 71 | sgl.v2f(sx, sy) 72 | sgl.v2f((sx + w), sy) 73 | sgl.v2f((sx + w), (sy + h)) 74 | sgl.v2f(sx, (sy + h)) 75 | sgl.v2f(sx, (sy - 1)) 76 | sgl.end() 77 | } 78 | } 79 | if b.fill.has(.debug) { 80 | debug_shape.rectangle(x, y, w, h) 81 | } 82 | if scale_factor != 1 { 83 | pop_matrix() 84 | } 85 | } 86 | 87 | @[inline] 88 | pub fn (b Shape) line(x1 f32, y1 f32, x2 f32, y2 f32) { 89 | scale_factor := b.scale * dpi_scale() 90 | c := b.colors.outline 91 | sgl.c4b(c.r, c.g, c.b, c.a) 92 | 93 | x1_ := x1 * scale_factor 94 | y1_ := y1 * scale_factor 95 | dx := x1 - x1_ 96 | dy := y1 - y1_ 97 | x2_ := x2 - dx 98 | y2_ := y2 - dy 99 | if scale_factor != 1 { 100 | push_matrix() 101 | translate(x1_, y1_, 0) 102 | scale(scale_factor, scale_factor, 1.0) 103 | translate(-x1_, -y1_, 0) 104 | } 105 | if b.radius > 1 { 106 | radius := b.radius 107 | 108 | mut tl_x := x1_ - x2_ 109 | mut tl_y := y1_ - y2_ 110 | tl_x, tl_y = perpendicular(tl_x, tl_y) 111 | tl_x, tl_y = normalize(tl_x, tl_y) 112 | tl_x *= radius 113 | tl_y *= radius 114 | tl_x += x1_ 115 | tl_y += y1_ 116 | 117 | tr_x := tl_x - x1_ + x2_ 118 | tr_y := tl_y - y1_ + y2_ 119 | 120 | mut bl_x := x2_ - x1_ 121 | mut bl_y := y2_ - y1_ 122 | bl_x, bl_y = perpendicular(bl_x, bl_y) 123 | bl_x, bl_y = normalize(bl_x, bl_y) 124 | bl_x *= radius 125 | bl_y *= radius 126 | bl_x += x1_ 127 | bl_y += y1_ 128 | 129 | br_x := bl_x - x1_ + x2_ 130 | br_y := bl_y - y1_ + y2_ 131 | 132 | /* 133 | sgl.c4b(255, 0, 0, 200) 134 | raw.rectangle(bl_x-1,br_y-1,2,2) 135 | raw.rectangle(tl_x-1,tl_y-1,2,2) 136 | raw.rectangle(tr_x-1,tr_y-1,2,2) 137 | raw.rectangle(br_x-1,br_y-1,2,2) 138 | */ 139 | 140 | sgl.c4b(c.r, c.g, c.b, c.a) 141 | 142 | sgl.begin_quads() 143 | sgl.v2f(tl_x, tl_y) 144 | sgl.v2f(tr_x, tr_y) 145 | sgl.v2f(br_x, br_y) 146 | sgl.v2f(bl_x, bl_y) 147 | sgl.end() 148 | } else { 149 | sgl.begin_line_strip() 150 | sgl.v2f(x1_, y1_) 151 | sgl.v2f(x2_, y2_) 152 | sgl.end() 153 | } 154 | if scale_factor != 1 { 155 | pop_matrix() 156 | } 157 | } 158 | 159 | @[inline] 160 | pub fn (b Shape) uniform_segment_poly(x f32, y f32, radius f32, steps u32) { 161 | scale_factor := b.scale * dpi_scale() 162 | sx := x * scale_factor 163 | sy := y * scale_factor 164 | 165 | if scale_factor != 1 { 166 | push_matrix() 167 | translate(sx, sy, 0) 168 | scale(scale_factor, scale_factor, 1.0) 169 | translate(-sx, -sy, 0) 170 | } 171 | mut c := b.colors.solid 172 | sgl.c4b(c.r, c.g, c.b, c.a) 173 | mut theta := f32(0) 174 | mut xx := f32(0) 175 | mut yy := f32(0) 176 | if b.fill.has(.solid) { 177 | sgl.begin_triangle_strip() 178 | for i := 0; i < steps + 1; i++ { 179 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 180 | xx = radius * math.cosf(theta) 181 | yy = radius * math.sinf(theta) 182 | sgl.v2f(xx + sx, yy + sy) 183 | sgl.v2f(sx, sy) 184 | } 185 | sgl.end() 186 | } 187 | if b.fill.has(.outline) { 188 | c = b.colors.outline 189 | sgl.c4b(c.r, c.g, c.b, c.a) 190 | if b.radius > 1 || scale_factor != 1 { 191 | for i := 0; i < steps; i++ { 192 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 193 | x1 := sx + (radius * math.cosf(theta)) 194 | y1 := sy + (radius * math.sinf(theta)) 195 | theta = 2.0 * f32(math.pi) * f32(i + 1) / f32(steps) 196 | x2 := sx + (radius * math.cosf(theta)) 197 | y2 := sy + (radius * math.sinf(theta)) 198 | theta = 2.0 * f32(math.pi) * f32(i + 2) / f32(steps) 199 | x3 := sx + (radius * math.cosf(theta)) 200 | y3 := sy + (radius * math.sinf(theta)) 201 | 202 | m12x, m12y := midpoint(x1, y1, x2, y2) 203 | m23x, m23y := midpoint(x2, y2, x3, y3) 204 | 205 | b.anchor(m12x, m12y, x2, y2, m23x, m23y) 206 | } 207 | } else { 208 | sgl.begin_line_strip() 209 | for i := 0; i < steps + 1; i++ { 210 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 211 | xx = radius * math.cosf(theta) 212 | yy = radius * math.sinf(theta) 213 | sgl.v2f(xx + sx, yy + sy) 214 | } 215 | sgl.end() 216 | } 217 | } 218 | if scale_factor != 1 { 219 | pop_matrix() 220 | } 221 | } 222 | 223 | @[inline] 224 | pub fn (b Shape) segment_poly(x f32, y f32, radius_x f32, radius_y f32, steps u32) { 225 | scale_factor := b.scale * dpi_scale() 226 | sx := x * scale_factor 227 | sy := y * scale_factor 228 | if scale_factor != 1 { 229 | push_matrix() 230 | translate(sx, sy, 0) 231 | scale(scale_factor, scale_factor, 1.0) 232 | translate(-sx, -sy, 0) 233 | } 234 | mut c := b.colors.solid 235 | sgl.c4b(c.r, c.g, c.b, c.a) 236 | mut theta := f32(0) 237 | mut xx := f32(0) 238 | mut yy := f32(0) 239 | if b.fill.has(.solid) { 240 | sgl.begin_triangle_strip() 241 | for i := 0; i < steps + 1; i++ { 242 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 243 | xx = radius_x * math.cosf(theta) 244 | yy = radius_y * math.sinf(theta) 245 | sgl.v2f(xx + sx, yy + sy) 246 | sgl.v2f(sx, sy) 247 | } 248 | sgl.end() 249 | } 250 | if b.fill.has(.outline) { 251 | c = b.colors.outline 252 | sgl.c4b(c.r, c.g, c.b, c.a) 253 | if b.radius > 1 { 254 | for i := 0; i < steps; i++ { 255 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 256 | x1 := sx + (radius_x * math.cosf(theta)) 257 | y1 := sy + (radius_y * math.sinf(theta)) 258 | theta = 2.0 * f32(math.pi) * f32(i + 1) / f32(steps) 259 | x2 := sx + (radius_x * math.cosf(theta)) 260 | y2 := sy + (radius_y * math.sinf(theta)) 261 | theta = 2.0 * f32(math.pi) * f32(i + 2) / f32(steps) 262 | x3 := sx + (radius_x * math.cosf(theta)) 263 | y3 := sy + (radius_y * math.sinf(theta)) 264 | 265 | m12x, m12y := midpoint(x1, y1, x2, y2) 266 | m23x, m23y := midpoint(x2, y2, x3, y3) 267 | 268 | b.anchor(m12x, m12y, x2, y2, m23x, m23y) 269 | } 270 | } else { 271 | sgl.begin_line_strip() 272 | for i := 0; i < steps + 1; i++ { 273 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 274 | xx = radius_x * math.cosf(theta) 275 | yy = radius_y * math.sinf(theta) 276 | sgl.v2f(xx + sx, yy + sy) 277 | } 278 | sgl.end() 279 | } 280 | } 281 | if scale_factor != 1 { 282 | pop_matrix() 283 | } 284 | } 285 | 286 | @[inline] 287 | pub fn (b Shape) uniform_line_segment_poly(x f32, y f32, radius f32, steps u32) { 288 | scale_factor := b.scale * dpi_scale() 289 | sx := x * scale_factor 290 | sy := y * scale_factor 291 | 292 | if scale_factor != 1 { 293 | push_matrix() 294 | translate(sx, sy, 0) 295 | scale(scale_factor, scale_factor, 1.0) 296 | translate(-sx, -sy, 0) 297 | } 298 | mut c := b.colors.solid 299 | sgl.c4b(c.r, c.g, c.b, c.a) 300 | mut theta := f32(0) 301 | mut xx := f32(0) 302 | mut yy := f32(0) 303 | if b.fill.has(.solid) { 304 | sgl.begin_triangle_strip() 305 | for i := 0; i < steps + 1; i++ { 306 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 307 | xx = radius * math.cosf(theta) 308 | yy = radius * math.sinf(theta) 309 | sgl.v2f(xx + sx, yy + sy) 310 | sgl.v2f(sx, sy) 311 | } 312 | sgl.end() 313 | } 314 | if b.fill.has(.outline) { 315 | c = b.colors.outline 316 | sgl.c4b(c.r, c.g, c.b, c.a) 317 | if b.radius > 1 || scale_factor != 1 { 318 | sgl.begin_triangle_strip() 319 | for i := 0; i < steps; i++ { 320 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 321 | mut x1 := ((radius + b.radius) * math.cosf(theta)) 322 | mut y1 := ((radius + b.radius) * math.sinf(theta)) 323 | mut x2 := ((radius - b.radius) * math.cosf(theta)) 324 | mut y2 := ((radius - b.radius) * math.sinf(theta)) 325 | sgl.v2f(sx + x1, sy + y1) 326 | sgl.v2f(sx + x2, sy + y2) 327 | theta = 2.0 * f32(math.pi) * f32(i + 1) / f32(steps) 328 | mut nx1 := ((radius + b.radius) * math.cosf(theta)) 329 | mut ny1 := ((radius + b.radius) * math.sinf(theta)) 330 | mut nx2 := ((radius - b.radius) * math.cosf(theta)) 331 | mut ny2 := ((radius - b.radius) * math.sinf(theta)) 332 | sgl.v2f(sx + nx1, sy + ny1) 333 | sgl.v2f(sx + nx2, sy + ny2) 334 | } 335 | sgl.end() 336 | } else { 337 | sgl.begin_line_strip() 338 | for i := 0; i < steps + 1; i++ { 339 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 340 | xx = radius * math.cosf(theta) 341 | yy = radius * math.sinf(theta) 342 | sgl.v2f(xx + sx, yy + sy) 343 | } 344 | sgl.end() 345 | } 346 | } 347 | if scale_factor != 1 { 348 | pop_matrix() 349 | } 350 | } 351 | 352 | @[inline] 353 | pub fn (b Shape) line_segment_poly(x f32, y f32, radius_x f32, radius_y f32, steps u32) { 354 | scale_factor := b.scale * dpi_scale() 355 | sx := x * scale_factor 356 | sy := y * scale_factor 357 | if scale_factor != 1 { 358 | push_matrix() 359 | translate(sx, sy, 0) 360 | scale(scale_factor, scale_factor, 1.0) 361 | translate(-sx, -sy, 0) 362 | } 363 | mut c := b.colors.solid 364 | sgl.c4b(c.r, c.g, c.b, c.a) 365 | mut theta := f32(0) 366 | mut xx := f32(0) 367 | mut yy := f32(0) 368 | if b.fill.has(.solid) { 369 | sgl.begin_triangle_strip() 370 | for i := 0; i < steps + 1; i++ { 371 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 372 | xx = radius_x * math.cosf(theta) 373 | yy = radius_y * math.sinf(theta) 374 | sgl.v2f(xx + sx, yy + sy) 375 | sgl.v2f(sx, sy) 376 | } 377 | sgl.end() 378 | } 379 | if b.fill.has(.outline) { 380 | c = b.colors.outline 381 | sgl.c4b(c.r, c.g, c.b, c.a) 382 | if b.radius > 1 { 383 | sgl.begin_triangle_strip() 384 | for i := 0; i < steps; i++ { 385 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 386 | mut x1 := ((radius_x + b.radius) * math.cosf(theta)) 387 | mut y1 := ((radius_y + b.radius) * math.sinf(theta)) 388 | mut x2 := ((radius_x - b.radius) * math.cosf(theta)) 389 | mut y2 := ((radius_y - b.radius) * math.sinf(theta)) 390 | sgl.v2f(sx + x1, sy + y1) 391 | sgl.v2f(sx + x2, sy + y2) 392 | 393 | theta = 2.0 * f32(math.pi) * f32(i + 1) / f32(steps) 394 | mut nx1 := ((radius_x + b.radius) * math.cosf(theta)) 395 | mut ny1 := ((radius_y + b.radius) * math.sinf(theta)) 396 | mut nx2 := ((radius_x - b.radius) * math.cosf(theta)) 397 | mut ny2 := ((radius_y - b.radius) * math.sinf(theta)) 398 | sgl.v2f(sx + nx1, sy + ny1) 399 | sgl.v2f(sx + nx2, sy + ny2) 400 | } 401 | sgl.end() 402 | } else { 403 | sgl.begin_line_strip() 404 | for i := 0; i < steps + 1; i++ { 405 | theta = 2.0 * f32(math.pi) * f32(i) / f32(steps) 406 | xx = radius_x * math.cosf(theta) 407 | yy = radius_y * math.sinf(theta) 408 | sgl.v2f(xx + sx, yy + sy) 409 | } 410 | sgl.end() 411 | } 412 | } 413 | if scale_factor != 1 { 414 | pop_matrix() 415 | } 416 | } 417 | 418 | @[inline] 419 | pub fn (b Shape) circle(x f32, y f32, radius f32, steps u32) { 420 | b.uniform_line_segment_poly(x, y, radius, u32(rad_max * radius)) 421 | } 422 | 423 | @[inline] 424 | pub fn (b Shape) ellipse(x f32, y f32, radius_x f32, radius_y f32, steps u32) { 425 | b.line_segment_poly(x, y, radius_x, radius_y, u32(rad_max * math.max(radius_x, radius_y))) 426 | } 427 | 428 | @[direct_array_access; inline] 429 | pub fn (b Shape) convex_poly(points []f32, offset_x f32, offset_y f32) { 430 | b.poly(points, no_indicies, offset_x, offset_y) 431 | } 432 | 433 | @[direct_array_access; inline] 434 | pub fn (b Shape) poly(points []f32, holes []int, offset_x f32, offset_y f32) { 435 | scale_factor := b.scale * dpi_scale() 436 | off_x := offset_x * scale_factor 437 | off_y := offset_y * scale_factor 438 | if scale_factor != 1 { 439 | push_matrix() 440 | translate(off_x, off_y, 0) 441 | scale(scale_factor, scale_factor, 1.0) 442 | translate(-off_x, -off_y, 0) 443 | } 444 | 445 | dim := 2 446 | if b.fill.has(.solid) { 447 | color := b.colors.solid 448 | sgl.c4b(color.r, color.g, color.b, color.a) 449 | 450 | mut indicies := earcut.earcut(points, holes, dim) 451 | sgl.begin_triangles() 452 | for i := 0; i < indicies.len; i += 3 { 453 | x1 := off_x + points[indicies[i] * dim] 454 | y1 := off_y + points[indicies[i] * dim + 1] 455 | 456 | x2 := off_x + points[indicies[i + 1] * dim] 457 | y2 := off_y + points[indicies[i + 1] * dim + 1] 458 | 459 | x3 := off_x + points[indicies[i + 2] * dim] 460 | y3 := off_y + points[indicies[i + 2] * dim + 1] 461 | 462 | sgl.v2f(x1, y1) 463 | sgl.v2f(x2, y2) 464 | sgl.v2f(x3, y3) 465 | } 466 | sgl.end() 467 | } 468 | 469 | if b.fill.has(.outline) { 470 | mut hole_start := points.len 471 | if holes.len > 0 { 472 | hole_start = holes[0] * dim 473 | } 474 | mut x1 := off_x + points[hole_start - 2] 475 | mut y1 := off_y + points[hole_start - 1] 476 | mut x2 := off_x + points[0] 477 | mut y2 := off_y + points[1] 478 | mut x3 := f32(0) 479 | mut y3 := f32(0) 480 | c := b.colors.outline 481 | sgl.c4b(c.r, c.g, c.b, c.a) 482 | 483 | if b.radius > 1 { 484 | for i := 0; i < hole_start; i += dim { 485 | x1 = off_x + points[loop(i, 0, hole_start)] 486 | y1 = off_y + points[loop(i + 1, 0, hole_start)] 487 | x2 = off_x + points[loop(i + 2, 0, hole_start)] 488 | y2 = off_y + points[loop(i + 3, 0, hole_start)] 489 | x3 = off_x + points[loop(i + 4, 0, hole_start)] 490 | y3 = off_y + points[loop(i + 5, 0, hole_start)] 491 | 492 | m12x, m12y := midpoint(x1, y1, x2, y2) 493 | m23x, m23y := midpoint(x2, y2, x3, y3) 494 | 495 | b.anchor(m12x, m12y, x2, y2, m23x, m23y) 496 | } 497 | 498 | for i := 0; i < holes.len; i++ { 499 | from := holes[i] * dim 500 | mut to := points.len 501 | if i + 1 < holes.len { 502 | to = holes[i + 1] * dim 503 | } 504 | for j := from; j < to; j += dim { 505 | x1 = off_x + points[loop(j, from, to)] 506 | y1 = off_y + points[loop(j + 1, from, to)] 507 | x2 = off_x + points[loop(j + 2, from, to)] 508 | y2 = off_y + points[loop(j + 3, from, to)] 509 | x3 = off_x + points[loop(j + 4, from, to)] 510 | y3 = off_y + points[loop(j + 5, from, to)] 511 | 512 | m12x, m12y := midpoint(x1, y1, x2, y2) 513 | m23x, m23y := midpoint(x2, y2, x3, y3) 514 | 515 | b.anchor(m12x, m12y, x2, y2, m23x, m23y) 516 | } 517 | } 518 | } else { 519 | sgl.begin_line_strip() 520 | for i := 0; i < points.len && i < hole_start; i += dim { 521 | sgl.v2f(x1, y1) 522 | sgl.v2f(x2, y2) 523 | 524 | x1 = off_x + points[i] 525 | y1 = off_y + points[i + 1] 526 | x2 = off_x + points[i + 2] 527 | y2 = off_y + points[i + 3] 528 | } 529 | sgl.end() 530 | 531 | sgl.begin_line_strip() 532 | for i := 0; i < holes.len; i++ { 533 | from := holes[i] * dim 534 | mut to := points.len - 2 535 | if i + 1 < holes.len { 536 | to = holes[i + 1] * dim 537 | } 538 | for j := from; j < to; j += dim { 539 | x1 = off_x + points[j] 540 | y1 = off_y + points[j + 1] 541 | x2 = off_x + points[j + 2] 542 | y2 = off_y + points[j + 3] 543 | 544 | sgl.v2f(x1, y1) 545 | sgl.v2f(x2, y2) 546 | } 547 | 548 | sgl.v2f(x2, y2) 549 | x1 = off_x + points[from] 550 | y1 = off_y + points[from + 1] 551 | sgl.v2f(x1, y1) 552 | } 553 | sgl.end() 554 | } 555 | } 556 | 557 | if b.fill.has(.debug) { 558 | mut indicies := earcut.earcut(points, holes, dim) 559 | for i := 0; i < indicies.len; i += 3 { 560 | x1 := off_x + points[indicies[i] * dim] 561 | y1 := off_y + points[indicies[i] * dim + 1] 562 | 563 | x2 := off_x + points[indicies[i + 1] * dim] 564 | y2 := off_y + points[indicies[i + 1] * dim + 1] 565 | 566 | x3 := off_x + points[indicies[i + 2] * dim] 567 | y3 := off_y + points[indicies[i + 2] * dim + 1] 568 | 569 | debug_shape.triangle(x1, y1, x2, y2, x3, y3) 570 | } 571 | 572 | /* 573 | for i := 0; i < points.len; i += 2 { 574 | debug_shape.rectangle(offset_x+points[i]*scale-1, offset_y+points[i+1]*scale-1, 2, 2) 575 | }*/ 576 | } 577 | if scale_factor != 1 { 578 | pop_matrix() 579 | } 580 | } 581 | 582 | @[inline] 583 | pub fn (b Shape) arc(x f32, y f32, radius f32, start_angle_in_rad f32, angle_in_rad f32) { 584 | scale_factor := b.scale * dpi_scale() 585 | sx := x * scale_factor 586 | sy := y * scale_factor 587 | sair := loopf(start_angle_in_rad - (90 * deg2rad), 0, rad_max) 588 | if scale_factor != 1 { 589 | push_matrix() 590 | translate(sx, sy, 0) 591 | scale(scale_factor, scale_factor, 1.0) 592 | translate(-sx, -sy, 0) 593 | } 594 | steps := (sair - angle_in_rad) * radius 595 | segdiv := u32(steps) // 4 596 | if b.fill.has(.solid) { 597 | c := b.colors.solid 598 | sgl.c4b(c.r, c.g, c.b, c.a) 599 | sgl.begin_triangle_strip() 600 | plot.arc(sx, sy, radius, sair, angle_in_rad, segdiv, .solid) 601 | sgl.end() 602 | } 603 | if b.fill.has(.outline) { 604 | c := b.colors.outline 605 | sgl.c4b(c.r, c.g, c.b, c.a) 606 | if b.radius <= 1 { 607 | sgl.begin_line_strip() 608 | plot.arc(sx, sy, radius, sair, angle_in_rad, segdiv, .outline) 609 | sgl.end() 610 | } else { 611 | sgl.begin_triangle_strip() 612 | plot.arc_line(sx, sy, radius, b.radius, sair, angle_in_rad, segdiv) 613 | sgl.end() 614 | } 615 | } 616 | if scale_factor != 1 { 617 | pop_matrix() 618 | } 619 | } 620 | 621 | @[inline] 622 | pub fn (b Shape) rounded_rectangle(x f32, y f32, w f32, h f32, radius f32) { 623 | scale_factor := b.scale * dpi_scale() 624 | sx := x * scale_factor 625 | sy := y * scale_factor 626 | if scale_factor != 1 { 627 | push_matrix() 628 | translate(sx, sy, 0) 629 | scale(scale_factor, scale_factor, 1.0) 630 | translate(-sx, -sy, 0) 631 | } 632 | r := radius 633 | steps := rad_max * r 634 | 635 | if b.fill.has(.solid) { 636 | c := b.colors.solid 637 | sgl.c4b(c.r, c.g, c.b, c.a) 638 | 639 | segdiv := u32(steps / 4) 640 | 641 | sgl.begin_triangle_strip() 642 | // left top 643 | lx := sx + r 644 | ly := sy + r 645 | plot.arc(lx, ly, r, 180 * deg2rad, deg90rad, segdiv, .solid) 646 | 647 | // right top 648 | rx := sx + w - r 649 | ry := sy + r 650 | sgl.v2f(rx, ry - r) 651 | sgl.v2f(rx, ry) 652 | plot.arc(rx, ry, r, 270 * deg2rad, deg90rad, segdiv, .solid) 653 | 654 | // right bottom 655 | rbx := rx 656 | rby := sy + h - r 657 | sgl.v2f(rbx + r, rby) 658 | sgl.v2f(rbx, rby) 659 | plot.arc(rbx, rby, r, 0, deg90rad, segdiv, .solid) 660 | 661 | // left bottom 662 | lbx := lx 663 | lby := sy + h - r 664 | sgl.v2f(lbx, lby + r) 665 | sgl.v2f(lbx, lby) 666 | plot.arc(lbx, lby, r, deg90rad, deg90rad, segdiv, .solid) 667 | 668 | sgl.v2f(lx - r, ly) 669 | sgl.v2f(lx, ly) 670 | 671 | sgl.end() 672 | 673 | sgl.begin_quads() 674 | sgl.v2f(lx, ly) 675 | sgl.v2f(rx, ry) 676 | sgl.v2f(rbx, rby) 677 | sgl.v2f(lbx, lby) 678 | sgl.end() 679 | } 680 | 681 | if b.fill.has(.outline) { 682 | c := b.colors.outline 683 | sgl.c4b(c.r, c.g, c.b, c.a) 684 | 685 | segdiv := u32(steps / 4) 686 | 687 | if b.radius <= 1 { 688 | // left top 689 | sgl.begin_line_strip() 690 | lx := sx + r 691 | ly := sy + r 692 | plot.arc(lx, ly, r, 180 * deg2rad, deg90rad, segdiv, .outline) 693 | rx := sx + w - r 694 | ry := sy + r 695 | // right top 696 | plot.arc(rx, ry, r, 270 * deg2rad, deg90rad, segdiv, .outline) 697 | rbx := rx 698 | rby := sy + h - r 699 | // right bottom 700 | plot.arc(rbx, rby, r, 0, deg90rad, segdiv, .outline) 701 | // left bottom 702 | lbx := lx 703 | lby := sy + h - r 704 | plot.arc(lbx, lby, r, deg90rad, deg90rad, segdiv, .outline) 705 | 706 | sgl.v2f(lx - r, ly) 707 | sgl.end() 708 | } else { 709 | sgl.begin_triangle_strip() 710 | // left top 711 | lx := sx + r 712 | ly := sy + r 713 | plot.arc_line(lx, ly, r, b.radius, 180 * deg2rad, deg90rad, segdiv) 714 | 715 | // right top 716 | rx := sx + w - r 717 | ry := sy + r 718 | sgl.v2f(rx, ry - (r + b.radius)) 719 | sgl.v2f(rx, ry - (r - b.radius)) 720 | plot.arc_line(rx, ry, r, b.radius, 270 * deg2rad, deg90rad, segdiv) 721 | 722 | // right bottom 723 | rbx := rx 724 | rby := sy + h - r 725 | sgl.v2f(rbx + (r + b.radius), rby) 726 | sgl.v2f(rbx + (r - b.radius), rby) 727 | plot.arc_line(rbx, rby, r, b.radius, 0, deg90rad, segdiv) 728 | 729 | // left bottom 730 | lbx := lx 731 | lby := sy + h - r 732 | sgl.v2f(lbx, lby + (r + b.radius)) 733 | sgl.v2f(lbx, lby + (r - b.radius)) 734 | plot.arc_line(lbx, lby, r, b.radius, deg90rad, deg90rad, segdiv) 735 | 736 | sgl.v2f(lx - (r + b.radius), ly) 737 | sgl.v2f(lx - (r - b.radius), ly) 738 | 739 | sgl.end() 740 | } 741 | } 742 | 743 | if scale_factor != 1 { 744 | pop_matrix() 745 | } 746 | } 747 | 748 | @[inline] 749 | pub fn (b Shape) triangle(x1 f32, y1 f32, x2 f32, y2 f32, x3 f32, y3 f32) { 750 | scale_factor := b.scale * dpi_scale() 751 | x1_ := x1 * scale_factor 752 | y1_ := y1 * scale_factor 753 | dx := x1 - x1_ 754 | dy := y1 - y1_ 755 | x2_ := x2 - dx 756 | y2_ := y2 - dy 757 | x3_ := x3 - dx 758 | y3_ := y3 - dy 759 | 760 | if scale_factor != 1 { 761 | push_matrix() 762 | translate(x1_, y1_, 0) 763 | scale(scale_factor, scale_factor, 1.0) 764 | translate(-x1_, -y1_, 0) 765 | } 766 | mut color := b.colors.solid 767 | sgl.c4b(color.r, color.g, color.b, color.a) 768 | 769 | if b.fill.has(.solid) { 770 | sgl.begin_triangles() 771 | sgl.v2f(x1_, y1_) 772 | sgl.v2f(x2_, y2_) 773 | sgl.v2f(x3_, y3_) 774 | sgl.end() 775 | } 776 | 777 | if b.fill.has(.outline) { 778 | if b.radius > 1 { 779 | m12x, m12y := midpoint(x1_, y1_, x2_, y2_) 780 | m23x, m23y := midpoint(x2_, y2_, x3_, y3_) 781 | m31x, m31y := midpoint(x3_, y3_, x1_, y1_) 782 | b.anchor(m12x, m12y, x2_, y2_, m23x, m23y) 783 | b.anchor(m23x, m23y, x3_, y3_, m31x, m31y) 784 | b.anchor(m31x, m31y, x1_, y1_, m12x, m12y) 785 | } else { 786 | color = b.colors.outline 787 | sgl.c4b(color.r, color.g, color.b, color.a) 788 | 789 | sgl.begin_line_strip() 790 | 791 | sgl.v2f(x1_, y1_) 792 | sgl.v2f(x2_, y2_) 793 | 794 | sgl.v2f(x2_, y2_) 795 | sgl.v2f(x3_, y3_) 796 | 797 | sgl.v2f(x3_, y3_) 798 | sgl.v2f(x1_, y1_) 799 | 800 | sgl.end() 801 | } 802 | } 803 | if scale_factor != 1 { 804 | pop_matrix() 805 | } 806 | } 807 | 808 | @[inline] 809 | pub fn (b Shape) image(x f32, y f32, w f32, h f32, path string) { 810 | img := load_image(path: path) or { return } 811 | if !img.ready { 812 | return 813 | } 814 | 815 | scale_factor := b.scale * dpi_scale() 816 | sx := x * scale_factor 817 | sy := y * scale_factor 818 | if scale_factor != 1 { 819 | push_matrix() 820 | translate(sx, sy, 0) 821 | scale(scale_factor, scale_factor, 1.0) 822 | translate(-sx, -sy, 0) 823 | } 824 | 825 | u0 := f32(0.0) 826 | v0 := f32(0.0) 827 | u1 := f32(1.0) 828 | v1 := f32(1.0) 829 | x0 := f32(0) 830 | y0 := f32(0) 831 | x1 := f32(w) 832 | y1 := f32(h) 833 | 834 | push_matrix() 835 | 836 | sgl.enable_texture() 837 | sgl.texture(img.sg_image, img.sg_sampler) 838 | sgl.translate(f32(sx), f32(sy), 0) 839 | // sgl.c4b(p.color.r, p.color.g, p.color.b, p.color.a) 840 | sgl.c4b(255, 255, 255, 255) 841 | 842 | sgl.begin_quads() 843 | sgl.v2f_t2f(x0, y0, u0, v0) 844 | sgl.v2f_t2f(x1, y0, u1, v0) 845 | sgl.v2f_t2f(x1, y1, u1, v1) 846 | sgl.v2f_t2f(x0, y1, u0, v1) 847 | sgl.end() 848 | 849 | sgl.translate(-f32(sx), -f32(sy), 0) 850 | sgl.disable_texture() 851 | 852 | pop_matrix() 853 | 854 | if scale_factor != 1 { 855 | pop_matrix() 856 | } 857 | } 858 | 859 | // Utility functions for sgldraw.ng an anchor point 860 | 861 | @[inline] 862 | fn (b Shape) anchor(x1 f32, y1 f32, x2 f32, y2 f32, x3 f32, y3 f32) { 863 | // Original author Chris H.F. Tsang / CPOL License 864 | // https://www.codeproject.com/Articles/226569/Drawing-polylines-by-tessellation 865 | // http://artgrammer.blogspot.com/search/label/opengl 866 | c := b.colors.outline 867 | sgl.c4b(c.r, c.g, c.b, c.a) 868 | radius := b.radius 869 | if radius == 1 { 870 | sgl.begin_line_strip() 871 | sgl.v2f(x1, y1) 872 | sgl.v2f(x2, y2) 873 | sgl.end() 874 | return 875 | } 876 | 877 | mut t0_x := x2 - x1 878 | mut t0_y := y2 - y1 879 | 880 | mut t2_x := x3 - x2 881 | mut t2_y := y3 - y2 882 | 883 | t0_x, t0_y = perpendicular(t0_x, t0_y) 884 | t2_x, t2_y = perpendicular(t2_x, t2_y) 885 | 886 | flip := signed_area(x1, y1, x2, y2, x3, y3) > 0 887 | if flip { 888 | t0_x = -t0_x 889 | t0_y = -t0_y 890 | 891 | t2_x = -t2_x 892 | t2_y = -t2_y 893 | } 894 | 895 | t0_x, t0_y = normalize(t0_x, t0_y) 896 | t2_x, t2_y = normalize(t2_x, t2_y) 897 | t0_x *= radius 898 | t0_y *= radius 899 | 900 | t2_x *= radius 901 | t2_y *= radius 902 | 903 | ip_x, ip_y, _ := intersect(t0_x + x1, t0_y + y1, t0_x + x2, t0_y + y2, t2_x + x3, 904 | t2_y + y3, t2_x + x2, t2_y + y2) 905 | 906 | vp_x := ip_x 907 | vp_y := ip_y 908 | 909 | vpp_x, vpp_y := rotate_point(x2, y2, vp_x, vp_y, 180 * deg2rad) 910 | 911 | /* 912 | sgl.c3b(155,0,0) 913 | if flip { 914 | raw.rectangle(vp_x-2,vp_y-2,4,4) 915 | } else { 916 | raw.rectangle(vpp_x-2,vpp_y-2,4,4) 917 | } 918 | sgl.c4b(c.r, c.g, c.b, c.a) 919 | */ 920 | 921 | t0_x += x1 922 | t0_y += y1 923 | 924 | at_x := t0_x - x1 + x2 925 | at_y := t0_y - y1 + y2 926 | 927 | t2_x += x3 928 | t2_y += y3 929 | 930 | bt_x := t2_x - x3 + x2 931 | bt_y := t2_y - y3 + y2 932 | 933 | t0r_x, t0r_y := rotate_point(x1, y1, t0_x, t0_y, 180 * deg2rad) 934 | t2r_x, t2r_y := rotate_point(x3, y3, t2_x, t2_y, 180 * deg2rad) 935 | 936 | // println('T0: $t0_x, $t0_y vP: $vp_x, $vp_y -vP: $vpp_x, $vpp_y') 937 | // sgl.c4b(c.r, c.g, c.b, 40) 938 | 939 | if b.connect.has(.miter) { 940 | sgl.begin_triangles() 941 | sgl.v2f(t0_x, t0_y) 942 | sgl.v2f(vp_x, vp_y) 943 | sgl.v2f(vpp_x, vpp_y) 944 | 945 | sgl.v2f(vpp_x, vpp_y) 946 | sgl.v2f(t0r_x, t0r_y) 947 | sgl.v2f(t0_x, t0_y) 948 | 949 | sgl.v2f(vp_x, vp_y) 950 | sgl.v2f(vpp_x, vpp_y) 951 | sgl.v2f(t2_x, t2_y) 952 | 953 | sgl.v2f(vpp_x, vpp_y) 954 | sgl.v2f(t2r_x, t2r_y) 955 | sgl.v2f(t2_x, t2_y) 956 | sgl.end() 957 | } else if b.connect.has(.bevel) { 958 | sgl.begin_triangles() 959 | sgl.v2f(t0_x, t0_y) 960 | sgl.v2f(at_x, at_y) 961 | sgl.v2f(vpp_x, vpp_y) 962 | 963 | sgl.v2f(vpp_x, vpp_y) 964 | sgl.v2f(t0r_x, t0r_y) 965 | sgl.v2f(t0_x, t0_y) 966 | 967 | sgl.v2f(at_x, at_y) 968 | sgl.v2f(bt_x, bt_y) 969 | sgl.v2f(vpp_x, vpp_y) 970 | 971 | sgl.v2f(vpp_x, vpp_y) 972 | sgl.v2f(bt_x, bt_y) 973 | sgl.v2f(t2_x, t2_y) 974 | 975 | sgl.v2f(vpp_x, vpp_y) 976 | sgl.v2f(t2_x, t2_y) 977 | sgl.v2f(t2r_x, t2r_y) 978 | sgl.end() 979 | 980 | /* 981 | // NOTE Adding this will also end up in .miter 982 | sgl.v2f(at_x, at_y) 983 | sgl.v2f(vp_x, vp_y) 984 | sgl.v2f(bt_x, bt_y) 985 | */ 986 | } else { 987 | // .round 988 | // arc / rounded corners 989 | mut start_angle := line_segment_angle(vpp_x, vpp_y, at_x, at_y) 990 | mut arc_angle := line_segment_angle(vpp_x, vpp_y, bt_x, bt_y) 991 | arc_angle -= start_angle 992 | 993 | if arc_angle < 0 { 994 | if flip { 995 | arc_angle = arc_angle + 2.0 * math.pi 996 | } 997 | } 998 | sgl.begin_triangle_strip() 999 | plot.arc(vpp_x, vpp_y, line_segment_length(vpp_x, vpp_y, at_x, at_y), start_angle, 1000 | arc_angle, u32(18), .solid) 1001 | sgl.end() 1002 | 1003 | sgl.begin_triangles() 1004 | 1005 | sgl.v2f(t0_x, t0_y) 1006 | sgl.v2f(at_x, at_y) 1007 | sgl.v2f(vpp_x, vpp_y) 1008 | 1009 | sgl.v2f(vpp_x, vpp_y) 1010 | sgl.v2f(t0r_x, t0r_y) 1011 | sgl.v2f(t0_x, t0_y) 1012 | 1013 | // TODO arc_points 1014 | // sgl.v2f(at_x, at_y) 1015 | // sgl.v2f(bt_x, bt_y) 1016 | // sgl.v2f(vpp_x, vpp_y) 1017 | 1018 | sgl.v2f(vpp_x, vpp_y) 1019 | sgl.v2f(bt_x, bt_y) 1020 | sgl.v2f(t2_x, t2_y) 1021 | 1022 | sgl.v2f(vpp_x, vpp_y) 1023 | sgl.v2f(t2_x, t2_y) 1024 | sgl.v2f(t2r_x, t2r_y) 1025 | 1026 | sgl.end() 1027 | } 1028 | 1029 | // Expected base lines 1030 | /* 1031 | sgl.c4b(0, 255, 0, 90) 1032 | line(x1, y1, x2, y2) 1033 | line(x2, y2, x3, y3) 1034 | */ 1035 | } 1036 | 1037 | @[inline] 1038 | fn line_segment_angle(x1 f32, y1 f32, x2 f32, y2 f32) f32 { 1039 | return math.pi + f32(math.atan2(y1 - y2, x1 - x2)) 1040 | } 1041 | 1042 | @[inline] 1043 | fn line_segment_length(x1 f32, y1 f32, x2 f32, y2 f32) f32 { 1044 | return math.sqrtf(((y2 - y1) * (y2 - y1)) + ((x2 - x1) * (x2 - x1))) 1045 | } 1046 | 1047 | @[inline] 1048 | fn rotate_point(cx f32, cy f32, px f32, py f32, angle_in_radians f32) (f32, f32) { 1049 | s := math.sinf(angle_in_radians) 1050 | c := math.cosf(angle_in_radians) 1051 | mut npx := px 1052 | mut npy := py 1053 | // translate point back to origin: 1054 | npx -= cx 1055 | npy -= cy 1056 | // rotate point 1057 | xnew := npx * c - npy * s 1058 | ynew := npx * s + npy * c 1059 | // translate point back: 1060 | npx = xnew + cx 1061 | npy = ynew + cy 1062 | return npx, npy 1063 | } 1064 | 1065 | @[inline] 1066 | fn midpoint(x1 f32, y1 f32, x2 f32, y2 f32) (f32, f32) { 1067 | return (x1 + x2) / 2, (y1 + y2) / 2 1068 | } 1069 | 1070 | @[inline] 1071 | fn loop(value int, from int, to int) int { 1072 | range := to - from 1073 | offset_value := value - from // value relative to 0 1074 | // + `from` to reset back to start of original range 1075 | return (offset_value - int((math.floor(offset_value / range) * range))) + from 1076 | } 1077 | 1078 | @[inline] 1079 | fn loopf(value f32, from f32, to f32) f32 { 1080 | range := to - from 1081 | offset_value := value - from // value relative to 0 1082 | // + `from` to reset back to start of original range 1083 | return (offset_value - f32((math.floor(offset_value / range) * range))) + from 1084 | } 1085 | 1086 | // perpendicular anti-clockwise 90 degrees 1087 | @[inline] 1088 | fn perpendicular(x f32, y f32) (f32, f32) { 1089 | return -y, x 1090 | } 1091 | 1092 | @[inline] 1093 | fn signed_area(x1 f32, y1 f32, x2 f32, y2 f32, x3 f32, y3 f32) f32 { 1094 | return (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) 1095 | } 1096 | 1097 | @[inline] 1098 | fn normalize(x f32, y f32) (f32, f32) { 1099 | w := math.sqrtf(x * x + y * y) 1100 | return x / w, y / w 1101 | } 1102 | 1103 | // x1, y1, x2, y2 = line 1 1104 | // x3, y3, x4, y4 = line 2 1105 | // output: (output point x,y, intersection type) 1106 | @[inline] 1107 | fn intersect(x1 f32, y1 f32, x2 f32, y2 f32, x3 f32, y3 f32, x4 f32, y4 f32) (f32, f32, int) { 1108 | // Determine the intersection point of two line steps 1109 | // http://paulbourke.net/geometry/lineline2d/ 1110 | mut mua, mut mub := f32(0), f32(0) 1111 | mut denom, mut numera, mut numerb := f32(0), f32(0), f32(0) 1112 | eps := f32(0.000000000001) 1113 | 1114 | denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1) 1115 | numera = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3) 1116 | numerb = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3) 1117 | 1118 | if (-eps < numera && numera < eps) && (-eps < numerb && numerb < eps) 1119 | && (-eps < denom && denom < eps) { 1120 | return (x1 + x2) * 0.5, (y1 + y2) * 0.5, 2 // meaning the lines coincide 1121 | } 1122 | 1123 | if -eps < denom && denom < eps { 1124 | return 0, 0, 0 // meaning lines are parallel 1125 | } 1126 | 1127 | mua = numera / denom 1128 | mub = numerb / denom 1129 | px := x1 + mua * (x2 - x1) 1130 | py := y1 + mua * (y2 - y1) 1131 | out1 := mua < 0 || mua > 1 1132 | out2 := mub < 0 || mub > 1 1133 | 1134 | if int(out1) & int(out2) == 0 { 1135 | return px, py, 5 // the intersection lies outside both steps 1136 | } else if out1 { 1137 | return px, py, 3 // the intersection lies outside segment 1 1138 | } else if out2 { 1139 | return px, py, 4 // the intersection lies outside segment 2 1140 | } else { 1141 | return px, py, 1 // the intersection lies inside both steps 1142 | } 1143 | } 1144 | 1145 | fn gen_arc_points(start_angle f32, end_angle f32, radius f32, steps u32) []f32 { 1146 | mut arc_points := []f32{len: int(steps) * 2} 1147 | mut angle := start_angle 1148 | arc_length := end_angle - start_angle 1149 | for i := 0; i <= steps; i++ { 1150 | x := math.sinf(angle) * radius 1151 | y := math.cosf(angle) * radius 1152 | 1153 | arc_points << x 1154 | arc_points << y 1155 | 1156 | angle += arc_length / steps 1157 | } 1158 | return arc_points 1159 | } 1160 | --------------------------------------------------------------------------------