Last active
September 22, 2024 20:15
-
-
Save scurest/2d4d61c4b0de1e585a23f86ca7e385ee to your computer and use it in GitHub Desktop.
Simplify Blender shaders to a simple diffuse texture for export (written for GLideN64-Scene-Ripper)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Fixes shaders from GLideN64-Scene-Ripper for OBJ/etc export. | |
# Instructions: select objects you want to fix, then run this | |
# script from the Text editor. | |
# Tested with Blender 3.6. | |
import bpy | |
# Whether to connect the diffuse texture's alpha to the | |
# Principled Alpha socket in the simplified material. | |
CONNECT_ALPHA = True | |
# Converts any material to a Principled BSDF material with a | |
# simple diffuse texture. | |
def simplify_material_for_export(material): | |
if not material.use_nodes: | |
return | |
nodes = material.node_tree.nodes | |
links = material.node_tree.links | |
# Find one texture node to use as the diffuse texture | |
tex_nodes = [ | |
node for node in nodes | |
if node.type == 'TEX_IMAGE' and node.image | |
] | |
# Simple heuristic to prefer 'Texture 0' to 'Texture 1' | |
tex_nodes.sort(key=lambda node: node.label or node.name) | |
tex_img = tex_nodes[0].image if tex_nodes else None | |
do_color = tex_img and tex_nodes[0].outputs['Color'].is_linked | |
do_alpha = CONNECT_ALPHA and tex_img and tex_nodes[0].outputs['Alpha'].is_linked | |
nodes.clear() | |
out_node = nodes.new('ShaderNodeOutputMaterial') | |
pbr_node = nodes.new('ShaderNodeBsdfPrincipled') | |
links.new(pbr_node.outputs[0], out_node.inputs[0]) | |
out_node.location = 300, 300 | |
pbr_node.location = 10, 300 | |
if tex_img: | |
tex_node = nodes.new('ShaderNodeTexImage') | |
tex_node.image = tex_img | |
tex_node.location = -330, 250 | |
if do_color: | |
links.new(tex_node.outputs["Color"], pbr_node.inputs["Base Color"]) | |
if do_alpha: | |
links.new(tex_node.outputs["Alpha"], pbr_node.inputs["Alpha"]) | |
obs = bpy.context.selected_objects | |
for ob in obs: | |
for slot in ob.material_slots: | |
if slot.material: | |
simplify_material_for_export(slot.material) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment