Recent

Author Topic: FreeGlut  (Read 7300 times)

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
FreeGlut
« on: October 09, 2020, 08:01:19 am »
Хотелось бы знать, куда обратиться, чтоб в FreePascal(Lazarus), вместо Glut сделали указание на FreeGlut, или хотя бы возможность подменять Glut на FreeGlut.

Указания в библиотеке идут на Glut, а в Glut прописан FreeGlut, но с библиотекой от Glut. А надо именно прописывать FreeGlut.

Эта проблема проявляется на Windows и MacOS, для Linux оказалось достаточно установить библиотеку.

FreeGlut работает как с устаревшим функционалом, так и с шейдерами! На MacOS я так же запустил, единственно не смог проверить шейдеры, не поддерживает видеокарта OpenGL больше 2.1.

Для Windows скачать FreeGlut и использовать нужную версию.

Для MacOS: XQuartz - скачиваем и устанавливаем.
Brew - следуем инструкциям.

Google translate:
I would like to know where to go, so that in FreePascal (Lazarus), instead of Glut, they made an indication of FreeGlut, or at least the ability to replace Glut with FreeGlut.

The directions in the library go to Glut, and in Glut FreeGlut is registered, but with a library from Glut. And you just need to register FreeGlut.

This problem manifests itself on Windows and MacOS, for Linux it turned out to be enough to install the library.

FreeGlut works with both legacy features and shaders! I also ran it on MacOS, the only thing I could not check the shaders, does not support the OpenGL video card more than 2.1.

For Windows, download FreeGlut and use the correct version.

For MacOS: XQuartz - download and install.
Brew - follow the instructions.

