Path: blob/master/editor/shader/shader_create_dialog.cpp
9902 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 "editor/editor_node.h"34#include "editor/gui/editor_file_dialog.h"35#include "editor/gui/editor_validation_panel.h"36#include "editor/themes/editor_scale.h"37#include "scene/resources/shader_include.h"38#include "scene/resources/visual_shader.h"39#include "servers/rendering/shader_types.h"4041enum ShaderType {42SHADER_TYPE_TEXT,43SHADER_TYPE_VISUAL,44SHADER_TYPE_INC,45SHADER_TYPE_MAX,46};4748void ShaderCreateDialog::_notification(int p_what) {49switch (p_what) {50case NOTIFICATION_ENTER_TREE: {51String last_lang = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_language", "");52if (!last_lang.is_empty()) {53for (int i = 0; i < type_menu->get_item_count(); i++) {54if (type_menu->get_item_text(i) == last_lang) {55type_menu->select(i);56current_type = i;57break;58}59}60} else {61type_menu->select(default_type);62}6364current_mode = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_mode", 0);65mode_menu->select(current_mode);66} break;6768case NOTIFICATION_THEME_CHANGED: {69static const char *shader_types[3] = { "Shader", "VisualShader", "TextFile" };70for (int i = 0; i < 3; i++) {71Ref<Texture2D> icon = get_editor_theme_icon(shader_types[i]);72if (icon.is_valid()) {73type_menu->set_item_icon(i, icon);74}75}7677path_button->set_button_icon(get_editor_theme_icon(SNAME("Folder")));78} break;79}80}8182void ShaderCreateDialog::_update_language_info() {83type_data.clear();8485for (int i = 0; i < SHADER_TYPE_MAX; i++) {86ShaderTypeData shader_type_data;87if (i == int(SHADER_TYPE_TEXT)) {88shader_type_data.use_templates = true;89shader_type_data.extensions.push_back("gdshader");90shader_type_data.default_extension = "gdshader";91} else if (i == int(SHADER_TYPE_INC)) {92shader_type_data.extensions.push_back("gdshaderinc");93shader_type_data.default_extension = "gdshaderinc";94} else {95shader_type_data.default_extension = "tres";96}97shader_type_data.extensions.push_back("res");98shader_type_data.extensions.push_back("tres");99type_data.push_back(shader_type_data);100}101}102103void ShaderCreateDialog::_path_hbox_sorted() {104if (is_visible()) {105int filename_start_pos = initial_base_path.rfind_char('/') + 1;106int filename_end_pos = initial_base_path.length();107108if (!is_built_in) {109file_path->select(filename_start_pos, filename_end_pos);110}111112file_path->set_caret_column(file_path->get_text().length());113file_path->set_caret_column(filename_start_pos);114115file_path->grab_focus();116}117}118119void ShaderCreateDialog::_mode_changed(int p_mode) {120current_mode = p_mode;121EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_mode", p_mode);122}123124void ShaderCreateDialog::_template_changed(int p_template) {125current_template = p_template;126EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_template", p_template);127}128129void ShaderCreateDialog::ok_pressed() {130if (is_new_shader_created) {131_create_new();132if (built_in_enabled) {133// Only save state of built-in checkbox if it's enabled.134EditorSettings::get_singleton()->set_project_metadata("shader_setup", "create_built_in_shader", internal->is_pressed());135}136} else {137_load_exist();138}139140is_new_shader_created = true;141validation_panel->update();142}143144void ShaderCreateDialog::_create_new() {145Ref<Resource> shader;146Ref<Resource> shader_inc;147148switch (type_menu->get_selected()) {149case SHADER_TYPE_TEXT: {150Ref<Shader> text_shader;151text_shader.instantiate();152shader = text_shader;153154StringBuilder code;155code += vformat("shader_type %s;\n", mode_menu->get_text().to_snake_case());156157if (current_template == 0) { // Default template.158switch (current_mode) {159case Shader::MODE_SPATIAL:160code += R"(161void vertex() {162// Called for every vertex the material is visible on.163}164165void fragment() {166// Called for every pixel the material is visible on.167}168169//void light() {170// // Called for every pixel for every light affecting the material.171// // Uncomment to replace the default light processing function with this one.172//}173)";174break;175case Shader::MODE_CANVAS_ITEM:176code += R"(177void vertex() {178// Called for every vertex the material is visible on.179}180181void fragment() {182// Called for every pixel the material is visible on.183}184185//void light() {186// // Called for every pixel for every light affecting the CanvasItem.187// // Uncomment to replace the default light processing function with this one.188//}189)";190break;191case Shader::MODE_PARTICLES:192code += R"(193void start() {194// Called when a particle is spawned.195}196197void process() {198// Called every frame on existing particles (according to the Fixed FPS property).199}200)";201break;202case Shader::MODE_SKY:203code += R"(204void sky() {205// Called for every visible pixel in the sky background, as well as all pixels206// in the radiance cubemap.207}208)";209break;210case Shader::MODE_FOG:211code += R"(212void fog() {213// Called once for every froxel that is touched by an axis-aligned bounding box214// of the associated FogVolume. This means that froxels that just barely touch215// a given FogVolume will still be used.216}217)";218}219}220text_shader->set_code(code.as_string());221} break;222case SHADER_TYPE_VISUAL: {223Ref<VisualShader> visual_shader;224visual_shader.instantiate();225shader = visual_shader;226visual_shader->set_mode(Shader::Mode(current_mode));227} break;228case SHADER_TYPE_INC: {229Ref<ShaderInclude> include;230include.instantiate();231shader_inc = include;232} break;233default: {234} break;235}236237if (shader.is_null()) {238String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());239shader_inc->set_path(lpath);240241Error error = ResourceSaver::save(shader_inc, lpath, ResourceSaver::FLAG_CHANGE_PATH);242if (error != OK) {243alert->set_text(TTR("Error - Could not create shader include in filesystem."));244alert->popup_centered();245return;246}247248emit_signal(SNAME("shader_include_created"), shader_inc);249} else {250if (is_built_in) {251Node *edited_scene = get_tree()->get_edited_scene_root();252if (likely(edited_scene)) {253shader->set_path(edited_scene->get_scene_file_path() + "::" + shader->generate_scene_unique_id());254}255} else {256String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());257shader->set_path(lpath);258259Error error = ResourceSaver::save(shader, lpath, ResourceSaver::FLAG_CHANGE_PATH);260if (error != OK) {261alert->set_text(TTR("Error - Could not create shader in filesystem."));262alert->popup_centered();263return;264}265}266267emit_signal(SNAME("shader_created"), shader);268}269270file_path->set_text(file_path->get_text().get_base_dir());271hide();272}273274void ShaderCreateDialog::_load_exist() {275String path = file_path->get_text();276Ref<Resource> p_shader = ResourceLoader::load(path, "Shader");277if (p_shader.is_null()) {278alert->set_text(vformat(TTR("Error loading shader from %s"), path));279alert->popup_centered();280return;281}282283emit_signal(SNAME("shader_created"), p_shader);284hide();285}286287void ShaderCreateDialog::_type_changed(int p_language) {288current_type = p_language;289ShaderTypeData shader_type_data = type_data.get(p_language);290291String selected_ext = "." + shader_type_data.default_extension;292String path = file_path->get_text();293String extension = "";294295if (!path.is_empty()) {296if (path.contains_char('.')) {297extension = path.get_extension();298}299if (extension.length() == 0) {300path += selected_ext;301} else {302path = path.get_basename() + selected_ext;303}304} else {305path = "shader" + selected_ext;306}307_path_changed(path);308file_path->set_text(path);309310type_menu->set_item_disabled(int(SHADER_TYPE_INC), load_enabled);311mode_menu->set_disabled(p_language == SHADER_TYPE_INC);312template_menu->set_disabled(!shader_type_data.use_templates);313template_menu->clear();314315if (shader_type_data.use_templates) {316int last_template = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_template", 0);317318template_menu->add_item(TTRC("Default"));319template_menu->add_item(TTRC("Empty"));320321template_menu->select(last_template);322current_template = last_template;323} else {324template_menu->add_item(TTRC("N/A"));325}326327EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_language", type_menu->get_item_text(type_menu->get_selected()));328validation_panel->update();329}330331void ShaderCreateDialog::_built_in_toggled(bool p_enabled) {332is_built_in = p_enabled;333if (p_enabled) {334is_new_shader_created = true;335} else {336_path_changed(file_path->get_text());337}338validation_panel->update();339}340341void ShaderCreateDialog::_browse_path() {342file_browse->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);343file_browse->set_title(TTR("Open Shader / Choose Location"));344file_browse->set_ok_button_text(TTR("Open"));345346file_browse->set_disable_overwrite_warning(true);347file_browse->clear_filters();348349List<String> extensions = type_data.get(type_menu->get_selected()).extensions;350351for (const String &E : extensions) {352file_browse->add_filter("*." + E);353}354355file_browse->set_current_path(file_path->get_text());356file_browse->popup_file_dialog();357}358359void ShaderCreateDialog::_file_selected(const String &p_file) {360String p = ProjectSettings::get_singleton()->localize_path(p_file);361file_path->set_text(p);362_path_changed(p);363364String filename = p.get_file().get_basename();365int select_start = p.rfind(filename);366file_path->select(select_start, select_start + filename.length());367file_path->set_caret_column(select_start + filename.length());368file_path->grab_focus();369}370371void ShaderCreateDialog::_path_changed(const String &p_path) {372if (is_built_in) {373return;374}375376is_path_valid = false;377is_new_shader_created = true;378379path_error = _validate_path(p_path);380if (!path_error.is_empty()) {381validation_panel->update();382return;383}384385Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES);386String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges());387if (f->file_exists(p)) {388is_new_shader_created = false;389}390391is_path_valid = true;392validation_panel->update();393}394395void ShaderCreateDialog::_path_submitted(const String &p_path) {396if (!get_ok_button()->is_disabled()) {397ok_pressed();398}399}400401void ShaderCreateDialog::config(const String &p_base_path, bool p_built_in_enabled, bool p_load_enabled, int p_preferred_type, int p_preferred_mode) {402if (!p_base_path.is_empty()) {403initial_base_path = p_base_path.get_basename();404file_path->set_text(initial_base_path + "." + type_data.get(type_menu->get_selected()).default_extension);405current_type = type_menu->get_selected();406} else {407initial_base_path = "";408file_path->set_text("");409}410file_path->deselect();411412built_in_enabled = p_built_in_enabled;413load_enabled = p_load_enabled;414415if (built_in_enabled) {416internal->set_pressed(EditorSettings::get_singleton()->get_project_metadata("shader_setup", "create_built_in_shader", false));417}418419if (p_preferred_type > -1) {420type_menu->select(p_preferred_type);421_type_changed(p_preferred_type);422}423424if (p_preferred_mode > -1) {425mode_menu->select(p_preferred_mode);426_mode_changed(p_preferred_mode);427}428429_type_changed(current_type);430_path_changed(file_path->get_text());431}432433String ShaderCreateDialog::_validate_path(const String &p_path) {434String p = p_path.strip_edges();435436if (p.is_empty()) {437return TTR("Path is empty.");438}439if (p.get_file().get_basename().is_empty()) {440return TTR("Filename is empty.");441}442443p = ProjectSettings::get_singleton()->localize_path(p);444if (!p.begins_with("res://")) {445return TTR("Path is not local.");446}447448Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);449if (d->change_dir(p.get_base_dir()) != OK) {450return TTR("Invalid base path.");451}452453Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES);454if (f->dir_exists(p)) {455return TTR("A directory with the same name exists.");456}457458String extension = p.get_extension();459HashSet<String> extensions;460461List<ShaderCreateDialog::ShaderTypeData>::ConstIterator itr = type_data.begin();462for (int i = 0; i < SHADER_TYPE_MAX; ++itr, ++i) {463for (const String &ext : itr->extensions) {464if (!extensions.has(ext)) {465extensions.insert(ext);466}467}468}469470bool found = false;471bool match = false;472473for (const String &ext : extensions) {474if (ext.nocasecmp_to(extension) == 0) {475found = true;476for (const String &type_ext : type_data.get(current_type).extensions) {477if (type_ext.nocasecmp_to(extension) == 0) {478match = true;479break;480}481}482break;483}484}485486if (!found) {487return TTR("Invalid extension.");488}489if (!match) {490return TTR("Wrong extension chosen.");491}492493return "";494}495496void ShaderCreateDialog::_update_dialog() {497if (!is_built_in && !is_path_valid) {498validation_panel->set_message(MSG_ID_SHADER, TTR("Invalid path."), EditorValidationPanel::MSG_ERROR);499}500if (!is_built_in && !path_error.is_empty()) {501validation_panel->set_message(MSG_ID_PATH, path_error, EditorValidationPanel::MSG_ERROR);502} else if (validation_panel->is_valid() && !is_new_shader_created) {503validation_panel->set_message(MSG_ID_SHADER, TTR("File exists, it will be reused."), EditorValidationPanel::MSG_OK);504}505if (!built_in_enabled) {506internal->set_pressed(false);507}508509if (is_built_in) {510file_path->set_editable(false);511path_button->set_disabled(true);512re_check_path = true;513} else {514file_path->set_editable(true);515path_button->set_disabled(false);516if (re_check_path) {517re_check_path = false;518_path_changed(file_path->get_text());519}520}521522internal->set_disabled(!built_in_enabled);523524if (is_built_in) {525validation_panel->set_message(MSG_ID_BUILT_IN, TTR("Note: Built-in shaders can't be edited using an external editor."), EditorValidationPanel::MSG_INFO, false);526}527528if (is_built_in) {529set_ok_button_text(TTR("Create"));530validation_panel->set_message(MSG_ID_PATH, TTR("Built-in shader (into scene file)."), EditorValidationPanel::MSG_OK);531} else if (is_new_shader_created) {532set_ok_button_text(TTR("Create"));533} else if (load_enabled) {534set_ok_button_text(TTR("Load"));535if (is_path_valid) {536validation_panel->set_message(MSG_ID_PATH, TTR("Will load an existing shader file."), EditorValidationPanel::MSG_OK);537}538} else {539set_ok_button_text(TTR("Create"));540validation_panel->set_message(MSG_ID_PATH, TTR("Shader file already exists."), EditorValidationPanel::MSG_ERROR);541}542}543544void ShaderCreateDialog::_bind_methods() {545ClassDB::bind_method(D_METHOD("config", "path", "built_in_enabled", "load_enabled"), &ShaderCreateDialog::config, DEFVAL(true), DEFVAL(true));546547ADD_SIGNAL(MethodInfo("shader_created", PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, "Shader")));548ADD_SIGNAL(MethodInfo("shader_include_created", PropertyInfo(Variant::OBJECT, "shader_include", PROPERTY_HINT_RESOURCE_TYPE, "ShaderInclude")));549}550551ShaderCreateDialog::ShaderCreateDialog() {552_update_language_info();553554// Main Controls.555556gc = memnew(GridContainer);557gc->set_columns(2);558559// Error Fields.560561validation_panel = memnew(EditorValidationPanel);562validation_panel->add_line(MSG_ID_SHADER, TTR("Shader path/name is valid."));563validation_panel->add_line(MSG_ID_PATH, TTR("Will create a new shader file."));564validation_panel->add_line(MSG_ID_BUILT_IN);565validation_panel->set_update_callback(callable_mp(this, &ShaderCreateDialog::_update_dialog));566validation_panel->set_accept_button(get_ok_button());567568// Spacing.569570Control *spacing = memnew(Control);571spacing->set_custom_minimum_size(Size2(0, 10 * EDSCALE));572573VBoxContainer *vb = memnew(VBoxContainer);574vb->add_child(gc);575vb->add_child(spacing);576vb->add_child(validation_panel);577add_child(vb);578579// Type.580581type_menu = memnew(OptionButton);582type_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);583type_menu->set_accessibility_name(TTRC("Type:"));584type_menu->set_custom_minimum_size(Size2(250, 0) * EDSCALE);585type_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);586gc->add_child(memnew(Label(TTR("Type:"))));587gc->add_child(type_menu);588589for (int i = 0; i < SHADER_TYPE_MAX; i++) {590String type;591bool invalid = false;592switch (i) {593case SHADER_TYPE_TEXT:594type = "Shader";595default_type = i;596break;597case SHADER_TYPE_VISUAL:598type = "VisualShader";599break;600case SHADER_TYPE_INC:601type = "ShaderInclude";602break;603case SHADER_TYPE_MAX:604invalid = true;605break;606default:607invalid = true;608break;609}610if (invalid) {611continue;612}613type_menu->add_item(type);614}615if (default_type >= 0) {616type_menu->select(default_type);617}618current_type = default_type;619type_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_type_changed));620621// Modes.622623mode_menu = memnew(OptionButton);624mode_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);625mode_menu->set_accessibility_name(TTRC("Mode:"));626for (const String &type_name : ShaderTypes::get_singleton()->get_types_list()) {627mode_menu->add_item(type_name.capitalize());628}629gc->add_child(memnew(Label(TTR("Mode:"))));630gc->add_child(mode_menu);631mode_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_mode_changed));632633// Templates.634635template_menu = memnew(OptionButton);636template_menu->set_accessibility_name(TTRC("Template:"));637gc->add_child(memnew(Label(TTR("Template:"))));638gc->add_child(template_menu);639template_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_template_changed));640641// Built-in Shader.642643internal = memnew(CheckBox);644internal->set_text(TTR("On"));645internal->set_accessibility_name(TTRC("Built-in Shader:"));646internal->connect(SceneStringName(toggled), callable_mp(this, &ShaderCreateDialog::_built_in_toggled));647gc->add_child(memnew(Label(TTR("Built-in Shader:"))));648gc->add_child(internal);649650// Path.651652HBoxContainer *hb = memnew(HBoxContainer);653hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);654hb->connect(SceneStringName(sort_children), callable_mp(this, &ShaderCreateDialog::_path_hbox_sorted));655file_path = memnew(LineEdit);656file_path->connect(SceneStringName(text_changed), callable_mp(this, &ShaderCreateDialog::_path_changed));657file_path->set_accessibility_name(TTRC("Path:"));658file_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);659hb->add_child(file_path);660register_text_enter(file_path);661path_button = memnew(Button);662path_button->set_accessibility_name(TTRC("Select"));663path_button->connect(SceneStringName(pressed), callable_mp(this, &ShaderCreateDialog::_browse_path));664hb->add_child(path_button);665gc->add_child(memnew(Label(TTR("Path:"))));666gc->add_child(hb);667668// Dialog Setup.669670file_browse = memnew(EditorFileDialog);671file_browse->connect("file_selected", callable_mp(this, &ShaderCreateDialog::_file_selected));672file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);673add_child(file_browse);674675alert = memnew(AcceptDialog);676alert->get_label()->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);677alert->get_label()->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);678alert->get_label()->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);679alert->get_label()->set_custom_minimum_size(Size2(325, 60) * EDSCALE);680add_child(alert);681682set_ok_button_text(TTR("Create"));683set_hide_on_ok(false);684685set_title(TTR("Create Shader"));686}687688689