You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

748 line
32 KiB

  1. /*******************************************************************************************
  2. *
  3. * raylib [text] example - Draw 3d
  4. *
  5. * NOTE: Draw a 2D text in 3D space, each letter is drawn in a quad (or 2 quads if backface is set)
  6. * where the texture coodinates of each quad map to the texture coordinates of the glyphs
  7. * inside the font texture.
  8. *
  9. * A more efficient approach, i believe, would be to render the text in a render texture and
  10. * map that texture to a plane and render that, or maybe a shader but my method allows more
  11. * flexibility...for example to change position of each letter individually to make somethink
  12. * like a wavy text effect.
  13. *
  14. * Special thanks to:
  15. * @Nighten for the DrawTextStyle() code https://github.com/NightenDushi/Raylib_DrawTextStyle
  16. * Chris Camacho (codifies - http://bedroomcoders.co.uk/) for the alpha discard shader
  17. *
  18. * Example originally created with raylib 3.5, last time updated with raylib 4.0
  19. *
  20. * Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
  21. *
  22. * Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
  23. * BSD-like license that allows static linking with closed source software
  24. *
  25. * Copyright (c) 2021-2023 Vlad Adrian (@demizdor)
  26. *
  27. ********************************************************************************************/
  28. #include "raylib.h"
  29. #include "rlgl.h"
  30. #include <stddef.h> // Required for: NULL
  31. #include <math.h> // Required for: sinf()
  32. // To make it work with the older RLGL module just comment the line below
  33. #define RAYLIB_NEW_RLGL
  34. //--------------------------------------------------------------------------------------
  35. // Globals
  36. //--------------------------------------------------------------------------------------
  37. #define LETTER_BOUNDRY_SIZE 0.25f
  38. #define TEXT_MAX_LAYERS 32
  39. #define LETTER_BOUNDRY_COLOR VIOLET
  40. bool SHOW_LETTER_BOUNDRY = false;
  41. bool SHOW_TEXT_BOUNDRY = false;
  42. //--------------------------------------------------------------------------------------
  43. // Data Types definition
  44. //--------------------------------------------------------------------------------------
  45. // Configuration structure for waving the text
  46. typedef struct WaveTextConfig {
  47. Vector3 waveRange;
  48. Vector3 waveSpeed;
  49. Vector3 waveOffset;
  50. } WaveTextConfig;
  51. //--------------------------------------------------------------------------------------
  52. // Module Functions Declaration
  53. //--------------------------------------------------------------------------------------
  54. // Draw a codepoint in 3D space
  55. static void DrawTextCodepoint3D(Font font, int codepoint, Vector3 position, float fontSize, bool backface, Color tint);
  56. // Draw a 2D text in 3D space
  57. static void DrawText3D(Font font, const char *text, Vector3 position, float fontSize, float fontSpacing, float lineSpacing, bool backface, Color tint);
  58. // Measure a text in 3D. For some reason `MeasureTextEx()` just doesn't seem to work so i had to use this instead.
  59. static Vector3 MeasureText3D(Font font, const char *text, float fontSize, float fontSpacing, float lineSpacing);
  60. // Draw a 2D text in 3D space and wave the parts that start with `~~` and end with `~~`.
  61. // This is a modified version of the original code by @Nighten found here https://github.com/NightenDushi/Raylib_DrawTextStyle
  62. static void DrawTextWave3D(Font font, const char *text, Vector3 position, float fontSize, float fontSpacing, float lineSpacing, bool backface, WaveTextConfig *config, float time, Color tint);
  63. // Measure a text in 3D ignoring the `~~` chars.
  64. static Vector3 MeasureTextWave3D(Font font, const char *text, float fontSize, float fontSpacing, float lineSpacing);
  65. // Generates a nice color with a random hue
  66. static Color GenerateRandomColor(float s, float v);
  67. //------------------------------------------------------------------------------------
  68. // Program main entry point
  69. //------------------------------------------------------------------------------------
  70. int main(void)
  71. {
  72. // Initialization
  73. //--------------------------------------------------------------------------------------
  74. const int screenWidth = 800;
  75. const int screenHeight = 450;
  76. SetConfigFlags(FLAG_MSAA_4X_HINT|FLAG_VSYNC_HINT);
  77. InitWindow(screenWidth, screenHeight, "raylib [text] example - draw 2D text in 3D");
  78. bool spin = true; // Spin the camera?
  79. bool multicolor = false; // Multicolor mode
  80. // Define the camera to look into our 3d world
  81. Camera3D camera = { 0 };
  82. camera.position = (Vector3){ -10.0f, 15.0f, -10.0f }; // Camera position
  83. camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
  84. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
  85. camera.fovy = 45.0f; // Camera field-of-view Y
  86. camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
  87. SetCameraMode(camera, CAMERA_ORBITAL);
  88. Vector3 cubePosition = { 0.0f, 1.0f, 0.0f };
  89. Vector3 cubeSize = { 2.0f, 2.0f, 2.0f };
  90. SetTargetFPS(60); // Set our game to run at 60 frames-per-second
  91. // Use the default font
  92. Font font = GetFontDefault();
  93. float fontSize = 8.0f;
  94. float fontSpacing = 0.5f;
  95. float lineSpacing = -1.0f;
  96. // Set the text (using markdown!)
  97. char text[64] = "Hello ~~World~~ in 3D!";
  98. Vector3 tbox = {0};
  99. int layers = 1;
  100. int quads = 0;
  101. float layerDistance = 0.01f;
  102. WaveTextConfig wcfg;
  103. wcfg.waveSpeed.x = wcfg.waveSpeed.y = 3.0f; wcfg.waveSpeed.z = 0.5f;
  104. wcfg.waveOffset.x = wcfg.waveOffset.y = wcfg.waveOffset.z = 0.35f;
  105. wcfg.waveRange.x = wcfg.waveRange.y = wcfg.waveRange.z = 0.45f;
  106. float time = 0.0f;
  107. // Setup a light and dark color
  108. Color light = MAROON;
  109. Color dark = RED;
  110. // Load the alpha discard shader
  111. Shader alphaDiscard = LoadShader(NULL, "resources/shaders/glsl330/alpha_discard.fs");
  112. // Array filled with multiple random colors (when multicolor mode is set)
  113. Color multi[TEXT_MAX_LAYERS] = {0};
  114. //--------------------------------------------------------------------------------------
  115. // Main game loop
  116. while (!WindowShouldClose()) // Detect window close button or ESC key
  117. {
  118. // Update
  119. //----------------------------------------------------------------------------------
  120. UpdateCamera(&camera);
  121. // Handle font files dropped
  122. if (IsFileDropped())
  123. {
  124. FilePathList droppedFiles = LoadDroppedFiles();
  125. // NOTE: We only support first ttf file dropped
  126. if (IsFileExtension(droppedFiles.paths[0], ".ttf"))
  127. {
  128. UnloadFont(font);
  129. font = LoadFontEx(droppedFiles.paths[0], fontSize, 0, 0);
  130. }
  131. else if (IsFileExtension(droppedFiles.paths[0], ".fnt"))
  132. {
  133. UnloadFont(font);
  134. font = LoadFont(droppedFiles.paths[0]);
  135. fontSize = font.baseSize;
  136. }
  137. UnloadDroppedFiles(droppedFiles); // Unload filepaths from memory
  138. }
  139. // Handle Events
  140. if (IsKeyPressed(KEY_F1)) SHOW_LETTER_BOUNDRY = !SHOW_LETTER_BOUNDRY;
  141. if (IsKeyPressed(KEY_F2)) SHOW_TEXT_BOUNDRY = !SHOW_TEXT_BOUNDRY;
  142. if (IsKeyPressed(KEY_F3))
  143. {
  144. // Handle camera change
  145. spin = !spin;
  146. // we need to reset the camera when changing modes
  147. camera = (Camera3D){ 0 };
  148. camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
  149. camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
  150. camera.fovy = 45.0f; // Camera field-of-view Y
  151. camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
  152. if (spin)
  153. {
  154. camera.position = (Vector3){ -10.0f, 15.0f, -10.0f }; // Camera position
  155. SetCameraMode(camera, CAMERA_ORBITAL);
  156. }
  157. else
  158. {
  159. camera.position = (Vector3){ 10.0f, 10.0f, -10.0f }; // Camera position
  160. SetCameraMode(camera, CAMERA_FREE);
  161. }
  162. }
  163. // Handle clicking the cube
  164. if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
  165. {
  166. Ray ray = GetMouseRay(GetMousePosition(), camera);
  167. // Check collision between ray and box
  168. RayCollision collision = GetRayCollisionBox(ray,
  169. (BoundingBox){(Vector3){ cubePosition.x - cubeSize.x/2, cubePosition.y - cubeSize.y/2, cubePosition.z - cubeSize.z/2 },
  170. (Vector3){ cubePosition.x + cubeSize.x/2, cubePosition.y + cubeSize.y/2, cubePosition.z + cubeSize.z/2 }});
  171. if (collision.hit)
  172. {
  173. // Generate new random colors
  174. light = GenerateRandomColor(0.5f, 0.78f);
  175. dark = GenerateRandomColor(0.4f, 0.58f);
  176. }
  177. }
  178. // Handle text layers changes
  179. if (IsKeyPressed(KEY_HOME)) { if (layers > 1) --layers; }
  180. else if (IsKeyPressed(KEY_END)) { if (layers < TEXT_MAX_LAYERS) ++layers; }
  181. // Handle text changes
  182. if (IsKeyPressed(KEY_LEFT)) fontSize -= 0.5f;
  183. else if (IsKeyPressed(KEY_RIGHT)) fontSize += 0.5f;
  184. else if (IsKeyPressed(KEY_UP)) fontSpacing -= 0.1f;
  185. else if (IsKeyPressed(KEY_DOWN)) fontSpacing += 0.1f;
  186. else if (IsKeyPressed(KEY_PAGE_UP)) lineSpacing -= 0.1f;
  187. else if (IsKeyPressed(KEY_PAGE_DOWN)) lineSpacing += 0.1f;
  188. else if (IsKeyDown(KEY_INSERT)) layerDistance -= 0.001f;
  189. else if (IsKeyDown(KEY_DELETE)) layerDistance += 0.001f;
  190. else if (IsKeyPressed(KEY_TAB))
  191. {
  192. multicolor = !multicolor; // Enable /disable multicolor mode
  193. if (multicolor)
  194. {
  195. // Fill color array with random colors
  196. for (int i = 0; i < TEXT_MAX_LAYERS; ++i)
  197. {
  198. multi[i] = GenerateRandomColor(0.5f, 0.8f);
  199. multi[i].a = GetRandomValue(0, 255);
  200. }
  201. }
  202. }
  203. // Handle text input
  204. int ch = GetCharPressed();
  205. if (IsKeyPressed(KEY_BACKSPACE))
  206. {
  207. // Remove last char
  208. int len = TextLength(text);
  209. if (len > 0) text[len - 1] = '\0';
  210. }
  211. else if (IsKeyPressed(KEY_ENTER))
  212. {
  213. // handle newline
  214. int len = TextLength(text);
  215. if (len < sizeof(text) - 1)
  216. {
  217. text[len] = '\n';
  218. text[len+1] ='\0';
  219. }
  220. }
  221. else
  222. {
  223. // append only printable chars
  224. int len = TextLength(text);
  225. if (len < sizeof(text) - 1)
  226. {
  227. text[len] = ch;
  228. text[len+1] ='\0';
  229. }
  230. }
  231. // Measure 3D text so we can center it
  232. tbox = MeasureTextWave3D(font, text, fontSize, fontSpacing, lineSpacing);
  233. quads = 0; // Reset quad counter
  234. time += GetFrameTime(); // Update timer needed by `DrawTextWave3D()`
  235. //----------------------------------------------------------------------------------
  236. // Draw
  237. //----------------------------------------------------------------------------------
  238. BeginDrawing();
  239. ClearBackground(RAYWHITE);
  240. BeginMode3D(camera);
  241. DrawCubeV(cubePosition, cubeSize, dark);
  242. DrawCubeWires(cubePosition, 2.1f, 2.1f, 2.1f, light);
  243. DrawGrid(10, 2.0f);
  244. // Use a shader to handle the depth buffer issue with transparent textures
  245. // NOTE: more info at https://bedroomcoders.co.uk/raylib-billboards-advanced-use/
  246. BeginShaderMode(alphaDiscard);
  247. // Draw the 3D text above the red cube
  248. rlPushMatrix();
  249. rlRotatef(90.0f, 1.0f, 0.0f, 0.0f);
  250. rlRotatef(90.0f, 0.0f, 0.0f, -1.0f);
  251. for (int i = 0; i < layers; ++i)
  252. {
  253. Color clr = light;
  254. if (multicolor) clr = multi[i];
  255. DrawTextWave3D(font, text, (Vector3){ -tbox.x/2.0f, layerDistance*i, -4.5f }, fontSize, fontSpacing, lineSpacing, true, &wcfg, time, clr);
  256. }
  257. // Draw the text boundry if set
  258. if (SHOW_TEXT_BOUNDRY) DrawCubeWiresV((Vector3){ 0.0f, 0.0f, -4.5f + tbox.z/2 }, tbox, dark);
  259. rlPopMatrix();
  260. // Don't draw the letter boundries for the 3D text below
  261. bool slb = SHOW_LETTER_BOUNDRY;
  262. SHOW_LETTER_BOUNDRY = false;
  263. // Draw 3D options (use default font)
  264. //-------------------------------------------------------------------------
  265. rlPushMatrix();
  266. rlRotatef(180.0f, 0.0f, 1.0f, 0.0f);
  267. char *opt = (char *)TextFormat("< SIZE: %2.1f >", fontSize);
  268. quads += TextLength(opt);
  269. Vector3 m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
  270. Vector3 pos = { -m.x/2.0f, 0.01f, 2.0f};
  271. DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE);
  272. pos.z += 0.5f + m.z;
  273. opt = (char *)TextFormat("< SPACING: %2.1f >", fontSpacing);
  274. quads += TextLength(opt);
  275. m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
  276. pos.x = -m.x/2.0f;
  277. DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE);
  278. pos.z += 0.5f + m.z;
  279. opt = (char *)TextFormat("< LINE: %2.1f >", lineSpacing);
  280. quads += TextLength(opt);
  281. m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
  282. pos.x = -m.x/2.0f;
  283. DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE);
  284. pos.z += 1.0f + m.z;
  285. opt = (char *)TextFormat("< LBOX: %3s >", slb? "ON" : "OFF");
  286. quads += TextLength(opt);
  287. m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
  288. pos.x = -m.x/2.0f;
  289. DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, RED);
  290. pos.z += 0.5f + m.z;
  291. opt = (char *)TextFormat("< TBOX: %3s >", SHOW_TEXT_BOUNDRY? "ON" : "OFF");
  292. quads += TextLength(opt);
  293. m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
  294. pos.x = -m.x/2.0f;
  295. DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, RED);
  296. pos.z += 0.5f + m.z;
  297. opt = (char *)TextFormat("< LAYER DISTANCE: %.3f >", layerDistance);
  298. quads += TextLength(opt);
  299. m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
  300. pos.x = -m.x/2.0f;
  301. DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, DARKPURPLE);
  302. rlPopMatrix();
  303. //-------------------------------------------------------------------------
  304. // Draw 3D info text (use default font)
  305. //-------------------------------------------------------------------------
  306. opt = "All the text displayed here is in 3D";
  307. quads += 36;
  308. m = MeasureText3D(GetFontDefault(), opt, 10.0f, 0.5f, 0.0f);
  309. pos = (Vector3){-m.x/2.0f, 0.01f, 2.0f};
  310. DrawText3D(GetFontDefault(), opt, pos, 10.0f, 0.5f, 0.0f, false, DARKBLUE);
  311. pos.z += 1.5f + m.z;
  312. opt = "press [Left]/[Right] to change the font size";
  313. quads += 44;
  314. m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
  315. pos.x = -m.x/2.0f;
  316. DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
  317. pos.z += 0.5f + m.z;
  318. opt = "press [Up]/[Down] to change the font spacing";
  319. quads += 44;
  320. m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
  321. pos.x = -m.x/2.0f;
  322. DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
  323. pos.z += 0.5f + m.z;
  324. opt = "press [PgUp]/[PgDown] to change the line spacing";
  325. quads += 48;
  326. m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
  327. pos.x = -m.x/2.0f;
  328. DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
  329. pos.z += 0.5f + m.z;
  330. opt = "press [F1] to toggle the letter boundry";
  331. quads += 39;
  332. m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
  333. pos.x = -m.x/2.0f;
  334. DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
  335. pos.z += 0.5f + m.z;
  336. opt = "press [F2] to toggle the text boundry";
  337. quads += 37;
  338. m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
  339. pos.x = -m.x/2.0f;
  340. DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
  341. //-------------------------------------------------------------------------
  342. SHOW_LETTER_BOUNDRY = slb;
  343. EndShaderMode();
  344. EndMode3D();
  345. // Draw 2D info text & stats
  346. //-------------------------------------------------------------------------
  347. DrawText("Drag & drop a font file to change the font!\nType something, see what happens!\n\n"
  348. "Press [F3] to toggle the camera", 10, 35, 10, BLACK);
  349. quads += TextLength(text)*2*layers;
  350. char *tmp = (char *)TextFormat("%2i layer(s) | %s camera | %4i quads (%4i verts)", layers, spin? "ORBITAL" : "FREE", quads, quads*4);
  351. int width = MeasureText(tmp, 10);
  352. DrawText(tmp, screenWidth - 20 - width, 10, 10, DARKGREEN);
  353. tmp = "[Home]/[End] to add/remove 3D text layers";
  354. width = MeasureText(tmp, 10);
  355. DrawText(tmp, screenWidth - 20 - width, 25, 10, DARKGRAY);
  356. tmp = "[Insert]/[Delete] to increase/decrease distance between layers";
  357. width = MeasureText(tmp, 10);
  358. DrawText(tmp, screenWidth - 20 - width, 40, 10, DARKGRAY);
  359. tmp = "click the [CUBE] for a random color";
  360. width = MeasureText(tmp, 10);
  361. DrawText(tmp, screenWidth - 20 - width, 55, 10, DARKGRAY);
  362. tmp = "[Tab] to toggle multicolor mode";
  363. width = MeasureText(tmp, 10);
  364. DrawText(tmp, screenWidth - 20 - width, 70, 10, DARKGRAY);
  365. //-------------------------------------------------------------------------
  366. DrawFPS(10, 10);
  367. EndDrawing();
  368. //----------------------------------------------------------------------------------
  369. }
  370. // De-Initialization
  371. //--------------------------------------------------------------------------------------
  372. UnloadFont(font);
  373. CloseWindow(); // Close window and OpenGL context
  374. //--------------------------------------------------------------------------------------
  375. return 0;
  376. }
  377. //--------------------------------------------------------------------------------------
  378. // Module Functions Definitions
  379. //--------------------------------------------------------------------------------------
  380. // Draw codepoint at specified position in 3D space
  381. static void DrawTextCodepoint3D(Font font, int codepoint, Vector3 position, float fontSize, bool backface, Color tint)
  382. {
  383. // Character index position in sprite font
  384. // NOTE: In case a codepoint is not available in the font, index returned points to '?'
  385. int index = GetGlyphIndex(font, codepoint);
  386. float scale = fontSize/(float)font.baseSize;
  387. // Character destination rectangle on screen
  388. // NOTE: We consider charsPadding on drawing
  389. position.x += (float)(font.glyphs[index].offsetX - font.glyphPadding)/(float)font.baseSize*scale;
  390. position.z += (float)(font.glyphs[index].offsetY - font.glyphPadding)/(float)font.baseSize*scale;
  391. // Character source rectangle from font texture atlas
  392. // NOTE: We consider chars padding when drawing, it could be required for outline/glow shader effects
  393. Rectangle srcRec = { font.recs[index].x - (float)font.glyphPadding, font.recs[index].y - (float)font.glyphPadding,
  394. font.recs[index].width + 2.0f*font.glyphPadding, font.recs[index].height + 2.0f*font.glyphPadding };
  395. float width = (float)(font.recs[index].width + 2.0f*font.glyphPadding)/(float)font.baseSize*scale;
  396. float height = (float)(font.recs[index].height + 2.0f*font.glyphPadding)/(float)font.baseSize*scale;
  397. if (font.texture.id > 0)
  398. {
  399. const float x = 0.0f;
  400. const float y = 0.0f;
  401. const float z = 0.0f;
  402. // normalized texture coordinates of the glyph inside the font texture (0.0f -> 1.0f)
  403. const float tx = srcRec.x/font.texture.width;
  404. const float ty = srcRec.y/font.texture.height;
  405. const float tw = (srcRec.x+srcRec.width)/font.texture.width;
  406. const float th = (srcRec.y+srcRec.height)/font.texture.height;
  407. if (SHOW_LETTER_BOUNDRY) DrawCubeWiresV((Vector3){ position.x + width/2, position.y, position.z + height/2}, (Vector3){ width, LETTER_BOUNDRY_SIZE, height }, LETTER_BOUNDRY_COLOR);
  408. rlCheckRenderBatchLimit(4 + 4*backface);
  409. rlSetTexture(font.texture.id);
  410. rlPushMatrix();
  411. rlTranslatef(position.x, position.y, position.z);
  412. rlBegin(RL_QUADS);
  413. rlColor4ub(tint.r, tint.g, tint.b, tint.a);
  414. // Front Face
  415. rlNormal3f(0.0f, 1.0f, 0.0f); // Normal Pointing Up
  416. rlTexCoord2f(tx, ty); rlVertex3f(x, y, z); // Top Left Of The Texture and Quad
  417. rlTexCoord2f(tx, th); rlVertex3f(x, y, z + height); // Bottom Left Of The Texture and Quad
  418. rlTexCoord2f(tw, th); rlVertex3f(x + width, y, z + height); // Bottom Right Of The Texture and Quad
  419. rlTexCoord2f(tw, ty); rlVertex3f(x + width, y, z); // Top Right Of The Texture and Quad
  420. if (backface)
  421. {
  422. // Back Face
  423. rlNormal3f(0.0f, -1.0f, 0.0f); // Normal Pointing Down
  424. rlTexCoord2f(tx, ty); rlVertex3f(x, y, z); // Top Right Of The Texture and Quad
  425. rlTexCoord2f(tw, ty); rlVertex3f(x + width, y, z); // Top Left Of The Texture and Quad
  426. rlTexCoord2f(tw, th); rlVertex3f(x + width, y, z + height); // Bottom Left Of The Texture and Quad
  427. rlTexCoord2f(tx, th); rlVertex3f(x, y, z + height); // Bottom Right Of The Texture and Quad
  428. }
  429. rlEnd();
  430. rlPopMatrix();
  431. rlSetTexture(0);
  432. }
  433. }
  434. // Draw a 2D text in 3D space
  435. static void DrawText3D(Font font, const char *text, Vector3 position, float fontSize, float fontSpacing, float lineSpacing, bool backface, Color tint)
  436. {
  437. int length = TextLength(text); // Total length in bytes of the text, scanned by codepoints in loop
  438. float textOffsetY = 0.0f; // Offset between lines (on line break '\n')
  439. float textOffsetX = 0.0f; // Offset X to next character to draw
  440. float scale = fontSize/(float)font.baseSize;
  441. for (int i = 0; i < length;)
  442. {
  443. // Get next codepoint from byte string and glyph index in font
  444. int codepointByteCount = 0;
  445. int codepoint = GetCodepoint(&text[i], &codepointByteCount);
  446. int index = GetGlyphIndex(font, codepoint);
  447. // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  448. // but we need to draw all of the bad bytes using the '?' symbol moving one byte
  449. if (codepoint == 0x3f) codepointByteCount = 1;
  450. if (codepoint == '\n')
  451. {
  452. // NOTE: Fixed line spacing of 1.5 line-height
  453. // TODO: Support custom line spacing defined by user
  454. textOffsetY += scale + lineSpacing/(float)font.baseSize*scale;
  455. textOffsetX = 0.0f;
  456. }
  457. else
  458. {
  459. if ((codepoint != ' ') && (codepoint != '\t'))
  460. {
  461. DrawTextCodepoint3D(font, codepoint, (Vector3){ position.x + textOffsetX, position.y, position.z + textOffsetY }, fontSize, backface, tint);
  462. }
  463. if (font.glyphs[index].advanceX == 0) textOffsetX += (float)(font.recs[index].width + fontSpacing)/(float)font.baseSize*scale;
  464. else textOffsetX += (float)(font.glyphs[index].advanceX + fontSpacing)/(float)font.baseSize*scale;
  465. }
  466. i += codepointByteCount; // Move text bytes counter to next codepoint
  467. }
  468. }
  469. // Measure a text in 3D. For some reason `MeasureTextEx()` just doesn't seem to work so i had to use this instead.
  470. static Vector3 MeasureText3D(Font font, const char* text, float fontSize, float fontSpacing, float lineSpacing)
  471. {
  472. int len = TextLength(text);
  473. int tempLen = 0; // Used to count longer text line num chars
  474. int lenCounter = 0;
  475. float tempTextWidth = 0.0f; // Used to count longer text line width
  476. float scale = fontSize/(float)font.baseSize;
  477. float textHeight = scale;
  478. float textWidth = 0.0f;
  479. int letter = 0; // Current character
  480. int index = 0; // Index position in sprite font
  481. for (int i = 0; i < len; i++)
  482. {
  483. lenCounter++;
  484. int next = 0;
  485. letter = GetCodepoint(&text[i], &next);
  486. index = GetGlyphIndex(font, letter);
  487. // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  488. // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set next = 1
  489. if (letter == 0x3f) next = 1;
  490. i += next - 1;
  491. if (letter != '\n')
  492. {
  493. if (font.glyphs[index].advanceX != 0) textWidth += (font.glyphs[index].advanceX+fontSpacing)/(float)font.baseSize*scale;
  494. else textWidth += (font.recs[index].width + font.glyphs[index].offsetX)/(float)font.baseSize*scale;
  495. }
  496. else
  497. {
  498. if (tempTextWidth < textWidth) tempTextWidth = textWidth;
  499. lenCounter = 0;
  500. textWidth = 0.0f;
  501. textHeight += scale + lineSpacing/(float)font.baseSize*scale;
  502. }
  503. if (tempLen < lenCounter) tempLen = lenCounter;
  504. }
  505. if (tempTextWidth < textWidth) tempTextWidth = textWidth;
  506. Vector3 vec = { 0 };
  507. vec.x = tempTextWidth + (float)((tempLen - 1)*fontSpacing/(float)font.baseSize*scale); // Adds chars spacing to measure
  508. vec.y = 0.25f;
  509. vec.z = textHeight;
  510. return vec;
  511. }
  512. // Draw a 2D text in 3D space and wave the parts that start with `~~` and end with `~~`.
  513. // This is a modified version of the original code by @Nighten found here https://github.com/NightenDushi/Raylib_DrawTextStyle
  514. static void DrawTextWave3D(Font font, const char *text, Vector3 position, float fontSize, float fontSpacing, float lineSpacing, bool backface, WaveTextConfig* config, float time, Color tint)
  515. {
  516. int length = TextLength(text); // Total length in bytes of the text, scanned by codepoints in loop
  517. float textOffsetY = 0.0f; // Offset between lines (on line break '\n')
  518. float textOffsetX = 0.0f; // Offset X to next character to draw
  519. float scale = fontSize/(float)font.baseSize;
  520. bool wave = false;
  521. for (int i = 0, k = 0; i < length; ++k)
  522. {
  523. // Get next codepoint from byte string and glyph index in font
  524. int codepointByteCount = 0;
  525. int codepoint = GetCodepoint(&text[i], &codepointByteCount);
  526. int index = GetGlyphIndex(font, codepoint);
  527. // NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  528. // but we need to draw all of the bad bytes using the '?' symbol moving one byte
  529. if (codepoint == 0x3f) codepointByteCount = 1;
  530. if (codepoint == '\n')
  531. {
  532. // NOTE: Fixed line spacing of 1.5 line-height
  533. // TODO: Support custom line spacing defined by user
  534. textOffsetY += scale + lineSpacing/(float)font.baseSize*scale;
  535. textOffsetX = 0.0f;
  536. k = 0;
  537. }
  538. else if (codepoint == '~')
  539. {
  540. if (GetCodepoint(&text[i+1], &codepointByteCount) == '~')
  541. {
  542. codepointByteCount += 1;
  543. wave = !wave;
  544. }
  545. }
  546. else
  547. {
  548. if ((codepoint != ' ') && (codepoint != '\t'))
  549. {
  550. Vector3 pos = position;
  551. if (wave) // Apply the wave effect
  552. {
  553. pos.x += sinf(time*config->waveSpeed.x-k*config->waveOffset.x)*config->waveRange.x;
  554. pos.y += sinf(time*config->waveSpeed.y-k*config->waveOffset.y)*config->waveRange.y;
  555. pos.z += sinf(time*config->waveSpeed.z-k*config->waveOffset.z)*config->waveRange.z;
  556. }
  557. DrawTextCodepoint3D(font, codepoint, (Vector3){ pos.x + textOffsetX, pos.y, pos.z + textOffsetY }, fontSize, backface, tint);
  558. }
  559. if (font.glyphs[index].advanceX == 0) textOffsetX += (float)(font.recs[index].width + fontSpacing)/(float)font.baseSize*scale;
  560. else textOffsetX += (float)(font.glyphs[index].advanceX + fontSpacing)/(float)font.baseSize*scale;
  561. }
  562. i += codepointByteCount; // Move text bytes counter to next codepoint
  563. }
  564. }
  565. // Measure a text in 3D ignoring the `~~` chars.
  566. static Vector3 MeasureTextWave3D(Font font, const char* text, float fontSize, float fontSpacing, float lineSpacing)
  567. {
  568. int len = TextLength(text);
  569. int tempLen = 0; // Used to count longer text line num chars
  570. int lenCounter = 0;
  571. float tempTextWidth = 0.0f; // Used to count longer text line width
  572. float scale = fontSize/(float)font.baseSize;
  573. float textHeight = scale;
  574. float textWidth = 0.0f;
  575. int letter = 0; // Current character
  576. int index = 0; // Index position in sprite font
  577. for (int i = 0; i < len; i++)
  578. {
  579. lenCounter++;
  580. int next = 0;
  581. letter = GetCodepoint(&text[i], &next);
  582. index = GetGlyphIndex(font, letter);
  583. // NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
  584. // but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set next = 1
  585. if (letter == 0x3f) next = 1;
  586. i += next - 1;
  587. if (letter != '\n')
  588. {
  589. if (letter == '~' && GetCodepoint(&text[i+1], &next) == '~')
  590. {
  591. i++;
  592. }
  593. else
  594. {
  595. if (font.glyphs[index].advanceX != 0) textWidth += (font.glyphs[index].advanceX+fontSpacing)/(float)font.baseSize*scale;
  596. else textWidth += (font.recs[index].width + font.glyphs[index].offsetX)/(float)font.baseSize*scale;
  597. }
  598. }
  599. else
  600. {
  601. if (tempTextWidth < textWidth) tempTextWidth = textWidth;
  602. lenCounter = 0;
  603. textWidth = 0.0f;
  604. textHeight += scale + lineSpacing/(float)font.baseSize*scale;
  605. }
  606. if (tempLen < lenCounter) tempLen = lenCounter;
  607. }
  608. if (tempTextWidth < textWidth) tempTextWidth = textWidth;
  609. Vector3 vec = { 0 };
  610. vec.x = tempTextWidth + (float)((tempLen - 1)*fontSpacing/(float)font.baseSize*scale); // Adds chars spacing to measure
  611. vec.y = 0.25f;
  612. vec.z = textHeight;
  613. return vec;
  614. }
  615. // Generates a nice color with a random hue
  616. static Color GenerateRandomColor(float s, float v)
  617. {
  618. const float Phi = 0.618033988749895f; // Golden ratio conjugate
  619. float h = GetRandomValue(0, 360);
  620. h = fmodf((h + h*Phi), 360.0f);
  621. return ColorFromHSV(h, s, v);
  622. }