Code: Pascal  [Select][+][-]
  1. program Glut_01;
  2.  
  3. {$mode objfpc}{$H+}
  4. {.$Define CORE_GL}
  5. uses
  6.   dynlibs, sysutils,
  7.   GL, glu, Glut, FreeGlut, GLext;
  8.  
  9. const
  10.   AppWidth = 800;
  11.   AppHeight = 600;
  12.  
  13. type
  14.   point = array[1..2] of GLfloat;
  15.  
  16.   {$IfDef CORE_GL}
  17.   TShader = record
  18.     vbo_point, vao_point, shaderProgram, vertexArrayObject: GLuint;
  19.     uniform_viewportSize: GLint;
  20.   end;
  21.  
  22.   TAAPLVertex = record
  23.     position: array [0..1] of single;
  24.     color: array [0..2] of single;
  25.   end;
  26.   {$EndIf}
  27.  
  28. var
  29.   {$IfnDef CORE_GL}
  30.   p: point = (0.0, 0.0);
  31.   vertices: array[1..3] of point = ((0.0, 0.0), (400.0, 600.0),(800.0, 0.0));
  32.   {$Else}
  33.   gOffsetXY: point = (0, 0);
  34.   gSize: Single = 100;
  35.   gShader: TShader;
  36.   verts: array[0..2] of TAAPLVertex;
  37.  
  38.   GLErrorStr: string = '';
  39.   {$EndIf}
  40.  
  41. {$IFDEF CORE_GL}
  42. const
  43. //Simple Vertex Shader
  44.     kVert = '#version 330'
  45. +#10'layout(location = 0) in vec2 position;'
  46. +#10'layout(location = 1) in vec3 color;'
  47. +#10'out vec3 fClr;'
  48. +#10'uniform vec2 viewportSize;'
  49. +#10'void main() {'
  50. +#10'    gl_Position = vec4((position / (viewportSize/2)), 0.0, 1.0);'
  51. +#10'    fClr = color;'
  52. +#10'}';
  53.  
  54. //Simple Fragment Shader
  55. kFrag = '#version 330'
  56. +#10'in vec3 fClr;'
  57. +#10'out vec4 color;'
  58. +#10'void main() {'
  59. +#10'    color = vec4(fClr, 1);'
  60. +#10'}';
  61.  
  62. procedure ReportErrorsGL(glObjectID: GLuint);
  63. var
  64.   s : string;
  65.   maxLength : GLint;
  66. begin
  67.   glGetShaderiv(glObjectID, GL_INFO_LOG_LENGTH, @maxLength);
  68.   if (maxLength < 2) then exit;
  69.   setlength(s, maxLength);
  70.   glGetShaderInfoLog(glObjectID, maxLength, @maxLength, @s[1]);
  71.   s:=trim(s);
  72.   if GLErrorStr = '' then begin
  73.      GLErrorStr := 'GLSL error '+s;
  74.      {$IFDEF UNIX}writeln(GLErrorStr); {$ENDIF}
  75.   end;
  76. end;
  77.  
  78. procedure GetError(p: integer; str: string = '');  //report OpenGL Error
  79. var
  80.   Error: GLenum;
  81.   s: string;
  82. begin
  83. Error := glGetError();
  84. if Error = GL_NO_ERROR then exit;
  85.   s := inttostr(p)+'->';
  86. if Error = GL_INVALID_ENUM then
  87.     s := s+'GL_INVALID_ENUM'
  88. else if Error = GL_INVALID_VALUE then
  89.     s := s+'GL_INVALID_VALUE' //out of range https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glGetError.xml
  90. else
  91.      s := s + inttostr(Error);
  92. if GLErrorStr = '' then begin
  93.     GLErrorStr := 'GLSL error '+str+s;
  94.     {$IFDEF UNIX}writeln(GLErrorStr);{$ENDIF}
  95. end;
  96. end;
  97.  
  98. function compileShaderOfType (shaderType: GLEnum;  shaderText: string): GLuint;
  99. var
  100.    status: GLint;
  101. begin
  102.      result := glCreateShader(shaderType);
  103.      glShaderSource(result, 1, PChar(@shaderText), nil);
  104.      glCompileShader(result);
  105.      ReportErrorsGL(result);
  106.      status := 0;
  107.      glGetShaderiv(result, GL_COMPILE_STATUS, @status);
  108.      if (status =  0) and (GLErrorStr = '') then begin //report compiling errors.
  109.         GLErrorStr := 'GLSL shader compile failure';
  110.      end;
  111. end;
  112.  
  113. procedure ReportCompileProgramError(glObjectID: GLuint);
  114. var
  115.   s : string;
  116.   maxLength : GLint;
  117. begin
  118.   glGetProgramiv(glObjectID, GL_LINK_STATUS, @maxLength);
  119.   //if (maxLength = GL_TRUE) then exit;
  120.   if (maxLength = 1) then exit; //DGL  GL_TRUE
  121.   maxLength := 4096;
  122.   setlength(s, maxLength);
  123.   glGetProgramInfoLog(glObjectID, maxLength, @maxLength, @s[1]);
  124.   if maxLength < 1 then begin
  125.      if GLErrorStr = '' then
  126.         GLErrorStr := ('Program compile error (unspecified)');
  127.      exit
  128.   end;
  129.   s:=trim(s);
  130.   if (length(s) < 2) then exit;
  131.   if GLErrorStr = '' then
  132.           GLErrorStr := ('Program compile error '+s);
  133. end;
  134.  
  135. function  initVertFrag(vert, frag: string): GLuint;
  136. var
  137.    fs, vs: GLuint;
  138. begin
  139.   result := 0;
  140.   vs := 0;
  141.   glGetError();
  142.   result := glCreateProgram();
  143.   if (length(vert) > 0) then begin
  144.      vs := compileShaderOfType(GL_VERTEX_SHADER, vert);
  145.      if (vs = 0) then exit;
  146.      glAttachShader(result, vs);
  147.   end;
  148.   fs := compileShaderOfType(GL_FRAGMENT_SHADER, frag);
  149.   if (fs = 0) then exit;
  150.   glAttachShader(result, fs);
  151.   glLinkProgram(result);
  152.   ReportCompileProgramError(result);
  153.   if (length(vert) > 0) then begin
  154.      glDetachShader(result, vs);
  155.      glDeleteShader(vs);
  156.   end;
  157.   glDetachShader(result, fs);
  158.   glDeleteShader(fs);
  159.   GetError(123,'newShader');
  160.   glGetError();
  161. end;
  162.  
  163. function  initVertFragX(vert, frag: string): GLuint;
  164. var
  165.    fr, vt: GLuint;
  166. begin
  167.     result := 0;
  168.     glGetError(); //<- ignore proior errors
  169.     vt := compileShaderOfType(GL_VERTEX_SHADER, vert);
  170.     fr := compileShaderOfType(GL_FRAGMENT_SHADER, frag);
  171.     if (fr = 0) or (vt = 0) then exit;
  172.     result := glCreateProgram();
  173.     glAttachShader(result, vt);
  174.     glAttachShader(result, fr);
  175.     glBindFragDataLocation(result, 0, 'FragColor');
  176.     glLinkProgram(result);
  177.     glDeleteShader(vt);
  178.     glDeleteShader(fr);
  179.     GetError(1,'initX');
  180.     glGetError(); //<- ignore proior errors
  181.  
  182. end;
  183.  
  184. procedure LoadBufferData (isInit: boolean);
  185. const
  186.     kATTRIB_POINT = 0;
  187.     kATTRIB_COLOR = 1;
  188. var
  189.    verts: array[0..2] of TAAPLVertex;
  190. begin
  191.   verts[0].position[0] := gOffsetXY[1] + gSize;
  192.   verts[0].position[1] := gOffsetXY[2] - gSize;
  193.   verts[0].color[0] := 1;
  194.   verts[0].color[1] := 0;
  195.   verts[0].color[2] := 0;
  196.   verts[1].position[0] := gOffsetXY[1] - gSize;
  197.   verts[1].position[1] := gOffsetXY[2] - gSize;
  198.   verts[1].color[0] := 0;
  199.   verts[1].color[1] := 1;
  200.   verts[1].color[2] := 0;
  201.   verts[2].position[0] := gOffsetXY[1];
  202.   verts[2].position[1] := gOffsetXY[2] + gSize;
  203.   verts[2].color[0] := 0;
  204.   verts[2].color[1] := 0;
  205.   verts[2].color[2] := 2;
  206.   if (not isInit) then begin
  207.      glBindBuffer(GL_ARRAY_BUFFER, gShader.vbo_point);
  208.      glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(verts), @verts[0]);
  209.      glBindBuffer(GL_ARRAY_BUFFER, 0);
  210.      exit;
  211.   end;
  212.   glGenBuffers(1, @gShader.vbo_point);
  213.   glBindBuffer(GL_ARRAY_BUFFER, gShader.vbo_point);
  214.   glBufferData(GL_ARRAY_BUFFER, sizeof(verts), @verts[0], GL_STATIC_DRAW);
  215.   glBindBuffer(GL_ARRAY_BUFFER, 0);
  216.   // Prepare vertrex array object (VAO)
  217.   //   glGenVertexArrays intoduced with OpenGL 3.0
  218.   glGenVertexArrays(1, @gShader.vao_point);
  219.   glBindVertexArray(gShader.vao_point);
  220.   glBindBuffer(GL_ARRAY_BUFFER, gShader.vbo_point);
  221.   glVertexAttribPointer(kATTRIB_POINT, 2, GL_FLOAT, GL_FALSE, 5*4, PChar(0));
  222.   glEnableVertexAttribArray(kATTRIB_POINT);
  223.   glVertexAttribPointer(kATTRIB_COLOR, 3, GL_FLOAT, GL_FALSE, 5*4, PChar(sizeof(single)*2));
  224.   glEnableVertexAttribArray(kATTRIB_COLOR);
  225.   glBindBuffer(GL_ARRAY_BUFFER, 0);
  226.   glBindVertexArray(0);
  227.   gShader.uniform_viewportSize := glGetUniformLocation(gShader.shaderProgram, pAnsiChar('viewportSize'));
  228. end;
  229. {$ENDIF}
  230.  
  231. procedure MyGlutInit(ParseCmdLine: Boolean);            // у меня уже создана, скопирую
  232. var
  233.   Cmd: array of PChar;
  234.   CmdCount, i: Integer;
  235. begin
  236.   if ParseCmdLine then
  237.      CmdCount := ParamCount + 1
  238.   else
  239.     CmdCount := 1;
  240.   SetLength(Cmd, CmdCount);
  241.   for i := 0 to CmdCount - 1 do
  242.     Cmd[i] := PChar(ParamStr(i));
  243.   GlutInit(@CmdCount, @Cmd);
  244. end;
  245.  
  246. procedure MyDrawScene; cdecl;
  247. {$IfnDef CORE_GL}
  248. var
  249.   i, j: Integer;
  250. {$EndIf}
  251. begin
  252.   {$IfnDef CORE_GL}
  253.   glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
  254.   glLoadIdentity;
  255.   glColor3f(0, 0, 0);
  256.   for i := 1 to 250000 do
  257.   begin
  258.     j := Random(3) + 1;
  259.     p[1] := (p[1] + vertices[j, 1]) / 2;
  260.     p[2] := (p[2] + vertices[j, 2]) / 2;
  261.     glBegin(GL_POINTS);
  262.       glVertex2fv(@p);
  263.     glEnd;
  264.   end;
  265.   {$Else}
  266.   LoadBufferData(false);
  267.   glClearColor(0.0, 0.0, 0.7, 1.0); //Set blue background
  268.   glClear(GL_COLOR_BUFFER_BIT);
  269.   glDisable(GL_DEPTH_TEST);
  270.   glUseProgram(gShader.shaderProgram);
  271.   glUniform2f(gShader.uniform_viewportSize, AppWidth, AppHeight);
  272.   glBindVertexArray(gShader.vao_point);
  273.   glDrawArrays(GL_TRIANGLE_STRIP, 0, 3);
  274.   glBindVertexArray(0);
  275.  
  276.   glUseProgram(0);
  277.   {$ENDIF}
  278.   glutSwapBuffers;
  279. end;
  280.  
  281. procedure MyResizeScene(width, height: Integer); cdecl;
  282. begin
  283.   if height = 0 then height := 1;
  284.   glViewport(0, 0, width, height);
  285.   glMatrixMode(GL_PROJECTION);
  286.   glLoadIdentity;
  287.   gluOrtho2D(0, width, 0, height);
  288. //  gluPerspective(45, width / height, 0.1, 1000);
  289.   glMatrixMode(GL_MODELVIEW);
  290.   glLoadIdentity;
  291. end;
  292.  
  293. procedure GLKeyboard(Key: Byte; x, y: LongInt); cdecl;
  294. begin
  295.   if Key =  27 then halt(0);
  296. end;
  297.  
  298. var
  299.   ScreenWidth, ScreenHeight: Integer;
  300. begin
  301.   {$IfDef MacOSAll}
  302.           // для MacOS вручную прописываем путь, куда установили FreeGlut
  303.           // for MacOS, manually write the path where FreeGlut was installed
  304.   LoadFreeGlut(LoadLibrary('/usr/local/Cellar/freeglut/3.2.1/lib/libglut.dylib'));
  305.           // у меня был путь "/usr/local/Cellar/freeglut/3.2.1" оставшуюся часть
  306.           // надо добавить (не знаю, может у кого другой путь будет)  !!! "lib/libglut.dylib" !!!!
  307.   {$EndIf}
  308.   Randomize;
  309.   MyGlutInit(True);
  310.   glutInitDisplayMode(GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH);
  311.   glutInitWindowSize(AppWidth, AppHeight);
  312.   ScreenWidth := glutGet(GLUT_SCREEN_WIDTH);
  313.   ScreenHeight :=  glutGet(GLUT_SCREEN_HEIGHT);
  314.   glutInitWindowPosition((ScreenWidth - AppWidth) div 2, (ScreenHeight - AppHeight) div 2);
  315.  
  316.   // запрос контекста!!! В Glut нет.
  317.   // context request!!! In Glut no.
  318.   {$IfDef CORE_GL}
  319.   glutInitContextProfile(GLUT_CORE_PROFILE);
  320.   glutInitContextVersion(3, 3);
  321.   {$Else}
  322.   glutInitContextProfile(GLUT_CORE_PROFILE);
  323.   glutInitContextVersion(2, 1);
  324.   {$EndIf}
  325.  
  326.   glutCreateWindow('OpenGL - Glut');
  327.   {$IfDef CORE_GL}
  328.   Load_GL_version_3_3_CORE();
  329.   gShader.shaderProgram :=  initVertFrag(kVert,  kFrag);
  330.   LoadBufferData(true);
  331.   {$EndIf}
  332.   glClearColor(0.18, 0.20, 0.66, 0);
  333.   glutDisplayFunc(@MyDrawScene);
  334.   glutReshapeFunc(@MyResizeScene);
  335.   glutKeyboardFunc(@GLKeyboard);
  336.  
  337.   glutMainLoop;
  338. end.
  339.  
Пример для проверки. Меняйте дефайн в начале.

An example to check. Change the define at the beginning.
« Last Edit: October 09, 2020, 08:16:17 am by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

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

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: FreeGlut
« Reply #1 on: October 17, 2020, 10:36:16 am »
Оставлю здесь, может пригодится кому для информации.

FreeGlut + WinAPI:
Code: Pascal  [Select][+][-]
  1. program GLUT_non_LCL;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.   sysutils, windows,
  7.   GL, glu, FreeGlut, Glut;
  8. //  newGlut;     use FreeGlut, Glut
  9.  
  10. const
  11.   AppWidth  = 800;
  12.   AppHeight = 600;
  13.  
  14.   // мышь
  15.   MB_LEFT   = 1;
  16.   MB_RIGHT  = 2;
  17.   MB_MIDDLE = 4;
  18.  
  19. type
  20.   XYZ_Col = record
  21.     X, Y, Z: Single;
  22.     R, G, B: Single;
  23.   end;
  24.  
  25. var
  26.   ScreenWidth, ScreenHeight: Integer;
  27.   point: array[0..3] of XYZ_Col;
  28.   angle: array [0..2] of Single;
  29.   MB_Down, MB_Up: Byte;
  30.  
  31.   mouseX, mouseY: Integer;
  32.   myTimeUse: Integer = 1;
  33.   KeyDown: array[0..255] of Boolean;
  34.  
  35.   winOn: Boolean = False;
  36.   oldFPS, newFPS, maxFPS: Single;
  37.   Z: Integer = 0;
  38.  
  39. procedure glutInitPascal(ParseCmdLine: Boolean);
  40. var
  41.   Cmd: array of PChar;
  42.   CmdCount, I: Integer;
  43. begin
  44.   if ParseCmdLine then
  45.     CmdCount := ParamCount + 1
  46.   else
  47.     CmdCount := 1;
  48.   SetLength(Cmd, CmdCount);
  49.   for I := 0 to CmdCount - 1 do
  50.     Cmd[I] := PChar(ParamStr(I));
  51.   glutInit(@CmdCount, @Cmd);
  52.  
  53.   // ------------------------------------
  54.   point[0].X := 0;
  55.   point[0].Y := 1;
  56.   point[0].Z := 0;
  57.   point[0].R := 1;
  58.   point[0].G := 0;
  59.   point[0].B := 0;
  60.  
  61.   point[1].X := - 0.8;
  62.   point[1].Y := - 0.5;
  63.   point[1].Z := 0.5;
  64.   point[1].R := 0;
  65.   point[1].G := 1;
  66.   point[1].B := 0;
  67.  
  68.   point[2].X := 0.8;
  69.   point[2].Y := - 0.5;
  70.   point[2].Z := 0.5;
  71.   point[2].R := 0;
  72.   point[2].G := 0;
  73.   point[2].B := 1;
  74.  
  75.   point[3].X := 0;
  76.   point[3].Y := - 0.5;
  77.   point[3].Z := - 0.8;
  78.   point[3].R := 0.7;
  79.   point[3].G := 0;
  80.   point[3].B := 0.7;
  81.  
  82.   angle[0] := 50;
  83.   angle[1] := 3;
  84.   angle[2] := 236;
  85.   // ------------------------------------
  86.   glutGameModeString('800x600:16@60');   // обратить особое внимание! Это запрос полноэкранного режима, существует он или нет.
  87.                                       // В Linux не надо прописывать :16@60 - оно там не работает для FreeGlut
  88. end;
  89.  
  90. procedure DrawGL; cdecl;
  91. begin
  92.   glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
  93.   glLoadIdentity;
  94.  
  95.   glTranslatef(0, 0, - 3);
  96.  
  97.   glRotatef(angle[0], 1, 0, 0);
  98.   glRotatef(angle[1], 0, 1, 0);
  99. //  glRotatef(angle[2], 0, 0, 1);
  100.  
  101.   glBegin(GL_TRIANGLES);
  102.     glColor3f(point[0].R, point[0].G, point[0].B);
  103.     glVertex3f(point[0].X, point[0].Y, point[0].Z);
  104.     glColor3f(point[1].R, point[1].G, point[1].B);
  105.     glVertex3f(point[1].X, point[1].Y, point[1].Z);
  106.     glColor3f(point[2].R, point[2].G, point[2].B);
  107.     glVertex3f(point[2].X, point[2].Y, point[2].Z);
  108.  
  109.     glColor3f(point[3].R, point[3].G, point[3].B);
  110.     glVertex3f(point[3].X, point[3].Y, point[3].Z);
  111.     glColor3f(point[1].R, point[1].G, point[1].B);
  112.     glVertex3f(point[1].X, point[1].Y, point[1].Z);
  113.     glColor3f(point[2].R, point[2].G, point[2].B);
  114.     glVertex3f(point[2].X, point[2].Y, point[2].Z);
  115.  
  116.     glColor3f(point[0].R, point[0].G, point[0].B);
  117.     glVertex3f(point[0].X, point[0].Y, point[0].Z);
  118.     glColor3f(point[3].R, point[3].G, point[3].B);
  119.     glVertex3f(point[3].X, point[3].Y, point[3].Z);
  120.     glColor3f(point[2].R, point[2].G, point[2].B);
  121.     glVertex3f(point[2].X, point[2].Y, point[2].Z);
  122.  
  123.     glColor3f(point[0].R, point[0].G, point[0].B);
  124.     glVertex3f(point[0].X, point[0].Y, point[0].Z);
  125.     glColor3f(point[1].R, point[1].G, point[1].B);
  126.     glVertex3f(point[1].X, point[1].Y, point[1].Z);
  127.     glColor3f(point[3].R, point[3].G, point[3].B);
  128.     glVertex3f(point[3].X, point[3].Y, point[3].Z);
  129.   glEnd;
  130.  
  131.   glutSwapBuffers;
  132. end;
  133.  
  134. procedure ReSizeGLScene(Width, Height: Integer); cdecl;
  135. begin
  136.   if Height = 0 then
  137.     Height := 1;
  138.  
  139.   glViewport(0, 0, Width, Height);
  140.   glMatrixMode(GL_PROJECTION);
  141.   glLoadIdentity;
  142.   gluPerspective(45, Width / Height, 0.1, 1000);
  143.  
  144.   glMatrixMode(GL_MODELVIEW);
  145.   glLoadIdentity;
  146. end;
  147.  
  148. // обработка клавиатуры, нажатие!!!!    keyboard down!!!
  149. procedure GLKeyboard(Key: Byte; X, Y: LongInt); cdecl;
  150. begin
  151.   inc(z);
  152.   if Key = 27 then
  153. //    glutLeaveMainLoop;
  154.     winOn := False;                   // закрываем если Escape (close)
  155.   if (key = 119) {and (not KeyDown[Key])} then
  156.   begin
  157.     myTimeUse := myTimeUse + 10;
  158.     if myTimeUse > 200 then myTimeUse := 200;
  159.  
  160.   end;
  161.   if (key = 115) and (not KeyDown[Key]) then
  162.   begin
  163.  
  164.     if myTimeUse < 20 then
  165.       myTimeUse := myTimeUse - 3
  166.     else
  167.       myTimeUse := myTimeUse - 10;
  168.     if myTimeUse < 1 then myTimeUse := 1;
  169.   end;
  170.   KeyDown[key] := true;
  171. //  glutSetWindowTitle(PChar('time: ' + IntToStr(myTimeUse)));
  172.   glutSetWindowTitle(Pchar(IntToStr(z)));
  173. end;
  174.  
  175. // обработка отпускания клавиши    keyboard up!!!
  176. procedure GLKeyboardUp(Key: Byte; X, Y: LongInt); cdecl;
  177. begin
  178.   KeyDown[key] := False;
  179. end;
  180.  
  181. // обработка специальных клавиш, нажатие!!!!   spec keyboard down (F1, F2 ... )
  182. procedure GLSpecKeyboard(Key, X, Y: LongInt); cdecl;
  183. begin
  184.  
  185. end;
  186.  
  187. // обработка отпускания специальных клавиш    spec keyboard up
  188. procedure GLSpecKeyboardUp(Key, X, Y: LongInt); cdecl;
  189. begin
  190.  
  191. end;
  192.  
  193. // закрываем окно    close window
  194. procedure ClozeGL; cdecl;
  195. begin
  196.   winOn := False;
  197. //  glutLeaveMainLoop
  198. end;
  199.  
  200. // таймер основного процесса, возможно нужен таймер для прорисовки???
  201. procedure MyTimerGL(value: Integer); cdecl;
  202. var
  203.   i: Integer;
  204. begin
  205.   if (MB_Down and MB_LEFT) > 0 then  ;
  206.  
  207.   if (MB_Down and MB_LEFT) > 0 then ;
  208.  
  209.   angle[0] := angle[0] + 0.5;
  210.   if angle[0] > 360 then angle[0] := 0;
  211.   angle[1] := angle[1] + 0.5;
  212.   if angle[1] > 360 then angle[1] := 0;
  213.   angle[2] := angle[2] + 0.5;
  214.   if angle[2] > 360 then angle[2] := 0;
  215.  
  216.   if newFPS > (oldFPS + maxFPS) then
  217.   begin
  218.     glutPostRedisplay;
  219.     oldFPS := oldFPS + maxFPS;
  220.   end;
  221.  
  222.   glutTimerFunc(myTimeUse, @MyTimerGL, value);          // создать структуру таймеров.
  223.   newFPS := newFPS + myTimeUse;
  224. end;
  225.  
  226. // обработка мыши       mouse (left, right, middle) down/up
  227. procedure MouseGL(button, state, X, Y: Integer); cdecl;
  228. var
  229.   n: Byte;
  230. begin
  231.   n := button;
  232.  
  233.   if state = GLUT_UP then
  234.     begin
  235.      if button = GLUT_LEFT_BUTTON then
  236.      begin
  237.        MB_Down := MB_Down and (255 - MB_LEFT);
  238.        MB_Up := MB_Up or MB_LEFT;
  239.      end;
  240.      if button = GLUT_RIGHT_BUTTON then
  241.      begin
  242.        MB_Down := MB_Down and (255 - MB_RIGHT);
  243.        MB_Up := MB_Up or MB_RIGHT;
  244.      end;
  245.      if button = GLUT_MIDDLE_BUTTON then
  246.      begin
  247.        MB_Down := MB_Down and (255 - MB_MIDDLE);
  248.        MB_Up := MB_Up or MB_MIDDLE;
  249.      end;
  250.      KeyDown[n] := false;               // клавиши с минимальным кодом всё равно не используются, используем пространство для мыши
  251.     end;
  252.  
  253.   if state = GLUT_DOWN then
  254.   begin
  255.    if button = GLUT_LEFT_BUTTON then
  256.    begin
  257.      MB_Down := MB_Down or MB_LEFT;
  258.      MB_Up := MB_Up and (255 - MB_LEFT);
  259.    end;
  260.    if button = GLUT_RIGHT_BUTTON then
  261.    begin
  262.      MB_Down := MB_Down or MB_RIGHT;
  263.      MB_Up := MB_Up and (255 - MB_RIGHT);
  264.    end;
  265.    if button = GLUT_MIDDLE_BUTTON then
  266.    begin
  267.      MB_Down := MB_Down or MB_MIDDLE;
  268.      MB_Up := MB_Up and (255 - MB_MIDDLE);
  269.    end;
  270.    KeyDown[n] := true;
  271.   end;
  272.  
  273.   mouseX := X;
  274.   mouseY := Y;
  275. end;
  276.  
  277. // ролик мыши     mouse wheel
  278. procedure MouseWheelGL(wheel, dir, X, Y: Integer); cdecl;
  279. begin
  280.  
  281. end;
  282.  
  283. var
  284.   win00: Integer;
  285.   myWND: HWND;
  286. begin
  287.   glutInitPascal(true);
  288.   glutInitDisplayMode(GLUT_DOUBLE or GLUT_RGB or GLUT_DEPTH);
  289.   glutInitWindowSize(AppWidth, AppHeight);
  290.        //----------------------------------------
  291.   glutInitContextVersion(2, 1);
  292.   glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
  293.        //----------------------------------------
  294.   ScreenWidth := glutGet(GLUT_SCREEN_WIDTH);
  295.   ScreenHeight := glutGet(GLUT_SCREEN_HEIGHT);
  296.   glutInitWindowPosition((ScreenWidth - AppWidth) div 2, (ScreenHeight - AppHeight) div 2);
  297.   win00 := glutCreateWindow('OpenGL testing mouse and keyboard.');
  298.  
  299.   // хендл окна
  300.   myWND := WindowFromDC(wglGetCurrentDC);
  301.  
  302.   // устанавливаем стиль окна   window style, disable window resizing
  303.   SetWindowLongPtr(myWND, GWL_STYLE, WS_CAPTION or WS_MINIMIZEBOX or WS_SYSMENU or WS_VISIBLE);
  304.   // устанавливаем размеры окна.   without this, the window is larger than the initially specified
  305.   SetWindowPos(myWND, HWND_TOPMOST, (ScreenWidth - AppWidth) div 2, (ScreenHeight - AppHeight) div 2, AppWidth, AppHeight, SWP_NOACTIVATE);
  306.  
  307.   glClearColor(0.48, 0.6, 0.86, 1.0);
  308.  
  309. // initializing
  310.   glutDisplayFunc(@DrawGL);
  311.   glutReshapeFunc(@ResizeGLScene);
  312.   glutKeyboardFunc(@GLKeyboard);
  313.   glutKeyboardUpFunc(@GLKeyboardUp);
  314.   glutCloseFunc(@ClozeGL);
  315.   glutMouseFunc(@MouseGL);
  316.   glutMouseWheelFunc(@MouseWheelGL);
  317.   glutSpecialFunc(@GLSpecKeyboard);
  318.   glutSpecialUpFunc(@GLSpecKeyboardUp);
  319.  
  320.   glClearDepth(1.0);
  321.   glDepthFunc(GL_LESS);
  322.   glEnable(GL_DEPTH_TEST);
  323.  
  324.   oldFPS := 0;
  325.   newFPS := 0;
  326.   maxFPS := 1000 / 60;
  327.   winOn := True;
  328.  
  329.   if glutGameModeGet(GLUT_GAME_MODE_POSSIBLE) = 1 then    // а здесь, мы проверяем существует ли запрошенный в начале программы
  330.     glutTimerFunc(50, @MyTimerGL, 0);                      // режим (800х600), и включаем таймер, если режим существует
  331.  
  332.   while winOn do
  333.   begin
  334.     glutMainLoopEvent;
  335.     inc(z);
  336.   end;
  337.   glutLeaveMainLoop;      // disable window processes
  338.   glutDestroyWindow(win00);    // we destroy the window manually
  339. end.
« Last Edit: October 17, 2020, 10:45:21 am by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

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

AlexTP

  • Hero Member
  • *****
  • Posts: 2400
    • UVviewsoft
Re: FreeGlut
« Reply #2 on: October 17, 2020, 10:43:11 am »
>куда обратиться, чтоб в FreePascal(Lazarus), вместо Glut сделали указание на FreeGlut

Какое указание, где? в каком-то юните стоит какая-то загрузка Glut? Почему не юзать не этот модуль а модуль FreeGlut?
Где именно место в LCL где грузится "плохая либа"?
« Last Edit: October 17, 2020, 10:46:23 am by Alextp »

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: FreeGlut
« Reply #3 on: October 17, 2020, 11:00:07 am »
Alextp, при установке Lazarus - GLUT установлено изначально, и ни какими средствами вы не заставите использовать FreeGlut, пока не установите FreeGlut на систему. Но, после установки, обращаться (почему-то) многое будет всё равно к изначальным библиотекам GLUT, вместо того чтоб было прописано использовать FreeGlut (не считая Linux, там просто подменяется библиотека).

google translate:
Alextp, when installing Lazarus - GLUT is preinstalled, and by no means can you force FreeGlut to be used until FreeGlut is installed on the system. But, after installation, (for some reason) a lot will still refer to the original GLUT libraries, instead of using FreeGlut (apart from Linux, the library is simply replaced there).

