/
Entity.cpp
387 lines (317 loc) · 11.2 KB
/
Entity.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
#include "Entity.h"
#include <limits>
#include "i18n.h"
#include "itransformable.h"
#include "selectionlib.h"
#include "imainframe.h"
#include "iregistry.h"
#include "itextstream.h"
#include "entitylib.h"
#include "gamelib.h"
#include "wxutil/dialog/MessageBox.h"
#include "selection/algorithm/General.h"
#include "selection/algorithm/Shader.h"
#include "selection/algorithm/Group.h"
#include "map/Map.h"
#include "eclass.h"
namespace selection
{
namespace algorithm
{
const char* const GKEY_BIND_KEY("/defaults/bindKey");
void setEntityKeyvalue(const scene::INodePtr& node, const std::string& key, const std::string& value)
{
Entity* entity = Node_getEntity(node);
if (entity)
{
// Check if we have a func_static-style entity
std::string name = entity->getKeyValue("name");
std::string model = entity->getKeyValue("model");
bool isFuncType = (!name.empty() && name == model);
// Set the actual value
entity->setKeyValue(key, value);
// Check for name key changes of func_statics
if (isFuncType && key == "name")
{
// Adapt the model key along with the name
entity->setKeyValue("model", value);
}
}
else if (Node_isPrimitive(node))
{
// We have a primitve node selected, check its parent
scene::INodePtr parent(node->getParent());
if (!parent) return;
Entity* parentEnt = Node_getEntity(parent);
if (parentEnt)
{
// We have child primitive of an entity selected, the change
// should go right into that parent entity
parentEnt->setKeyValue(key, value);
}
}
}
void setEntityKeyvalue(const std::string& key, const std::string& value)
{
if (key.empty()) return;
if (key == "name")
{
// Check the global namespace if this change is ok
scene::IMapRootNodePtr mapRoot = GlobalMapModule().getRoot();
if (mapRoot)
{
INamespacePtr nspace = mapRoot->getNamespace();
if (nspace && nspace->nameExists(value))
{
// name exists, cancel the change
throw std::runtime_error(fmt::format(_("The name {0} already exists in this map!"), value));
}
}
}
// Detect classname changes
if (key == "classname")
{
// Classname changes are handled in a special way
setEntityClassname(value);
return;
}
// Regular key change, set value on all selected entities
GlobalSelectionSystem().foreachSelected([&](const scene::INodePtr& node)
{
setEntityKeyvalue(node, key, value);
});
}
void setEntityClassname(const std::string& classname)
{
if (classname.empty())
{
throw std::runtime_error(_("Cannot set classname to an empty string."));
}
if (classname == "worldspawn")
{
throw std::runtime_error(_("Cannot change classname to worldspawn."));
}
std::set<scene::INodePtr> entitiesToProcess;
// Collect all entities that should have their classname set
GlobalSelectionSystem().foreachSelected([&](const scene::INodePtr& node)
{
// Check if we have an entity
Entity* entity = Node_getEntity(node);
if (entity != NULL && Node_isSelected(node))
{
if (!entity->isWorldspawn())
{
entitiesToProcess.insert(node);
}
else
{
throw std::runtime_error(_("Cannot change classname of worldspawn entity."));
}
}
});
for (const scene::INodePtr& node : entitiesToProcess)
{
// "Rename" the entity, this deletes the old node and creates a new one
scene::INodePtr newNode = changeEntityClassname(node, classname);
// Select the new entity node
Node_setSelected(newNode, true);
}
}
void bindEntities(const cmd::ArgumentList& args) {
const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();
if (info.totalCount == 2 && info.entityCount == 2) {
UndoableCommand command("bindEntities");
Entity* first = Node_getEntity(GlobalSelectionSystem().ultimateSelected());
Entity* second = Node_getEntity(GlobalSelectionSystem().penultimateSelected());
if (first != NULL && second != NULL) {
// Get the bind key
std::string bindKey = game::current::getValue<std::string>(GKEY_BIND_KEY);
if (bindKey.empty()) {
// Fall back to a safe default
bindKey = "bind";
}
// Set the spawnarg
second->setKeyValue(bindKey, first->getKeyValue("name"));
}
else {
wxutil::Messagebox::ShowError(
_("Critical: Cannot find selected entities."));
}
}
else {
wxutil::Messagebox::ShowError(
_("Exactly two entities must be selected for this operation."));
}
}
void connectSelectedEntities(const cmd::ArgumentList& args)
{
if (GlobalSelectionSystem().countSelected() == 2)
{
// Obtain both entities
Entity* e1 = Node_getEntity(GlobalSelectionSystem().penultimateSelected()); // source
Entity* e2 = Node_getEntity(GlobalSelectionSystem().ultimateSelected()); // target
// Check entities are valid
if (e1 == nullptr || e2 == nullptr)
{
rError() << "connectSelectedEntities: both of the selected instances must be entities" << std::endl;
return;
}
// Check entities are distinct
if (e1 == e2)
{
rError() << "connectSelectedEntities: the selected entities must be different" << std::endl;
return;
}
// Start the scoped undo session
UndoableCommand undo("entityConnectSelected");
// Find the first unused target key on the source entity
for (unsigned int i = 0; i < std::numeric_limits<unsigned int>::max(); ++i)
{
// Construct candidate key by appending number to "target"
auto targetKey = fmt::format("target{0:d}", i);
// If the source entity does not have this key, add it and finish,
// otherwise continue looping
if (e1->getKeyValue(targetKey).empty())
{
e1->setKeyValue(targetKey, e2->getKeyValue("name"));
break;
}
}
// Redraw the scene
SceneChangeNotify();
}
else
{
wxutil::Messagebox::ShowError(
_("Exactly two entities must be selected for this operation."));
}
}
// Default radius of lights is 320 (Q4) rather than 300 (D3)
// since the grid is usually a multiple of 8.
const float DEFAULT_LIGHT_RADIUS = 320;
// Function to return an AABB based on the current workzone AABB (retrieved
// from the currently selected brushes), or to use the default light radius
// if the workzone AABB is not valid or none is available.
AABB Doom3Light_getBounds(AABB aabb)
{
// If the extents are 0 or invalid (-1), replace with the default radius
for (int i = 0; i < 3; i++)
{
if (aabb.extents[i] <= 0)
{
aabb.extents[i] = DEFAULT_LIGHT_RADIUS;
}
}
return aabb;
}
/**
* Create an instance of the given entity at the given position, and return
* the Node containing the new entity.
*
* @returns: the scene::INodePtr referring to the new entity.
*/
scene::INodePtr createEntityFromSelection(const std::string& name, const Vector3& origin)
{
// Obtain the structure containing the selection counts
const SelectionInfo& info = GlobalSelectionSystem().getSelectionInfo();
IEntityClassPtr entityClass = GlobalEntityClassManager().findOrInsert(name, true);
// TODO: to be replaced by inheritance-based class detection
bool isModel = (info.totalCount == 0 && name == "func_static");
// Some entities are based on the size of the currently-selected primitive(s)
bool primitivesSelected = info.brushCount > 0 || info.patchCount > 0;
if (!(entityClass->isFixedSize() || isModel) && !primitivesSelected) {
throw EntityCreationException(
fmt::format(_("Unable to create entity {0}, no brushes selected."), name)
);
}
// Get the selection workzone bounds
AABB workzone = GlobalSelectionSystem().getWorkZone().bounds;
// Create the new node for the entity
IEntityNodePtr node(GlobalEntityModule().createEntity(entityClass));
GlobalSceneGraph().root()->addChildNode(node);
// The layer list we're moving the newly created node/subgraph into
scene::LayerList targetLayers;
if (entityClass->isFixedSize() || (isModel && !primitivesSelected))
{
selection::algorithm::deleteSelection();
ITransformablePtr transform = Node_getTransformable(node);
if (transform != 0) {
transform->setType(TRANSFORM_PRIMITIVE);
transform->setTranslation(origin);
transform->freezeTransform();
}
GlobalSelectionSystem().setSelectedAll(false);
// Move the item to the active layer
if (GlobalMapModule().getRoot())
{
targetLayers.insert(GlobalMapModule().getRoot()->getLayerManager().getActiveLayer());
}
Node_setSelected(node, true);
}
else // brush-based entity
{
// Add selected brushes as children of non-fixed entity
node->getEntity().setKeyValue("model",
node->getEntity().getKeyValue("name"));
// Take the selection center as new origin
Vector3 newOrigin = selection::algorithm::getCurrentSelectionCenter();
node->getEntity().setKeyValue("origin", string::to_string(newOrigin));
// If there is an "editor_material" class attribute, apply this shader
// to all of the selected primitives before parenting them
std::string material = node->getEntity().getEntityClass()->getAttribute("editor_material").getValue();
if (!material.empty())
{
selection::algorithm::applyShaderToSelection(material);
}
// If we had primitives to reparent, the new entity should inherit the layer info from them
if (primitivesSelected)
{
scene::INodePtr primitive = GlobalSelectionSystem().ultimateSelected();
targetLayers = primitive->getLayers();
}
// Otherwise move the item to the active layer
else if (GlobalMapModule().getRoot())
{
targetLayers.insert(GlobalMapModule().getRoot()->getLayerManager().getActiveLayer());
}
// Parent the selected primitives to the new node
selection::algorithm::ParentPrimitivesToEntityWalker walker(node);
GlobalSelectionSystem().foreachSelected(walker);
walker.reparent();
// De-select the children and select the newly created parent entity
GlobalSelectionSystem().setSelectedAll(false);
Node_setSelected(node, true);
}
// Assign the layers - including all child nodes (#2864)
scene::AssignNodeToLayersWalker layerWalker(targetLayers);
node->traverse(layerWalker);
// Set the light radius and origin
if (entityClass->isLight() && primitivesSelected)
{
AABB bounds(Doom3Light_getBounds(workzone));
node->getEntity().setKeyValue("origin",
string::to_string(bounds.getOrigin()));
node->getEntity().setKeyValue("light_radius",
string::to_string(bounds.getExtents()));
}
// Flag the map as unsaved after creating the entity
GlobalMap().setModified(true);
// Check for auto-setting key values. TODO: use forEachClassAttribute
// directly here.
eclass::AttributeList list = eclass::getSpawnargsWithPrefix(
*entityClass, "editor_setKeyValue"
);
if (!list.empty())
{
for (eclass::AttributeList::const_iterator i = list.begin(); i != list.end(); ++i)
{
// Cut off the "editor_setKeyValueN " string from the key to get the spawnarg name
std::string key = i->getName().substr(i->getName().find_first_of(' ') + 1);
node->getEntity().setKeyValue(key, i->getValue());
}
}
// Return the new node
return node;
}
} // namespace algorithm
} // namespace selection