
# This code creates the user interface for global.
#
# Copyright (c) 1993 - 1995 Pacific Marketing and Consulting, Inc,
#       and ICEM Systems, GmbH.  All rights reserved.
# Author:  Wayne A. Christopher, wayne@icemcfd.com

set tool_name "ICEM GLOBAL"
set whoami "$tool_name $version"

set tool_id global

if [info exists env(GLOBAL_DIR)] {
    set tool_dir $env(GLOBAL_DIR)
} else {
    set tool_dir $env(ICEM_ACN)/lib/global
}

if [info exists env(GLOBAL_BIN)] {
    set tool_bin $env(GLOBAL_BIN)
} else {
    set tool_bin $env(ICEM_ACN)/icemcfd/global
}


proc global_configuration_read {} {
    if [file exists .global_config] {
	uplevel \#0 {source .global_config}
    }
}

proc global_configuration_write {} {
    set fp [open .global_config w]
    
    set global_array_list "display_flag global_options"
    foreach arr $global_array_list {
	global $arr
	puts $fp "array set $arr {\n[array get $arr]\n}\n"
    }
    close $fp
}

# Default values for global_options array.  Need to set cart_file
# and tool_bin before execute global_option_defaults.  Proper cart_file
# and tool_bin will be set when execute tool_command

proc global_option_defaults {} {
    global env global_options is_win display_flag
    
    # Don't write these quantities to file
    
    set global_options(mask) {
	tool_bin cart_file tetin_file remote_executes rdir cart_file_name
    }
    
    # Allowable remote processes
    
    set global_options(remote_executes) {Staircase}
    foreach r $global_options(remote_executes) {
	set global_options($r) 0
    }
    
    # Remote machine and user
    
    set global_options(remote) ""
    if $is_win {
	set global_options(ruser) ""
    } else {
	if [catch {set global_options(ruser) [cmd_whoami]}] {
	    if [catch {set global_options(ruser) [exec whoami]}] {
		set global_options(ruser) unknown
	    }
	}
    }
    
    # home directory
    
    set global_options(curdir) ""
    
    # executable
    
    set global_options(bin) $global_options(tool_bin)
    
    # Needed environment variables: ICEM_ACN and optional license file
    
    set global_options(icemacn) $env(ICEM_ACN)

    if [info exists env(LM_LICENSE_FILE)] {
	set global_options(license) $env(LM_LICENSE_FILE)
    } else {
	set global_options(license) ""
    }
    
    # Cart file
    
    set cart_file $global_options(cart_file)
    set meshdir [file dirname $cart_file]
    set global_options(meshdir) $meshdir
    
    # use 4.2 file structure if file directories not specified
    
    set global_options(projdir) $meshdir
    set global_options(domdir) $meshdir
    set global_options(transdir) $meshdir
    
    set global_options(cart_file_name) [file tail $cart_file]
    
    # Set the default viewing parameters.
    
    set display_flag(block_boundary) 1
    
    # Initialize staircase repair/display flags

    foreach ex {marking autofix fixvolid quad bar} {
	set idx quad_$ex
	set display_flag($idx) 1
    }

    foreach ex {rebuild showcre shrinkwrap specialmat outside} {
	set idx quad_$ex
	set display_flag($idx) 0
    }
    
    # set the assign material option (if any specified)
    
    set display_flag(quad_assignmat) -ORFN    
    set display_flag(quad_ff_type) "-standard"
    set display_flag(quad_saveallquads) 1   
    set display_flag(curve) 0
    set display_flag(surf)  1
    set display_flag(point_mater) 1
    
    # mirroring options
    
    set global_options(mdir) 0; set global_options(mval) 1
    set global_options(mtype) gridline
    set global_options(mall) 1
    set global_options(mmat) 1
	
    set global_options(symtype) 1
    set global_options(corr) .90
    set global_options(famirrel) 1
    
    # output options
    
    set global_options(aqua_vol) "aqua.bd1"
    set global_options(aqua_surf) "aqua.bd2"
    set global_options(ppd) 0
}

# sticky permanent defaults that must be set before executing
# global_option_defaults.  Actually set in tool_command

set global_options(cart_file) "cart_file"
set global_options(tetin_file) ""
set global_options(tool_bin) $tool_bin

# Actually set the global_option_defaults

global_option_defaults

# execute the global configuration options script

set help_base global/global

set domdir ""
set transdir ""
set projdir ""
set cart_file ""
set tetin_file ""
set nopushmat 0
set oned 0
set nvold 0
set vface 0
set mvold 0
set sheetmetal 0
set fixwall 0
set assignmat 0
set assignORFN 0
set nosurfs 0
set showcurves 0
set fract ""
set usedefaults 0
set saveallquads 1

set tool_options {
    { -cart cart_file 1 }
    { -tetin tetin_file 1 }
    { -projdir projdir 1 }
    { -domdir domdir 1 }
    { -transdir transdir 1 }
    { -nopushmat nopushmat }
    { -no_vol_disamb nvold }
    { -mat_disamb mvold }
    { -sheetmetal sheetmetal }
    { -fract fract 1 }
    { -vface vface }
    { -1D oned }
    { -fixwall fixwall }
    { -assignmat assignmat }
    { -ORFN assignORFN }
    { -nosurfs nosurfs }
    { -showcurves showcurves }
    { -usedefaults usedefaults }
    { -saveallquads 1 }
}

set tool_files {
    disp_global
    file_global
    anal_global
    diag_global
    mesh_global
    edit_global
    select_global
    hardcopy_global
}

set tool_prompt global%

proc tool_command {} {
    global display_flag global_options
    global tool_bin cart_file tool_arguments black_and_white
    global tetin_file nopushmat oned nvold vface mvold sheetmetal
    global projdir domdir transdir fract usedefaults saveallquads
    
    set lta [llength $tool_arguments]
    #puts "cart_file, tool_arguments = $cart_file $tool_arguments"
    if {$cart_file == ""} {
	if {[llength $tool_arguments] != 1} {
	    error "Usage: global [-tetin tfile] cart_file"
	}
	set cart_file [lindex $tool_arguments 0]
    }
	
    if [file isdirectory $cart_file] {
	set cart_file $cart_file/mesh/cart_file
    }
	
    if ![file exists $cart_file] {
	error "No such file: $cart_file"
	exit 1
    }
    
    set othopts ""
    if $black_and_white { append othopts "-bw" }
    if $nopushmat { append othopts " -nopushmat" }
    if $oned { append othopts " -1D" }
    if $nvold { append othopts " -no_vol_disamb" }
    if $vface { append othopts " -vface" }
    if $mvold { append othopts " -mat_disamb" }
    if $sheetmetal { append othopts " -sheetmetal" }
    if $saveallquads { append othopts " -save_all_quads" }
    
    if !$usedefaults { global_configuration_read }
    
    # Sticky permenant defaults.  These MUST be masked
    
    set global_options(tool_bin) $tool_bin
    set global_options(cart_file) $cart_file
    set global_options(tetin_file) $tetin_file

    # Changeable.  Currently rdir and cart_file_name are masked.  User
    # can change these parameters are masked if he/she wants.
    
    set global_options(bin) $tool_bin
    set global_options(cart_file_name) [file tail $cart_file]
    
    set meshdir [file dirname $cart_file]
    set global_options(meshdir) $meshdir
    
    if {$projdir == ""} { set projdir $meshdir }
    if {$domdir == ""} { set domdir $meshdir }
    if {$transdir == ""} { set transdir $meshdir }
    
    set global_options(projdir) $projdir
    set global_options(domdir) $domdir
    set global_options(transdir) $transdir
    
    set ret "$tool_bin "
    
    if {$tetin_file != ""} {
	append ret "-tetin \"$tetin_file\" "
    }
    
    append ret "$othopts -i \"$cart_file\""
    append ret " -projdir \"$projdir\" -domdir \"$domdir\" -transdir \"$transdir\""
    
    if {$fract != ""} {
	append ret " -fract $fract"
    }
    
    return $ret
}

proc tool_setup {} {
    global display_flag is_win global_info last_line global_options
    global assignmat fixwall nosurfs showcurves
    
    # Get families
    
    add_families
    get_indices 1
    
    # Display with current values
    
    if $showcurves { set display_flag(curve) 1 }
    if $nosurfs    { set display_flag(surf)  0 }
    
    if $fixwall { set assignmat 0 }
    if $assignmat {
	append othopts " -assignmat"
	set display_flag(quad_assignmat) "-assignmat"
    }
    if $fixwall {
	append othopts " -fixwall"
	set display_flag(quad_assignmat) "-fixwall"
    }
    
    # get non-standard named curve/surface entities
    
    command "surface_ids" 0
    set global_info(init_surfs) $last_line
    
    command "curve_ids" 0
    set global_info(init_curves) $last_line
    
    update_display
    command "orient +z"
    
    if $is_win {
	bind all <Key> {check_binding %W %X %Y %x %y %K}
    }
}

proc make_tool_windows {} {
    make_display_window
}

#set tool_logo "$tool_dir/global-logo.xbm black"
#set tool_logo $tool_dir/global-logo.ppm
set tool_logotext "ICEM CFD 10.0\nGlobal Mesher"
set tool_logo_relief flat

set dirs [list [pwd] $env(HOME) $env(ICEM_ACN)/lib/med_gui \
	      $env(ICEM_ACN)/lib/med]

set tool_logo ""
foreach d $dirs {
    set logo $d/med-logo-bits.xbm
    if [file exists $logo] {
	set tool_logo "$logo \#0000ff $d/med-logo-mask.xbm \#547eff"
	set tool_logo_small "$d/med-smlogo-bits.xbm black \
        $d/med-smlogo-mask.xbm blue"
	break
    }
}

if {$tool_logo == ""} {
    set msg "Could not find ICEMCFD Logo files \"med-logo-bits.xbm\" etc.\n"
    append msg "Please put them in one of the following directories:\n"
    append msg "$dirs"
    error $msg
}

set axes_use_minmax 1

proc axes_minmax_initialize {} {
    global display_axes_pos index_min_limit index_max_limit
    foreach i {0 1 2} {
	set ii [lindex {i j k} $i]
	set display_axes_pos(${ii}pos) $index_min_limit($i)
	set display_axes_pos(${ii}size) [expr $index_max_limit($i) - \
					     $index_min_limit($i) - 1]
    }
}

proc axes_select_minmax {} {
    set banner "Select a node position with the left button."
    set last_line [select_node $banner node 1]
    
    return [lindex $last_line 0]
}

# -------------------------------------------------

set tool_phases {
    {File        file}
    {Diagnostics anal}
    {Edit        edit}
}

set tool_phase_info(file) {
    {write_super     button "Super domain"       0,1 file_super}
    {write_surface   menu   "Unstruct surface"   0,2 {
	{ command -label "Bounding Vol..." -command { file_unstruct bvol}}
	{ command -label "Surfaces..."     -command { file_unstruct surf}}
	{ checkbutton -label "Emit As Triangles" \
	      -variable mesh_params(emit_triangles)}
	{ checkbutton -label "No Materials" -variable mesh_params(no_mat)}}}
    {write_volume    button "Staircase volume"   0,3 "file_unstruct vol"}
    {write_staircase button "Staircase surface"  0,4 "file_unstruct stair"}
    {write_hgrid     button "H-grid"             0,5 "file_hgrid"}
    {out_inter       menu   "Interfaces"         0,6 {
	{cascade "Gorf" {
	    { command -label "Read"  -command "file_read_gorf read" }
	    { command -label "Merge" -command "file_read_gorf merge" }
	    { command -label "Write" -command file_write_gorf }
	}}
	{cascade "Uh3d" {
	    {command -label "Write" -command file_write_uh3d}
	}}
	{cascade "AQUA" {
	    {command -label "Write" -command file_write_AQUA}
	}}
    }}
    
    {read_stair      button "Read staircase"     1,1 file_read_staircase}
    {hardcopy        button "Hardcopy"           1,2 file_hardcopy}
    {shell           button "Shell"              1,3 file_shell}
    {remote          button "Remote Execute"     1,4 file_remote}
    {quit            button "Quit"               1,5 file_quit}
}

set tool_phase_info(anal) {
    {free_surf       button "Free surface"       0,1 anal_freesurf}
    {calc_vol        button "Calc volume"        0,2 anal_calcvol}

    {mismarked     checkbutton "Mismarked materials" "1,1 -columnspan 2" \
	    mismarked_mats_on diag_mismarked_mats}
    {miss_intercpt checkbutton "Missing intercepts"  "1,3 -columnspan 2"\
	    miss_intercepts_on diag_missing_intercepts}
}

# Don't give option until autofix works better
#
#	{ checkbutton -label "Autofix" \
#    -variable display_flag(quad_autofix) -command edit_repair_stair}

