<file_sep>#-*- coding:utf-8 -*-

import os
import hou

hip_dir = os.path.expandvars("$HIP")
log_dir = "/script/sim_log/"

density_log = hip_dir + log_dir + "density.txt"
temperature_log = hip_dir + log_dir + "temperature.txt"
heat_log = hip_dir + log_dir + "heat.txt"

padding = 4

density_max = str(hou.hscriptExpression('volumemax(0,0)'))
density_max = density_max.split('.')
density_max = density_max[0].zfill(padding) + '.' + density_max[1][:2]

temperature_max = str(hou.hscriptExpression('volumemax(0,1)'))
temperature_max = temperature_max.split('.')
temperature_max = temperature_max[0].zfill(padding) + '.' + temperature_max[1][:2]

heat_max = str(hou.hscriptExpression('volumemax(0,2)'))
heat_max = heat_max.split('.')
heat_max = heat_max[0].zfill(padding) + '.' + heat_max[1][:2]



with open(density_log, 'a') as density_log_file:
  density_log_file.write(density_max + "\n")

with open(temperature_log, 'a') as temperature_log_file:
  temperature_log_file.write(temperature_max + "\n")

with open(heat_log, 'a') as heat_log_file:
  heat_log_file.write(heat_max + "\n")
<file_sep>
hou.hipFile.load(file_name='/home/gulliver/Desktop/Job/Study/command_line/test_v01.hip')


hip_dir = hou.hscriptExpression('$HIP')

new_geo = hou.node('/obj').createNode('geo')


font_node = new_geo.createNode('font')

font_node.parm('text').set(hip_dir)

print(hou.isUIAvailable(1))

#print(hou.ui.paneTabs())


hou.hipFile.save(file_name='/home/gulliver/Desktop/Job/Study/command_line/test_v02.hip')
#
# print(hip_dir)
# #ver = 'v' + str(hou.hscriptExpression('$VER').zfill(2))
# ver = 'v01'
# #wipver = str(hou.hscriptExpression('$WIPVER').zfill(2))
# wipver = 'w01'
# #justin = hou.hscriptFloatExpression('$JUSTIN')
# #justout = hou.hscriptFloatExpression('$JUSTOUT')
#
# panes = hou.ui.paneTabs()
#
# sceneview = None
#
# for i in panes:
#     if 'Scene' in str(i.type()):
#         sceneview = i
#     else:
#         pass
#
# flipbook_setup = sceneview.flipbookSettings()
#
# flipbook_setup.frameRange((1, 50))
# # flipbook_setup.resolution((1920,1080))
# flipbook_setup.useResolution(0)
#
# flipbook_setup.output(hip_dir + '/flipbook/' + ver + '_' + wipver + '/' + 'test_$F4.png')
# flipbook_setup.outputToMPlay(0)
#
# sceneview.flipbook()

<file_sep># Name: Oncreated.py

manager_color = (0, 0.533, 0)	# green
generator_color = (1, 0.9, 0.65)	# ivory

# Common node type colors.	These colors affect these types in all contexts.
# Node names are matched identically with keys.

common_type_colors = {
	
	"null": (0, 0, 0), # black
	"switch": (1, 0.4, 1),	# pink
	"attribvop": (0.188, 0.529, 0.459),	# blue green
	"volumevop": (0.188, 0.529, 0.459), # blue green
	"attribwrangle": (0.1, 0.37, 0.7), # blue
	"volumewrangle": (0.1, 0.37, 0.7), # blue
}
# Specific/general node type colors based on context. By default, node names are matched
# by a search result. "hlight", "indirectlight", etc will all be matched to "light". To
# match identically, change the last argument to the checkDicionaryForTypeName() call
# to False
node_type_colors = {
	
	"object": {

		"null": (0, 0.4, 1), # blue
		"geo": (0.8, 0.8, 0.8), # gray
		"light": (1, 0.8, 0), # yellow
		"ambient": (1, 0.8, 0), # yellow
		"cam": (0.6, 0.8, 1), # skyblue
		"bone": (0.867, 0, 0), # red
	},

	"dop": {

	},
}

# Specific tab menu folders based on context. For example, all the nodes who
# ars located in the "Forces" tab in a DOP context will be colored orange.
tool_menu_colors = {
	
	"dop": {
		"Solvers": (0, 0.3, 1), # blue
		"Objects": (0.4, 1, 0.4), # green
		"Forces": (1, 0.4, 0), # orange
	},

	"sop": {
		"Manipulate": (1, 0.8, 0), # yellow
		"Import": (0.573, 0.353, 0), # brown
	},

	"vop": {
		"Geometry": (0.4, 1, 0.4), # green
		"Utility": (1, 0.4, 0), # orange
	},
}

def getNodeTypeTool(node_type):
	""" Get the hou.Tool entry for a particular node type. """
	tools = hou.shelves.tools()
	tool_name = "%s_%s" % (node_type.category().name().lower(), node_type.name())
	return	tools.get(tool_name)

def checkDicionaryForTypeName(type_dictionary, type_name, soft_check=True):
	""" Check a dictionary for a specific node type name.

		soft_check: Use a soft check by searching for the specified type
					name in the string rather than an absolute string
					match.	This allows generic names like 'light' to
					encompass several nodes at once.
	"""
	if soft_check:
		for key, color in type_dictionary.iteritems():
			if type_name.find(key) != -1:
				return color
		return	None
	else:
		# Try for a direct match of the type name.
		return type_dictionary.get(type_name)

# Node type information
node = kwargs["node"]
node_type = node.type()
node_type_name = node_type.name()
type_category_name = node_type.category().name().lower()

#  Start with no node color:
node_color = None

# Manager nodes (sopnet, chopnet, ropnet, etc).
if node_type.isManager():
	node_color = manager_color

# Common node types (nulls, switches, etc) are colored the same across
# different contexts.
elif node_type_name in common_type_colors:
	node_color = common_type_colors[node_type_name]

