/
modelrenderer.cpp
406 lines (347 loc) · 13.4 KB
/
modelrenderer.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
/** @file modelrenderer.cpp Model renderer.
*
* @authors Copyright (c) 2014 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "render/modelrenderer.h"
#include "gl/gl_main.h"
#include "render/rend_main.h"
#include "world/p_players.h"
#include "world/clientmobjthinkerdata.h"
#include "clientapp.h"
#include <de/filesys/AssetObserver>
#include <de/App>
#include <de/ModelBank>
#include <de/ScriptedInfo>
using namespace de;
static String const DEF_ANIMATION ("animation");
static String const DEF_MATERIAL ("material");
static String const DEF_UP_VECTOR ("up");
static String const DEF_FRONT_VECTOR("front");
static String const DEF_AUTOSCALE ("autoscale");
static String const DEF_MIRROR ("mirror");
DENG2_PIMPL(ModelRenderer)
, DENG2_OBSERVES(filesys::AssetObserver, Availability)
, DENG2_OBSERVES(Bank, Load)
, DENG2_OBSERVES(ModelDrawable, AboutToGLInit)
{
#define MAX_LIGHTS 4
filesys::AssetObserver observer { "model\\..*" };
ModelBank bank;
std::unique_ptr<AtlasTexture> atlas;
GLProgram program; /// @todo Specific models may want to use a custom program.
GLUniform uMvpMatrix { "uMvpMatrix", GLUniform::Mat4 };
GLUniform uTex { "uTex", GLUniform::Sampler2D };
GLUniform uEyeDir { "uEyeDir", GLUniform::Vec3 };
GLUniform uAmbientLight { "uAmbientLight", GLUniform::Vec4 };
GLUniform uLightDirs { "uLightDirs", GLUniform::Vec3Array, MAX_LIGHTS };
GLUniform uLightIntensities { "uLightIntensities", GLUniform::Vec4Array, MAX_LIGHTS };
Matrix4f inverseLocal;
int lightCount = 0;
Id defaultNormals { Id::None };
Id defaultEmission { Id::None };
Id defaultSpecular { Id::None };
Instance(Public *i) : Base(i)
{
observer.audienceForAvailability() += this;
bank.audienceForLoad() += this;
}
void init()
{
ClientApp::shaders().build(program, "model.skeletal.normal_specular_emission")
<< uMvpMatrix
<< uTex
<< uEyeDir
<< uAmbientLight
<< uLightDirs
<< uLightIntensities;
atlas.reset(AtlasTexture::newWithKdTreeAllocator(
Atlas::DefaultFlags,
GLTexture::maximumSize().min(GLTexture::Size(4096, 4096))));
atlas->setBorderSize(1);
atlas->setMarginSize(0);
// Fallback normal map for models who don't provide one.
QImage img(QSize(1, 1), QImage::Format_ARGB32);
img.fill(qRgba(127, 127, 255, 255)); // z+
defaultNormals = atlas->alloc(img);
// Fallback emission map for models who don't have one.
img.fill(qRgba(0, 0, 0, 0));
defaultEmission = atlas->alloc(img);
// Fallback specular map.
img.fill(qRgba(128, 128, 128, 180));
defaultSpecular = atlas->alloc(img);
uTex = *atlas;
/*
// All loaded items should use this atlas.
bank.iterate([this] (DotPath const &path)
{
if(bank.isLoaded(path))
{
setupModel(bank.model(path));
}
});*/
}
void deinit()
{
// GL resources must be accessed from the main thread only.
bank.unloadAll(Bank::ImmediatelyInCurrentThread);
atlas.reset();
program.clear();
}
void assetAvailabilityChanged(String const &identifier, filesys::AssetObserver::Event event)
{
//qDebug() << "loading model:" << identifier << event;
if(event == filesys::AssetObserver::Added)
{
bank.add(identifier, App::asset(identifier).absolutePath("path"));
// Begin loading the model right away.
bank.load(identifier);
}
else
{
bank.remove(identifier);
}
}
/**
* Configures a ModelDrawable with the appropriate atlas and GL program.
*
* @param model Model to configure.
*/
void setupModel(ModelDrawable &model)
{
if(atlas)
{
model.setAtlas(*atlas);
model.setDefaultTexture(ModelDrawable::Normals, defaultNormals);
model.setDefaultTexture(ModelDrawable::Emissive, defaultEmission);
model.setDefaultTexture(ModelDrawable::Specular, defaultSpecular);
// Use the texture mapping specified in the shader. This has to be done
// only now because earlier we may not have the shader available yet.
Record const &def = ClientApp::shaders()["model.skeletal.normal_specular_emission"];
if(def.has("textureMapping"))
{
ModelDrawable::Mapping mapping;
for(Value const *value : def.geta("textureMapping").elements())
{
mapping << ModelDrawable::textToTextureMap(value->asText());
}
//qDebug() << "using mapping" << mapping;
model.setTextureMapping(mapping);
}
}
else
{
model.unsetAtlas();
}
model.setProgram(program);
}
void modelAboutToGLInit(ModelDrawable &model)
{
setupModel(model);
}
/**
* When model assets have been loaded, we can parse their metadata to see if there
* are any animation sequences defined. If so, we'll set up a shared lookup table
* that determines which sequences to start in which mobj states.
*
* @param path Model asset id.
*/
void bankLoaded(DotPath const &path)
{
// Models use the shared atlas.
ModelDrawable &model = bank.model(path);
model.audienceForAboutToGLInit() += this;
auto const asset = App::asset(path);
std::unique_ptr<AuxiliaryData> aux(new AuxiliaryData);
// Determine the coordinate system of the model.
Vector3f front(0, 0, 1);
Vector3f up (0, 1, 0);
if(asset.has(DEF_FRONT_VECTOR))
{
front = Vector3f(asset.geta(DEF_FRONT_VECTOR));
}
if(asset.has(DEF_UP_VECTOR))
{
up = Vector3f(asset.geta(DEF_UP_VECTOR));
}
bool mirror = (asset.has(DEF_MIRROR)? ScriptedInfo::isTrue(asset.get(DEF_MIRROR)) : false);
aux->cull = mirror? gl::Back : gl::Front;
// Assimp's coordinate system uses different handedness than Doomsday,
// so mirroring is needed.
aux->transformation = Matrix4f::unnormalizedFrame(front, up, !mirror);
if(asset.has(DEF_AUTOSCALE))
{
aux->autoscaleToThingHeight = !ScriptedInfo::isFalse(asset.get(DEF_AUTOSCALE));
}
// Custom texture maps.
if(asset.has(DEF_MATERIAL))
{
auto mats = asset.subrecord(DEF_MATERIAL).subrecords();
DENG2_FOR_EACH_CONST(Record::Subrecords, mat, mats)
{
handleMaterialTexture(model, mat.key(), *mat.value(), "diffuseMap", ModelDrawable::Diffuse);
handleMaterialTexture(model, mat.key(), *mat.value(), "normalMap", ModelDrawable::Normals);
handleMaterialTexture(model, mat.key(), *mat.value(), "heightMap", ModelDrawable::Height);
handleMaterialTexture(model, mat.key(), *mat.value(), "specularMap", ModelDrawable::Specular);
handleMaterialTexture(model, mat.key(), *mat.value(), "emissiveMap", ModelDrawable::Emissive);
}
}
// Set up the animation sequences for states.
if(asset.has(DEF_ANIMATION))
{
auto states = ScriptedInfo::subrecordsOfType("state", asset.subrecord(DEF_ANIMATION));
DENG2_FOR_EACH_CONST(Record::Subrecords, state, states)
{
// Note that the sequences are added in alphabetical order.
auto seqs = ScriptedInfo::subrecordsOfType("sequence", *state.value());
DENG2_FOR_EACH_CONST(Record::Subrecords, seq, seqs)
{
aux->animations[state.key()] << AnimSequence(seq.key(), *seq.value());
}
}
// TODO: Check for a possible timeline and calculate time factors accordingly.
}
// Store the additional information in the bank.
bank.setUserData(path, aux.release());
}
void handleMaterialTexture(ModelDrawable &model,
String const &matName,
Record const &matDef,
String const &textureName,
ModelDrawable::TextureMap map)
{
if(matDef.has(textureName))
{
String path = ScriptedInfo::absolutePathInContext(matDef, matDef.gets(textureName));
int matId = identifierFromText(matName, [&model] (String const &text) {
return model.materialId(text);
});
model.setTexturePath(matId, map, path);
}
}
};
ModelRenderer::ModelRenderer() : d(new Instance(this))
{}
void ModelRenderer::glInit()
{
d->init();
}
void ModelRenderer::glDeinit()
{
d->deinit();
}
ModelBank &ModelRenderer::bank()
{
return d->bank;
}
ModelRenderer::StateAnims const *ModelRenderer::animations(DotPath const &modelId) const
{
if(auto const *aux = d->bank.userData(modelId)->maybeAs<AuxiliaryData>())
{
if(!aux->animations.isEmpty())
{
return &aux->animations;
}
}
return 0;
}
void ModelRenderer::setTransformation(Vector3f const &eyeDir, Matrix4f const &modelToLocal,
Matrix4f const &localToView)
{
d->uMvpMatrix = localToView * modelToLocal;
d->inverseLocal = modelToLocal.inverse();
d->uEyeDir = (d->inverseLocal * eyeDir).normalize();
}
void ModelRenderer::setAmbientLight(Vector3f const &ambientIntensity)
{
d->uAmbientLight = Vector4f(ambientIntensity, 1.f);
}
void ModelRenderer::clearLights()
{
d->lightCount = 0;
for(int i = 0; i < MAX_LIGHTS; ++i)
{
d->uLightDirs .set(i, Vector3f());
d->uLightIntensities.set(i, Vector4f());
}
}
void ModelRenderer::addLight(Vector3f const &direction, Vector3f const &intensity)
{
if(d->lightCount == MAX_LIGHTS) return;
int idx = d->lightCount;
d->uLightDirs .set(idx, (d->inverseLocal * direction).normalize());
d->uLightIntensities.set(idx, Vector4f(intensity, intensity.max()));
d->lightCount++;
}
void ModelRenderer::render(vissprite_t const &spr)
{
/*
* Work in progress:
*
* Here is the contact point between the old renderer and the new GL2 model renderer.
* In the future, vissprites should form a class hierarchy, and the entire drawing
* operation should be encapsulated within. This will allow drawing a model (or a
* sprite, etc.) by creating a VisSprite instance and telling it to draw itself.
*/
drawmodel2params_t const &p = spr.data.model2;
Matrix4f viewMat =
Viewer_Matrix() *
Matrix4f::scale(Vector3f(1.0f, 1.0f/1.2f, 1.0f)) * // Inverse aspect correction.
Matrix4f::translate((spr.pose.origin + spr.pose.srvo).xzy());
Matrix4f localMat =
Matrix4f::rotate(-90 + (spr.pose.viewAligned? spr.pose.yawAngleOffset :
spr.pose.yaw),
Vector3f(0, 1, 0) /* vertical axis for yaw */);
gl::Cull culling = gl::Back;
if(p.object)
{
auto const &mobjData = THINKER_DATA(p.object->thinker, ClientMobjThinkerData);
localMat = localMat * mobjData.modelTransformation();
culling = mobjData.modelCullFace();
}
GLState::push().setCull(culling);
// Set up a suitable matrix for the pose.
setTransformation(Rend_EyeOrigin() - spr.pose.mid().xzy(), localMat, viewMat);
// Ambient color and lighting vectors.
setAmbientLight(spr.light.ambientColor * .8f);
clearLights();
ClientApp::renderSystem().forAllVectorLights(spr.light.vLightListIdx,
[this] (VectorLightData const &vlight)
{
// Use this when drawing the model.
addLight(vlight.direction.xzy(), vlight.color);
return LoopContinue;
});
// Draw the model using the current animation state.
p.model->draw(p.animator);
GLState::pop();
/// @todo Something is interfering with the cull setting elsewhere (remove this).
GLState::current().setCull(gl::Back).apply();
}
int ModelRenderer::identifierFromText(String const &text,
std::function<int (String const &)> resolver) // static
{
/// @todo This might be useful on a more general level, outside ModelRenderer. -jk
int id = 0;
if(text.beginsWith('@'))
{
id = text.mid(1).toInt();
}
else
{
id = resolver(text);
}
return id;
}