SpriteBatch.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. #include "Base.h"
  2. #include "SpriteBatch.h"
  3. #include "Game.h"
  4. // Default size of a newly created sprite batch
  5. #define SPRITE_BATCH_DEFAULT_SIZE 128
  6. // Factor to grow a sprite batch by when its size is exceeded
  7. #define SPRITE_BATCH_GROW_FACTOR 2.0f
  8. // Macro for adding a sprite to the batch
  9. #define ADD_SPRITE_VERTEX(vtx, vx, vy, vz, vu, vv, vr, vg, vb, va) \
  10. vtx.x = vx; vtx.y = vy; vtx.z = vz; \
  11. vtx.u = vu; vtx.v = vv; \
  12. vtx.r = vr; vtx.g = vg; vtx.b = vb; vtx.a = va
  13. // Default sprite vertex shader
  14. #define SPRITE_VSH \
  15. "uniform mat4 u_projectionMatrix;\n" \
  16. "attribute vec3 a_position;\n" \
  17. "attribute vec2 a_texCoord;\n" \
  18. "attribute vec4 a_color;\n" \
  19. "varying vec2 v_texCoord;\n" \
  20. "varying vec4 v_color;\n" \
  21. "void main()\n" \
  22. "{\n" \
  23. "gl_Position = u_projectionMatrix * vec4(a_position, 1);\n" \
  24. "v_texCoord = a_texCoord;\n" \
  25. "v_color = a_color;\n" \
  26. "}\n"
  27. // Default sprite fragment shader
  28. #define SPRITE_FSH \
  29. "#ifdef OPENGL_ES\n" \
  30. "precision highp float;\n" \
  31. "#endif\n" \
  32. "varying vec2 v_texCoord;\n" \
  33. "varying vec4 v_color;\n" \
  34. "uniform sampler2D u_texture;\n" \
  35. "void main()\n" \
  36. "{\n" \
  37. "gl_FragColor = v_color * texture2D(u_texture, v_texCoord);\n" \
  38. "}\n"
  39. namespace gameplay
  40. {
  41. // Sprite vertex structured used for batching
  42. struct SpriteVertex
  43. {
  44. float x, y, z;
  45. float u, v;
  46. float r, g, b, a;
  47. };
  48. // Shared sprite effects
  49. static Effect* __spriteEffect = NULL;
  50. SpriteBatch::SpriteBatch()
  51. : _batch(NULL), _textureWidthRatio(0.0f), _textureHeightRatio(0.0f)
  52. {
  53. }
  54. SpriteBatch::SpriteBatch(const SpriteBatch& copy)
  55. {
  56. // hiddden
  57. }
  58. SpriteBatch::~SpriteBatch()
  59. {
  60. SAFE_DELETE(_batch);
  61. if (!_customEffect)
  62. {
  63. if (__spriteEffect->getRefCount() == 1)
  64. {
  65. __spriteEffect->release();
  66. __spriteEffect = NULL;
  67. }
  68. else
  69. __spriteEffect->release();
  70. }
  71. }
  72. SpriteBatch* SpriteBatch::create(const char* texturePath, Effect* effect, unsigned int initialCapacity)
  73. {
  74. Texture* texture = Texture::create(texturePath);
  75. SpriteBatch* batch = SpriteBatch::create(texture);
  76. SAFE_RELEASE(texture);
  77. return batch;
  78. }
  79. SpriteBatch* SpriteBatch::create(Texture* texture, Effect* effect, unsigned int initialCapacity)
  80. {
  81. assert(texture != NULL);
  82. bool customEffect = (effect != NULL);
  83. if (!customEffect)
  84. {
  85. // Create our static sprite effect.
  86. if (__spriteEffect == NULL)
  87. {
  88. __spriteEffect = Effect::createFromSource(SPRITE_VSH, SPRITE_FSH);
  89. if (__spriteEffect == NULL)
  90. {
  91. LOG_ERROR("Unable to load sprite effect.");
  92. return NULL;
  93. }
  94. effect = __spriteEffect;
  95. }
  96. else
  97. {
  98. effect = __spriteEffect;
  99. __spriteEffect->addRef();
  100. }
  101. }
  102. // Search for the first sampler uniform in the effect.
  103. Uniform* samplerUniform = NULL;
  104. for (unsigned int i = 0, count = effect->getUniformCount(); i < count; ++i)
  105. {
  106. Uniform* uniform = effect->getUniform(i);
  107. if (uniform && uniform->getType() == GL_SAMPLER_2D)
  108. {
  109. samplerUniform = uniform;
  110. break;
  111. }
  112. }
  113. if (!samplerUniform)
  114. {
  115. LOG_ERROR("No uniform of type GL_SAMPLER_2D found in sprite effect.");
  116. SAFE_RELEASE(effect);
  117. return NULL;
  118. }
  119. // Wrap the effect in a material
  120. Material* material = Material::create(effect); // +ref effect
  121. // Set initial material state
  122. material->getStateBlock()->setBlend(true);
  123. material->getStateBlock()->setBlendSrc(RenderState::BLEND_SRC_ALPHA);
  124. material->getStateBlock()->setBlendDst(RenderState::BLEND_ONE_MINUS_SRC_ALPHA);
  125. // Bind the texture to the material as a sampler
  126. Texture::Sampler* sampler = Texture::Sampler::create(texture); // +ref texture
  127. material->getParameter(samplerUniform->getName())->setValue(sampler);
  128. SAFE_RELEASE(sampler);
  129. // Define the vertex format for the batch
  130. VertexFormat::Element vertexElements[] =
  131. {
  132. VertexFormat::Element(VertexFormat::POSITION, 3),
  133. VertexFormat::Element(VertexFormat::TEXCOORD0, 2),
  134. VertexFormat::Element(VertexFormat::COLOR, 4)
  135. };
  136. VertexFormat vertexFormat(vertexElements, 3);
  137. // Create the mesh batch
  138. MeshBatch* meshBatch = MeshBatch::create(vertexFormat, Mesh::TRIANGLE_STRIP, material, true, initialCapacity > 0 ? initialCapacity : SPRITE_BATCH_DEFAULT_SIZE);
  139. material->release(); // don't call SAFE_RELEASE since material is used below
  140. // Create the batch
  141. SpriteBatch* batch = new SpriteBatch();
  142. batch->_customEffect = customEffect;
  143. batch->_batch = meshBatch;
  144. batch->_textureWidthRatio = 1.0f / (float)texture->getWidth();
  145. batch->_textureHeightRatio = 1.0f / (float)texture->getHeight();
  146. // Bind an ortho projection to the material by default (user can override with setProjectionMatrix)
  147. material->getParameter("u_projectionMatrix")->bindValue(batch, &SpriteBatch::getOrthoMatrix);
  148. return batch;
  149. }
  150. void SpriteBatch::begin()
  151. {
  152. _batch->begin();
  153. }
  154. void SpriteBatch::draw(const Rectangle& dst, const Rectangle& src, const Vector4& color)
  155. {
  156. // Calculate uvs.
  157. float u1 = _textureWidthRatio * src.x;
  158. float v1 = 1.0f - _textureHeightRatio * src.y;
  159. float u2 = u1 + _textureWidthRatio * src.width;
  160. float v2 = v1 - _textureHeightRatio * src.height;
  161. draw(dst.x, dst.y, dst.width, dst.height, u1, v1, u2, v2, color);
  162. }
  163. void SpriteBatch::draw(const Vector3& dst, const Rectangle& src, const Vector2& scale, const Vector4& color)
  164. {
  165. // Calculate uvs.
  166. float u1 = _textureWidthRatio * src.x;
  167. float v1 = 1.0f - _textureHeightRatio * src.y;
  168. float u2 = u1 + _textureWidthRatio * src.width;
  169. float v2 = v1 - _textureHeightRatio * src.height;
  170. draw(dst.x, dst.y, dst.z, scale.x, scale.y, u2, v2, u1, v1, color);
  171. }
  172. void SpriteBatch::draw(const Vector3& dst, const Rectangle& src, const Vector2& scale, const Vector4& color,
  173. const Vector2& rotationPoint, float rotationAngle)
  174. {
  175. // Calculate uvs.
  176. float u1 = _textureWidthRatio * src.x;
  177. float v1 = 1.0f - _textureHeightRatio * src.y;
  178. float u2 = u1 + _textureWidthRatio * src.width;
  179. float v2 = v1 - _textureHeightRatio * src.height;
  180. draw(dst, scale.x, scale.y, u1, v1, u2, v2, color, rotationPoint, rotationAngle);
  181. }
  182. void SpriteBatch::draw(const Vector3& dst, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color,
  183. const Vector2& rotationPoint, float rotationAngle, bool positionIsCenter)
  184. {
  185. float x = dst.x;
  186. float y = dst.y;
  187. // Treat the given position as the center if the user specified it as such.
  188. if (positionIsCenter)
  189. {
  190. x -= 0.5f * width;
  191. y -= 0.5f * height;
  192. }
  193. // Expand the destination position by scale into 4 points.
  194. float x2 = x + width;
  195. float y2 = y + height;
  196. Vector2 upLeft(x, y);
  197. Vector2 upRight(x2, y);
  198. Vector2 downLeft(x, y2);
  199. Vector2 downRight(x2, y2);
  200. // Rotate points around rotationAxis by rotationAngle.
  201. Vector2 pivotPoint(rotationPoint);
  202. pivotPoint.x *= width;
  203. pivotPoint.y *= height;
  204. pivotPoint.x += x;
  205. pivotPoint.y += y;
  206. upLeft.rotate(pivotPoint, rotationAngle);
  207. upRight.rotate(pivotPoint, rotationAngle);
  208. downLeft.rotate(pivotPoint, rotationAngle);
  209. downRight.rotate(pivotPoint, rotationAngle);
  210. // Write sprite vertex data.
  211. static SpriteVertex v[4];
  212. ADD_SPRITE_VERTEX(v[0], upLeft.x, upLeft.y, dst.z, u1, v1, color.x, color.y, color.z, color.w);
  213. ADD_SPRITE_VERTEX(v[1], upRight.x, upRight.y, dst.z, u1, v2, color.x, color.y, color.z, color.w);
  214. ADD_SPRITE_VERTEX(v[2], downLeft.x, downLeft.y, dst.z, u2, v1, color.x, color.y, color.z, color.w);
  215. ADD_SPRITE_VERTEX(v[3], downRight.x, downRight.y, dst.z, u2, v2, color.x, color.y, color.z, color.w);
  216. static unsigned short indices[4] = { 0, 1, 2, 3 };
  217. _batch->add(v, 4, indices, 4);
  218. }
  219. void SpriteBatch::draw(const Vector3& position, const Vector3& right, const Vector3& forward, float width, float height,
  220. float u1, float v1, float u2, float v2, const Vector4& color, const Vector2& rotationPoint, float rotationAngle)
  221. {
  222. // Calculate the vertex positions.
  223. Vector3 p[4];
  224. p[0] = position - 0.5f * width * right - 0.5f * height * forward;
  225. p[1] = position + 0.5f * width * right - 0.5f * height * forward;
  226. p[2] = p[0] + height * forward;
  227. p[3] = p[1] + height * forward;
  228. // Calculate the rotation point.
  229. Vector3 rp = p[0] + (rotationPoint.x * width * right) + (rotationPoint.y * height * forward);
  230. // Rotate all points the specified amount about the given point (about the up vector).
  231. Vector3 u;
  232. Vector3::cross(right, forward, &u);
  233. Matrix rotation;
  234. Matrix::createRotation(u, rotationAngle, &rotation);
  235. p[0] = (rotation * (p[0] - rp)) + rp;
  236. p[1] = (rotation * (p[1] - rp)) + rp;
  237. p[2] = (rotation * (p[2] - rp)) + rp;
  238. p[3] = (rotation * (p[3] - rp)) + rp;
  239. // Add the sprite vertex data to the batch.
  240. static SpriteVertex v[4];
  241. ADD_SPRITE_VERTEX(v[0], p[0].x, p[0].y, p[0].z, u1, v1, color.x, color.y, color.z, color.w);
  242. ADD_SPRITE_VERTEX(v[1], p[1].x, p[1].y, p[1].z, u2, v1, color.x, color.y, color.z, color.w);
  243. ADD_SPRITE_VERTEX(v[2], p[2].x, p[2].y, p[2].z, u1, v2, color.x, color.y, color.z, color.w);
  244. ADD_SPRITE_VERTEX(v[3], p[3].x, p[3].y, p[3].z, u2, v2, color.x, color.y, color.z, color.w);
  245. static const unsigned short indices[4] = { 0, 1, 2, 3 };
  246. _batch->add(v, 4, const_cast<unsigned short*>(indices), 4);
  247. }
  248. void SpriteBatch::draw(float x, float y, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color)
  249. {
  250. draw(x, y, 0, width, height, u1, v1, u2, v2, color);
  251. }
  252. void SpriteBatch::draw(float x, float y, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color, const Rectangle& clip)
  253. {
  254. // Need to clip the rectangle given by { x, y, width, height } into clip by potentially:
  255. // - Moving x to the right.
  256. // - Moving y down.
  257. // - Moving width to the left.
  258. // - Moving height up.
  259. // - A combination of the above.
  260. // - Not drawing at all.
  261. //
  262. // We need to scale the uvs accordingly as we do this.
  263. // First check to see if we need to draw at all.
  264. if (x + width < clip.x || x > clip.x + clip.width ||
  265. y + height < clip.y || y > clip.y + clip.height)
  266. {
  267. return;
  268. }
  269. const float uvWidth = u2 - u1;
  270. const float uvHeight = v2 - v1;
  271. // Moving x to the right.
  272. if (x < clip.x)
  273. {
  274. const float percent = (clip.x - x) / width;
  275. x = clip.x;
  276. u1 += uvWidth * percent;
  277. }
  278. // Moving y down.
  279. if (y < clip.y)
  280. {
  281. const float percent = (clip.y - y) / height;
  282. y = clip.y;
  283. v1 += uvHeight * percent;
  284. }
  285. // Moving width to the left.
  286. const float clipX2 = clip.x + clip.width;
  287. float x2 = x + width;
  288. if (x2 > clipX2)
  289. {
  290. const float percent = (x2 - clipX2) / width;
  291. width = clipX2 - x;
  292. u2 -= uvWidth * percent;
  293. }
  294. // Moving height up.
  295. const float clipY2 = clip.y + clip.height;
  296. float y2 = y + height;
  297. if (y2 > clipY2)
  298. {
  299. const float percent = (y2 - clipY2) / height;
  300. height = clipY2 - y;
  301. v2 -= uvHeight * percent;
  302. }
  303. // Now we can perform a normal draw call.
  304. draw(x, y, 0, width, height, u1, v1, u2, v2, color);
  305. }
  306. void SpriteBatch::draw(float x, float y, float z, float width, float height, float u1, float v1, float u2, float v2, const Vector4& color, bool positionIsCenter)
  307. {
  308. // Treat the given position as the center if the user specified it as such.
  309. if (positionIsCenter)
  310. {
  311. x -= 0.5f * width;
  312. y -= 0.5f * height;
  313. }
  314. // Write sprite vertex data.
  315. const float x2 = x + width;
  316. const float y2 = y + height;
  317. static SpriteVertex v[4];
  318. ADD_SPRITE_VERTEX(v[0], x, y, z, u1, v1, color.x, color.y, color.z, color.w);
  319. ADD_SPRITE_VERTEX(v[1], x, y2, z, u1, v2, color.x, color.y, color.z, color.w);
  320. ADD_SPRITE_VERTEX(v[2], x2, y, z, u2, v1, color.x, color.y, color.z, color.w);
  321. ADD_SPRITE_VERTEX(v[3], x2, y2, z, u2, v2, color.x, color.y, color.z, color.w);
  322. static unsigned short indices[4] = { 0, 1, 2, 3 };
  323. _batch->add(v, 4, indices, 4);
  324. }
  325. void SpriteBatch::end()
  326. {
  327. // Finish and draw the batch
  328. _batch->end();
  329. _batch->draw();
  330. }
  331. RenderState::StateBlock* SpriteBatch::getStateBlock() const
  332. {
  333. return _batch->getMaterial()->getStateBlock();
  334. }
  335. Material* SpriteBatch::getMaterial()
  336. {
  337. return _batch->getMaterial();
  338. }
  339. void SpriteBatch::setProjectionMatrix(const Matrix& matrix)
  340. {
  341. // Bind the specified matrix to a parameter named 'u_projectionMatrix' (assumed to exist).
  342. _batch->getMaterial()->getParameter("u_projectionMatrix")->setValue(matrix);
  343. }
  344. const Matrix& SpriteBatch::getOrthoMatrix() const
  345. {
  346. // Update matrix with ortho projection and return it.
  347. Game* game = Game::getInstance();
  348. Matrix::createOrthographicOffCenter(0, game->getWidth(), game->getHeight(), 0, 0, 1, &_projectionMatrix);
  349. return _projectionMatrix;
  350. }
  351. }