Recent

Author Topic: ZenGL +android + MacOS Cocoa (beta)  (Read 11349 times)

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
ZenGL +android + MacOS Cocoa (beta)
« on: December 21, 2020, 12:55:45 am »
Rus:
Текущая версия: ZenGL 4.2 (download)

ZenGL - это библиотека создающая контекст окна для работы с OpenGL на разных платформах. Так же, это игровой 2D движок, позволяющий писать игры (приложение), без знаний OpenGL.
На данное время, есть возможность использования полного OpenGL и OpenGL ES (OpenGL ES в следующей версии ZenGL 4.3).
Green Engine - это наработки над ZenGL, своеобразное API.

Среда разработки и поддерживаемые платформы для:
Lazarus/FreePascal:
   - Windows 32/64
   - Linux 32/64
   - Android ARM32(v5, v6, v7a)/ARM64(v8a)/x86/x86_64
   - Портативные компьютеры: Steam Deck, Rog Ally, Ayaneo и другие основанные на ОС Windows и Linux.
   - MacOS Cocoa beta version

Delphi:
   - Windows 32 (вероятно некоторые демо-версии будут работать и с Windows 64, но точно не все)

!!! Здесь информация по сборке проекта под Android!
---------------------------------------------------------------------------------------------------------------------

Eng:
Google translate:
Current version: ZenGL 4.2 (download)

ZenGL is a window context library for working with OpenGL on different platforms. Also, this is a 2D game engine that allows you to write games (applications) without knowledge of OpenGL.
At this time, it is possible to use full OpenGL and OpenGL ES (OpenGL ES in the next version ZenGL 4.3).
Green Engine are developments on ZenGL, a kind of API.

Development environment and supported platforms for:
Lazarus/FreePascal:
    - Windows 32/64
    - Linux 32/64
    - Android ARM32(v5, v6, v7a)/ARM64(v8a)/x86/x86_64
    - Portable computers: Steam Deck, Rog Ally, Ayaneo and others based on Windows and Linux OS.
    - MacOS Cocoa beta version

Delphi:
    - Windows 32 (probably some demos will work with Windows 64, but definitely not all)

!!! Here is information on building a project for Android!
see more information on GitHub.

---------------------------------------------------------------------------------------------------------------------
Внимание! Для новых версий FPC (> 3.0.4) для Unix-систем и не LCL в запускаемом модуле обязательно надо выставлять:
Code: Pascal  [Select][+][-]
  1. uses
  2. {$IFDEF UNIX}
  3.    cthreads;
  4. {$ENDIF}
---------------------------------------------------------------------------------------------------------------------
старые версии не включённые в SourceForge:

ZenGL до версии 4.2 (GitHub)
ZenGL 3.24
ZenGL 3.20

и версия от Скалогрыза - данная версия должна работать с iOS.
---------------------------------------------------------------------------------------------------------------------

Сопутствующие видео:
решение проблем, связанных с запуском приложений на Android.

Запустил демо-версии на андроиде. Запустил я все демо-версии, и все заставил работать, поэтому при сборке у вас тоже они должны работать, но на видео ещё тот момент, когда не удалось найти все ошибки и исправить их.

На данный момент проверено большинство демок для Android под большинство поддерживаемых архитектур! 8)

В версии 3.20 не сильно много поменялось, но корректирована работа с fpc (версия желательно больше 3.0.4) под андроид и настроены дефайны.

Проблемы с компиляцией под андроид могут возникнуть в множестве случаев. Смотрите видео, задавайте вопросы.

Первые проблемы бывают с тем, что некоторые установленные у вас Lazarus-ы путают дефайны и для них Linux и Android одно и то же, а это не так!!!

Может быть где-то пути упустили, где-то Лазарус тянет за собой шлейф ненужной информации и зачастую прийдётся удалить *.lpi файл.

Ещё один из простых вариантов, вы используете не тот компилятор.

вопросы, предложения можно оставлять здесь или отправлять на мыло M12Mirrel@yandex.ru

Благодарю за внимание.  :)
« Last Edit: October 09, 2023, 06:41:45 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #1 on: December 21, 2020, 01:21:07 am »
Если вы используете BigSur или CPU не x86_64 то вам надо:
установить библиотеки из brew

If you are using BigSur or a CPU not x86_64 then you need:
install libraries from brew
- zlib
- libzip
- libogg
- vorbis
и если знаете как запустить 15-ю и 16-ю демо-версии, то:
and if you know how to run the 15th and 16th demo versions, then:
- theora
- chipmunk

в файле "zgl_config.cfg" выставить
in the file "zgl_config.cfg" set
Code: Pascal  [Select][+][-]
  1. {$DEFINE MAC_COCOA}
and disable
Code: Pascal  [Select][+][-]
  1. {$IFDEF MAC_COCOA}
  2.   {$DEFINE NO_USE_STATIC_LIBRARY} // -> {.$DEFINE NO_USE_STATIC_LIBRARY}
  3. {$ENDIF}
If all libraries are installed by default, then the demo versions should work.

Если все библиотеки будут установлены по умолчанию, то демо-версии должны заработать.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

skalogryz

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 2770
    • havefunsoft.com
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #2 on: December 21, 2020, 02:51:05 am »
zlib идёт в маке из коробки

с Маком вся тонкость как динамические либы распростронять.
Их обязательно нужно класть в нужную директорию в бандле!

иначе конечных пользователей тоже придёться просить ставить Brew. не камильфо!  :)

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #3 on: December 21, 2020, 07:23:03 am »
skalogryz, и вот тут вырисовывается интересная проблема... о которой я даже не задумывался...
Допустим для своего процессора я добавлю эти самые библиотеки, это не проблема.

Но!!! Как обеспечить полную совместимость программы для разных процессоров по свое сути?!
Мне надо об этом заботится? Или всё же приложение скомпилированное на процессоре x86-64 будет работать на процессоре ARM64? Если да, то как мне получить библиотеки для процессора ARM?

Эта проблема, похоже, касается не только MacOS, но и Linux?

Я ни сколько не на Java программирую...

Google translate:
and here an interesting problem looms ... which I did not even think about ...
Suppose I add these same libraries for my processor, this is not a problem.

But!!! How to ensure full compatibility of the program for different processors in essence?!
Do I need to take care of this? Or will an application compiled on an x86-64 processor run on an ARM64 processor? If so, how do I get libraries for the ARM processor?

Does this problem seem to affect not only macOS but Linux as well?

I do not program in Java at all ...

P.S. skalogryz, мы не на русскоязычном форуме.  :)
« Last Edit: December 21, 2020, 08:41:09 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #4 on: July 18, 2021, 03:18:14 am »
Всем привет! Обновил версию ZenGL до 3.28.
И с данного момента (так то и раньше уже было) теперь параллельно идёт разработка собственной библиотеки Green Engine. Работает только с ZenGL.

Прошу прощения, но на английском информации мало. Но по ходу разработки добавляю комментарии в код и демонстрационные версии.

GE - предоставляет в данное время только возможность работать с полем ввода, и виртуальной клавиатурой, которая ещё не доделана...  Для мобильных систем пока ни как не состыкована эта клавиатура, хотя для неё изначально только и делал.

Поле ввода пока только проверены на Windows и Linux. На MacOS должно работать, но пока не проверял. :-[

Надеюсь полезное видео, где я переделываю 3-ю демо-версию. В конце видео показываю, как можно использовать несколько полей ввода.

Google translate:
Hello everyone! Updated ZenGL version to 3.28.
And from this moment (and it has already happened before), the development of its own Green Engine library is now going on in parallel. Works with ZenGL only.

Sorry, but there is little information in English. But in the course of development, I add comments to the code and demos.

GE - at this time only provides the ability to work with the input field, and the virtual keyboard, which has not yet been completed ... For mobile systems, this keyboard has not yet been docked, although it was originally only done for it.

The input field has only been tested on Windows and Linux so far. It should work on macOS, but haven't tested it yet. :-[

Hopefully helpful video of me remaking the 3rd demo. (rus) At the end of the video, I show you how you can use multiple input fields.
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Blade

  • Full Member
  • ***
  • Posts: 177
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #5 on: September 16, 2021, 12:39:40 am »
Very interesting and good to see the update.  Have seen various sources that had good things to say about ZenGL. 

Hopefully, ZenGL for iOS (https://github.com/skalogryz/zengl) works or gets updated too.

Akira1364

  • Hero Member
  • *****
  • Posts: 561
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #6 on: January 02, 2022, 11:20:16 am »
FYI, the custom code used in https://github.com/Seenkao/New-ZenGL/blob/ZenGL_3_28/Zengl_SRC/src/zgl_opengles_all.pas is equally applicable to the desktop platforms that do not use OpenGLES, and significantly faster than just letting it use the default actual glBegin / glEnd that is usually does for them.

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #7 on: January 05, 2022, 03:47:29 pm »
Blade, благодарю. По поводу iOS я ни чего не могу сказать на данный момент. У меня времени не хватает поднять код и/или включить код skalogryz. Времени на всё надо очень много, а иногда желание просто пропадает.  :(

Akira1364, вероятно что и для OpenGL ES это так же. Но надо не забывать включать batch2d_Begin/batch2d_End. Я думал это работает только для OpenGL ES, но я ошибался. Andru лучше меня знал как работает "устаревший" OpenGL/OpenGL ES - и это даёт ускорение в обоих случаях. Но надо знать, что это будет работать только при использовании функций ZenGL, пользуясь напряму OpenGL мы не получим этого ускорения (если только сами не включим дополнительный код используемый в функциях ZenGL).

Google translate:
Blade, thanks. As for iOS, I can't say anything at the moment. I don’t have enough time to raise the code and / or include the code skalogryz. It takes a lot of time for everything, and sometimes the desire just disappears. :(

Akira1364, it is probably the same for OpenGL ES. But remember to enable batch2d_Begin/batch2d_End. I thought this only works for OpenGL ES, but I was wrong. Andru knew better than me how the "outdated" OpenGL / OpenGL ES works - and this gives acceleration in both cases. But you need to know that this will only work when using ZenGL functions, using OpenGL directly, we will not get this acceleration (unless we ourselves include additional code used in ZenGL functions).
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #8 on: February 27, 2022, 03:53:42 pm »
Выпущена новая версия ZenGL 3.29.
 8)
Изменения в файле Update_ZenGL.txt.

Основное из изменений: В ZenGL включён полный OpenGL по состоянию на конец 2021 года. По умолчанию включена минимальная версия, для использования основной функциональности ZenGL. Для использования полного OpenGL вам надо будет отключить в файле GLdefine.cfg дефайн USE_MIN_OPENGL (смотрите первую демо версию).

Окно и контекст окна создаются автоматически. Работу с View-портом надо настраивать. Эти функции были сделаны ещё Andru, для 2D под ZenGL подойдёт (может и вам подойдёт), для 3D надо самим настраивать функцию.
Займусь этим немного позже. Вы можете сами что-нибудь предложить.

Демки переделаны только под Lazarus, поэтому все изменения смотрите в них.

Демка LCL не будет работать в Windows 10. Я пока не решал этой проблемы. Зависает окно.

------------------------------------------------------------------------------------------------------------------------------------
Google translate:
New version ZenGL 3.29 has been released.
 8)
Changes in the file Update_ZenGL.txt.

Key changes: ZenGL includes full OpenGL as of late 2021. By default, a minimum version is enabled to use the core functionality of ZenGL. To use full OpenGL you will need to disable USE_MIN_OPENGL in the GLdefine.cfg file (see the first demo).

The window and window context are created automatically. Work with the View-port must be configured. These functions were made by Andru, for 2D under ZenGL it will work (maybe it will work for you too), for 3D you need to configure the function yourself.
I'll deal with this a little later. You can offer something yourself.

Demos are remade only for Lazarus, so look at all the changes in them.

The LCL demo won't work on Windows 10. I haven't solved this problem yet. The window hangs.
« Last Edit: February 28, 2022, 08:37:48 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #9 on: March 15, 2023, 08:37:02 pm »
  Вышла новая версия ZenGL 3.30. Изменений достаточно немало и я не смогу их все упомнить. Всё постарался записать в файле Update_ZenGL.txt (к сожаленью только на Русском языке, прошу простить, но документацию стараюсь поддерживать и на Английском! ::)). Документирую функции в модулях. Документация на данный момент не полная.
  Основные изменения это то, что теперь для мобильных систем работает нативная клавиатура и она не зависит от системы!!! Её можно использовать как виртуальную клавиатуру для настольных ОС. Но вот про джойстики для мобильных систем - забыл... Они не доделаны.
  Клавиатура поддерживает кириллицу и латиницу. Для поддержки других раскладок клавиатур нужна помощь носителей данных языков. Если кого заинтересует, обращайтесь.

Google translate:
   New version ZenGL 3.30 has been released. There are so many changes that I can't remember them all. I tried to write everything in the file Update_ZenGL.txt (unfortunately, only in Russian, I'm sorry, but I try to support the documentation in English too! ::)). I document functions in modules. The documentation is currently incomplete.
   The main changes are that now a native keyboard works for mobile systems and it does not depend on the system!!! It can be used as a virtual keyboard for desktop OS. But I forgot about joysticks for mobile systems... They haven't been completed yet.
   The keyboard supports Cyrillic and Latin. Support for other keyboard layouts requires the assistance of native speakers of these languages. If anyone is interested, please contact.

Sorry for my English. But it's a translator...

