-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
SkeletonTwoColorBatch.cpp
420 lines (335 loc) · 15 KB
/
SkeletonTwoColorBatch.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated July 28, 2023. Replaces all prior versions.
*
* Copyright (c) 2013-2023, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software or
* otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE
* SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include <spine/spine-cocos2dx.h>
#if COCOS2D_VERSION >= 0x00040000
#include "base/ccTypes.h"
#include "base/ccUtils.h"
#include <algorithm>
#include <spine/Extension.h>
#include <stddef.h>// offsetof
#include "renderer/backend/Device.h"
#include "renderer/ccShaders.h"
#include "xxhash.h"
USING_NS_CC;
#define EVENT_AFTER_DRAW_RESET_POSITION "director_after_draw"
using std::max;
#define INITIAL_SIZE (10000)
#define MAX_VERTICES 64000
#define MAX_INDICES 64000
#define STRINGIFY(A) #A
namespace {
const char *TWO_COLOR_TINT_VERTEX_SHADER = STRINGIFY(
uniform mat4 u_PMatrix;
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec4 a_color2;
attribute vec2 a_texCoords;
\n #ifdef GL_ES\n
varying lowp vec4 v_light;
varying lowp vec4 v_dark;
varying mediump vec2 v_texCoord;
\n #else \n
varying vec4 v_light;
varying vec4 v_dark;
varying vec2 v_texCoord;
\n #endif \n
void main() {
v_light = a_color;
v_dark = a_color2;
v_texCoord = a_texCoords;
gl_Position = u_PMatrix * a_position;
});
const char *TWO_COLOR_TINT_FRAGMENT_SHADER = STRINGIFY(
\n #ifdef GL_ES\n
precision lowp float;
\n #endif \n
uniform sampler2D u_texture;
varying vec4 v_light;
varying vec4 v_dark;
varying vec2 v_texCoord;
void main() {
vec4 texColor = texture2D(u_texture, v_texCoord);
float alpha = texColor.a * v_light.a;
gl_FragColor.a = alpha;
gl_FragColor.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;
});
std::shared_ptr<backend::ProgramState> __twoColorProgramState = nullptr;
backend::UniformLocation __locPMatrix;
backend::UniformLocation __locTexture;
static void updateProgramStateLayout(backend::ProgramState *programState) {
__locPMatrix = programState->getUniformLocation("u_PMatrix");
__locTexture = programState->getUniformLocation("u_texture");
auto layout = programState->getVertexLayout();
auto locPosition = programState->getAttributeLocation("a_position");
auto locTexcoord = programState->getAttributeLocation("a_texCoords");
auto locColor = programState->getAttributeLocation("a_color");
auto locColor2 = programState->getAttributeLocation("a_color2");
layout->setAttribute("a_position", locPosition, backend::VertexFormat::FLOAT3, offsetof(spine::V3F_C4B_C4B_T2F, position), false);
layout->setAttribute("a_color", locColor, backend::VertexFormat::UBYTE4, offsetof(spine::V3F_C4B_C4B_T2F, color), true);
layout->setAttribute("a_color2", locColor2, backend::VertexFormat::UBYTE4, offsetof(spine::V3F_C4B_C4B_T2F, color2), true);
layout->setAttribute("a_texCoords", locTexcoord, backend::VertexFormat::FLOAT2, offsetof(spine::V3F_C4B_C4B_T2F, texCoords), false);
layout->setLayout(sizeof(spine::V3F_C4B_C4B_T2F));
}
static void initTwoColorProgramState() {
if (__twoColorProgramState) {
return;
}
auto program = backend::Device::getInstance()->newProgram(TWO_COLOR_TINT_VERTEX_SHADER, TWO_COLOR_TINT_FRAGMENT_SHADER);
auto *programState = new backend::ProgramState(program);
program->release();
updateProgramStateLayout(programState);
__twoColorProgramState = std::shared_ptr<backend::ProgramState>(programState);
}
}// namespace
namespace spine {
TwoColorTrianglesCommand::TwoColorTrianglesCommand() : _materialID(0), _texture(nullptr), _blendType(BlendFunc::DISABLE) {
_type = RenderCommand::Type::CUSTOM_COMMAND;
}
void TwoColorTrianglesCommand::init(float globalOrder, cocos2d::Texture2D *texture, cocos2d::backend::ProgramState *programState, BlendFunc blendType, const TwoColorTriangles &triangles, const Mat4 &mv, uint32_t flags) {
updateCommandPipelineDescriptor(programState);
const cocos2d::Mat4 &projectionMat = Director::getInstance()->getMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_PROJECTION);
auto finalMatrix = projectionMat * mv;
_programState->setUniform(_locPMatrix, finalMatrix.m, sizeof(finalMatrix.m));
_programState->setTexture(_locTexture, 0, texture->getBackendTexture());
RenderCommand::init(globalOrder, mv, flags);
_triangles = triangles;
if (_triangles.indexCount % 3 != 0) {
int count = _triangles.indexCount;
_triangles.indexCount = count / 3 * 3;
CCLOGERROR("Resize indexCount from %d to %d, size must be multiple times of 3", count, _triangles.indexCount);
}
_mv = mv;
if (_blendType.src != blendType.src || _blendType.dst != blendType.dst ||
_texture != texture->getBackendTexture() || _pipelineDescriptor.programState != _programState) {
_texture = texture->getBackendTexture();
_blendType = blendType;
_prog = _programState->getProgram();
auto &blendDescriptor = _pipelineDescriptor.blendDescriptor;
blendDescriptor.blendEnabled = true;
blendDescriptor.sourceRGBBlendFactor = blendDescriptor.sourceAlphaBlendFactor = blendType.src;
blendDescriptor.destinationRGBBlendFactor = blendDescriptor.destinationAlphaBlendFactor = blendType.dst;
generateMaterialID();
}
}
void TwoColorTrianglesCommand::updateCommandPipelineDescriptor(cocos2d::backend::ProgramState *programState) {
// OPTIMIZE ME: all commands belong a same Node should share a same programState like SkeletonBatch
if (!__twoColorProgramState) {
initTwoColorProgramState();
}
bool needsUpdateStateLayout = false;
auto &pipelinePS = _pipelineDescriptor.programState;
if (programState != nullptr) {
if (_programState != programState) {
CC_SAFE_RELEASE(_programState);
_programState = programState;// Because the programState belong to Node, so no need to clone
CC_SAFE_RETAIN(_programState);
needsUpdateStateLayout = true;
}
} else {
needsUpdateStateLayout = _programState != nullptr && _programState->getProgram() != __twoColorProgramState->getProgram();
CC_SAFE_RELEASE(_programState);
_programState = __twoColorProgramState->clone();
}
CCASSERT(_programState, "programState should not be null");
pipelinePS = _programState;
if (needsUpdateStateLayout)
updateProgramStateLayout(pipelinePS);
_locPMatrix = __locPMatrix;
_locTexture = __locTexture;
}
TwoColorTrianglesCommand::~TwoColorTrianglesCommand() {
CC_SAFE_RELEASE_NULL(_programState);
}
void TwoColorTrianglesCommand::generateMaterialID() {
// do not batch if using custom uniforms (since we cannot batch) it
struct
{
void *texture;
void *prog;
backend::BlendFactor src;
backend::BlendFactor dst;
} hashMe;
// NOTE: Initialize hashMe struct to make the value of padding bytes be filled with zero.
// It's important since XXH32 below will also consider the padding bytes which probably
// are set to random values by different compilers.
memset(&hashMe, 0, sizeof(hashMe));
hashMe.texture = _texture;
hashMe.src = _blendType.src;
hashMe.dst = _blendType.dst;
hashMe.prog = _prog;
_materialID = XXH32((const void *) &hashMe, sizeof(hashMe), 0);
}
void TwoColorTrianglesCommand::draw(Renderer *r) {
SkeletonTwoColorBatch::getInstance()->batch(r, this);
}
void TwoColorTrianglesCommand::updateVertexAndIndexBuffer(Renderer *r, V3F_C4B_C4B_T2F *vertices, int verticesSize, uint16_t *indices, int indicesSize) {
if (verticesSize != _vertexCapacity)
createVertexBuffer(sizeof(V3F_C4B_C4B_T2F), verticesSize, CustomCommand::BufferUsage::DYNAMIC);
if (indicesSize != _indexCapacity)
createIndexBuffer(CustomCommand::IndexFormat::U_SHORT, indicesSize, CustomCommand::BufferUsage::DYNAMIC);
updateVertexBuffer(vertices, sizeof(V3F_C4B_C4B_T2F) * verticesSize);
updateIndexBuffer(indices, sizeof(uint16_t) * indicesSize);
}
static SkeletonTwoColorBatch *instance = nullptr;
SkeletonTwoColorBatch *SkeletonTwoColorBatch::getInstance() {
if (!instance) instance = new SkeletonTwoColorBatch();
return instance;
}
void SkeletonTwoColorBatch::destroyInstance() {
if (instance) {
delete instance;
instance = nullptr;
}
}
SkeletonTwoColorBatch::SkeletonTwoColorBatch() : _vertexBuffer(0), _indexBuffer(0) {
_commandsPool.reserve(INITIAL_SIZE);
for (unsigned int i = 0; i < INITIAL_SIZE; i++) {
_commandsPool.push_back(new TwoColorTrianglesCommand());
}
reset();
// callback after drawing is finished so we can clear out the batch state
// for the next frame
Director::getInstance()->getEventDispatcher()->addCustomEventListener(EVENT_AFTER_DRAW_RESET_POSITION, [this](EventCustom *eventCustom) {
this->update(0);
});
}
SkeletonTwoColorBatch::~SkeletonTwoColorBatch() {
Director::getInstance()->getEventDispatcher()->removeCustomEventListeners(EVENT_AFTER_DRAW_RESET_POSITION);
for (unsigned int i = 0; i < _commandsPool.size(); i++) {
delete _commandsPool[i];
_commandsPool[i] = nullptr;
}
delete[] _vertexBuffer;
delete[] _indexBuffer;
}
void SkeletonTwoColorBatch::update(float delta) {
reset();
}
V3F_C4B_C4B_T2F *SkeletonTwoColorBatch::allocateVertices(uint32_t numVertices) {
if (_vertices.size() - _numVertices < numVertices) {
V3F_C4B_C4B_T2F *oldData = _vertices.data();
_vertices.resize((_vertices.size() + numVertices) * 2 + 1);
V3F_C4B_C4B_T2F *newData = _vertices.data();
for (uint32_t i = 0; i < this->_nextFreeCommand; i++) {
TwoColorTrianglesCommand *command = _commandsPool[i];
TwoColorTriangles &triangles = (TwoColorTriangles &) command->getTriangles();
triangles.verts = newData + (triangles.verts - oldData);
}
}
V3F_C4B_C4B_T2F *vertices = _vertices.data() + _numVertices;
_numVertices += numVertices;
return vertices;
}
void SkeletonTwoColorBatch::deallocateVertices(uint32_t numVertices) {
_numVertices -= numVertices;
}
unsigned short *SkeletonTwoColorBatch::allocateIndices(uint32_t numIndices) {
if (_indices.getCapacity() - _indices.size() < numIndices) {
unsigned short *oldData = _indices.buffer();
int oldSize = (int)_indices.size();
_indices.ensureCapacity(_indices.size() + numIndices);
unsigned short *newData = _indices.buffer();
for (uint32_t i = 0; i < this->_nextFreeCommand; i++) {
TwoColorTrianglesCommand *command = _commandsPool[i];
TwoColorTriangles &triangles = (TwoColorTriangles &) command->getTriangles();
if (triangles.indices >= oldData && triangles.indices < oldData + oldSize) {
triangles.indices = newData + (triangles.indices - oldData);
}
}
}
unsigned short *indices = _indices.buffer() + _indices.size();
_indices.setSize(_indices.size() + numIndices, 0);
return indices;
}
void SkeletonTwoColorBatch::deallocateIndices(uint32_t numIndices) {
_indices.setSize(_indices.size() - numIndices, 0);
}
TwoColorTrianglesCommand *SkeletonTwoColorBatch::addCommand(cocos2d::Renderer *renderer, float globalOrder, cocos2d::Texture2D *texture, backend::ProgramState *programState, cocos2d::BlendFunc blendType, const TwoColorTriangles &triangles, const cocos2d::Mat4 &mv, uint32_t flags) {
TwoColorTrianglesCommand *command = nextFreeCommand();
command->init(globalOrder, texture, programState, blendType, triangles, mv, flags);
command->updateVertexAndIndexBuffer(renderer, triangles.verts, triangles.vertCount, triangles.indices, triangles.indexCount);
renderer->addCommand(command);
return command;
}
void SkeletonTwoColorBatch::batch(cocos2d::Renderer *renderer, TwoColorTrianglesCommand *command) {
if (_numVerticesBuffer + command->getTriangles().vertCount >= MAX_VERTICES || _numIndicesBuffer + command->getTriangles().indexCount >= MAX_INDICES) {
flush(renderer, _lastCommand);
}
uint32_t materialID = command->getMaterialID();
if (_lastCommand && _lastCommand->getMaterialID() != materialID) {
flush(renderer, _lastCommand);
}
memcpy(_vertexBuffer + _numVerticesBuffer, command->getTriangles().verts, sizeof(V3F_C4B_C4B_T2F) * command->getTriangles().vertCount);
const Mat4 &modelView = command->getModelView();
for (int i = _numVerticesBuffer; i < _numVerticesBuffer + command->getTriangles().vertCount; i++) {
modelView.transformPoint(&_vertexBuffer[i].position);
}
unsigned short vertexOffset = (unsigned short) _numVerticesBuffer;
unsigned short *indices = command->getTriangles().indices;
for (int i = 0, j = _numIndicesBuffer; i < command->getTriangles().indexCount; i++, j++) {
_indexBuffer[j] = indices[i] + vertexOffset;
}
_numVerticesBuffer += command->getTriangles().vertCount;
_numIndicesBuffer += command->getTriangles().indexCount;
if (command->isForceFlush()) {
flush(renderer, command);
}
_lastCommand = command;
}
void SkeletonTwoColorBatch::flush(cocos2d::Renderer *renderer, TwoColorTrianglesCommand *materialCommand) {
if (!materialCommand)
return;
materialCommand->updateVertexAndIndexBuffer(renderer, _vertexBuffer, _numVerticesBuffer, _indexBuffer, _numIndicesBuffer);
renderer->addCommand(materialCommand);
_numVerticesBuffer = 0;
_numIndicesBuffer = 0;
_numBatches++;
}
void SkeletonTwoColorBatch::reset() {
_nextFreeCommand = 0;
_numVertices = 0;
_indices.setSize(0, 0);
_numVerticesBuffer = 0;
_numIndicesBuffer = 0;
_lastCommand = nullptr;
_numBatches = 0;
}
TwoColorTrianglesCommand *SkeletonTwoColorBatch::nextFreeCommand() {
if (_commandsPool.size() <= _nextFreeCommand) {
unsigned int newSize = (int)_commandsPool.size() * 2 + 1;
for (int i = (int)_commandsPool.size(); i < newSize; i++) {
_commandsPool.push_back(new TwoColorTrianglesCommand());
}
}
TwoColorTrianglesCommand *command = _commandsPool[_nextFreeCommand++];
command->setForceFlush(false);
return command;
}
}// namespace spine
#endif