summaryrefslogtreecommitdiff
path: root/editor/import/resource_importer_texture_atlas.cpp
blob: bca24a126cd158f27ea9279bebc5b37091d69934 (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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**************************************************************************/
/*  resource_importer_texture_atlas.cpp                                   */
/**************************************************************************/
/*                         This file is part of:                          */
/*                             GODOT ENGINE                               */
/*                        https://godotengine.org                         */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.                  */
/*                                                                        */
/* 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 "resource_importer_texture_atlas.h"

#include "atlas_import_failed.xpm"
#include "core/io/file_access.h"
#include "core/io/image_loader.h"
#include "core/io/resource_saver.h"
#include "core/math/geometry_2d.h"
#include "editor/editor_atlas_packer.h"
#include "scene/resources/mesh.h"
#include "scene/resources/texture.h"

String ResourceImporterTextureAtlas::get_importer_name() const {
	return "texture_atlas";
}

String ResourceImporterTextureAtlas::get_visible_name() const {
	return "TextureAtlas";
}

void ResourceImporterTextureAtlas::get_recognized_extensions(List<String> *p_extensions) const {
	ImageLoader::get_recognized_extensions(p_extensions);
}

String ResourceImporterTextureAtlas::get_save_extension() const {
	return "res";
}

String ResourceImporterTextureAtlas::get_resource_type() const {
	return "Texture2D";
}

bool ResourceImporterTextureAtlas::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
	return true;
}

int ResourceImporterTextureAtlas::get_preset_count() const {
	return 0;
}

String ResourceImporterTextureAtlas::get_preset_name(int p_idx) const {
	return String();
}

void ResourceImporterTextureAtlas::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
	r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "atlas_file", PROPERTY_HINT_SAVE_FILE, "*.png"), ""));
	r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_mode", PROPERTY_HINT_ENUM, "Region,Mesh2D"), 0));
	r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "crop_to_region"), false));
	r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "trim_alpha_border_from_region"), true));
}

String ResourceImporterTextureAtlas::get_option_group_file() const {
	return "atlas_file";
}

Error ResourceImporterTextureAtlas::import(const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
	/* If this happens, it's because the atlas_file field was not filled, so just import a broken texture */

	//use an xpm because it's size independent, the editor images are vector and size dependent
	//it's a simple hack
	Ref<Image> broken = memnew(Image((const char **)atlas_import_failed_xpm));
	ResourceSaver::save(ImageTexture::create_from_image(broken), p_save_path + ".tex");

	return OK;
}

static void _plot_triangle(Vector2i *vertices, const Vector2i &p_offset, bool p_transposed, Ref<Image> p_image, const Ref<Image> &p_src_image) {
	int width = p_image->get_width();
	int height = p_image->get_height();
	int src_width = p_src_image->get_width();
	int src_height = p_src_image->get_height();

	int x[3];
	int y[3];

	for (int j = 0; j < 3; j++) {
		x[j] = vertices[j].x;
		y[j] = vertices[j].y;
	}

	// sort the points vertically
	if (y[1] > y[2]) {
		SWAP(x[1], x[2]);
		SWAP(y[1], y[2]);
	}
	if (y[0] > y[1]) {
		SWAP(x[0], x[1]);
		SWAP(y[0], y[1]);
	}
	if (y[1] > y[2]) {
		SWAP(x[1], x[2]);
		SWAP(y[1], y[2]);
	}

	double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);
	double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);
	double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);
	double xf = x[0];
	double xt = x[0] + dx_upper; // if y[0] == y[1], special case
	int max_y = MIN(y[2], height - p_offset.y - 1);
	for (int yi = y[0]; yi < max_y; yi++) {
		if (yi >= 0) {
			for (int xi = (xf > 0 ? int(xf) : 0); xi < (xt <= src_width ? xt : src_width); xi++) {
				int px = xi, py = yi;
				int sx = px, sy = py;
				sx = CLAMP(sx, 0, src_width - 1);
				sy = CLAMP(sy, 0, src_height - 1);
				Color color = p_src_image->get_pixel(sx, sy);
				if (p_transposed) {
					SWAP(px, py);
				}
				px += p_offset.x;
				py += p_offset.y;

				//may have been cropped, so don't blit what is not visible?
				if (px < 0 || px >= width) {
					continue;
				}
				if (py < 0 || py >= height) {
					continue;
				}
				p_image->set_pixel(px, py, color);
			}

			for (int xi = (xf < src_width ? int(xf) : src_width - 1); xi >= (xt > 0 ? xt : 0); xi--) {
				int px = xi, py = yi;
				int sx = px, sy = py;
				sx = CLAMP(sx, 0, src_width - 1);
				sy = CLAMP(sy, 0, src_height - 1);
				Color color = p_src_image->get_pixel(sx, sy);
				if (p_transposed) {
					SWAP(px, py);
				}
				px += p_offset.x;
				py += p_offset.y;

				//may have been cropped, so don't blit what is not visible?
				if (px < 0 || px >= width) {
					continue;
				}
				if (py < 0 || py >= height) {
					continue;
				}
				p_image->set_pixel(px, py, color);
			}
		}
		xf += dx_far;
		if (yi < y[1]) {
			xt += dx_upper;
		} else {
			xt += dx_low;
		}
	}
}