Всем успехов!  ;D
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Akira1364

  • Hero Member
  • *****
  • Posts: 561
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #10 on: May 27, 2023, 10:38:19 pm »
FYI, the reimplementations of glBegin / glEnd etc from zgl_opengles_all.pas in terms of glDrawArrays and such should definitely also be used on desktop. Currently, ZenGL on desktop just actually uses the real immediate mode functions, which is much slower than the array-based wrappers from zgl_opengles.pas.

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #11 on: May 28, 2023, 02:34:38 am »
FYI, the reimplementations of glBegin / glEnd etc from zgl_opengles_all.pas in terms of glDrawArrays and such should definitely also be used on desktop. Currently, ZenGL on desktop just actually uses the real immediate mode functions, which is much slower than the array-based wrappers from zgl_opengles.pas.
Благодарю за замечание! Но для персональных компьютеров, в ZenGL мы не можем использовать функции и процедуры из zgl_opengles_all.pas, они замедлят работу настольных компьютеров  :( .
Если переделывать, то переделывать надо будет полностью и делать общие функции и для OpenGL и для OpenGL ES.
Я думал уже над этим, и,  вероятно я займусь этим. Но, так же это надо будет сделать и для версий OpenGL 3+ (на выбор пользователя-программиста).

Google translate:
Thanks for the note! But for personal computers, in ZenGL we can't use functions and procedures from zgl_opengles_all.pas, they will slow down desktop computers :( .
If you redo it, then you will have to completely redo it and make common functions for both OpenGL and OpenGL ES.
I've already thought about it, and I'll probably do it. But, it will also need to be done for versions of OpenGL 3+ (at the choice of the user-programmer).
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #12 on: September 16, 2023, 06:20:58 pm »
Всем привет! :-[
На данный момент у меня получилось запустить пример с OpenGL 3.3. Вывод треугольника используя шейдер, VAO и VBO. Прикладываю код, который должен работать в последних версиях ZenGL, заодно его прокомментировал для новичков:
Google translate:
Hi all!
At the moment I was able to run the example with OpenGL 3.3. Drawing a triangle using a shader, VAO and VBO. I am attaching code that should work in the latest versions of ZenGL, at the same time commented on it for beginners:

Code: Pascal  [Select][+][-]
  1. program demo19;
  2.  
  3. // RU: Этот файл содержит некоторые настройки(например использовать ли статическую компиляцию) и определения ОС под которую происходит компиляция.
  4. // EN: This file contains some options(e.g. whether to use static compilation) and defines of OS for which is compilation going.
  5. {$I zglCustomConfig.cfg}
  6. {$I zgl_config.cfg}
  7.  
  8. {$IFDEF WINDOWS}
  9.   {$R *.res}
  10. {$ENDIF}
  11.  
  12. uses
  13.   {$IFDEF UNIX}
  14.   cthreads,
  15.   {$ENDIF}
  16.   Math,
  17.   zgl_window,
  18.   zgl_screen,
  19.   zgl_timers,
  20.   zgl_utils,
  21.   zgl_types,
  22.   zgl_pasOpenGL,
  23.   zgl_opengl_all,
  24.   zgl_gltypeconst,
  25.   zgl_matrix,    // new
  26.   zgl_file,
  27.   zgl_log;
  28.  
  29. const
  30.   _vertex = 0;
  31.   _color  = 1;
  32.  
  33. var
  34.   DirApp  : UTF8String;
  35.   DirHome : UTF8String;
  36.   DirShader: UTF8String = {$IfNDef MAC_COCOA}'shaders/'{$EndIf};
  37.  
  38.   TimeStart  : LongWord = 0;
  39.  
  40.   // RU: переменная для хранения индекса юниформа.
  41.   // EN: variable to store the uniform index.
  42.   projMatrLoc: GLuint;
  43.   // RU: шейдер, вершинный шейдер, фрагментный шейдер.
  44.   // EN: shader, vertex shader, fragment shader.
  45.   shadProg, vertShad, fragShad: GLuint;
  46.   // RU: вершины (3 координаты).
  47.   // EN: vertices (3 coordinates).
  48.   verticesData: array[0..11] of Single = (-1, 0, -2, 1,
  49.                                           1, 0, -1, 1,
  50.                                           3, 1, -2, 1);
  51.   // RU: цветю.
  52.   // EN: color.
  53.   colorData: array[0..11] of Single    = (1, 0, 0, 1,
  54.                                           0, 1, 0, 1,
  55.                                           0, 0, 1, 1);
  56.   vao: GLuint;
  57.   vboHandles: array[0..1] of GLuint;
  58.  
  59. {// RU: матрица перспективы.
  60. // EN: perspective matrix.
  61. procedure Matrix4Perspective(fovy, aspect, _near, _far: Single);
  62. var
  63.   f: Single;
  64. begin
  65.   f := 1 / tan(fovy * Pi / 180);
  66.   projMatr[0] := f / aspect;
  67.   projMatr[1] := 0;
  68.   projMatr[2] := 0;
  69.   projMatr[3] := 0;
  70.  
  71.   projMatr[4] := 0;
  72.   projMatr[5] := f;
  73.   projMatr[6] := 0;
  74.   projMatr[7] := 0;
  75.  
  76.   projMatr[8] := 0;
  77.   projMatr[9] := 0;
  78.   projMatr[10] := (_far + _near) / (_near - _far);
  79.   projMatr[11] := 2 * _far * _near / (_near - _far);
  80.  
  81.   projMatr[12] := 0;
  82.   projMatr[13] := 0;
  83.   projMatr[14] := - 1;
  84.   projMatr[15] := 0;
  85. end;
  86.  
  87. // RU: загрузка шейдера, компиляция и проверка на успех компиляции.
  88. // EN: loading the shader, compiling and checking for compilation success.
  89. function LoadAndCreateShader(name: string; shade: GLuint): Boolean;
  90. var
  91.   Ftext: zglTFile;
  92.   Fmem: zglTMemory;
  93.   status: GLint;
  94. begin
  95.   Result := False;
  96.   // RU: проверка существования загружаемого файла.
  97.   // EN: Checking the existence of the downloaded file.
  98.   if not file_Exists(name) then
  99.     Exit;
  100.   // RU: открываем файл.
  101.   // EN: open the file.
  102.   if file_Open(Ftext, name, FOM_OPENR)then
  103.   begin
  104.     Fmem.Size := file_GetSize(Ftext);
  105.     Fmem.Position := 0;
  106.     // RU: подготавливаем память для загрузки шейдера.
  107.     // EN: prepare memory for loading the shader.
  108.     zgl_GetMem(Fmem.Memory, Fmem.Size);
  109.     // RU: загружаем шейдер в память.
  110.     // EN: load the shader into memory.
  111.     file_Read(Ftext, Fmem.Memory^, Fmem.Size);
  112.     file_Close(Ftext);
  113.     // RU: исходный код шейдера и его компиляция. Обратите внимание, "Fmem.Memory"
  114.     //     это указатель на память, где находится строка. И мы передаём указатель
  115.     //     на данный участок памяти. Это работает правильно, потому что данные
  116.     //     должны идти под двойным указателем (PPGLchar).
  117.     // EN: shader source code and its compilation. Note that "Fmem.Memory" is a
  118.     //     pointer to the memory where the string is located. And we pass a
  119.     //     pointer to this memory location. This works correctly because the data
  120.     //     must go under a double pointer (PPGLchar).
  121.     glShaderSource(shade, 1, @Fmem.Memory, @Fmem.Size);
  122.     glCompileShader(shade);
  123.     // RU: освобождаем память, данный текст больше не нужен.
  124.     // EN: freeing up memory, this text is no longer needed.
  125.     zgl_FreeMem(Fmem.Memory);
  126.   end;
  127.  
  128.   // RU: проверяем на успех компиляции шейдера.
  129.   // EN: check for success of shader compilation.
  130.   glGetShaderiv(shade, GL_COMPILE_STATUS, @status);
  131.   if status <> 1 then
  132.     Exit;
  133.   Result := True;
  134. end;    }
  135.  
  136. // RU: создание VAO и VBO.
  137. // EN: creation of VAO and VBO.
  138. procedure createVBOAndVAO;
  139. begin
  140.   // RU: буферные объекты.
  141.   // EN: buffer objects.
  142.   glGenBuffers(2, @vboHandles);
  143.  
  144.   // RU: Создаём объект массива вершин (для того чтоб при прорисовке этого не делать).
  145.   // EN: We create an object of an array of vertices (so that we don’t have to do this when drawing).
  146.   glGenVertexArrays(1, @vao);
  147.   // установим созданный VAO как текущий
  148.   glBindVertexArray(vao);
  149.  
  150.   // RU: активируем массив вершинных атрибутов.
  151.   // EN: activate the array of vertex attributes.
  152.   glEnableVertexAttribArray(_vertex); // vertex
  153.   glEnableVertexAttribArray(_color);  // color
  154.  
  155.   // RU: закрепить индекс 0 за буфером координат.
  156.   // EN: assign index 0 to the coordinate buffer.
  157.   glBindBuffer(GL_ARRAY_BUFFER, vboHandles[_vertex]);
  158.   // RU: заполнить буфер координат.      Это позволительно, ошибки не создаёт.
  159.   // EN: fill the coordinate buffer.     This is permissible and does not create errors.
  160.   glBufferData(GL_ARRAY_BUFFER, SizeOf(verticesData), @verticesData, GL_STATIC_DRAW);
  161.   glVertexAttribPointer(_vertex, 4, GL_FLOAT, GL_FALSE, 0, nil);
  162.  
  163.   // RU: закрепить индекс 1 за буфером цвета.
  164.   // EN: assign index 1 to the color buffer.
  165.   glBindBuffer(GL_ARRAY_BUFFER, vboHandles[_color]);
  166.   // RU: заполнить буфер цвета.      Это позволительно, ошибки не создаёт.
  167.   // EN: fill the color buffer.      This is permissible and does not create errors.
  168.   glBufferData(GL_ARRAY_BUFFER, SizeOf(colorData), @colorData, GL_STATIC_DRAW);
  169.   glVertexAttribPointer(_color, 4, GL_FLOAT, GL_FALSE, 0, nil);
  170.  
  171. end;
  172.  
  173. // RU: определяем ViewPort для нашей программы.
  174. // EN: We define the ViewPort for our program.
  175. procedure UserSetViewPort;
  176. begin
  177.   // RU: вместо "zgl_Get(WINDOW_WIDTH)" и "zgl_Get(WINDOW_HEIGHT)" можно создать
  178.   //     константы для ширины и высоты окна и указать их во ViewPort.
  179.   // EN: Instead of "zgl_Get(WINDOW_WIDTH)" and "zgl_Get(WINDOW_HEIGHT)" you can
  180.   //     create constants for the width and height of the window and specify them
  181.   //     in the ViewPort.
  182.   glViewport(0, 0, zgl_Get(WINDOW_WIDTH), zgl_Get(WINDOW_HEIGHT));
  183. end;
  184.  
  185. // RU: используем свою матрицу проекции.
  186. // EN: We use our projection matrix.
  187. procedure UserMode;
  188. begin
  189.   Matrix4_Perspective(45, zgl_Get(WINDOW_WIDTH) / zgl_Get(WINDOW_HEIGHT), 1, 100);
  190. //  glUseProgram(shadProg);        // это не обязательно
  191.   // RU: если данная переменная не используется в шейдере, то и вызов делать не будем.
  192.   // EN: if this variable is not used in the shader, then we will not make the call.
  193.   if projMatrLoc <> -1 then
  194.     glUniformMatrix4fv(projMatrLoc, 1, GL_FALSE, @projMatr);
  195.   //  glUseProgram(0);             // это не обязательно
  196. end;
  197.  
  198. // RU: Тут можно выполнять загрузку основных ресурсов и производить инициализацию
  199. //     начальных данных программы.
  200. // EN: Here you can load the main resources and initialize the initial program data.
  201. procedure Init;
  202. var
  203.   status: GLint;
  204. begin
  205.   // RU: создаём буфера и привязываем их к VAO.
  206.   // EN: we create buffers and bind them to VAO.
  207.   createVBOAndVAO;
  208.   // RU: создание шедерной программы и шейдеров.
  209.   // EN: creating a shader program and shaders.
  210.   shadProg := glCreateProgram;
  211.   vertShad := glCreateShader(GL_VERTEX_SHADER);
  212.   fragShad := glCreateShader(GL_FRAGMENT_SHADER);
  213.   // RU: загружаем шейдера, компилируем и делаем проверку успешно скомпилирован
  214.   //     шейдер или нет.
  215.   // EN: we load the shader, compile it and check whether the shader compiled
  216.   //     successfully or not.
  217.   if not LoadAndCreateShader(DirShader + 'first.vs', vertShad) or not LoadAndCreateShader(DirShader + 'first.fs', fragShad) then
  218.   begin
  219.     log_Add('Shader not loaded!!!');
  220.     zgl_Exit;
  221.   end;
  222.   // RU: присоединяем шейдера к программе.
  223.   // EN: We attach the shader to the program.
  224.   glAttachShader(shadProg, vertShad);
  225.   glAttachShader(shadProg, fragShad);
  226.   // RU: линкуем программу.
  227.   // EN: link the program.
  228.   glLinkProgram(shadProg);
  229.   // RU: проверяем статус линковки.
  230.   // EN: check the status of the link.
  231.   glGetProgramiv(shadProg, GL_LINK_STATUS, @status);
  232.   if status <> 1 then
  233.   begin
  234.     log_Add('Shader program not link!!!');
  235.     zgl_Exit;
  236.   end;
  237.   // RU: получаем юниформ-индекс projMatr из шейдерной программы.
  238.   // EN: get the uniform index projMatr from the shader program.
  239.   projMatrLoc := glGetUniformLocation(shadProg, 'projMatr');
  240.   // RU: проверяем, указана ли данная матрица в шейдере.
  241.   // EN: we check whether this matrix is specified in the shader.
  242.   if projMatrLoc <> -1 then
  243.   begin
  244.     // RU: это может быть не критичной ошибкой. Просто данный аргумент не
  245.     //     используется в шейдере или удалён из шейдера, как не используемый.
  246.     // EN: this may not be a critical error. It’s just that this argument is not
  247.     //     used in the shader or has been removed from the shader as not being used.
  248.     log_Add('projMatr not found in shader.');
  249.   end;
  250.  
  251.   // RU: проверка корректности скомпилированной программы.
  252.   // EN: checking the correctness of the compiled program.
  253.   glValidateProgram(shadProg);
  254.   glGetProgramiv(shadProg, GL_VALIDATE_STATUS, @status);
  255.   if status <> 1 then
  256.   begin
  257.     log_Add('Shader program not validate!!!');
  258.     zgl_Exit;
  259.   end;
  260.  
  261.   glDeleteShader(vertShad);
  262.   glDeleteShader(fragShad);
  263.  
  264.   glUseProgram(shadProg);
  265.   zgl_Enable(DEPTH_BUFFER);
  266.   glDepthMask(GL_TRUE);
  267.   glDepthFunc(GL_LEQUAL);
  268.   glDepthRange(0.0, 1.0);
  269. end;
  270.  
  271. procedure Draw;
  272. begin
  273.   // RU: Тут "рисуем" что угодно :)
  274.   // EN: Here "draw" anything :)        // это не обязательно
  275.   glClearDepth(1);
  276. //  glUseProgram(shadProg);             // это не обязательно
  277. //  glBindVertexArray(vao);             // это не обязательно
  278.   glDrawArrays(GL_TRIANGLES, 0, 3);
  279.  
  280. //  glUseProgram(0);                    // это не обязательно
  281. end;
  282.  
  283. procedure Update( dt : Double );
  284. begin
  285.   // RU: Эта функция наземенима для реализация плавного движения чего-либо, т.к. точность таймеров ограничена FPS.
  286.   // EN: This function is the best way to implement smooth moving of something, because accuracy of timers are restricted by FPS.
  287. end;
  288.  
  289. // RU: Пример использования таймера.
  290. // EN: An example of using a timer.
  291. procedure Timer;
  292. begin
  293.   // RU: Будем в заголовке показывать количество кадров в секунду.
  294.   // EN: Caption will show the frames per second.
  295.   wnd_SetCaption( 'test OpenGL 3.3. [ FPS: ' + u_IntToStr( zgl_Get( RENDER_FPS ) ) + ' ]' );
  296. end;
  297.  
  298. procedure KeyMouseEvent;
  299. begin
  300.   // RU: Функция обработки клавиатуры, мыши, джойстика и тачпада. Все события связанные с ними очищаются после её обработки.
  301.   //     Все попытки обработать клавиатуру, мышь или тачпад в других функциях могут привести к непредвиденным ситуациям.
  302.   // EN: Keyboard, mouse, joystick and touchpad handling function. All events associated with them are cleared after processing it.
  303.   //     Any attempt to handle the keyboard, mouse, or touchpad in other functions may lead to unexpected situations.
  304. end;
  305.  
  306. procedure Quit;
  307. begin
  308.   // RU: События которые надо произвести по завершению программы.
  309.   // EN: Events to be performed at the end of the program.
  310.   // это нужно или нет?
  311.   glBindBuffer(GL_ARRAY_BUFFER, 0);
  312.   glDeleteBuffers(2, @vboHandles);
  313.   glBindVertexArray(0);
  314.   glDeleteVertexArrays(1, @vao);
  315.  
  316.   glUseProgram(0);
  317.  
  318.   glDeleteProgram(shadProg);
  319. end;
  320.  
  321. Begin
  322.   // RU: Для загрузки/создания каких-то своих настроек/профилей/etc. можно получить путь к домашенему каталогу пользователя, или к исполняемому файлу(не работает для GNU/Linux).
  323.   // EN: For loading/creating your own options/profiles/etc. you can get path to user home directory, or to executable file(not works for GNU/Linux).
  324.   DirApp  := utf8_Copy( PAnsiChar( zgl_Get( DIRECTORY_APPLICATION ) ) );
  325.   DirHome := utf8_Copy( PAnsiChar( zgl_Get( DIRECTORY_HOME ) ) );
  326.  
  327.   // RU: Устанавливаем интервал на обработку событий клавиатуры, мыши, тачпада. И регистрируем процедуру.
  328.   //     Вызывать zgl_SetEventInterval не обязательно. Значение 16 стоит по умолчанию.
  329.   // EN: We set the interval for processing keyboard, mouse, touchpad events. And we register the procedure.
  330.   //     Calling zgl_SetEventInterval is optional. The default is 16.
  331.   zgl_SetEventsInterval(16);
  332.   zgl_Reg(SYS_EVENTS, @KeyMouseEvent);
  333.  
  334.   // RU: Создаем таймер с интервалом 1000мс.
  335.   // EN: Create a timer with interval 1000ms.
  336.   TimeStart := timer_Add( @Timer, 1000, t_Start );
  337.  
  338.   // RU: Регистрируем процедуру, что выполнится сразу после инициализации ZenGL.
  339.   // EN: Register the procedure, that will be executed after ZenGL initialization.
  340.   zgl_Reg( SYS_LOAD, @Init );
  341.   // RU: Регистрируем процедуру, где будет происходить рендер.
  342.   // EN: Register the render procedure.
  343.   zgl_Reg( SYS_DRAW, @Draw );
  344.   // RU: Регистрируем процедуру, которая будет принимать разницу времени между кадрами.
  345.   // EN: Register the procedure, that will get delta time between the frames.
  346.   zgl_Reg( SYS_UPDATE, @Update );
  347.   // RU: Регистрируем процедуру, которая выполнится после завершения работы ZenGL.
  348.   // EN: Register the procedure, that will be executed after ZenGL shutdown.
  349.   zgl_Reg( SYS_EXIT, @Quit );
  350.   // RU: пользовательский ViewPort. В данном случае это не обязательно.
  351.   // EN: custom ViewPort. In this case it is not necessary.
  352.   zgl_Reg(OGL_VIEW_PORT, @UserSetViewPort);
  353.   // RU: пользовательский режим 2d или 3d.
  354.   // EN: custom 2d or 3d mode.
  355.   zgl_Reg(OGL_USER_MODE, @UserMode);
  356.  
  357.   // RU: Устанавливаем заголовок окна.
  358.   // EN: Set the caption of the window.
  359.   wnd_SetCaption(utf8_Copy('01 - Initialization'));
  360.   // RU: Разрешаем курсор мыши.
  361.   // EN: Allow to show the mouse cursor.
  362.   wnd_ShowCursor( TRUE );                        // по умолчанию стоит
  363.  
  364.   // RU: Указываем первоначальные настройки.
  365.   // EN: Set screen options.
  366.   zgl_SetParam(800, 600, false, false);
  367.  
  368.   {$IfDef GL_VERSION_3_0}
  369.   // RU: Устанавливаем контекст OpenGL 3.3. Для этого надо включить  дефайн "USE_GL_33" и отключить "USE_MIN_OPENGL" в GLdefine.cfg.
  370.   // EN: Setting context OpenGL 3.3. To do this, enable the "USE_GL_33" define and disable "USE_MIN_OPENGL" in GLdefine.cfg.
  371.   SetGLVersionAndFlags(3, 3);
  372.   {$EndIf}
  373.  
  374.   // RU: Инициализируем ZenGL.
  375.   // EN: Initialize ZenGL.
  376.   zgl_Init();
  377. End.
  378.  
Вы можете скопировать первую демку и дополнить её недостающим кодом что я привёл. В файле GLdefine.cfg включите определения USE_GL_21 и USE_GL_33.
Может кому пригодится! В дальнейшем определённый функционал будет включён в ZenGL чтобы не приходилось переписывать по нескольку раз один и тот же код. На самом деле я уже добавляю этот функционал в ZenGL, ведь я хочу подключить GLES 2.0 и выше в Android. Заголовки уже все переведены, а вот опыта работы с GLES не хватает. Поэтому и начал рассматривать демки по работе с шейдерами,VAO, VBO и матрицами. Чтоб потом ни чего не упустить.
Google translate:
You can copy the first demo and supplement it with the missing code that I provided. In the GLdefine.cfg file, include the USE_GL_21 and USE_GL_33 definitions.
Maybe someone will find it useful! In the future, certain functionality will be included in ZenGL so that the same code does not have to be rewritten several times. In fact, I'm already adding this functionality to ZenGL, because I want to connect GLES 2.0 and higher to Android. All the titles have already been translated, but there is not enough experience working with GLES. That's why I started looking at demos on working with shaders, VAO, VBO and matrices. So that you don’t miss anything later.  ;)
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #13 on: October 19, 2023, 02:41:41 pm »
В связи с выпуском ZenGL 4.3 и возможностью сборки проектов используя FPC/Lazarus + Android Studio прикладываю видео показывающие как можно собрать демки ZenGL.
Необходимый минимум для сборки проектов. И сборка проектов с помощью FPC из командной строки и Android Studio.
Сборка проектов используя Lazarus и Android Studio.
Видео на русском языке, но я надеюсь основная часть будет понятна и без перевода.   :-[

------------------------------------------------------------
Google translate:
In connection with the release of ZenGL 4.3 and the ability to build projects using FPC/Lazarus + Android Studio, I am attaching a video showing how to build ZenGL demos.
The required minimum for assembling projects. And building projects using FPC from the command line and Android Studio.
Building projects using Lazarus and Android Studio.
The video is in Russian, but I hope the main part will be clear without translation. :-[

ZenGL 4.3 download.
« Last Edit: October 19, 2023, 02:46:56 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Seenkao

  • Hero Member
  • *****
  • Posts: 545
    • New ZenGL.
Re: ZenGL +android + MacOS Cocoa (beta)
« Reply #14 on: November 11, 2023, 07:08:55 am »
Rus:
Обновлена последняя версия ZenGL. В связи с утраченной функциональностью.
Там же добавлен Light Engine 2D с правками под последнюю версию ZenGL. Читайте вложенный ReadME.txt.
Скачать можно по той же ссылке.

Eng:
Latest version of ZenGL updated. Due to lost functionality.
Light Engine 2D was also added there with edits for the latest version of ZenGL. Read the attached ReadME.txt.
You can download it from the same link.

 8-)
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

 

TinyPortal © 2005-2018