
# The GUI for Autohex.
#
# Copyright (c) 1993, 1994 Pacific Marketing and Consulting
# Author:  Wayne A. Christopher, wayne@pmac.com
#          Pacific Marketing and Consulting, Berkeley, California

if [file exists $autohex_root/lib/version] {
    set fp [open $autohex_root/lib/version r]
    set version [gets $fp]
    close $fp
} else {
    set version ?
}

set whoami AutoHex
set tool_name "ICEM AutoModel"
set copyright "Copyright 2011, SAS IP, Inc.\nAll rights reserved. Unauthorized use, distribution or duplication is prohibited.\nANSYS and ICEM CFD Autohexa are trademarks or registered trademarks of ANSYS, Inc. or its subsidiaries in the United States or other countries."

set auto_debug [info exists env(AUTO_DEBUG)]

set tool_id automodel

set tool_dir $autohex_lib_dir
set tool_dir2 $tdv_library
set default_job_directory ""
set job_directory ""
set library_path ""
set options(select_mode) all
set app_is_autohex 1
set background_color #000000
set vwindow_fills_screen 1
set edit_update_button_active 1
set form_default_resize 0
set expression_trial_prefix trial
set model_had_checksum 0
set checkbuttons_have_params 1

# This is not such a good way to do it - hardwiring the path name for the 
# single-view window - but it's easiest for now.

set tdv_default .v.bot.f1.frame.f.f0.frame.one

if {$tcl_version >= 8.3} {
    set bwdir [file dirname $tool_dir]/bwidget
} else {
    set bwdir [file dirname $tool_dir]/BWidget-1.2.1
}
if {!$batch_mode && [file exists $bwdir]} {
    lappend auto_path $bwdir
    package require BWidget
}

array set try_suff {
    sgi { sgi sgi5 sgi6 mips4 }
    sgi6 { sgi sgi5 sgi6 mips4 }
    mips4 { sgi sgi5 sgi6 mips4 }
    mips64 { mips64 sgi sgi5 sgi6 mips4 }
    hp { hp hp9 hp10 }
    hp9 { hp hp9 hp10 }
    hp10 { hp hp9 hp10 }
    hp11 { hp hp9 hp10 hp11 hp11_32 }
    hp11_32 { hp hp9 hp10 hp11 hp11_32 }
    ibm { ibm ibm41 ibm42 ibm43 }
    ibm42 { ibm ibm43 }
    ibm43 { ibm ibm43 }
    ibm64 { ibm64 ibm ibm43 }
    sol { sol solaris sol5 }
    sol5 { sol solaris sol5 }
    sol7 { sol7 sol solaris sol5 }
    sol64 { sol64 sol7 sol solaris sol5 }
    hpit { hpit }
    alpha { alpha alpha40 }
    alpha40 { alpha alpha40 }
    win { win40 ntx86 }
    win40 { win40 ntx86 }
    win64 { win64 win40 ntx86 }
    decwin { decwin40 }
    decwin40 { decwin40 }
    linux { linux linux_rh9 lnx86 }
    linux_rh9 { linux linux_rh9 lnx86 }
    linux64 { linux64 linux }
}

foreach suff $try_suff($host_vendor) {
    set bindir $autohex_root/bin.$suff
    if [file exists $bindir] break
}

if ![file exists $bindir] {
    set obin $bindir
    set bindir $autohex_root/bin
}
if ![file exists $bindir] {
    error "Can't find the binary directory!  It should be $bindir or $obin ..."
}

if [info exists env(PATH)] {
    if {$tcl_platform(platform) == "windows"} {
        set env(PATH) [join [split $bindir /] \\]\;$env(PATH)
    } else {
        set env(PATH) $bindir:$env(PATH)
    }
}

# This disables the 2GB NFS warning
set env(ICEM_NO_WARN_NFS) 1

#set DEBUG "bindir is $bindir\n"

foreach prog {
    global tetra cutter mesher smooth prism tetssi hexa mesh2block
    iparta_to_tetin igespost_exec ssish qtet mesh_direct uncouple steptotin
    iceboard_meshing dwg2tin ifc2pak acistotin
} {
    set ${prog}_path not_found
    foreach p [list $bindir/$prog $autohex_root/icemcfd/${prog}bat \
		   $autohex_root/icemcfd/${prog}_batch \
		   $autohex_root/icemcfd/$prog \
		   $bindir/auto_$prog $autohex_root/icemcfd/auto_$prog \
		   $autohex_root/iges/$prog $autohex_root/iges/${prog}_exec] {
	#append DEBUG "checking $p\n"
	if [file exists $p] {
	    #append DEBUG "got it\n"
	    set ${prog}_path $p
	    break
	}
	#append DEBUG "checking $p.exe\n"
	if [file exists $p.exe] {
	    #append DEBUG "got it\n"
	    set ${prog}_path $p.exe
	    break
	}
    }
    if {[set ${prog}_path] == "not_found"} {
	#append DEBUG "found nothing for $prog\n"
	# puts "WARNING: no $prog binary"
    }
}

if ![info exists env(ICMIF_ACN)] {
    if [file exists $bindir/dif] {
	set env(ICMIF_ACN) $bindir/dif
    } else {
	foreach suff $try_suff($host_vendor) {
	    set difdir $autohex_root/dif.$suff
	    if [file exists $difdir] break
	}
	if ![file exists $difdir] {
	    puts "Can't find the direct interfaces directory!  It should be $bindir/dif ..."
	} else {
	    set env(ICMIF_ACN) $difdir
	}
    }
}

#puts $DEBUG

proc check_advanced_mesher_ok {} {
    global autohex_root advanced_mesher_ok tetra_path global_path
    global grid_license_found hexa_path

    set grid_license_found(mesher) 1
    set grid_license_found(tetra) [expr {$tetra_path != "not_found"}]
    set grid_license_found(global) [expr {$global_path != "not_found"}]
    set grid_license_found(hexa) [expr {$hexa_path != "not_found"}]
    set advanced_mesher_ok 1
    return


    # This is no longer really needed

    set grid_license_found(mesher) 1
    set grid_license_found(tetra) 0
    set grid_license_found(global) 0
    set grid_license_found(hexa) 0
    set advanced_mesher_ok 0
    
    set dl $autohex_root/lic/license.dat
    
    if {[is_feature_available TETRA $dl] || \
	    [is_feature_available tetra $dl]} {
	set grid_license_found(tetra) 1
	set advanced_mesher_ok 1
    }
    if {[is_feature_available GLOBAL $dl] || \
	    [is_feature_available global $dl]} {
	set grid_license_found(global) 1
	set advanced_mesher_ok 1
    }
    if {[is_feature_available HEXA $dl] || \
	    [is_feature_available hexa $dl]} {
	set grid_license_found(hexa) 1
	set advanced_mesher_ok 1
    }
    
    if {($tetra_path == "not_found") && ($global_path == "not_found")} {
	set advanced_mesher_ok 0
    }
}

