1 /** renderable text */ 2 3 module re.gfx.text; 4 5 import re.ecs; 6 import re.math; 7 import re.ng.diag; 8 import std.string; 9 static import raylib; 10 11 /// renderable text 12 class Text : Component, Renderable2D { 13 private string _text; 14 /// text font 15 public raylib.Font font; 16 /// font size 17 public int size; 18 /// text color 19 public raylib.Color color; 20 private Vector2 _text_size; 21 private Vector2 _origin; 22 /// default font size 23 public enum default_size = 10; 24 private Align _horiz_align; 25 private Align _vert_align; 26 27 /// alignment style 28 public enum Align { 29 /// left or top 30 Close, 31 /// center 32 Center, 33 /// right or bottom 34 Far 35 } 36 37 /// create a new text 38 this(raylib.Font font, string text, int size, raylib.Color color) { 39 import re.core : Core; 40 41 this._text = text; 42 this.font = font; 43 this.size = size; 44 this.color = color; 45 update_dimens(); 46 47 raylib.SetTextureFilter(font.texture, Core.default_filter_mode); 48 } 49 50 /// gets text string 51 @property string text() { 52 return _text; 53 } 54 55 /// sets text string 56 @property string text(string value) { 57 _text = value; 58 update_dimens(); 59 return value; 60 } 61 62 @property Rectangle bounds() { 63 return Bounds.calculate(entity.transform, _origin, _text_size.x, _text_size.y); 64 } 65 66 @property private int spacing() { 67 return size / default_size; 68 } 69 70 /// default font (builtin to raylib) 71 @property public static raylib.Font default_font() { 72 return raylib.GetFontDefault(); 73 } 74 75 private void update_dimens() { 76 _text_size = raylib.MeasureTextEx(font, toStringz(_text), size, spacing); 77 // calculate origin 78 auto ori_x = 0.0; 79 auto ori_y = 0.0; 80 if (_horiz_align == Align.Close) 81 ori_x = 0; 82 else if (_horiz_align == Align.Center) 83 ori_x = _text_size.x / 2; 84 else 85 ori_x = _text_size.x; 86 if (_vert_align == Align.Close) 87 ori_y = 0; 88 else if (_vert_align == Align.Center) 89 ori_y = _text_size.y / 2; 90 else 91 ori_y = _text_size.y; 92 _origin = Vector2(ori_x, ori_y); 93 } 94 95 public void set_align(Align horiz, Align vert) { 96 _horiz_align = horiz; 97 _vert_align = vert; 98 update_dimens(); 99 } 100 101 void render() { 102 raylib.DrawTextEx(font, toStringz(_text), entity.position2 - _origin, size, spacing, color); 103 } 104 105 void debug_render() { 106 DebugRender.default_debug_render(this); 107 } 108 }