1 /*************************************************************************/
2 /*  particles_2d_editor_plugin.cpp                                       */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
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 "particles_2d_editor_plugin.h"
32 
33 #include "canvas_item_editor_plugin.h"
34 #include "core/io/image_loader.h"
35 #include "scene/2d/cpu_particles_2d.h"
36 #include "scene/gui/separator.h"
37 #include "scene/resources/particles_material.h"
38 
edit(Object * p_object)39 void Particles2DEditorPlugin::edit(Object *p_object) {
40 
41 	particles = Object::cast_to<Particles2D>(p_object);
42 }
43 
handles(Object * p_object) const44 bool Particles2DEditorPlugin::handles(Object *p_object) const {
45 
46 	return p_object->is_class("Particles2D");
47 }
48 
make_visible(bool p_visible)49 void Particles2DEditorPlugin::make_visible(bool p_visible) {
50 
51 	if (p_visible) {
52 
53 		toolbar->show();
54 	} else {
55 
56 		toolbar->hide();
57 	}
58 }
59 
_file_selected(const String & p_file)60 void Particles2DEditorPlugin::_file_selected(const String &p_file) {
61 
62 	source_emission_file = p_file;
63 	emission_mask->popup_centered_minsize();
64 }
65 
_menu_callback(int p_idx)66 void Particles2DEditorPlugin::_menu_callback(int p_idx) {
67 
68 	switch (p_idx) {
69 		case MENU_GENERATE_VISIBILITY_RECT: {
70 			float gen_time = particles->get_lifetime();
71 			if (gen_time < 1.0)
72 				generate_seconds->set_value(1.0);
73 			else
74 				generate_seconds->set_value(trunc(gen_time) + 1.0);
75 			generate_visibility_rect->popup_centered_minsize();
76 		} break;
77 		case MENU_LOAD_EMISSION_MASK: {
78 
79 			file->popup_centered_ratio();
80 
81 		} break;
82 		case MENU_CLEAR_EMISSION_MASK: {
83 
84 			emission_mask->popup_centered_minsize();
85 		} break;
86 		case MENU_OPTION_CONVERT_TO_CPU_PARTICLES: {
87 
88 			CPUParticles2D *cpu_particles = memnew(CPUParticles2D);
89 			cpu_particles->convert_from_particles(particles);
90 			cpu_particles->set_name(particles->get_name());
91 			cpu_particles->set_transform(particles->get_transform());
92 			cpu_particles->set_visible(particles->is_visible());
93 			cpu_particles->set_pause_mode(particles->get_pause_mode());
94 			cpu_particles->set_z_index(particles->get_z_index());
95 
96 			UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo();
97 			ur->create_action(TTR("Convert to CPUParticles"));
98 			ur->add_do_method(EditorNode::get_singleton()->get_scene_tree_dock(), "replace_node", particles, cpu_particles, true, false);
99 			ur->add_do_reference(cpu_particles);
100 			ur->add_undo_method(EditorNode::get_singleton()->get_scene_tree_dock(), "replace_node", cpu_particles, particles, false, false);
101 			ur->add_undo_reference(particles);
102 			ur->commit_action();
103 
104 		} break;
105 		case MENU_RESTART: {
106 
107 			particles->restart();
108 		}
109 	}
110 }
111 
_generate_visibility_rect()112 void Particles2DEditorPlugin::_generate_visibility_rect() {
113 
114 	float time = generate_seconds->get_value();
115 
116 	float running = 0.0;
117 
118 	EditorProgress ep("gen_vrect", TTR("Generating Visibility Rect"), int(time));
119 
120 	bool was_emitting = particles->is_emitting();
121 	if (!was_emitting) {
122 		particles->set_emitting(true);
123 		OS::get_singleton()->delay_usec(1000);
124 	}
125 
126 	Rect2 rect;
127 	while (running < time) {
128 
129 		uint64_t ticks = OS::get_singleton()->get_ticks_usec();
130 		ep.step("Generating...", int(running), true);
131 		OS::get_singleton()->delay_usec(1000);
132 
133 		Rect2 capture = particles->capture_rect();
134 		if (rect == Rect2())
135 			rect = capture;
136 		else
137 			rect = rect.merge(capture);
138 
139 		running += (OS::get_singleton()->get_ticks_usec() - ticks) / 1000000.0;
140 	}
141 
142 	if (!was_emitting) {
143 		particles->set_emitting(false);
144 	}
145 
146 	undo_redo->create_action(TTR("Generate Visibility Rect"));
147 	undo_redo->add_do_method(particles, "set_visibility_rect", rect);
148 	undo_redo->add_undo_method(particles, "set_visibility_rect", particles->get_visibility_rect());
149 	undo_redo->commit_action();
150 }
151 
_generate_emission_mask()152 void Particles2DEditorPlugin::_generate_emission_mask() {
153 
154 	Ref<ParticlesMaterial> pm = particles->get_process_material();
155 	if (!pm.is_valid()) {
156 		EditorNode::get_singleton()->show_warning(TTR("Can only set point into a ParticlesMaterial process material"));
157 		return;
158 	}
159 
160 	Ref<Image> img;
161 	img.instance();
162 	Error err = ImageLoader::load_image(source_emission_file, img);
163 	ERR_FAIL_COND_MSG(err != OK, "Error loading image '" + source_emission_file + "'.");
164 
165 	if (img->is_compressed()) {
166 		img->decompress();
167 	}
168 	img->convert(Image::FORMAT_RGBA8);
169 	ERR_FAIL_COND(img->get_format() != Image::FORMAT_RGBA8);
170 	Size2i s = Size2(img->get_width(), img->get_height());
171 	ERR_FAIL_COND(s.width == 0 || s.height == 0);
172 
173 	Vector<Point2> valid_positions;
174 	Vector<Point2> valid_normals;
175 	Vector<uint8_t> valid_colors;
176 
177 	valid_positions.resize(s.width * s.height);
178 
179 	EmissionMode emode = (EmissionMode)emission_mask_mode->get_selected();
180 
181 	if (emode == EMISSION_MODE_BORDER_DIRECTED) {
182 		valid_normals.resize(s.width * s.height);
183 	}
184 
185 	bool capture_colors = emission_colors->is_pressed();
186 
187 	if (capture_colors) {
188 		valid_colors.resize(s.width * s.height * 4);
189 	}
190 
191 	int vpc = 0;
192 
193 	{
194 		PoolVector<uint8_t> data = img->get_data();
195 		PoolVector<uint8_t>::Read r = data.read();
196 
197 		for (int i = 0; i < s.width; i++) {
198 			for (int j = 0; j < s.height; j++) {
199 
200 				uint8_t a = r[(j * s.width + i) * 4 + 3];
201 
202 				if (a > 128) {
203 
204 					if (emode == EMISSION_MODE_SOLID) {
205 
206 						if (capture_colors) {
207 							valid_colors.write[vpc * 4 + 0] = r[(j * s.width + i) * 4 + 0];
208 							valid_colors.write[vpc * 4 + 1] = r[(j * s.width + i) * 4 + 1];
209 							valid_colors.write[vpc * 4 + 2] = r[(j * s.width + i) * 4 + 2];
210 							valid_colors.write[vpc * 4 + 3] = r[(j * s.width + i) * 4 + 3];
211 						}
212 						valid_positions.write[vpc++] = Point2(i, j);
213 
214 					} else {
215 
216 						bool on_border = false;
217 						for (int x = i - 1; x <= i + 1; x++) {
218 							for (int y = j - 1; y <= j + 1; y++) {
219 
220 								if (x < 0 || y < 0 || x >= s.width || y >= s.height || r[(y * s.width + x) * 4 + 3] <= 128) {
221 									on_border = true;
222 									break;
223 								}
224 							}
225 
226 							if (on_border)
227 								break;
228 						}
229 
230 						if (on_border) {
231 							valid_positions.write[vpc] = Point2(i, j);
232 
233 							if (emode == EMISSION_MODE_BORDER_DIRECTED) {
234 								Vector2 normal;
235 								for (int x = i - 2; x <= i + 2; x++) {
236 									for (int y = j - 2; y <= j + 2; y++) {
237 
238 										if (x == i && y == j)
239 											continue;
240 
241 										if (x < 0 || y < 0 || x >= s.width || y >= s.height || r[(y * s.width + x) * 4 + 3] <= 128) {
242 											normal += Vector2(x - i, y - j).normalized();
243 										}
244 									}
245 								}
246 
247 								normal.normalize();
248 								valid_normals.write[vpc] = normal;
249 							}
250 
251 							if (capture_colors) {
252 								valid_colors.write[vpc * 4 + 0] = r[(j * s.width + i) * 4 + 0];
253 								valid_colors.write[vpc * 4 + 1] = r[(j * s.width + i) * 4 + 1];
254 								valid_colors.write[vpc * 4 + 2] = r[(j * s.width + i) * 4 + 2];
255 								valid_colors.write[vpc * 4 + 3] = r[(j * s.width + i) * 4 + 3];
256 							}
257 
258 							vpc++;
259 						}
260 					}
261 				}
262 			}
263 		}
264 	}
265 
266 	valid_positions.resize(vpc);
267 	if (valid_normals.size()) {
268 		valid_normals.resize(vpc);
269 	}
270 
271 	ERR_FAIL_COND_MSG(valid_positions.size() == 0, "No pixels with transparency > 128 in image...");
272 
273 	PoolVector<uint8_t> texdata;
274 
275 	int w = 2048;
276 	int h = (vpc / 2048) + 1;
277 
278 	texdata.resize(w * h * 2 * sizeof(float));
279 
280 	{
281 		PoolVector<uint8_t>::Write tw = texdata.write();
282 		float *twf = (float *)tw.ptr();
283 		for (int i = 0; i < vpc; i++) {
284 
285 			twf[i * 2 + 0] = valid_positions[i].x;
286 			twf[i * 2 + 1] = valid_positions[i].y;
287 		}
288 	}
289 
290 	img.instance();
291 	img->create(w, h, false, Image::FORMAT_RGF, texdata);
292 
293 	Ref<ImageTexture> imgt;
294 	imgt.instance();
295 	imgt->create_from_image(img, 0);
296 
297 	pm->set_emission_point_texture(imgt);
298 	pm->set_emission_point_count(vpc);
299 
300 	if (capture_colors) {
301 
302 		PoolVector<uint8_t> colordata;
303 		colordata.resize(w * h * 4); //use RG texture
304 
305 		{
306 			PoolVector<uint8_t>::Write tw = colordata.write();
307 			for (int i = 0; i < vpc * 4; i++) {
308 
309 				tw[i] = valid_colors[i];
310 			}
311 		}
312 
313 		img.instance();
314 		img->create(w, h, false, Image::FORMAT_RGBA8, colordata);
315 
316 		imgt.instance();
317 		imgt->create_from_image(img, 0);
318 		pm->set_emission_color_texture(imgt);
319 	}
320 
321 	if (valid_normals.size()) {
322 		pm->set_emission_shape(ParticlesMaterial::EMISSION_SHAPE_DIRECTED_POINTS);
323 
324 		PoolVector<uint8_t> normdata;
325 		normdata.resize(w * h * 2 * sizeof(float)); //use RG texture
326 
327 		{
328 			PoolVector<uint8_t>::Write tw = normdata.write();
329 			float *twf = (float *)tw.ptr();
330 			for (int i = 0; i < vpc; i++) {
331 				twf[i * 2 + 0] = valid_normals[i].x;
332 				twf[i * 2 + 1] = valid_normals[i].y;
333 			}
334 		}
335 
336 		img.instance();
337 		img->create(w, h, false, Image::FORMAT_RGF, normdata);
338 
339 		imgt.instance();
340 		imgt->create_from_image(img, 0);
341 		pm->set_emission_normal_texture(imgt);
342 
343 	} else {
344 		pm->set_emission_shape(ParticlesMaterial::EMISSION_SHAPE_POINTS);
345 	}
346 }
347 
_notification(int p_what)348 void Particles2DEditorPlugin::_notification(int p_what) {
349 
350 	if (p_what == NOTIFICATION_ENTER_TREE) {
351 
352 		menu->get_popup()->connect("id_pressed", this, "_menu_callback");
353 		menu->set_icon(menu->get_popup()->get_icon("Particles2D", "EditorIcons"));
354 		file->connect("file_selected", this, "_file_selected");
355 	}
356 }
357 
_bind_methods()358 void Particles2DEditorPlugin::_bind_methods() {
359 
360 	ClassDB::bind_method(D_METHOD("_menu_callback"), &Particles2DEditorPlugin::_menu_callback);
361 	ClassDB::bind_method(D_METHOD("_file_selected"), &Particles2DEditorPlugin::_file_selected);
362 	ClassDB::bind_method(D_METHOD("_generate_visibility_rect"), &Particles2DEditorPlugin::_generate_visibility_rect);
363 	ClassDB::bind_method(D_METHOD("_generate_emission_mask"), &Particles2DEditorPlugin::_generate_emission_mask);
364 }
365 
Particles2DEditorPlugin(EditorNode * p_node)366 Particles2DEditorPlugin::Particles2DEditorPlugin(EditorNode *p_node) {
367 
368 	particles = NULL;
369 	editor = p_node;
370 	undo_redo = editor->get_undo_redo();
371 
372 	toolbar = memnew(HBoxContainer);
373 	add_control_to_container(CONTAINER_CANVAS_EDITOR_MENU, toolbar);
374 	toolbar->hide();
375 
376 	toolbar->add_child(memnew(VSeparator));
377 
378 	menu = memnew(MenuButton);
379 	menu->get_popup()->add_item(TTR("Generate Visibility Rect"), MENU_GENERATE_VISIBILITY_RECT);
380 	menu->get_popup()->add_separator();
381 	menu->get_popup()->add_item(TTR("Load Emission Mask"), MENU_LOAD_EMISSION_MASK);
382 	//	menu->get_popup()->add_item(TTR("Clear Emission Mask"), MENU_CLEAR_EMISSION_MASK);
383 	menu->get_popup()->add_separator();
384 	menu->get_popup()->add_item(TTR("Convert to CPUParticles"), MENU_OPTION_CONVERT_TO_CPU_PARTICLES);
385 	menu->get_popup()->add_separator();
386 	menu->get_popup()->add_item(TTR("Restart"), MENU_RESTART);
387 	menu->set_text(TTR("Particles"));
388 	menu->set_switch_on_hover(true);
389 	toolbar->add_child(menu);
390 
391 	file = memnew(EditorFileDialog);
392 	List<String> ext;
393 	ImageLoader::get_recognized_extensions(&ext);
394 	for (List<String>::Element *E = ext.front(); E; E = E->next()) {
395 		file->add_filter("*." + E->get() + "; " + E->get().to_upper());
396 	}
397 	file->set_mode(EditorFileDialog::MODE_OPEN_FILE);
398 	toolbar->add_child(file);
399 
400 	epoints = memnew(SpinBox);
401 	epoints->set_min(1);
402 	epoints->set_max(8192);
403 	epoints->set_step(1);
404 	epoints->set_value(512);
405 	file->get_vbox()->add_margin_child(TTR("Generated Point Count:"), epoints);
406 
407 	generate_visibility_rect = memnew(ConfirmationDialog);
408 	generate_visibility_rect->set_title(TTR("Generate Visibility Rect"));
409 	VBoxContainer *genvb = memnew(VBoxContainer);
410 	generate_visibility_rect->add_child(genvb);
411 	generate_seconds = memnew(SpinBox);
412 	genvb->add_margin_child(TTR("Generation Time (sec):"), generate_seconds);
413 	generate_seconds->set_min(0.1);
414 	generate_seconds->set_max(25);
415 	generate_seconds->set_value(2);
416 
417 	toolbar->add_child(generate_visibility_rect);
418 
419 	generate_visibility_rect->connect("confirmed", this, "_generate_visibility_rect");
420 
421 	emission_mask = memnew(ConfirmationDialog);
422 	emission_mask->set_title(TTR("Load Emission Mask"));
423 	VBoxContainer *emvb = memnew(VBoxContainer);
424 	emission_mask->add_child(emvb);
425 	emission_mask_mode = memnew(OptionButton);
426 	emvb->add_margin_child(TTR("Emission Mask"), emission_mask_mode);
427 	emission_mask_mode->add_item(TTR("Solid Pixels"), EMISSION_MODE_SOLID);
428 	emission_mask_mode->add_item(TTR("Border Pixels"), EMISSION_MODE_BORDER);
429 	emission_mask_mode->add_item(TTR("Directed Border Pixels"), EMISSION_MODE_BORDER_DIRECTED);
430 	emission_colors = memnew(CheckBox);
431 	emission_colors->set_text(TTR("Capture from Pixel"));
432 	emvb->add_margin_child(TTR("Emission Colors"), emission_colors);
433 
434 	toolbar->add_child(emission_mask);
435 
436 	emission_mask->connect("confirmed", this, "_generate_emission_mask");
437 }
438 
~Particles2DEditorPlugin()439 Particles2DEditorPlugin::~Particles2DEditorPlugin() {
440 }
441