demo03.lpr 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. program demo03;
  2. {$I zglCustomConfig.cfg}
  3. {$I zgl_config.cfg}
  4. // RU: Включите KEYBOARD_OLD_FUNCTION в zgl_config.cfg, если хотите использовать старые функции клавиатуры.
  5. // С введением Green Engine - они стали не актуальны, но я их пока оставляю.
  6. // EN: Enable KEYBOARD_OLD_FUNCTION in zgl_config.cfg if you want to use the old keyboard functions.
  7. // With the introduction of the Green Engine - they are no longer relevant, but I leave them for now.
  8. {$IFDEF WINDOWS}
  9. {$R *.res}
  10. {$ENDIF}
  11. uses
  12. {$IFDEF UNIX}
  13. cthreads,
  14. {$ENDIF}
  15. zgl_screen,
  16. zgl_window,
  17. zgl_timers,
  18. zgl_mouse,
  19. zgl_keyboard,
  20. zgl_joystick,
  21. zgl_primitives_2d,
  22. zgl_render_2d,
  23. zgl_font,
  24. zgl_text,
  25. zgl_textures,
  26. zgl_textures_png,
  27. zgl_types,
  28. {$IfDef KEYBOARD_OLD_FUNCTION}
  29. zgl_collision_2d,
  30. {$Else}
  31. gegl_VElements,
  32. gegl_utils,
  33. // Rus: Включите Define USE_VKEYBOARD в zgl_config.cfg если хотите попробовать использовать виртуальную клавиатуру.
  34. // Eng: Enable Define USE_VKEYBOARD in zgl_config.cfg if you want to try using the virtual keyboard.
  35. {$IfDef USE_VKEYBOARD}
  36. gegl_draw_gui,
  37. gegl_menu_gui,
  38. {$EndIf}
  39. {$EndIf}
  40. gegl_color,
  41. zgl_utils
  42. ;
  43. var
  44. dirRes : UTF8String {$IFNDEF MACOSX} = '../data/' {$ENDIF};
  45. joyCount : Integer;
  46. // RU: строка для получения значения из поля ввода
  47. // EN: string to get value from input field
  48. userInput : UTF8String;
  49. {$IfDef KEYBOARD_OLD_FUNCTION}
  50. trackInput : Boolean;
  51. inputRect : zglTRect;
  52. lineAlpha : LongWord;
  53. TimeStart : LongWord;
  54. {$Else}
  55. // Rus: номера шрифтов. Вся работа со шрифтами происходит именно от этих номеров.
  56. // Eng: font numbers. All work with fonts comes from these numbers.
  57. fntMain, fntEdit: LongWord;
  58. // Rus: номер цвета. Работа с цветом происходит именно от этого номера.
  59. // Eng: color number. Work with color comes from this number.
  60. EditColor: LongWord;
  61. // RU: прямоугольник описывающий поле ввода
  62. // EN: rectangle describing the input field
  63. myRect: zglTRect2D;
  64. // "перепись" полей ввода для того, чтоб знать с каким полем работаем.
  65. // RU: объявляем переменную для работы с полем ввода
  66. // EN: we declare a variable to work with the input field
  67. myEdit, myEdit2: LongWord;
  68. // RU: прорисовываем основание поля ввода. Всё ограничено только вашим воображением. )))
  69. // EN: draw the base of the input field. Everything is limited only by your imagination. )))
  70. procedure EditCont;
  71. begin
  72. // RU: при прорисовке поля ввода, смешение и поворот уже будут сделаны. Я показываю как нарисовать рамку.
  73. // Текст будет выведен поверх того, что вы здесь нарисуете.
  74. // EN: displacement and rotation will be done prior to performing the procedure. I am showing you how to draw a frame.
  75. // The text will be drawn on top of what you draw here.
  76. pr2d_Rect(- 2, - 1, myRect.W + 5, myRect.H, cl_White, PR2D_FILL);
  77. end;
  78. {$EndIf}
  79. procedure Init;
  80. {$IfNDef KEYBOARD_OLD_FUNCTION}
  81. var
  82. EScale: LongWord;
  83. {$EndIf}
  84. begin
  85. fntMain := font_LoadFromFile( dirRes + 'font.zfi' );
  86. {$IfNDef KEYBOARD_OLD_FUNCTION}
  87. // RU: Загружаем данные о шрифте.
  88. // EN: Load the font.
  89. fntEdit := font_LoadFromFile( dirRes + 'CalibriBold50pt.zfi');
  90. {$IfDef USE_VKEYBOARD}
  91. //------------------------------------------------------------------------------
  92. // RU: Данные для виртуальной клавиатуры. Раскомментируйте, если будете использовать виртуальную клавиатуру для ПК.
  93. // EN: Data for the virtual keyboard. Uncomment if you will use the virtual keyboard for PC.
  94. // обязательный код! Данные для отображения клавиатуры.
  95. // RU: Загружаем данные о шрифте.
  96. // EN: Load the font.
  97. fontUse := font_LoadFromFile(dirRes + 'CalibriBold50pt.zfi');
  98. JoyArrow := tex_LoadFromFile(dirRes + 'arrow.png'); // загрузили текстуру
  99. tex_SetFrameSize(JoyArrow, 64, 64); // и разбили её на части, но в записях не будет указано количество полученных текстур
  100. // RU: Данные для виртуальной клавиатуры.
  101. // EN: Data for the virtual keyboard.
  102. txt_LoadFromFile(dirRes + 'Rus.txt', LoadText);
  103. // RU: Создаём виртуальную клавиатуру. Для мобильных систем это будет обязательным кодом в дальнейшем.
  104. // EN: We create a virtual keyboard. For mobile systems, this will be a mandatory code in the future.
  105. CreateTouchKeyboard;
  106. // RU: здесь данные для виртуальной клавиатуры заканчиваются.
  107. // EN: here the data for the virtual keyboard ends.
  108. //------------------------------------------------------------------------------
  109. {$EndIf}
  110. // RU: устанавливаем размеры шрифтов
  111. // EN: set font sizes
  112. setFontTextScale(15, fntMain);
  113. setFontTextScale(20, fntEdit);
  114. // RU: размер шрифта поля ввода (для понимания что происходит). Изменяя размер шрифта, мы должны менять и
  115. // размеры поля ввода - myRect в данном случае. Сами они не изменятся.
  116. // EN: the font size of the input field (to understand what's going on). By changing the font size,
  117. // we must also change the size of the input field - myRect in this case. They themselves will not change.
  118. EScale := 20;
  119. setFontTextScale(EScale, fntEdit);
  120. // RU: указываем размеры поля ввода
  121. // EN: specify the size of the input field
  122. myRect.X := 200;
  123. myRect.Y := 150;
  124. myRect.W := 200;
  125. myRect.H := 33;
  126. // RU: указываем точку вращения, в данном случае центр поля ввода (по необходимости) и угол поворота (например 45)
  127. // EN: specify the point of rotation, in this case the center of the input field (if necessary) and the angle of rotation (for example 45)
  128. SetOfRotateAngleAndPoint(myRect.x + myRect.W / 2, myRect.y + myRect.H / 2, 30);
  129. // RU: указываем цвет текста (добавляем новый номер цвета, хотя данная функция вам возвратит цвет, если он уже был прописан).
  130. // EN: specify the color of the text (we add a new color number, although this function will return the color to you if it
  131. // has already been assigned).
  132. EditColor := Color_FindOrAdd($208055FF);
  133. // Ru: устанавливаем цвета по умолчанию для всех элементов API. Эти цвета будут задействованы только при создании
  134. // определённого элемента. Для изменения цвета в самом (уже созданном) элементе, ни чего не прилагается.
  135. // Дальнейшие измениня этих значений цвета, ни как не скажется на уже созданных элементах.
  136. // En: set default colors for all API elements. These colors will only be used when creating a specific element.
  137. // To change the color in the (already created) element itself, nothing is attached. Further changes to these
  138. // color values will not affect the already created elements in any way.
  139. SetDefColor(EditColor, cl_Green, cl_Black);
  140. // RU: создаём само поле ввода с данными указанными выше и передаваемыми данными
  141. // EN: create the input field itself with the data specified above and the data that needs to be transferred
  142. myEdit := CreateEdit(myRect, fntEdit, EScale, @EditCont);
  143. // RU: корректируем курсор.
  144. // EN: adjust the cursor.
  145. CorrectEditCursor(myEdit, 2);
  146. // RU: задаём очистку экрана заданным цветом
  147. // EN: set the screen to clear with a specified color
  148. scr_SetClearColor(true, $7090af);
  149. {$Else}
  150. inputRect.X := 400 - 192;
  151. inputRect.Y := 300 - 100 - 32;
  152. inputRect.W := 384;
  153. inputRect.H := 96;
  154. setFontTextScale(15, fntMain);
  155. {$EndIf}
  156. // RU: Инициализируем обработку ввода джойстиков и получаем количество подключенных джойстиков.
  157. // EN: Initialize processing joystick input and get count of plugged joysticks.
  158. joyCount := joy_Init();
  159. end;
  160. procedure Draw;
  161. {$IfDef KEYBOARD_OLD_FUNCTION}
  162. var
  163. w : Single;
  164. {$EndIf}
  165. begin
  166. batch2d_Begin;
  167. // Ru: балуемся цветом шрифта.
  168. // En: indulge in the color of the font.
  169. setTextColor(Get_Color(cl_Blue));
  170. text_Draw( fntMain, 0, 0, 'Escape - Exit' );
  171. setTextColor(Get_Color(cl_White));
  172. // RU: Координаты мыши можно получить при помощи функций mouse_X и mouse_Y.
  173. // EN: Mouse coordinates can be got using functions mouse_X and mouse_Y.
  174. text_Draw( fntMain, 0, 18, 'Mouse X, Y: ' + u_IntToStr( mouseX ) + '; ' + u_IntToStr( mouseY ) );
  175. {$IfDef KEYBOARD_OLD_FUNCTION}
  176. // RU: Выводим введённый пользователем текст.
  177. // EN: Show the inputted text.
  178. pr2d_Rect( inputRect.X, inputRect.Y, inputRect.W, inputRect.H, $FFFFFF, 255 );
  179. if trackInput Then
  180. begin
  181. text_Draw( fntMain, 400, 300 - 100, 'Press Enter to stop track text input:', TEXT_HALIGN_CENTER );
  182. w := text_GetWidth( fntMain, userInput );
  183. pr2d_Rect( 400 + w / 2 + 2, 300 - 70, 10, 20, $FFFFFF, lineAlpha, PR2D_FILL );
  184. end else
  185. text_Draw( fntMain, 400, 300 - 100, 'Click here to enter text(maximum - 24 symbols):', TEXT_HALIGN_CENTER );
  186. text_Draw( fntMain, 400, 300 - 70, userInput, TEXT_HALIGN_CENTER );
  187. {$Else}
  188. text_Draw(fntMain, 0, 36, 'Press F5 to copy from Edit and draw'); // какой я нафиг англичанин? ))))
  189. text_Draw(fntMain, 0, 54, 'Press F12 - Rus/Eng');
  190. if userInput <> '' then
  191. text_Draw(fntMain, 400, 300 - 70, userInput, TEXT_HALIGN_CENTER);
  192. {$EndIf}
  193. // RU: Вывод состояния осей и кнопок первого джойстика в системе.
  194. // EN: Show the state of axes and buttons of first joystick in the system.
  195. text_Draw( fntMain, 400, 360, 'JOYSTICK ( Found: ' + u_IntToStr( joyCount ) + ' )', TEXT_HALIGN_CENTER );
  196. setTextColor(Get_Color(cl_Black));
  197. text_Draw( fntMain, 100, 400, 'Axis X: ' + u_FloatToStr( joy_AxisPos( 0, JOY_AXIS_X ) ) );
  198. text_Draw( fntMain, 100, 420, 'Axis Y: ' + u_FloatToStr( joy_AxisPos( 0, JOY_AXIS_Y ) ) );
  199. setTextColor(Get_Color(cl_Black05));
  200. text_Draw( fntMain, 100, 440, 'Axis Z: ' + u_FloatToStr( joy_AxisPos( 0, JOY_AXIS_Z ) ) );
  201. setTextColor(Get_Color(cl_Green));
  202. text_Draw( fntMain, 100, 460, 'Axis R: ' + u_FloatToStr( joy_AxisPos( 0, JOY_AXIS_R ) ) );
  203. text_Draw( fntMain, 100, 480, 'Axis U: ' + u_FloatToStr( joy_AxisPos( 0, JOY_AXIS_U ) ) );
  204. setTextColor(Get_Color(cl_Green05));
  205. text_Draw( fntMain, 100, 500, 'Axis V: ' + u_FloatToStr( joy_AxisPos( 0, JOY_AXIS_V ) ) );
  206. text_Draw( fntMain, 100, 520, 'POVX: ' + u_FloatToStr( joy_AxisPos( 0, JOY_POVX ) ) );
  207. text_Draw( fntMain, 100, 540, 'POVY: ' + u_FloatToStr( joy_AxisPos( 0, JOY_POVY ) ) );
  208. setTextColor(Get_Color(cl_Red05));
  209. text_Draw( fntMain, 400, 400, 'Button1: ' + u_BoolToStr( joy_Down( 0, 0 ) ) );
  210. text_Draw( fntMain, 400, 420, 'Button2: ' + u_BoolToStr( joy_Down( 0, 1 ) ) );
  211. text_Draw( fntMain, 400, 440, 'Button3: ' + u_BoolToStr( joy_Down( 0, 2 ) ) );
  212. text_Draw( fntMain, 400, 460, 'Button4: ' + u_BoolToStr( joy_Down( 0, 3 ) ) );
  213. text_Draw( fntMain, 400, 480, 'Button5: ' + u_BoolToStr( joy_Down( 0, 4 ) ) );
  214. text_Draw( fntMain, 400, 500, 'Button6: ' + u_BoolToStr( joy_Down( 0, 5 ) ) );
  215. text_Draw( fntMain, 400, 520, 'Button7: ' + u_BoolToStr( joy_Down( 0, 6 ) ) );
  216. text_Draw( fntMain, 400, 540, 'Button8: ' + u_BoolToStr( joy_Down( 0, 7 ) ) );
  217. text_Draw( fntMain, 550, 400, 'Button9: ' + u_BoolToStr( joy_Down( 0, 8 ) ) );
  218. text_Draw( fntMain, 550, 420, 'Button10: ' + u_BoolToStr( joy_Down( 0, 9 ) ) );
  219. text_Draw( fntMain, 550, 440, 'Button11: ' + u_BoolToStr( joy_Down( 0, 10 ) ) );
  220. text_Draw( fntMain, 550, 460, 'Button12: ' + u_BoolToStr( joy_Down( 0, 11 ) ) );
  221. text_Draw( fntMain, 550, 480, 'Button13: ' + u_BoolToStr( joy_Down( 0, 12 ) ) );
  222. text_Draw( fntMain, 550, 500, 'Button14: ' + u_BoolToStr( joy_Down( 0, 13 ) ) );
  223. text_Draw( fntMain, 550, 520, 'Button15: ' + u_BoolToStr( joy_Down( 0, 14 ) ) );
  224. text_Draw( fntMain, 550, 540, 'Button16: ' + u_BoolToStr( joy_Down( 0, 15 ) ) );
  225. batch2d_End;
  226. end;
  227. {$IfDef KEYBOARD_OLD_FUNCTION}
  228. procedure Timer;
  229. begin
  230. if lineAlpha > 5 Then
  231. DEC( lineAlpha, 10 )
  232. else
  233. lineAlpha := 255;
  234. end;
  235. {$EndIf}
  236. procedure KeyMouseEvent;
  237. begin
  238. {$IfDef KEYBOARD_OLD_FUNCTION}
  239. // RU: Проверить нажата ли левая кнопка мыши в пределах inputRect и начать отслеживать ввод текста.
  240. // EN: Check if left mouse button was pressed inside inputRect and start to track text input.
  241. if mouseBClick( M_BLEFT ) and col2d_PointInRect( mouseX, mouseY, inputRect ) Then
  242. begin
  243. trackInput := TRUE;
  244. key_BeginReadText( userInput, 24 );
  245. end;
  246. // RU: Если был нажат Enter прекращаем отслеживать ввод текста.
  247. // EN: Finish to track text input if Enter was pressed.
  248. if key_Press( K_ENTER ) Then
  249. begin
  250. trackInput := FALSE;
  251. key_EndReadText();
  252. end;
  253. // RU: Получаем введённый пользователем текст.
  254. // EN: Get inputted by user text.
  255. if trackInput Then
  256. userInput := key_GetText();
  257. {$Else}
  258. // RU: по нажатию F5 копируем то, что написано в поле ввода
  259. // EN: by pressing F5, copy what is written in the input field
  260. if keysDown[K_F5] then
  261. begin
  262. userInput := GetEditToText(myEdit);
  263. end;
  264. {$EndIf}
  265. end;
  266. Begin
  267. {$IfDef KEYBOARD_OLD_FUNCTION}
  268. TimeStart := timer_Add( @Timer, 16, t_Start );
  269. {$EndIf}
  270. zgl_Reg(SYS_EVENTS, @KeyMouseEvent);
  271. zgl_Reg( SYS_LOAD, @Init );
  272. zgl_Reg( SYS_DRAW, @Draw );
  273. wnd_SetCaption(utf8_Copy('03 - Input'));
  274. zgl_Init();
  275. End.