=begin

Ithil
Copyright 2013-2016, Ithil


Disclaimer
THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED 
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

License
Ithil Render Tools 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 3 of the License, or
    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, see <http://www.gnu.org/licenses/>

Information:
Author - Ithil
Plugin Name - Ithil Render Tools
Version - v2.0.1
SU Version - Developed on SU 2015,  checked in SU 2016. Only for Windows
V-ray Version - 2.* 
Date - August 18 , 2016

Description:
Plugin for optimization of work with the render

=end
require 'sketchup.rb'
require 'Win32API'
module IR


$ith_mat_dif = nil
$ith_mat_atr = nil
$ith_mat_texture = nil

def self.ithil_vr_render

Sketchup.active_model.start_operation('Change Layer&Render',true)
model = Sketchup.active_model
layers = model.layers

 layer_vis = layers['Render']
 layer_hide = layers['Proxy'] 
if layer_vis.class == NilClass or layer_hide.class == NilClass
 UI.messagebox("This script creates two layers 
under following names:
 \"Render\" and \"Proxy\"
 You can use them for Hi-poly model or construction geometry
 Render - visible at render time
 Proxy - invisible at render time"
 ) 
    new_layers_render=model.layers.add('Render')
    new_layers_Proxy=model.layers.add('Proxy')  
    layer_vis = layers['Render']      
    layer_vis.visible = true
    layer_hide = layers['Proxy'] 
    layer_hide.visible = false
    return
end
  layer_vis.visible = true
  layer_hide.visible = false
  
VRayForSketchUp.launch_vray_render  


  layer_vis = layers['Proxy']      
  layer_vis.visible = true
  
  layer_hide = layers['Render']
  layer_hide.visible = false


end

def self.ithil_vr_copy
                model = Sketchup.active_model
                material  = model.materials.current
                $ith_mat_dif = "Used"
IR.ithil_vr_save_diffuse (material)
 
 end #self.ithil_vr_copy

def self.ithil_vr_past
    model = Sketchup.active_model
    material = model.materials.current
    model.start_operation("Past Material", true)
    IR.material_test (material)
    IR.ithil_vr_load_diffuse (material)
    model.commit_operation

end #self.ithil_vr_past

def self.ithil_vr_attribute_copy
        model = Sketchup.active_model
        material  = model.materials.current
        IR.material_test (material)
        vfs_dictionary = ""
        @@vr_Hac_test=get_vfs_material_attribute( material )
        @@vr_Hac_test_old_name = material.display_name
         $ith_mat_atr = "Used"
end #ithil_vr_attribute_copy

def self.ithil_vr_attribute_past_select
        model = Sketchup.active_model
        material  = model.materials.current
        IR.material_test (material)
        model.start_operation("Past V-ray attribute", true)
        Sketchup.set_status_text "Program is running..."
        mat = find_material_with_tag
        if mat.to_s != [] then self.ithil_vr_attribute_past_to_all(mat)
        self.ithil_vr_attribute_past 
        end
model.commit_operation
end #ithil_vr_attribute_past_select 

def self.ithil_vr_attribute_past
        model = Sketchup.active_model
        material = model.materials.current
        IR.material_test (material)
        IR.ithil_vr_save_diffuse (material)
        url_new=ithil_vr_url_change(@@vr_Hac_test, @@vr_Hac_test_old_name, material.display_name)
        PythonBridge.direct_send("create_material_from_xml",[material.display_name, url_new,"1"])
        
new_name = material.name.gsub(/\(ST\)_/,'')
material.name = new_name
model.materials.current = material.name     
IR.ithil_vr_load_diffuse (material)


PythonBridge.direct_send("select_current_material",[material.display_name])

Sketchup.set_status_text "Done! Past V-ray material attribute" + material.display_name + " from " + @@vr_Hac_test_old_name
return
end #ithil_vr_attribute_past

def self.ithil_vr_attribute_past_to_all(mat)
        mat.each { |material|
        IR.ithil_vr_save_diffuse (material)
        url_new=ithil_vr_url_change(@@vr_Hac_test, @@vr_Hac_test_old_name, material.display_name)
        PythonBridge.direct_send("create_material_from_xml",[material.display_name, url_new,"1"])
        Sketchup.active_model.materials.current = material.name     
        IR.ithil_vr_load_diffuse (material)
        PythonBridge.direct_send("select_current_material",[material.display_name])
        }
return
end #ithil_vr_attribute_past_to_all

def self.ithil_vr_TexMap_copy
            model = Sketchup.active_model
        selection = model.selection
            material  = model.materials.current
item = selection[0] 
IR.vray_check
is_light = VRayForSketchUp.is_light( item )

