FontRenderer.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include "rendering/FontRenderer.h"
  2. #include "gaming-core/rendering/Attributes.h"
  3. #include "gaming-core/utils/Buffer.h"
  4. #include "gaming-core/utils/Color.h"
  5. FontRenderer::FontRenderer() : activeTex(0), scale(1) {
  6. tex.add("resources/font8x8.png");
  7. tex.add("resources/font16x16.png");
  8. tex.add("resources/font24x24.png");
  9. vertexBuffer.setAttributes(
  10. Attributes().addFloat(2).addFloat(2).addColor4());
  11. vertexBuffer.setStreamData(256 * 4 * sizeof(float) * 8);
  12. }
  13. float FontRenderer::drawString(float x, float y, const char* text) {
  14. const int maxIndex = 256;
  15. Buffer buffer(sizeof(float) * maxIndex * 4 * 8);
  16. int index = 0;
  17. Color4 color(0xFF, 0xFF, 0xFF, 0xFF);
  18. float addX = 6.0f * scale;
  19. float addY = 8.0f * scale;
  20. while(text[index] != '\0' && index < maxIndex) {
  21. char32_t c = text[index];
  22. if(c > 128 && index + 1 < maxIndex && text[index + 1] != '\0') {
  23. index++;
  24. c = (text[index] & 0x3F) | ((c & 0x1F) << 6);
  25. }
  26. if(c == '&') {
  27. if(text[index + 1] == '\0' || text[index + 2] == '\0' ||
  28. text[index + 3] == '\0') {
  29. break;
  30. }
  31. color[0] = ((text[index + 1] - '0') * 255) / 9;
  32. color[1] = ((text[index + 2] - '0') * 255) / 9;
  33. color[2] = ((text[index + 3] - '0') * 255) / 9;
  34. index += 4;
  35. continue;
  36. }
  37. float minX = (c & 0xF) * (1.0f / 16.0f) + 1.0f / 128.0f;
  38. float minY = (c >> 4) * (1.0f / 16.0f);
  39. float maxX = minX + (1.0f / 16.0f) - 2.0f / 128.0f;
  40. float maxY = minY + (1.0f / 16.0f);
  41. buffer.add(x).add(y).add(minX).add(minY).add(color);
  42. buffer.add(x).add(y + addY).add(minX).add(maxY).add(color);
  43. buffer.add(x + addX).add(y).add(maxX).add(minY).add(color);
  44. buffer.add(x + addX).add(y + addY).add(maxX).add(maxY).add(color);
  45. x += addX;
  46. index++;
  47. }
  48. tex[activeTex].bindTo(0);
  49. vertexBuffer.updateData(0, buffer.getLength(), buffer);
  50. vertexBuffer.drawStrip(buffer.getLength() /
  51. (4 * sizeof(float) + sizeof(Color4)));
  52. return y + addY;
  53. }
  54. void FontRenderer::setSize(int size) {
  55. if(size == 1 || size == 2) {
  56. activeTex = size;
  57. scale = size + 1;
  58. } else {
  59. activeTex = 0;
  60. scale = 1;
  61. }
  62. }