set tool_phase_info(edit) {
    {repair_stair    menu   "Repair staircase"     0,1 {
	{ command -label "Check Staircase" -command edit_repair_stair}
	{ command -label "Erase Marking Path" -command "edit_repair_erase"}
	{ command -label "Unneeded Quad Delete" \
	      -command "edit_delete_unneeded" }
	{ separator }
	{ radiobutton -label "Standard" \
	      -variable display_flag(quad_ff_type) -value "-standard" \
	      -command edit_repair_stair}
	{ radiobutton -label "Restricted" \
	      -variable display_flag(quad_ff_type) -value "-restrict" \
	      -command edit_repair_stair}
	{ separator }
	{ checkbutton -label "Shrinkwrap" \
	      -variable display_flag(quad_shrinkwrap) \
	      -command edit_repair_stair }
	{ checkbutton -label "Special Mat Only" \
	      -variable display_flag(quad_specialmat) \
	      -command edit_repair_stair }
	{ checkbutton -label "Outside Boundary" \
	      -variable display_flag(quad_outside) \
	      -command edit_repair_stair }
	{ separator }
	{ checkbutton -label "Show Marking Path" \
	      -variable display_flag(quad_marking)}
	{ checkbutton -label "Fix Volume Ids" \
	      -variable display_flag(quad_volid)}
	{ checkbutton -label "AutoFix" \
	      -variable display_flag(quad_autofix)}
	{ checkbutton -label "Save ORFN Mat Quads" \
	      -variable display_flag(quad_saveallquads)}
	{ separator }
	{ radiobutton -label "Assign Unknown" \
	      -variable display_flag(quad_assignmat) -value -assignmat}
	{ radiobutton -label "Assign Unk. to ORFN" \
	      -variable display_flag(quad_assignmat) -value -ORFN}
	{ radiobutton -label "Fix Unknown" \
	      -variable display_flag(quad_assignmat) -value -fixwall}
	{ separator }
	{ command -label "Rebuild Staircase" -command "edit_rebuild_stair" }
	{ separator }
	{ radiobutton -label "No Highlight" \
	      -variable display_flag(quad_unneeded) -value 0 \
	      -command "edit_repair_dispquad"}
	{ radiobutton -label "Highlight Unneeded" \
	      -variable display_flag(quad_unneeded) -value 1 \
	      -command "edit_repair_dispquad"}
	{ radiobutton -label "Only Unneeded" \
	      -variable display_flag(quad_unneeded) -value 2 \
	      -command "edit_repair_dispquad"}
   }}
    {add_stair       menu   "Add staircase"        0,2 {
	{ command -label "Quad"   -command { edit_add_stair quad } }
	{ command -label "Bar"    -command { edit_add_stair bar } }
    } }
    {del_stair       menu   "Delete staircase"     0,3 {
	{ command -label "Selected quad: unneeded visible" \
	      -command { edit_del_stair quad sel_v_un } }
	{ command -label "Selected quad: unneeded all" \
	      -command { edit_del_stair quad sel_a_un } }
	{ command -label "Visible quad: unneeded " \
	      -command { edit_del_stair quad vis_un } }
	{ command -label "All quad: unneeded" \
	      -command { edit_del_stair quad all_un } }
	{ separator }
	{ command -label "Selected quad: visible" \
	      -command { edit_del_stair quad sel_v } }
	{ command -label "Selected quad: all" \
	      -command { edit_del_stair quad sel_a } }
	{ command -label "Visible quad" \
	      -command { edit_del_stair quad vis } }
	{ command -label "All quad" -command { edit_del_stair quad all } }
	{ separator }
	{ command -label "Selected bar: visible" \
	      -command { edit_del_stair bar  sel_v } }
	{ command -label "Selected bar: all" \
	      -command { edit_del_stair bar  sel_a } }
	{ command -label "Visible bar" \
	      -command { edit_del_stair bar  vis } }
	{ command -label "All bar"  -command { edit_del_stair bar  all } }
    } }
    {change_stair    menu   "Change Family"     0,4 {
	{ command -label "Quad"   -command { edit_change_stair quad } }
	{ command -label "Bar"    -command { edit_change_stair bar } }
	{ command -label "Volume" -command { edit_change_stair volume } }
    } }
    { mirror_stair menu "Symmetry" 0,5 {
	{command -label "Mirror" -command mirror_staircase}
	{command -label "Symmetrize" -command symmetrize_staircase}
    } }
    {define_item menu "Define geometry" 1,1 {
	{ command -label "Line"  -command edit_define_line }
	{ command -label "Point" -command edit_define_point }
    } }
    {delete_item menu "Delete geometry" 1,2 {
	{ command -label "Line"  -command "edit_delete_geo line" }
	{ command -label "Point" -command "edit_delete_geo point" }
    } }
	
    {index_planes    button "Index planes"         1,3 mesh_index_planes}
    {fcolor          button "Family color"         1,4 change_family_color}
}

# {slice_planes    button "Slice Planes"         1,5 mesh_slice_planes}

set edge_color(single) \#ffff00
set edge_color(double) \#ff0000
set edge_color(multiple) \#0000ff

# meshing parameters

set mesh_params(emit_triangles) 1
set mesh_params(no_mat) 0

#array set command_needs_stopbutton {
#    display_unstruct_quads "Stop staircase display."
#}

proc check_binding {win x y wx wy c} {
    set viewx1 [winfo rootx .v.view]
    set viewy1 [winfo rooty .v.view]
    set viewx2 [expr $viewx1 + [winfo width .v.view]]
    set viewy2 [expr $viewy1 + [winfo height .v.view]]
    set cc [winfo containing $wx $wy]
    if {($wx < $viewx1) || ($wx > $viewx2) || \
	($wy < $viewy1) || ($wy > $viewy2) || ($cc != "")} return

    if {$win == ".v"} {
        if {$c == "h"} {
	    dl_home
	} elseif {$c == "F9"} {
	    send_event k O $wx $wy 0
	}
    }
}
