Path: blob/master/editor/shader/shader_create_dialog.cpp
20934 views
/**************************************************************************/1/* shader_create_dialog.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "shader_create_dialog.h"3132#include "core/config/project_settings.h"33#include "core/io/dir_access.h"34#include "editor/editor_node.h"35#include "editor/gui/editor_file_dialog.h"36#include "editor/gui/editor_validation_panel.h"37#include "editor/shader/editor_shader_language_plugin.h"38#include "editor/themes/editor_scale.h"39#include "scene/resources/shader_include.h"40#include "servers/rendering/shader_types.h"4142void ShaderCreateDialog::_notification(int p_what) {43switch (p_what) {44case NOTIFICATION_ENTER_TREE: {45current_mode = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_mode", 0);46mode_menu->select(current_mode);47} break;4849case NOTIFICATION_THEME_CHANGED: {50path_button->set_button_icon(get_editor_theme_icon(SNAME("Folder")));51// Note that some of the theme logic happens in `config()` when opening the dialog.52} break;53}54}5556void ShaderCreateDialog::_refresh_type_icons() {57for (int i = 0; i < type_menu->get_item_count(); i++) {58const String item_name = type_menu->get_item_text(i);59Ref<Texture2D> icon = get_editor_theme_icon(item_name);60if (icon.is_valid()) {61type_menu->set_item_icon(i, icon);62} else {63icon = get_editor_theme_icon("TextFile");64if (icon.is_valid()) {65type_menu->set_item_icon(i, icon);66}67}68}69}7071void ShaderCreateDialog::_update_language_info() {72type_data.clear();7374for (int i = 0; i < EditorShaderLanguagePlugin::get_shader_language_variation_count(); i++) {75ShaderTypeData shader_type_data;76if (i == 0) {77// HACK: The ShaderCreateDialog class currently only shows templates for text shaders. Generalize this later.78shader_type_data.use_templates = true;79}80shader_type_data.default_extension = EditorShaderLanguagePlugin::get_file_extension_for_index(i);81shader_type_data.extensions.push_back(shader_type_data.default_extension);82if (shader_type_data.default_extension != "tres") {83shader_type_data.extensions.push_back("tres");84}85shader_type_data.extensions.push_back("res");86type_data.push_back(shader_type_data);87}88}8990void ShaderCreateDialog::_path_hbox_sorted() {91if (is_visible()) {92int filename_start_pos = initial_base_path.rfind_char('/') + 1;93int filename_end_pos = initial_base_path.length();9495if (!is_built_in) {96file_path->select(filename_start_pos, filename_end_pos);97}9899file_path->set_caret_column(file_path->get_text().length());100file_path->set_caret_column(filename_start_pos);101102file_path->grab_focus();103}104}105106void ShaderCreateDialog::_mode_changed(int p_mode) {107current_mode = p_mode;108EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_mode", p_mode);109}110111void ShaderCreateDialog::_template_changed(int p_template) {112current_template = p_template;113EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_template", p_template);114}115116void ShaderCreateDialog::ok_pressed() {117if (is_new_shader_created) {118_create_new();119if (built_in_enabled) {120// Only save state of built-in checkbox if it's enabled.121EditorSettings::get_singleton()->set_project_metadata("shader_setup", "create_built_in_shader", internal->is_pressed());122}123} else {124_load_exist();125}126127is_new_shader_created = true;128validation_panel->update();129}130131void ShaderCreateDialog::_create_new() {132Ref<Resource> shader;133Ref<Resource> shader_inc;134135const int type_index = type_menu->get_selected();136Ref<EditorShaderLanguagePlugin> shader_lang = EditorShaderLanguagePlugin::get_shader_language_for_index(type_index);137// A bit of an unfortunate hack because Shader and ShaderInclude do not share a common base class.138// We need duplicate code paths for includes vs non-includes, so just check for the string "Include".139if (type_menu->get_item_text(type_index).contains("Include")) {140shader_inc = shader_lang->create_new_shader_include();141} else {142shader = shader_lang->create_new_shader(0, Shader::Mode(current_mode), current_template);143}144145if (shader.is_null()) {146String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());147shader_inc->set_path(lpath);148149Error error = ResourceSaver::save(shader_inc, lpath, ResourceSaver::FLAG_CHANGE_PATH);150if (error != OK) {151alert->set_text(TTR("Error - Could not create shader include in filesystem."));152alert->popup_centered();153return;154}155156emit_signal(SNAME("shader_include_created"), shader_inc);157} else {158if (is_built_in) {159Node *edited_scene = get_tree()->get_edited_scene_root();160if (likely(edited_scene)) {161shader->set_path(edited_scene->get_scene_file_path() + "::" + shader->generate_scene_unique_id());162}163} else {164String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());165shader->set_path(lpath);166167Error error = ResourceSaver::save(shader, lpath, ResourceSaver::FLAG_CHANGE_PATH);168if (error != OK) {169alert->set_text(TTR("Error - Could not create shader in filesystem."));170alert->popup_centered();171return;172}173}174175emit_signal(SNAME("shader_created"), shader);176}177178file_path->set_text(file_path->get_text().get_base_dir());179hide();180}181182void ShaderCreateDialog::_load_exist() {183String path = file_path->get_text();184Ref<Resource> p_shader = ResourceLoader::load(path, "Shader");185if (p_shader.is_null()) {186alert->set_text(vformat(TTR("Error loading shader from %s"), path));187alert->popup_centered();188return;189}190191emit_signal(SNAME("shader_created"), p_shader);192hide();193}194195void ShaderCreateDialog::_type_changed(int p_language) {196current_type = p_language;197ShaderTypeData shader_type_data = type_data.get(p_language);198199String selected_ext = "." + shader_type_data.default_extension;200String path = file_path->get_text();201String extension = "";202203if (!path.is_empty()) {204if (path.contains_char('.')) {205extension = path.get_extension();206}207if (extension.length() == 0) {208path += selected_ext;209} else {210path = path.get_basename() + selected_ext;211}212} else {213path = "shader" + selected_ext;214}215_path_changed(path);216file_path->set_text(path);217218mode_menu->set_disabled(false);219for (int i = 0; i < type_menu->get_item_count(); i++) {220const String item_name = type_menu->get_item_text(i);221if (item_name.contains("Include")) {222type_menu->set_item_disabled(i, load_enabled);223if (i == p_language) {224mode_menu->set_disabled(true);225}226} else {227type_menu->set_item_disabled(i, false);228}229}230template_menu->set_disabled(!shader_type_data.use_templates);231template_menu->clear();232233if (shader_type_data.use_templates) {234int last_template = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_template", 0);235236template_menu->add_item(TTRC("Default"));237template_menu->add_item(TTRC("Empty"));238239template_menu->select(last_template);240current_template = last_template;241} else {242template_menu->add_item(TTRC("N/A"));243}244245EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_language", type_menu->get_item_text(type_menu->get_selected()));246validation_panel->update();247}248249void ShaderCreateDialog::_built_in_toggled(bool p_enabled) {250is_built_in = p_enabled;251if (p_enabled) {252is_new_shader_created = true;253} else {254_path_changed(file_path->get_text());255}256validation_panel->update();257}258259void ShaderCreateDialog::_browse_path() {260file_browse->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);261file_browse->set_title(TTR("Open Shader / Choose Location"));262file_browse->set_ok_button_text(TTR("Open"));263264file_browse->set_customization_flag_enabled(FileDialog::CUSTOMIZATION_OVERWRITE_WARNING, false);265file_browse->clear_filters();266267List<String> extensions = type_data.get(type_menu->get_selected()).extensions;268269for (const String &E : extensions) {270file_browse->add_filter("*." + E);271}272273file_browse->set_current_path(file_path->get_text());274file_browse->popup_file_dialog();275}276277void ShaderCreateDialog::_file_selected(const String &p_file) {278String p = ProjectSettings::get_singleton()->localize_path(p_file);279file_path->set_text(p);280_path_changed(p);281282String filename = p.get_file().get_basename();283int select_start = p.rfind(filename);284file_path->select(select_start, select_start + filename.length());285file_path->set_caret_column(select_start + filename.length());286file_path->grab_focus();287}288289void ShaderCreateDialog::_path_changed(const String &p_path) {290if (is_built_in) {291return;292}293294is_path_valid = false;295is_new_shader_created = true;296297path_error = _validate_path(p_path);298if (!path_error.is_empty()) {299validation_panel->update();300return;301}302303Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES);304String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges());305if (f->file_exists(p)) {306is_new_shader_created = false;307}308309is_path_valid = true;310validation_panel->update();311}312313void ShaderCreateDialog::_path_submitted(const String &p_path) {314if (!get_ok_button()->is_disabled()) {315ok_pressed();316}317}318319void ShaderCreateDialog::config(const String &p_base_path, bool p_built_in_enabled, bool p_load_enabled, const String &p_preferred_type, int p_preferred_mode) {320_update_language_info();321type_menu->clear();322const Vector<Ref<EditorShaderLanguagePlugin>> shader_langs = EditorShaderLanguagePlugin::get_shader_languages_read_only();323ERR_FAIL_COND_MSG(shader_langs.is_empty(), "ShaderCreateDialog: Unable to load any shader languages!");324for (Ref<EditorShaderLanguagePlugin> shader_lang : shader_langs) {325const PackedStringArray variations = shader_lang->get_language_variations();326for (const String &variation : variations) {327type_menu->add_item(variation);328}329}330_refresh_type_icons();331332int preferred_type = -1;333// Select preferred type if specified.334for (int i = 0; i < type_menu->get_item_count(); i++) {335if (type_menu->get_item_text(i) == p_preferred_type) {336preferred_type = i;337break;338}339}340if (preferred_type < 0 || preferred_type >= type_menu->get_item_count()) {341preferred_type = 0;342// Select the last selected language if possible, otherwise default to the first language.343String last_lang = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_language", "");344if (!last_lang.is_empty()) {345for (int i = 0; i < type_menu->get_item_count(); i++) {346if (type_menu->get_item_text(i) == last_lang) {347preferred_type = i;348break;349}350}351}352}353type_menu->select(preferred_type);354current_type = 0;355356if (!p_base_path.is_empty()) {357initial_base_path = p_base_path.get_basename();358file_path->set_text(initial_base_path + "." + type_data.get(type_menu->get_selected()).default_extension);359current_type = type_menu->get_selected();360} else {361initial_base_path = "";362file_path->set_text("");363}364file_path->deselect();365366built_in_enabled = p_built_in_enabled;367load_enabled = p_load_enabled;368369if (built_in_enabled) {370internal->set_pressed(EditorSettings::get_singleton()->get_project_metadata("shader_setup", "create_built_in_shader", false));371}372373if (p_preferred_mode > -1) {374mode_menu->select(p_preferred_mode);375_mode_changed(p_preferred_mode);376}377378_type_changed(current_type);379_path_changed(file_path->get_text());380}381382String ShaderCreateDialog::_validate_path(const String &p_path) {383ERR_FAIL_COND_V(current_type >= type_data.size(), TTR("Invalid shader type selected."));384String stripped_file_path = p_path.strip_edges();385386if (stripped_file_path.is_empty()) {387return TTR("Path is empty.");388}389if (stripped_file_path.get_file().get_basename().is_empty()) {390return TTR("Filename is empty.");391}392393stripped_file_path = ProjectSettings::get_singleton()->localize_path(stripped_file_path);394if (!stripped_file_path.begins_with("res://")) {395return TTR("Path is not local.");396}397398Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);399if (d->change_dir(stripped_file_path.get_base_dir()) != OK) {400return TTR("Invalid base path.");401}402403Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES);404if (f->dir_exists(stripped_file_path)) {405return TTR("A directory with the same name exists.");406}407408const ShaderCreateDialog::ShaderTypeData ¤t_type_data = type_data.get(current_type);409const String file_extension = stripped_file_path.get_extension();410411for (const String &type_ext : current_type_data.extensions) {412if (type_ext.nocasecmp_to(file_extension) == 0) {413return "";414}415}416417return TTR("Invalid extension for selected shader type.");418}419420void ShaderCreateDialog::_update_dialog() {421if (!is_built_in && !is_path_valid) {422validation_panel->set_message(MSG_ID_SHADER, TTR("Invalid path."), EditorValidationPanel::MSG_ERROR);423}424if (!is_built_in && !path_error.is_empty()) {425validation_panel->set_message(MSG_ID_PATH, path_error, EditorValidationPanel::MSG_ERROR);426} else if (validation_panel->is_valid() && !is_new_shader_created) {427validation_panel->set_message(MSG_ID_SHADER, TTR("File exists, it will be reused."), EditorValidationPanel::MSG_OK);428}429if (!built_in_enabled) {430internal->set_pressed(false);431}432433if (is_built_in) {434file_path->set_editable(false);435path_button->set_disabled(true);436re_check_path = true;437} else {438file_path->set_editable(true);439path_button->set_disabled(false);440if (re_check_path) {441re_check_path = false;442_path_changed(file_path->get_text());443}444}445446internal->set_disabled(!built_in_enabled);447448if (is_built_in) {449validation_panel->set_message(MSG_ID_BUILT_IN, TTR("Note: Built-in shaders can't be edited using an external editor."), EditorValidationPanel::MSG_INFO, false);450}451452if (is_built_in) {453set_ok_button_text(TTR("Create"));454validation_panel->set_message(MSG_ID_PATH, TTR("Built-in shader (into scene file)."), EditorValidationPanel::MSG_OK);455} else if (is_new_shader_created) {456set_ok_button_text(TTR("Create"));457} else if (load_enabled) {458set_ok_button_text(TTR("Load"));459if (is_path_valid) {460validation_panel->set_message(MSG_ID_PATH, TTR("Will load an existing shader file."), EditorValidationPanel::MSG_OK);461}462} else {463set_ok_button_text(TTR("Create"));464validation_panel->set_message(MSG_ID_PATH, TTR("Shader file already exists."), EditorValidationPanel::MSG_ERROR);465}466}467468void ShaderCreateDialog::_bind_methods() {469ClassDB::bind_method(D_METHOD("config", "path", "built_in_enabled", "load_enabled"), &ShaderCreateDialog::config, DEFVAL(true), DEFVAL(true));470471ADD_SIGNAL(MethodInfo("shader_created", PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, Shader::get_class_static())));472ADD_SIGNAL(MethodInfo("shader_include_created", PropertyInfo(Variant::OBJECT, "shader_include", PROPERTY_HINT_RESOURCE_TYPE, ShaderInclude::get_class_static())));473}474475ShaderCreateDialog::ShaderCreateDialog() {476_update_language_info();477478// Main Controls.479480gc = memnew(GridContainer);481gc->set_columns(2);482483// Error Fields.484485validation_panel = memnew(EditorValidationPanel);486validation_panel->add_line(MSG_ID_SHADER, TTR("Shader path/name is valid."));487validation_panel->add_line(MSG_ID_PATH, TTR("Will create a new shader file."));488validation_panel->add_line(MSG_ID_BUILT_IN);489validation_panel->set_update_callback(callable_mp(this, &ShaderCreateDialog::_update_dialog));490validation_panel->set_accept_button(get_ok_button());491492// Spacing.493494Control *spacing = memnew(Control);495spacing->set_custom_minimum_size(Size2(0, 10 * EDSCALE));496497VBoxContainer *vb = memnew(VBoxContainer);498vb->add_child(gc);499vb->add_child(spacing);500vb->add_child(validation_panel);501add_child(vb);502503// Type.504505type_menu = memnew(OptionButton);506type_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);507type_menu->set_accessibility_name(TTRC("Type:"));508type_menu->set_custom_minimum_size(Size2(250, 0) * EDSCALE);509type_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);510gc->add_child(memnew(Label(TTR("Type:"))));511gc->add_child(type_menu);512513type_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_type_changed));514515// Modes.516517mode_menu = memnew(OptionButton);518mode_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);519mode_menu->set_accessibility_name(TTRC("Mode:"));520for (const String &type_name : ShaderTypes::get_singleton()->get_types_list()) {521mode_menu->add_item(type_name.capitalize());522}523gc->add_child(memnew(Label(TTR("Mode:"))));524gc->add_child(mode_menu);525mode_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_mode_changed));526527// Templates.528529template_menu = memnew(OptionButton);530template_menu->set_accessibility_name(TTRC("Template:"));531gc->add_child(memnew(Label(TTR("Template:"))));532gc->add_child(template_menu);533template_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_template_changed));534535// Built-in Shader.536537internal = memnew(CheckBox);538internal->set_text(TTR("On"));539internal->set_accessibility_name(TTRC("Built-in Shader:"));540internal->connect(SceneStringName(toggled), callable_mp(this, &ShaderCreateDialog::_built_in_toggled));541gc->add_child(memnew(Label(TTR("Built-in Shader:"))));542gc->add_child(internal);543544// Path.545546HBoxContainer *hb = memnew(HBoxContainer);547hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);548hb->connect(SceneStringName(sort_children), callable_mp(this, &ShaderCreateDialog::_path_hbox_sorted));549file_path = memnew(LineEdit);550file_path->connect(SceneStringName(text_changed), callable_mp(this, &ShaderCreateDialog::_path_changed));551file_path->set_accessibility_name(TTRC("Path:"));552file_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);553hb->add_child(file_path);554register_text_enter(file_path);555path_button = memnew(Button);556path_button->set_accessibility_name(TTRC("Select"));557path_button->connect(SceneStringName(pressed), callable_mp(this, &ShaderCreateDialog::_browse_path));558hb->add_child(path_button);559gc->add_child(memnew(Label(TTR("Path:"))));560gc->add_child(hb);561562// Dialog Setup.563564file_browse = memnew(EditorFileDialog);565file_browse->connect("file_selected", callable_mp(this, &ShaderCreateDialog::_file_selected));566file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);567add_child(file_browse);568569alert = memnew(AcceptDialog);570alert->get_label()->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);571alert->get_label()->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);572alert->get_label()->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);573alert->get_label()->set_custom_minimum_size(Size2(325, 60) * EDSCALE);574add_child(alert);575576set_ok_button_text(TTR("Create"));577set_hide_on_ok(false);578579set_title(TTR("Create Shader"));580}581582583