proc cad_get_menu {pos} {
    global app_name
    
    set stuff1 {
	{ command -label "Load tetin file"     -command "cad_load_tetin" }
	{ command -label "Load IGES file"      -command "cad_load_iges" }
    }
    
    set stuff2 {
	{ command -label "Options"             -command "cad_edit_options" }
	separator
	{ command -label "Selected -> objects" -command "cad_create_multiple single"}
	{ command -label "Families -> objects"  -command "cad_create_multiple family"}
	{ command -label "Regions -> objects"  -command "cad_create_multiple region"}
    }
    switch $app_name {
	icepak - airpak { set stuff3 "" }
	default {
	    set stuff3 {
		{ command -label "Create CAD objects"  -command "cad_create_multiple cad"}
		{ command -label "Update existing"     -command "cad_regenerate" }
	    }
	    lappend stuff1 \
		{ command -label "Load Nastran file"   -command "cad_load_mesh nastran Nastran" }
	}
    }
    set stuff4 {
	{ command -label "Blank surfaces"      -command "cad_blank_surface" }
	{ command -label "Unblank surfaces"    -command "cad_unblank_surface" }
	{ command -label "Delete all CAD data" -command "cad_clear 1" }
	{ command -label "Change family"       -command "cad_change_family" }
	{ command -label "Family visibility"   -command "cad_edit_families" }
	{ command -label "Rescale geometry"    -command "cad_rescale" }
	separator
	{ checkbutton -label "Show used"       -variable cad_show_used \
	      -command "cad_toggle_show" }
	{ checkbutton -label "Show unused"     -variable cad_show_unused \
	      -command "cad_toggle_show" }
	{ checkbutton -label "Solid shading"   -variable cad_show_solid \
	      -command "cad_toggle_show" }
	{ checkbutton -label "Fast movement"   -variable geom_fast_dynamics }
    }
    
    return [list cadops menu "CAD import" $pos \
		[concat $stuff1 $stuff2 $stuff3 separator $stuff3 $stuff4]]
}

if 0 {
    set p $autohex_root/bin.$host_vendor:$autohex_root/bin
    if [info exists env(LD_LIBRARY_PATH)] {
	append env(LD_LIBRARY_PATH) :$p
    } else {
	set env(LD_LIBRARY_PATH) $p
    }
}

set batch_update_file ""

set server_mode 0
set server_port 12345
set server_dir .
set server_host ""
set queue_server 0

set tool_options {
    { -part         part_flag     "" 0 }
    { -batch        batch_type    1  "" }
    { -unpack       unpack_flag   "" 0 }
    { -jd           default_job_directory 1 }
    { -batch_update batch_update_file 1 }
    { -server       server_mode "" 0 }
    { -server_port  server_port 1 }
    { -server_dir   server_dir 1 }
    { -remote       server_host 1 }
}

set graphics_type native
set autohex_dir $tool_dir

set no_full_msgs_buttons 1
#set use_smoother_ssi 1

set grid_type ""

set allow_multi_thick_quads 0
set grid_quality_warning 1
set select_cad_autohex_options 1

set use_grid_grading [expr {($app_name != "icepak") &&
			    ($app_name != "airpak")}]
#set use_grid_grading 0

set never_ignore(name) 1
set never_ignore(active) 1
set never_ignore(*,current_genus) 1
set default_cache(*,active) 1
set default_cache(*,groups) {}
set default_cache(*,current_section) body
set default_cache(*,units) Problem
set default_cache(*,current_genus) default
set default_cache(*,fixvals) 0

lappend source_dirs $tool_dir
lappend source_dirs $tool_dir2
lappend source_dirs $app_dir

set tool_files {
    open_auto
    file_auto
    csv_auto
    job_auto
    model_auto
    edit_auto
    view_auto
    interact_auto
    edit_subforms
    copymove_auto
    group_auto
    bocos_auto
    summary_auto
    anno_auto
    fluent_uns
    part_auto
    misc
    undo_auto
    grid_auto
    grid_perobject
    grid_params_table
    mesher_auto
    global_auto
    tetra_auto
    hexa_auto
    meshface
    meshinfo
    smoother_auto
    tetin_auto
    domainfile
    iges_autohex
    check_auto
    macro_auto
    hardcopy_auto
    units
    expression
    summary_sheet
    material
    profile
    unit_data
    pipe_auto
    cad_auto
    projlib_auto
    local_coords
    scripting_auto
    tree_auto
    tree_standalone
    trash_auto
    spread_auto
    server_auto
    diff_auto
    library_auto
    library_browser
    options_auto
    summary_html
    iceboard_meshing
    named_point
}

set tool_files2 {
    viewer
    wb_binding
}

set guibase_files_extra {
    trace_events
    bocofile
    colormap
    curve
    bltemu
    exec_cmds
    poll
    dialog
    spreadsheet
    interrupt
    projlib
    family_boco
    makedoc
    jobs
    select_geom
    select_sub
    run_application
    flexlist
    url_io
    option_edit
}
#    bmatrix

set prog_guide_files { scripting_auto forms exec_cmds }

if [info exists env(ICEM_MODELBUILDER)] {
    set is_modelbuilder 1
    set mbdir $tool_dir/../modelbuilder
    source $mbdir/mb_main.tcl
} else {
    set is_modelbuilder 0
}

foreach i { config problem solve grid config graph other uns } {
    set ${i}_params ""
}

proc tool_command {} {
    return ""
}

proc tool_setup {} {
    global part_flag initial_job unpack_flag model_container tool_arguments
    global batch_mode license_message batch_update_file tdv_default
    global env autohex_root default_job_directory is_win
    global language_text_file job_directory is_modelbuilder
    global can_do_open_operation server_mode model_container_root
    global after_objects_loaded_cmd trash_container app_name
    global object_type_list type_visible queue_server
    
    if $server_mode return
    
    if {$queue_server} {
	do_batch_queue_server
    }

    busy 1
    
    check_advanced_mesher_ok

    if {[info commands tool_setup_app] != ""} { tool_setup_app }

    if {[llength $tool_arguments] > 1} {
	user_error "Usage: progname \[ options \] \[ projectname \]"
	return
    } elseif {[llength $tool_arguments] == 1} {
	set initial_job [lindex $tool_arguments 0]
	if {([llength [file split $initial_job]] == 1) && 
	    ($job_directory != ".") &&
	    ![file exists $initial_job] &&
	    ($default_job_directory != "")} {
	    set initial_job $default_job_directory/$initial_job
	}
    } elseif $batch_mode {
	user_error "No project specifed on command line."
	return
    }
    
    if [info exists license_message] {
	mess "Licensing: $license_message\n" red
    }
    
    
    foreach t "$object_type_list part" { set type_visible($t) 1 }    
    save_default_param_values
    
    set model_container [model_container]
    set model_container_root $model_container
    set shcon [shape_container -shtype container -is_open 1]
    $model_container setval body_shape $shcon

    set trash_container [model_container]
    
    if !$batch_mode {
	$tdv_default add_image $shcon
    }
     
    set jj job; if $part_flag { set jj part }
    
    if $part_flag {
	if {$default_job_directory != ""} {
	    set job_directory $default_job_directory/parts
	} else {
	    set job_directory [pwd]/parts
	}
    }
    
    options_edit_grab_defaults
    
    busy 0
    
    if [info exists initial_job] {
	# This is a convenience so that you can say "Open using application"
	# from an html browser
	switch [file extension $initial_job] {
	    .gz - .tzr - .tgz - .tar {
		set unpack_flag 1
	    }
	}
	
	if $unpack_flag {
	    set pfile $initial_job
	    set initial_job [file_diagunpack $pfile]
	    if {$initial_job == ""} {
		mess "Error: can't unpackage file \"$pfile\"\n" red
		unset initial_job
	    }
	}
    }
    
    set can_do_open_operation 1
    
    if ![info exists initial_job] {
    mess "The Autohexa product has been officially discontinued and is unsupported.  However, due to popular demand, we have allowed access.  Please use at your own risk\n"
	set more 1
	while {$more} {
	    if [winfo exists .new_job] { destroy .new_job }
	    if {$app_name == "emax"} { ;# fix this!!
		set ok [tk_dialog .new_job "New/existing" "Do you want to open an existing project, or create a new one?" "" -1 Existing New Quit]
		switch -- $ok {
		    0 { if [file_job] { set more 0 } }
		    1 { if [file_new] { set more 0 } }
		    2 { exit 0 }
		}
	    } else {
		set ok [tk_dialog .new_job "New/existing" "Do you want to open an existing project, create a new one, or unpack a .tzr file?" "" -1 Existing New Unpack Quit]
		switch -- $ok {
		    0 { if [file_job] { set more 0 } }
		    1 { if [file_new] { set more 0 } }
		    2 { if [file_unpack] { set more 0 } }
		    3 { exit 0 }
		}
	    }
	}
    } else {
	job_load $initial_job ""
    }
    
    if [info exists initial_iges] {
	file_do_import iges $initial_iges 1 0
    }
    
    db_dirty off
    
    if {[info procs app_after_setup] != ""} {
	app_after_setup
    }
    
    if $is_modelbuilder { set_phase model }
    
    if {$batch_update_file != ""} {
	update_parameters_and_remesh $batch_update_file
    }
    
    if [info exists after_objects_loaded_cmd] {
	eval $after_objects_loaded_cmd
    }
    if !$batch_mode {
	wm protocol . WM_DELETE_WINDOW "file_quit 1"
    }
    
    if [info exists env(TRACE_EVENTS_FILE)] {
	trace_events_start $env(TRACE_EVENTS_FILE)
    }
}

