/*
 *  $Id: shade.c 30111 2026-06-22 11:02:00Z yeti-dn $
 *  Copyright (C) 2003-2022 David Necas (Yeti), Petr Klapetek.
 *  E-mail: yeti@gwyddion.net, klapetek@gwyddion.net.
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 *  License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any
 *  later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 *  warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 *  details.
 *
 *  You should have received a copy of the GNU General Public License along with this program; if not, write to the
 *  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include <glib/gi18n-lib.h>
#include <gtk/gtk.h>
#include <gwy.h>
#include "../preview.h"

#define RUN_MODES (GWY_RUN_IMMEDIATE | GWY_RUN_INTERACTIVE)

enum {
    PARAM_THETA,
    PARAM_PHI,
    PARAM_MIX,
    PARAM_DO_MIX,
};

typedef struct {
    GwyParams *params;
    GwyField *field;
    GwyField *result;
} ModuleArgs;

typedef struct {
    ModuleArgs *args;
    GtkWidget *dialog;
    GwyParamTable *table;
    GtkWidget *shader;
} ModuleGUI;

static gboolean         module_register     (void);
static GwyParamDef*     define_module_params(void);
static void             execute             (ModuleArgs *args);
static GwyDialogOutcome run_gui             (ModuleArgs *args,
                                             GwyFile *data,
                                             gint id);
static void             param_changed       (ModuleGUI *gui,
                                             gint id);
static void             preview             (gpointer user_data);
static void             module_main         (GwyFile *data,
                                             GwyRunModeFlags mode);
static void             shade_changed       (ModuleGUI *gui,
                                             GwyShader *shader);
static void             mix_with_plane      (GwyField *shaded,
                                             GwyField *plane,
                                             gdouble mixfraction);

static GwyModuleInfo module_info = {
    GWY_MODULE_ABI_VERSION,
    &module_register,
    N_("Creates a shaded presentation of data."),
    "Petr Klapetek <klapetek@gwyddion.net>",
    "3.0",
    "David Nečas (Yeti) & Petr Klapetek",
    "2003",
};

GWY_MODULE_QUERY2(module_info, shade)

static gboolean
module_register(void)
{
    gwy_image_func_register("shade",
                            module_main,
                            N_("/_Presentation/_Shading..."),
                            GWY_ICON_SHADER,
                            RUN_MODES,
                            GWY_MENU_FLAG_IMAGE,
                            N_("Shade data"));

    return TRUE;
}

static GwyParamDef*
define_module_params(void)
{
    static GwyParamDef *paramdef = NULL;

    if (paramdef)
        return paramdef;

    paramdef = gwy_param_def_new();
    gwy_param_def_set_function_name(paramdef, gwy_image_func_current());
    gwy_param_def_add_angle(paramdef, PARAM_THETA, "theta", _("θ"), TRUE, 4, 0.0);
    gwy_param_def_add_angle(paramdef, PARAM_PHI, "phi", _("φ"), TRUE, 1, 0.0);
    gwy_param_def_add_percentage(paramdef, PARAM_MIX, "mix", _("_Mix"), 0.0);
    gwy_param_def_add_boolean(paramdef, PARAM_DO_MIX, "do_mix", _("_Mix"), FALSE);
    return paramdef;
}

static void
module_main(GwyFile *data, GwyRunModeFlags mode)
{
    GwyDialogOutcome outcome = GWY_DIALOG_PROCEED;
    ModuleArgs args;
    gwy_clear1(args);
    GQuark squark;
    gint id;

    g_return_if_fail(mode & RUN_MODES);
    gwy_data_browser_get_current(GWY_APP_FIELD, &args.field,
                                 GWY_APP_FIELD_ID, &id,
                                 GWY_APP_SHOW_FIELD_KEY, &squark,
                                 0);
    g_return_if_fail(args.field && squark);

    args.params = gwy_params_new_from_settings(define_module_params());
    args.result = gwy_field_new_alike(args.field, TRUE);
    gwy_unit_clear(gwy_field_get_unit_z(args.result));

    if (mode == GWY_RUN_INTERACTIVE) {
        outcome = run_gui(&args, data, id);
        gwy_params_save_to_settings(args.params);
        if (outcome == GWY_DIALOG_CANCEL)
            goto end;
    }
    if (outcome != GWY_DIALOG_HAVE_RESULT)
        execute(&args);

    gwy_app_undo_qcheckpointv(GWY_DICT(data), 1, &squark);

    gwy_dict_set_object(GWY_DICT(data), gwy_file_key_image_picture(id), args.result);
    gwy_log_add(data, GWY_FILE_IMAGE, id, id);

end:
    g_object_unref(args.result);
    g_object_unref(args.params);
}

static GwyDialogOutcome
run_gui(ModuleArgs *args, GwyFile *data, gint id)
{
    GtkWidget *hbox, *vbox, *dataview;
    GwyParamTable *table;
    const gchar *gradient = NULL;
    ModuleGUI gui;
    GwyDialog *dialog;

    gui.args = args;

    gui.dialog = gwy_dialog_new(_("Shading"));
    dialog = GWY_DIALOG(gui.dialog);
    gwy_dialog_add_stock_buttons(dialog, GWY_STOCK_RESET, GWY_STOCK_CANCEL, GWY_STOCK_OK, 0);

    dataview = gwy_create_preview(args->result, NULL, PREVIEW_SIZE);
    gwy_setup_data_view(GWY_DATA_VIEW(dataview), data, GWY_FILE_IMAGE, id,
                        GWY_FILE_ITEM_PALETTE | GWY_FILE_ITEM_RANGE | GWY_FILE_ITEM_REAL_SQUARE);
    hbox = gwy_create_dialog_preview_hbox(GTK_DIALOG(dialog), GWY_DATA_VIEW(dataview), FALSE);

    vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);

    gui.shader = gwy_shader_new();
    gwy_set_widget_margins(gui.shader, 4, 4, 4, 4);
    gradient = gwy_file_get_palette(data, GWY_FILE_IMAGE, id);
    gwy_shader_set_gradient(GWY_SHADER(gui.shader), gwy_gradients_get_gradient(gradient));
    gwy_shader_set_angle(GWY_SHADER(gui.shader),
                         gwy_params_get_double(args->params, PARAM_THETA),
                         gwy_params_get_double(args->params, PARAM_PHI));
    gtk_widget_set_size_request(gui.shader, -1, 180);
    gtk_box_pack_start(GTK_BOX(vbox), gui.shader, FALSE, TRUE, 0);

    table = gui.table = gwy_param_table_new(args->params);
    gwy_param_table_append_slider(table, PARAM_THETA);
    gwy_param_table_append_slider(table, PARAM_PHI);
    gwy_param_table_append_slider(table, PARAM_MIX);
    gwy_param_table_add_enabler(table, PARAM_DO_MIX, PARAM_MIX);

    gtk_box_pack_start(GTK_BOX(vbox), gwy_param_table_widget(table), TRUE, TRUE, 0);

    g_signal_connect_swapped(gui.shader, "angle_changed", G_CALLBACK(shade_changed), &gui);
    g_signal_connect_swapped(table, "param-changed", G_CALLBACK(param_changed), &gui);
    gwy_dialog_set_preview_func(dialog, GWY_PREVIEW_IMMEDIATE, preview, &gui, NULL);

    return gwy_dialog_run(dialog);
}

static void
shade_changed(ModuleGUI *gui, GwyShader *shader)
{
    GwyParamTable *table = gui->table;

    gwy_param_table_set_double(table, PARAM_THETA, fmin(gwy_shader_get_theta(shader), 0.5*G_PI*(1.0 - 1e-15)));
    gwy_param_table_set_double(table, PARAM_PHI, gwy_shader_get_phi(shader));
}

static void
param_changed(ModuleGUI *gui, gint id)
{
    GwyParams *params = gui->args->params;
    /* Read the values first. Do not the one-level recursive shader's update mess up our ϑ and φ. */
    gdouble theta = gwy_params_get_double(params, PARAM_THETA);
    gdouble phi = gwy_params_get_double(params, PARAM_PHI);

    if (id < 0 || id == PARAM_THETA)
        gwy_shader_set_theta(GWY_SHADER(gui->shader), theta);
    if (id < 0 || id == PARAM_PHI)
        gwy_shader_set_phi(GWY_SHADER(gui->shader), phi);

    gwy_dialog_invalidate(GWY_DIALOG(gui->dialog));
}

