├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── align.go ├── analogueclock └── aclock.go ├── bartext └── bartext.go ├── basecontrol.go ├── controli.go ├── example ├── DejaVuSerif.ttf ├── NanumGothic.ttf ├── clock.go ├── example.go ├── hangulscreenshot.png ├── nanumfontlicense.txt └── screenshot.png ├── font.go ├── overlayfilter.go ├── sdlevent.go ├── textbox └── textbox.go ├── util.go └── window.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | *.test 24 | *.prof 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-sdlgui 2 | SDL2 base GUI package for go 3 | 4 | Based on veandco's sdl2 binding 5 | 6 | It's very early stage and has very little UI controls but usable. 7 | 8 | (separated from goguelike client ) 9 | 10 | See example directory for sample usage. 11 | 12 | # Requirements 13 | 14 | changed to use forked version of 15 | 16 | https://github.com/veandco/go-sdl2 17 | 18 | use 19 | 20 | "github.com/kasworld/go-sdl2/sdl" 21 | 22 | ## korean discription 23 | 24 | http://kasw.blogspot.kr/2015/02/go-gui.html 25 | 26 | ## Requirements2 27 | 28 | "github.com/kasworld/idgen" 29 | "github.com/kasworld/log" 30 | "github.com/kasworld/quadtree" 31 | "github.com/kasworld/rect" 32 | "github.com/kasworld/htmlcolors" 33 | 34 | ## Requirements for example 35 | 36 | "github.com/kasworld/actionstat" 37 | "github.com/kasworld/htmlcolors" 38 | "github.com/kasworld/log" 39 | 40 | "github.com/kasworld/go-sdlgui" 41 | 42 | ![analogueclock screenshot] 43 | (https://github.com/kasworld/go-sdlgui/blob/master/example/screenshot.png) 44 | 45 | ![analogueclock screenshot] 46 | (https://github.com/kasworld/go-sdlgui/blob/master/example/hangulscreenshot.png) 47 | -------------------------------------------------------------------------------- /align.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "github.com/kasworld/go-sdl2/sdl" 16 | "github.com/kasworld/rect" 17 | ) 18 | 19 | const ( 20 | Align_Center = uint8(iota) 21 | Align_Up 22 | Align_UpRight 23 | Align_Right 24 | Align_DownRight 25 | Align_Down 26 | Align_DownLeft 27 | Align_Left 28 | Align_UpLeft 29 | ) 30 | 31 | var AlignVt = [...][2]int{ 32 | Align_Center: [2]int{0, 0}, 33 | Align_Up: [2]int{0, -1}, 34 | Align_UpRight: [2]int{1, -1}, 35 | Align_Right: [2]int{1, 0}, 36 | Align_DownRight: [2]int{1, 1}, 37 | Align_Down: [2]int{0, 1}, 38 | Align_DownLeft: [2]int{-1, 1}, 39 | Align_Left: [2]int{-1, 0}, 40 | Align_UpLeft: [2]int{-1, -1}, 41 | } 42 | 43 | // rect inner align 44 | func SdlInRectAlign(dst rect.Rect, src sdl.Rect, aligndir uint8) sdl.Rect { 45 | rtn := src 46 | vt := AlignVt[aligndir] 47 | switch vt[0] { 48 | case -1: 49 | rtn.X = int32(dst.X) 50 | case 0: 51 | rtn.X = int32(dst.X + dst.W/2 - int(src.W)/2) 52 | case 1: 53 | rtn.X = int32(dst.X + dst.W - int(src.W)) 54 | } 55 | switch vt[1] { 56 | case -1: 57 | rtn.Y = int32(dst.Y) 58 | case 0: 59 | rtn.Y = int32(dst.Y + dst.H/2 - int(src.H/2)) 60 | case 1: 61 | rtn.Y = int32(dst.Y + dst.H - int(src.H)) 62 | } 63 | return rtn 64 | } 65 | 66 | // point base align 67 | func SdlDestRect(src sdl.Rect, x, y int32, aligndir uint8) sdl.Rect { 68 | rtn := sdl.Rect{x, y, src.W, src.H} 69 | vt := AlignVt[aligndir] 70 | rtn.X = x + src.W/2*(int32(vt[0])-1) 71 | rtn.Y = y + src.H/2*(int32(vt[1])-1) 72 | return rtn 73 | } 74 | -------------------------------------------------------------------------------- /analogueclock/aclock.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package analogueclock 13 | 14 | import ( 15 | "math" 16 | "time" 17 | 18 | "github.com/kasworld/go-sdlgui" 19 | "github.com/kasworld/htmlcolors" 20 | ) 21 | 22 | const ( 23 | CO_bg = uint8(iota) 24 | CO_face 25 | CO_daial 26 | CO_hhand 27 | CO_mhand 28 | CO_shand 29 | CO_End 30 | ) 31 | 32 | type Clock struct { 33 | *sdlgui.Control 34 | colors [CO_End]htmlcolors.RGBA 35 | t time.Time 36 | } 37 | 38 | func New(x, y, z int, wx, wy int) *Clock { 39 | c := Clock{ 40 | sdlgui.NewControl(x, y, z, wx, wy), 41 | [CO_End]htmlcolors.RGBA{ 42 | htmlcolors.Black.ToRGBA(), 43 | htmlcolors.Gray.ToRGBA(), 44 | htmlcolors.White.ToRGBA(), 45 | htmlcolors.Green.ToRGBA(), 46 | htmlcolors.Blue.ToRGBA(), 47 | htmlcolors.Red.ToRGBA(), 48 | }, 49 | time.Now(), 50 | } 51 | c.BorderType = 0 52 | return &c 53 | } 54 | 55 | func (tc *Clock) SetColor(n int, co htmlcolors.RGBA) { 56 | if co == tc.colors[n] { 57 | return 58 | } 59 | tc.ContentsChanged = true 60 | tc.colors[n] = co 61 | } 62 | 63 | func (tc *Clock) SetTime(t time.Time) { 64 | if t == tc.t { 65 | return 66 | } 67 | tc.ContentsChanged = true 68 | tc.t = t 69 | } 70 | 71 | func (tc *Clock) drawFace() { 72 | tc.Rend.SetDrawColor(tc.colors[CO_face][0], tc.colors[CO_face][1], tc.colors[CO_face][2], tc.colors[CO_face][3]) 73 | c := tc.GetRect().Center() 74 | rx := tc.GetRect().SizeVector()[0] / 2 75 | ry := tc.GetRect().SizeVector()[1] / 2 76 | rate := float64(ry) / float64(rx) 77 | for x := -rx; x < rx; x++ { 78 | theta := math.Acos(float64(x) / float64(rx)) 79 | y := int(float64(x) * math.Tan(theta) * rate) 80 | if x == 0 { 81 | y = ry 82 | } 83 | tc.Rend.DrawLine(c[0]+x, c[1]-y, c[0]+x, c[1]+y) 84 | } 85 | } 86 | 87 | func (tc *Clock) getFacePos(angle float64, l float64) (int, int) { 88 | angle -= 90 89 | xc, yc := tc.W/2, tc.H/2 90 | x := xc + int(math.Cos(angle/180*math.Pi)*float64(xc)*l) 91 | y := yc + int(math.Sin(angle/180*math.Pi)*float64(yc)*l) 92 | return x, y 93 | } 94 | 95 | func (tc *Clock) drawHand(co htmlcolors.RGBA, angle float64, l float64) { 96 | // x1, y1 := tc.W/2, tc.H/2 97 | x1, y1 := tc.getFacePos(angle, -l/5) 98 | x2, y2 := tc.getFacePos(angle, l) 99 | tc.Rend.SetDrawColor(co[0], co[1], co[2], co[3]) 100 | tc.Rend.DrawLine(x1, y1, x2, y2) 101 | } 102 | 103 | func (tc *Clock) drawDialLine(co htmlcolors.RGBA, angle float64, s, e float64) { 104 | x1, y1 := tc.getFacePos(angle, s) 105 | x2, y2 := tc.getFacePos(angle, e) 106 | tc.Rend.SetDrawColor(co[0], co[1], co[2], co[3]) 107 | tc.Rend.DrawLine(x1, y1, x2, y2) 108 | } 109 | 110 | func (tc *Clock) drawDials() { 111 | for a := 0.0; a < 360; a += 6 { 112 | tc.drawDialLine(tc.colors[CO_daial], a, 0.95, 0.99) 113 | } 114 | for a := 0.0; a < 360; a += 6 * 5 { 115 | tc.drawDialLine(tc.colors[CO_daial], a, 0.90, 0.99) 116 | } 117 | } 118 | 119 | func (tc *Clock) time2Angle() (float64, float64, float64) { 120 | ms := float64(tc.t.Nanosecond()/1000000) / 1000 121 | s := (float64(tc.t.Second()) + ms) 122 | m := (float64(tc.t.Minute()) + s/60) 123 | h := (float64(tc.t.Hour()%12) + m/60) 124 | 125 | sa := s / 60 * 360 126 | ma := m / 60 * 360 127 | ha := h / 12 * 360 128 | return ha, ma, sa 129 | } 130 | 131 | func (tc *Clock) DrawSurface() { 132 | if !tc.ContentsChanged { 133 | return 134 | } 135 | tc.ContentsChanged = false 136 | 137 | tc.Rend.SetDrawColor(tc.colors[CO_bg][0], tc.colors[CO_bg][1], tc.colors[CO_bg][2], tc.colors[CO_bg][3]) 138 | tc.Rend.Clear() 139 | 140 | h, m, s := tc.time2Angle() 141 | tc.drawFace() 142 | tc.drawDials() 143 | tc.drawHand(tc.colors[CO_hhand], h, 0.60) 144 | tc.drawHand(tc.colors[CO_mhand], m, 0.75) 145 | tc.drawHand(tc.colors[CO_shand], s, 0.90) 146 | 147 | tc.Rend.Present() 148 | tc.Win.AddUpdateControl(tc) 149 | } 150 | -------------------------------------------------------------------------------- /bartext/bartext.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package bartext 13 | 14 | import ( 15 | "fmt" 16 | 17 | "github.com/kasworld/go-sdl2/sdl" 18 | "github.com/kasworld/go-sdlgui" 19 | "github.com/kasworld/htmlcolors" 20 | ) 21 | 22 | type TextControl struct { 23 | *sdlgui.Control 24 | text string 25 | font *sdlgui.Font 26 | bg htmlcolors.RGBA 27 | fg htmlcolors.RGBA 28 | bar float64 29 | aligndir uint8 30 | } 31 | 32 | func New(x, y, z int, wx, wy int, s string, font *sdlgui.Font) *TextControl { 33 | tc := TextControl{ 34 | sdlgui.NewControl(x, y, z, wx, wy), 35 | s, 36 | font, 37 | htmlcolors.Black.ToRGBA(), 38 | htmlcolors.White.ToRGBA(), 39 | 1.0, 40 | sdlgui.Align_Left, 41 | } 42 | tc.BorderSize = 2 43 | tc.BorderType = 1 44 | return &tc 45 | } 46 | 47 | func (tc *TextControl) DrawSurface() { 48 | if !tc.ContentsChanged { 49 | return 50 | } 51 | tc.ContentsChanged = false 52 | 53 | tc.Rend.SetDrawColor(127, 127, 127, 255) 54 | tc.Rend.Clear() 55 | tc.Rend.SetDrawColor(tc.bg[0], tc.bg[1], tc.bg[2], tc.bg[3]) 56 | barrect := sdl.Rect{ 57 | 0, 0, 58 | int32(float64(tc.W) * tc.bar), int32(tc.H), 59 | } 60 | tc.Rend.FillRect(&barrect) 61 | 62 | surface, srcRect := tc.font.MakeSurface(tc.fg, tc.text) 63 | defer surface.Free() 64 | 65 | torect := tc.GetClientConnRect().ShrinkSym(int(tc.BorderSize)) 66 | if srcRect.W < int32(torect.W) { 67 | dstRect := sdlgui.SdlInRectAlign(torect, srcRect, tc.aligndir) 68 | surface.Blit(&srcRect, tc.Suf, &dstRect) 69 | } else { 70 | tsrcRect := srcRect 71 | tsrcRect.W = int32(tc.W) 72 | dstRect := sdlgui.SdlInRectAlign(torect, tsrcRect, tc.aligndir) 73 | surface.BlitScaled(&srcRect, tc.Suf, &dstRect) 74 | } 75 | 76 | tc.Rend.Present() 77 | tc.Win.AddUpdateControl(tc) 78 | } 79 | func (tc *TextControl) MouseOver(x, y int, btnstate uint32) { 80 | } 81 | func (tc *TextControl) MouseButton(x, y int, btnnum uint8, btnstate uint8) { 82 | // log.Info("%v btn %v %v ", tc.GetID(), btnnum, btnstate) 83 | tc.bg, tc.fg = tc.fg, tc.bg 84 | tc.ContentsChanged = true 85 | tc.DrawSurface() 86 | } 87 | func (tc *TextControl) SetBG(bg htmlcolors.RGBA) { 88 | if bg == tc.bg { 89 | return 90 | } 91 | tc.ContentsChanged = true 92 | tc.bg = bg 93 | } 94 | func (tc *TextControl) SetFG(fg htmlcolors.RGBA) { 95 | if fg == tc.fg { 96 | return 97 | } 98 | tc.ContentsChanged = true 99 | tc.fg = fg 100 | } 101 | func (tc *TextControl) SetFGBG(fg, bg htmlcolors.RGBA) { 102 | tc.SetFG(fg) 103 | tc.SetBG(bg) 104 | } 105 | func (tc *TextControl) SetText(format string, a ...interface{}) { 106 | text := fmt.Sprintf(format, a...) 107 | if text == tc.text { 108 | return 109 | } 110 | tc.ContentsChanged = true 111 | tc.text = text 112 | } 113 | func (tc *TextControl) SetBar(bar float64) { 114 | if bar == tc.bar { 115 | return 116 | } 117 | tc.ContentsChanged = true 118 | tc.bar = bar 119 | } 120 | func (tc *TextControl) SetFGBGText(fg, bg htmlcolors.RGBA, format string, a ...interface{}) { 121 | tc.SetFG(fg) 122 | tc.SetBG(bg) 123 | tc.SetText(format, a...) 124 | } 125 | func (tc *TextControl) SetBarText(bar float64, format string, a ...interface{}) { 126 | tc.SetBar(bar) 127 | tc.SetText(format, a...) 128 | } 129 | func (tc *TextControl) SetAlign(align uint8) { 130 | if align == tc.aligndir { 131 | return 132 | } 133 | tc.aligndir = align 134 | tc.ContentsChanged = true 135 | } 136 | -------------------------------------------------------------------------------- /basecontrol.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "fmt" 16 | 17 | "github.com/kasworld/go-sdl2/sdl" 18 | "github.com/kasworld/idgen" 19 | "github.com/kasworld/rect" 20 | ) 21 | 22 | const ( 23 | Rmask = 0x000000ff 24 | Gmask = 0x0000ff00 25 | Bmask = 0x00ff0000 26 | Amask = 0xff000000 27 | ) 28 | 29 | // QuadTreeObjI 30 | func (c *Control) GetRect() rect.Rect { 31 | return rect.Rect{ 32 | c.X, c.Y, 33 | c.W, c.H, 34 | } 35 | } 36 | func (c *Control) GetID() idgen.IDInt { 37 | return c.ID 38 | } 39 | 40 | // ControlI 41 | func (c *Control) UpdateContents() { 42 | if c.UpdateContentsFn != nil { 43 | c.UpdateContentsFn() 44 | return 45 | } 46 | } 47 | func (c *Control) DrawSurface() { 48 | if c.DrawSurfaceFn != nil { 49 | c.DrawSurfaceFn() 50 | return 51 | } 52 | } 53 | func (c *Control) UpdateToWindow() { 54 | if c.UpdateToWindowFn != nil { 55 | c.UpdateToWindowFn() 56 | return 57 | } 58 | 59 | t, err := c.Win.Rend.CreateTextureFromSurface(c.Suf) 60 | if err != nil { 61 | fmt.Printf("Failed to create Texture: %s\n", err) 62 | } 63 | defer t.Destroy() 64 | srcrect := sdl.Rect{} 65 | c.Suf.GetClipRect(&srcrect) 66 | 67 | dstrect := Rect2SdlRect(c.GetRect()) 68 | 69 | c.Win.Rend.SetClipRect(c.GetClipRect()) 70 | t.SetBlendMode(sdl.BLENDMODE_NONE) 71 | c.Win.Rend.SetDrawColor(0, 0, 0, 255) 72 | c.Win.Rend.Clear() 73 | c.Win.Rend.Copy(t, &srcrect, &dstrect) 74 | c.DrawBorder() 75 | c.Win.Rend.SetClipRect(nil) 76 | } 77 | func (c *Control) SetWindow(w *Window) { 78 | c.Win = w 79 | } 80 | func (c *Control) MouseOver(x, y int, btnstate uint32) { 81 | if c.MouseOverFn != nil { 82 | c.MouseOverFn(x, y, btnstate) 83 | return 84 | } 85 | } 86 | func (c *Control) MouseButton(x, y int, btnnum uint8, btnstate uint8) { 87 | if c.MouseButtonFn != nil { 88 | c.MouseButtonFn(x, y, btnnum, btnstate) 89 | return 90 | } 91 | } 92 | func (c *Control) MouseWheel(x, y int, dx int32, dy int32, btnstate uint32) { 93 | if c.MouseWheelFn != nil { 94 | c.MouseWheelFn(x, y, dx, dy, btnstate) 95 | return 96 | } 97 | } 98 | func (c *Control) GetZ() int { 99 | return c.Z 100 | } 101 | func (c *Control) Show(visible bool) { 102 | c.Visible = visible 103 | if visible { 104 | c.Win.AddUpdateControl(c) 105 | } else { 106 | c.Win.UpdateRect(c.GetRect()) 107 | } 108 | // log.Info("show %v", c.GetRect()) 109 | } 110 | func (c *Control) IsVisible() bool { 111 | return c.Visible 112 | } 113 | func (c *Control) IsTransparent() bool { 114 | return false 115 | } 116 | 117 | type Control struct { 118 | ID idgen.IDInt 119 | Win *Window 120 | X, Y, Z int 121 | W, H int 122 | Suf *sdl.Surface 123 | Rend *sdl.Renderer 124 | Visible bool 125 | ContentsChanged bool 126 | BorderSize int32 127 | BorderType int 128 | 129 | // overriding 130 | MouseOverFn MouseOverFn 131 | MouseButtonFn MouseButtonFn 132 | MouseWheelFn MouseWheelFn 133 | UpdateContentsFn UpdateContentsFn 134 | DrawSurfaceFn DrawSurfaceFn 135 | UpdateToWindowFn UpdateToWindowFn 136 | } 137 | 138 | func NewControl(x, y, z int, wx, wy int) *Control { 139 | c := Control{ 140 | ID: <-idgen.GenCh(), 141 | X: x, 142 | Y: y, 143 | Z: z, 144 | W: wx, 145 | H: wy, 146 | Visible: true, 147 | ContentsChanged: true, 148 | BorderSize: 0, 149 | BorderType: 0, 150 | } 151 | var err error 152 | c.Suf, err = sdl.CreateRGBSurface(0, int32(c.W), int32(c.H), 32, 153 | Rmask, Gmask, Bmask, Amask) 154 | if err != nil { 155 | fmt.Printf("Failed to create surface: %s\n", err) 156 | } 157 | c.Rend, err = sdl.CreateSoftwareRenderer(c.Suf) 158 | if err != nil { 159 | fmt.Printf("Failed to create renderer: %s\n", err) 160 | } 161 | return &c 162 | } 163 | func (c *Control) GetClipRect() *sdl.Rect { 164 | clipRect := Rect2SdlRect(c.GetRect()) 165 | // clipRect.X += int32(c.X) 166 | // clipRect.Y += int32(c.Y) 167 | return &clipRect 168 | } 169 | func (c *Control) GetClientConnRect() rect.Rect { 170 | return rect.Rect{ 171 | 0, 0, 172 | c.W, c.H, 173 | } 174 | } 175 | func (c *Control) Cleanup() { 176 | if c.Suf != nil { 177 | c.Suf.Free() 178 | } 179 | if c.Rend != nil { 180 | c.Rend.Destroy() 181 | } 182 | } 183 | func (c *Control) MakeTexture(surface *sdl.Surface) *sdl.Texture { 184 | t, err := c.Rend.CreateTextureFromSurface(surface) 185 | if err != nil { 186 | fmt.Printf("Failed to create Texture: %s\n", err) 187 | } 188 | return t 189 | } 190 | func (c *Control) DrawOverlayFilter(colors OverlayFilter) { 191 | c.Win.Rend.SetDrawBlendMode(sdl.BLENDMODE_BLEND) 192 | for i, v := range colors { 193 | if i >= c.W/2 || i >= c.H/2 { 194 | break 195 | } 196 | r := sdl.Rect{int32(c.X + i), int32(c.Y + i), int32(c.W - i*2), int32(c.H - i*2)} 197 | c.Win.Rend.SetDrawColor(v[0], v[1], v[2], v[3]) 198 | c.Win.Rend.DrawRect(&r) 199 | } 200 | } 201 | func (c *Control) DrawBorder() { 202 | switch c.BorderType { 203 | case 0: 204 | case 1: 205 | c.DrawBoderBlackMild() 206 | case 2: 207 | c.DrawBorderBlackHard() 208 | case 3: 209 | c.DrawBorderWhiteHard() 210 | default: 211 | fmt.Printf("unknown bordertype %v", c.BorderType) 212 | } 213 | } 214 | func (c *Control) DrawBorderBlackHard() { 215 | c.Win.Rend.SetDrawBlendMode(sdl.BLENDMODE_BLEND) 216 | for i := int32(0); i < c.BorderSize; i++ { 217 | r := sdl.Rect{int32(c.X) + i, int32(c.Y) + i, int32(c.W) - i*2, int32(c.H) - i*2} 218 | c.Win.Rend.SetDrawColor(0, 0, 0, uint8(255-i*256/c.BorderSize)) 219 | c.Win.Rend.DrawRect(&r) 220 | } 221 | } 222 | func (c *Control) DrawBoderBlackMild() { 223 | c.Win.Rend.SetDrawBlendMode(sdl.BLENDMODE_BLEND) 224 | for i := int32(0); i < c.BorderSize; i++ { 225 | r := sdl.Rect{int32(c.X) + i, int32(c.Y) + i, int32(c.W) - i*2, int32(c.H) - i*2} 226 | c.Win.Rend.SetDrawColor(0, 0, 0, uint8(127-i*128/c.BorderSize)) 227 | c.Win.Rend.DrawRect(&r) 228 | } 229 | } 230 | func (c *Control) DrawBorderWhiteHard() { 231 | c.Win.Rend.SetDrawBlendMode(sdl.BLENDMODE_BLEND) 232 | for i := int32(0); i < c.BorderSize; i++ { 233 | r := sdl.Rect{int32(c.X) + i, int32(c.Y) + i, int32(c.W) - i*2, int32(c.H) - i*2} 234 | c.Win.Rend.SetDrawColor(255, 255, 255, uint8(255-i*256/c.BorderSize)) 235 | c.Win.Rend.DrawRect(&r) 236 | } 237 | } 238 | 239 | func (c *Control) UpdateNow() { 240 | c.UpdateContents() 241 | c.DrawSurface() 242 | c.Win.AddUpdateControl(c) 243 | } 244 | -------------------------------------------------------------------------------- /controli.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "github.com/kasworld/quadtree" 16 | ) 17 | 18 | type ControlIList []ControlI 19 | 20 | func (s ControlIList) Len() int { 21 | return len(s) 22 | } 23 | func (s ControlIList) Swap(i, j int) { 24 | s[i], s[j] = s[j], s[i] 25 | } 26 | func (s ControlIList) Less(i, j int) bool { 27 | return s[i].GetZ() < s[j].GetZ() 28 | } 29 | 30 | // for overriding 31 | type MouseOverFn func(x, y int, btnstate uint32) 32 | type MouseButtonFn func(x, y int, btnnum uint8, btnstate uint8) 33 | type MouseWheelFn func(x, y int, dx int32, dy int32, btnstate uint32) 34 | type UpdateContentsFn func() 35 | type DrawSurfaceFn func() 36 | type UpdateToWindowFn func() 37 | 38 | type ControlI interface { 39 | quadtree.QuadTreeObjI 40 | 41 | MouseOver(x, y int, btnstate uint32) 42 | MouseButton(x, y int, btnnum uint8, btnstate uint8) 43 | MouseWheel(x, y int, dx int32, dy int32, btnstate uint32) 44 | 45 | UpdateContents() 46 | DrawSurface() 47 | UpdateToWindow() 48 | 49 | SetWindow(w *Window) 50 | GetZ() int 51 | Show(visible bool) 52 | IsVisible() bool 53 | IsTransparent() bool 54 | } 55 | -------------------------------------------------------------------------------- /example/DejaVuSerif.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kasworld/go-sdlgui/c572586395386956bcee5817fa41e74a3bdff907/example/DejaVuSerif.ttf -------------------------------------------------------------------------------- /example/NanumGothic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kasworld/go-sdlgui/c572586395386956bcee5817fa41e74a3bdff907/example/NanumGothic.ttf -------------------------------------------------------------------------------- /example/clock.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package main 13 | 14 | import ( 15 | "time" 16 | 17 | "github.com/kasworld/actionstat" 18 | "github.com/kasworld/go-sdl2/sdl" 19 | "github.com/kasworld/go-sdlgui" 20 | "github.com/kasworld/go-sdlgui/analogueclock" 21 | "github.com/kasworld/log" 22 | ) 23 | 24 | func main() { 25 | NewApp().Run() 26 | } 27 | 28 | type App struct { 29 | Quit bool 30 | SdlCh chan interface{} 31 | Keys sdlgui.KeyState 32 | Win *sdlgui.Window 33 | Controls sdlgui.ControlIList 34 | 35 | cl *analogueclock.Clock 36 | Stat *actionstat.ActionStat 37 | } 38 | 39 | const ( 40 | WinW = 2000 41 | WinH = 2000 42 | ClockW = 2000 43 | ClockH = 2000 44 | DrawFPS = 100 45 | ) 46 | 47 | func NewApp() *App { 48 | app := App{ 49 | SdlCh: make(chan interface{}, 1), 50 | Keys: make(map[sdl.Scancode]bool), 51 | Win: sdlgui.NewWindow("SDL GUI Clock Example", WinW, WinH, true), 52 | 53 | Stat: actionstat.New(), 54 | } 55 | app.addControls() 56 | app.Win.UpdateAll() 57 | return &app 58 | } 59 | 60 | func (app *App) AddControl(c sdlgui.ControlI) { 61 | app.Controls = append(app.Controls, c) 62 | app.Win.AddControl(c) 63 | } 64 | 65 | // change as app's need 66 | 67 | func (g *App) addControls() { 68 | g.cl = analogueclock.New(0, 0, 0, ClockW, ClockH) 69 | g.AddControl(g.cl) 70 | } 71 | 72 | func (app *App) Run() { 73 | // need to co-exist sdl lib 74 | // runtime.LockOSThread() 75 | // defer runtime.UnlockOSThread() 76 | 77 | // start sdl event loop 78 | sdlgui.SDLEvent2Ch(app.SdlCh) 79 | 80 | timerInfoCh := time.Tick(time.Duration(1000) * time.Millisecond) 81 | timerDrawCh := time.Tick(time.Second / DrawFPS) 82 | 83 | for !app.Quit { 84 | select { 85 | case data := <-app.SdlCh: 86 | if app.Win.ProcessSDLMouseEvent(data) || 87 | app.Keys.ProcessSDLKeyEvent(data) { 88 | app.Quit = true 89 | } 90 | 91 | case <-timerDrawCh: 92 | app.cl.SetTime(time.Now()) 93 | for _, v := range app.Controls { 94 | v.DrawSurface() 95 | } 96 | app.Win.Update() 97 | app.Stat.Inc() 98 | 99 | case <-timerInfoCh: 100 | log.Info("FPS %v", app.Stat) 101 | app.Stat.UpdateLap() 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /example/example.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package main 13 | 14 | import ( 15 | "time" 16 | 17 | "github.com/kasworld/actionstat" 18 | "github.com/kasworld/go-sdl2/sdl" 19 | "github.com/kasworld/go-sdlgui" 20 | "github.com/kasworld/go-sdlgui/bartext" 21 | "github.com/kasworld/go-sdlgui/textbox" 22 | "github.com/kasworld/htmlcolors" 23 | "github.com/kasworld/log" 24 | ) 25 | 26 | func main() { 27 | NewApp().Run() 28 | } 29 | 30 | type App struct { 31 | Quit bool 32 | SdlCh chan interface{} 33 | Keys sdlgui.KeyState 34 | Win *sdlgui.Window 35 | Controls sdlgui.ControlIList 36 | 37 | Stat *actionstat.ActionStat 38 | msgtext *textbox.TextBoxControl 39 | barctrl *bartext.TextControl 40 | } 41 | 42 | func NewApp() *App { 43 | app := App{ 44 | SdlCh: make(chan interface{}, 1), 45 | Keys: make(map[sdl.Scancode]bool), 46 | Win: sdlgui.NewWindow("SDL GUI Example", 1024, 800, true), 47 | 48 | Stat: actionstat.New(), 49 | } 50 | app.addControls() 51 | app.Win.UpdateAll() 52 | return &app 53 | } 54 | 55 | func (app *App) AddControl(c sdlgui.ControlI) { 56 | app.Controls = append(app.Controls, c) 57 | app.Win.AddControl(c) 58 | } 59 | 60 | // change as app's need 61 | 62 | func (g *App) addControls() { 63 | g.msgtext = textbox.New( 64 | 0, 0, 0, 65 | 1024, 720, 60, 66 | sdlgui.LoadFont("NanumGothic.ttf", 12)) 67 | g.msgtext.SetBG(htmlcolors.Gray.ToRGBA()) 68 | g.AddControl(g.msgtext) 69 | 70 | dispstr := "안녕" 71 | println(dispstr) 72 | log.Printf("%v %x %+q", dispstr, dispstr, dispstr) 73 | 74 | g.barctrl = bartext.New( 75 | 0, 720, 0, 76 | 1024, 80, dispstr, 77 | sdlgui.LoadFont("NanumGothic.ttf", 36)) 78 | g.barctrl.SetBG(htmlcolors.Pink.ToRGBA()) 79 | g.AddControl(g.barctrl) 80 | 81 | } 82 | 83 | func (app *App) Run() { 84 | // need to co-exist sdl lib 85 | // runtime.LockOSThread() 86 | // defer runtime.UnlockOSThread() 87 | 88 | // start sdl event loop 89 | sdlgui.SDLEvent2Ch(app.SdlCh) 90 | 91 | timerInfoCh := time.Tick(time.Duration(1000) * time.Millisecond) 92 | timerDrawCh := time.Tick(time.Duration(1000/60) * time.Millisecond) 93 | // timerDrawCh := time.Tick(time.Microsecond) 94 | barlen := 0.0 95 | 96 | for !app.Quit { 97 | select { 98 | case data := <-app.SdlCh: 99 | if app.Win.ProcessSDLMouseEvent(data) || 100 | app.Keys.ProcessSDLKeyEvent(data) { 101 | app.Quit = true 102 | } 103 | app.msgtext.AddText("data %v", data) 104 | app.barctrl.SetBar(barlen) 105 | barlen += 0.01 106 | if barlen > 1 { 107 | barlen = 0 108 | } 109 | app.Stat.Inc() 110 | 111 | case <-timerDrawCh: 112 | for _, v := range app.Controls { 113 | v.DrawSurface() 114 | } 115 | app.Win.Update() 116 | 117 | case <-timerInfoCh: 118 | log.Info("stat %v", app.Stat) 119 | app.Stat.UpdateLap() 120 | 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /example/hangulscreenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kasworld/go-sdlgui/c572586395386956bcee5817fa41e74a3bdff907/example/hangulscreenshot.png -------------------------------------------------------------------------------- /example/nanumfontlicense.txt: -------------------------------------------------------------------------------- 1 | see 2 | http://help.naver.com/ops/step2/faq.nhn?faqId=15879 3 | 4 | 5 | 네이버 나눔글꼴의 지적 재산권은 네이버에 있습니다. 6 | 네이버 나눔글꼴은 개인 및 기업 사용자를 포함한 모든 사용자에게 7 | 8 | 무료로 제공되며 자유롭게 수정하고 재배포하실 수 있습니다. 9 | 10 | 단, 글꼴 자체를 유료로 판매하는 것은 금지하며, 11 | 12 | 네이버 나눔글꼴은 본 저작권 안내와 라이선스 전문을 포함해서 13 | 14 | 다른 소프트웨어와 번들하거나 재배포 또는 판매가 가능합니다. 15 | 네이버 나눔글꼴 라이선스 전문을 포함하기 어려울 경우, 16 | 17 | 나눔글꼴의 출처 표기를 권장합니다. 18 | 19 | 예) 이 페이지에는 네이버에서 제공한 나눔글꼴이 적용되어 있습니다 20 | 21 | 네이버 나눔글꼴을 사용한 인쇄물, 광고물(온라인 포함)의 이미지는 22 | 23 | 나눔글꼴 프로모션을 위해 활용될 수 있습니다. 24 | 25 | 이를 원치 않는 사용자는 언제든지 당사에 요청하실 수 있습니다. 26 | 27 | 정확한 사용 조건은 아래 네이버 나눔글꼴 라이선스 전문을 참고하시기 바랍니다. 28 | 29 | 30 | 31 | 32 | 33 | *나눔글꼴 라이선스 전문의 한글은 이용자의 이해를 돕기 위해 영문 원본을 번역해 서비스하고 있으며 34 | 35 | 법적 효력은 영문에 한합니다. 이 점 참고하시기 바랍니다. 36 | 37 | 38 | 39 | Copyright (c) 2010, NAVER Corporation (http://www.nhncorp.com), 40 | 41 | with Reserved Font Name Nanum, Naver Nanum, NanumGothic, Naver NanumGothic, NanumMyeongjo, Naver NanumMyeongjo, NanumBrush, Naver NanumBrush, NanumPen, Naver NanumPen, Naver NanumGothicEco, NanumGothicEco, Naver NanumMyeongjoEco, NanumMyeongjoEco, Naver NanumGothicLight, NanumGothicLight, NanumBarunGothic, Naver NanumBarunGothic, 42 | 43 | This Font Software is licensed under the SIL Open Font License, Version 1.1. 44 | 45 | This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL 46 | 47 | SIL OPEN FONT LICENSE 48 | 49 | Version 1.1 - 26 February 2007 50 | 51 | 52 | 53 | ‘나눔, 네이버 나눔, 나눔고딕, 네이버 나눔고딕, 나눔명조, 네이버 나눔명조, 나눔손글씨, 네이버 나눔손글씨, 나눔펜, 네이버 나눔펜, 네이버 나눔고딕에코, 나눔고딕에코, 네이버 나눔명조에코, 나눔명조에코, 네이버 나눔고딕라이트, 나눔고딕라이트, 나눔바른고딕, 네이버나눔바른고딕’ 폰트명에 대해 NAVER (http://www.nhncorp.com)이 저작권을 소유하고 있습니다. 54 | 55 | 본 폰트 소프트웨어는 SIL 오픈 폰트 라이선스 버전 1.1에 따라 라이선스 취득을 하였습니다. 56 | 57 | 본 라이선스는 하단에 복사되었고 http://scripts.sil.org/OFL의 FAQ란 에서도 열람가능 합니다. 58 | 59 | 60 | 61 | SIL 오픈 폰트 라이선스 62 | 63 | 버전 1.1 (2007년 2월 26일) 64 | 65 | 66 | 67 | 68 | 69 | DEFINITIONS 70 | 71 | "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. 72 | 73 | 74 | 75 | "Reserved Font Name" refers to any names specified as such after the copyright statement(s). 76 | 77 | 78 | 79 | "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). 80 | 81 | 82 | 83 | "Modified Version" refers to any derivative made by adding to, deleting, or substituting in part or in whole any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment.‘ 84 | 85 | 86 | 87 | "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. 88 | 89 | 90 | 91 | 정의 92 | 93 | ‘폰트 소프트웨어’는 본 라이선스에 입거해 저작권자가 배포하고 명확하게 같은 표시가 된 파일들의 집합을 뜻하며, 여기에는 소스 파일, 빌드 스크립트와 문서가 이에 포함됩니다. 94 | 95 | 96 | 97 | ‘저작권이 있는 폰트명’은 저작권 정책에 따라서 지정된 이름을 말합니다. 98 | 99 | 100 | 101 | ‘원본’은 저작권자가 배포한 폰트 소프트웨어 구성요소를 의미합니다. 102 | 103 | 104 | 105 | ‘수정본’은 포맷의 변경이나 폰트 소프트웨어를 새로운 환경에 포팅시켜, 원본의 일부 혹은 전체에 추가, 삭제 대체해 만든 파생 저작물을 의미합니다. 106 | 107 | 108 | 109 | ‘저자’는 폰트 소프트웨어에 기여한 디자이너, 엔지니어, 프로그래머, 기술 전문가 등을 의미합니다. 110 | 111 | 112 | 113 | 114 | PREAMBLE 115 | 116 | The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, 117 | 118 | to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework 119 | in which fonts may be shared and improved in partnership with others. 120 | 121 | The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold 122 | by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. 123 | The fonts and derivatives, however, cannot be released under any other type of license. 124 | 125 | The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. 126 | 127 | 128 | 129 | 전문 130 | 131 | 본 폰트 라이선스를 오픈 하는 것은(이하 OFL)는 전 세계 폰트 개발 프로젝트를 지원하고 학계와 언어 관련 학계의 폰트 개발을 위한 연구를 지지하기 위해서인 동시에, 폰트 제휴를 통해 폰트가 공유되고 개선될 수 있는 자유롭게 개방된 환경을 만들기 위해서 입니다. 132 | 133 | OFL은 라이선스를 취득한 폰트가 그 자체로 판매되지 않는 한 자유롭게 사용, 연구, 수정, 재배포 하는 것을 허가합니다. 수정된 폰트를 포함한 폰트는 저작권 명이 사용되지 않는 한 기타 소프트웨어와 함께 묶이거나 삽입, 재배포 할 수 있습니다. 단 폰트와 수정된 폰트는 기타 다른 라이선스에 포함되어 배포될 수는 없습니다. 이 라이선스 하에 있기 위한 폰트에 대한 요구사항은 본 폰트나 수정본을 사용하여 제작된 어떠한 문서에도 적용되지 않습니다. 134 | 135 | 136 | 137 | 138 | 139 | PERMISSION & CONDITIONS 140 | 141 | Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 142 | 143 | 144 | 145 | 허가 및 조건 146 | 147 | 본 폰트 소프트웨어를 사용하도록 허가 받은 개인/기업/단체 누구라도 다음 명시된 조건에 따라 폰트 소프트웨어의 수정 혹은 수정되지 않은 복사본을 무료로 사용, 연구, 복사, 통합, 삽입, 수정, 재배포할 수 있도록 허가합니다. 148 | 149 | 150 | 151 | 1) Neither the Font Software nor any of its individual components,in Original or Modified Versions, may be sold by itself. 152 | 153 | 원본이나 수정본의 폰트 소프트웨어 혹은 개별 구성요소인 폰트 자체가 판매되어서는 안됩니다. 154 | 155 | 156 | 157 | 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 158 | 159 | 160 | 161 | 본 폰트 소프트웨어의 원본 혹은 수정본은 상기 저작권 안내와 본 라이선스에 대한 내용을 포함하는 경우에는 다른 소프트웨어와 함께 묶이거나 재배포 혹은 판매가 가능합니다. 이는 독립 텍스트 파일과 가독성이 있는 헤더 혹은 유저가 용이하게 열람 가능한 이상 텍스트파일 혹은 이진파일 내 기계가 읽을 수 있는 메타데이터 형태를 모두 의미 합니다. 162 | 163 | 164 | 165 | 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written 166 | 167 | permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 168 | 169 | 170 | 171 | 본 폰트 소프트웨어의 어떠한 수정본도 동일한 저작권자가 명시적 허가서를 부여하지 않는 한 저작권이 있는 폰트명을 사용해서는 안 됩니다. 본 제한 사항은 유저들에게 제공된 기존 폰트명을 뜻합니다. 172 | 173 | 174 | 175 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 176 | 177 | 178 | 179 | 본 폰트 소프트웨어의 저작권자 혹은 저자의 이름은 그들의 명시적 서면 허가가 있거나 또는 그들의 공헌을 인정하기 위한 경우를 제외하고는 수정본에 대한 사용을 유도,추천 혹은 광고하기 위한 목적으로 사용할 수 없습니다. 180 | 181 | 182 | 183 | 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. 184 | 185 | 186 | 187 | 본 폰트 소프트웨어는 전체나 부분, 혹은 수정 여부에 상관없이 본 라이선스 하에 배포가 되어야 하며 기타 다른 라이선스 하에서는 배포를 할 수 없습니다. 폰트에 대한 요구조건은 이 라이선스 하에서만 유효하며 이 라이선스 하에 있기 위한 폰트에 대한 요구사항은 본 폰트 소프트웨어를 사용해 제작한 어떠한 문서에도 적용되지 않습니다. 188 | 189 | 190 | 191 | 192 | 193 | TERMINATION 계약의 종료 194 | 195 | This license becomes null and void if any of the above conditions are not met. 196 | 197 | 본 라이선스는 상기 조건 중 일부라도 부합되지 않으면 무효가 될 수 있습니다. 198 | 199 | 200 | 201 | 202 | 203 | DISCLAIMER 204 | 205 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. 206 | 207 | 208 | 209 | 210 | 211 | 면책조항 212 | 213 | 본 폰트 소프트웨어는 저작권, 특허권, 상표권 및 기타 권리의 비침해성과 특정 목적에의 적합성 포함한 명시적, 묵시적인 어떠한 종류의 보증 없이 “있는 그대로” 제공됩니다. 어떠한 경우에도 저작권자는 본 폰트 소프트웨어의 사용 또는 이의 사용불가, 그밖에 폰트 소프트웨어의 취급과 관련하여 발생하는 모든 계약, 불법행위 혹은 다른 일로 하여금 발생하는 일반적, 특수적, 간접적, 부차적 혹은 필연적 손해를 포함하는 소송, 손해, 혹은 기타 책임에 대한 의무를 가지지 않습니다. 214 | -------------------------------------------------------------------------------- /example/screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kasworld/go-sdlgui/c572586395386956bcee5817fa41e74a3bdff907/example/screenshot.png -------------------------------------------------------------------------------- /font.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "fmt" 16 | 17 | "github.com/kasworld/go-sdl2/sdl" 18 | "github.com/kasworld/go-sdl2/sdl_ttf" 19 | "github.com/kasworld/htmlcolors" 20 | ) 21 | 22 | func init() { 23 | // println("init ttf") 24 | ttf.Init() 25 | } 26 | 27 | type FontKey struct { 28 | co htmlcolors.RGBA 29 | text string 30 | } 31 | type Font struct { 32 | Font *ttf.Font 33 | Cache map[FontKey]*sdl.Surface 34 | } 35 | 36 | func LoadFont(filename string, size int) *Font { 37 | font, err := ttf.OpenFont(filename, size) 38 | if err != nil { 39 | fmt.Printf("font open fail %v\n", err) 40 | } 41 | return &Font{ 42 | Font: font, 43 | Cache: make(map[FontKey]*sdl.Surface), 44 | } 45 | } 46 | func (f *Font) MakeSurface(co htmlcolors.RGBA, text string) (*sdl.Surface, sdl.Rect) { 47 | surface, err := f.Font.RenderUTF8_Blended(text, RGBA2SDL(co)) 48 | if err != nil { 49 | fmt.Printf("%v %v %v", err, co, text) 50 | fmt.Printf("Failed to create surface: %s\n", sdl.GetError()) 51 | } 52 | srcRect := sdl.Rect{} 53 | surface.GetClipRect(&srcRect) 54 | return surface, srcRect 55 | } 56 | 57 | func (f *Font) GetSurfaceWithCache(co htmlcolors.RGBA, text string) (*sdl.Surface, sdl.Rect) { 58 | surface := f.Cache[FontKey{co, text}] 59 | if surface != nil { 60 | srcRect := sdl.Rect{} 61 | surface.GetClipRect(&srcRect) 62 | return surface, srcRect 63 | } else { 64 | surface, srcRect := f.MakeSurface(co, text) 65 | f.Cache[FontKey{co, text}] = surface 66 | return surface, srcRect 67 | } 68 | } 69 | func (f *Font) MakeTexture(co htmlcolors.RGBA, text string, rend *sdl.Renderer) (*sdl.Texture, sdl.Rect) { 70 | surface, srcRect := f.MakeSurface(co, text) 71 | defer surface.Free() 72 | t, err := rend.CreateTextureFromSurface(surface) 73 | if err != nil { 74 | fmt.Printf("Failed to create Texture: %s\n", err) 75 | } 76 | return t, srcRect 77 | } 78 | -------------------------------------------------------------------------------- /overlayfilter.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "github.com/kasworld/htmlcolors" 16 | ) 17 | 18 | type OverlayFilter []htmlcolors.RGBA 19 | 20 | func MakeOverlayFilter(n int, b htmlcolors.RGBA) OverlayFilter { 21 | rtn := make(OverlayFilter, n) 22 | for i := 0; i < n; i++ { 23 | for j, v := range b { 24 | if int(v) < i*256/n { 25 | rtn[i][j] = 0 26 | } else { 27 | rtn[i][j] = v - uint8(i*256/n) 28 | } 29 | } 30 | } 31 | return rtn 32 | } 33 | -------------------------------------------------------------------------------- /sdlevent.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "github.com/kasworld/go-sdl2/sdl" 16 | ) 17 | 18 | type KeyState map[sdl.Scancode]bool 19 | 20 | func (ks KeyState) ProcessSDLKeyEvent(data interface{}) (quit bool) { 21 | quit = false 22 | switch t := data.(type) { 23 | case *sdl.KeyUpEvent: 24 | delete(ks, t.Keysym.Scancode) 25 | case *sdl.KeyDownEvent: 26 | if t.Repeat == 0 { 27 | ks[t.Keysym.Scancode] = true 28 | } 29 | switch t.Keysym.Scancode { 30 | case sdl.SCANCODE_ESCAPE: 31 | quit = true 32 | } 33 | } 34 | return 35 | } 36 | 37 | func (w *Window) ProcessSDLMouseEvent(data interface{}) (quit bool) { 38 | quit = false 39 | switch t := data.(type) { 40 | case *sdl.MouseMotionEvent: 41 | c, x, y, btnstate := w.ProcessMouseMotionEvent(t) 42 | if c != nil { 43 | c.MouseOver(x, y, btnstate) 44 | } 45 | case *sdl.MouseButtonEvent: 46 | c, x, y, n, s := w.ProcessMouseButtonEvent(t) 47 | if c != nil { 48 | c.MouseButton(x, y, n, s) 49 | } 50 | case *sdl.MouseWheelEvent: 51 | c, x, y, dx, dy, btnstate := w.ProcessMouseWheelEvent(t) 52 | if c != nil { 53 | c.MouseWheel(x, y, dx, dy, btnstate) 54 | } 55 | case *sdl.QuitEvent: 56 | // log.Printf("quit %v\n", t) 57 | quit = true 58 | } 59 | return 60 | } 61 | 62 | func SDLEvent2Ch(ch chan<- interface{}) { 63 | go func() { 64 | for { 65 | event := sdl.WaitEvent() 66 | if event == nil { 67 | continue 68 | } 69 | ch <- event 70 | } 71 | }() 72 | } 73 | -------------------------------------------------------------------------------- /textbox/textbox.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package textbox 13 | 14 | import ( 15 | "fmt" 16 | 17 | "github.com/kasworld/go-sdl2/sdl" 18 | "github.com/kasworld/go-sdlgui" 19 | "github.com/kasworld/htmlcolors" 20 | ) 21 | 22 | type TextBoxControl struct { 23 | *sdlgui.Control 24 | font *sdlgui.Font 25 | bg htmlcolors.RGBA 26 | fg htmlcolors.RGBA 27 | texts []string 28 | linecount int 29 | } 30 | 31 | func New(x, y, z int, wx, wy int, linecount int, font *sdlgui.Font) *TextBoxControl { 32 | tc := TextBoxControl{ 33 | sdlgui.NewControl(x, y, z, wx, wy), 34 | font, 35 | htmlcolors.Black.ToRGBA(), 36 | htmlcolors.White.ToRGBA(), 37 | make([]string, 0), 38 | linecount, 39 | } 40 | tc.BorderSize = 2 41 | tc.BorderType = 1 42 | return &tc 43 | } 44 | func (tc *TextBoxControl) DrawSurface() { 45 | if !tc.ContentsChanged { 46 | return 47 | } 48 | tc.ContentsChanged = false 49 | 50 | tc.Rend.SetDrawColor(tc.bg[0], tc.bg[1], tc.bg[2], tc.bg[3]) 51 | tc.Rend.Clear() 52 | st := 0 53 | if len(tc.texts) > tc.linecount { 54 | st = len(tc.texts) - tc.linecount 55 | } 56 | for i, text := range tc.texts[st:] { 57 | surface, srcRect := tc.font.MakeSurface(tc.fg, text) 58 | defer surface.Free() 59 | dstRect := sdl.Rect{ 60 | tc.BorderSize, int32(i*int(tc.H)/tc.linecount) - tc.BorderSize, 61 | srcRect.W*int32(tc.H/tc.linecount)/srcRect.H - tc.BorderSize, int32(tc.H / tc.linecount), 62 | } 63 | if dstRect.W < int32(tc.W) { 64 | surface.Blit(&srcRect, tc.Suf, &dstRect) 65 | } else { 66 | dstRect.W = int32(tc.W) 67 | surface.BlitScaled(&srcRect, tc.Suf, &dstRect) 68 | } 69 | } 70 | tc.Rend.Present() 71 | tc.Win.AddUpdateControl(tc) 72 | } 73 | func (tc *TextBoxControl) MouseOver(x, y int, btnstate uint32) { 74 | } 75 | func (tc *TextBoxControl) MouseButton(x, y int, btnnum uint8, btnstate uint8) { 76 | tc.bg, tc.fg = tc.fg, tc.bg 77 | tc.ContentsChanged = true 78 | tc.DrawSurface() 79 | } 80 | func (tc *TextBoxControl) MouseWheel(x, y int, dx int32, dy int32, btnstate uint32) { 81 | } 82 | func (tc *TextBoxControl) SetBG(bg htmlcolors.RGBA) { 83 | if bg == tc.bg { 84 | return 85 | } 86 | tc.ContentsChanged = true 87 | tc.bg = bg 88 | } 89 | func (tc *TextBoxControl) SetFG(fg htmlcolors.RGBA) { 90 | if fg == tc.fg { 91 | return 92 | } 93 | tc.ContentsChanged = true 94 | tc.fg = fg 95 | } 96 | func (tc *TextBoxControl) AddText(format string, a ...interface{}) { 97 | tc.ContentsChanged = true 98 | text := fmt.Sprintf(format, a...) 99 | tc.texts = append(tc.texts, text) 100 | } 101 | func (tc *TextBoxControl) SetTexts(texts []string) { 102 | tc.ContentsChanged = true 103 | tc.texts = texts 104 | } 105 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "fmt" 16 | 17 | "github.com/kasworld/go-sdl2/sdl" 18 | "github.com/kasworld/go-sdl2/sdl_image" 19 | "github.com/kasworld/htmlcolors" 20 | "github.com/kasworld/rect" 21 | ) 22 | 23 | func RGBA2SDL(c htmlcolors.RGBA) sdl.Color { 24 | return sdl.Color{c[0], c[1], c[2], c[3]} 25 | } 26 | 27 | func SdlRect2Rect(wr sdl.Rect) rect.Rect { 28 | return rect.Rect{ 29 | int(wr.X), int(wr.Y), 30 | int(wr.W), int(wr.H), 31 | } 32 | } 33 | func Rect2SdlRect(rt rect.Rect) sdl.Rect { 34 | return sdl.Rect{ 35 | int32(rt.X), int32(rt.Y), 36 | int32(rt.W), int32(rt.H), 37 | } 38 | } 39 | 40 | func LoadBMP(imageName string) *sdl.Surface { 41 | image, err := sdl.LoadBMP(imageName) 42 | if err != nil { 43 | fmt.Printf("Failed to load BMP: %s", err) 44 | } 45 | return image 46 | } 47 | func LoadImage(imageName string) *sdl.Surface { 48 | image, err := img.Load(imageName) 49 | if err != nil { 50 | fmt.Printf("Failed to load Image: %s", err) 51 | } 52 | return image 53 | } 54 | -------------------------------------------------------------------------------- /window.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 SeukWon Kang (kasworld@gmail.com) 2 | // Licensed under the Apache License, Version 2.0 (the "License"); 3 | // you may not use this file except in compliance with the License. 4 | // You may obtain a copy of the License at 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // Unless required by applicable law or agreed to in writing, software 7 | // distributed under the License is distributed on an "AS IS" BASIS, 8 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9 | // See the License for the specific language governing permissions and 10 | // limitations under the License. 11 | 12 | package sdlgui 13 | 14 | import ( 15 | "fmt" 16 | "sort" 17 | 18 | "github.com/kasworld/go-sdl2/sdl" 19 | "github.com/kasworld/idgen" 20 | "github.com/kasworld/quadtree" 21 | "github.com/kasworld/rect" 22 | ) 23 | 24 | type Window struct { 25 | ID idgen.IDInt 26 | Win *sdl.Window 27 | Rend *sdl.Renderer 28 | Controls *quadtree.QuadTree 29 | controlsToUpdate ControlIList 30 | } 31 | 32 | func NewWindow(title string, wx, wy int, show bool) *Window { 33 | w := Window{ 34 | ID: <-idgen.GenCh(), 35 | } 36 | var err error 37 | if show { 38 | w.Win, err = sdl.CreateWindow(title, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 39 | wx, wy, sdl.WINDOW_SHOWN) 40 | } else { 41 | w.Win, err = sdl.CreateWindow(title, sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 42 | wx, wy, sdl.WINDOW_HIDDEN) 43 | } 44 | if err != nil { 45 | fmt.Printf("Failed to create window: %s\n", err) 46 | } 47 | // w.Rend, err = sdl.CreateRenderer(w.Win, -1, sdl.RENDERER_SOFTWARE) 48 | w.Rend, err = sdl.CreateRenderer(w.Win, -1, sdl.RENDERER_ACCELERATED) 49 | if err != nil { 50 | fmt.Printf("Failed to create renderer: %s\n", err) 51 | } 52 | 53 | wr := sdl.Rect{} 54 | w.Rend.GetViewport(&wr) 55 | w.Controls = quadtree.New(SdlRect2Rect(wr)) 56 | return &w 57 | } 58 | func (w *Window) Cleanup() { 59 | if w.Rend != nil { 60 | w.Rend.Destroy() 61 | } 62 | if w.Win != nil { 63 | w.Win.Destroy() 64 | } 65 | } 66 | func (w *Window) SetTitle(title string) { 67 | w.Win.SetTitle(title) 68 | } 69 | func (w *Window) Show(show bool) { 70 | if show { 71 | w.Win.Show() 72 | } else { 73 | w.Win.Hide() 74 | } 75 | } 76 | func (w *Window) AddControl(c ControlI) { 77 | w.Controls.Insert(c) 78 | c.SetWindow(w) 79 | } 80 | func (w *Window) DelControl(c ControlI) { 81 | w.Controls.Remove(c) 82 | } 83 | func (w *Window) UpdateAll() { 84 | wr := sdl.Rect{} 85 | w.Rend.GetViewport(&wr) 86 | controlsToUpdate := w.GetControlListByRect(SdlRect2Rect(wr)) 87 | 88 | w.UpdateControls(controlsToUpdate) 89 | w.controlsToUpdate = w.controlsToUpdate[:0] 90 | w.Rend.Present() 91 | } 92 | func (w *Window) Update() { 93 | w.UpdateControls(w.controlsToUpdate) 94 | w.controlsToUpdate = w.controlsToUpdate[:0] 95 | w.Rend.Present() 96 | } 97 | 98 | func (w *Window) UpdateControls(controlsToUpdate ControlIList) { 99 | toupdatecontrols := w.listVisibleControls(controlsToUpdate) 100 | for _, v := range toupdatecontrols { 101 | v.UpdateToWindow() 102 | } 103 | } 104 | 105 | func (w *Window) GetControlListByRect(wr rect.Rect) ControlIList { 106 | controlsToUpdate := ControlIList{} 107 | fn := func(qi quadtree.QuadTreeObjI) bool { 108 | c := qi.(ControlI) 109 | if c.IsVisible() { 110 | controlsToUpdate = append(controlsToUpdate, c) 111 | } 112 | return false 113 | } 114 | w.Controls.QueryByRect(fn, wr) 115 | return controlsToUpdate 116 | } 117 | 118 | func (w *Window) listVisibleControls(in ControlIList) ControlIList { 119 | sort.Sort(in) 120 | rtn := ControlIList{} 121 | loop: 122 | for _, v := range in { 123 | if !v.IsVisible() { 124 | continue loop 125 | } 126 | 127 | cinrect := w.GetControlListByRect(v.GetRect()) 128 | sort.Sort(cinrect) 129 | 130 | for _, w := range cinrect { 131 | if w.IsTransparent() || !w.IsVisible() || v.GetID() == w.GetID() { 132 | continue 133 | } 134 | if v.GetZ() < w.GetZ() && v.GetRect().IsIn(w.GetRect()) { 135 | continue loop 136 | } 137 | } 138 | rtn = append(rtn, v) 139 | } 140 | return rtn 141 | } 142 | 143 | func (w *Window) UpdateRect(wr rect.Rect) { 144 | controlsToUpdate := w.GetControlListByRect(wr) 145 | w.UpdateControls(controlsToUpdate) 146 | } 147 | 148 | func (w *Window) AddUpdateControl(c ControlI) { 149 | w.controlsToUpdate = append(w.controlsToUpdate, c) 150 | } 151 | func (w *Window) FindControl(x, y int) ControlI { 152 | var rtn ControlI 153 | fn := func(qi quadtree.QuadTreeObjI) bool { 154 | c := qi.(ControlI) 155 | if !c.IsVisible() { 156 | return false 157 | } 158 | if rtn == nil { 159 | rtn = c 160 | } else { 161 | if rtn.GetZ() < c.GetZ() { 162 | rtn = c 163 | } 164 | } 165 | return false 166 | } 167 | w.Controls.QueryByPos(fn, [2]int{x, y}) 168 | // log.Info("find control %v %v %v", rtn, x, y) 169 | return rtn 170 | } 171 | 172 | func (w *Window) ProcessMouseEvent() (ControlI, int, int, uint32) { 173 | mx, my, btnstate := sdl.GetMouseState() 174 | c := w.FindControl(int(mx), int(my)) 175 | if c == nil { 176 | return c, 0, 0, btnstate 177 | } 178 | cx, cy := int(mx)-c.GetRect().X, int(my)-c.GetRect().Y 179 | return c, cx, cy, btnstate 180 | } 181 | func (w *Window) ProcessMouseMotionEvent(t *sdl.MouseMotionEvent) (ControlI, int, int, uint32) { 182 | _, _, btnstate := sdl.GetMouseState() 183 | c := w.FindControl(int(t.X), int(t.Y)) 184 | if c == nil { 185 | return c, 0, 0, btnstate 186 | } 187 | cx, cy := int(t.X)-c.GetRect().X, int(t.Y)-c.GetRect().Y 188 | return c, cx, cy, btnstate 189 | } 190 | func (w *Window) ProcessMouseButtonEvent(t *sdl.MouseButtonEvent) (ControlI, int, int, uint8, uint8) { 191 | c := w.FindControl(int(t.X), int(t.Y)) 192 | if c == nil { 193 | return c, 0, 0, t.Button, t.State 194 | } 195 | cx, cy := int(t.X)-c.GetRect().X, int(t.Y)-c.GetRect().Y 196 | return c, cx, cy, t.Button, t.State 197 | } 198 | func (w *Window) ProcessMouseWheelEvent(t *sdl.MouseWheelEvent) (ControlI, int, int, int32, int32, uint32) { 199 | mx, my, btnstate := sdl.GetMouseState() 200 | c := w.FindControl(mx, my) 201 | if c == nil { 202 | return c, 0, 0, t.X, t.Y, btnstate 203 | } 204 | cx, cy := mx-c.GetRect().X, my-c.GetRect().Y 205 | return c, cx, cy, t.X, t.Y, btnstate 206 | } 207 | --------------------------------------------------------------------------------