-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathqlibutils.py
1312 lines (1014 loc) · 38.5 KB
/
qlibutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
@file qlibutils.py
@author xy
@since 2012-07-23
@brief qLib-related utility functions.
"""
import string
import hou
import collections
import datetime
import getpass
import glob
import json
import os
import socket
import sys
import re
import subprocess
import traceback
import urllib
from operator import itemgetter
# for paste_clipboard_to_netview()
from hutil import Qt
import nodegraphutils
FLASH_SECONDS = 6.0
# TODO: msg functions with exception handling
def is_platform(name):
assert type(name) is str
return sys.platform.lower().startswith(name.lower())
def is_linux():
return is_platform('linux')
def is_windows():
return is_platform('win')
def is_mac():
return is_platform('darwin')
def houVersionAsFloat():
v = hou.applicationVersion()
return float( "%d.%d" % (v[0], v[1], ) )
def get_current_user_name(username_only=False):
"""Get name of the current user.
"""
username = getpass.getuser()
if username_only:
username = username.split("@")[0]
return username
def get_current_host_name():
"""Get the current host (computer) name.
"""
hostname = socket.gethostname() # socket.getfqdn() gives full name
return hostname
def statmsg(msg, warn=False):
""".
"""
assert type(msg) is str
s = hou.severityType.ImportantMessage if warn else hou.severityType.Message
if warn:
msg = "WARNING: %s" % msg
if hou.isUIAvailable():
hou.ui.setStatusMessage(msg, severity=s)
def ynreq(text="Are you sure?",
buttons=("Yes", "No", ) ):
"""Shows an "Are you sure Y/N" style yes/no dialog.
"""
do_it = 1
try:
do_it = hou.ui.displayMessage(text,
buttons=buttons,
default_choice=1, close_choice=1)
except:
print("ERROR: %s" % traceback.format_exc())
return do_it==0
def date_string(timestamp):
'''Returns an informal file date string (absolute/relative).
timestamp: can be a timestamp or a datetime.datetime
'''
r = "(?)"
assert type(timestamp) in [ float, datetime.datetime ]
file_t = timestamp \
if type(timestamp) is datetime.datetime \
else datetime.datetime.fromtimestamp(timestamp)
now_t = datetime.datetime.now(file_t.tzinfo) # NOTE: tzinfo is important for doing date diff!
dt = now_t - file_t # date difference (timedelta)
# TODO: format human-readable timedelta
ago = str(dt)
#ago = ago.split('.')[0] # chop off fractional seconds
ago = re.sub(":[^:]+$", "", ago) # chop off seconds
r = "%s (%s ago)" % (file_t.strftime("%Y-%m-%d %H:%M:%S"), ago, )
return r
def sizeof_fmt(num, suffix='B'):
"""Converts storage space in bytes to a human-readable format (e.g. 1.3MiB).
https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
num: size in bytes
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
def uri_to_path(uri):
"""Converts URI paths to regular filesystem paths.
https://stackoverflow.com/questions/5977576/is-there-a-convenient-way-to-map-a-file-uri-to-os-path
uri: URI path (string)
"""
#assert type(uri) is str
p = urllib.parse.urlparse(str(uri))
path = os.path.abspath(os.path.join(p.netloc, p.path))
return path
def set_namespace_aliases(prefix="qLib::", alias=True, verbose=False):
"""Defines (non-)namespaced aliases for operators with a particular namespace prefix.
This is used for always creating the namespaced versions of assets, even if an
older .hip file contains non-namespaced asset names.
Mapping looks like: <opname> --> <prefix>::<opname>::<version>
@note
IMPORTANT: Although the manual says it's fine to omit the version of a
namespaced asset (and that would refer to the latest version),
omitting it results in files getting messed up when loaded,
so version numbers _are_ included in the opaliases.
@note
This function should be called (preferably) on Houdini startup, e.g.
import qlibutils
qlibutils.set_namespace_aliases( ["qLib::", "myStuff::"] )
@todo
For each asset, the highest version number should be found and used.
Right now it uses the first version it founds (which is fine for now).
"""
if type(prefix) is list:
for p in prefix:
set_namespace_aliases(p)
return
assert "::" in prefix, "Include trailing '::' characters in prefix"
cmds = []
for file in hou.hda.loadedFiles():
names = [(d.nodeType().name(), d.nodeTypeCategory().name())
for d in list(hou.hda.definitionsInFile(file))
if prefix in d.nodeType().name()]
for n in names:
try:
# strip namespace prefix and version suffix
old = re.sub("^[^:]+::", "", n[0])
old = re.search("^[^:]+", old).group(0)
# opalias <network> <namespaced-op.> <plain-old-op.>
cmd = "opalias %s %s %s" % (n[1], n[0], old)
if cmd not in cmds:
if verbose:
print(cmd)
if alias:
hou.hscript(cmd)
cmds.append(cmd)
else:
print("# ALREADY ALIASED: %s (%s)" % (cmd, file))
except:
print("ERROR: %s" % traceback.format_exc())
def to_clipboard(contents="", env=None):
"""Copies the specified string to the system clipboard.
"""
try:
contents = str(contents)
if env:
contents = str(hou.getenv(env))
hou.ui.copyTextToClipboard(contents)
except:
pass
def get_recovery_dir():
tmpdir = str(hou.getenv("HOUDINI_TEMP_DIR") or hou.getenv("TEMP"))
return tmpdir
def do_crash_recovery(calledFromUI=False):
"""Performs crash recovery from an emergency-saved file.
"""
tmpdir = get_recovery_dir()
files = glob.glob(os.path.join(tmpdir, '*.hip'))
uicall = calledFromUI
if hou.isUIAvailable() and len(files) > 0:
td = os.path.join(tmpdir, '') # dir with '/'
files = [ (f, os.path.getmtime(f), os.path.getsize(f), ) for f in files ]
files = sorted(files, key=lambda f: f[1], reverse=True)
# filename + date_string + file size
files = [ str(re.sub('^%s' % td, '', f[0]))+" -- "+ sizeof_fmt(f[2])+", "+date_string(f[1]) \
for f in files ]
sel = hou.ui.selectFromList(files, exclusive=True,
title="Crash Recovery",
message="Select .hip File to Recover")
recovered = False
if len(sel) > 0:
f = files[sel[0]].split()[0]
fn = os.path.join(tmpdir, f)
# extract HIPNAME
f = re.sub('^crash.', '', f)
f = re.sub('\..+_[0-9]+\.hip', '.hip', f)
# do recovery
try:
hou.hipFile.clear(True)
hou.hipFile.load(fn, True)
hou.setUpdateMode(hou.updateMode.Manual)
recovered = True
except:
hou.ui.setStatusMessage(
"error while recovering file %s" % fn, hou.severityType.Error)
print("ERROR: %s" % traceback.format_exc())
hou.hipFile.setName(f)
# delete crash file(s)
if False:
msg = 'Cleanup: Delete all crash recovery hip files?'
if recovered:
msg = \
'File recovered. Make sure to save it to a safe location.\n' \
'NOTE: Update mode is set to "Manual" to avoid potential re-crashes.\n' \
'\n%s' % msg
if ynreq(msg, buttons=("DELETE", "Skip", )):
files = \
glob.glob(os.path.join(tmpdir, 'crash.*')) + \
glob.glob(os.path.join(tmpdir, '*.hip'))
for f in files:
try:
os.remove(f)
except:
pass
hou.ui.setStatusMessage(
"crash recovery cleanup: deleted %d files" % len(files))
else:
pass # user cancelled
else:
# no crash files found
#
if uicall:
hou.ui.setStatusMessage(
' Crash Recovery: No emergency-saved .hip file(s) found -- nothing to recover. (%s)' % tmpdir, hou.severityType.ImportantMessage)
pass
def open_dir(dir="", env=None):
"""Opens the specified directory in the system file browser.
"""
dir = str(dir)
if env:
dir = str(hou.getenv(env))
if not os.path.exists(dir):
statmsg("Directory doesn't exist (%s)" % dir, warn=True)
return
oss, cmd = None, None
if is_linux():
oss, cmd = "linux", "xdg-open"
if is_windows():
dir = dir.replace('/', '\\') # of course
oss, cmd = "windows", "start"
if is_mac():
oss, cmd = "macos", "open"
if oss and cmd:
statmsg("(%s) %s %s" % (oss, cmd, dir, ) )
r = subprocess.call(' '.join([cmd, dir]), shell=True)
if r!=0:
statmsg("(%s) FAILED: %s %s" % (oss, cmd, dir, ), warn=True)
def open_clipboard_as_dir():
"""Opens the clipboard contents as a folder in the file browser.
"""
path = hou.ui.getTextFromClipboard()
path = uri_to_path(path) # convert URI (e.g. pdg paths) to regular filesystem path
path = hou.text.expandString(path) # substitute variables
if not os.path.isdir(path):
path = os.path.dirname(path)
open_dir(path)
def get_hda_paths(nodes):
"""Finds filesystem paths for specified HDAs or compiled DSOs.
"""
hdas = []
for node in nodes:
t = node.type()
s = t.source()
if s==hou.nodeTypeSource.CompiledCode:
# it's a compiled DSO
path = t.sourcePath()
hdas.append(path)
else:
# assume it's a HDA
d = t.definition()
if d:
path = d.libraryFilePath()
if path != 'Embedded':
hdas.append(path)
return hdas
def open_hda_dirs():
"""Opens folders for the selected HDAs or DSOs.
"""
hdas = get_hda_paths(hou.selectedNodes())
dirs = set()
for h in hdas:
dirs.add(os.path.split(h)[0])
for d in dirs:
open_dir(d)
def hdapath_to_clipboard():
"""Copies the full path of the first selected HDA to the clipboard.
"""
hdas = get_hda_paths(hou.selectedNodes())
hdas = '\n'.join(hdas)
to_clipboard(hdas)
def nodes_to_clipboard(fullPaths=False, hdaTypeNames=False):
"""Copies the names or full paths of selected nodes to the clipboard.
"""
sep = '\n' if fullPaths else ' '
nodes = hou.selectedNodes()
func = lambda n: n.name()
if hdaTypeNames:
func = lambda n: n.type().name()
if fullPaths:
func = lambda n: n.path()
if hdaTypeNames:
func = lambda n: "%s (%s)" % (n.path(), n.type().name(), )
text = sep.join([ func(n) for n in nodes ])
to_clipboard(text)
def find_camera(oppattern, path=None):
"""Finds a camera OBJ within nested subnets and returns its full path.
"""
r = ''
try:
root = hou.pwd()
if path:
root = hou.node(path)
root = root.glob(oppattern)
if len(root) > 0:
cam = [n.path() for n in root[0].allSubChildren()
if n.type().name() == 'cam']
if len(cam) > 0:
r = cam[0]
else:
pass # no camera found
else:
pass # no root node found
except:
pass # TODO: error handling
return r
def backup_rop_output_file():
"""Creates a dated backup of an output file of a ROP.
Useful as a ROP Pre-Render call.
"""
pass
def remove_embedded_hdas():
"""Remove all embedded HDAs from the scene.
"""
do_it = ynreq(
"Remove all Embdedded HDAs (OTLs) from the current scene?\n"
"Warning: This cannot be undone!\n\n"
"NOTE: Embedded definitions that don't have a non-embedded version available\n"
"will not be removed.",
buttons=("Ok", "Cancel", ))
if do_it:
hou.hda.uninstallFile("Embedded")
def find_same_nodes(nodes):
"""Find the same node types in a network.
"""
def type_name(n):
"""Build a (not exactly correct) full typename (but without the asset version)."""
r = n.networkItemType().name().lower()
if r=="node":
r = "::".join(n.type().nameComponents()[0:-1])
return r
r = []
if len(nodes)>0:
types = set()
for n in nodes:
types.add(type_name(n))
all = nodes[0].parent().allItems()
r = [ n for n in all if type_name(n) in types ]
return r
def find_same_colored(nodes):
"""Find nodes with the same color(s) as the specified node(s).
TODO:
- make sure there's no need for per-component floating point comparison
"""
r = []
if len(nodes)>0:
colors = set()
for n in nodes:
colors.add(n.color())
all = nodes[0].parent().allItems()
r = [ n for n in all if n.color() in colors ]
return r
def get_shape_name(node):
"""Return shape name of the node.
"""
#TODO: assert: node is a node object
shape = None
try:
shape = node.userData("nodeshape") or node.type().defaultShape()
except:
pass
return shape
def find_same_shape(nodes):
"""Find nodes with the same shape(s) as the specified node(s).
TODO:
- make sure there's no need for per-component floating point comparison
"""
r = []
if len(nodes)>0:
shapes = set()
for n in nodes:
shapes.add(get_shape_name(n))
all = nodes[0].parent().allItems()
r = [ n for n in all if get_shape_name(n) in shapes ]
return r
def get_netview_path(kwargs):
"""Finds the path of the current network view from kwargs.
"""
if "editor" in kwargs:
return kwargs["editor"].pwd()
else:
# TODO: raise an error
return None
def is_node_locked(node):
"""Check if node is locked. Implementation level LOL.
"""
r = False
if "isHardLocked" in dir(node):
r = node.isHardLocked()
elif "isLocked" in dir(node):
r = node.isLocked()
return r
def has_embedded_def(node):
"""Check if the node's HDA definition is Embedded.
"""
d = node.type().definition()
r = d and d.libraryFilePath() == "Embedded"
return r
def is_hda_open_for_edit(node):
"""Check if HDA is editable (unlocked).
Code based on Houdini OPmenu.xml / "Match Current Definition"
"""
if node.matchesCurrentDefinition():
return False
if not node.isNetwork():
return False
hda_def = node.type().definition()
if not hda_def:
return False
options = hda_def.options()
if not options.lockContents():
return False
if node.isInsideLockedHDA() and not node.isEditableInsideLockedHDA():
return False
if hou.hda.safeguardHDAs():
return False
if not node.type().isWritable():
return False
if not node.type().areContentsViewable():
return False
return True
def get_node_author(node, username_only=False):
"""Returns the author of the specified node.
"""
author = '???'
try:
# digging up author info using an archaic command
author = hou.hscript('opstat -u %s' % node.path())[0].split(' ')[-1].split('\n')[0]
if username_only:
author = author.split("@")[0]
except:
pass # we can't hack the info out, just return '???'
return author
def get_node_authors(nodes, username_only=False):
"""Returns a list of authors for the specified list of nodes.
"""
r = set()
for n in nodes:
r.add(get_node_author(n, username_only=username_only))
return list(r)
def has_author(node, authors, username_only=False):
"""Check if a node has one of the authors in the "authors" list.
"""
a = get_node_author(node, username_only=username_only)
return a in authors
def parm_is_keyframed(parm):
"""Checks if parm is keyframed.
A parm is considered keyframed if there's at least 2 keyframes,
or has a single one with a curve expression thing on it (ending with "()")
parm: a hou.Parm
"""
num_keys = len(parm.keyframes())
if num_keys>1:
return True
if num_keys==1:
k = parm.keyframes()[0]
# single keyframe: should be a hscript expression of "bezier()" or similar
return \
k.expressionLanguage() == hou.exprLanguage.Hscript and \
re.match("^[a-z]*\(\)$", k.expression())
return False
def parm_is_time_dependent(parm):
"""Checks if parm is time-dependent.
"""
return parm.isTimeDependent()
def has_parm_with_criteria(node, criteria):
"""Returns True if the specified node has any parms
that match a given criteria.
criteria: (lambda) function with a hou.Parm as argument
"""
parms = node.parms() # should it be parmTuples()?
for parm in parms:
if criteria(parm):
return True
return False
def has_keyframed_parms(node):
"""Check if a node has keyframed parms.
"""
return has_parm_with_criteria(node, parm_is_keyframed)
def has_time_dependent_parms(node):
"""Check if a node has time-dependent parms.
"""
return has_parm_with_criteria(node, parm_is_time_dependent)
def add_to_selection(nodes, kwargs, selectMode=None, statMsg=None):
"""Extends the current node selection with 'nodes', according to
the modifier keys in kwargs.
no modifier: replace selection
shift, alt: add to selection
ctrl: remove from selection
ctrl+shift: intersect with selection
"""
assert selectMode is None or type(selectMode) is str
haz_shift = kwargs["shiftclick"] or kwargs['altclick']
haz_ctrl = kwargs["ctrlclick"]
if selectMode is None:
# determine select mode based on kwargs
if haz_shift or haz_ctrl:
# we got some modifier pressed
if haz_shift:
# shift: add (union), shift+ctrl: intersect
selectMode = "intersect" if haz_ctrl else "add"
else:
# ctrl: remove from selection
selectMode = "remove"
else:
selectMode = selectMode.lower()
current = set(hou.selectedItems())
sel = set(nodes)
sel_length_old = len(sel)
if selectMode=="intersect":
sel = sel.intersection(current)
elif selectMode=="add":
sel = sel.union(current)
elif selectMode=="remove":
sel = current.difference(sel)
else:
selectMode = "replace"
if sel is not None:
hou.clearAllSelected()
for n in sel:
n.setSelected(True)
# report back
msg0 = "Select (%s) %d matches: Now %d selected (was %d)" \
% ( selectMode.lower(), sel_length_old, len(sel), len(current), )
if statMsg:
msg0 = msg0 + " " + str(statMsg)
if "editor" in kwargs:
kwargs["editor"].flashMessage("BUTTONS_reselect", msg0, FLASH_SECONDS)
statmsg("%s (ALT: add to selection"
", CTRL:remove from selecton"
", CTRL+ALT:intersect with selection)" % msg0)
def select_netview_nodes(kwargs, criteria, allItems=False, selectMode=None, statMsg=None):
"""Select nodes.
"""
path = get_netview_path(kwargs)
child_func = path.allItems if allItems else path.children
sel = None
try:
sel = [ n for n in child_func() if criteria(n) ]
except:
statmsg("Couldn't select / Selection criteria not applicable", warn=True)
if sel is not None:
add_to_selection(sel, kwargs, selectMode=selectMode, statMsg=statMsg)
def set_netview_selection(kwargs, criteria, allItems=False):
"""Replace selection with nodes matching a criteria function.
"""
select_netview_nodes(kwargs, criteria, allItems=allItems, selectMode="replace")
def select_ropnet_input_depdendents(kwargs):
"""Select ROP network input dependents.
"""
sel = hou.selectedNodes()
deps = []
if len(sel)>0:
# find dependencies
deps0 = []
for node in sel:
if hasattr(node, "inputDependencies"):
deps0 = deps0 + [ d[0] for d in node.inputDependencies() ]
# find nodes of dependencies that are in the same network
# as the initial selection (dependencies might return subnet contents)
pp = "^"+sel[0].parent().path()+"/[^/]+"
deps = []
for node in deps0:
m = re.search(pp, node.path())
if m:
deps.append(hou.node(m.group(0)))
# select dependencies
add_to_selection(deps, kwargs)
# select original selection
add_to_selection(sel, kwargs, selectMode="add")
def select_dependencies_same_network(kwargs):
"""Select dependents/references that are in the same network as current selection.
"""
sel = hou.selectedNodes()
parents = [ n.parent() for n in sel ]
deps = []
for node in sel:
linked = node.dependents(include_children=False) + node.references(include_children=False)
deps = deps + [ l for l in linked if l.parent() in parents ]
# select dependencies
add_to_selection(deps, kwargs)
# select original selection
add_to_selection(sel, kwargs, selectMode="add")
def reset_nodes(kwargs, nodes, resetColor=True, resetShape=True):
""".
"""
for n in nodes:
if resetColor:
d = n.type().defaultColor()
if d!=n.color():
n.setColor(d)
if resetShape:
if "nodeshape" in n.userDataDict():
n.destroyUserData("nodeshape")
def embedded_img_prefix(image_name):
""".
"""
return "opdef:/qLib::Object/embedded_images?%s" % image_name if not "/" in image_name else image_name
def embedded_hda_typename():
return 'qLib::embedded_images'
def get_embedded_img_hdadef():
category = hou.objNodeTypeCategory()
embedded = 'Embedded'
hda_def = hou.hdaDefinition(category, embedded_hda_typename(), embedded)
return hda_def
def get_existing_images(kwargs):
"""Return a list of paths (opdef:/...) for existing images in the hip file.
(Coming from the embedded qLib image container hda)
"""
R = []
hda_def = get_embedded_img_hdadef()
if hda_def:
R = [ n for n in hda_def.sections() if n.endswith(".png") ]
return R
def get_existing_hip_images(kwargs=None, skipEmbedded=True):
"""Return a list of paths for all network editor background images in the hip file.
"""
R = set()
nodes = hou.node("/").allSubChildren(recurse_in_locked_nodes=False)
nodes = [ n for n in nodes if n.isNetwork() and n.userDataDict().get("backgroundimages") ]
cond = lambda p: "opdef:" not in p if skipEmbedded else True
for n in nodes:
paths = [ i["path"] for i in json.loads(n.userData("backgroundimages")) if cond(i["path"]) ]
paths = set(paths)
R = R.union(paths)
return sorted(list(R))
def hip_has_pasted_images(kwargs):
""".
"""
return len(get_existing_images(kwargs))>0 or len(get_existing_hip_images(kwargs))>0
def add_image_to_netview(image_path, pane, pwd):
""".
"""
# add image to network view
image = hou.NetworkImage(image_path)
image.setBrightness(0.75)
#image.setRect(hou.BoundingRect(0, 0, 5, 2))
s = pane.visibleBounds()
center = s.center()
s.translate(-center)
s.scale((0.25, 0.25, ))
s.translate(center)
image.setRect(s)
images = nodegraphutils.loadBackgroundImages(pwd)
images.append(image)
pane.setBackgroundImages(images)
nodegraphutils.saveBackgroundImages(pwd, images)
def paste_clipboard_to_netview(kwargs):
"""Paste clipboard contents (text or image) into the network editor.
"""
clipboard = Qt.QtGui.QGuiApplication.clipboard()
image = clipboard.image()
text = clipboard.text()
pane = kwargs.get('editor', None)
shift = kwargs.get('shiftclick', None)
ctrl = kwargs.get('ctrlclick', None)
alt = kwargs.get('altclick', None)
if pane:
pwd = pane.pwd()
if image.isNull():
# paste text (if any)
if text!="":
# copy/pasted from the "add sticky note" shelf button
# TODO: refactor this into a proper function that can be called from both
date = datetime.datetime.now().replace(second=0, microsecond=0).isoformat(' ')
date = re.sub(":00$", "", date) # strip seconds
username = get_current_user_name()
hostname = get_current_host_name()
user = '%s@%s' % (username, hostname, ) if (shift or alt) else username
notename = "%s_%s_1" % (username, re.sub("[^0-9]+", "_", date), )
notetext = "[%s, %s]" % (user, date, )
note = pwd.createStickyNote()
note.move(pane.visibleBounds().center())
s = note.size()
s = hou.Vector2((s.x()*1.5, s.y()*0.5, ))
text = "%s --\n%s" % (notetext, text, )
note.setText(text)
note.setSize(s)
else:
# paste image
# generate automatic name
image_name = 'image_' + datetime.datetime.now().replace(microsecond=0).isoformat('_').replace(":", "")
msg = []
images = sorted(get_existing_images(kwargs))
if len(images)>0:
msg.append("Existing images:")
c=0
for i in images:
msg.append(" - %s" % i)
c+=1
if c>=20:
break
if c<len(images):
msg.append(" - (...) ")
msg.append('\n(Images are stored in an embedded "qLib::embedded_images" /obj node).')
msg = "\n".join(msg)
ok, image_name = hou.ui.readInput("Enter name of image to be pasted",
buttons=('Ok', 'Cancel', ), close_choice=1, help=msg,
initial_contents=image_name)
if image_name=='':
ok = 1
image_name += '.png'
if ok==0:
hda_typename = embedded_hda_typename()
hda_def = get_embedded_img_hdadef()
# create hda definition if doesn't exist
if not hda_def:
temp_node = hou.node('/obj').createNode('subnet')
hda_node = temp_node.createDigitalAsset(name=hda_typename,
description="qLib: Embedded Images",
save_as_embedded=True)
hda_node.destroy()
hda_def = get_embedded_img_hdadef()
# create an instance in /obj if doesn't exist
node = None
nodes = [ n for n in hou.node('/obj').children() if n.type().name()==hda_typename ]
if len(nodes)==0:
node = hou.node('/obj').createNode(hda_typename, node_name="embedded_images")
node.setComment("embedded BG images for network views\n(do not delete)")
hou.hscript("opset -Y on %s" % node.path())
pass # set comment "do not delete"
# add clipboard image to hda definition (as section)
ba = Qt.QtCore.QByteArray();
buffer = Qt.QtCore.QBuffer(ba)
buffer.open(Qt.QtCore.QIODevice.WriteOnly)
image.save(buffer, "png")
buffer.close()
hda_def.addSection(image_name, buffer.data().data())
# add image to network view
add_image_to_netview(embedded_img_prefix(image_name), pane, pwd)
pane.flashMessage("COP2_still", "Pasted new image: %s (Ctrl+I to edit)" % image_name, 8)
def paste_existing_image(kwargs):
""".
"""
images = sorted(get_existing_images(kwargs)) + sorted(get_existing_hip_images(kwargs))
pane = kwargs.get('editor', None)
sel = hou.ui.selectFromList(images, exclusive=True,
title="Paste Existing Image",
message="Select Image to Paste")
if len(sel)>0 and pane:
image_name = images[sel[0]]
pwd = pane.pwd()
add_image_to_netview(embedded_img_prefix(image_name), pane, pwd)
pane.flashMessage("COP2_still", "Pasted existing image: %s (Ctrl+I to edit)" % image_name, 8)
def embed_selected_hdas(kwargs):
"""Embed HDA definitions of selected nodes (interactive only).
"""
defs = set()
for s in hou.selectedNodes():
d = s.type().definition()
if d and d.libraryFilePath()!="Embedded":
defs.add(d)
defs = list(defs)