summaryrefslogtreecommitdiff
path: root/modules/mono/editor/godotsharp_export.cpp
blob: ae5b939b26138b166f57cc3b7812fbe2e4ce39c0 (plain)
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
/*************************************************************************/
/*  godotsharp_export.cpp                                                */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "godotsharp_export.h"

#include "core/version.h"

#include "../csharp_script.h"
#include "../godotsharp_defs.h"
#include "../godotsharp_dirs.h"
#include "../mono_gd/gd_mono_class.h"
#include "../mono_gd/gd_mono_marshal.h"
#include "csharp_project.h"
#include "godotsharp_builds.h"

static MonoString *godot_icall_GodotSharpExport_GetTemplatesDir() {
	String current_version = VERSION_FULL_CONFIG;
	String templates_dir = EditorSettings::get_singleton()->get_templates_dir().plus_file(current_version);
	return GDMonoMarshal::mono_string_from_godot(ProjectSettings::get_singleton()->globalize_path(templates_dir));
}

static MonoString *godot_icall_GodotSharpExport_GetDataDirName() {
	String appname = ProjectSettings::get_singleton()->get("application/config/name");
	String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
	return GDMonoMarshal::mono_string_from_godot("data_" + appname_safe);
}

void GodotSharpExport::register_internal_calls() {
	static bool registered = false;
	ERR_FAIL_COND(registered);
	registered = true;

	mono_add_internal_call("GodotSharpTools.Editor.GodotSharpExport::GetTemplatesDir", (void *)godot_icall_GodotSharpExport_GetTemplatesDir);
	mono_add_internal_call("GodotSharpTools.Editor.GodotSharpExport::GetDataDirName", (void *)godot_icall_GodotSharpExport_GetDataDirName);
}

void GodotSharpExport::_export_file(const String &p_path, const String &p_type, const Set<String> &) {

	if (p_type != CSharpLanguage::get_singleton()->get_type())
		return;

	ERR_FAIL_COND(p_path.get_extension() != CSharpLanguage::get_singleton()->get_extension());

	// TODO what if the source file is not part of the game's C# project

	if (!GLOBAL_GET("mono/export/include_scripts_content")) {
		// We don't want to include the source code on exported games
		add_file(p_path, Vector<uint8_t>(), false);
		skip();
	}
}

void GodotSharpExport::_export_begin(const Set<String> &p_features, bool p_debug, const String &p_path, int p_flags) {

	// TODO right now there is no way to stop the export process with an error

	ERR_FAIL_COND(!GDMono::get_singleton()->is_runtime_initialized());
	ERR_FAIL_NULL(TOOLS_DOMAIN);
	ERR_FAIL_NULL(GDMono::get_singleton()->get_editor_tools_assembly());

	if (FileAccess::exists(GodotSharpDirs::get_project_sln_path())) {
		String build_config = p_debug ? "Debug" : "Release";

		String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file("scripts_metadata." + String(p_debug ? "debug" : "release"));
		Error metadata_err = CSharpProject::generate_scripts_metadata(GodotSharpDirs::get_project_csproj_path(), scripts_metadata_path);
		ERR_FAIL_COND(metadata_err != OK);

		ERR_FAIL_COND(!_add_file(scripts_metadata_path, scripts_metadata_path));

		// Turn export features into defines
		Vector<String> godot_defines;
		for (Set<String>::Element *E = p_features.front(); E; E = E->next()) {
			godot_defines.push_back(E->get());
		}
		ERR_FAIL_COND(!GodotSharpBuilds::build_project_blocking(build_config, godot_defines));

		// Add dependency assemblies

		Map<String, String> dependencies;

		String project_dll_name = ProjectSettings::get_singleton()->get("application/config/name");
		if (project_dll_name.empty()) {
			project_dll_name = "UnnamedProject";
		}

		String project_dll_src_dir = GodotSharpDirs::get_res_temp_assemblies_base_dir().plus_file(build_config);
		String project_dll_src_path = project_dll_src_dir.plus_file(project_dll_name + ".dll");
		dependencies.insert(project_dll_name, project_dll_src_path);

		{
			MonoDomain *export_domain = GDMonoUtils::create_domain("GodotEngine.ProjectExportDomain");
			ERR_FAIL_NULL(export_domain);
			_GDMONO_SCOPE_EXIT_DOMAIN_UNLOAD_(export_domain);

			_GDMONO_SCOPE_DOMAIN_(export_domain);

			GDMonoAssembly *scripts_assembly = NULL;
			bool load_success = GDMono::get_singleton()->load_assembly_from(project_dll_name,
					project_dll_src_path, &scripts_assembly, /* refonly: */ true);

			ERR_EXPLAIN("Cannot load refonly assembly: " + project_dll_name);
			ERR_FAIL_COND(!load_success);

			Vector<String> search_dirs;
			GDMonoAssembly::fill_search_dirs(search_dirs, build_config);
			Error depend_error = _get_assembly_dependencies(scripts_assembly, search_dirs, dependencies);
			ERR_FAIL_COND(depend_error != OK);
		}

		for (Map<String, String>::Element *E = dependencies.front(); E; E = E->next()) {
			String depend_src_path = E->value();
			String depend_dst_path = GodotSharpDirs::get_res_assemblies_dir().plus_file(depend_src_path.get_file());
			ERR_FAIL_COND(!_add_file(depend_src_path, depend_dst_path));
		}
	}

	// Mono specific export template extras (data dir)

	GDMonoClass *export_class = GDMono::get_singleton()->get_editor_tools_assembly()->get_class("GodotSharpTools.Editor", "GodotSharpExport");
	ERR_FAIL_NULL(export_class);
	GDMonoMethod *export_begin_method = export_class->get_method("_ExportBegin", 4);
	ERR_FAIL_NULL(export_begin_method);

	MonoArray *features = mono_array_new(mono_domain_get(), CACHED_CLASS_RAW(String), p_features.size());
	int i = 0;
	for (const Set<String>::Element *E = p_features.front(); E; E = E->next()) {
		MonoString *boxed = GDMonoMarshal::mono_string_from_godot(E->get());
		mono_array_set(features, MonoString *, i, boxed);
		i++;
	}

	MonoBoolean debug = p_debug;
	MonoString *path = GDMonoMarshal::mono_string_from_godot(p_path);
	uint32_t flags = p_flags;
	void *args[4] = { features, &debug, path, &flags };
	MonoException *exc = NULL;
	export_begin_method->invoke_raw(NULL, args, &exc);

	if (exc) {
		GDMonoUtils::debug_print_unhandled_exception(exc);
		ERR_FAIL();
	}
}