Где именно место в LCL где грузится "плохая либа"?
Извиняюсь, что?

Тут не идёт речи об LCL. Изначально вы ни какими методами не заставите FreeGlut работать с LCL. Последний код, может поможет, там есть возможность подмены окна средствами WinAPI на другое созданное окно (удалять потом надо будет оба окна или сразу удалять окно, как только подменили его). Используйте для этого SetWindowLongPtr (в Windows).

google translate:
Sorry, what?

There is no question of LCL here. Initially, you will not force FreeGlut to work with LCL by any means. The last code may help, there is a possibility of replacing a window using WinAPI to another created window (then you will have to delete both windows or immediately delete as soon as the window was replaced). Use SetWindowLongPtr for this (on Windows).
« Last Edit: October 17, 2020, 11:11:09 am by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

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

AlexTP

  • Hero Member
  • *****
  • Posts: 2400
    • UVviewsoft
Re: FreeGlut
« Reply #4 on: October 17, 2020, 12:05:48 pm »
>Но, после установки, обращаться (почему-то) многое будет всё равно к изначальным библиотекам GLUT, вместо того чтоб было прописано использовать FreeGlut

Только скажу что обычно делают так- в сорцах Laz/FPC ищут привязки к либам (GLUT). Это может быть что-то типа константы lib_gl='libglut.so.1' (в винде .dll, в Мак .dylib), это надо найти и уже там делать патч - грузить через "dlopen" уже не эту либу а например 'libfreeglut.so'..

