Debian Codegraph @

plugins/dm.objectives/ObjectiveEntity.cpp

raw
1 #include "ObjectiveEntity.h"
2 #include "ObjectiveKeyExtractor.h"
3 #include "TargetList.h"
4
5 #include "i18n.h"
6 #include "itextstream.h"
7 #include "iscenegraph.h"
8 #include "iundo.h"
9 #include "ientity.h"
10
11 #include "string/convert.h"
12 #include "string/predicate.h"
13 #include "string/split.h"
14 #include <fmt/format.h>
15 #include <regex>
16
17 #include <wx/choice.h>
18
19 namespace objectives {
20
21 namespace
22 {
23 const std::string KV_SUCCESS_LOGIC("mission_logic_success");
24 const std::string KV_FAILURE_LOGIC("mission_logic_failure");
25 const int INVALID_LEVEL_INDEX = -9999;
26
27 const std::string OBJ_COND_PREFIX("obj_condition_");
28 }
29
30 // Constructor
31 ObjectiveEntity::ObjectiveEntity(const scene::INodePtr& node) :
32 _entityNode(node)
33 {
34 Entity* entity = Node_getEntity(node);
35 assert(entity != NULL);
36
37 // Use an ObjectiveKeyExtractor to populate the ObjectiveMap from the keys
38 // on the entity
39 ObjectiveKeyExtractor extractor(_objectives);
40 entity->forEachKeyValue(extractor);
41
42 // Parse the logic strings from the entity
43 readMissionLogic(*entity);
44
45 readObjectiveConditions(*entity);
46 }
47
48 void ObjectiveEntity::readObjectiveConditions(Entity& ent)
49 {
50 _objConditions.clear(); // remove any previously parsed conditions
51
52 Entity::KeyValuePairs condSpawnargs = ent.getKeyValuePairs(OBJ_COND_PREFIX);
53
54 static const std::regex objCondExpr(OBJ_COND_PREFIX + "(\\d+)_(.*)");
55
56 for (Entity::KeyValuePairs::const_iterator kv = condSpawnargs.begin();
57 kv != condSpawnargs.end(); kv++)
58 {
59 std::smatch results;
60
61 if (!std::regex_match(kv->first, results, objCondExpr))
62 {
63 continue; // No match, abort
64 }
65
66 int index = string::convert<int>(results[1].str());
67
68 // Valid indices are [1..infinity)
69 if (index < 1)
70 {
71 continue; // invalid index, continue
72 }
73
74 const ObjectiveConditionPtr& cond = getOrCreateObjectiveCondition(index);
75
76 std::string postfix = results[2];
77
78 if (postfix == "src_mission")
79 {
80 cond->sourceMission = string::convert<int>(kv->second);
81 }
82 else if (postfix == "src_obj")
83 {
84 cond->sourceObjective = string::convert<int>(kv->second);
85 }
86 else if (postfix == "src_state")
87 {
88 int val = string::convert<int>(kv->second);
89
90 if (val >= Objective::INCOMPLETE && val < Objective::NUM_STATES)
91 {
92 cond->sourceState = static_cast<Objective::State>(val);
93 }
94 else
95 {
96 rWarning() << "Unsupported objective condition source state encountered: "
97 << kv->second << std::endl;
98 }
99 }
100 else if (postfix == "target_obj")
101 {
102 cond->targetObjective = string::convert<int>(kv->second);
103 }
104 else if (postfix == "type")
105 {
106 if (kv->second == "changestate")
107 {
108 cond->type = ObjectiveCondition::CHANGE_STATE;
109 }
110 else if (kv->second == "changevisibility")
111 {
112 cond->type = ObjectiveCondition::CHANGE_VISIBILITY;
113 }
114 else if (kv->second == "changemandatory")
115 {
116 cond->type = ObjectiveCondition::CHANGE_MANDATORY;
117 }
118 else
119 {
120 rWarning() << "Unsupported objective condition type encountered: "
121 << kv->second << std::endl;
122 }
123 }
124 else if (postfix == "value")
125 {
126 cond->value = string::convert<int>(kv->second);
127 }
128 }
129 }
130
131 void ObjectiveEntity::writeObjectiveConditions(Entity& ent)
132 {
133 // No need to clear previous set of obj_condition_ spawnargs,
134 // as they've been removed by clearEntity() already
135
136 // Spawnargs are numbered starting with 1 as first index
137 std::size_t index = 1;
138
139 // Go through all the conditions and save them. Skip invalid ones such that the
140 // set of conditions will be "compressed" in terms of their indices.
141 for (ObjectiveEntity::ConditionMap::const_iterator i = _objConditions.begin();
142 i != _objConditions.end(); ++i)
143 {
144 const ObjectiveCondition& cond = *i->second;
145
146 if (!cond.isValid())
147 {
148 continue; // skip invalid conditions without increasing the index
149 }
150
151 std::string prefix = fmt::format(OBJ_COND_PREFIX + "{0:d}_", index);
152
153 ent.setKeyValue(prefix + "src_mission", string::to_string(cond.sourceMission));
154 ent.setKeyValue(prefix + "src_obj", string::to_string(cond.sourceObjective));
155 ent.setKeyValue(prefix + "src_state", string::to_string(cond.sourceState));
156 ent.setKeyValue(prefix + "target_obj", string::to_string(cond.targetObjective));
157
158 std::string typeKey = prefix + "type";
159
160 switch (cond.type)
161 {
162 case ObjectiveCondition::CHANGE_STATE:
163 ent.setKeyValue(typeKey, "changestate");
164 break;
165 case ObjectiveCondition::CHANGE_VISIBILITY:
166 ent.setKeyValue(typeKey, "changevisibility");
167 break;
168 case ObjectiveCondition::CHANGE_MANDATORY:
169 ent.setKeyValue(typeKey, "changemandatory");
170 break;
171 default:
172 ent.setKeyValue(typeKey, ""); // empty value to be sure
173 rWarning() << "Invalid objective condition type encountered on saving." << std::endl;
174 break;
175 };
176
177 ent.setKeyValue(prefix + "value", string::to_string(cond.value));
178
179 ++index; // next index
180 }
181 }
182
183 void ObjectiveEntity::readMissionLogic(Entity& ent)
184 {
185 // Find the success logic strings
186 Entity::KeyValuePairs successLogics = ent.getKeyValuePairs(KV_SUCCESS_LOGIC);
187
188 for (Entity::KeyValuePairs::const_iterator kv = successLogics.begin();
189 kv != successLogics.end(); kv++)
190 {
191 std::string postfix = kv->first.substr(KV_SUCCESS_LOGIC.size());
192
193 if (postfix.empty()) {
194 // Empty postfix means that we've found the default logic
195 LogicPtr logic = getMissionLogic(-1);
196 logic->successLogic = kv->second;
197 }
198 else if (string::starts_with(postfix, "_diff_"))
199 {
200 // We seem to have a difficulty-related logic, get the level
201 int level = string::convert<int>(postfix.substr(6), INVALID_LEVEL_INDEX);
202
203 if (level == INVALID_LEVEL_INDEX) {
204 rError() << "[ObjectivesEditor]: Cannot parse difficulty-specific " <<
205 "logic strings: " << kv->second << std::endl;
206 continue;
207 }
208
209 LogicPtr logic = getMissionLogic(level);
210 logic->successLogic = kv->second;
211 }
212 }
213
214 // Find the failure logic strings
215 Entity::KeyValuePairs failureLogics = ent.getKeyValuePairs(KV_FAILURE_LOGIC);
216
217 for (Entity::KeyValuePairs::const_iterator kv = failureLogics.begin();
218 kv != failureLogics.end(); kv++)
219 {
220 std::string postfix = kv->first.substr(KV_FAILURE_LOGIC.size());
221
222 if (postfix.empty()) {
223 // Empty postfix means that we've found the default logic
224 LogicPtr logic = getMissionLogic(-1);
225 logic->failureLogic = kv->second;
226 }
227 else if (string::starts_with(postfix, "_diff_"))
228 {
229 // We seem to have a difficulty-related logic, get the level
230 int level = string::convert<int>(postfix.substr(6), INVALID_LEVEL_INDEX);
231
232 if (level == INVALID_LEVEL_INDEX) {
233 rError() << "[ObjectivesEditor]: Cannot parse difficulty-specific " <<
234 "logic strings: " << kv->second << std::endl;
235 continue;
236 }
237
238 LogicPtr logic = getMissionLogic(level);
239 logic->failureLogic = kv->second;
240 }
241 }
242 }
243
244 void ObjectiveEntity::writeMissionLogic(Entity& ent)
245 {
246 for (LogicMap::iterator i = _logics.begin(); i != _logics.end(); i++) {
247 int index = i->first;
248
249 if (index == -1) {
250 // Default logic
251 ent.setKeyValue(KV_SUCCESS_LOGIC, i->second->successLogic);
252 ent.setKeyValue(KV_FAILURE_LOGIC, i->second->failureLogic);
253 }
254 else {
255 // Difficulty-specific logic
256 ent.setKeyValue(KV_SUCCESS_LOGIC + "_diff_" + string::to_string(index), i->second->successLogic);
257 ent.setKeyValue(KV_FAILURE_LOGIC + "_diff_" + string::to_string(index), i->second->failureLogic);
258 }
259 }
260 }
261
262 // Delete the entity's world node
263 void ObjectiveEntity::deleteWorldNode() {
264 // Try to convert the weak_ptr reference to a shared_ptr
265 scene::INodePtr node = _entityNode.lock();
266
267 if (node != NULL) {
268 GlobalSceneGraph().root()->removeChildNode(node);
269 }
270 }
271
272 // Add a new objective
273 void ObjectiveEntity::addObjective() {
274 // Locate the first unused id
275 int index = 1;
276 while (_objectives.find(index) != _objectives.end())
277 ++index;
278
279 // Insert a new Objective at this ID.
280 Objective o;
281 o.description = fmt::format(_("New objective {0:d}"), index);
282 _objectives.insert(ObjectiveMap::value_type(index, o));
283 }
284
285 int ObjectiveEntity::moveObjective(int index, int delta)
286 {
287 // Calculate the target index
288 int targetIndex = index + delta;
289
290 if (targetIndex < getLowestObjIndex())
291 {
292 targetIndex = getLowestObjIndex() -1;
293 }
294
295 // Constrain the obj index to sane values
296 if (targetIndex < 0)
297 {
298 targetIndex = 0;
299 }
300
301 if (targetIndex > getHighestObjIndex())
302 {
303 targetIndex = getHighestObjIndex() + 1;
304 }
305
306 if (targetIndex == index) return index; // nothing to do
307
308 // Try to look up the command indices in the conversation
309 ObjectiveMap::iterator oldObj = _objectives.find(index);
310 ObjectiveMap::iterator newObj = _objectives.find(targetIndex);
311
312 if (oldObj == _objectives.end()) return -1; // invalid source objective
313
314 if (newObj == _objectives.end())
315 {
316 // no objective at the target index, just re-locate the source objective
317 Objective temp(oldObj->second);
318
319 _objectives.erase(oldObj);
320
321 _objectives[targetIndex] = temp;
322 }
323 else
324 {
325 // Both source and target indices exist, swap them
326 Objective temp(oldObj->second);
327
328 _objectives[index] = _objectives[targetIndex];
329 _objectives[targetIndex] = temp;
330 }
331
332 return targetIndex;
333 }
334
335 void ObjectiveEntity::deleteObjective(int index) {
336 // Look up the objective with the given index
337 ObjectiveMap::iterator i = _objectives.find(index);
338
339 if (i == _objectives.end()) {
340 // not found, nothing to do
341 return;
342 }
343
344 // Delete the found element
345 _objectives.erase(i++);
346
347 // Then iterate all the way to the highest index
348 while (i != _objectives.end()) {
349 // Decrease the index of this objective
350 int newIndex = i->first - 1;
351 // Copy the objective into a temporary object
352 Objective temp = i->second;
353
354 // Remove the old one
355 _objectives.erase(i++);
356
357 // Re-insert with new index
358 _objectives.insert(
359 ObjectiveMap::value_type(newIndex, temp)
360 );
361 }
362 }
363
364 // Test for targeting
365 bool ObjectiveEntity::isOnTargetList(const TargetList& list) const {
366 // Try to convert the weak_ptr reference to a shared_ptr
367 Entity* entity = Node_getEntity(_entityNode.lock());
368 assert(entity != NULL);
369
370 return list.isTargeted(entity);
371 }
372
373 LogicPtr ObjectiveEntity::getMissionLogic(int difficultyLevel) {
374 // The usual game, look up and insert if not found
375 LogicMap::iterator i = _logics.find(difficultyLevel);
376
377 if (i == _logics.end()) {
378 std::pair<LogicMap::iterator, bool> result = _logics.insert(
379 LogicMap::value_type(difficultyLevel, LogicPtr(new Logic))
380 );
381
382 i = result.first;
383 }
384
385 // At this point, the iterator is pointing to something valid
386 return i->second;
387 }
388
389 // Returns the full list of objective conditions by value
390 ObjectiveEntity::ConditionMap ObjectiveEntity::getObjectiveConditions() const
391 {
392 return _objConditions;
393 }
394
395 // Replaces the existing set of objective conditions with this new one
396 void ObjectiveEntity::setObjectiveConditions(const ObjectiveEntity::ConditionMap& conditions)
397 {
398 _objConditions = conditions;
399 }
400
401 std::size_t ObjectiveEntity::getNumObjectiveConditions() const
402 {
403 return _objConditions.size();
404 }
405
406 const ObjectiveConditionPtr& ObjectiveEntity::getOrCreateObjectiveCondition(int index)
407 {
408 ConditionMap::iterator i = _objConditions.find(index);
409
410 if (i == _objConditions.end())
411 {
412 // Insert and get iterator to new object
413 i = _objConditions.insert(ConditionMap::value_type(
414 index, ObjectiveConditionPtr(new ObjectiveCondition))).first;
415 }
416
417 return i->second;
418 }
419
420 void ObjectiveEntity::clearObjectiveConditions()
421 {
422 _objConditions.clear();
423 }
424
425 void ObjectiveEntity::populateChoice(wxChoice* choice) const
426 {
427 for (ObjectiveMap::const_iterator i = _objectives.begin();
428 i != _objectives.end();
429 ++i)
430 {
431 choice->Append(i->second.description,
432 new wxStringClientData(string::to_string(i->first)));
433 }
434 }
435
436 void ObjectiveEntity::populateListStore(wxutil::TreeModel& store,
437 const ObjectivesListColumns& columns) const
438 {
439 for (ObjectiveMap::const_iterator i = _objectives.begin();
440 i != _objectives.end();
441 ++i)
442 {
443 std::string diffStr = "all";
444
445 if (!i->second.difficultyLevels.empty()) {
446 // clear the string first
447 diffStr.clear();
448
449 // Split the string and increase each index by 1 for display (Level 1 == 0)
450 std::vector<std::string> parts;
451 string::split(parts, i->second.difficultyLevels, " ");
452
453 for (std::size_t d = 0; d < parts.size(); ++d) {
454 diffStr += (diffStr.empty()) ? "" : " ";
455 diffStr += string::to_string(string::convert<int>(parts[d]) + 1);
456 }
457 }
458
459 wxutil::TreeModel::Row row = store.AddItem();
460
461 row[columns.objNumber] = i->first;
462 row[columns.description] = i->second.description;
463 row[columns.difficultyLevel] = diffStr;
464
465 row.SendItemAdded();
466 }
467 }
468
469 // Write the Components from a single Objective to the underlying entity
470 void ObjectiveEntity::writeComponents(Entity* entity,
471 const std::string& keyPrefix, const Objective& obj
472 )
473 {
474 assert(entity != NULL);
475
476 for (Objective::ComponentMap::const_iterator i = obj.components.begin();
477 i != obj.components.end();
478 ++i)
479 {
480 const Component& c = i->second;
481
482 // Component prefix is like obj1_2_blah
483 std::string prefix = keyPrefix + string::to_string(i->first) + "_";
484
485 // Write out Component keyvals
486 entity->setKeyValue(prefix + "state", c.isSatisfied() ? "1" : "0");
487 entity->setKeyValue(prefix + "not", c.isInverted() ? "1" : "0");
488 entity->setKeyValue(prefix + "irreversible", c.isIrreversible() ? "1": "0");
489 entity->setKeyValue(prefix + "player_responsible", c.isPlayerResponsible() ? "1" : "0");
490 entity->setKeyValue(prefix + "type", c.getType().getName());
491
492 entity->setKeyValue(prefix + "clock_interval",
493 c.getClockInterval() > 0 ? string::to_string(c.getClockInterval()) : "");
494
495 // Write out Specifier keyvals
496 for (int s = Specifier::FIRST_SPECIFIER; s < Specifier::MAX_SPECIFIERS; s++)
497 {
498 // The specifier index of the spawnargs is starting from 1, not 0
499 std::string indexStr = string::to_string(s + 1);
500
501 SpecifierPtr spec = c.getSpecifier(static_cast<Specifier::SpecifierNumber>(s));
502
503 if (spec != NULL) {
504 entity->setKeyValue(prefix + "spec" + indexStr, spec->getType().getName());
505 entity->setKeyValue(prefix + "spec_val" + indexStr, spec->getValue());
506 }
507 }
508
509 // Export the component arguments
510 entity->setKeyValue(prefix + "args", c.getArgumentString());
511 }
512 }
513
514 void ObjectiveEntity::clearEntity(Entity* entity) {
515 // Get all keyvalues matching the "obj" prefix.
516 Entity::KeyValuePairs keyValues = entity->getKeyValuePairs("obj");
517
518 for (Entity::KeyValuePairs::const_iterator i = keyValues.begin();
519 i != keyValues.end(); ++i)
520 {
521 // Set the spawnarg to empty, which is equivalent to a removal
522 entity->setKeyValue(i->first, "");
523 }
524 }
525
526 // Write out Objectives to entity keyvals
527 void ObjectiveEntity::writeToEntity()
528 {
529 UndoableCommand cmd("saveObjectives");
530
531 // Try to convert the weak_ptr reference to a shared_ptr
532 Entity* entity = Node_getEntity(_entityNode.lock());
533 assert(entity != NULL);
534
535 // greebo: Remove all objective-related spawnargs first
536 clearEntity(entity);
537
538 for (ObjectiveMap::const_iterator i = _objectives.begin();
539 i != _objectives.end();
540 ++i)
541 {
542 // Obtain the Objective and construct the key prefix from the index
543 const Objective& o = i->second;
544 std::string prefix = "obj" + string::to_string(i->first) + "_";
545
546 // Set the entity keyvalues
547 entity->setKeyValue(prefix + "desc", o.description);
548 entity->setKeyValue(prefix + "ongoing", o.ongoing ? "1" : "0");
549 entity->setKeyValue(prefix + "visible", o.visible ? "1" : "0");
550 entity->setKeyValue(prefix + "mandatory", o.mandatory ? "1" : "0");
551 entity->setKeyValue(prefix + "irreversible",
552 o.irreversible ? "1" : "0");
553 entity->setKeyValue(prefix + "state", string::to_string(o.state));
554
555 // Write an empty "objN_difficulty" value when this objective applies to all levels
556 entity->setKeyValue(prefix + "difficulty", o.difficultyLevels);
557
558 entity->setKeyValue(prefix + "enabling_objs", o.enablingObjs);
559
560 entity->setKeyValue(prefix + "script_complete", o.completionScript);
561 entity->setKeyValue(prefix + "script_failed", o.failureScript);
562
563 entity->setKeyValue(prefix + "target_complete", o.completionTarget);
564 entity->setKeyValue(prefix + "target_failed", o.failureTarget);
565
566 entity->setKeyValue(prefix + "logic_success", o.logic.successLogic);
567 entity->setKeyValue(prefix + "logic_failure", o.logic.failureLogic);
568
569 // Write the Components for this Objective
570 writeComponents(entity, prefix, o);
571 }
572
573 // Export the mission success/failure logic
574 writeMissionLogic(*entity);
575
576 // Export objective conditions
577 writeObjectiveConditions(*entity);
578 }
579
580 } // namespace objectives