bool GodotSharpExport::_add_file(const String &p_src_path, const String &p_dst_path, bool p_remap) {

	FileAccessRef f = FileAccess::open(p_src_path, FileAccess::READ);
	ERR_FAIL_COND_V(!f, false);

	Vector<uint8_t> data;
	data.resize(f->get_len());
	f->get_buffer(data.ptrw(), data.size());

	add_file(p_dst_path, data, p_remap);

	return true;
}

Error GodotSharpExport::_get_assembly_dependencies(GDMonoAssembly *p_assembly, const Vector<String> &p_search_dirs, Map<String, String> &r_dependencies) {

	MonoImage *image = p_assembly->get_image();

	for (int i = 0; i < mono_image_get_table_rows(image, MONO_TABLE_ASSEMBLYREF); i++) {
		MonoAssemblyName *ref_aname = aname_prealloc;
		mono_assembly_get_assemblyref(image, i, ref_aname);
		String ref_name = mono_assembly_name_get_name(ref_aname);

		if (r_dependencies.find(ref_name))
			continue;

		GDMonoAssembly *ref_assembly = NULL;
		String path;
		bool has_extension = ref_name.ends_with(".dll") || ref_name.ends_with(".exe");

		for (int j = 0; j < p_search_dirs.size(); j++) {
			const String &search_dir = p_search_dirs[j];

			if (has_extension) {
				path = search_dir.plus_file(ref_name);
				if (FileAccess::exists(path)) {
					GDMono::get_singleton()->load_assembly_from(ref_name.get_basename(), path, &ref_assembly, true);
					if (ref_assembly != NULL)
						break;
				}
			} else {
				path = search_dir.plus_file(ref_name + ".dll");
				if (FileAccess::exists(path)) {
					GDMono::get_singleton()->load_assembly_from(ref_name, path, &ref_assembly, true);
					if (ref_assembly != NULL)
						break;
				}

				path = search_dir.plus_file(ref_name + ".exe");
				if (FileAccess::exists(path)) {
					GDMono::get_singleton()->load_assembly_from(ref_name, path, &ref_assembly, true);
					if (ref_assembly != NULL)
						break;
				}
			}
		}

		if (!ref_assembly) {
			ERR_EXPLAIN("Cannot load assembly (refonly): " + ref_name);
			ERR_FAIL_V(ERR_CANT_RESOLVE);
		}

		r_dependencies.insert(ref_name, ref_assembly->get_path());

		Error err = _get_assembly_dependencies(ref_assembly, p_search_dirs, r_dependencies);
		if (err != OK)
			return err;
	}

	return OK;
}

GodotSharpExport::GodotSharpExport() {
	// MonoAssemblyName is an incomplete type (internal to mono), so we can't allocate it ourselves.
	// There isn't any api to allocate an empty one either, so we need to do it this way.
	aname_prealloc = mono_assembly_name_new("whatever");
	mono_assembly_name_free(aname_prealloc); // "it does not frees the object itself, only the name members" (typo included)
}

GodotSharpExport::~GodotSharpExport() {
	if (aname_prealloc)
		mono_free(aname_prealloc);
}