#proc do_batch_job {args} { tool_setup }

proc add_mesh_button {r c {where model}} {
    global tool_phase_info autohex_root host_vendor messages_at_startup
    
    set bin_places [list $autohex_root/bin $autohex_root/bin.$host_vendor \
			$autohex_root/icemcfd]
    if {$host_vendor == "hp"} { lappend bin_places $autohex_root/bin.hp10 }
    
    foreach bin {mesher auto_mesher global tetra cutter smooth hexa iceboard_meshing} {
	if {$bin == "auto_mesher"} {
	    set pn mesher_path
	} else {
	    set pn ${bin}_path
	}
	global $pn
	if ![info exists $pn] { set $pn not_found }
	foreach d $bin_places {
	    if [file exists $d/$bin] {
		set $pn $d/$bin
		break
	    } elseif [file exists $d/${bin}_batch.exe] {
		set $pn $d/${bin}_batch.exe
		break
	    } elseif [file exists $d/${bin}bat.exe] {
		set $pn $d/${bin}bat.exe
		break
	    } elseif [file exists $d/$bin.exe] {
		set $pn $d/$bin.exe
		break
	    }
	}
    }
    
    set has_auto [expr {$mesher_path != "not_found"}]
    set has_tetra [expr {$tetra_path != "not_found"}]
    set has_global [expr {$global_path != "not_found"}]
    set has_hexa [expr {$hexa_path != "not_found"}]
    set has_iceboard [expr {$iceboard_meshing_path != "not_found"}]
    
    if {$has_auto + $has_tetra + $has_global + $has_hexa + $has_iceboard == 0} {
	lappend messages_at_startup \
	    [list "Warning: no meshers are available\n" red]
	
    } else {
	lappend tool_phase_info($where) \
	    [list mesh button Mesh $r,$c \
	 "edit_grid $has_auto $has_tetra $has_global $has_hexa $has_iceboard"]
    }
}

proc make_tool_windows {} {
    make_edit_window
}

set tool_logo ""

set tool_extra(1) {button Undo undo_action}
set tool_extra(2) {button Redo redo_action}
set tool_extra(3) {menubutton View}
set tool_extra(4) {menubutton Visible}
set tool_extra(5) {button Print file_hardcopy }
set tool_extra(6) {button Print print_hardcopy}
set tool_extra(7) {button Prompt file_shell}

set extra_position(help)   1,1
set extra_position(extra3) 1,2
set extra_position(orient) 2,1
set extra_position(extra4) 2,2
set extra_position(extra1) 3,1
set extra_position(extra2) 3,2
set extra_position(extra5) 4,1
set extra_position(extra6) 4,2
set extra_position(extra7) 5,1

set orient_buttons {
    { command -label "Home"         -command "tdv_home .v.view" }
    { command -label "Zoom"         -command "tdv_zoomin .v.view" }
    { command -label "Scale to fit" -command "tdv_scale_to_fit .v.view" }
    { command -label "Positive X"   -command "tdv_along_axis .v.view +x" }
    { command -label "Negative X"   -command "tdv_along_axis .v.view -x" }
    { command -label "Positive Y"   -command "tdv_along_axis .v.view +y" }
    { command -label "Negative Y"   -command "tdv_along_axis .v.view -y" }
    { command -label "Positive Z"   -command "tdv_along_axis .v.view +z" }
    { command -label "Negative Z"   -command "tdv_along_axis .v.view -z" }
    { command -label "Isometric"    -command "tdv_isoview .v.view" }
    { command -label "Reverse"      -command "tdv_reverse .v.view" }
}

set no_all_interaction_button 1
set is_iceboard 0
set is_airpak 0

source $tool_dir/params_auto.tcl
source $app_init
    
set graph_types [concat $app_graph_types $graph_types]

if ![info exists tool_logotext] {
    set tool_logotext "Version $version"
}

# The variables tool_phases and tool_phase_info must be set in the
# app_init file.

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

set job_name ""
set job_version ""
set domain ""
set projlib ""
set part_container ""
set undo_tag 0
set current_mtype none
set current_object ""
set current_shape ""
if ![info exists shading_type] { set shading_type wire }
set form_entry_justify_right 1
set edit_geometry_okay 1
set edit_nameactive_okay 1
set tdv_mouse_bindings_autohex_names 1
set default_autoscale_factor 1.2
set open_job_override_prefs 0

# The "info command" command is *really* slow.  So let's do some precomputation

foreach appf {
    shape_is_active decorate special_grid section_list_for_meshing
    before_solve verify transform is_vol_shape_solid special_priority
    graphparams should_split_nodes grid_type special_perobject_shape_dependence
    clean_up can_touch initialize decorate update_version grid_type 
    apply_transform set_power special_perobject_params radiation
} {
    foreach com [info command app_${appf}_*] {
	set obt [string range $com [string length app_${appf}_] end]
	set app_has_${appf}($obt) 1
    }
}
foreach com [info command obsolve_uns_*_int] {
    set obt [string range $com [string length obsolve_uns_] end-4]
    set app_has_obsolve_uns_int($obt) 1
}
foreach com [info command obsolve_uns_*] {
    set obt [string range $com [string length obsolve_uns_] end]
    set app_has_obsolve_uns($obt) 1
}

# Make things a bit quicker to access

foreach t [array names app_object_params_affect_graphics] {
    foreach p $app_object_params_affect_graphics($t) {
	set object_params_affect_graphics($t,$p) 1
    }
}

foreach t [array names app_object_params_affect_mesh] {
    foreach p $app_object_params_affect_mesh($t) {
	set object_params_affect_mesh($t,$p) 1
    }
}

foreach t [array names app_object_params_affect_sections] {
    foreach p $app_object_params_affect_sections($t) {
	set object_params_affect_sections($t,$p) 1
    }
}

proc about_autohexa {} {
    global whoami version copyright 
    global autohexa_about_message
    
    set d [form_init .about_icepak "About Autohexa" "" close]
    if {$d==""} return
    form_frame $d.fr sunken 3 {0 0}; set d $d.fr
    form_frame $d.tfr flat 0 {0 0};  set tfr $d.tfr
    form_colwidth $tfr 0 2 M
    form_rowheight $tfr 10 2
    set about_frame $d.tfr
    
    set autohexa_about_message "$whoami Autohex Version $version \n$copyright\n\nThe\
        Autohexa product has been officially discontinued and is unsupported. However,\
        due to popular demand, we have allowed access. Please use at your own risk."
    set w [form_text $about_frame.texta "" autohexa_about_message {0 0 -cols 2 } "" 50x15]
    $w configure -wrap word
    form_finish
    
}

# Windows 64 with tcl 8.4.11 does not have math functions floor and ceil.

proc ceil {v} {
    if {$v == int($v)} {
	return [expr int($v)]
    } else {
	return [expr int($v + 1)]
    }
}

proc floor {v} {
    if {$v == int($v)} {
	return [expr int($v)]
    } else {
	return [expr int($v - 1)]
    }
}