static void
preview(gpointer user_data)
{
    ModuleGUI *gui = (ModuleGUI*)user_data;

    execute(gui->args);
    gwy_field_data_changed(gui->args->result);
}

static void
execute(ModuleArgs *args)
{
    GwyParams *params = args->params;
    GwyField *field = args->field, *result = args->result;

    gwy_field_shade(field, result,
                    gwy_params_get_double(params, PARAM_THETA), gwy_params_get_double(params, PARAM_PHI));
    if (gwy_params_get_boolean(params, PARAM_DO_MIX))
        mix_with_plane(result, field, gwy_params_get_double(params, PARAM_MIX));
    gwy_field_normalize(result);
}

static void
mix_with_plane(GwyField *shaded,
               GwyField *plane,
               gdouble mixfraction)
{
    gdouble plane_min, plane_max, shade_min, shade_max, plane_range, shade_range, q;

    gwy_field_min_max(plane, &plane_min, &plane_max);
    gwy_field_min_max(shaded, &shade_min, &shade_max);
    plane_range = plane_max - plane_min;
    shade_range = shade_max - shade_min;

    q = (plane_range > 0.0 ? mixfraction*shade_range/plane_range : 1.0);
    gwy_field_linear_combination(shaded, 1.0 - mixfraction, shaded, q, plane, 0.0);
}

/* vim: set cin columns=120 tw=118 et ts=4 sw=4 cino=>1s,e0,n0,f0,{0,}0,^0,\:1s,=0,g1s,h0,t0,+1s,c3,(0,u0 : */