else:
	# Get the color mappings for this context.
	type_colors = node_type_colors.get(type_category_name)

	if type_colors is not None:
		# Check to see if there ars any mappings for this type.
		node_color = checkDicionaryForTypeName(type_colors, node_type_name, True)

	# If there were no mappings for the specific type, check for the tab
	# menu.
	if node_color is None:
		# Get the tool for the node type.
		tool = getNodeTypeTool(node_type)

		# Get a tuple of possible tab menu locations this tool will appear.
		try:
			menu_locations = tool.toolMenuLocations()
		except AttributeError:
			pass

		# Get any possible colored menu locations for this context.
		menu_colors = tool_menu_colors.get(type_category_name)

		if menu_colors is not None:
			# Iterate over all the possible locations for the tool.
			try:
				for location in menu_locations:
					# Try and get the color of the location.
					node_color = menu_colors.get(location)
					# If we got a color then use it.
					if node_color is not None:
						break
			except NameError:
				pass

	# If there have been no previous assignments, color generator nodes.
	if node_color is None and node_type.isGenerator():
		node_color = generator_color

# If we found a color mapping, set the color of the node.
if node_color is not None:
	node.setColor(hou.Color(node_color))<file_sep>import hou
import os
import json
from utility_scripts import main as util
reload(util)

proj_list = 'D:\Job\Study\Rebelway\Python\Week_6\project_list.json'

def read_json():
    try:
        with open(proj_list, 'r') as f:
            data = json.load(f)
    except ValueError:
        data = {}

    return data


# def fix_path(old_path, new_sep='/'):
#     _path = old_path.replace('\\', '/')
#     _path = old_path.replace('\\\\', '/')
#     _path = _path.replace('//', '/')
#
#     if _path.endswith('/'):
#         _path = _path[:-1]
#
#     _path = _path.replace('/', new_sep)
#
#     new_path = _path
#     return new_path
#
#
# def error(message, severity=hou.severityType.Error):
#     print('{severity}: {message}'.format(severity=severity.name(), message=message))
#     hou.ui.displayMessage(message, severity=severity)
#
#
# def print_report(header, *body):
#     print('\n{header:-^50}'.format(header=header))
#
#     for b in body:
#         print('\t{0}'.format(b))
#
#     print('-'*50)


def manage_proj():
    sel = hou.ui.displayMessage('Select an action', buttons=('Add', 'Remove', 'Details', 'Cancel'))
    if sel == 0:
        add_proj()
    elif sel == 1:
        remove_proj()
    elif sel == 2:
        details_proj()
    else:
        return


def add_proj():
    data = read_json()
    # Init
    _proj_name = None
    path = None
    path_name = None
    path_code = None
    path_fps = None
    # Select Proejct Path
    repeat = True
    while repeat:
        repeat = False
        _path = hou.ui.selectFile(title='Select Project Directory', file_type=hou.fileType.Directory)
        path = os.path.dirname(_path)

        if path == '':
            return

        for k, v in data.items():
            if util.fix_path(path) == util.fix_path(v['PATH']):
                util.error('Project path is already used by another project {0}\nPlease select a different path'.format(k))
                repeat = True
                break
        if repeat:
            continue


        _proj_name = os.path.split(path)[-1]


    # Select Project Name, Code and FPS
    repeat = True
    while repeat:
        repeat = False
        inputs = hou.ui.readMultiInput(message='Enter Project Data', input_labels=('Project Name', 'Project Code', 'FPS'),
                                       buttons=('OK', 'Cancel'), initial_contents=(_proj_name, '', '24'))

        if inputs[0] == 1:
            return

        proj_name = inputs[1][0]
        proj_code = inputs[1][1]
        proj_fps = inputs[1][2]

        if proj_name == '' or proj_code == '' or proj_fps == '':
            util.error('Please fill in all fields')
            repeat = True
            continue

        try:
            proj_fps = int(proj_fps)
        except ValueError:
            util.error('FPS not set to a number. \n Please enter a whole number')
            repeat = True
            continue

        for k, v in data.items():
            if proj_name == k:
                util.error('Project name is already in use\nPlease select a different name')
                repeat = True
                break

            if proj_code == v['CODE']:
                util.error('Project code is already in use\nPlease select a different code')
                repeat = True
                break

        if repeat:
            continue





    if proj_name and proj_code and proj_fps:
        proj_data = {
            'CODE' : proj_code,
            'PATH' : path,
            'FPS' : proj_fps
        }
        data[proj_name] = proj_data

    if data:
        with open(proj_list, 'w') as f:
            json.dump(data, f, sort_keys=True, indent=4)


def remove_proj():
    data = read_json()
    projects = data.keys()
    sel = hou.ui.selectFromList(projects, message='Select Project to Remove', title='Remove Project',
                          column_header='Projects', clear_on_cancel=True)
    if len(sel) == 0:
        return

    for i in sel:
        key = projects[i]
        del data[key]

    with open(proj_list, 'w') as f:
        json.dump(data, f, sort_keys=True, indent=4)


def details_proj():
    data = read_json()
    projects = data.keys()
    sel = hou.ui.selectFromList(projects, exclusive=True, message='Select Project to view details',
                                title='Project Details', column_header='Projects', clear_on_cancel=True)
    if len(sel) == 0:
        return

    proj = projects[sel[0]]
    proj_data = data[proj]

    util.print_report('Project Details',
                 'Name: {0}'.format(proj),
                 'Code: {0}'.format(proj_data['CODE']),
                 'Path: {0}'.format(proj_data['PATH']),
                 'FPS: {0}'.format(proj_data['FPS'])
                 )
<file_sep>#-*- coding:utf-8 -*-


import hou
import os
import math
from pprint import pprint
from itertools import product
from decimal import Decimal

menu_list = []


# 파라미터에 입력된 Wedge 값들을 얻어오는 함수
def get():
    global menu_list
    node = hou.pwd()
    parm = 'wedge_parm'
    node.parm('wedge_select').set(0)

    wedge_parms = node.parm(parm).multiParmInstances()

    value_list = []

    for i in wedge_parms:
        value_list.append(i.eval())

    dl = divide_list(value_list, 0, len(value_list), 6)

    wedge_val_list = []


    for j in dl:
        # Use Set Value가 켜져있는지 체크
        if j[4] == 0:
            # 상승값이 0일 경우 첫번째 Parm의 값으로 리스트 구성
            if j[3] == 0:
                wedge_val_list.append([j[1], j[1], j[1]])
            else:
                wedge_val_list.append(increase(j[1], j[2], j[3]))

        else:
            custom_list = j[-1].split(' ')
            set_val = []
            for c in custom_list:
                set_val.append(float(c))
            wedge_val_list.append(set_val)


    noc_list = list(product(*wedge_val_list))

    for i, n in enumerate(noc_list):
        noc_list[i] = list(n)



    wirte_wedge_val(node, len(noc_list), noc_list)

    menu_list = wedge_select_list(len(noc_list))



