Advertisement
Guest User

map_porter

a guest
Sep 10th, 2023
1,244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.23 KB | None | 0 0
  1. import bpy, sys, os, json
  2.  
  3. ### USER DEFINED VARIABLES ###
  4. # tip: uses forward slashes for paths!
  5. mappath = r'VMF_FILE_PATH'
  6. materials = r'PATH/_materials.blend'
  7. props = r'PATH/_props.blend'
  8. filesavepath = r'FILE/SAVE/PATH.blend'
  9.  
  10.  
  11. bpy.ops.import_scene.plumber_vmf(filepath=mappath, light_factor=10, game='0', scale=0.1)
  12. bpy.ops.wm.save_as_mainfile(filepath=filesavepath)
  13.  
  14.  
  15. for i in bpy.data.actions:
  16.     i.use_fake_user = True
  17.  
  18. def link(a):
  19.     blendfile = materials
  20.     section   = "\\Material\\"
  21.     object    = a
  22.  
  23.     filepath  = blendfile + section + object
  24.     directory = blendfile + section
  25.     filename  = object
  26.  
  27.     bpy.ops.wm.link(
  28.         filepath=filepath,
  29.         filename=filename,
  30.         directory=directory)
  31.  
  32. def name(a):
  33.     return a.lower()
  34.  
  35.  
  36. global rl
  37. rl = [] #removelist
  38. mesh = []
  39. mats = {}
  40. skip = []
  41. def add(a, b):
  42.     if not a in b:
  43.         b.append(a)
  44.  
  45. lookfor = ""
  46.  
  47. for i in [*bpy.data.collections['brushes'].objects, *bpy.data.collections['overlays'].objects]:
  48.     for m in i.material_slots:
  49.         if m.material.name.startswith('materials/'):
  50.             if bpy.data.materials.get(m.material.name.replace('materials/', '')) != None:
  51.                 m.material = bpy.data.materials[m.material.name.replace('materials/', '')]
  52.     if i.type != "MESH":
  53.         continue
  54.    
  55.     for m in i.material_slots:
  56.         if m.material == None:
  57.             continue
  58.         if m.material.library != None:
  59.             continue
  60.         m.material.name = m.material.name.upper()
  61.         if m.material.name not in mats:
  62.             mats[m.material.name] = f'{name(m.material.name)}'
  63.         if mats[m.material.name] in skip:
  64.             continue
  65.         try:
  66.             bpy.data.materials[mats[m.material.name]]
  67.             m.material = bpy.data.materials[mats[m.material.name]]
  68.             continue
  69.         except:
  70.             link(mats[m.material.name])
  71.            
  72.         try:
  73.             bpy.data.materials[mats[m.material.name]]
  74.             print(f"successfully linked {mats[m.material.name]}")
  75.             add(m.material.name, rl)
  76.             m.material = bpy.data.materials[mats[m.material.name]]
  77.         except:
  78.             #raise
  79.             print(f'Material {mats[m.material.name]} not found!')
  80.             skip.append(mats[m.material.name])
  81.             m.material.name = m.material.name.lower()
  82.             continue
  83.        
  84.         print(len(rl))
  85.        
  86. for i in rl:
  87.     bpy.data.materials.remove(bpy.data.materials[i])
  88. bpy.ops.outliner.orphans_purge(do_recursive=True)
  89. import math
  90. import mathutils
  91.  
  92. def link(a):
  93.     blendfile = props
  94.     section   = "\\Mesh\\"
  95.     object    = a
  96.  
  97.     filepath  = blendfile + section + object
  98.     directory = blendfile + section
  99.     filename  = object
  100.  
  101.     bpy.ops.wm.link(
  102.         filepath=filepath,
  103.         filename=filename,
  104.         directory=directory)
  105.  
  106. def name(a):
  107.     return a.lower()
  108.  
  109. PATH = mappath
  110. breaking = 0
  111. VMF = open(PATH, 'r')
  112. FOUND = False
  113.  
  114. mesh = []
  115. msh = {}
  116. skip = []
  117. def add(a, b):
  118.     if not a in b:
  119.         b.append(a)
  120.  
  121. lookfor = ""
  122.  
  123. for obj in bpy.data.collections['props'].objects:
  124.     if obj.type != 'EMPTY':
  125.         continue
  126.     NAME = obj.name.split('_')[-1]
  127.     bak = obj.name
  128.     obj.name = 'EMPTY'
  129.    
  130.     VMF = open(PATH, "r")
  131.     FOUND = False
  132.     for i in VMF:
  133.         if f'"id" "{NAME}"' in i:
  134.             FOUND = True
  135.             continue
  136.        
  137.         if FOUND and "}" in i:
  138.             #VMF.close()
  139.             break
  140.        
  141.         if FOUND and '"model"' in i:
  142.             #print(i)
  143.             LINE = i.replace('\t', '').replace('\n', '')
  144.             MODEL = LINE.replace('"', '').split(' ')[1]
  145.             print
  146.             MODEL = MODEL.replace("models/", '').replace('.mdl', '')
  147.            
  148.             if bpy.data.meshes.get(MODEL) == None:
  149.                 link(MODEL)
  150.                 if bpy.data.meshes.get(MODEL) == None:
  151.                     print(f'nothing found for {bak}, {MODEL}')
  152.                     VMF.close()
  153.                     obj.name = bak
  154.                     break
  155.            
  156.             NEW = bpy.data.objects.new(bak, bpy.data.meshes[MODEL])
  157.            
  158.             NEW.location = obj.location
  159.             NEW.rotation_euler = obj.rotation_euler
  160.             NEW.scale = obj.scale
  161.             bpy.data.collections['props'].objects.link(NEW)
  162.             bpy.data.objects.remove(obj)
  163.             #VMF.close()
  164.             continue
  165.  
  166.  
  167.  
  168. for i in bpy.data.collections["props"].objects:
  169.    
  170.     #print(mesh)
  171.     if i.type != 'MESH':
  172.         continue
  173.     if i.data.library != None:
  174.         continue
  175.     if i.data.name.endswith('_ref'):
  176.         i.data.name = i.data.name[:i.data.name.rfind('/')]
  177.     i.data.name = i.data.name.upper()
  178.     if not i.data.name in msh:
  179.         msh[i.data.name] = f"{name(i.data.name)}"
  180.     if msh[i.data.name] in skip:
  181.         continue
  182.     try:
  183.         bpy.data.meshes[msh[i.data.name]]
  184.     except:
  185.         link(msh[i.data.name])
  186.    
  187.     try:
  188.         bpy.data.meshes[msh[i.data.name]]
  189.         print(f"Mesh {msh[i.data.name]} found in file!\n---------")
  190.         i.data = bpy.data.meshes[msh[i.data.name]]
  191.         print(f"{i.name}'s mesh is now {i.data.name}\n---------")
  192.         i.scale[0] = i.scale[0]*10
  193.         i.scale[1] = i.scale[1]*10
  194.         i.scale[2] = i.scale[2]*10
  195.         obj = i
  196.         if obj.data.get('skin_groups') == None:
  197.             continue
  198.         for mod in [mod for mod in obj.modifiers if mod.type == 'NODES']:
  199.             if mod.node_group.name == 'SETSKIN':
  200.                 obj.modifiers.remove(mod)
  201.         FOUND = False
  202.         NAME = obj.name.split('_')[-1]
  203.         VMF = open(PATH, 'r')
  204.         for i in VMF:
  205.             if f'"id" "{NAME}"' in i:
  206.                 FOUND = True
  207.             if FOUND == True and "}" in i:
  208.                 print(f'Nothing found for {obj.name}!')
  209.                 break
  210.             if "skin" in i and FOUND == True:
  211.                 LINE = i.replace('\t', '').replace('\n', '')
  212.                 SKIN = int(LINE.replace('"', '').split(' ')[1])
  213.                 if SKIN == 0:
  214.                     continue
  215.                 GROUPS = obj.data.get('skin_groups')
  216.                 obj.select_set(True)
  217.                 #print(obj.data.get('skin_groups')[str(SKIN)])
  218.                 for mod in obj.modifiers:
  219.                     if 'REPLACEMAT' in mod.name:
  220.                         obj.modifiers.remove(mod)
  221.                 print(obj.name)
  222.                 try:
  223.                     for MAT in GROUPS[str(SKIN)]:
  224.                         if bpy.data.materials.get(MAT) == None:
  225.                             print(f'No matching skin found for {obj.name}!')
  226.                             VMF.close()
  227.                             breaking = 1
  228.                             break
  229.                 except:
  230.                     break
  231.                 if breaking == 1:
  232.                     breaking = 0
  233.                     break
  234.                 for num in range(len(GROUPS['0'])):
  235.                    
  236.                     MOD = obj.modifiers.new('REPLACEMAT', 'NODES')
  237.                     MOD.node_group = bpy.data.node_groups['REPLACEMAT']
  238.                     MOD["Input_2"] = bpy.data.materials[GROUPS['0'][num]]
  239.                     MOD["Input_3"] = bpy.data.materials[GROUPS[str(SKIN)][num]]
  240.                     if GROUPS[str(SKIN)][num] not in obj.material_slots:
  241.                         print(f'{GROUPS[str(SKIN)][num]} not in {obj.name}!')
  242.                 VMF.close()
  243.                 break
  244.  
  245.     except:
  246.         print(f"Mesh {msh[i.data.name]} not found in file!\nObject {i.name}'s mesh is still {i.data.name}")
  247.         skip.append(msh[i.data.name])
  248.         i.data.name = i.data.name.lower()
  249.         continue
  250. bpy.ops.outliner.orphans_purge(do_recursive=True)
  251.  
  252. for obj in bpy.data.collections['Collection'].objects:
  253.     bpy.data.objects.remove(obj)
  254.  
  255. from pathlib import Path
  256. import shutil
  257. WITH_ALPHA = True
  258.  
  259.  
  260. def save():
  261.     bpy.ops.wm.save_mainfile(compress=True)
  262.    
  263. def pack():
  264.     try:
  265.         bpy.ops.file.pack_all()
  266.     except:
  267.         pass
  268. # Disable
  269.  
  270. unpk = Path(bpy.path.abspath('//unpack//'))
  271. if not os.path.exists(unpk):
  272.     os.mkdir(unpk)
  273. oldtext = Path(bpy.path.abspath('//textures//'))
  274. counter = 0
  275. #blockPrint()
  276. for mat in bpy.data.materials:
  277.     if mat.library != None:
  278.         continue
  279.     if mat.use_nodes == False:
  280.         continue
  281.     for NODE in mat.node_tree.nodes:
  282.         if NODE.type != 'TEX_IMAGE':
  283.             continue
  284.         if NODE.image.get('optimized') == True:
  285.             continue
  286.         try:
  287.             png = NODE.image
  288.             oldname = NODE.image.name
  289.             newname = png.name.replace('/', '--')
  290.             png.name = newname
  291.             savepath = os.path.join(unpk, (png.name + '.png'))
  292.             png.file_format = 'PNG'
  293.             png.filepath_raw = savepath
  294.             png.save(filepath=savepath)
  295.             try:
  296.                 png.unpack()
  297.                 try:
  298.                     shutil.rmtree(oldtext)
  299.                 except:
  300.                     pass
  301.                 png.filepath_raw = savepath
  302.                 png.reload()
  303.                 png.name = oldname
  304.                 counter +=1
  305.             except:
  306.                 continue
  307.         except:
  308.             print(mat.name)
  309.             print(NODE.name)
  310.             print('fart')
  311.             continue
  312. print(f'OPTIMIZED {counter} IMAGES')
  313. if counter != 0:
  314.     print('PACKING')
  315.  
  316.     pack()
  317.     print('SAVING')
  318.  
  319.     save()
  320.  
  321.     print('REMOVING UNPACKS')
  322.     try:
  323.         shutil.rmtree(unpk)
  324.     except:
  325.         pass
  326.     print('REMOVING ORIGINALS')
  327.     try:
  328.         shutil.rmtree(oldtext)
  329.     except:
  330.         pass
  331.  
  332.     #logfile.writelines(f'{bpy.path.basename(bpy.data.filepath)}: {oldsize}MB to {newsize}MB\n\n')
  333.     #logfile.close()
  334.     os.remove(bpy.data.filepath + '1')
  335. else:
  336.     print('NOTHING TO DO!')
  337.  
  338. VMF = open(PATH, 'r')
  339.  
  340. LINES = VMF.readlines()
  341.  
  342. START = LINES.index("}\n")
  343. VMFlines = LINES[START:]
  344. FOUND = False
  345. VMF.close()
  346.  
  347. for x, i in enumerate(bpy.data.collections["brushes"].objects):
  348.     #print(x, i)
  349.     ID = i.name.split("_")
  350.    
  351.     if len(ID) != 3:
  352.         continue
  353.    
  354.     ID = ID[-1]
  355.    
  356.     FOUND = False
  357.     PAST = True
  358.     BAD = True
  359.     for LINE in VMFlines:
  360.         LINE = LINE.strip()
  361.         if f'"id" "{ID}"' in LINE:
  362.             FOUND = True
  363.             continue
  364.         if "}" in LINE and FOUND:
  365.             Bad = True
  366.             break
  367.         if '"rendermode" "10"' in LINE and FOUND:
  368.             print(i.name, 'deleted')
  369.             bpy.data.objects.remove(i)
  370.             Bad = False
  371.             break
  372.     else:
  373.         print(i.name, ' None')
  374.     if Bad == False:
  375.         pass
  376.     else:
  377.         print(i.name, ' None')
  378.  
  379. suns = list(filter(lambda a: a.data.type == 'SUN', filter(lambda a: a.type == 'LIGHT', bpy.data.objects)))
  380.  
  381. for sun in suns:
  382.     sun.data.shadow_cascade_max_distance = 1000
  383.  
  384.  
  385.  
  386.  
  387. sunID = suns[0].name.split('_')[2]
  388.    
  389. map_file = open(mappath, 'r')
  390. found = False
  391. for line in map_file.readlines():
  392.     if f'"id" "{sunID}"' in line:
  393.         found = True
  394.         continue
  395.     if '}' in line and found == True:
  396.         break
  397.         #bpy.ops.wm.quit_blender()
  398.     if '"_ambient"' in line and not "_ambientHDR" in line:
  399.         data = line.strip()
  400.         line = data.split('" "')
  401.         line = line[1].replace('"', '')
  402.         line = line.split(' ')
  403.         color = list(map(lambda a: float(a)/255, line))[:-1] + [1]
  404.         #print(list(line))
  405.         break
  406.    
  407. #print(color)
  408.  
  409. worldmat = bpy.context.scene.world
  410.  
  411. AMBY = worldmat.node_tree.nodes.new('ShaderNodeGroup')
  412.  
  413. AMBY.node_tree = bpy.data.node_groups['TF2 Ambient']
  414.  
  415. OUTPUT = worldmat.node_tree.nodes['World Output'].inputs[0]
  416.  
  417. BG = OUTPUT.links[0].from_socket
  418.  
  419. worldmat.node_tree.links.new(BG, AMBY.inputs[0])
  420.  
  421. worldmat.node_tree.links.new(AMBY.outputs[0], OUTPUT)
  422.  
  423. AMBY.inputs[1].default_value = color
  424.  
  425. bpy.context.scene.eevee.use_gtao = True
  426.  
  427. bpy.context.scene.eevee.gtao_distance = 10
  428.  
  429. ENV = worldmat.node_tree.nodes["Environment Texture"]
  430. ENV.image.unpack()
  431. fp = ENV.image.filepath_raw
  432. tpath = os.path.join(Path(bpy.path.abspath(fp)).parents[0], 'skybox.exr')
  433. #os.remove(bpy.path.abspath(fp))
  434. bak = [bpy.context.scene.render.image_settings.file_format, bpy.context.scene.render.image_settings.color_mode, bpy.context.scene.render.image_settings.exr_codec]
  435.  
  436. bpy.context.scene.render.image_settings.file_format = 'OPEN_EXR'
  437. bpy.context.scene.render.image_settings.color_mode = 'RGB'
  438. bpy.context.scene.render.image_settings.exr_codec = 'DWAA'
  439.  
  440. ENV.image.save_render(filepath=tpath, scene=bpy.context.scene)
  441. ENV.image.filepath = tpath
  442. ENV.image.filepath_raw = tpath
  443. ENV.image.reload()
  444. ENV.image.pack()
  445. os.remove(bpy.path.abspath(fp))
  446. bpy.context.scene.render.image_settings.file_format = bak[0]
  447. bpy.context.scene.render.image_settings.color_mode = bak[1]
  448. bpy.context.scene.render.image_settings.exr_codec = bak[2]
  449. del bak
  450.  
  451. '''
  452. imgname = os.path.basename(ENV.image.name).replace('.exr', '.png')
  453. print('---file---')
  454. print(imgname)
  455. newfilepath = os.path.join(skyboxes, imgname)
  456. print(newfilepath)
  457. if os.path.exists(newfilepath):
  458.    print('------')
  459.  
  460.    ENV.image.unpack()
  461.  
  462.    filepath = ENV.image.filepath
  463.  
  464.    os.remove(bpy.path.abspath(filepath))
  465.  
  466.    ENV.image.filepath = newfilepath
  467.  
  468.    ENV.image.pack()
  469. else:
  470.    ENV.image.save_render(newfilepath)
  471.    ENV.image.unpack()
  472.  
  473.    filepath = ENV.image.filepath
  474.  
  475.    os.remove(bpy.path.abspath(filepath))
  476.  
  477.    ENV.image.filepath = newfilepath
  478.  
  479.    ENV.image.pack()'''
  480.  
  481. try:
  482.     for i in bpy.data.objects:
  483.         if i.type != 'MESH':
  484.             continue
  485.         if i.data.library != None:
  486.             continue
  487.         for m in i.material_slots:
  488.             if m.material == None: continue
  489.             if m.material.name.startswith(''):
  490.                 #print(m.material.name)
  491.                 NAME = m.material.name.replace('materials/', '')
  492.                 NAME = NAME[:None if "." not in NAME else NAME.find(".")]
  493.                 #print(NAME)
  494.                 if bpy.data.materials.get(NAME) != None:
  495.                     print(NAME)
  496.                     print(i.name)
  497.                     m.material = bpy.data.materials.get(NAME)
  498.  
  499.  
  500. except:
  501.     pass
  502. save()
  503. try:
  504.     os.remove(bpy.data.filepath + '1')
  505. except:
  506.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement