gui.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. vector=require("vector")
  2. local gui={}
  3. local gui_vertex_shader=[[
  4. #version 450
  5. layout (location=0) in vec2 pos;
  6. layout (location=1) in vec2 texcoord;
  7. uniform vec2 rpos;
  8. uniform vec2 rsize;
  9. out vec2 otexcoord;
  10. void main()
  11. {
  12. gl_Position=vec4(vec2(pos.x*rsize.x,pos.y*rsize.y)+rpos,0.0,1.0);
  13. otexcoord=rpos+texcoord*rsize;
  14. }]]
  15. local gui_fragment_shader=[[
  16. #version 450
  17. uniform vec4 color;
  18. uniform vec2 rsize;
  19. uniform vec2 rpos;
  20. in vec2 otexcoord;
  21. out vec4 ocolor;
  22. float dist_Rect(vec2 pixel, vec2 rect_center, vec2 rect_size) {
  23. vec2 d = abs(rect_center - pixel) - rect_size*0.5;
  24. return length(max(d,0.0));
  25. }
  26. float dist_RoundRect(vec2 pixel, vec2 rect_center, vec2 rect_size, float rect_round) {
  27. return dist_Rect(pixel, rect_center, rect_size - vec2(rect_round*2.0)) - rect_round;
  28. }
  29. void main()
  30. {
  31. float d = dist_RoundRect(otexcoord, rpos+rsize*0.5, rsize,0.05);
  32. if(d<0)
  33. ocolor=vec4(color.rgb,color.a);
  34. else
  35. ocolor=vec4(0.0,0.0,0.0,0.0);
  36. }]]
  37. gui.init=function(w)
  38. local shader=w:shader(w:vertexshader(gui_vertex_shader),w:fragmentshader(gui_fragment_shader))
  39. local vd=shader:vertex("pos")
  40. vd:add(0.0,0.0)
  41. vd:add(1.0,0.0)
  42. vd:add(1.0,1.0)
  43. vd:add(1.0,1.0)
  44. vd:add(0.0,1.0)
  45. vd:add(0.0,0.0)
  46. local texcoord=shader:vertex("texcoord")
  47. texcoord:add(0.0,0.0)
  48. texcoord:add(1.0,0.0)
  49. texcoord:add(1.0,1.0)
  50. texcoord:add(1.0,1.0)
  51. texcoord:add(0.0,1.0)
  52. texcoord:add(0.0,0.0)
  53. local vbo=vd:vbo()
  54. local vbo2=texcoord:vbo()
  55. local vao=w:vao("triangles",vbo,vbo2)
  56. return setmetatable({win=w,vao=vao},{__index=gui})
  57. end
  58. gui.draw=function(self,x,y,w,h,color)
  59. local width,height=self.win:getsize()
  60. local oh=h/height*2
  61. self.vao:draw({color=vector:new(table.unpack(color)),rpos=vector:new((x+2)/width*2-1,-((y-2)/height*2-1)-oh),
  62. rsize=vector:new((w-4)/width*2,(h-4)/height*2)})
  63. end
  64. return gui