-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplugin.cpp
97 lines (81 loc) · 2.7 KB
/
plugin.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
/**
* Copyright (c) 2018 - Marcos Cardinot <[email protected]>
* Copyright (c) 2018 - Ethan Padden <[email protected]>
*
* This source code is licensed under the MIT license found in
* the LICENSE file in the root directory of this source tree.
*/
#include "plugin.h"
namespace evoplex {
QBitArray LifeLike::ruleToBitArray(int cmd) const
{
QBitArray rules(9);
// convert rule to a bitstream
// Check the command should be empty (input of -1)
// before iterating.
if (cmd != -1)
{
int c;
do
{
c = cmd%10;
if (c == 9) {
qWarning() << "Command should contain only valid integers (0-8).";
return QBitArray();
}
if (rules[c]){
qWarning() << "Rulestring should contain only unique integers.";
return QBitArray();
}
rules.setBit(c);
cmd /= 10;
} while(cmd);
}
return rules;
}
bool LifeLike::init()
{
// gets the id of the `live` node's attribute, which is the same for all nodes
m_liveAttrId = node(0).attrs().indexOf("live");
// parses the ruleset
if (attrExists("birth") && attrExists("survival")) {
m_birthLst = ruleToBitArray(attr("birth").toInt());
m_survivalLst = ruleToBitArray(attr("survival").toInt());
} else{
qWarning() << "missing attributes.";
return false;
}
return m_liveAttrId >= 0 && !m_birthLst.isNull() && !m_survivalLst.isNull();
}
bool LifeLike::algorithmStep()
{
std::vector<Value> nextStates;
nextStates.reserve(nodes().size());
for (Node node : nodes()) {
int liveNeighbourCount = 0;
for (Node neighbour : node.outEdges()) {
if (neighbour.attr(m_liveAttrId).toBool()) {
++liveNeighbourCount;
}
}
if (node.attr(m_liveAttrId).toBool()) {
// If the node is alive, then it only survives if its number of neighbors is specified in the rulestring.
// Otherwise, it dies from under/overpopulation
nextStates.emplace_back(m_survivalLst[liveNeighbourCount]);
} else {
// Any dead cell can become alive if its number of neighbors matches the one specified in the rulestring.
// Otherwise, it remains dead.
nextStates.emplace_back(m_birthLst[liveNeighbourCount]);
}
}
// For each node, load the next state into the current state
size_t i = 0;
for (Node node : nodes()) {
node.setAttr(m_liveAttrId, nextStates.at(i));
++i;
}
return true;
}
} // evoplex
REGISTER_PLUGIN(LifeLike)
#include "plugin.moc"