gegl_button.pas 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. (*
  2. * Copyright (c) 2021 SSW
  3. *
  4. * This software is provided 'as-is', without any express or
  5. * implied warranty. In no event will the authors be held
  6. * liable for any damages arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute
  10. * it freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented;
  13. * you must not claim that you wrote the original software.
  14. * If you use this software in a product, an acknowledgment
  15. * in the product documentation would be appreciated but
  16. * is not required.
  17. *
  18. * 2. Altered source versions must be plainly marked as such,
  19. * and must not be misrepresented as being the original software.
  20. *
  21. * 3. This notice may not be removed or altered from any
  22. * source distribution.
  23. *)
  24. // Модуль для создания кнопок и работы с ними? Или просто создание?
  25. // Мы не делаем здесь сами кнопки. Мы делаем их текстуры. Эти текстуры уже
  26. // будут использоваться в кнопках.
  27. unit gegl_button;
  28. {$I zgl_config.cfg}
  29. interface
  30. uses
  31. zgl_screen,
  32. zgl_primitives_2d,
  33. zgl_primitives_2dEX,
  34. zgl_textures,
  35. zgl_text,
  36. zgl_window,
  37. zgl_types,
  38. gegl_color,
  39. gegl_Types;
  40. // Rus: создаём кнопку. Кнопка создаётся от меню. Но так же кнопки могут быть в игре.
  41. // Данные кнопки с двумя изображениями. Нажато/отжато. Если работать с текстурой
  42. // где используется изображения для нескольких кнопок, то надо работать с
  43. // фреймами данной текстуры.
  44. // Eng:
  45. function AddButton(x, y, w, h: Single; Texture: zglPTexture; passive: Boolean = False): LongWord;
  46. (* решено было сделать создание кнопки, но в дальнейшем просто перевести в текстуру отрисованное.
  47. *)
  48. // Rus: создаём кнопку с номером. Надо определиться, будут они массштабируемы или нет?
  49. // EndDraw - показывает, будут ещё кнопки прорисовываться или нет. Если будут, то надо сохранять фреймы
  50. // для текстуры общей. Иначе, надо сохранять текстуры.
  51. // Пока про это забываем и делаем только текстуры.
  52. // Eng:
  53. function AddNumButton(x, y, w, h: Single; num: LongWord; passive: Boolean = False{; EndDraw: Boolean = True}): LongWord;
  54. // Rus: создаём кнопку с текстом. Надо определиться, будут они массштабируемы или нет?
  55. // Eng:
  56. function AddStrButton(x, y, w, h: Single; text: UTF8String; passive: Boolean = False): LongWord;
  57. // Rus: процедура которая нужна чтоб получить текстуры кнопок.
  58. // Eng:
  59. procedure ButtonPostDraw(W, H: Single; text: UTF8String);
  60. // пока создаю две процедуры для начала постотрисовки и конца, позже посмотрим как это реализовать.
  61. procedure BeginPostDraw;
  62. procedure EndPostDraw;
  63. implementation
  64. var
  65. // Rus: менеджер всех кнопок
  66. // Eng:
  67. managerButton: TButtonManager;
  68. PTRButton: PButtonObj;
  69. // текстура, которая будет действовать для постотрисовки и для создания "общей" текстуры, которая будет сохранена в дальнейшем.
  70. TexturePostDraw: zglPTexture;
  71. _xx, _yy, _ww, _hh: Single;
  72. procedure _GetMemoryForButton;
  73. begin
  74. // здесь задаётся только основная информация о кнопке
  75. if managerButton.Count >= managerButton.MaxButton then
  76. begin
  77. // подготовка к созданию кнопок, есл под кнопки не выделена область
  78. inc(managerButton.MaxButton, 20);
  79. SetLength(managerButton.thisButton, managerButton.MaxButton);
  80. end;
  81. // выделяем память
  82. zgl_GetMem(PTRButton, SizeOf(TButtonObj));
  83. managerButton.thisButton[managerButton.Count] := PTRButton;
  84. end;
  85. function AddButton(x, y, w, h: Single; Texture: zglPTexture; passive: Boolean): LongWord;
  86. begin
  87. Result := managerButton.Count;
  88. _GetMemoryForButton;
  89. PTRButton^.rect.X := x;
  90. PTRButton^.rect.Y := y;
  91. PTRButton^.rect.W := w;
  92. PTRButton^.rect.H := h;
  93. PTRButton^.Texture := Texture;
  94. PTRButton^.passiv := passive;
  95. PTRButton^.ID := managerButton.Count;
  96. // сохранение указателя на кнопку.
  97. inc(managerButton.Count);
  98. PTRButton := nil;
  99. end;
  100. function AddNumButton(x, y, w, h: Single; num: LongWord; passive: Boolean): LongWord;
  101. begin
  102. Result := managerButton.Count;
  103. _GetMemoryForButton;
  104. PTRButton^.Texture := ButtonPostDraw(round(w), round(h), u_IntToStr(num));
  105. PTRButton^.rect.X := x;
  106. PTRButton^.rect.Y := y;
  107. PTRButton^.rect.W := w;
  108. PTRButton^.rect.H := h;
  109. PTRButton^.passiv := passive;
  110. PTRButton^.ID := managerButton.Count;
  111. inc(managerButton.Count);
  112. PTRButton := nil;
  113. end;
  114. function AddStrButton(x, y, w, h: Single; text: UTF8String; passive: Boolean): LongWord;
  115. begin
  116. Result := managerButton.Count;
  117. _GetMemoryForButton;
  118. PTRButton^.Texture := ButtonPostDraw(round(w), round(h), text);
  119. PTRButton^.rect.X := x;
  120. PTRButton^.rect.Y := y;
  121. PTRButton^.rect.W := w;
  122. PTRButton^.rect.H := h;
  123. PTRButton^.passiv := passive;
  124. PTRButton^.ID := managerButton.Count;
  125. inc(managerButton.Count);
  126. PTRButton := nil;
  127. end;
  128. procedure ButtonPostDraw(W, H: Single; text: UTF8String);
  129. var
  130. point: zglTPoint2D;
  131. rect: zglTRect2D;
  132. pData: PByteArray;
  133. begin
  134. if (_ww + W > 1024) and (_hh + H > 1024) then
  135. begin
  136. EndPostDraw; // завершаем работу с предыдущей тестурой и начинаем работу с новой.
  137. BeginPostDraw; // а значит, что нужен номер текстуры дополнительно
  138. end;
  139. // данную процедуру необходимо переделать под множество кнопок. И возвращать значения текстурных координат.
  140. pr2d_Rect(0, 0, W, H * 2, cl_Black, PR2D_FILL);
  141. pr2d_RectEX(0, 0, W, H, cl_Black, cl_Blue05, 3, PR2D_FILL);
  142. rect.X := 0;
  143. rect.Y := 0;
  144. rect.W := W;
  145. rect.H := H;
  146. point := text_GetXY(fntEdit, rect, text);
  147. text_Draw(fntEdit, point.x, point.y, text);
  148. pr2d_RectEX(0, H, W, H, cl_Black, cl_Gray, 3, PR2D_FILL);
  149. rect.Y := H;
  150. // point := text_GetXY(fntEdit, rect, text); // возможно просто прибавить высоту?
  151. point.Y := point.Y + H;
  152. text_Draw(fntEdit, point.x, point.y, text);
  153. // получение фрейма текстуры.
  154. // основная ширина текстуры - 1 (= 1024), ширина фрейма - известна. (1/1024 * wframe)
  155. end;
  156. procedure BeginPostDraw;
  157. begin
  158. _xx := 0;
  159. _yy := 0;
  160. _ww := 0;
  161. _hh := 0;
  162. // полная очистка будующей текстуры
  163. // ставлю hh, чтоб паскаль взял последнее значение, а не в очередной раз извлекал его из регистра. Хотя... наверняка опять извлекать будет...
  164. pr2d_Rect(_hh, _hh, 1024, 1024, cl_transparent, PR2D_FILL);
  165. end;
  166. procedure EndPostDraw;
  167. begin
  168. scr_ReadPixels(pData, 0, 0, 1024, 1024);
  169. // мы должны сохранить данную полученную текстуру
  170. // tex_CalcTransparent(pData, TEX_NO_COLORKEY, 1024, 1024); // не обязательно, при таких данных.
  171. Result := tex_Create(pData, 1024, 1024);
  172. Freemem(pData);
  173. // надо отправить всем созданным "объектам" номер текстуры.
  174. // разбить текстуры надо по другому, а может и не надо вовсе.
  175. // tex_SetFrameSize(Result, W, H);
  176. end;
  177. end.