A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

shaders.cc 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "shaders.h"
  2. namespace Cygnet::Shaders {
  3. const char *spriteVx = R"glsl(
  4. #define TILE_SIZE 32.0
  5. uniform mat3 camera;
  6. uniform mat3 transform;
  7. uniform vec2 frameSize;
  8. uniform vec2 frameInfo; // frame count, frame index
  9. attribute vec2 vertex;
  10. varying vec2 v_texCoord;
  11. void main() {
  12. // Here, I'm basically treating 1/(TILE_SIZE*16) as half the size of a "pixel".
  13. // It's just an arbitrary small number, but it works as an offset to make sure
  14. // neighbouring parts of the atlas don't bleed into the frame we actually
  15. // want to draw due to (nearest neighbour) interpolation.
  16. float pixoffset = (1.0 - vertex.y * 2.0) / (frameSize.y * TILE_SIZE * 16.0);
  17. v_texCoord = vec2(
  18. vertex.x,
  19. (frameSize.y * frameInfo.y + (frameSize.y * vertex.y)) /
  20. (frameSize.y * frameInfo.x) + pixoffset);
  21. vec3 pos = camera * transform * vec3(vertex * frameSize, 1);
  22. gl_Position = vec4(pos.xy, 0, 1);
  23. }
  24. )glsl";
  25. const char *spriteFr = R"glsl(
  26. precision mediump float;
  27. varying vec2 v_texCoord;
  28. uniform sampler2D tex;
  29. void main() {
  30. gl_FragColor = texture2D(tex, v_texCoord);
  31. }
  32. )glsl";
  33. const char *chunkVx = R"glsl(
  34. uniform mat3 camera;
  35. uniform vec2 pos;
  36. attribute vec2 vertex;
  37. varying vec2 v_tileCoord;
  38. void main() {
  39. vec3 pos = camera * vec3(pos + vertex, 1);
  40. gl_Position = vec4(pos.xy, 0, 1);
  41. v_tileCoord = vec2(vertex.x, vertex.y);
  42. }
  43. )glsl";
  44. const char *chunkFr = R"glsl(
  45. precision mediump float;
  46. #define TILE_SIZE 32.0
  47. #define CHUNK_WIDTH 64
  48. #define CHUNK_HEIGHT 64
  49. varying vec2 v_tileCoord;
  50. uniform sampler2D tileAtlas;
  51. uniform vec2 tileAtlasSize;
  52. uniform sampler2D tiles;
  53. void main() {
  54. vec2 tilePos = floor(vec2(v_tileCoord.x, v_tileCoord.y));
  55. vec4 tileColor = texture2D(tiles, tilePos / vec2(CHUNK_WIDTH, CHUNK_HEIGHT));
  56. float tileID = floor((tileColor.r * 256.0 + tileColor.a) * 256.0);
  57. // 1/(TILE_SIZE*16) plays the same role here as in the sprite vertex shader.
  58. vec2 offset = v_tileCoord - tilePos;
  59. vec2 pixoffset = (1.0 - offset * 2.0) / (TILE_SIZE * 16.0);
  60. vec2 atlasPos = vec2(
  61. pixoffset.x + tileID + offset.x,
  62. pixoffset.y + floor(tileID / tileAtlasSize.x) + offset.y);
  63. gl_FragColor = texture2D(tileAtlas, atlasPos / tileAtlasSize);
  64. }
  65. )glsl";
  66. }