Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/multiplayer/multiplayer_spawner.cpp
20920 views
1
/**************************************************************************/
2
/* multiplayer_spawner.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "multiplayer_spawner.h"
32
33
#include "core/io/resource_loader.h"
34
#include "scene/main/multiplayer_api.h"
35
36
#ifdef TOOLS_ENABLED
37
/* This is editor only */
38
bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {
39
if (p_name == "_spawnable_scene_count") {
40
spawnable_scenes.resize(p_value);
41
notify_property_list_changed();
42
return true;
43
} else {
44
String ns = p_name;
45
if (ns.begins_with("scenes/")) {
46
uint32_t index = ns.get_slicec('/', 1).to_int();
47
ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
48
spawnable_scenes[index].path = ResourceUID::ensure_path(p_value);
49
return true;
50
}
51
}
52
return false;
53
}
54
55
bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {
56
if (p_name == "_spawnable_scene_count") {
57
r_ret = spawnable_scenes.size();
58
return true;
59
} else {
60
String ns = p_name;
61
if (ns.begins_with("scenes/")) {
62
uint32_t index = ns.get_slicec('/', 1).to_int();
63
ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
64
r_ret = ResourceUID::path_to_uid(spawnable_scenes[index].path);
65
return true;
66
}
67
}
68
return false;
69
}
70
71
void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {
72
p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));
73
List<String> exts;
74
ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);
75
String ext_hint;
76
for (const String &E : exts) {
77
if (!ext_hint.is_empty()) {
78
ext_hint += ",";
79
}
80
ext_hint += "*." + E;
81
}
82
for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
83
p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));
84
}
85
}
86
#endif
87
88
PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {
89
PackedStringArray warnings = Node::get_configuration_warnings();
90
91
if (spawn_path.is_empty() || !has_node(spawn_path)) {
92
warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes."));
93
}
94
return warnings;
95
}
96
97
void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {
98
SpawnableScene sc;
99
sc.path = ResourceUID::ensure_path(p_path);
100
if (Engine::get_singleton()->is_editor_hint()) {
101
ERR_FAIL_COND(!ResourceLoader::exists(sc.path));
102
}
103
spawnable_scenes.push_back(sc);
104
#ifdef TOOLS_ENABLED
105
if (Engine::get_singleton()->is_editor_hint()) {
106
return;
107
}
108
#endif
109
Node *node = get_spawn_node();
110
if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
111
node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
112
}
113
}
114
115
int MultiplayerSpawner::get_spawnable_scene_count() const {
116
return spawnable_scenes.size();
117
}
118
119
String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {
120
ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");
121
return spawnable_scenes[p_idx].path;
122
}
123
124
void MultiplayerSpawner::clear_spawnable_scenes() {
125
spawnable_scenes.clear();
126
#ifdef TOOLS_ENABLED
127
if (Engine::get_singleton()->is_editor_hint()) {
128
return;
129
}
130
#endif
131
Node *node = get_spawn_node();
132
if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
133
node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
134
}
135
}
136
137
Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {
138
Vector<String> ss;
139
ss.resize(spawnable_scenes.size());
140
for (int i = 0; i < ss.size(); i++) {
141
ss.write[i] = ResourceUID::path_to_uid(spawnable_scenes[i].path);
142
}
143
return ss;
144
}
145
146
void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {
147
clear_spawnable_scenes();
148
for (int i = 0; i < p_scenes.size(); i++) {
149
add_spawnable_scene(p_scenes[i]);
150
}
151
}
152
153
void MultiplayerSpawner::_bind_methods() {
154
ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);
155
ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);
156
ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);
157
ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);
158
159
ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);
160
ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);
161
162
ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");
163
164
ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));
165
166
ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);
167
ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);
168
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");
169
170
ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);
171
ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);
172
ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");
173
174
ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);
175
ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);
176
ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");
177
178
ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, Node::get_class_static())));
179
ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, Node::get_class_static())));
180
}
181
182
void MultiplayerSpawner::_update_spawn_node() {
183
#ifdef TOOLS_ENABLED
184
if (Engine::get_singleton()->is_editor_hint()) {
185
return;
186
}
187
#endif
188
if (spawn_node.is_valid()) {
189
Node *node = ObjectDB::get_instance<Node>(spawn_node);
190
if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
191
node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
192
}
193
}
194
Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);
195
if (node) {
196
spawn_node = node->get_instance_id();
197
if (get_spawnable_scene_count()) {
198
node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
199
}
200
} else {
201
spawn_node = ObjectID();
202
}
203
}
204
205
void MultiplayerSpawner::_notification(int p_what) {
206
switch (p_what) {
207
case NOTIFICATION_POST_ENTER_TREE: {
208
_update_spawn_node();
209
} break;
210
211
case NOTIFICATION_EXIT_TREE: {
212
_update_spawn_node();
213
214
for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {
215
Node *node = ObjectDB::get_instance<Node>(E.key);
216
ERR_CONTINUE(!node);
217
node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit));
218
get_multiplayer()->object_configuration_remove(node, this);
219
}
220
tracked_nodes.clear();
221
} break;
222
}
223
}
224
225
void MultiplayerSpawner::_node_added(Node *p_node) {
226
if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {
227
return;
228
}
229
if (tracked_nodes.has(p_node->get_instance_id())) {
230
return;
231
}
232
const Node *parent = get_spawn_node();
233
if (!parent || p_node->get_parent() != parent) {
234
return;
235
}
236
int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());
237
if (id == INVALID_ID) {
238
return;
239
}
240
const String name = p_node->get_name();
241
ERR_FAIL_COND_MSG(name.validate_node_name() != name, vformat("Unable to auto-spawn node with reserved name: %s. Make sure to add your replicated scenes via 'add_child(node, true)' to produce valid names.", name));
242
_track(p_node, Variant(), id);
243
}
244
245
NodePath MultiplayerSpawner::get_spawn_path() const {
246
return spawn_path;
247
}
248
249
void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {
250
spawn_path = p_path;
251
_update_spawn_node();
252
update_configuration_warnings();
253
}
254
255
void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {
256
ObjectID oid = p_node->get_instance_id();
257
if (!tracked_nodes.has(oid)) {
258
tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);
259
p_node->connect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);
260
_spawn_notify(p_node->get_instance_id());
261
}
262
}
263
264
void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {
265
get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);
266
}
267
268
void MultiplayerSpawner::_node_exit(ObjectID p_id) {
269
Node *node = ObjectDB::get_instance<Node>(p_id);
270
ERR_FAIL_NULL(node);
271
if (tracked_nodes.has(p_id)) {
272
tracked_nodes.erase(p_id);
273
get_multiplayer()->object_configuration_remove(node, this);
274
}
275
}
276
277
int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {
278
for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
279
if (spawnable_scenes[i].path == p_scene) {
280
return i;
281
}
282
}
283
return INVALID_ID;
284
}
285
286
int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {
287
const SpawnInfo *info = tracked_nodes.getptr(p_id);
288
return info ? info->id : INVALID_ID;
289
}
290
291
const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {
292
const SpawnInfo *info = tracked_nodes.getptr(p_id);
293
return info ? info->args : Variant();
294
}
295
296
Node *MultiplayerSpawner::instantiate_scene(int p_id) {
297
ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
298
ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);
299
SpawnableScene &sc = spawnable_scenes[p_id];
300
if (sc.cache.is_null()) {
301
sc.cache = ResourceLoader::load(sc.path);
302
}
303
ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);
304
return sc.cache->instantiate();
305
}
306
307
Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {
308
ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
309
ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");
310
const Variant *argv[1] = { &p_data };
311
Variant ret;
312
Callable::CallError ce;
313
spawn_function.callp(argv, 1, ret, ce);
314
ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");
315
ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");
316
return Object::cast_to<Node>(ret.operator Object *());
317
}
318
319
Node *MultiplayerSpawner::spawn(const Variant &p_data) {
320
ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);
321
ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
322
ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");
323
324
Node *parent = get_spawn_node();
325
ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");
326
327
Node *node = instantiate_custom(p_data);
328
ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");
329
330
_track(node, p_data);
331
parent->add_child(node, true);
332
return node;
333
}
334
335