# 최종적으로 현재씬에 적용할 Wedge 값을 불러오는 함수
def import_btn():
    node = hou.pwd()
    parm = node.parm('wedge_select')
    parm_val = parm.eval()
    load_value = node.parm('wedge_list').eval().split('\n')

    value_list = []

    wedge_parms = node.parm('wedge_parm').multiParmInstances()

    for i in wedge_parms:
        if 'chs' in i.rawValue():
            value_list.append(i.rawValue()[6:-3])
        else:
            pass


    import_value_list = []

    for l in load_value:
        import_value_list.append(l.split(' - ')[-1])

    import_value = import_value_list[parm_val][1:-1]

    import_parm = node.parm('import_value')
    import_parm.lock(False)
    import_parm.set(import_value)
    import_parm.lock(True)

    set_value = import_value_list[parm_val][1:-1].split(', ')

    for v, s in zip(value_list, set_value):
        hou.parm(v).set(float(s))





# Wedge에 대한 값들을 Text로 출력해주는 함수
def wirte_wedge_val(node, wedge_count, noc):
    text = ''
    for i, n in zip(range(wedge_count), noc):
        text = text + 'WEDGE ' + str(i) + ' - ' + str(n) + '\n'

    list_parm = node.parm('wedge_list')
    list_parm.lock(False)
    list_parm.set(text)
    list_parm.lock(True)

    total_parm = node.parm('total_count')
    total_parm.lock(False)
    total_parm.set(str(wedge_count))
    total_parm.lock(True)



def wedge_select_list(wedge_count):
    result_list = []
    for i in range(wedge_count):
        result_list.append('{}'.format(i))
        result_list.append('WEDGE {}'.format(i))

    return result_list



# 기능 구현만 해두고 사용하지 않은 함수임
# Wedge 경우의 수에 따른 파라미터 생성
def add_parm(node):
    ptg = node.parmTemplateGroup()

    if ptg.parmTemplates()[-1].name() == 'wedge_list':
        for i in ptg.parmTemplates()[-1].parmTemplates():
            node.parm(i.name()).set(10)
    else:
        parm_folder = hou.FolderParmTemplate('wedge_list', 'Wedge List')
        parm_folder.setFolderType(hou.folderType.Simple)
        parm_folder.addParmTemplate(hou.FloatParmTemplate('first', 'First', 1))
        parm_folder.addParmTemplate(hou.FloatParmTemplate('last', 'Last', 1))
        ptg.append(parm_folder)

    node.setParmTemplateGroup(ptg)



# 리스트를 특정 갯수로 나누는 함수
def divide_list(source_list, start_pos, end_pos, div):
    div_list = []

    for i in range(start_pos, end_pos + div, div):
        out = source_list[start_pos:start_pos + div]
        if out != []:
            div_list.append(out)
        start_pos = start_pos + div

    return div_list



# 주어진 숫자가 상승되는 리스트
def increase(val0, val1, val2):
    list = [val0, val1, val2]
    icnt = list[0]
    val_list = []
    while (icnt <= list[1]):
        icnt += list[-1]
        val_list.append(float(str(icnt - list[-1])))    # 부동소수점 제거를 위해 float을 str로 변환하고 다시 float으로 변환
    return val_list
<file_sep>import datetime
import hou
import os
import re
import json
import shutil
from save_scene import main as save_scene
reload(save_scene)
from utility_scripts import main as util
reload(util)



def cache_dir():
    root = hou.getenv('OUTPUT_PATH')
    if not root:
        root = hou.getenv('HIP')
        root = os.path.join(root, 'Output')
    root = util.fix_path(root)

    sub_folders = ['cache']
    path = util.fix_path(os.sep.join(root.split('/') + sub_folders))

    return path


def cache_path(mode='path'):
    node = hou.pwd()

    name = node.evalParm('cache_name')

    if node.evalParm('enable_version'):
        ver = '_v{0:0>3}'.format(node.evalParm('version'))
    else:
        ver = ''


    if node.evalParm('trange') > 0:
        frame = '.{0:0>4}'.format(int(hou.frame()))
    else:
        frame = ''

    ext = node.evalParm('ext')

    full_name = '{name}{ver}{frame}{ext}'.format(name=name, ver=ver, frame=frame, ext=ext)


    path = util.fix_path(os.path.join(node.evalParm('cache_dir'), full_name))

    if mode == 'path':
        return path
    elif mode == 'name':
        return full_name
    else:
        return


def auto_version(node, forced=False):
    if node.evalParm('enable_version') and (node.evalParm('auto_version') or forced):
        cache_dir = node.evalParm('cache_dir')
        if not os.access(cache_dir, os.F_OK):
            node.parm('version').set(1)
            return

        files = os.listdir(cache_dir)

        versions_list = []
        for f in files:
            if not os.path.isdir(os.path.join(cache_dir, f)):
                regex = '(?P<name>{0})_v(?P<ver>\\d+)\\..+'.format(node.evalParm('cache_name'))
                match = re.match(regex, f)
                if match:
                    versions_list.append(int(match.group('ver')))

        if len(versions_list) == 0:
            node.parm('version').set(1)
            return

        else:
            versions_list = list(set(versions_list))
            versions_list.sort()

            latest_version = versions_list[-1]
            if forced:
                node.parm('version').set(latest_version)
            else:
                node.parm('version').set(latest_version+1)

    return


def latest_version(kwargs):
    node = kwargs['node']
    auto_version(node, forced=True)
    node.parm('reload').pressButton()
    return


def watchlist_val_parm(node_num, parm_num):
    node = hou.parm('watch_node_{0}'.format(node_num)).evalAsNode()
    parm_name = hou.evalParm('watch_parm_{0}_{1}'.format(node_num, parm_num))
    watch_parm = node.parm(parm_name)

    if not watch_parm:
        return

    has_keyframe = len(watch_parm.keyframes()) > 0

    try:
        watch_parm.expression()
        is_expr = True
    except hou.OperationFailed:
        is_expr = False

    if has_keyframe and not is_expr:
        return '<< Animated Parameter >>'
    elif has_keyframe and is_expr:
        return '<< Expression >>'
    else:
        return watch_parm.evalAsString()