if is_light == true #&&(selection.size == 1) # copy from vr-light
            @@vr_Hac_test = VRayForSketchUp.get_vfs_light_attribute( item )
            root_name = @@vr_Hac_test[/(?:url="\/)([^\/]*?)(?:\/)/,1]
else

    IR.material_test (material) 
    root_name = material.display_name.gsub('<','&lt;').gsub('"','&quot;')

    IR.ithil_vr_attribute_copy
    IR.ithil_vr_save_diffuse (material) 
end #if
    
    shablon = /#{'(?:<Asset renderer="vray" url=")([^"]+?)" type="texture"(?:(?!TexCombineColor).)*?/Asset>'}/m
    all_map_in_material = []
    if @@vr_Hac_test  == nil
  UI.messagebox("Maps not found!")
     return
    end # if
    all_map_in_material = @@vr_Hac_test.scan(shablon).map{ |item| item.join } 
all_map_in_material = all_map_in_material 

    textur_var = @@vr_Hac_test.gsub('<Assets>','').gsub('/</?Assets>/','').scan(/#{'<Asset.*?</Asset>'}/m)
    textur_var_temp = textur_var
        all_slot_in_material = []
        all_slot_in_material = all_map_in_material.map{|url| IR.full_url_to_name(url)}
        massiv = Array.new
        all_slot_in_material.each_index{|i| #создаем  хеш для возврата в корректном виде из меню выбора
            massiv << IR.format_menu_string(all_slot_in_material[i]) # форатирование текста
            massiv << all_map_in_material[i] }
        hash_slot_materia = Hash[*massiv]
        if all_slot_in_material.size == 0
                    UI.messagebox("Maps not found!")
                return
        end # if
        all_slot_in_material = IR.cleaning_menu(all_slot_in_material)
        all_slot_in_material.sort!
        
        
        prompts = ['Map to copy']
        
        if all_slot_in_material.size == 1
        defaults = [all_slot_in_material[0]]
        else
        defaults = ['Enter name']
        end # if
        
        newname = all_slot_in_material.reverse.join("                   |")
        newname = all_slot_in_material[0]+ '          ' if all_slot_in_material.size == 1
in_str = "material ( #{material.name.gsub(/[\"\[\]]/ ,"")} )" if material != nil
in_str = "( #{item.name} )" if (is_light && selection.size == 1)

        result = UI.inputbox(prompts, defaults, [newname], "Copy map from #{in_str}")
        return if result == false
        return if result == ['Enter name']
        result_s = result.join.rstrip
    
    select = hash_slot_materia[result_s]
    user_select = select[1..-1]
        child_list =[]
        child_list = @@vr_Hac_test.scan(/#{'(?:<value>)(.' + IR.escape_meta(root_name) + '.*?)(?:</value>)'}/) 
            child_list.each_index {|x|
                child_list[x] = child_list[x].join if child_list[x] != nil
                child_list[x] = nil if child_list[x].include?(user_select) == false
            }
          child_list.compact!
          child_list_escape = child_list.map{|i| IR.escape_meta(i)}

                    all_child_in_regexp = "(url=\\\"#{child_list_escape.join'\")|(url=\"'}\\\")"
    textur_var_copy =[] 
            textur_var_temp.each_index {|x|
            textur_var_copy.push (textur_var_temp[x]) if textur_var_temp[x].to_s.scan(/#{all_child_in_regexp}/).size > 0
          }
        $ith_mat_texture  = textur_var_copy # ушло в блок вставки.
        $ith_user_select = user_select  # откуда было скопированно

        if (textur_var_copy.size == 0)   # проверяем корректность
            UI.messagebox("Copy error! 
            user_select = (#{user_select.gsub('&lt;','<')})
            select = (#{select.gsub('&lt;','<')})")
            return
        end 
end #ithil_vr_TexMap_copy






def self.ithil_vr_TexMap_past
    model = Sketchup.active_model
    material  = model.materials.current

        past_to_light = false
        selection = model.selection

item = selection[0] 
is_light = VRayForSketchUp.is_light( item )
if is_light && selection.size == 1
            @@vr_Hac_test = VRayForSketchUp.get_vfs_light_attribute( item )
            root_name = @@vr_Hac_test[/(?:url="\/)([^\/]*?)(?:\/)/,1]
            past_to_light = true
    else
    IR.material_test (material)
    IR.ithil_vr_attribute_copy
    IR.ithil_vr_save_diffuse (material)
    root_name = material.display_name.gsub('<','&lt;').gsub('"','&quot;')
end #if

    textur_var = @@vr_Hac_test.gsub('<Assets>','').gsub('</Assets>','').split('</Asset>') # Режем на куски атрибут
    textur_var.each_index {|x| textur_var[x] = textur_var[x] + '</Asset>' }
    textur_var_copy = textur_var


    shablon = /#{'(?:<parameter handler="TextureHandler" listType="none" type="plugin" name=")(.+?)(?:")'}/
    all_handler_in_material = []
    all_asset = []
    all_asset = @@vr_Hac_test.scan(/#{'<Asset.*>[^\r]*?</Asset>'}/)
    all_slot = []
    all_url = []

        all_asset.each{|asset|
            
            
            asset_name = asset.match('(?:vrayplugin.*?name=")(.*?)(?:">)')[1]
            texture_test = asset.match(/#{'((?:<Asset renderer="vray" url="[^"]*/(Texture)\d{,2}").*?type="texture".*?<parameters>)'}/m)


            next if (asset_name =~ /TexCombineColorp|TexAColorO/ ) && (texture_test == nil)
            @asset_layout =  asset.match('(?:Asset renderer.*?layout=")(.*?)(?:">)')[1] #"ReflectionLayer"
            url = asset.match('(?:Asset renderer.*?url=")(.*?)(?:")')[1]
            
            all_slot_in_asset = []
            all_label_in_asset = []
            asset.scan(/#{'(<.*?handler="(?!DoubleSpinBoxHandler).*?"(?:float|acolor) texture.*?name="(.*?)".*label="(.*?)".*>)'}/).map{|a|
                    all_slot_in_asset << a[1]
                    all_label_in_asset <<  a[2]

                } 
    all_slot_in_asset.each_index{|i| 
        
        if all_label_in_asset[i] != 'Texture' # Выбираем более информативный вариант 
        suf = all_label_in_asset[i]
        else
        suf = all_slot_in_asset[i]
        end

    next if ['alpha_tex','bump_tex_mult_tex'].include? (all_slot_in_asset[i]) and @asset_layout == 'defvrmat'
        all_slot << IR.format_menu_string("#{IR.full_url_to_name(url)}(#{suf})")
        all_url << url + '***' + all_slot_in_asset[i]
        }

    }
    

            hash_slot_materia = {}       #создаем  хеш для возврата в корректном виде из меню выбора

            all_slot.each_index{|i|
            hash_slot_materia[all_slot[i]]  =   [i]}

        massiv = Array.new
        all_slot.each_index{|i| #создаем  хеш для возврата в корректном виде из меню выбора
            massiv << all_slot[i]
            massiv << all_url[i] }
            
    all_map_in_material= @@vr_Hac_test.scan(shablon) #(all map in material Maps)

     
    all_map_in_material.each_index{|i|
    next if ['alpha_tex','bump_tex_mult_tex','gi_tex'].include? (all_map_in_material[i].join)
        massiv << IR.format_menu_string(" (#{all_map_in_material[i].join.capitalize})")
        massiv << all_map_in_material[i].join+"***"+all_map_in_material[i].join
        }
        hash_slot_materia = Hash[*massiv]   

    map_tip_1 = all_slot.sort
    all_handler_in_material = hash_slot_materia.keys
    all_handler_in_material = IR.cleaning_menu(all_handler_in_material) # Чистим не читаемые и то что нельзя выбрать
    all_handler_in_material.sort!

     
     copi_tip_aray = ['Copy','Swap'] 
    if  $ith_user_select == nil
    copi_tip_aray.delete('Swap')
    end 

      if all_handler_in_material.size > 15   # limit
        newname = 'None|' + all_handler_in_material.reverse.join("|") + '|None'  
        newname_short = IR.cleaning_short_menu(all_handler_in_material)
        prompts = ['Full list','Short list','Tip']
        defaults = [ 'None' ,'None', 'Copy' ]
        str_out = "material ( #{material.name.gsub(/[\"\[\]]/ ,"")} )" if material != nil
        str_out = "( #{item.name} )" if (is_light && selection.size == 1)
        result = UI.inputbox(prompts, defaults, [newname,"None|#{newname_short.reverse.join("|")}|None",copi_tip_aray.join("|")], "Past map to#{str_out}")
        return if result == false

        if (result[0] == 'None') and (result[1] == 'None')
                    UI.messagebox("Please, select any slot!")
                return
        end # if
            if (result[0] != 'None') and (result[1] != 'None')
                    UI.messagebox("Please, select only one slot!")
                return
        end # if
        if (result[0] == 'None')
            result_s = result[1].rstrip
        end # if
        
        if (result[1] == 'None')
            result_s = result[0].rstrip
        end # if
        copi_tip = result[2]
    else 
        newname = 'None|' + all_handler_in_material.join("|")
        prompts = ['Full list','Tip']
        defaults = [ 'None', 'Copy' ]
        result = UI.inputbox(prompts, defaults, [newname,copi_tip_aray.join("|")], "Past map to material (#{material.name.gsub(/[\"\[\]]/ ,"")})")
        return if result == false
            if (result[0] == 'None') 
                    UI.messagebox("Please, select any slot!")
                return
        end # if
        result_s = result[0].rstrip
        copi_tip = result[1]
    end # if    

        user_url_select = hash_slot_materia[result_s].split('***')[0]
        user_slot_select = hash_slot_materia[result_s].split('***')[1]

        if all_map_in_material.flatten.index(user_url_select) != nil # материал из слотом матс а не из слоев меняем  данные
            substitution_method = 'mat tip'
            user_slot_select = user_url_select
            name_zamena = IR.check_the_available_url("/#{root_name.gsub(/[\"\[\]]/ ,"")}/Texture")
            name_zamena = IR.check_the_available_url("/#{root_name}/Texture")
            
        else #if
            substitution_method = 'layer tip'
            name_zamena = IR.check_the_available_url(user_url_select+'/Texture')      # меняем ссылку на вставку на новое значение отправяем на проверку и правку урл 
        end #if

        #получаем блок
        textur_var_new_part = [] 
        textur_var_new_part = $ith_mat_texture  #Забираем скопированную часть атрибута 
            if (textur_var_new_part== nil)   # проверяем корректность
                UI.messagebox("Please, copy texture before!")
                return
            end 

        # выводим рутнейм из импортированного или вставленного куска атрибута

    scan_root_name = textur_var_new_part[0].scan(/#{'(?:vray" url="/).+?(?:")'}/).join.split('/')
    textur_var_root_name = scan_root_name[1]
    if $ith_user_select != nil
    textur_var_old_url_name = $ith_user_select # Адрес выбранный юзером при копиовании
    else # адреса нет - импортированный кусок
    array = IR.all_url_in_part ($ith_mat_texture)
    min = array.map {|item| item[1..-1].split('/').size }.min # минимальный  общий  предок
    textur_var_old_url_name = array[0][1..-1].split('/')[0,min].join('/')
    end #if


    array = IR.all_url_in_part (textur_var_new_part)
    replacement_array = IR.replacement_url_in_array(array,'/'+ textur_var_old_url_name, name_zamena) 

    if copi_tip == 'Copy' 

    textur_var_new_part_fix = textur_var_new_part.join
      array.each_index{|i| textur_var_new_part_fix.gsub!(array[i] ,replacement_array[i])} #new
        attribute = textur_var_new_part_fix + textur_var.join 
      attribute_new = "<Assets>
    " + attribute.insert(-2, 's')

    else #'Swap'
      attribute = textur_var.join
      attribute_new = "<Assets>
    " + attribute.insert(-2, 's')
        attribute_new.gsub!('>/'+textur_var_old_url_name+'</value>','></value>')  # удалили старое значение из слота
        array.each_index{|i| attribute_new.gsub!(/#{IR.escape_meta(array[i]) + '(?=(\"|</value>))'}/,replacement_array[i])} 
    end #if
    
     @@ColorTexFrameHandler_test =[] # Для проверки  
    
     if substitution_method == 'layer tip'
     
     asset = IR.asset_by_url attribute_new, user_url_select
    asset_pravlen = self.change_parameter_by_name asset, user_slot_select, name_zamena
    attribute_new.gsub!(asset,asset_pravlen)
    attribute_new = change_parameter_by_name attribute_new, "trace_refractions_dummy" , "1" if !past_to_light
    else
     case user_url_select
      
    when 'bump_tex'  

      attribute_new = self.change_parameter_by_name attribute_new, "bump_on", "1"
      attribute_new = self.change_parameter_by_name attribute_new, "bump_tex", name_zamena

      when 'displace_tex'  
      attribute_new = self.change_parameter_by_name attribute_new, "displace_on", "1"
      attribute_new = self.change_parameter_by_name attribute_new, "displace_tex", name_zamena

     when 'bg_tex'  
      attribute_new = self.change_parameter_by_name attribute_new, "override_bg", "1"
      attribute_new = self.change_parameter_by_name attribute_new, "bg_tex", name_zamena

     when 'reflect_tex'  
      attribute_new = self.change_parameter_by_name attribute_new, "override_reflect", "1"
      attribute_new = self.change_parameter_by_name attribute_new, "reflect_tex", name_zamena

     when 'refract_tex'  
      attribute_new = self.change_parameter_by_name attribute_new, "override_refract", "1"
      attribute_new = self.change_parameter_by_name attribute_new, "refract_tex", name_zamena

             else 
             return
        end 
    end #if
    attribute_new.gsub!(@@ColorTexFrameHandler_test[0],@@ColorTexFrameHandler_test[1]) if @@ColorTexFrameHandler_test != []
    attribute_new.gsub!(/#{'>\s+?<value><\/value>\s+?<\/parameter>'}/m,'/>')  # закрываем пустые слоты



    PythonBridge.direct_send("create_material_from_xml",[material.display_name, attribute_new,"1"]) if !past_to_light
    if past_to_light
    vfs_dictionary = item.attribute_dictionary(VRayForSketchUp::VFS_PRODUCT_GUID, true)
            if vfs_dictionary != nil
                vfs_dictionary[VRayForSketchUp::VFS_LIGHT_ATTRIBUTE] = attribute_new
                else 
                return
            end
            VRayForSketchUp.change_observer(VRayForSketchUp::VfSDefinitionsObserver,VRayForSketchUp.active_model.definitions)
            if PythonBridge.is_rt_active()
                PythonBridge.direct_send( "edit_light", [attribute_new] )
            end # if
    else
        model.materials.current = material.name 
IR.ithil_regenerate_previews
    return
    
    end # if past_to_light

end #ithil_vr_TexMap_past

def self.ithil_vr_TexMap_save

texture = $ith_mat_texture 

    if texture == nil
        UI.messagebox("Please, copy texture before!")
        return 
    end# if
model = Sketchup.active_model
model.start_operation("Save VRMAT part", true)
Sketchup.set_status_text "Program is running..."
material = model.materials.current
    filename = UI.savepanel("Save the VRMAT file", "", "#{material.name}_part.vrpart")
    return if filename.nil?
                vrmat_file = File.new(filename, "w")
                            vrmat_file.write(texture.join)
                            vrmat_file.close
model.commit_operation
end #ithil_vr_TexMap_save


def self.ithil_vr_TexMap_load
model = Sketchup.active_model
model.start_operation("Import VRMAT from folder", true)
Sketchup.set_status_text "Program is running...  Select file in the folder"

filename = UI.openpanel("Open File", "","Vrpart and Image Files|*.vrpart;*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;|Vrpart Files|*.vrpart;|Image Files|*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;||")
return if filename == nil
    
        filename = ithil_vr_import_by_linked_image filename, 'vrpart'
    

Sketchup.set_status_text "Program is running..."
         import_texture = IO.read(filename).split(/\s*(?=<Asset )/)
        del_temp=import_texture.shift
        $ith_mat_texture = import_texture
        $ith_user_select = nil
    
end #ithil_vr_TexMap_save

def self.ithil_vr_past_hex_color
        model = Sketchup.active_model
        model.start_operation('Past HEX color',true)
        material = model.materials.current
        IR.material_test (material)
        Sketchup.set_status_text "Enter your color. (#FFAABB, FFAABB, #ffaabb, ffaabb)"
    value = ['']
    prompts = ['Past color']
        results = inputbox prompts, value, "Insert HEX color"
            
check_result = results.join.[](/#{'^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$'}/)
    if check_result == nil
        UI.messagebox("Please, enter the correct value!")
        return 
    end# if
hex_color = check_result.gsub('#','')

r = hex_color[0,2].hex
g = hex_color[2,2].hex
b = hex_color[4,2].hex
material.color = Sketchup::Color.new(r,g,b)
            model.commit_operation
            Sketchup.set_status_text "Done!"

end # def

def self.ithil_vr_url_change(xml,old_url,new_url) # заменяем старый URL в XML перед вставкой в материал
        return xml.gsub(old_url, new_url).gsub(/(\<preview\>).*?(\<\/preview\>)/, "")
    end #ithil_vr_url_change

def self.get_vfs_material_attribute( skp_mat )
        return nil if nil == skp_mat
        vfs_dictionary = skp_mat.attribute_dictionary(VRayForSketchUp::VFS_PRODUCT_GUID, false)
            if nil == vfs_dictionary or vfs_dictionary.length <= 0
               return nil
            end
            return vfs_dictionary[VRayForSketchUp::VFS_MATERIAL_ATTRIBUTE]
    end #get_vfs_material_attribute

def self.material_test (material)
IR.vray_check
    model = Sketchup.active_model
    if material == nil
        UI.messagebox("Please, select any material!")
        return 
    end# if
    
    if material.display_name[/[\/\\"]/] 
        UI.messagebox("Please, rename material \' #{material.display_name} \'!
Remove \' #{material.display_name.scan(/[\/\\"]/).join(' , ')} \' or use \"Fix Material Name\"")
        exit
    end# if
    if !model.materials.include?( material )
        UI.messagebox( "Select a material already in the model. Not from the libraries." )
        exit
    end
end #material_test

def self.ithil_vr_save_diffuse (material)
    IR.material_test (material)
if (material.respond_to?(:texture))
@@ith_copy_texture_use = material.texture
else 
@@ith_copy_texture_use = nil
@@ith_copy_texture = nil
end if

@@ith_copy_alpha = material.alpha

@@ith_copy_color_red = material.color.red
@@ith_copy_color_green = material.color.green
@@ith_copy_color_blue = material.color.blue


if @@ith_copy_texture_use
texture_filename = @@ith_copy_texture_use.filename
rashir = texture_filename.[](/(\.(jpg|jpeg|tga|png|bmp|psd|gif|tiff|tif)$)/i)

    file_name="/"+material.display_name.gsub(/({\w+}_)|(\(ST\)_)/,'').gsub(/[\/\\\:\*\?\«\\<>\|]/,'_').gsub(/(_\b|\b_)/,'').gsub(/_{2,}/,'_')+rashir
    model = Sketchup.active_model
  path=model.path
  if not path or path==""
    name="Untitled"
    output=File.join(Dir.pwd,name).tr("\\","/")
  else
    name=model.title
    output=File.join(File.dirname(path),name).tr("\\","/")
  end
@@ith_copy_texture = output+file_name
@@ith_copy_texture_width = material.texture.width
@@ith_copy_texture_height = material.texture.height
Dir.mkdir(output) unless File.exist?(output)

  group=model.entities.add_group
  tw = Sketchup.create_texture_writer


    if material.texture
      group.material= material
      tw.load(group, true)
    end

 tw.write(group, @@ith_copy_texture, true) 
  group.erase! if group.valid?
end 

end #ithil_vr_save_diffuse


def self.ithil_vr_load_diffuse (material)
                    material.alpha = @@ith_copy_alpha
     if @@ith_copy_texture_use
                        material.texture=@@ith_copy_texture
                        material.texture.size=[@@ith_copy_texture_width,@@ith_copy_texture_height]
    else material.texture = nil
        material.color = Sketchup::Color.new((@@ith_copy_color_red),( @@ith_copy_color_green),(@@ith_copy_color_blue))

    end # if
end # def ithil_vr_load_diffuse

def self.ithil_insert_tag
    model = Sketchup.active_model
    material = model.materials.current
    selection = model.selection

    tag = nil
    if material != nil
    IR.material_test (material) 
    tag = material.display_name.scan(/{[^}]+}/)[0]
    end #if

                mat=[]
    if tag == nil
    if selection.empty? and tag == nil
            result = UI.messagebox('Add a {TAG} to all materials model?', MB_YESNO)
         if result == IDNO
            return
         else
          mat = model.materials
         end #if
    end #if
    
                model.start_operation('Rename Materials',true)
                Sketchup.set_status_text "Program is running..."

                if mat == []
                mat = self.find_material_in_selection mat, selection, {} 
                end
               newname = ['GROUP']
               prompts = ['New name']
                    results = inputbox prompts, newname, "Ithil Materials Renamer"
                    return if not results
                    result_to_string = results.to_s.gsub(/[\"\[\]]/ ,"")
            mat.each { |m|
            old_name = m.name
            if !old_name[/{[^}]+}/]
            new_name = old_name.gsub(/(\{).*(\})/,'').gsub(/^_+/,'').gsub(/[\"\[\]]/ ,"")
            m.name = "{#{result_to_string.upcase.gsub(/(_+|\s)/ ,"_")}}_#{new_name.gsub(/(_+|\s)/ ,"_")}"
            end
             }
            model.commit_operation
            Sketchup.set_status_text "Done!"
    else 

        prompts = ["Target"]
        defaults = ["Remove #{tag} from all materials"]
        values = ["Remove #{tag} from all materials"]
        values << "Remove {ALL TAGS} from all materials"
        values << "Remove #{tag} from transparent materials"
        values << "Remove #{tag} from material with textures"
        values << "Remove #{tag} from solid material"
        values << "Remove #{tag} from active material"

        results = UI.inputbox( prompts, defaults, [values.join('|')] , "Remove tag "+ tag)
        return nil if not results
        tip = results[0]

        Sketchup.active_model.start_operation('Find and Remove tag',true)
            case tip
                when "Remove #{tag} from all materials"

                Sketchup.active_model.materials.each { |m| m.name = m.name.gsub(tag+"_",'')}
                
                when "Remove {ALL TAGS} from all materials"
            
                Sketchup.active_model.materials.each { |m|  tag = m.display_name[/(\{).*(\})/] ; m.name = m.name.gsub(tag+"_",'') if tag != nil}
                                
                when "Remove #{tag} from transparent materials"
                                    Sketchup.active_model.materials.each { |m|
                        if m.respond_to?(:alpha) 
                            m.name = m.name.gsub(tag+"_",'') if m.alpha < 1
                        end #if 
                    }                       
                when "Remove #{tag} from material with textures"
                    Sketchup.active_model.materials.each { |m|
                        if m.respond_to?(:texture) 
                            m.name = m.name.gsub(tag+"_",'') if m.texture != nil
                        end #if             
                    }   
                when "Remove #{tag} from solid material"
                    Sketchup.active_model.materials.each { |m|
                        if m.respond_to?(:texture) 
                            m.name = m.name.gsub(tag+"_",'') if m.texture == nil
                        end #if             
                    }   
                when "Remove #{tag} from active material"
                    
                            material.name = material.name.gsub("#{tag}_",'')

                end #case
        Sketchup.active_model.commit_operation
    
    end #if
end # ithil_insert_tag

def self.progresbar (ent)

@@aray_all = @@aray_value = ent.size if ent !='next'
@@aray_value = @@aray_value - 1 if ent =='next'
# 
Sketchup.set_status_text "Program is running : " + (@@aray_all - @@aray_value).to_s + " from " + @@aray_all.to_s

end #progresbar
def self.ithil_vr_mark_standart_material
    IR.vray_check
    model = Sketchup.active_model
    model.start_operation('Rename Materials',true)
    Sketchup.set_status_text "Program is running..."

            progresbar (model.materials)
            model.materials.each { |mat|
            progresbar ('next')
                vfs_dictionary = ""
                vr_attribute_size = 0
                attribute = get_vfs_material_attribute( mat )
                    if attribute == nil
                    mat.name = '(ST)_' + mat.name
                    next
                    end# if
                    dif_tex_test = 0
                    dif_tex_test = attribute.scan(/url="[^"]*Texture[^"]*Bitmap"/).size 
                    if dif_tex_test == 0
                        tipM = "solid"
                        min_size = 3
                    else 
                        tipM = "texture"
                        min_size = 6
                    end #if
                    
                    new_name = mat.name.gsub(/\(ST\)_/,'')
                                                #.scan('Asset renderer').size
                vr_attribute_size = attribute.split('</Asset>').size

                if vr_attribute_size > min_size 
                    mat.name = new_name
                else 
                    mat.name = '(ST)_' + new_name
                end #if

                }

model.commit_operation
Sketchup.set_status_text "Done!"
end # ithil_vr_mark_standart_material

def self.ithil_convert_standart_tag
IR.vray_check
    model = Sketchup.active_model
    model.start_operation('Rename Materials',true)
    Sketchup.set_status_text "Program is running..."
    progresbar (model.materials)
Sketchup.active_model.materials.each_with_index { |m,i| progresbar ('next')
m.name = m.name.gsub('(ST)_','{ST}_') }
model.commit_operation
Sketchup.set_status_text "Done!"
end # ithil_convert_standart_tag

def self.ithil_clipping_plane
IR.vray_check
model = Sketchup.active_model
model.start_operation('Camera clipping plane',true)
url = "/RenderView"

ithil_setup_unit_format

clip = VRayForSketchUp.get_option_value( url, "clipping", "bool")
    clip_val = "Yes" if clip == true
    clip_val = "No" if clip == false
near = VRayForSketchUp.get_option_value( url, "clipping_near", "float")
far = VRayForSketchUp.get_option_value( url, "clipping_far", "float" )

        prompts = ["Clipping","Near clipping plane (#{@unit_name})","Far clipping plane (#{@unit_name})"]
        defaults = [clip_val,(near/@unit_kor).to_i,(far/@unit_kor).to_i]
        values = ["Yes|No","",""]
        results = UI.inputbox( prompts, defaults, values, "Clipping plane")
            return nil if not results
        clip_new = true if results[0] == "Yes"
        clip_new = false if results[0] == "No"
        near_new = results[1].to_f * @unit_kor
         far_new = results[2].to_f * @unit_kor
        VRayForSketchUp.set_option_value( "/RenderView", "clipping", "bool", clip_new)
        VRayForSketchUp.set_option_value( "/RenderView", "clipping_near", "float", near_new)
        VRayForSketchUp.set_option_value( "/RenderView", "clipping_far", "float", far_new)
model.commit_operation
Sketchup.set_status_text "Done!"
end # def ithil_clipping_plane

def self.ithil_vr_set_max_subdivs
        model = Sketchup.active_model
        IR.vray_check
                model.start_operation("Set V-ray Subdivs to all materials", true)
    newname = ['20']
    prompts = ['Max Subdivs']
        results = inputbox prompts, newname, "Set Max Subdivs in All Material"
        return nil if not results
        if (results.join.to_f.to_i == 0)
            UI.messagebox("Insert correct value!")
            return
        end 
            Sketchup.set_status_text "Program is running..."
            max_sub = results.join.to_f.to_i
            model.materials.each { |mat|
                vfs_dictionary = ""
                model.materials.current = mat.name  
                vr_attribute=get_vfs_material_attribute( mat )
                        str_sub=/(\"Subdivs\">\n      <value>)(\d+)(<\/value>)/
                    all_sub_in_mat=[]
                    all_sub_in_mat=vr_attribute.scan(str_sub).join.split('</value>').map{ |item| item.delete '"Subdivs\">\n      <value>' }
             all_sub_in_mat.each { |sub| vr_attribute.gsub!(str_sub, '"Subdivs\">\n      <value>'+max_sub.to_s+'</value>' ) if sub.to_i > max_sub.to_i}
            PythonBridge.direct_send("create_material_from_xml",[mat.display_name,vr_attribute,"1"])
            }
        model.commit_operation
Sketchup.set_status_text "Done!"
end #ithil_vr_set_max_subdivs


def self.ithil_vr_mark_max_subdivs_material
IR.vray_check
        model = Sketchup.active_model
                model.start_operation("Set V-ray Subdivs to all materials", true)
    newname = ['40']
    prompts = ['Threshold Value Subdivs']
        results = inputbox prompts, newname, "Mark Max Subdivs in Material"

        if (results.join.to_f.to_i == 0)
            UI.messagebox("Insert correct value!")
            return
        end 
            Sketchup.set_status_text "Program is running..."
            max_sub = results.join.to_f.to_i
            model.materials.each { |mat|
                vfs_dictionary = ""
                model.materials.current = mat.name  
                vr_attribute=get_vfs_material_attribute( mat )
                        if vr_attribute == nil
                            next 
                            end #if
                    str_sub=/(\"Subdivs\">\n      <value>)(\d+)(<\/value>)/
                    max_sub_in_mat=vr_attribute.scan(str_sub).join.split('</value>').map{ |item| item.delete '"Subdivs\">\n      <value>' }.max.to_f.to_i
                    mat.name=mat.name.gsub(/\(SUB:\d+?\)_/,'')
                    if max_sub_in_mat > max_sub
                        mat.name = mat.name
                        mat.name = "(SUB:#{max_sub_in_mat})_" + mat.name
                    end #if
            }
        model.commit_operation
Sketchup.set_status_text "Done!"
end #ithil_vr_mark_max_subdivs_material

def self.ithil_vr_interpolation_off
IR.vray_check
model = Sketchup.active_model
model.start_operation("Turn off interpolation in all materials", true)
Sketchup.set_status_text "Program is running..."

model.materials.each { |mat|
                vfs_dictionary = ""
                model.materials.current = mat.name  
                vr_attribute=get_vfs_material_attribute( mat )
                patern ="nterpolation\">\n      <value>1</value>"
                new_value ="nterpolation\">\n      <value>0</value>"    
                vr_attribute.gsub!(patern,new_value)
            PythonBridge.direct_send("create_material_from_xml",[mat.display_name,vr_attribute,"1"])
            }
model.commit_operation
Sketchup.set_status_text "Done!"
end #ithil_vr_interpolation_off

def self.ithil_vr_displacement_off
IR.vray_check
model = Sketchup.active_model
model.start_operation("Turn off Displacement in all materials", true)
Sketchup.set_status_text "Program is running..."

model.materials.each { |mat|
                vfs_dictionary = ""
                model.materials.current = mat.name  
                vr_attribute=get_vfs_material_attribute( mat )
                patern ="\"Displacement\">\n      <value>1</value>"
                new_value ="\"Displacement\">\n      <value>0</value>"  
                vr_attribute.gsub!(patern,new_value)
            PythonBridge.direct_send("create_material_from_xml",[mat.display_name,vr_attribute,"1"])
            }
model.commit_operation
Sketchup.set_status_text "Done!"
end #ithil_vr_interpolation_off

def self.ithil_vr_displacement_to_bump
IR.vray_check
model = Sketchup.active_model
model.start_operation("Turn off Displacement in all materials", true)
Sketchup.set_status_text "Program is running..."

otchet = []
model.materials.each { |mat|
                vfs_dictionary = ""
                model.materials.current = mat.name  
                vr_attribute=get_vfs_material_attribute( mat )
            displace_on_value = vr_attribute[/<parameter[^>]+name="displace_on".*?<value>([^<]*?)<\/value>.*?<\/parameter>/m,1]
if displace_on_value == '1'
            else
                next # no disp in mat
            end # if
            displace_tex_old = vr_attribute[/(<parameter[^>]+label="displace_tex">.*?<value>([^<]*?)<\/value>.*?<\/parameter>)/m]
            displace_tex_value = Regexp.last_match[2]
            bump_old_value = vr_attribute[/<parameter[^>]+label="bump_tex">.*?<value>[^<]*?<\/value>.*?<\/parameter>/m]
            bump_new_value = bump_old_value.gsub(/<value>[^<]*?<\/value>/,'<value>'+displace_tex_value+'</value>')
            displace_tex_new = displace_tex_old.gsub(/<value>[^<]*?<\/value>/,'<value></value>')

          attribute_new = vr_attribute.sub(bump_old_value , bump_new_value).sub(displace_tex_old , displace_tex_new)
          attribute_new = self.change_parameter_by_name attribute_new, "bump_on", "1"
          attribute_new = self.change_parameter_by_name attribute_new, "displace_on", "0"
otchet << mat.display_name 
            PythonBridge.direct_send("create_material_from_xml",[mat.display_name,attribute_new,"1"])
            }
model.commit_operation
Sketchup.set_status_text "Done!"
            if otchet.size != 0
                UI.messagebox("Changed materials:\n#{otchet.join(', ')}",MB_MULTILINE)
                return
            end # if
end #ithil_vr_displacement_to_bump

def self.ithil_regenerate_previews
    model = Sketchup.active_model
        mat  = model.materials.current
        mat.name = mat.name + '+temp+name+'
        mat.name = mat.name.gsub('+temp+name+','')
end #ithil_vr_displacement_to_bump



def self.ithil_vr_change_the_path
IR.vray_check
model = Sketchup.active_model
model.start_operation("Change the path to the texture in all materials", true)
Sketchup.set_status_text "Program is running..."
filename = UI.openpanel("Open File", "","Image Files|*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;|")
        return if filename == nil
        folder=File.dirname(filename)
        folder_alt = folder.gsub('\\','/')
path_new = folder+'\\'
    model.materials.each { |mat|
        vfs_dictionary = ""
        model.materials.current = mat.name  
        vr_attribute=get_vfs_material_attribute( mat )
        patern = '[a-zA-Z]\:(\\|\/)'

        new_attribute = vr_attribute.gsub(/#{'[a-zA-Z]:[\|/](?:[^\\/:*?"<>]+[\|/])*'}/) {path_new}
        PythonBridge.direct_send("create_material_from_xml",[mat.display_name,new_attribute,"1"])
    }
    model.commit_operation
    Sketchup.set_status_text "Done!"
end #ithil_vr_change_the_path

def self.ithil_vr_change_the_path_vrmesh
IR.vray_check
model = Sketchup.active_model
model.start_operation("Change the path to the texture in all materials", true)
    selection = model.selection
    selection = model.active_entities if selection.empty?
Sketchup.set_status_text "Program is running..."
filename = UI.openpanel("Open File", "","Vrmesh Files|*.vrmesh;|")
        return if filename == nil
        folder=File.dirname(filename).gsub(/[\\]/,'/') + '/'
         Dir.chdir(folder)
            vrmat_list=Dir["*.vrmesh"] 
            if vrmat_list.size == 0
                UI.messagebox("Not found Vrmesh files in a folder")
                return
            end # if
@vrmesh_list = []
process_at_leve_change_the_path_vrmesh  folder, selection, {}
    
lost = []
if @vrmesh_list.length > 0  
@vrmesh_list.uniq! 
@vrmesh_list.sort
@vrmesh_list.each_index { |i| lost << File.basename(@vrmesh_list[i]) if FileTest::exists?(@vrmesh_list[i]) == false}
end # if
if lost.size > 0
Sketchup.send_action "showRubyPanel:"
UI.messagebox("Not found #{lost.size} Vrmesh file#{'s' if lost.size > 1} in a folder.")
puts ' Search template:'
puts '_'*40
puts "(=#{lost.join(')OR(=')})"
            end # if

    model.commit_operation
    Sketchup.set_status_text "Done!"
end #ithil_vr_change_the_path_vrmesh

def self.process_at_leve_change_the_path_vrmesh(path_new, entities, hcomp)
    entities.each do |entity| 
        current_selection = entity
        is_proxy = VRayForSketchUp.is_proxy( entity) 
        case entity.typename
        when 'Group'
        
          if is_proxy 
        proxy_xml = VRayForSketchUp.get_vfs_proxy_attribute( entity )
        proxy_xml_doc = VRayXML::QDomDocument.new proxy_xml
        proxy_xml_node = VRayForSketchUp.find_asset_of_type_in_doc( proxy_xml_doc, "geometry" )
        originalProxyPath = oldProxyPath = VRayForSketchUp.get_param_value_as_text( proxy_xml_node, "file", "string" )
        oldPath = originalProxyPath[/([a-zA-Z]\:\/[^.]*\/)/]
       newVRMeshPath = originalProxyPath.gsub(oldPath,path_new)
        if newVRMeshPath.length > 0
        @vrmesh_list << newVRMeshPath
                proxy_file_path_param = VRayForSketchUp.make_string_parameter_xml("file", newVRMeshPath)
                VRayForSketchUp.replace_parameter_in_xml_node(proxy_xml_node, proxy_file_path_param) 
                proxy_xml = proxy_xml_doc.to_s
                VRayForSketchUp.set_vfs_proxy_attribute( entity, proxy_xml )
            end
        end
            process_at_leve_change_the_path_vrmesh path_new, entity.entities, hcomp
        when 'ComponentInstance'
      
            edef = entity.definition
            next if hcomp[edef.to_s]
            hcomp[edef.to_s] = edef
            process_at_leve_change_the_path_vrmesh path_new, edef.entities, hcomp

        end
    end
end 



def self.ithil_replace_all_vrmat
IR.vray_check
model = Sketchup.active_model
model.start_operation("Replace all VRMAT from folder", true)
Sketchup.set_status_text "Program is running...  Select any VRMAT file in the folder"

filename = UI.openpanel 'Open File'
return if filename == nil
materials_in_scene = []
model.materials.each { |m| materials_in_scene.push (m.name.to_s) }
    if not filename
      puts "REPLACE ALL - CANCELED."
      Sketchup.send_action("selectSelectionTool:")
      return nil
    end #if
     if filename.to_s.downcase.index(".vrmat") == nil
        UI.messagebox ("Select any VRMAT file in the folder!")
        return
     end #if

prompts = ["Replace all the materials?"]
        defaults = ["All"]
        values = ["All|Only (ST)"]
        results = UI.inputbox( prompts, defaults, values, "Replace all VRMAT from folder")
        return nil if not results
        tip = results[0]
     
Sketchup.set_status_text "Program is running..."
folder=File.dirname(filename)
 Dir.chdir(folder)
    vrmat_list=[]
    vrmat_list=Dir["*.vrmat"] 

vrmat_list.each { |vrmat|
vrmat_name = vrmat.gsub(".vrmat","").gsub(".VRMAT","")

if tip == 'All'
     if materials_in_scene.include?( vrmat_name )  
     model.materials.current = vrmat_name
        IR.ithil_vr_mat_select folder+'\\'+vrmat,"5"
    end #if
end #if

if materials_in_scene.include?( '(ST)_' + vrmat_name) 
 model.materials.current = '(ST)_' + vrmat_name
    IR.ithil_vr_mat_select folder+'\\'+vrmat,"5"
    else
    next
end #if




}
end #ithil_replace_all_vrmat

def self.ithil_import_all_vrmat
IR.vray_check
model = Sketchup.active_model
model.start_operation("Replace all VRMAT from folder", true)
Sketchup.set_status_text "Program is running...  Select any VRMAT file in the folder"

filename = UI.openpanel("Open File", "","Vrmat Files|*.vrmat;|Image Files|*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;||")
        return if filename == nil
        filename = ithil_vr_import_by_linked_image filename, 'vrmat'
materials_in_scene = []
model.materials.each { |m| materials_in_scene.push (m.name.to_s) }
    if not filename
      puts "IMPORT ALL - CANCELED."
      Sketchup.send_action("selectSelectionTool:")
      return nil
    end #if

Sketchup.set_status_text "Program is running..."
folder=File.dirname(filename)
 Dir.chdir(folder)
    vrmat_list=[]
    vrmat_list=Dir["*.vrmat"] 

 prompts = ["Texture width","Texture height"]
units = Sketchup.active_model.options["UnitsOptions"]["LengthUnit"]
case units
    when 0
    defaults = [600,600]
    unit_name = "Inches"
    kor = 1
    when 1
    defaults = [50,50]
    unit_name = "Feet"
    kor = 12
    when 2
    defaults = [2000,2000]
    unit_name = "mm"
    kor = 0.393700787401575
    when 3
    defaults = [200,200]
    unit_name = "cm"
    kor = 3.93700787401575
    when 4
    defaults = [2,2]
    unit_name = "m"
    kor = 39.3700787401575
end #case
        values = ["",""]
        
        results = UI.inputbox( prompts, defaults, values, "Default texture size( #{unit_name})")
        return nil if not results
        tip = results[0]
 texture_width = results[0].to_l*kor
texture_height = results[1].to_l*kor

vrmat_list.each { |vrmat|
vrmat_name = vrmat.gsub(".vrmat","").gsub(".VRMAT","")

in_scene = []

material = model.materials.add(vrmat_name)
 model.materials.current = vrmat_name
 

 if (material.materialType != 0 )
material.texture.size=[texture_width,texture_height]
end if

    IR.ithil_vr_mat_select folder+'\\'+vrmat,"5"
}
end #ithil_import_all_vrmat

def self.ithil_import_all_texture_and_convert_to_vrmat
        model = Sketchup.active_model
        model.start_operation('Import and Convert Image Files',true)
        materials=model.materials
        # open_and_Clear_Console
        IR.vray_check # << удалить  IR
        filename = UI.openpanel("Open File", "","Image Files*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff|*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;|")
        return if filename == nil
        folder=File.dirname(filename).gsub(/[\\]/,'/') + '/'
        file_select = File.basename(filename).gsub(/((_[a-z]{1,5})+?\.)|((\.)?jpg|jpeg|tga|png|bmp|psd|gif|tiff|tif)/i,'')

        folder_vrmat = File.dirname(__FILE__) + "/user_vrmat"
        Dir.chdir(folder_vrmat)
        vrmat_list = Dir["*.vrmat"] 
        vrmat_list.unshift("Load new") 
        vrmat_list.each{|vrmat| vrmat.gsub!('.vrmat','')}
        Dir.chdir(folder)
            file_list=Dir["*.{jpg,jpeg,tga,png,bmp,psd,gif,tif,tiff}"] 
            if file_list.size == 0
                UI.messagebox("Not found files in a folder")
                return
            end # if
            var = []

            all_file_in_string = '*'+file_list.join('*')
            all_suffix = all_file_in_string.downcase.scan(/(_[a-z]{1,5})+?(?=\.(?=jpg|jpeg|tga|png|bmp|psd|gif|tiff|tif))/i)
            sum_all_without_suffix = all_file_in_string.gsub(/\*(([\w\.\s]*)(_[a-z]{1,5})+(\.(jpg|jpeg|tga|png|bmp|psd|gif|tiff|tif)))/i,'').gsub(/^\*/,'').split('*').compact

            var << 'filename' + " (#{sum_all_without_suffix.size.to_s})" if sum_all_without_suffix.size > 0
            if all_suffix.size > 0
            all_suffix.uniq! if all_suffix.size !=1
                all_suffix.flatten! 
                all_suffix.sort.each {|i| patrn = i.to_s+'\.\w{3,4}'
                sum = all_file_in_string.scan(/#{patrn}/i).size
                var << 'filename'+ i.to_s + "(#{sum})"
                }                   
                end # if

            all_mask = all_file_in_string.downcase.scan(/(?<=[*])[^*_\s]+(?=[_\s]\w+\w{1,5}\.\w{3,4})/).flatten.uniq
            mask = ['All file',file_select]
                all_mask.sort.each {|i| patrn = i.to_s+'[_\s]'
                    sum = all_file_in_string.scan(/#{patrn}/i).size
                    mask << i.to_s + "(#{sum})"
                }   
            
            
self.ithil_setup_unit_format 

        
        prompts = [] ; defaults = [] ;  values = []
        
        #[0]
        prompts << "Apply VR attribute"
        values  << "Yes|No"
        defaults << 'Yes'
        
        #[1]
        prompts << "Vr Mat"
        values  << vrmat_list.join('|')
        defaults << vrmat_list[0]
        
        #[2]
        prompts << "Diffuse texture"
        values  << var.join('|')
        defaults << var[0]
        
        #[3]
        prompts << "Caps"
        values  << "CAPS|Caps|caps"
        defaults << 'Caps'
        
        #[4]
        prompts << "add prefix to name"
        values  << ''
        defaults << ''
        
        #[5
        prompts << " "
        values  << "As prefix|As {TAG}"
        defaults << 'As prefix'
        
        #[6]
        prompts << "File Mask" 
        values  << mask.join('|')
        defaults << mask[0]
        
        #[7]
        prompts << "Max texture size(Length\&width)(#{@unit_name})" 
        values  << ''
        defaults << "2000#{@unit_name}"
        

        results = UI.inputbox( prompts, defaults, values, "Clipping plane ") 
        apply = results[0] 
        vrmat_select = results[1]
        text = results[2].gsub(/(filename)|([\s\d\(\)]*)/,'')
        caps = results[3]
        prefix = results[4]
        pref_tag = results[5]
        mask = results[6].gsub(/\(\d+\)/,'')
        max_length = results[7].to_i
        prefix_mod = ''
        if prefix != ''
            prefix_mod = "{#{prefix.upcase}}_" if pref_tag == 'As {TAG}'
            prefix_mod = "#{prefix}_" if pref_tag == 'As prefix'
        end #if
        
            if text == ''
                file_list_2 = sum_all_without_suffix
            else
            patern = '[^\*]+' + text + '\.\w{3,4}'
            file_list_2 = all_file_in_string.scan(/#{patern}/i)
            end # if
            
        if mask != 'All file'
            file_list_2.delete_if {|i| i.include?(mask) == false }
            file_list_2.compact!
            if file_list_2.size == 0
                UI.messagebox ("Error. No match is found
                Change the \"File Mask\" or \"Diffuse texture\"")
                return
            end #if
        end #if
        
        if (vrmat_select == 'Load new') and (apply == 'Yes')
            filename = UI.openpanel("Open File", "","Vrmat and Image Files|*.vrmat;*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;|Vrmat Files|*.vrmat;|Image Files|*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;||")
                    return if filename == nil
                    filename = ithil_vr_import_by_linked_image filename, 'vrmat'
                    vr_attribute_test = IO.read(filename).[](/#{'\w:(([^\<]*?setup[\\/])|([\\/]temp[\\/]))(test|texturemap)(?=(_[a-z]{0,5})*(\.\w{3,4}))'}/i) 
                     if vr_attribute_test == nil
                     UI.messagebox ("Could not find a template for a replacement.
            This Vrmat file is not supported.
            Please read the manual.")
                     return
                     end # if
            folder_vrmat = File.dirname(filename)
            vrmat_select = File.basename(filename).gsub!('.vrmat','')
         end # if
        max_length = 100 if max_length == 0 

lost_texture = []

file_list_2.compact.each {|texture_file|
    name = texture_file.gsub(/\.\w{3,4}$/,'')
    case caps
            when "CAPS"
                name_caps = name.upcase
            when "Caps"
                name_caps = name.capitalize
            when "caps"
                name_caps = name.downcase
    end #case

    name = prefix_mod + name_caps.gsub(' ','_').gsub(/#{text}/i,'')
     material = materials.add(name)
     mat = []
     model.materials.current = material
     material.texture = texture_file
     replace_part = folder+texture_file.gsub(/#{text}/i,'').gsub(/\.\w{3,4}$/,'')
     
 file_path = folder_vrmat +'/'+vrmat_select + '.vrmat'


if apply == 'Yes'
name = name.gsub('<','&lt;').gsub('"','&quot;').rstrip
       vr_attribute = IO.read(file_path)
       vr_attribute.gsub!(/#{'\w:(([^\<]*?setup[\\/])|([\\/]temp[\\/]))(test|texturemap)(?=(_[a-zA-Z]{0,5})*(\.\w{3,4}))'}/i, replace_part)
        old_mat_name = vr_attribute[/(?<=<entry>\/).+?(?=\/)/]
        puts " old_mat_name = #{old_mat_name} name = #{name} "         
        new_vr_attribute  = vr_attribute.gsub(old_mat_name, name).gsub(/(\<preview\>).*?(\<\/preview\>)/, "")
       all_texture_in_mat =  vr_attribute.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:jpg|jpeg|png|psd|tga|tiff|tif|sgi|rgb|rgba|pic|bmp|exr|hdr))(?=<)/i).uniq.flatten
       PythonBridge.direct_send("create_material_from_xml",[material.display_name, new_vr_attribute,"1"])
       PythonBridge.direct_send("select_current_material",[material.display_name])
     
     
    IR.ithil_vr_mat_select folder_vrmat +'\\'+vrmat_select + '.vrmat',"5" if vrmat_select != 'Load new'
     all_texture_in_mat   
    all_texture_in_mat.each_index { |i|
        flag = FileTest::exists?(all_texture_in_mat[i])
        
        if flag != true # Lost
            lost_texture << File.basename(all_texture_in_mat[i])
        end
    }   
        
end #if
     width = material.texture.image_width rescue eror_dif = true
     if eror_dif
                 UI.messagebox ("Diffuse texture not found.
    Please read the manual.")
             return
             end # if
     height = material.texture.image_height
     tex_asp = width / height.to_f

length = max_length*@unit_kor
     if height >= width
     material.texture.size=[length*tex_asp,length]
     else
      material.texture.size=[length,length/tex_asp]
     end # if
    

}

end # def ithil_import_all_texture_and_convert_to_vrmat

def self.ithil_setup_unit_format

units = Sketchup.active_model.options["UnitsOptions"]["LengthUnit"]
case units
    when 0
    @unit_name = "Inches" ; @unit_kor = 1
    when 1
    @unit_name = "Feet" ;   @unit_kor = 12
    when 2
    @unit_name = "mm" ; @unit_kor = 0.0393700787401575
    when 3
    @unit_name = "cm" ; @unit_kor = 0.393700787401575
    when 4
    @unit_name = "m" ;  @unit_kor = 39.3700787401575
end #case

end #ithil_setup_unit_format

def self.ithil_copy_and_rename_from_temp_folder
IR.vray_check
model = Sketchup.active_model
model.start_operation("Copy and rename from Cache folder", true)
Sketchup.set_status_text "Program is running..."

    filename = UI.savepanel("Select the new folder", "", "folder")
    return if filename.nil?
    output=File.dirname(filename)

Dir.mkdir(output) unless File.exist?(output)
    model.materials.each { |mat|
    next if mat.name == nil 
        model.materials.current = mat.name

    if (mat.respond_to?(:texture))
texture_test = mat.texture.filename.[](/([a-zA-Z]\:[^<]*ChaosGroupTextureCache[^<]*.(?:jpg|jpeg|png|tif|psd|tga|bmp))/i) if mat.texture != nil
next if texture_test == nil
file_type = texture_test.[](/(.(?:jpg|jpeg|png|tif|psd|tga|bmp))/i)
file_type = '.jpg' if file_type == nil
texture_width = mat.texture.width
texture_height = mat.texture.height
end # if

new_path = output+'\\'+ mat.display_name.gsub(/({\w+}_)|(\(ST\)_)/,'') + file_type
group=model.entities.add_group
  tw = Sketchup.create_texture_writer
      group.material= mat
      tw.load(group, true)
 tw.write(group, new_path, true) 
  group.erase! if group.valid?
  mat.texture=new_path
  mat.texture.size=[texture_width,texture_height]

}
    model.commit_operation
    Sketchup.set_status_text "Done!"
end #ithil_copy_and_rename_from_temp_folder

def self.ithil_resource_collector
IR.vray_check
model = Sketchup.active_model
model.start_operation("Resource Collector", true) 
Sketchup.set_status_text "Program is running..."

    selection = model.active_entities
    Sketchup.send_action "showRubyPanel:"
    filename = UI.savepanel("Select the folder", "", "folder")
    return if filename.nil?
    output=File.dirname(filename).gsub('\/','\\')
    

@vrmesh_list = []
@lost = []

    process_at_leve_IT_VR_TEST  selection, {}
    ithil_vr_texture_collect_list
    ithil_vr_option_texture_list
    @vrmesh_list.uniq! 
    @vrmesh_list.flatten!.sort
    p
    p
    puts "   #{@vrmesh_list.size} files found:" if @vrmesh_list.size > 0
    puts '_'*40
    puts @vrmesh_list
    @vrmesh_list.each {|url| copy_file url, output }    
    puts '_'*40
    puts 'Copy is completed'
    
        if @lost.size > 0
        puts "   #{@lost.size}  files not found:"
        puts '   Search template:'
            puts "(=#{@lost.join(')OR(=')})" 
        else
            puts "No lost textures"
        end #if
    
    model.commit_operation
end #ithil_resource_collector

def self.process_at_leve_IT_VR_TEST( entities, hcomp)

    entities.each do |entity| 
       is_light = VRayForSketchUp.is_light( entity ) 
        is_proxy = VRayForSketchUp.is_proxy( entity) 
        case entity.typename
        when 'Group'
        
        if is_proxy 
            proxy_xml = VRayForSketchUp.get_vfs_proxy_attribute( entity )
            path = proxy_xml[/(?<=>)([a-zA-Z]\:[^<]*(?:vrmesh))(?=<)/]
            @vrmesh_list << path if path.length > 0
        end
        if is_light 
            light_xml = VRayForSketchUp.get_vfs_light_attribute( entity )
            path = light_xml.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:ies|jpg|jpeg|png|psd|tga|tiff|tif|sgi|rgb|rgba|pic|bmp|exr|hdr))(?=<)/i).join
            @vrmesh_list << path if path.length > 0
        end #if
            process_at_leve_IT_VR_TEST  entity.entities, hcomp
        when 'ComponentInstance'
      
            edef = entity.definition
            next if hcomp[edef.to_s]
            hcomp[edef.to_s] = edef
            process_at_leve_IT_VR_TEST  edef.entities, hcomp

        end
    end
end 

def self.ithil_vr_texture_collect_list
# p 'ithil_vr_texture_list'
model = Sketchup.active_model
materials = model.materials.sort_by{|mat| [mat.display_name.upcase] }
    materials.each { |mat|
    model.materials.current = mat.name 
    vr_attribute=get_vfs_material_attribute( mat )
    tex = []
    tex = vr_attribute.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:jpg|jpeg|png|psd|tga|tiff|tif|sgi|rgb|rgba|pic|bmp|exr|hdr))(?=<)/i).uniq.flatten
    @vrmesh_list << tex
}
end #ithil_vr_texture_collect_list

def self.ithil_vr_option_texture_list
vr_attribute = VRayForSketchUp.get_vfs_scene_attribute(VRayForSketchUp::VFS_OPTIONS_DICTIONARY)
    tex = vr_attribute.join.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:jpg|jpeg|png|psd|tga|tiff|tif|sgi|rgb|rgba|pic|bmp|exr|hdr))(?=<)/i).uniq.flatten
    @vrmesh_list << tex
end #ithil_vr_option_texture_list

 def self.copy_file (file_in_folder , output)
    if File.exist?(file_in_folder.to_s.gsub('\/','\\')) 
        new = output +'\\' + File.basename(file_in_folder)
    else 
        alt_path = file_in_folder.gsub(File.dirname(file_in_folder),File.dirname(Sketchup.active_model.path)).gsub('\\','/')
        flag = FileTest::exists?(alt_path)
            if flag == true
                new = alt_path
            else
                @lost << File.basename(file_in_folder)
                return
            end #if flag
     end # if File.exist?
        file_n = File.new(new, "w")
        File::copy_stream(file_in_folder, new)
        file_n.close

 end # def

def self.ithil_save_all_vrmat
IR.vray_check
model = Sketchup.active_model
model.start_operation("Save all VRMAT", true)
Sketchup.set_status_text "Program is running..."
materials_in_scene = []
model.materials.each { |m| materials_in_scene.push (m.name.to_s) }
if materials_in_scene.length == 0
UI.messagebox ("The file does not contain materials")
end #if

    filename = UI.savepanel("Save the VRMAT file", "", "VRMAT.txt")
    return if filename.nil?
    folder=File.dirname(filename)
model.materials.each { |mat|
                vfs_dictionary = ""
                model.materials.current = mat.name
    vr_attribute = get_vfs_material_attribute( mat ).gsub("<Assets>","<vrmat>").gsub("</Assets>","</vrmat>")
    mat_preview = vr_attribute.[](/#{'(?<=<preview>).*?(?=</preview>)'}/)
                filename = mat.name + ".vrmat"
                vrmat_file = File.new(folder+'\\'+filename, "w")
                            vrmat_file.write(vr_attribute)
                            vrmat_file.close
            }
model.commit_operation

end #.ithil_save_all_vrmat

def self.ithil_vr_texture_list
IR.vray_check
model = Sketchup.active_model
model.start_operation("Vray Texture List", true) 
Sketchup.set_status_text "Program is running..."
Sketchup.send_action "showRubyPanel:"

prompts = ["Report"]
        defaults = ["Short"]
        values = ["Full|Short|Only Lost"]
        all_texture = []
        lost_texture_and_mat = []
        lost_texture = []
        cyrillic_texture = []
        damaged_material = []
        @@print_log = []
        
        results = UI.inputbox( prompts, defaults, values, "Select the type of report")
        return nil if not results
        tip = results[0]


@@print_log << '   Material and textur list'
@@print_log << '_'*40
    model.materials.each { |mat|
        vfs_dictionary = ""
        model.materials.current = mat.name
        report = '[Lost ]'
    mat_text =[]
    lost_text_count = 0

        vr_attribute=get_vfs_material_attribute( mat )
        texture_list = []
            if vr_attribute == nil
                state = '[Trouble]'
                damaged_material.push(mat.name.to_s)
                @@print_log << "Mat:"+"!" + state +"!"*3 +  mat.name
                next 
            end #if
        texture_list = vr_attribute.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:jpg|jpeg|png|tif|psd|tga|bmp))(?=<)/i).uniq.flatten
    if texture_list.empty?
    state = '[Solid]'
    else
    state = '[Texture]'
    end

    next if state == '[Solid]' and tip == "Short"
 

mat_text << "Mat:"+" "*(10-state.length) + state +" "*3 +  mat.name


    texture_list.each_index { |i|

        flag = FileTest::exists?(texture_list[i])
         if texture_list[i][/[А-Яа-я]+/] != nil
         cyrillic = "
                   (Cyrillic in the file path!)"
         cyrillic_texture << "#{texture_list[i]} - #{mat.display_name}"
         else 
         cyrillic = ''
         end # if
         all_texture << texture_list[i]
    if flag == true
    state = '[Found] '
    else
    state ='!!![Lost ]!!!'
    if Sketchup.active_model.path != nil
    alt_path = texture_list[i].gsub(File.dirname(texture_list[i]),File.dirname(model.path)).gsub('\\','/')
    flag2 = FileTest::exists?(alt_path)
    
    state = '[Found in folder]' if flag2 == true
    end #if
    #path=model.path
    lost_texture_and_mat << "#{texture_list[i]} - #{mat.display_name}" if !flag2
    if !flag2
    lost_texture.push(texture_list[i]) if !flag2
    lost_text_count += 1
    end #if
    next if state == '[Found]' and tip == "Short"
    end
mat_text << " "*10 + state 
mat_text << " "*16 + "Tex: "+ texture_list[i] + cyrillic

@@print_log = @@print_log + mat_text if ((lost_text_count > 0) and (tip == "Only Lost")) or (tip != "Only Lost")
# @@print_log << "Cyrillic in the file path (#{texture_list[i]})" if texture_list[i][/[А-Яа-я]+/] != nil
 }  
    
}
    
@@print_log << '_'*40

    lost_texture.uniq! #удаляем дубликаты
    lost_texture.sort
    if lost_texture.length > 0
    
@@print_log << ' '
@@print_log << ' '

        @@print_log << '   Lost textures: ' + lost_texture.length.to_s
@@print_log << '  '
@@print_log << '_'*40
lost_name =[]
lost_texture.each_index { |i| @@print_log << lost_texture[i]
lost_name << File.basename(lost_texture[i])
} 
@@print_log << '  '
@@print_log << '  '
    lost_texture_and_mat.uniq!
    lost_texture_and_mat.sort
@@print_log << '   Lost textures in material:' 
@@print_log << '_'*40
lost_texture_and_mat
lost_texture_and_mat.each_index { |i| @@print_log << lost_texture_and_mat[i]} 
@@print_log << '  '
@@print_log << '_'*40
@@print_log << ' Search template:'
@@print_log << '_'*40
@@print_log << '  '
@@print_log << '  '
@@print_log << "(=#{lost_name.join(')OR(=')})"
else 
@@print_log << "No lost textures"


end # if

if damaged_material.length > 0
@@print_log << '  '
@@print_log << '  '
@@print_log <<  '_'*40
        @@print_log <<  '   Damaged materials: ' + damaged_material.length.to_s
@@print_log << '  '
@@print_log <<  '_'*40
damaged_material.each_index { |i| @@print_log <<  damaged_material[i]} 
@@print_log << '  '
@@print_log <<  '   Remove or reload these materials'


end # if

    cyrillic_texture.uniq! #удаляем дубликаты
    cyrillic_texture.sort
if cyrillic_texture.length > 0
@@print_log << '  '
@@print_log << '  '
@@print_log <<  '_'*40
        @@print_log <<  '   Texture with Cyrillic characters in path: ' + cyrillic_texture.length.to_s
@@print_log << '  '
@@print_log <<  '_'*40
cyrillic_texture.each_index { |i| @@print_log <<  cyrillic_texture[i].gsub('/','\\')} 
@@print_log << '  '
@@print_log <<  '   Change the path to these textures!'
end # if

@@print_log << '  '
@@print_log << '  '


if all_texture.length > 0  and tip == "Full"
all_texture.uniq! 
all_texture.sort
@@print_log << '  '
@@print_log << '  '
@@print_log <<  '   All Texture in File: ' + all_texture.length.to_s
all_texture.each_index { |i| @@print_log << "#{all_texture[i]}"}

end # if
@@print_log.each_index { |i| puts @@print_log[i]} 
    model.commit_operation
    Sketchup.set_status_text "Done!"
end #ithil_vr_texture_list

def self.ithil_ml_list
IR.vray_check
model = Sketchup.active_model
model.start_operation("Vray Layers List", true) 
Sketchup.set_status_text "Program is running..."
Sketchup.send_action "showRubyPanel:"
materials = model.materials.sort_by{|mat| [mat.display_name.upcase] }
    materials.each { |mat|
     next if !mat.respond_to?( :display_name )
        model.materials.current = mat.name 
        vr_attribute=get_vfs_material_attribute( mat )
        texture_list = []
            if vr_attribute == nil
                next 
            end #if

                scan_layer = []
                scan_layer = vr_attribute.[](/#{'(<list>)(.|\n)*?(</list>)'}/).gsub(/#{'(/.*?/)|(<.+?>)|((?<!try>)\s*)'}/,'').split
                map_slot_test = ''
                opt_slot_test = ''
                map_slot_test << '(Bump) 'if vr_attribute[/#{'name="bump_on"[^/]*1\<'}/]
                map_slot_test << '(Disp) 'if vr_attribute[/#{'name="displace_on"[^/]*1\<'}/]
                map_slot_test << '(Reflect) 'if vr_attribute[/#{'name="override_reflect"[^/]*1\<'}/]
                map_slot_test << '(Refract) 'if vr_attribute[/#{'name="override_refract"[^/]*1\<'}/]
                map_slot_test << '(Background) 'if vr_attribute[/#{'name="override_bg"[^/]*1\<'}/]
                opt_slot_test << '(Shadow - OFF) 'if vr_attribute[/#{'name="cast_shadow"[^/]*0\<'}/]
                opt_slot_test << '(Can be Overridden - OFF) 'if vr_attribute[/#{'name="effected_by_mtl_override"[^/]*0\<'}/]
                puts 
                puts "Material: (layers: #{scan_layer.size})     #{mat.name}"  
                puts "="*(50-opt_slot_test.size) + opt_slot_test if opt_slot_test.size > 0
                puts "—"*(50-map_slot_test.size) + map_slot_test
 scan_layer.map{|layer| puts "            #{layer}"}
}
end # ithil_ml_list

def self.ithil_vr_mat_import (var)
IR.vray_check
        filename = UI.openpanel("Open File", "","Vrmat and Image Files|*.vrmat;*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;|Vrmat Files|*.vrmat;|Image Files|*.jpg;*.jpeg;*.tga;*.png;*.bmp;*.psd;*.gif;*.tif;*.tiff;||")
        return if filename == nil
        filename = ithil_vr_import_by_linked_image filename, 'vrmat'
        IR.ithil_vr_mat_select filename,var
end #ithil_vr_mat_import


def self.ithil_vr_mat_select (file_name,tip)
 # 1 - save difuse. load from temp folder
 # 2 - save and copy difuse color. load from temp folder
 # 3 - save and copy difuse textur. load from temp folder
 # 4 - save difuse. load from user folder
 # 5 - dont save difuse. load from user folder
        model = Sketchup.active_model
        material = model.materials.current 
        IR.material_test (material)
        model.start_operation("Past V-ray attribute", true)
        Sketchup.set_status_text "Program is running..."
        mat = find_material_with_tag
        if mat.to_s != [] then  self.ithil_vr_mat(mat,file_name,tip) 
            mat[0] = material
            self.ithil_vr_mat(mat,file_name,tip)
        end
model.commit_operation

end #ithil_vr_mat_select 

def self.ithil_vr_mat (mat,file_name,tip)
        model = Sketchup.active_model
        plugins = Sketchup.find_support_file("Plugins")
        folder="ithil_render/vrmat"
mat.each { |material|
        IR.ithil_vr_save_diffuse (material)
        IR.ithil_vr_attribute_copy
        filename = plugins+"/"+folder+"/"+file_name+".vrmat"
        if tip=="3" and @@ith_copy_texture_use == nil
            filename = plugins+"/"+folder+"/"+file_name+"_solid.vrmat"
            tip="2" 
        end
        filename = file_name if tip == "4" or tip == "5" 
        vr_attribute = IO.read(filename)
        old_mat_name = vr_attribute[/(?<=<entry>\/).+?(?=\/)/]
        new_vr_attribute=vr_attribute.gsub(old_mat_name, material.display_name.gsub('<','&lt;').gsub('"','&quot;')).gsub(/(\<preview\>).*?(\<\/preview\>)/, "")
        new_vr_attribute.gsub!(/#{'\w:(([^\<]*?setup[\\/])|([\\/]temp[\\/]))(test|texturemap)(?=(_[a-zA-Z]{0,5})*(\.\w{3,4}))'}/i, @@ith_copy_texture.gsub(/\.\w{3,4}$/,'')) if @@ith_copy_texture_use
    tex = new_vr_attribute.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:jpg|jpeg|png|psd|tga|tiff|tif|sgi|rgb|rgba|pic|bmp|exr|hdr))(?=<)/i).uniq.flatten
        if tip=="2" or tip=="4"
            color = []
            color = color_convert(@@ith_copy_color_red,@@ith_copy_color_green,@@ith_copy_color_blue)
            old_color="<r>0.800000</r>\n      <g>0.200000</g>\n      <b>0.200000</b>"
            new_color="<r>" + color[0] + "</r>\n      <g>" + color[1] + "</g>\n      <b>" + color[2] + "</b>"
            new_vr_attribute.gsub!(old_color, new_color)
        end #if
        PythonBridge.direct_send("create_material_from_xml",[material.display_name, new_vr_attribute,"1"])
        new_name = material.name.gsub(/\(ST\)_/,'')
        material.name = new_name
        model.materials.current = material.name 
        IR.ithil_vr_past if tip == "1" or tip == "4"
        material.alpha = @@ith_copy_alpha if tip == "2"
         if tip == "3"
IR.ithil_regenerate_previews
         end 
        
}
return
end #ithil_vr_mat


def self.ithil_vr_mat_from_folder (material,file_name,replace_part)
        model = Sketchup.active_model
        model.materials.current = material
        IR.ithil_vr_save_diffuse (material)
        vr_attribute = IO.read(file_name)
        old_mat_name = vr_attribute[/(\<entry\>\/).*?(\/)/].gsub("<entry>/","").gsub("/","")
        new_vr_attribute=vr_attribute.gsub(old_mat_name, material.display_name).gsub(/(\<preview\>).*?(\<\/preview\>)/, "")
        new_vr_attribute.gsub!(/#{'\w:(([^\<]*?setup[\\/])|([\\/]temp[\\/]))(test|texturemap)(?=(_[a-zA-Z]{0,5})*(\.\w{3,4}))'}/i, replace_part)
        tex = new_vr_attribute.scan(/(?<=>)([a-zA-Z]\:[^<]*(?:jpg|jpeg|png|psd|tga|tiff|tif|sgi|rgb|rgba|pic|bmp|exr|hdr))(?=<)/i).uniq.flatten
        PythonBridge.direct_send("create_material_from_xml",[material.display_name, new_vr_attribute,"1"])
        new_name = material.name.gsub(/\(ST\)_/,'')
        material.name = new_name
        return tex
return
end #ithil_vr_mat_from_folder
 
 def self.all_in_material(xml,name)
 return xml.scan(/#{'(<parameter.*?name="'+name+'"(.|\n)*?</value>(.|\n)*?</parameter>)'}/).join.scan(/#{'(?<=<value>).*(?=</value>)'}/).map{|item| item.to_f }.join (' | ')
 end 
 
def self.ithil_rotate_hdri
    model = Sketchup.active_model
                model.start_operation("Change \"size\" in Procedural Map", true)
    selection = model.selection
    
    #*
   if not selection[0]
      UI.messagebox("No Selection!")
      return nil
   end#if
   if selection[1]
      UI.messagebox("Select only ONE V-Ray Dome Light!")
      return nil
   end#if
  item = selection[0] 
is_light = VRayForSketchUp.is_light( item )

        if is_light 
         
            light_xml = VRayForSketchUp.get_vfs_light_attribute( item )
            check_light_dome = light_xml.[]('name="LightDome"')
        else
         UI.messagebox("Select only ONE V-Ray Dome Light!")
        return
        end #if
            offset = light_xml.[](/#{'(?<=<x_offset>).*?(?=</x_offset>)'}/)
   if offset == nil
      UI.messagebox("Not Found BitMap in V-Ray Dome Light!")
      return nil
   end#if
            if offset.size
                offset = offset.to_f
            end #if
            old_value = ((360*100*offset).round)/100.0
                Sketchup.set_status_text "Offset in HDRI: #{old_value} degrees"
    newname = ["#{old_value}"]
    prompts = ['New value']
        results = inputbox prompts, newname, "Change \"offset\" in HDRI"
        return nil if not results
        results_a = results.join.scan(/#{'([/*\-+]*)(\d*)[.,]*(\d*)'}/).flatten
        operation = results_a[0]
        value_in = results_a[1].to_f + 0.1 * results_a[2].to_f
            case operation
    when '' # replacement
     value = value_in
    when '*' # multiplication
     value = old_value * value_in
    when '/' # division
     value = old_value / value_in if value_in.to_f != 0.0
     if value_in.to_f == 0.0
     UI.messagebox "You can't divide by zero"
     return 
     end # if
    when '+' # addition
    value = old_value + value_in
    when '-' # subtraction
    value = old_value - value_in
             else 
             return
        end #case 
value = float_integer(value.remainder(360)/360.0)
light_xml.gsub!(/#{'<x_offset>.*?</x_offset>'}/,"<x_offset>#{value}</x_offset>")
            vfs_dictionary = item.attribute_dictionary(VRayForSketchUp::VFS_PRODUCT_GUID, true)
            if vfs_dictionary != nil
                vfs_dictionary[VRayForSketchUp::VFS_LIGHT_ATTRIBUTE] = light_xml
                else 
                return
            end
            VRayForSketchUp.change_observer(VRayForSketchUp::VfSDefinitionsObserver,VRayForSketchUp.active_model.definitions)
            if PythonBridge.is_rt_active()
                PythonBridge.direct_send( "edit_light", [light_xml] )
            end # if

Sketchup.set_status_text "Done!"
 end #ithil_temp
 
 def self.ithil_change_size
    model = Sketchup.active_model
                model.start_operation("Change \"size\" in Procedural Map", true)
    material = model.materials.current
    vr_attribute=get_vfs_material_attribute( material )
    
    all_size = all_in_material vr_attribute , "size"
        if all_size == ''
            UI.messagebox("Unable to find the parameter \"size\" in material #{material.name.gsub(/[\[\]]/ ,'"')}")
            return
        end # if
    
    Sketchup.set_status_text "All size in material: #{all_size}"
    newname = ['*2.0']
    prompts = ['new size']
        results = inputbox prompts, newname, "Change \"size\" in Procedural Map"
        return nil if not results
        results_a = results.join.scan(/#{'([/*\-+]*)(\d*)[.,]*(\d*)'}/).flatten
        operation = results_a[0]
        results_f = results_a[1].to_f + 0.1 * results_a[2].to_f

        if results_f <= 0
            UI.messagebox("Insert correct value!")
            return
        end 
            Sketchup.set_status_text "Program is running..."
            max_sub = results.join.to_f.to_i
                vfs_dictionary = ""
    attribute_new = self.change_float_parameter_by_name vr_attribute, "size", operation, results_f
            PythonBridge.direct_send("create_material_from_xml",[material.display_name,attribute_new,"1"])
        model.commit_operation
        model.materials.current = material.name 
        all_size = all_in_material vr_attribute , "size"
Sketchup.set_status_text "Done!"
 end #ithil_change_size
 
 def self.check_the_available_url(url_in)

 # находим свободный адрес не использованый в материале 
    return url_in if (@@vr_Hac_test.include? '>'+url_in+'<') == false # проверяем есть ли не измененный может и не надо изменять
url_part = url_in.split('/') 
    return url_in if url_part.size == 2  #запрещаем изменять имя материала заканчивающийся на число
numeric = url_part[-1].gsub(/[\D]/,'').to_i
url_part[-1].gsub!(numeric.to_s,(numeric+1).to_s)
url_next = url_part.join('/')
url_next = url_in + '1' if numeric == 0
    if @@vr_Hac_test.include? '>'+url_next+'<'
        IR.check_the_available_url(url_next)
    else
        return url_next
    end# if
 end #check_the_available_url
 
 def self.full_url_to_name( url ) # Конвертируем полный путь вложенных текстур по адресу в иерархию вложености

all_url = []
all_url =  url[1..-1].split('/')
sum = ""
all_url.each_index { |i| sum = sum +"/"+ all_url[i]; all_url[i] = sum}
all_name = all_url.map {|url|

IR.url_to_name(url[0..-1])
}

if all_name[0] == ''
ret = all_name[1..-1]
else
ret = all_name
end 
return ret.join(" → ").gsub('MtlASGVIS','')
 end #full_url_to_name 
 
 
 
 
 
 def self.url_to_name (url) # По адресу узнаем тип карты
url_fix = url.gsub(/(?<meta-symbol>(?<!\\)[\^\[\]\$\(\)\|\?\+\*])/,'\\\\\k<meta-symbol>')
   part = @@vr_Hac_test.scan(/#{'(<Asset renderer.*?url="' + url_fix + '"[^\r]*?<vrayplugin.*?">)'}/).join
name = part.scan(/#{'(?<=name=")(?=).+?(?=")'}/).join
layout = part.scan(/#{'(?<=layout=")(?=).*?(?=")'}/).join
layout = '#' + layout if layout != ''
    url_split = url.split('/')
name2 = url_split[-1]
if (url_split.size == 3) && (name2.include?('Texture') == false) #находим имя не стандартно названных слоев. Защищаем хеш от одинаковых ключей
name = name2
end #if
slot_temp = @@vr_Hac_test[/#{'(?<=<parameter)(?:(?!<parameter|</parameter>).)*(?:' + url_fix + ')(?=</value>)'}/m]
slot_alt_temp = @@vr_Hac_test[/#{'(?:<parameter isUserData)((?:(?!<parameter|</parameter>).)*>).{,10}(?:<value>)(?:' + url_fix + ')(?=</value>)'}/m]
slot_alt2 = slot_alt_temp.[](/#{'(?<=name=").+?(?=")'}/) if slot_alt_temp != nil

                
    if name == 'TexAColorOp' and !name2.[](/Texture/)   # Помечаем лишние паразитные TexAColor чтобы сохранить оригинальные
        name += 'Odd'
    end # If name
                
if slot_temp !=nil
    slot = slot_temp.scan(/#{'(?<=label=")(?=).+?(?=")'}/).join.gsub(' Texture','')
    slot_alt = slot_temp.scan(/#{'(?<=name=")(?=).+?(?=")'}/).join#     .gsub('_tex','')

    if slot == 'Texture'
        slot = slot_alt.capitalize
    end # if
        slot = '('+slot+')'
else 
slot =''
end

slot = '('+slot_alt2+')' if slot_alt_temp != nil   # fix for Emissive layer

otchet = name + layout.gsub('Layer','') + slot# опускаем  нечитаемое 
otchet =  '' if name == 'MtlASGVIS' 
return otchet
 end #url_to_name
 
def self.all_url_in_part ( value )
    if value.class.to_s == 'Array' 
        value = value.join      
    end # if 
url_scan = value.scan(/#{'(?<=<value>|")\/.*?(?=</value>|")'}/)
url_scan = nil if url_scan.size == 0
return url_scan
end #

def self.replacement_url_in_array ( array , string_old ,string_new )
string_old.gsub!('\\','')
string_new.gsub!('\\','')
base_old = string_old[/#{'(^/.*?)(?:/)'}/,1]
base_new = string_new[/#{'(^/.*?)(?:/)'}/,1]
return array.map {|item| item.gsub(string_old,string_new).gsub(base_old,base_new) }
end #


def self.format_menu_string (string)
string.gsub!(/(\s\(-1..1\))/,'')
string.gsub!(/(?<=\()\w/) {|w| w.capitalize }  # все слоты с заглавной сохраняя остальные заглавные 

string.gsub!(/_tex|\sTexture/,'')
string.gsub!(/→\s*→/,'→') # old mat

string.gsub!('(Bg)','(Background)')
string.gsub!(/\(Hi(?:gh)?light\s?glossiness\)/i,'(Hilight Gloss.)')
string.gsub!(/\((?:refl[\.\w\s]{,7})(?:Glossiness)\)/i,'(Reflect Gloss.)')
string.gsub!('(Transp.)','(Transparency)')
string.gsub!('(Displace)','(Displacement)')

string.gsub!(/(?:VRayBRDF|Reflection)(\(Rotation\))/,'(Anisotropy Rot.)') 
string.gsub!('Reflection(Color)','Reflection(Filter)')

string.gsub!(/(#(?:\s*)(?:Emissive|Diffuse|Reflection|Reflection|Refraction|VRayBRDF|texture)?)/,'') #Удаляем layout после сравнения 
string.gsub!(/(?<separator>\s*[\?→]\s*)(?<word>[^(]*(?=\())(?<dop>\([\w\s]*\))/, '\k<dop> \k<separator> \k<word>' ) # меняем местами слот и сепаатор
string.gsub!('Emissive(Multiplier)','Emissive(---)')

string.gsub!(/Reflection\(Transparency\)/i,'Reflection(Reflection)')
string.gsub!(/^(?<dop>\([\w\s]*\))\s*(?<word>\w*)/, '\k<word> \k<dop>' ) # возвращаем для корневых
string.gsub!(/(?<dop>^.+?)(?<base>\((?:Displacement|Bump|Reflect|Refract|Background)\))/i, '\k<base> \k<dop>' ) # возвращаем для корневых II
string.gsub!(/^(?<map_tip>^\w*)\s*(?<root>\([\w\s]*\))\s*(?<slot>\(.*\))$/, '\k<root> \k<map_tip> \k<slot>' ) # возвращаем для корневых

string.gsub!(/TexCombineColor\(Texture\)$/,'(---)') #mixmap
string.gsub!(/TexCellular\((Color offset|Nouvw color|Color mult|Alpha mult|Alpha offset)\)$/,'(---)') #TexCellular
string.gsub!(/TexBulge\(Alpha/,'(---)') #TexCellular

string.gsub!(/(?<sep>\()(?<value>[^-]*?)(?<sep2>\))/, ' \k<sep> \k<value> \k<sep2>' ) # Добавим пробелы у скобок
string.gsub!(/\s{2,}/, ' ' )# Удаляем лишние пробелы
string.gsub!(/^\s*/, '' ) # Удаляем лишние пробелы

return string.rstrip # Возврат без замыкающих пробелов
end

def self.cleaning_menu (array)
        array.each_index{ |i|
        array[i] = '' if array[i].to_s[/TexNoiseMax\s?\( \w*? \).?\((mix_map|color\d)\)/]
        array[i] = '' if array[i].to_s[/TexAColorOpOdd/] # VRBRDF Emissive
        array[i] = '' if array[i].to_s[/\(---\)/] # Emissive
        }
        array << ''
        array.delete('')
    return array
end #cleaning_menu


def self.cleaning_short_menu (array)
        array.each_index{ |i|
            scan_last = array[i].[](/#{'(?:(?:→\s)([^\)]*)\s?)(\([^\()]*?\))$'}/)
            scan_last2 = array[i].[](/#{'(\([^\()]*?\))(?:\s(?:→\s)([^\s\(\)]*?)\s)(\([^\()]*?\))$'}/)

            
            array[i] = '' if array[i][/#{'^\(\s(Background|Refract|Reflect)\s\)$'}/]
        if scan_last != nil
            array[i] = '' if scan_last[/TexBitmap/] && scan_last[/No UVW Color|Color Offset|Alpha Offset|Alpha Multiplier/]
            array[i] = '' if scan_last[/TexFresnel/] && scan_last[/IOR/]
            array[i] = '' if scan_last[/TexNoiseMax/] && scan_last[/Alpha mult|Alpha offset|Color mult|Nouvw color/]
            array[i] = '' if scan_last[/TexMix/] && scan_last[/Alpha mult|Alpha offset|Color mult|Color offset/]
            array[i] = '' if scan_last[/(Nouvw|Alpha)/i] 
        end
        if scan_last2 != nil

            array[i] = '' if scan_last2[/TexNoiseMax/] && scan_last2[/TexCombineColor.*Texture/]
        end
        }
        array << ''
        array.delete('')
    return array
end #cleaning_short_menu
 
 def self.ithil_vr_import_by_linked_image (filename,tip)
# Находим "связанные" файлы по изображению превью ренера файл материала при совпадении имен файлов
        filename_part = filename.scan(/([a-zA-Z]\:\\[^.]*\\)([^.]*)(\.\w{3,})/).flatten
        if filename_part[2].downcase[/#{'\.(jpg|jpeg|tga|png|bmp|psd|gif|tif|tiff|'+tip+')'}/] != nil
            filename_part[2] = ".#{tip}"
        else
        UI.messagebox("Please, select any #{tip.upcase} file or image!")
         return
        end #if
        if File.exist?(filename_part.join) #проверяем наличие желаемого файла
        filename = filename_part.join
        else
        UI.messagebox("File (#{filename_part[1]}.#{tip})not found!")
        end #if
        return filename
end


 def self.change_parameter_by_name (xml, name, value)
 return nil if xml==nil                 #(string,string,string)
 v_old = xml.[](/#{'<parameter[^\>]*?name="'+name+'"(?:.|/n){,100}<value>(.*?)</value>(?:.|/n)*?</parameter>'}/m)
    if v_old != nil
        if v_old.include?('ColorTexFrameHandler')

                     old_url_in_slot = Regexp.last_match[1].clone
                     shablon_test = '<Asset[^>]*?"'+old_url_in_slot+'".*?</Asset>'
                     aset_temp = @@vr_Hac_test.[](/#{'<Asset[^>]*?"'+old_url_in_slot+'".*?</Asset>'}/m) # не XML а весь материал!

     old = aset_temp.[](/#{'<parameter[^\>]*?name="texture".*?("/>|</parameter>)'}/m)
          if old == nil
          puts "Unexpected patern. 
Replacement is not possible.
Please refer to the developer."
          end 
     new = aset_temp.gsub(/#{'/>'}/,">\n         <value>#{value}</value>\n      </parameter>").gsub('<value></value>',"<value>#{value}</value>")

@@ColorTexFrameHandler_test[0] = aset_temp   #Возвращаем  для  замены в основном  коде в пришедшем куске нет этого  куска.
@@ColorTexFrameHandler_test[1] = new
v_old_alt = xml.[](/#{'<parameter isUserData="1"[^>]*name="'+name+'_tex.*?("/>|</parameter>)'}/m)
        if v_old != nil
        
    v2_new_alt = v_old_alt.gsub(/#{'/>'}/,">\n       <value>#{value}</value>\n      </parameter>").gsub('<value></value>',"<value>#{value}</value>")
         return xml.gsub(v_old_alt,v2_new_alt)
            end # if v_old != nil
        end # if include?('ColorTexFrameHandler')
    end # if v_old != nil
     if v_old == nil
     v2_old = xml.[](/#{'<parameter[^\>]*?name="'+name+'".*?"/>'}/)
          if v2_old == nil
          puts "Unexpected patern. 
        Replacement is not possible.
        Please refer to the developer."
          end 
     v2_new = v2_old.gsub(/#{'/>'}/,">
         <value>#{value}</value>
        </parameter>")
     return xml.gsub(v2_old,v2_new)
 
 else
     v_new = v_old.gsub(/#{'<value>.*?</value>'}/,"<value>#{value}</value>") 
    return xml.gsub(v_old,v_new)
end# if

  end #change_parameter_by_name
  
   def self.change_float_parameter_by_name (xml, name, operation,value_in)
   value = value.to_f
 return nil if xml==nil     
 v_old = [] 
 v_new = []
 old_v_a = []
 v_old = xml.scan(/#{'(<parameter.*?name="'+name+'"(.|\n)*?</value>(.|\n)*?</parameter>)'}/)
 v_old.uniq!
if v_old == nil
    return
 else
v_old.map {|old| 
old_v =  old[0]
old_v_a.push(old_v)
old_value  = old_v.[](/#{'(?<=<value>).*(?=</value>)'}/).to_f
    case operation
    when '' # replacement
     value = float_integer(value_in)
    when '*' # multiplication
     value = float_integer(old_value * value_in)
    when '/' # division
     value = float_integer(old_value / value_in)
    when '+' # addition
    value = float_integer(old_value + value_in)
    when '-' # subtraction
    value = float_integer(old_value - value_in)
             else 
             return
        end #case 
        
         v_new.push(old_v.gsub(/#{'<value>.*?</value>'}/,"<value>#{value}</value>"))
    
        }

old_v_a.each_index{|i|xml.gsub!(old_v_a[i],v_new[i]) }
        return  xml
end# if

  end #change_float_parameter_by_name
  
  def self.ithil_fix_material_name
Sketchup.active_model.start_operation('Rename Materials',true)
Sketchup.active_model.materials.each_with_index { |m| m.name = "#{ IR.name_caps(m.name)}";  }
Sketchup.active_model.commit_operation
Sketchup.send_action(21074) # show the Materials Browser Window
  end#def
  
  def self.name_caps (string)
string_old = string.clone
string.strip!
string.gsub!('%20',"_")
string.gsub!(/#{'[/\\\\*#?@"|><.]'}/,"_") #=>  Замена по шаблону
string.gsub!(/_{2,}/,'_')
string.gsub!(/(\w)\1{4,}/,'\1')
string.gsub!(/(?:[^)}])([_]\b|\b[_])/,"") 

puts "#{string_old} >> #{string}" if string != string_old
return string
end
  
  
 def self.change_parameter_by_name_and_url (xml, name, value)
                                #(string,string,string)
 v_old = xml.[](/#{'<parameter.*?name="'+name+'"(.|\n)*?</value>'}/)
 v_new = v_old.gsub(/#{'<value>.*?</value>'}/,"<value>#{value}</value>") 
return xml.gsub(v_old,v_new)
  end #change_parameter_by_name
  
  def self.escape_meta (string)
        return string.gsub(/(?<meta-symbol>(?<!\\)[\^\[\]\$\(\)\|\?\+\*])/,'\\\\\k<meta-symbol>').gsub('"','&quot;')
  end #escape_meta

 def self.asset_by_url (xml, url)

 url.gsub!(/(?<meta-symbol>(?<!\\)[\^\[\]\$\(\)\|\?\+\*])/,'\\\\\k<meta-symbol>')
asset = xml[/#{'<Asset renderer.*url="'+url+'"[^\r]*?</Asset>'}/]
return asset
 end #asset_by_url
 
def self.float_integer (float_integer)
 new = (float_integer * 100000).to_i.to_f / 100000
 if new.to_s.size < 7
 new = (new.to_s+"0"*(8-new.to_s.size))
 end# if
  return new.to_s
  end
 
def self.color_convert (r,g,b)
 color = []
 return color = [float_integer(r.to_f/255) , float_integer(g.to_f/255) , float_integer(b.to_f/255)]
 end
 
def self.ithil_material_merge
# объеденяем выделенные материалы
    model = Sketchup.active_model
    selection = model.selection
    model.start_operation("test")
    Sketchup.set_status_text "Program is running..."
    mat=[]
    mat = self.find_material_in_selection mat, selection, {}
    if mat == [] 
    UI.messagebox("Nothing Selected!")
    return
    end
replace_material(model.materials.current,mat)
model.commit_operation

Sketchup.set_status_text "Done!"
end

def self.find_material_in_selection(mat, entities, hcomp)
    entities.each do |entity| 
        case entity.typename
        when 'Group'
                self.find_material_in_selection mat, entity.entities, hcomp
                mat.push(entity.material) if (entity.material != nil )
        when 'ComponentInstance'
                edef = entity.definition
                next if hcomp[edef.to_s]
                hcomp[edef.to_s] = edef
                self.find_material_in_selection mat, edef.entities, hcomp
                mat.push(entity.material) if ( entity.material != nil )
            when 'Face'
              mat.push(entity.material) if (entity.respond_to?( :material ) and entity.material != nil )
              mat.push(entity.back_material) if (entity.respond_to?( :back_material ) and entity.back_material != nil)
        end
    end

    mat.uniq! #удаляем дубликаты
    mat.sort
    return mat
end 

def self.find_material_with_tag
        mat = []
        model = Sketchup.active_model
        current = model.materials.current
        tag = current.display_name[/(\{).*(\})/]
        model.materials.each { |m| mat.push(m) if (m.display_name.to_s.include?(tag)) } if tag != nil
        mat.sort
    return mat
end 

def self.inspect_fix (array,string)
    array.each_index { |m|
                if array[m].to_s.gsub('["','').gsub('"]','') == string.gsub('"','')
                   return true
                end#if
             }
    return nil
end


def self.vray_check
    if !VRayForSketchUp.respond_to?(:launch_vray_render)
            UI.messagebox( "V-ray Not Installed or Disabled" ) 
            exit
    end #if 
end # def

    def self.empty_folder_test (output)
    if Dir.entries(output).size == 2
        UI.messagebox ("Not found files in a folder")
        exit
    end #if
    end # def 
def self.replace_material (new_mat,old_mat)
            model = Sketchup.active_model
            model.entities.each { |e|
                    if (e.respond_to?(:material)) and (e.material != nil) 
                        e.material = new_mat if old_mat.include?(e.material)  
                    end
                    if (e.respond_to?(:back_material)) and (e.back_material != nil) 
                        e.back_material = new_mat if old_mat.include?(e.material) 
                    end
                }
                model.definitions.each { |d|
                    next if d.image?
                    d.entities.each { |e|
                        if (e.respond_to?(:material)) and (e.material != nil) 
                            e.material = new_mat if old_mat.include?(e.material) 
                        end
                        if (e.respond_to?(:back_material)) and (e.back_material != nil)
                            e.back_material = new_mat if old_mat.include?(e.material)
                        end
                    }
                }
end # replace_material

if not file_loaded?(File.basename(__FILE__))
    VFS_PRODUCT_GUID = "Something...Check the previous project to see the value we used"
    VFS_MATERIAL_ATTRIBUTE = "V-Ray for SketchUp Material Attribute"
end # if

end #module IR
class IRtest < Sketchup::AppObserver
def IRtest::validate_selection_mat
        model = Sketchup.active_model
        material  = model.materials.current
        return nil if material == nil
        return true if model.materials.include?( material )
        return true
    end # IRtest::validate_selection_mat
    
    def IRtest::validate_vray_check
        return VRayForSketchUp.respond_to?(:launch_vray_render)
    end # IRtest::validate_selection_mat
end #IRtest



if not file_loaded?(File.basename(__FILE__))
if( $submenu )
    organizer = $submenu 
        organizer.add_item("Edit Subdivs") { IR.ithil_vr_set_max_subdivs }
else
        $ithil_IRT_menu = UI.menu("Plugins").add_submenu("Ithil Render Tools")
        $ithil_IRT_menu.add_item("Camera Clipping Plane") { IR.ithil_clipping_plane }
        $ithil_IRT_menu.add_separator
        $ithil_IRT_menu.add_item("Edit Subdivs") { IR.ithil_vr_set_max_subdivs }
        $ithil_IRT_menu.add_item("Turn off Interpolation") { IR.ithil_vr_interpolation_off }
        $ithil_IRT_menu.add_item("Turn off Displacement") { IR.ithil_vr_displacement_off }
        $ithil_IRT_menu.add_item("Convert Displacement to Bump") { IR.ithil_vr_displacement_to_bump }
        $ithil_IRT_menu.add_separator
        $ithil_IRT_menu.add_item("Copy and rename texture file from Cache folder") { IR.ithil_copy_and_rename_from_temp_folder } 
        $ithil_IRT_menu.add_item("Change the path to the textures") { IR.ithil_vr_change_the_path }
        $ithil_IRT_menu.add_item("Change the path to the .VRMESH") { IR.ithil_vr_change_the_path_vrmesh } 
        $ithil_IRT_menu.add_item("Replace all VRMAT from  folder") { IR.ithil_replace_all_vrmat }
        $ithil_IRT_menu.add_item("Import all VRMAT from  folder") { IR.ithil_import_all_vrmat }
        $ithil_IRT_menu.add_item("Save all VRMAT") { IR.ithil_save_all_vrmat }
        $ithil_IRT_menu.add_item("Resource Collector") { IR.ithil_resource_collector }
        $ithil_IRT_menu.add_separator
        $ithil_IRT_menu.add_item("Texture list") { IR.ithil_vr_texture_list }
        $ithil_IRT_menu.add_item("Material Layers list") { IR.ithil_ml_list }
        $ithil_IRT_menu.add_item("Mark Standart Material (ST)") { IR.ithil_vr_mark_standart_material }
        $ithil_IRT_menu.add_item("Mark Max Subdivs         (SUB:80) ") { IR.ithil_vr_mark_max_subdivs_material }      
        $ithil_IRT_menu.add_item("Convert (ST) >> {ST} tag") { IR.ithil_convert_standart_tag }
        $ithil_IRT_menu.add_item("Fix Material Name") { IR.ithil_fix_material_name }

        
        
end
UI.menu("File").add_item("Import texture and convert to VRmat") { IR.ithil_import_all_texture_and_convert_to_vrmat }
   UI.add_context_menu_handler do |menu|
      menu.add_separator if (IRtest::validate_selection_mat)
    if IRtest::validate_selection_mat
    menu.add_item("Import material") { IR.ithil_vr_mat_import ("5") } 
    menu.add_item("Import attribute") { IR.ithil_vr_mat_import ("4") } 
    menu.add_item("Change \"Size\" in Map") { IR.ithil_change_size} 
    menu.add_item("Past HEX color") { IR.ithil_vr_past_hex_color} 
    
    end #if
   end
        plugins = Sketchup.find_support_file("Plugins")
        folder="ithil_render/icons"
        icon_ren_b = File.join(plugins,folder, "vr_r_large.png")
        icon_s_ren_b = File.join(plugins,folder, "vr_r_smal.png")
        
        icon_copy_b = File.join(plugins,folder, "vr_c_large.png")
        icon_s_copy_b = File.join(plugins,folder, "vr_c_smal.png")

        icon_past_b = File.join(plugins,folder, "vr_p_large.png")
        icon_s_past_b = File.join(plugins,folder, "vr_p_smal.png")
        
        icon_copy2_b = File.join(plugins,folder, "vr_c2_large.png")
        icon_s_copy2_b = File.join(plugins,folder, "vr_c2_smal.png")
        
        icon_copy3_b = File.join(plugins,folder, "vr_c3_large.png")
        icon_s_copy3_b = File.join(plugins,folder, "vr_c3_smal.png")

        icon_past2_b = File.join(plugins,folder, "vr_p2_large.png")
        icon_s_past2_b = File.join(plugins,folder, "vr_p2_smal.png")
        
        icon_past3_b = File.join(plugins,folder, "vr_p3_large.png")
        icon_s_past3_b = File.join(plugins,folder, "vr_p3_smal.png")
        
        icon_ms_b = File.join(plugins,folder, "vr_ms_large.png")
        icon_s_ms_b = File.join(plugins,folder, "vr_ms_smal.png")
        
        icon_ml_b = File.join(plugins,folder, "vr_ml_large.png")
        icon_s_ml_b = File.join(plugins,folder, "vr_ml_smal.png")
        
        icon_sub_b = File.join(plugins,folder, "vr_sub_large.png")
        icon_s_sub_b = File.join(plugins,folder, "vr_sub_smal.png")
        
        icon_tag_b = File.join(plugins,folder, "vr_tag_large.png")
        icon_s_tag_b = File.join(plugins,folder, "vr_tag_smal.png")
        
        icon_merge_b = File.join(plugins,folder, "vr_merge_large.png")
        icon_s_merge_b = File.join(plugins,folder, "vr_merge_smal.png")
        
        icon_temp_b = File.join(plugins,folder, "vr_hdr_large.png")
        icon_s_temp_b = File.join(plugins,folder, "vr_hdr_smal.png")
        
    
        icon_mat_plastic1_b = File.join(plugins,folder, "vr_mat_plastic1_large.png")
        icon_s_mat_plastic1_b = File.join(plugins,folder, "vr_mat_plastic1_smal.png")
        
        icon_mat_plastic2_b = File.join(plugins,folder, "vr_mat_plastic2_large.png")
        icon_s_mat_plastic2_b = File.join(plugins,folder, "vr_mat_plastic2_smal.png")

        icon_mat_plastic3_b = File.join(plugins,folder, "vr_mat_plastic3_large.png")
        icon_s_mat_plastic3_b = File.join(plugins,folder, "vr_mat_plastic3_smal.png")   
        
        icon_mat_metal_b = File.join(plugins,folder, "vr_mat_metal_large.png")
        icon_s_mat_metal_b = File.join(plugins,folder, "vr_mat_metal_smal.png")
            
        icon_mat_wood_b = File.join(plugins,folder, "vr_mat_wood_large.png")
        icon_s_mat_wood_b = File.join(plugins,folder, "vr_mat_wood_smal.png")
        
        icon_mat_lbox_b = File.join(plugins,folder, "vr_mat_lbox_large.png")
        icon_s_mat_lbox_b = File.join(plugins,folder, "vr_mat_lbox_smal.png")
        
        icon_glass_clean_b = File.join(plugins,folder, "vr_mat_glass_clean_large.png")
        icon_s_glass_clean_b = File.join(plugins,folder, "vr_mat_glass_clean_smal.png")

        icon_glass_bottle_b = File.join(plugins,folder, "vr_mat_glass_bottle_large.png")
        icon_s_glass_bottle_b = File.join(plugins,folder, "vr_mat_glass_bottle_smal.png")
        
    
It_tb = UI::Toolbar.new("Ithil Render Tools")
It_tb_m = UI::Toolbar.new("Ithil Material Wizard ")

        ith_render = UI::Command.new("Render"){ IR.ithil_vr_render }
        ith_render.small_icon = icon_s_ren_b
        ith_render.large_icon = icon_ren_b
        ith_render.tooltip = "Start render"
        ith_render.status_bar_text = "Change the visibility of layers and start rendering"
        
        ith_copy = UI::Command.new("Copy"){ IR.ithil_vr_copy }
        ith_copy.small_icon = icon_s_copy_b
        ith_copy.large_icon = icon_copy_b
        ith_copy.tooltip = "Copy Difuse Layer"
        ith_copy.status_bar_text = "Copy difuse layer from selected material"
        
        ith_past = UI::Command.new("Past"){ IR.ithil_vr_past }
        ith_past.small_icon = icon_s_past_b
        ith_past.large_icon = icon_past_b
        ith_past.tooltip = "Past Difuse Layer"
        ith_past.status_bar_text = "Past Difuse Layer in selected material"
        ith_past.set_validation_proc { if $ith_mat_dif  == nil
     MF_GRAYED
   else
    MF_ENABLED
   end}
        
        ith_copy2 = UI::Command.new("Copy V-ray attribute"){ IR.ithil_vr_attribute_copy }
        ith_copy2.small_icon = icon_s_copy2_b
        ith_copy2.large_icon = icon_copy2_b
        ith_copy2.tooltip = "Copy V-ray material attribute"
        ith_copy2.status_bar_text = "Copy V-ray material attribute from selected material"

        
        ith_past2 = UI::Command.new("Past V-ray attribute"){ IR.ithil_vr_attribute_past_select }
        ith_past2.small_icon = icon_s_past2_b
        ith_past2.large_icon = icon_past2_b
        ith_past2.tooltip = "Past V-ray attribute"
        ith_past2.status_bar_text = "Past V-ray material attribute in selected material or \{teg\} group"
        ith_past2.set_validation_proc { if $ith_mat_atr  == nil
     MF_GRAYED
   else
    MF_ENABLED
   end}
        ith_copy3 = UI::Command.new("Copy V-ray texture map"){ IR.ithil_vr_TexMap_copy }
        ith_copy3.small_icon = icon_s_copy3_b
        ith_copy3.large_icon = icon_copy3_b
        ith_copy3.tooltip = "Copy V-ray material texture map"
        ith_copy3.status_bar_text = "Copy V-ray material texture map from selected material"
        
        ith_past3 = UI::Command.new("Past V-ray texture map"){ IR.ithil_vr_TexMap_past }
        ith_past3.set_validation_proc { if $ith_mat_texture  == nil             #                      !!!!!!!!!!!!!!!!!!!!!!! выключенно для тестов
     MF_GRAYED
   else
    MF_ENABLED
   end}
        ith_past3.small_icon = icon_s_past3_b
        ith_past3.large_icon = icon_past3_b
        ith_past3.tooltip = "Past V-ray texture map"
        ith_past3.status_bar_text = "Past V-ray material texture map in selected material"
        
        ith_ms = UI::Command.new("Save V-ray texture map"){ IR.ithil_vr_TexMap_save }       
        ith_ms.small_icon = icon_s_ms_b
        ith_ms.large_icon = icon_ms_b
        ith_ms.tooltip = "Save V-ray texture map"
        ith_ms.status_bar_text = "Save V-ray material texture map in selected material or \{teg\} group"
    
        ith_ms.set_validation_proc { if $ith_mat_texture  == nil
             MF_GRAYED
           else
            MF_ENABLED
           end}
        ith_ml = UI::Command.new("Load V-ray texture map"){ IR.ithil_vr_TexMap_load }
        ith_ml.small_icon = icon_s_ml_b
        ith_ml.large_icon = icon_ml_b
        ith_ml.tooltip = "Load V-ray texture map"
        ith_ml.status_bar_text = "Load V-ray texture map "

        ith_sub = UI::Command.new("Edit Subdivs"){ IR.ithil_vr_set_max_subdivs }
        ith_sub.small_icon = icon_s_sub_b
        ith_sub.large_icon = icon_sub_b
        ith_sub.tooltip = "Edit Subdivs"
        ith_sub.status_bar_text = "Edit Subdivs V-ray material"
        
        ith_tag = UI::Command.new("Edit Tag"){ IR.ithil_insert_tag }
        ith_tag.small_icon = icon_s_tag_b
        ith_tag.large_icon = icon_tag_b
        ith_tag.tooltip = "Edit Tag"
        ith_tag.status_bar_text = "Insert or Delit Material Tag"
        
        ith_merge = UI::Command.new("Merge material"){ IR.ithil_material_merge }
        ith_merge.small_icon = icon_s_merge_b
        ith_merge.large_icon = icon_merge_b
        ith_merge.tooltip = "Merge material"
        ith_merge.status_bar_text = "Merge selected material"
        
        ith_temp = UI::Command.new("Rotate HDRI"){ IR.ithil_rotate_hdri }
        ith_temp.small_icon = icon_s_temp_b
        ith_temp.large_icon = icon_temp_b
        ith_temp.tooltip = "Rotate HDRI"
        ith_temp.status_bar_text = "Rotate HDRI in V-Ray Dome Light"
        
        ith_mat_plastic1 = UI::Command.new("Plastic tip 1"){ IR.ithil_vr_mat_select "plastic1","1"  }
        ith_mat_plastic1.small_icon = icon_s_mat_plastic1_b
        ith_mat_plastic1.large_icon = icon_mat_plastic1_b
        ith_mat_plastic1.tooltip = "Plastic tip 1"
        ith_mat_plastic1.status_bar_text = "Flat Enamel Plastic"
        
        ith_mat_plastic2 = UI::Command.new("Plastic tip 2"){ IR.ithil_vr_mat_select "plastic2","1"  }
        ith_mat_plastic2.small_icon = icon_s_mat_plastic2_b
        ith_mat_plastic2.large_icon = icon_mat_plastic2_b
        ith_mat_plastic2.tooltip = "Plastic tip 2"
        ith_mat_plastic2.status_bar_text = "Soft Gloss Plastic"
            
        ith_mat_plastic3 = UI::Command.new("Plastic tip 3"){ IR.ithil_vr_mat_select "plastic3","1" }
        ith_mat_plastic3.small_icon = icon_s_mat_plastic3_b
        ith_mat_plastic3.large_icon = icon_mat_plastic3_b
        ith_mat_plastic3.tooltip = "Plastic tip 3"
        ith_mat_plastic3.status_bar_text = "Polished Plastic"
        
        ith_mat_metal = UI::Command.new("Metal"){ IR.ithil_vr_mat_select "metal","3" }
        ith_mat_metal.small_icon = icon_s_mat_metal_b
        ith_mat_metal.large_icon = icon_mat_metal_b
        ith_mat_metal.tooltip = "Non-ferrous metal"
        ith_mat_metal.status_bar_text = "Copper, gold, bronze, etc."

        ith_mat_wood = UI::Command.new("Wood material"){ IR.ithil_vr_mat_select "wood","3" }
        ith_mat_wood.small_icon = icon_s_mat_wood_b
        ith_mat_wood.large_icon = icon_mat_wood_b
        ith_mat_wood.tooltip = "Wood"
        ith_mat_wood.status_bar_text = "Old wood with bump"

        ith_mat_lbox = UI::Command.new("Emissive materials"){ IR.ithil_vr_mat_select "lbox","3" }
        ith_mat_lbox.small_icon = icon_s_mat_lbox_b
        ith_mat_lbox.large_icon = icon_mat_lbox_b
        ith_mat_lbox.tooltip = "Emissive materials"
        ith_mat_lbox.status_bar_text = "Neon signs, TV screen, lightbox, LED, etc."

        ith_glass_clean = UI::Command.new("Clean glass"){ IR.ithil_vr_mat_select "glass","0" }
        ith_glass_clean.small_icon = icon_s_glass_clean_b
        ith_glass_clean.large_icon = icon_glass_clean_b
        ith_glass_clean.tooltip = "Clean glass"
        ith_glass_clean.status_bar_text = "Window glass, water bottles, etc."
            
        ith_glass_bottle = UI::Command.new("Colored glass"){ IR.ithil_vr_mat_select "glass_bottle","2" }
        ith_glass_bottle.small_icon = icon_s_glass_bottle_b
        ith_glass_bottle.large_icon = icon_glass_bottle_b
        ith_glass_bottle.tooltip = "Colored glass"
        ith_glass_bottle.status_bar_text = "Stained glass, bottle glass, colored glass, etc."
    

It_tb.add_item(ith_render)
It_tb.add_item(ith_copy)
It_tb.add_item(ith_past)
It_tb.add_separator
It_tb.add_item(ith_copy2)
It_tb.add_item(ith_past2)
It_tb.add_separator
It_tb.add_item(ith_copy3)
It_tb.add_item(ith_past3)
It_tb.add_separator
It_tb.add_item(ith_ms)
It_tb.add_item(ith_ml)
It_tb.add_separator
It_tb.add_item(ith_sub)
It_tb.add_item(ith_tag)
It_tb.add_item(ith_merge)
It_tb.add_item(ith_temp)
It_tb_m.add_item(ith_mat_plastic1)
It_tb_m.add_item(ith_mat_plastic2)
It_tb_m.add_item(ith_mat_plastic3)
It_tb_m.add_item(ith_mat_metal)
It_tb_m.add_item(ith_mat_wood)
It_tb_m.add_item(ith_mat_lbox)
It_tb_m.add_item(ith_glass_clean)
It_tb_m.add_item(ith_glass_bottle)
It_tb.show
It_tb_m.show
file_loaded(File.basename(__FILE__))
end