Error ResourceImporterTextureAtlas::import_group_file(const String &p_group_file, const HashMap<String, HashMap<StringName, Variant>> &p_source_file_options, const HashMap<String, String> &p_base_paths) {
	ERR_FAIL_COND_V(p_source_file_options.size() == 0, ERR_BUG); //should never happen

	Vector<EditorAtlasPacker::Chart> charts;
	Vector<PackData> pack_data_files;

	pack_data_files.resize(p_source_file_options.size());

	int idx = 0;
	for (const KeyValue<String, HashMap<StringName, Variant>> &E : p_source_file_options) {
		PackData &pack_data = pack_data_files.write[idx];
		const String &source = E.key;
		const HashMap<StringName, Variant> &options = E.value;

		Ref<Image> image;
		image.instantiate();
		Error err = ImageLoader::load_image(source, image);
		ERR_CONTINUE(err != OK);

		pack_data.image = image;
		pack_data.is_cropped = options["crop_to_region"];

		int mode = options["import_mode"];
		bool trim_alpha_border_from_region = options["trim_alpha_border_from_region"];

		if (mode == IMPORT_MODE_REGION) {
			pack_data.is_mesh = false;

			EditorAtlasPacker::Chart chart;

			Rect2i used_rect = Rect2i(Vector2i(), image->get_size());
			if (trim_alpha_border_from_region) {
				// Clip a region from the image.
				used_rect = image->get_used_rect();
			}
			pack_data.region = used_rect;

			chart.vertices.push_back(used_rect.position);
			chart.vertices.push_back(used_rect.position + Vector2i(used_rect.size.x, 0));
			chart.vertices.push_back(used_rect.position + Vector2i(used_rect.size.x, used_rect.size.y));
			chart.vertices.push_back(used_rect.position + Vector2i(0, used_rect.size.y));
			EditorAtlasPacker::Chart::Face f;
			f.vertex[0] = 0;
			f.vertex[1] = 1;
			f.vertex[2] = 2;
			chart.faces.push_back(f);
			f.vertex[0] = 0;
			f.vertex[1] = 2;
			f.vertex[2] = 3;
			chart.faces.push_back(f);
			chart.can_transpose = false;
			pack_data.chart_vertices.push_back(chart.vertices);
			pack_data.chart_pieces.push_back(charts.size());
			charts.push_back(chart);

		} else {
			pack_data.is_mesh = true;

			Ref<BitMap> bit_map;
			bit_map.instantiate();
			bit_map->create_from_image_alpha(image);
			Vector<Vector<Vector2>> polygons = bit_map->clip_opaque_to_polygons(Rect2(0, 0, image->get_width(), image->get_height()));

			for (int j = 0; j < polygons.size(); j++) {
				EditorAtlasPacker::Chart chart;
				chart.vertices = polygons[j];
				chart.can_transpose = true;

				Vector<int> poly = Geometry2D::triangulate_polygon(polygons[j]);
				for (int i = 0; i < poly.size(); i += 3) {
					EditorAtlasPacker::Chart::Face f;
					f.vertex[0] = poly[i + 0];
					f.vertex[1] = poly[i + 1];
					f.vertex[2] = poly[i + 2];
					chart.faces.push_back(f);
				}

				pack_data.chart_pieces.push_back(charts.size());
				charts.push_back(chart);

				pack_data.chart_vertices.push_back(polygons[j]);
			}
		}
		idx++;
	}

	//pack the charts
	int atlas_width, atlas_height;
	EditorAtlasPacker::chart_pack(charts, atlas_width, atlas_height);

	//blit the atlas
	Ref<Image> new_atlas = Image::create_empty(atlas_width, atlas_height, false, Image::FORMAT_RGBA8);

	for (int i = 0; i < pack_data_files.size(); i++) {
		PackData &pack_data = pack_data_files.write[i];

		for (int j = 0; j < pack_data.chart_pieces.size(); j++) {
			const EditorAtlasPacker::Chart &chart = charts[pack_data.chart_pieces[j]];
			for (int k = 0; k < chart.faces.size(); k++) {
				Vector2i positions[3];
				for (int l = 0; l < 3; l++) {
					int vertex_idx = chart.faces[k].vertex[l];
					positions[l] = Vector2i(chart.vertices[vertex_idx]);
				}

				_plot_triangle(positions, Vector2i(chart.final_offset), chart.transposed, new_atlas, pack_data.image);
			}
		}
	}

	//save the atlas

	new_atlas->save_png(p_group_file);

	//update cache if existing, else create
	Ref<Texture2D> cache;
	cache = ResourceCache::get_ref(p_group_file);
	if (!cache.is_valid()) {
		Ref<ImageTexture> res_cache = ImageTexture::create_from_image(new_atlas);
		res_cache->set_path(p_group_file);
		cache = res_cache;
	}

	//save the images
	idx = 0;
	for (const KeyValue<String, HashMap<StringName, Variant>> &E : p_source_file_options) {
		PackData &pack_data = pack_data_files.write[idx];

		Ref<Texture2D> texture;

		if (!pack_data.is_mesh) {
			Vector2 offset = charts[pack_data.chart_pieces[0]].vertices[0] + charts[pack_data.chart_pieces[0]].final_offset;

			//region
			Ref<AtlasTexture> atlas_texture;
			atlas_texture.instantiate();
			atlas_texture->set_atlas(cache);
			atlas_texture->set_region(Rect2(offset, pack_data.region.size));

			if (!pack_data.is_cropped) {
				atlas_texture->set_margin(Rect2(pack_data.region.position, pack_data.image->get_size() - pack_data.region.size));
			}

			texture = atlas_texture;
		} else {
			Ref<ArrayMesh> mesh;
			mesh.instantiate();

			for (int i = 0; i < pack_data.chart_pieces.size(); i++) {
				const EditorAtlasPacker::Chart &chart = charts[pack_data.chart_pieces[i]];
				Vector<Vector2> vertices;
				Vector<int> indices;
				Vector<Vector2> uvs;
				int vc = chart.vertices.size();
				int fc = chart.faces.size();
				vertices.resize(vc);
				uvs.resize(vc);
				indices.resize(fc * 3);

				{
					Vector2 *vw = vertices.ptrw();
					int *iw = indices.ptrw();
					Vector2 *uvw = uvs.ptrw();

					for (int j = 0; j < vc; j++) {
						vw[j] = chart.vertices[j];
						Vector2 uv = chart.vertices[j];
						if (chart.transposed) {
							SWAP(uv.x, uv.y);
						}
						uv += chart.final_offset;
						uv /= new_atlas->get_size(); //normalize uv to 0-1 range
						uvw[j] = uv;
					}

					for (int j = 0; j < fc; j++) {
						iw[j * 3 + 0] = chart.faces[j].vertex[0];
						iw[j * 3 + 1] = chart.faces[j].vertex[1];
						iw[j * 3 + 2] = chart.faces[j].vertex[2];
					}
				}

				Array arrays;
				arrays.resize(Mesh::ARRAY_MAX);
				arrays[Mesh::ARRAY_VERTEX] = vertices;
				arrays[Mesh::ARRAY_TEX_UV] = uvs;
				arrays[Mesh::ARRAY_INDEX] = indices;

				mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
			}

			Ref<MeshTexture> mesh_texture;
			mesh_texture.instantiate();
			mesh_texture->set_base_texture(cache);
			mesh_texture->set_image_size(pack_data.image->get_size());
			mesh_texture->set_mesh(mesh);

			texture = mesh_texture;
		}

		String save_path = p_base_paths[E.key] + ".res";
		ResourceSaver::save(texture, save_path);
		idx++;
	}

	return OK;
}

ResourceImporterTextureAtlas::ResourceImporterTextureAtlas() {
}