def watchlist_action(kwargs):
    node = kwargs['node']

    parent_num = kwargs['script_multiparm_index2']
    parent_parm = node.parm('watch_node_{0}'.format(parent_num))
    parent_node = parent_parm.evalAsNode()

    if not parent_node:
        util.error('Invalid node selected')
        return

    parm_list = []
    for p in parent_node.parms():
        template = p.parmTemplate()
        parm_type = template.type()
        if parm_type == hou.parmTemplateType.Folder or parm_type == hou.parmTemplateType.FolderSet:
            continue

        parm_list.append(p)

    tree_list = []
    for p in parm_list:
        hierarchy = list(p.containingFolders())
        hierarchy.append('{0} ({1})'.format(p.parmTemplate().label(), p.name()))
        tree_list.append('/'.join(hierarchy))

    choice = hou.ui.selectFromTree(tree_list, exclusive=True, message='Select a parameter to watch',
                                   title='Watchlist Select', clear_on_cancel=True)
    if len(choice) > 0:
        idx = tree_list.index(choice[0])
        parm = parm_list[idx]

        val_parm = kwargs['parmtuple'][0]
        name_parm = node.parm(val_parm.name()[:-4])
        name_parm.set(parm.name())

    return


def watchlist_write():
    def set_string_attrib(attrib_name, attrib_val):
        if not geo.findGlobalAttrib(attrib_name):
            geo.addAttrib(hou.attribType.Global, attrib_name, '', create_local_variable=False)
        geo.setGlobalAttribValue(attrib_name, attrib_val)


    node = hou.pwd()
    parent = node.parent()
    geo = node.geometry()

    set_string_attrib('hipfile_path', parent.evalParm('hipfile_path'))
    set_string_attrib('hipfile_date', parent.evalParm('hipfile_date'))
    set_string_attrib('hipfile_project', parent.evalParm('hipfile_project'))
    set_string_attrib('hipfile_source', parent.evalParm('hipfile_source'))
    set_string_attrib('hipfile_error', parent.evalParm('hipfile_error'))

    watch_metadata = {}
    num_watch_nodes = parent.evalParm('watchlist_parms')
    for n in range(num_watch_nodes):
        watch_node = parent.parm('watch_node_{0}'.format(n+1)).evalAsNode()

        if not watch_node:
            continue
        watch_node_path = watch_node.path()

        watch_metadata[watch_node_path] = {}

        num_watch_parms = parent.evalParm('watch_parms_{0}'.format(n+1))
        for p in range(num_watch_parms):
            key = parent.evalParm('watch_parm_{0}_{1}'.format(n+1, p+1))

            watch_parm = hou.parm('{0}/{1}'.format(watch_node_path, key))
            if not watch_parm:
                continue

            has_keyframe = len(watch_parm.keyframes()) > 0

            try:
                watch_parm.expression()
                is_expr = True
            except hou.OperationFailed:
                is_expr = False

            if has_keyframe and not is_expr:
                val = ('<< Animated Parameter >>', '<< Animated Parameter >>')
            else:
                val = (watch_parm.eval(), watch_parm.evalAsString())

            watch_metadata[watch_node_path][key] = val

    _watch_metadata = json.dumps(watch_metadata)
    set_string_attrib('watchlist', _watch_metadata)

    return


def watchlist_read(kwargs):
    def lock_parms(val):
        for p in node.parms():
            if p.name().startswith('read_') and p.name().endswith('_val'):
                p.lock(val)


    node = kwargs['node']
    read_node = node.node('READ_METADATA')
    geo = read_node.geometry()

    if not geo or not node.evalParm('load'):
        watchlist_dict = {}
    else:
        try:
            watchlist = geo.attribValue('watchlist')
            watchlist_dict = json.loads(watchlist)
        except hou.OperationFailed:
            watchlist_dict = {}


    lock_parms(False)

    num_keys = len(watchlist_dict.keys())
    node.parm('read_watchlist_parms').set(num_keys)

    for i, (k, v) in enumerate(watchlist_dict.items()):
        node.parm('read_watch_node_{0}'.format(i+1)).set(k)

        num_parm_keys = len(v.keys())
        node.parm('read_watch_parms_{0}'.format(i+1)).set(num_parm_keys)

        for i2, (k2, v2) in enumerate(v.items()):
            node.parm('read_watch_parm_{0}_{1}'.format(i+1, i2+1)).set(k2)
            node.parm('read_watch_parm_{0}_{1}_val'.format(i+1, i2+1)).set(v2[1])

    lock_parms(True)


def watchlist_restore_single(kwargs):
    node = kwargs['node']
    read_node = node.node('READ_METADATA')
    geo = read_node.geometry()

    watchlist = geo.attribValue('watchlist')
    watchlist_dict = json.loads(watchlist)

    parent_num = kwargs['script_multiparm_index2']
    parent_parm = node.parm('read_watch_node_{0}'.format(parent_num))
    parent_node = parent_parm.evalAsNode()

    if not parent_node:
        util.error('Node to restore to [{0}] does not exist'.format(parent_parm.evalAsString()))
        return

    parm_num = kwargs['script_multiparm_index']
    parm = node.parm('read_watch_parm_{0}_{1}'.format(parent_num, parm_num))
    parm_name = parm.eval()

    parm_to_restore = parent_node.parm(parm_name)
    if not parm_to_restore:
        util.error('Parm to restore [{0}/{1}] does not exist'.format(parent_node.path(), parm_name))
        return

    vals = watchlist_dict[parent_node.path()][parm_name]

    if vals[0] == '<< Animated Parameter >>':
        util.error('This parm [{0}] is an Animated Parameter and cannot be restored this way'.format(parm_name),
                   severity=hou.severityType.Warning)
        return

    try:
        parm_to_restore.set(vals[0])
        print('Parm [{0}/{1}] restored to [{2}]'.format(parent_node.path(), parm_name, vals[1]))
    except TypeError:
        parm_to_restore.set(vals[1])
        print('Parm [{0}/{1}] restored to [{2}]'.format(parent_node.path(), parm_name, vals[1]))

    return



def save_backup_hip(node):
    def generateReport(success, **kwargs):
        parent.parm('hipfile_path').set('None')
        parent.parm('hipfile_date').set('None')
        parent.parm('hipfile_error').set('None')
        parent.parm('hipfile_project').set('None')
        parent.parm('hipfile_source').set('None')


        if success:
            util.print_report(
                'Scene Backup Report',
                'Status: Successful',
                'Scene File: {0}'.format(kwargs['scenefile']),
                'Date Created: {0}'.format(kwargs['date'])
            )
            parent.parm('hipfile_path').set(kwargs['scenefile'])
            parent.parm('hipfile_date').set(kwargs['date'])
            parent.parm('hipfile_project').set(hou.getenv('PROJECT'))
            parent.parm('hipfile_source').set(hou.hipFile.basename())

        else:
            util.print_report(
                'Scene Backup Report',
                'Status Failed',
                'Error Log: {0}'.format(kwargs['error'])
            )
            parent.parm('hipfile_error').set(kwargs['error'])

    def error_report(message, severity=hou.severityType.Error):
        util.error(message, severity=severity)
        generateReport(False, error=message)

    ### Notes ###
    # file = name of file
    # dir = path to folder
    # path = dir/file

    parent = node.parent()

    backup_dir = hou.getenv('HOUDINI_BACKUP_DIR')
    if not backup_dir:
        hip = hou.getenv('HIP')
        backup_dir = util.fix_path(os.path.join(hip, 'backup'))
        # hou.putenv('HOUDINI_BACKUP_DIR', backup_dir)

    if not os.access(backup_dir, os.F_OK):
        try:
            os.makedirs(backup_dir)
        except:
            error_report('Unable to create backup directory')
            return

    old_files = os.listdir(backup_dir)
    hou.hipFile.save()
    hou.hipFile.saveAsBackup()
    new_files = os.listdir(backup_dir)

    # delta = []
    # for f in new_files:
    #     if f not in old_files:
    #         delta.append(f)

    delta = [f for f in new_files if f not in old_files]

    if len(delta) > 1:
        error_report('Unable to link backup file')
        return

    new_backup_file = delta[0]
    if not new_backup_file:
        error_report('Unable to link backup file')
        return

    new_backup_path = util.fix_path(os.path.join(backup_dir, new_backup_file))

    cache_path = node.evalParm('sopoutput')
    _split = os.path.split(cache_path)
    cache_dir = util.fix_path(_split[0])
    cache_file = _split[1]
    cache_name = cache_file.split('.')[0]

    cache_hip_dir = os.path.join(cache_dir, 'cache_hips')

    if not os.access(cache_hip_dir, os.F_OK):
        try:
            os.makedirs(cache_hip_dir)
        except:
            error_report('Unable to create a directory for cache .hip files')
            return

    cache_hip_file = '{name}{ext}'.format(name=cache_name, ext=os.path.splitext(new_backup_file)[-1])
    cache_hip_path = util.fix_path(os.path.join(cache_hip_dir, cache_hip_file))

    try:
        shutil.copy(new_backup_path, cache_hip_path)
    except:
        error_report('Unable to copy backup file to cache .hip file directory')
        return

    date = datetime.datetime.now()
    generateReport(True, scenefile=cache_hip_path, date=str(date))


def hip_actions(action):
    node = hou.pwd()

    metadata_node = node.node('READ_METADATA')
    hip_file = metadata_node.geometry().attribValue('hipfile_path')

    if hip_file == '' or not hip_file:
        return

    if not os.access(hip_file, os.F_OK):
        return

    if action == 'open':
        hou.hipFile.load(hip_file)

    if action == 'explore':
        util.open_explorer(hip_file)
        pass

    return


def restore(kwargs):
    node = kwargs['node']

    scene_data = None
    for n in hou.node('/obj').children():
        if n.type().nameComponents()[2] == 'scene_data':
            scene_data = n
            break
    if not scene_data:
        util.error('Scene Data node not found. Scene cannot be correctly restored')
        return

    if os.path.dirname(hou.hipFile.path()) == hou.getenv('SAVE_PATH'):
        message = 'Current .hip already seems to be saved to \"working_files\" directory\n'\
                  'Are you sure you want to perform this operation?'

        choice = hou.ui.displayMessage(message, buttons=('Yes', 'No'), severity=hou.severityType.Warning)
        if choice == 1:
            return

    try:
        metadata = node.node('READ_METADATA').geometry().attribValue('hipfile_source')
    except hou.OperationFailed:
        util.error('Unable to find source file in metadata')
        return

    regex = r'(?P<scene>^\w+)-(?P<task>\w+)-(?P<ver>v\d{3,})(-(?P<desc>\w+))?-(?P<user>\w+)\.(?P<ext>hip\w*$)'
    match = re.match(regex, metadata)
    if not match:
        util.error('Source does not align with correct naming convertion. \n'
                   'Unable to restore file correctly')
        return

    task = match.group('task')
    if not task or task == '':
        util.error('Unable to find task name from metadata.\n'
                   'Reverting to "restore" task name', severity=hou.severityType.Warning)
        task = 'restore'

    desc = 'restore'
    save_scene.save_scene(None, task, desc)


def prerender(node):
    auto_version(node.parent())
    save_backup_hip(node)

    return

def preframe(node):
    # print('preframe')
    return

def postframe(node):
    # print('postframe')
    return

def postwrite(node):
    # print('postwrite')
    return

def postrender(node):
    # print('postrender')
    return<file_sep>#-*- coding:utf-8 -*-

import os
import hou

hip_dir = hou.hscriptExpression('$HIP')
log_dir = '/script/sim_log/'
node_name = hou.hscriptExpression('opname("..")')

ver = hou.hscriptExpression('$VER')
wipver = hou.hscriptExpression('$WIPVER')


density_log = open(hip_dir + log_dir + 'density.txt', 'r')
density_lead = density_log.readlines()
# 개행문자 제거
density_lead = list(map(lambda s: s.strip(), density_lead))
density_max = max(density_lead)

temperature_log = open(hip_dir + log_dir + 'temperature.txt', 'r')
temperature_lead = temperature_log.readlines()
# 개행문자 제거
temperature_lead = list(map(lambda s: s.strip(), temperature_lead))
temperature_max = max(temperature_lead)

