Crossfire Server  1.75.0
Messages.cpp
Go to the documentation of this file.
1 /*
2  * Crossfire -- cooperative multi-player graphical RPG and adventure game
3  *
4  * Copyright (c) 2020 the Crossfire Development Team
5  *
6  * Crossfire is free software and comes with ABSOLUTELY NO WARRANTY. You are
7  * welcome to redistribute it under certain conditions. For details, please
8  * see COPYING and LICENSE.
9  *
10  * The authors can be reached via e-mail at <crossfire@metalforge.org>.
11  */
12 
13 #include "Messages.h"
14 #include "global.h"
15 
16 template<>
17 GeneralMessage *asset_create(const std::string& name) {
18  auto msg = static_cast<GeneralMessage *>(calloc(1, sizeof(GeneralMessage)));
19  msg->identifier = add_string(name.c_str());
20  return msg;
21 }
22 
23 template<>
29  free(item);
30 }
31 
32 Messages::Messages() : m_totalChance(0) {
33 }
34 
36  FREE_AND_COPY_IF(existing->identifier, update->identifier);
37  FREE_AND_COPY_IF(existing->message, update->message);
38  FREE_AND_COPY_IF(existing->quest_code, update->quest_code);
39  FREE_AND_COPY_IF(existing->title, existing->title);
40  m_totalChance -= existing->chance;
41  m_totalChance += update->chance;
42  existing->chance = update->chance;
43  asset_destroy(update);
44 }
45 
47  m_totalChance += asset->chance;
48 }
49 
51  if (!m_totalChance) {
52  return nullptr;
53  }
54 
55  auto msg = m_assets.begin();
56  int weight = (RANDOM() % m_totalChance);
57  while (msg != m_assets.end()) {
58  weight -= msg->second->chance;
59  if (weight < 0)
60  break;
61  msg++;
62  }
63  return msg->second;
64 }
virtual void added(GeneralMessage *asset) override
An asset was either referenced (but undefined) or defined.
Definition: Messages.cpp:46
sstring title
The message&#39;s title, only used for knowledge.
Definition: book.h:48
virtual void replace(GeneralMessage *existing, GeneralMessage *update) override
Replace an asset by an updated version.
Definition: Messages.cpp:35
sstring add_string(const char *str)
Share a string.
Definition: shstr.cpp:137
#define FREE_AND_CLEAR_STR_IF(xyz)
Definition: global.h:202
GeneralMessage * asset_create(const std::string &name)
Definition: Messages.cpp:17
sstring identifier
Message identifier, can be NULL.
Definition: book.h:47
Global type definitions and header inclusions.
void asset_destroy(GeneralMessage *item)
Definition: Messages.cpp:24
std::unordered_map< std::string, GeneralMessage *> m_assets
Known assets.
GeneralMessage * random()
Definition: Messages.cpp:50
#define FREE_AND_COPY_IF(sv, nv)
Definition: global.h:208
int chance
Relative chance of the message appearing randomly.
Definition: book.h:45
sstring quest_code
Optional quest code and state this message will start.
Definition: book.h:50
int m_totalChance
Definition: Messages.h:30
#define RANDOM()
Definition: define.h:667
One general message, from the lib/messages file.
Definition: book.h:44
Messages()
Definition: Messages.cpp:32
sstring message
The message&#39;s body.
Definition: book.h:49