PascalDragon

  • Hero Member
  • *****
  • Posts: 5462
  • Compiler Developer
Re: FreeGlut
« Reply #5 on: October 17, 2020, 12:19:25 pm »
>куда обратиться, чтоб в FreePascal(Lazarus), вместо Glut сделали указание на FreeGlut

Какое указание, где? в каком-то юните стоит какая-то загрузка Glut? Почему не юзать не этот модуль а модуль FreeGlut?
Где именно место в LCL где грузится "плохая либа"?

We're in the international part of the forum here. Please at least provide English translations in addition to any foreign language (like Seenkao did).

Seenkao

  • Hero Member
  • *****
  • Posts: 549
    • New ZenGL.
Re: FreeGlut
« Reply #6 on: October 17, 2020, 12:50:25 pm »
Alextp, я знаю как это делается, но это не отменяет того, что если надо выкладывать код, чтоб он работал у всех, то надо сразу делать свою библиотеку, которая обращается к нужным файлам, а не библиотеку FreeGlut, в которой идёт указание через Glut и автоматически сводит на нет все произведённые действия.

google translate:
Alextp, I know how this is done, but this does not negate the fact that if you need to lay out the code so that it works for everyone, then you need to immediately create your own library that refers to the necessary files, and not the FreeGlut library , in which there is an indication through Glut and automatically nullifies all the actions performed.

И, вас просят делать переводы, этот форум английский, поэтому хотя бы через переводчик, чтоб было понятно людям о чём общаемся.
« Last Edit: October 17, 2020, 03:11:00 pm by Seenkao »
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

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

 

TinyPortal © 2005-2018