heat_log = open(hip_dir + log_dir + 'heat.txt', 'r')
heat_lead = heat_log.readlines()
# 개행문자 제거
heat_lead = list(map(lambda s: s.strip(), heat_lead))
heat_max = max(heat_lead)


# 정수 패딩 제거
density_max = density_max.replace('0', ' ').lstrip().replace(' ', '0')
temperature_max = temperature_max.replace('0', ' ').lstrip().replace(' ', '0')
heat_max = heat_max.replace('0', ' ').lstrip().replace(' ', '0')


max_log_dir = hip_dir + "/script/" + node_name + '_v' + ver.zfill(2) + '_w' + wipver.zfill(2) + '_' +"max_log.txt"


with open(max_log_dir, 'w') as max_log:
    max_log.write('density: ' + str(density_max) + "\n")
    max_log.write('temperature: ' + str(temperature_max) + "\n")
    max_log.write('heat: ' + str(heat_max) + "\n")
<file_sep>import hou
import json
import os
import sys
from utility_scripts import main as util

proj_list = 'D:\Job\Study\Rebelway\Python\Week_6\project_list.json'


def read_json():
    try:
        with open(proj_list, 'r') as f:
            data = json.load(f)
    except ValueError:
        data = {}

    return data


def create_folder_and_var(var, path):
    path = util.fix_path(path)
    hou.putenv(var, path)

    if not os.access(path, os.F_OK):
        os.makedirs(path)
        print('Creating variable {0} and folder [{1}]'.format(var, path))

    return


def unset_all_scene_vars():
    variables = [
        'SCENE',
        'SCENE_PATH',
        'SAVE_PATH',
        'OUTPUT_PATH',
        'CACHE_PATH',
        'RENDER_PATH'
    ]
    for v in variables:
        hou.unsetenv(v)
    return


def project_menu(kwargs):
    data = read_json()
    menu = ['-', '-']
    for k in data.keys():
        menu.append(k)
        menu.append(k)

    return menu


def scene_menu(kwargs):
    menu = []
    scenes_path = hou.getenv('SCENES_PATH')
    if scenes_path and os.access(scenes_path, os.F_OK):
        for f in os.listdir(scenes_path):
            if os.path.isdir(util.fix_path(os.path.join(scenes_path, f))):
                menu.append(f)
                menu.append(f)
    return menu


def set_project(kwargs):
    node = kwargs['node']
    project_name = node.evalParm('proj')
    # project_name = kwargs['script_value']

    node.parm('scene').set('')
    unset_all_scene_vars()

    data = read_json()

    if project_name == '-':
        hou.unsetenv('PROJECT')
        hou.unsetenv('CODE')
        hou.unsetenv('PROJ_FPS')
        hou.setFps(24)
        hou.unsetenv('PROJECT_PATH')
        hou.unsetenv('SCENES_PATH')
        hou.unsetenv('HDA_PATH')
        hou.unsetenv('SCRIPTS_PATH')
        node.cook(True)
        return

    try:
        project_data = data[project_name]
    except KeyError:
        util.error('Project Data not found')
        return

    hou.putenv('PROJECT', project_name)

    hou.putenv('CODE', project_data['CODE'])

    fps = project_data['FPS']
    hou.putenv('PROJ_FPS', str(fps))
    hou.setFps(fps)

    project_path = project_data['PATH']
    hou.putenv('PROJECT_PATH', project_data['PATH'])

    create_folder_and_var('SCENES_PATH', util.fix_path(os.path.join(project_path, 'scenes')))

    hda_path = util.fix_path(os.path.join(project_path, 'hda'))
    create_folder_and_var('HDA_PATH', hda_path)

    scripts_path = util.fix_path(os.path.join(project_path, 'scripts'))
    create_folder_and_var('SCRIPTS_PATH', scripts_path)

    hda_paths = [hda_path, ]
    scan_path = hou.getenv('HOUDINI_OTLSCAN_PATH')
    if scan_path:
        hda_paths += scan_path.split(';')
    hda_paths = list(set(hda_paths))
    hou.putenv('HOUDINI_OTLSCAN_PATH', ';'.join(hda_paths))
    hou.hda.reloadAllFiles()

    sys.path.append(scripts_path)

    node.cook(True)


def set_scene(kwargs):
    node = kwargs['node']
    scene_name = node.evalParm('scene')

    # If null scene > unset all
    if scene_name == '':
        unset_all_scene_vars()
        node.cook(True)
        return


    # If no PROJECT_PATH var
    project_path = hou.getenv('PROJECT_PATH')
    if not project_path or not os.access(project_path, os.F_OK):
        util.error('Project path is invalid')
        return

    # If no SCENES_PATH var
    scenes_path = hou.getenv('SCENES_PATH')
    if not scenes_path or not os.access(scenes_path, os.F_OK):
        util.error('Scenes path is invalid')
        return

    # If SCENES_PATH var but no folder
    if not os.access(scenes_path, os.F_OK):
        os.makedirs(scenes_path)

    scene_path = util.fix_path(os.path.join(scenes_path, scene_name))
    if not os.access(scene_path, os.F_OK):
        message = 'Scene folder "{0}" does not exist\n'\
                  'Create this folder now?'.format(scene_name)
        choice = hou.ui.displayMessage(message, severity=hou.severityType.ImportantMessage, buttons=('Yes', 'No'))
        if choice == 0:
            os.makedirs(scene_path)
        else:
            unset_all_scene_vars()
            node.cook(True)
            return

    hou.putenv('SCENE', scene_name)
    hou.putenv('SCENE_PATH', scene_path)

    create_folder_and_var('SAVE_PATH', os.path.join(scene_path, 'working_files'))

    output_path = os.path.join(scene_path, 'output')
    create_folder_and_var('OUTPUT_PATH', output_path)
    create_folder_and_var('CACHE_PATH', os.path.join(output_path, 'cache'))
    create_folder_and_var('RENDER_PATH', os.path.join(output_path, 'render'))

    node.cook(True)


def onLoaded(kwargs):
    node = kwargs['node']
    curr_scene = node.evalParm('scene')
    # print(curr_scene)

    node.parm('proj').pressButton()
    if not curr_scene == '':
        node.parm('scene').set(curr_scene)
        if curr_scene in scene_menu({}):
            node.parm('scene').pressButton()


def onCreated(kwargs):
    node = kwargs['node']

    node.setName('SCENE_DATA')

    # node.setUserData('nodeshape', 'circle')
    node.setColor(hou.Color(0.58, 0.2, 0.48))
    node.setGenericFlag(hou.nodeFlag.Display, False)
    node.setGenericFlag(hou.nodeFlag.Selectable, False)

    node.parm('proj').set(hou.getenv('PROJECT'))
    node.parm('scene').set(hou.getenv('SCENE'))
<file_sep>#-*- coding:utf-8 -*-

import hou
import os
import json
import time
reload(time)
from collections import OrderedDict




# Slate에 작성될 GLOBAL 변수
hip_dir = hou.hscriptExpression("$HIP")
hip_name = hou.hscriptExpression("$HIPNAME")
# username = hou.hscriptExpression("$FXUSER")
username = 'nosung'

# Simulation Log에 대한 json 데이터를 저장할 경로
log_dir = hip_dir + "/simulation_log"


hip_dict = {'hip_dir':hip_dir, 'hip_name':hip_name, 'username':username, 'log_dir':log_dir}

houdini_os = hou.hscriptExpression("$HOUDINI_OS")



def convert_path(path):
    if 'window' in houdini_os.lower():
        repath = path.replace('/', '\\\\')
    else:
        repath = path

    return repath


def read_info():
    node = hou.pwd()

    today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    nowtime = time.strftime('%H-%M-%S', time.localtime(time.time()))

    path_list = []
    parm_path_list = hou.pwd().parms()
    for i in list(parm_path_list):
        if 'parm_path' in i.name():
            path = i.rawValue().split('"')[1]
            path = path
            path_list.append(path)

    lv_list = []

    for j in path_list:
        parm = hou.parm(j)
        parm_label = parm.description() + ' (' + parm.name() + ')'
        parm_value = parm.eval()

        lv_list.append([parm_label, str(parm_value)])

    parm_dict = dict(zip(range(len(lv_list)), lv_list))

    for i, v in enumerate(parm_dict.items()):
        parm_dict[i] = dict([parm_dict[i]])

    write_dict = dict(Hip_information=hip_dict, Parameter=parm_dict)


    write_json(write_dict, today, nowtime)
    load_list = load_json(today, nowtime)

    node.parm('title').set(hip_name)
    node.parm('user').set(username)
    node.parm('time').set(today + ' ' + nowtime)

    text = ''

    for l in load_list:
        text = text + str(l)
        node.parm('text').set(text + '\n')


def write_json(dict_data, today, nowtime):
    json_data = OrderedDict()
    json_data = dict_data

    json_save_dir = log_dir + "/json"

    if os.path.isdir(log_dir) == False:
        os.mkdir(log_dir)
    if os.path.isdir(json_save_dir) == False:
        os.mkdir(json_save_dir)

    json_file = json_save_dir + '/' + hip_name + '_' + today + '_' + nowtime + ".json"


    with open(convert_path(json_file), 'w') as make_file:
        json.dump(json_data, make_file, ensure_ascii=False, indent=4)


def load_json(today, nowtime):
    json_save_dir = log_dir + "/json"
    json_file = json_save_dir + '/' + hip_name + '_' + today + '_' + nowtime + ".json"

    out_list = []

    with open(convert_path(json_file)) as load_file:
        json_data = json.load(load_file)
        parm_data = json_data['Parameter']
        parm_data = sorted(parm_data.items())

    for data in parm_data:
        k_encode = data[0].encode('utf-8')
        v = data[1].items()[0]
        v_encode = str(v[0]).encode('utf-8') + ': ' + str(v[1]).encode('utf-8') + '\n'
        convert_json = k_encode + ' ' + v_encode
        out_list.append(convert_json)
        out_list.sort()

    write_list = [i[2:] for i in out_list]

    return write_list
<file_sep>import hou

hou.node('/obj').createNode('geo')
hou.hipFile.save(file_name='/home/gulliver/Desktop/Job/Study/command_line/test_v01.hip')
<file_sep># -*- coding:utf-8 -*-

import sys
sys.path.append("/core/inhouse/rez/packages/python_library/2.7/python/site-packages")

import pyperclip
import os
import hou


nodes = hou.selectedNodes()

cam_path_list = []
out_path_list = []
start_f_list = []
end_f_list = []
resx_list = []
resy_list = []
name_list = []



for node in nodes:
    cam_path_list.append(node.parm('camera').eval())
    start_f_list.append(node.parm('f1').eval())
    end_f_list.append(node.parm('f2').eval())
    name_list.append(node.name())

    if node.parm('override_camerares').eval() == 0:
        resx_list.append(hou.parm(node.parm('camera').eval() + '/resx').eval())
        resy_list.append(hou.parm(node.parm('camera').eval() + '/resy').eval())
    else:
        res_mult = node.parm('res_fraction').eval()
        resx = hou.parm(node.parm('camera').eval() + '/resx').eval()
        resy = hou.parm(node.parm('camera').eval() + '/resy').eval()

        resx_list.append(int(round(float(resx) * float(res_mult))))
        resy_list.append(int(round(float(resy) * float(res_mult))))


    node_name = node.type().name()

    if 'Arnold' in node_name:
        out_path_split = node.parm('ar_picture').eval().split('.')
    elif 'Mantra' in node_name:
        out_path_split = node.parm('vm_picture').eval().split('.')
    else:
        pass

    out_path_split[-2] = '####'

    new_path = '.'.join(out_path_split)
    out_path_list.append(new_path)




def write_script(path, resx, resy, start_f, end_f, name, xpos, ypos):
    head = 'set cut_paste_input [stack 0]\nversion 12.0 v3\n'
    read_head = 'Read {\n inputs 0\n'
    file_type = ' file_type exr\n'
    file_path = ' file {}\n'.format(path)
    img_format = ' format "{0} {1}"\n'.format(resx, resy)
    first = ' first ' + str(int(start_f)) + '\n'
    last = ' last ' + str(int(end_f)) + '\n'
    origfirst = ' origfirst ' + str(int(start_f)) + '\n'
    origlast = ' origlast ' + str(int(end_f)) + '\n'
    origset = ' origset true\n'
    version = ' version 0\n'
    name = ' name {}\n'.format(name)
    selected = ' selected true\n'
    xpos = ' xpos {}\n'.format(xpos)
    ypos = ' ypos {}\n'.format(ypos)
    end = '}'

    read_list = [
        head,
        read_head,
        file_type,
        file_path,
        img_format,
        first,
        last,
        origfirst,
        origlast,
        version,
        name,
        selected,
        xpos,
        ypos,
        end
    ]

    read_script = ''

    for j in read_list:
        read_script += j

    return read_script





result = ''

for i, (out, resx, resy, start_f, end_f) in enumerate(zip(out_path_list, resx_list, resy_list, start_f_list, end_f_list)):
    result += write_script(out_path_list[i], resx_list[i], resy_list[i], start_f_list[i], end_f_list[i], name_list[i], i*100, 0) + '\n'



pyperclip.copy(result)<file_sep>import subprocess
import os
import hou


def fix_path(old_path, new_sep='/'):
    _path = old_path.replace('\\', '/')
    # _path = old_path.replace('\\\\', '/')
    _path = _path.replace('//', '/')

    if _path.endswith('/'):
        _path = _path[:-1]

    _path = _path.replace('/', new_sep)

    new_path = _path

    return new_path


def error(message, severity=hou.severityType.Error):
    print('{severity}: {message}'.format(severity=severity.name(), message=message))
    hou.ui.displayMessage(message, severity=severity)


def print_report(header, *body):
    print('\n{header:-^50}'.format(header=header))

    for b in body:
        print('\t{0}'.format(b))

    print('-'*50)


def open_explorer(path):
    path = os.path.dirname(path)
    path = fix_path(path, os.path.sep)

    open_path = 'explorer {0}'.format(path)
    subprocess.Popen(open_path, shell=True)
    return<file_sep>print('importing the Project Tools Module')<file_sep>import hou
import os
import re
from utility_scripts import main as util
reload(util)


def clean_name(name):
    new_name = name.lower().strip()
    regex = r'\W+'
    new_name = re.sub(regex, '_', new_name)
    return new_name


def save_scene(kwargs=None, task=None, desc=None):
    if kwargs:
        ctrl = kwargs['ctrlclick']
    else:
        ctrl = False

    # Find scene_data node
    scene_data = None
    scene_data_nodes = []
    for n in hou.node('/obj').children():
        if n.type().nameComponents()[2].startswith('scene_data'):
            scene_data_nodes.append(n)
    if len(scene_data_nodes) > 1:
        util.error('Multiple SCENE DATA nodes found\nAborting Operation')
    elif len(scene_data_nodes) == 1:
        scene_data = scene_data_nodes[0]
    else:
        util.error('SCENE DATA node not found\nPlease create one and select a scene before saving')
        return

    # Gather variables
    save_path = hou.getenv('SAVE_PATH')
    scene = hou.getenv('SCENE')

    if not save_path or not scene:
        util.error('Local variables not defined\nPlease use SCENE DATA node to set these correctly')
        return

    # Set task and desc from curr scene or initialize
    curr_name = hou.hipFile.basename()
    regex = r'^(?P<scene>\w+)-(?P<task>\w+)-(?P<full_ver>v(?P<ver>\d{3,}))(-(?P<desc>\w+))?-(?P<user>\w+)' \
            r'(\.(?P<ext>\w+))$'
    match = re.match(regex, curr_name, flags=re.IGNORECASE)
    if match:
        if not task:
            task = match.group('task')
        if not desc:
            desc = match.group('desc')

    if not task:
        task = ''
    if not desc:
        desc = ''

    ask_input = True
    if ctrl and task != '':
        ask_input = False

    # Input Task and Description
    if ask_input:
        repeat = True
        while repeat:
            repeat = False

            user_input = hou.ui.readMultiInput('Select Task and Description', ('Task', 'Description (optional'),
                                               buttons=('OK', 'Cancel'), initial_contents=(task, desc))
            if user_input[0] == 1:
                return

            task = user_input[1][0]
            desc = user_input[1][1]

            if task == '':
                util.error('Task cannot be left blank', hou.severityType.Warning)
                repeat = True
                continue


    # Set version
    regex = '(?P<scene>{scene})-(?P<task>{task})-v(?P<ver_num>\\d{{3,}})'.format(scene=scene, task=task)
    ver_nums = []
    for f in os.listdir(save_path):
        if not os.path.isdir(f):
            match = re.match(regex, f, flags=re.IGNORECASE)
            if match:
                ver_nums.append(int(match.group('ver_num')))

    if len(ver_nums) > 0:
        high_ver = sorted(ver_nums)[-1]
        ver = 'v{0:>03}'.format(high_ver+1)
    else:
        ver = 'v001'

    # Set User
    user = hou.getenv('USER').lower()

    components = [scene, task, ver, desc, user]
    for i, c in enumerate(components):
        if c and c != '':
            components[i] = clean_name(c)
        else:
            del components[i]

    # Set extension
    lic_dict = {
        'Commercial': 'hip',
        'Indie': 'hiplc',
        'Apprentice': 'hipnc',
        'ApprenticeHD': 'hipnc',
        'Education': 'hipnc'
    }
    lic = hou.licenseCategory().name()
    ext = lic_dict[lic]

    # Build Filename
    name = '-'.join(components)
    filename = '{path}/{name}.{ext}'.format(path=save_path, name=name, ext=ext)

    # Save
    hou.hipFile.save(filename)<file_sep>#-*- coding:utf-8 -*-

import os
import hou

hip_dir = hou.hscriptExpression('$HIP')
log_dir = hip_dir + '/script/sim_log/'


# log_dir 경로가 없을 경우 경로를 생성하고, 있을 경우 파일을 제거
if os.path.isdir(log_dir) == False:
	os.mkdir(log_dir)
else:
	if os.path.isfile(log_dir + 'density.txt'):
		os.remove(log_dir + 'density.txt')
	if os.path.isfile(log_dir + 'temperature.txt'):
		os.remove(log_dir + 'temperature.txt')
	if os.path.isfile(log_dir + 'heat.txt'):
		os.remove(log_dir + 'heat.txt')



