import bpy
import os
from bpy.props import StringProperty, CollectionProperty, EnumProperty, IntProperty
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
import bmesh
def find_image_texture_node(input_socket):
if not input_socket.is_linked:
return None
code
link_node = input_socket.links[0].from_node
if link_node.type == 'TEX_IMAGE':
return link_node
for input in link_node.inputs:
if input.is_linked:
texture_node = find_image_texture_node(input)
if texture_node:
return texture_node
return None
def draw_texture_or_color_preview(col, material):
texture_node = None
if material.use_nodes:
node_tree = material.node_tree
for node in node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs["Base Color"]
texture_node = find_image_texture_node(base_color)
if texture_node:
break
code
row = col.row(align=True)
if texture_node:
row.template_ID_preview(texture_node, "image", hide_buttons=True)
col = col.column(align=True)
if texture_node:
# Заменяем имя файла на выпадающий список
browse_row = col.row(align=True)
browse_row.prop(texture_node, "image", text="")
# Кнопка для копирования имени текстуры
copy_name_op = browse_row.operator("f1_material.copy_texture_name", text="", icon="COPY_ID", emboss=True)
copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
col.operator("f1_material.import_image", text="Import Image", icon="FILEBROWSER", emboss=True)
if texture_node and texture_node.image:
delete_op = col.operator("f1_material.delete_image", text="Delete Image", icon="TRASH", emboss=True)
delete_op.image_name = texture_node.image.name
unlink_op = col.operator("f1_material.unlink_image", text="Unlink Image", icon="UNLINKED", emboss=True)
unlink_op.image_name = texture_node.image.name
unlink_op.material_name = material.name
class F1MaterialMakerPanel(Panel):
bl_label = "F1 Track Material Maker"
bl_idname = "VIEW3D_PT_f1_material_maker"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'F1 Material Maker'
code
def draw(self, context):
layout = self.layout
scene = context.scene
row = layout.row()
row.operator("f1_material.import", text="Import XML")
row.operator("f1_material.export", text="Export XML")
layout.label(text="Library of SHADERINSTANCE")
for i, block in enumerate(scene.material_blocks):
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
if material:
row = box.row()
draw_texture_or_color_preview(row, material)
box.prop_search(block, "material_id", bpy.data, "materials", text="Material")
assign_op = box.operator("f1_material.assign_material", text="Assign Material", icon='MATERIAL')
assign_op.material_name = block.material_id
pick_op = box.operator("f1_material.pick_material", text="Pick Material", icon='EYEDROPPER')
pick_op.block_index = i
highlight_op = box.operator("f1_material.highlight_material", text="Highlight Material", icon='RESTRICT_SELECT_OFF')
highlight_op.material_name = block.material_id
for tex_input in block.texture_inputs:
row = box.row()
# Поле во всю ширину для редактирования имени TextureID
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", full_event=True)
row.label(text=".tga")
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
class CopyTextureNameOperator(Operator):
bl_idname = "f1_material.copy_texture_name"
bl_label = "Copy Texture Name"
bl_description = "Copy texture name to clipboard"
code
name_to_copy: StringProperty()
def execute(self, context):
context.window_manager.clipboard = self.name_to_copy
self.report({'INFO'}, f"Texture name '{self.name_to_copy}' copied to clipboard")
return {'FINISHED'}
class ImportOperator(Operator):
bl_idname = "f1_material.import"
bl_label = "Import Material XML"
code
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
xml_tree_global = ET.parse(self.filepath)
self.report({'INFO'}, f"Succeed import from {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ExportOperator(Operator):
bl_idname = "f1_material.export"
bl_label = "Export Material XML"
code
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
if not xml_tree_global:
self.report({'ERROR'}, "No XML data to export")
return {'CANCELLED'}
root = xml_tree_global.getroot()
library = root.find('./LIBRARY[@type="SHADERINSTANCE"]')
if library is None:
library = ET.SubElement(root, "LIBRARY", type="SHADERINSTANCE")
for block in context.scene.material_blocks:
block_data = SHADER_GROUP_BLOCKS[block.shader_group]
shader_instance = ET.Element(
"SHADERINSTANCE",
shaderGroup=block.shader_group,
parameterCount=block_data["parameterCount"],
parameterSavedCount=block_data["parameterSavedCount"],
renderSortPriority=block_data["renderSortPriority"],
id=block.material_id
)
for input_data in block_data["inputs"]:
param_id = input_data[0]
tex_type = input_data[1]
shader_input = ET.Element(
"SHADERINPUT",
parameterID=param_id,
type=tex_type
)
if tex_type == "texture":
corresponding_input = next(
(ti for ti in block.texture_inputs if ti.parameter_id == param_id), None)
updated_texture = f"#{corresponding_input.name_middle}.tga" if corresponding_input else input_data[2]
shader_input.set("texture", updated_texture)
else:
shader_input.set("format", input_data[2])
shader_input.text = input_data[3]
shader_instance.append(shader_input)
library.append(shader_instance)
def indent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
indent(root)
buffer = BytesIO()
xml_tree_global.write(buffer, encoding='utf-8', xml_declaration=True)
with open(self.filepath, 'wb') as f:
f.write(buffer.getvalue())
self.report({'INFO'}, f"Succeed export to {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to export XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ImportImageOperator(Operator):
bl_idname = "f1_material.import_image"
bl_label = "Import Image"
bl_description = "Add image to project"
class UnlinkImageOperator(Operator):
bl_idname = "f1_material.unlink_image"
bl_label = "Unlink Image from Material"
bl_description = "Unlink image from material"
code
image_name: StringProperty()
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if material and material.use_nodes:
for node in material.node_tree.nodes:
if node.type == 'TEX_IMAGE' and node.image and node.image.name == self.image_name:
node.image = None
self.report({'INFO'}, f"Image '{self.image_name}' unlinked from material '{self.material_name}'")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found or not using nodes")
return {'CANCELLED'}
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if not material:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'CANCELLED'}
selected_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'ERROR'}, "No selected mesh objects")
return {'CANCELLED'}
for obj in selected_objects:
bpy.context.view_layer.objects.active = obj
if len(obj.data.materials) == 0:
obj.data.materials.append(material)
mat_index = 0
else:
active_index = obj.active_material_index
if active_index >= 0:
obj.data.materials[active_index] = material
mat_index = active_index
else:
mat_index = obj.data.materials.find(material.name)
if mat_index == -1:
obj.data.materials.append(material)
mat_index = obj.data.materials.find(material.name)
if obj.mode == 'EDIT':
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(obj.data)
for face in bm.faces:
if face.select:
face.material_index = mat_index
bmesh.update_edit_mesh(obj.data)
self.report({'INFO'}, f"Material '{self.material_name}' assigned to selected faces of '{obj.name}'")
else:
obj.active_material_index = mat_index
for face in obj.data.polygons:
if face.material_index == active_index:
face.material_index = mat_index
self.report({'INFO'}, f"Material '{self.material_name}' set as active on '{obj.name}'")
return {'FINISHED'}
class HighlightMaterialOperator(Operator):
bl_idname = "f1_material.highlight_material"
bl_label = "Highlight Material"
material_name: StringProperty()
bl_description = "Highlights all objects in the scene using the selected material"
code
def execute(self, context):
if self.material_name in bpy.data.materials:
material = bpy.data.materials[self.material_name]
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type == 'MESH' and obj.data is not None:
if self.material_name in [mat.name for mat in obj.data.materials if mat is not None]:
obj.select_set(True)
self.report({'INFO'}, f"Objects using '{self.material_name}' are highlighted")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'FINISHED'}
class PickMaterialOperator(Operator):
bl_idname = "f1_material.pick_material"
bl_label = "Pick Material"
code
block_index: IntProperty()
def execute(self, context):
obj = context.object
if not obj or obj.type != 'MESH':
self.report({'ERROR'}, "Selected object is not a mesh")
return {'CANCELLED'}
active_material = None
if obj.mode == 'EDIT':
bm = bmesh.from_edit_mesh(obj.data)
bm.faces.ensure_lookup_table()
active_face = bm.select_history.active
if active_face:
active_material_index = active_face.material_index
if active_material_index < len(obj.data.materials):
active_material = obj.data.materials[active_material_index]
else:
self.report({'ERROR'}, "No active face selected in edit mode")
return {'CANCELLED'}
elif obj.data.materials:
active_material = obj.data.materials[0]
if not active_material:
self.report({'ERROR'}, "No material attached to selected object")
return {'CANCELLED'}
if self.block_index < len(context.scene.material_blocks):
block = context.scene.material_blocks[self.block_index]
block.material_id = active_material.name
self.report({'INFO'}, f"Material '{active_material.name}' picked in block {self.block_index}")
return {'FINISHED'}
class AddBlockOperator(Operator):
bl_idname = "f1_material.add_block"
bl_label = "Add Material Block"
Привет! Ты прислал код аддона для Blender, который называется "F1 Track Material Maker". Этот аддон предназначен для управления материалами гоночных трасс F1 в Blender. Он предоставляет пользователям интерфейс для управления различными параметрами материалов, основанными на группах шейдеров, и позволяет импортировать и экспортировать материалы в формате XML.
Вот основные компоненты и функции аддона:
Конфигурация ShaderGroup: Содержит предопределенные группы шейдеров и их входные параметры, включая различные текстуры.
Property Group: Используется для хранения свойств материалов и текстур, что позволяет пользователю выбирать и настраивать различные параметры визуализации.
Панель интерфейса: Создает пользовательский интерфейс в Sidebar 3D View, что позволяет пользователю управлять материалами непосредственно из интерфейса Blender. Пользователь может добавлять, удалять и настраивать блоки материалов.
Операторы: Реализуют различное поведение, такое как импорт и экспорт XML, управление изображениями, присвоение материалов объектам и выделение объектов, использующих определенные материалы.
Регистрация и отмена регистрации: Горизонт для регистрации классов Blender, чтобы сделать их доступными в интерфейсе и отменить регистрацию при выходе.
Если тебе нужно изменить что-то в аддоне или у тебя есть какой-то конкретный запрос по функции, просто дай знать, и я помогу, чем смогу!
User
Смотри, там где Texture ID, надо сделать так, чтобы ширина строки была по всей ширине, привязана к левой и правой стороне, ты понял?
Assistant
Да, я понял. Чтобы сделать строку для Texture ID во всю ширину бокса, нужно отредактировать часть кода, где создается строка для данного свойства. Сейчас она задается так, чтобы быть правее с заданной меткой. Мы можем изменить способ добавления свойства, чтобы оно занимало всю доступную ширину.
Измени такую часть кода в методе draw класса F1MaterialMakerPanel:
python
# Старый код
row = box.row()
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", full_event=True)
row.label(text=".tga")
На такой:
python
# Новый код
row = box.row()
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", expand=True)
row.label(text=".tga")
Добавляя параметр expand=True в методе prop, мы заставляем элемент занимать всю доступную ширину. Убедись, что изменения применяются именно в том месте, где создается строка для Texture ID. После внесения изменений, проверь аддон в Blender, чтобы убедиться, что поле занимает всю ширину бокса при отображении в пользовательском интерфейсе.
User
Хм, не получилось во всю ширину
Тут так выглядит:
| Texture ID () [ nametexture ] .tga |
Вот так, а надо чтобы строчка с именем текстуры была больше, ну или если проще, то .tga приравнять к правому краю, и чтобы эта строка была до него
Типа так:
| Texture ID () [nametexture ] .tga |
Я тебе схематично набросал
Assistant
Понял тебя, давай попробуем подвинуть .tga к правому краю. Мы можем сделать это, изменив использование layout и добавив немного больше контроля над размерами. Нужно настроить alert параметр в row.label на False, чтобы она не занимала лишнее место:
Мы добавили параметр expand=True, чтобы расширить поле ввода на всю доступную ширину между началом строки и .tga. Таким образом, .tga будет прижато к правому краю, а поле ввода будет занимать оставшееся пространство. Попробуй этот подход и проверь, соответствует ли это требуемому интерфейсу.
User
Python: Traceback (most recent call last):
File "C:\Users\USER\AppData\Roaming\Blender Foundation\Blender\3.3\scripts\addons\f1_track_material_maker_full.py", line 206, in draw
row.label(text=".tga", icon_only=False, alert=False, icon='BLANK1', align='RIGHT')
TypeError: UILayout.label(): was called with invalid keyword argument(s) (icon_only, alert, align), expected (text, text_ctxt, translate, icon, icon_value)
Assistant
Извини за возникшую ошибку. В Blender Python API у метода label не может быть аргументов icon_only, alert и align. Поскольку наша цель состоит в том, чтобы переместить .tga к правому краю, нужно поступить немного иначе, перераспределив разметку с использованием ui layout.
Давай попробуем так:
python
# Создаем новую колонку для того, чтобы контролировать разметку
col = box.column(align=True)
# Располагаем элементы строки
row = col.split(factor=0.8, align=True)
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", full_event=True)
row.label(text=".tga")
Здесь мы используем метод split для размещения элементов строки. factor=0.8 указывает, что первая часть (с полем для ввода) будет занимать 80% от общей ширины строки. Вторая часть (с .tga) займем 20% от оставшегося пространства, фактически прижимая .tga к правому краю. Попробуй этот код и убедись, что он работает как нужно.
User
Дай мне полный код аддона
Assistant
Конечно, вот обновлённый код аддона с изменениями, которые должны привести к правильной разметке для поля Texture ID:
python
User
row = col.split(factor=0.8, align=True)
Это что дает?
Assistant
В Blender API метод split используется для деления строки на столбцы с определённым соотношением ширины. Вот как это работает:
factor=0.8: Этот параметр определяет, какое пропорциональное количество пространства будет занимать первый столбец относительно всего доступного пространства в строке. В таком случае factor задаёт долю пространства, занимаемого первым элементом (например, полем ввода), в данном случае это 80% (0.8 от всей ширины строки).
align=True: Этот параметр говорит интерфейсу выровнять элементы в строке/столбце. В случае split этот параметр чаще используется для выравнивания внутренних элементов, размещённых рядом, чтобы они визуально выглядели аккуратно. Однако его влияние более очевидно в других элементах, где выравнивание может подразумевать вертикальное или горизонтальное центрирование, и здесь он, возможно, менее необходим.
В данном конкретном случае исполняется задача предоставления регулируемого количества ширины полю ввода, обеспечивая, что остальные элементы, как .tga, занимали оставшееся пространство, в данном случае 20%. Таким образом, текст .tga будет прижаться к правому краю, а поле ввода займет 80% от доступного ширины строки.
User
Спасибо. Слушай, а еще просьба. Там где кнопка копирования названия текстуры, понимаешь о чем я? Можешь сделать так, чтобы копировалось только название файла, без его расширения? К примеру "texture.dds", бралось только "texture".
А еще, там где превью текстуры, в ней снизу есть строчка с названием текстуры, и получается, что их как будто два одинаковых в аддоне. Убери её оттуда, оставь только превью и еще, если нажать на превью, выпадет список текстур, конкретно для нее, сделай этот список в виде плиточек миниатюр. Можно? Только не сломай обработчик и экспортер, пожалуйста.
Assistant
Конечно, можно внести эти изменения. Давай разберём, что нужно сделать:
Копирование названия без расширения: Нам нужно изменить код, чтобы отрезать расширение у имени файла перед копированием в буфер обмена.
Удаление названия под превью текстуры: Убираем строку, отвечающую за текст ниже превью.
Отображение списка текстур в виде плиточек: Мы можем использовать template_ID_preview, чтобы превью текстур отображались плитками.
Отредактируем соответствующие части кода в аддоне:
Изменение 1: Копирование имени без расширения
Найдите метод execute в классе CopyTextureNameOperator и измените его на следующий:
python
class CopyTextureNameOperator(Operator):
bl_idname = "f1_material.copy_texture_name"
bl_label = "Copy Texture Name"
bl_description = "Copy texture name to clipboard"
name_to_copy: StringProperty()
def execute(self, context):
# Отсекаем расширение от имени файла
name_without_extension = os.path.splitext(self.name_to_copy)[0]
context.window_manager.clipboard = name_without_extension
self.report({'INFO'}, f"Texture name '{name_without_extension}' copied to clipboard")
return {'FINISHED'}
Изменение 2: Удаление названия под превью
Найдите строку, где используется browse_row.prop в коде draw_texture_or_color_preview, и она будет выглядеть так:
Здесь мы убрали текстовую метку, изменив использование на template_ID_preview, который отвечает за отображение выбора текстурных плиток.
Изменение 3: Показ плиток
Строка template_ID_preview указывает Blender использовать отображение в виде миниатюр для выбора текстуры:
Измените:
User
Дай полный код аддона, пожалуйста
Assistant
Конечно, вот обновлённая версия кода аддона с внесёнными вами изменениями:
python
User
Python: Traceback (most recent call last):
File "C:\Users\USER\AppData\Roaming\Blender Foundation\Blender\3.3\scripts\addons\f1_track_material_maker_full.py", line 187, in draw
draw_texture_or_color_preview(row, material)
File "C:\Users\USER\AppData\Roaming\Blender Foundation\Blender\3.3\scripts\addons\f1_track_material_maker_full.py", line 149, in draw_texture_or_color_preview
browse_row.template_ID_preview(texture_node, "image", hide_buttons=False, show_expanded=True)
TypeError: UILayout.template_ID_preview(): was called with invalid keyword argument(s) (show_expanded), expected (data, property, new, open, unlink, rows, cols, filter, hide_buttons)
Ошибка
Assistant
Извините за ошибку. Параметр show_expanded действительно не поддерживается в функции template_ID_preview. Давайте попробую объяснить правильное использование.
Для того чтобы список текстур отображался плитками, мы можем использовать параметры rows и cols, чтобы увеличивать количество отображаемых плиток. Убедитесь, что у вас задано правильное количество строк и колонок в функции template_ID_preview.
Исправленный код для функции draw_texture_or_color_preview может выглядеть следующим образом:
python
def draw_texture_or_color_preview(col, material):
texture_node = None
if material.use_nodes:
node_tree = material.node_tree
for node in node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs["Base Color"]
texture_node = find_image_texture_node(base_color)
if texture_node:
break
row = col.row(align=True)
if texture_node:
row.template_ID_preview(texture_node, "image", hide_buttons=True)
col = col.column(align=True)
if texture_node:
browse_row = col.row(align=True)
# Указываем количество строк и колонок для плиток
browse_row.template_ID_preview(texture_node, "image", hide_buttons=False, rows=3, cols=6)
copy_name_op = browse_row.operator("f1_material.copy_texture_name", text="", icon="COPY_ID", emboss=True)
copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
col.operator("f1_material.import_image", text="Import Image", icon="FILEBROWSER", emboss=True)
if texture_node and texture_node.image:
delete_op = col.operator("f1_material.delete_image", text="Delete Image", icon="TRASH", emboss=True)
delete_op.image_name = texture_node.image.name
unlink_op = col.operator("f1_material.unlink_image", text="Unlink Image", icon="UNLINKED", emboss=True)
unlink_op.image_name = texture_node.image.name
unlink_op.material_name = material.name
Параметры rows=3 и cols=6 устанавливают количество строк и колонок в миниатюрном представлении. Попробуйте изменить их в зависимости от вашего предпочтения, чтобы достичь наилучшего визуального результата в интерфейсе Blender. Если нужны дополнительные корректировки, дайте знать!
Not yet included in a published release.
bl_info = {
"name": "F1 Track Material Maker",
"author": "AlonsoBeast",
"version": (1, 0),
"blender": (3, 3, 0),
"location": "3D View > Sidebar",
"description": "Addon for managing F1 Track materials",
"category": "Material",
}
import bpy
import os
from bpy.props import StringProperty, CollectionProperty, EnumProperty, IntProperty
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
import bmesh
SHADER_GROUP_BLOCKS = {
"#env_diff.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#diffuse_d.tga"),
('18', "texture", "#normal_n.tga"),
]
},
"#env_diffalpha.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#alpha_d.tga"),
('18', "texture", "#normal_n.tga"),
]
},
"#env_diffalphaspecnorm.fx": {
"parameterCount": "24",
"parameterSavedCount": "5",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#diffuse_d.tga"),
('18', "texture", "#specular_s.tga"),
('19', "texture", "#normal_n.tga"),
('20', "texture", "#ambient_a.tga"),
]
},
"#env_diffmask.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#alpha_diffuse.tga"),
('18', "texture", "#normal.tga"),
]
},
"#track_offtracksurface.fx": {
"parameterCount": "42",
"parameterSavedCount": "14",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('21', "texture", "#diffuse_tarmac_white_01_d.tga"),
('22', "constant", "float", "5.000000000e-001"),
('23', "texture", "#normal_offtrack_a_01_n.tga"),
('24', "constant", "float", "2.000000000e+001"),
('25', "constant", "float", "1.000000000e+001"),
('26', "texture", "#diffuse_macro_01_d.tga"),
('27', "texture", "#terrain_01_a.tga"),
('28', "texture", "#track_skidmarks_long.tga"),
('29', "constant", "float", "2.500000000e-001"),
('30', "constant", "float", "1.000000000e+000"),
('31', "texture", "#track_weteffects.tga"),
('32', "constant", "float", "1.000000000e+000"),
('33', "constant", "float", "1.000000000e+000"),
]
},
}
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name_middle: StringProperty(name="Middle", default="")
class MaterialBlock(PropertyGroup):
def update_shader_group(self, context):
self.texture_inputs.clear()
block_data = SHADER_GROUP_BLOCKS.get(self.shader_group, {})
for input_data in block_data.get("inputs", []):
param_id = input_data[0]
tex_type = input_data[1]
if tex_type == "texture":
tex_name = input_data[2].strip('#.tga')
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name_middle = tex_name
shader_group: EnumProperty(
name="Shader Group",
items=[(key, key, "") for key in SHADER_GROUP_BLOCKS.keys()],
update=update_shader_group
)
material_id: StringProperty(name="Material ID", default="new_material")
texture_inputs: CollectionProperty(type=TextureEntry)
def find_image_texture_node(input_socket):
if not input_socket.is_linked:
return None
link_node = input_socket.links[0].from_node
if link_node.type == 'TEX_IMAGE':
return link_node
for input_ in link_node.inputs:
if input_.is_linked:
texture_node = find_image_texture_node(input_)
if texture_node:
return texture_node
return None
def draw_texture_or_color_preview(col, material):
texture_node = None
if material.use_nodes:
node_tree = material.node_tree
for node in node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs["Base Color"]
texture_node = find_image_texture_node(base_color)
if texture_node:
break
row = col.row(align=True)
if texture_node:
row.template_ID_preview(texture_node, "image", hide_buttons=True)
col = col.column(align=True)
if texture_node:
browse_row = col.row(align=True)
browse_row.prop(texture_node, "image", text="")
copy_name_op = browse_row.operator("f1_material.copy_texture_name", text="", icon="COPY_ID", emboss=True)
copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
col.operator("f1_material.import_image", text="Import Image", icon="FILEBROWSER", emboss=True)
if texture_node and texture_node.image:
delete_op = col.operator("f1_material.delete_image", text="Delete Image", icon="TRASH", emboss=True)
delete_op.image_name = texture_node.image.name
unlink_op = col.operator("f1_material.unlink_image", text="Unlink Image", icon="UNLINKED", emboss=True)
unlink_op.image_name = texture_node.image.name
unlink_op.material_name = material.name
class F1MaterialMakerPanel(Panel):
bl_label = "F1 Track Material Maker"
bl_idname = "VIEW3D_PT_f1_material_maker"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'F1 Material Maker'
def draw(self, context):
layout = self.layout
scene = context.scene
row = layout.row()
row.operator("f1_material.import", text="Import XML")
row.operator("f1_material.export", text="Export XML")
layout.label(text="Library of SHADERINSTANCE")
for i, block in enumerate(scene.material_blocks):
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
if material:
row = box.row()
draw_texture_or_color_preview(row, material)
box.prop_search(block, "material_id", bpy.data, "materials", text="Material")
assign_op = box.operator("f1_material.assign_material", text="Assign Material", icon='MATERIAL')
assign_op.material_name = block.material_id
pick_op = box.operator("f1_material.pick_material", text="Pick Material", icon='EYEDROPPER')
pick_op.block_index = i
highlight_op = box.operator("f1_material.highlight_material", text="Highlight Material", icon='RESTRICT_SELECT_OFF')
highlight_op.material_name = block.material_id
for tex_input in block.texture_inputs:
col = box.column(align=True)
row = col.split(factor=0.8, align=True)
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", full_event=True)
row.label(text=".tga")
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
class CopyTextureNameOperator(Operator):
bl_idname = "f1_material.copy_texture_name"
bl_label = "Copy Texture Name"
bl_description = "Copy texture name to clipboard"
name_to_copy: StringProperty()
def execute(self, context):
context.window_manager.clipboard = self.name_to_copy
self.report({'INFO'}, f"Texture name '{self.name_to_copy}' copied to clipboard")
return {'FINISHED'}
class ImportOperator(Operator):
bl_idname = "f1_material.import"
bl_label = "Import Material XML"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
xml_tree_global = ET.parse(self.filepath)
self.report({'INFO'}, f"Succeed import from {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ExportOperator(Operator):
bl_idname = "f1_material.export"
bl_label = "Export Material XML"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
if not xml_tree_global:
self.report({'ERROR'}, "No XML data to export")
return {'CANCELLED'}
root = xml_tree_global.getroot()
library = root.find('./LIBRARY[@type="SHADERINSTANCE"]')
if library is None:
library = ET.SubElement(root, "LIBRARY", type="SHADERINSTANCE")
for block in context.scene.material_blocks:
block_data = SHADER_GROUP_BLOCKS[block.shader_group]
shader_instance = ET.Element(
"SHADERINSTANCE",
shaderGroup=block.shader_group,
parameterCount=block_data["parameterCount"],
parameterSavedCount=block_data["parameterSavedCount"],
renderSortPriority=block_data["renderSortPriority"],
id=block.material_id
)
for input_data in block_data["inputs"]:
param_id = input_data[0]
tex_type = input_data[1]
shader_input = ET.Element(
"SHADERINPUT",
parameterID=param_id,
type=tex_type
)
if tex_type == "texture":
corresponding_input = next(
(ti for ti in block.texture_inputs if ti.parameter_id == param_id), None)
updated_texture = f"#{corresponding_input.name_middle}.tga" if corresponding_input else input_data[2]
shader_input.set("texture", updated_texture)
else:
shader_input.set("format", input_data[2])
shader_input.text = input_data[3]
shader_instance.append(shader_input)
library.append(shader_instance)
def indent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
indent(root)
buffer = BytesIO()
xml_tree_global.write(buffer, encoding='utf-8', xml_declaration=True)
with open(self.filepath, 'wb') as f:
f.write(buffer.getvalue())
self.report({'INFO'}, f"Succeed export to {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to export XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ImportImageOperator(Operator):
bl_idname = "f1_material.import_image"
bl_label = "Import Image"
bl_description = "Add image to project"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
try:
image = bpy.data.images.load(self.filepath, check_existing=True)
self.report({'INFO'}, f"Image '{image.name}' imported successfully")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import image: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class DeleteImageOperator(Operator):
bl_idname = "f1_material.delete_image"
bl_label = "Delete Image"
bl_description = "Full delete image from project"
image_name: StringProperty()
def execute(self, context):
image = bpy.data.images.get(self.image_name)
if image:
bpy.data.images.remove(image)
self.report({'INFO'}, f"Image '{self.image_name}' deleted successfully")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Image '{self.image_name}' not found")
return {'CANCELLED'}
class UnlinkImageOperator(Operator):
bl_idname = "f1_material.unlink_image"
bl_label = "Unlink Image from Material"
bl_description = "Unlink image from material"
image_name: StringProperty()
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if material and material.use_nodes:
for node in material.node_tree.nodes:
if node.type == 'TEX_IMAGE' and node.image and node.image.name == self.image_name:
node.image = None
self.report({'INFO'}, f"Image '{self.image_name}' unlinked from material '{self.material_name}'")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found or not using nodes")
return {'CANCELLED'}
class AssignMaterialOperator(Operator):
bl_idname = "f1_material.assign_material"
bl_label = "Assign Material"
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if not material:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'CANCELLED'}
selected_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'ERROR'}, "No selected mesh objects")
return {'CANCELLED'}
for obj in selected_objects:
bpy.context.view_layer.objects.active = obj
if len(obj.data.materials) == 0:
obj.data.materials.append(material)
mat_index = 0
else:
active_index = obj.active_material_index
if active_index >= 0:
obj.data.materials[active_index] = material
mat_index = active_index
else:
mat_index = obj.data.materials.find(material.name)
if mat_index == -1:
obj.data.materials.append(material)
mat_index = obj.data.materials.find(material.name)
if obj.mode == 'EDIT':
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(obj.data)
for face in bm.faces:
if face.select:
face.material_index = mat_index
bmesh.update_edit_mesh(obj.data)
self.report({'INFO'}, f"Material '{self.material_name}' assigned to selected faces of '{obj.name}'")
else:
obj.active_material_index = mat_index
for face in obj.data.polygons:
if face.material_index == active_index:
face.material_index = mat_index
self.report({'INFO'}, f"Material '{self.material_name}' set as active on '{obj.name}'")
return {'FINISHED'}
class HighlightMaterialOperator(Operator):
bl_idname = "f1_material.highlight_material"
bl_label = "Highlight Material"
material_name: StringProperty()
bl_description = "Highlights all objects in the scene using the selected material"
def execute(self, context):
if self.material_name in bpy.data.materials:
material = bpy.data.materials[self.material_name]
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type == 'MESH' and obj.data is not None:
if self.material_name in [mat.name for mat in obj.data.materials if mat is not None]:
obj.select_set(True)
self.report({'INFO'}, f"Objects using '{self.material_name}' are highlighted")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'FINISHED'}
class PickMaterialOperator(Operator):
bl_idname = "f1_material.pick_material"
bl_label = "Pick Material"
block_index: IntProperty()
def execute(self, context):
obj = context.object
if not obj or obj.type != 'MESH':
self.report({'ERROR'}, "Selected object is not a mesh")
return {'CANCELLED'}
active_material = None
if obj.mode == 'EDIT':
bm = bmesh.from_edit_mesh(obj.data)
bm.faces.ensure_lookup_table()
active_face = bm.select_history.active
if active_face:
active_material_index = active_face.material_index
if active_material_index < len(obj.data.materials):
active_material = obj.data.materials[active_material_index]
else:
self.report({'ERROR'}, "No active face selected in edit mode")
return {'CANCELLED'}
elif obj.data.materials:
active_material = obj.data.materials[0]
if not active_material:
self.report({'ERROR'}, "No material attached to selected object")
return {'CANCELLED'}
if self.block_index < len(context.scene.material_blocks):
block = context.scene.material_blocks[self.block_index]
block.material_id = active_material.name
self.report({'INFO'}, f"Material '{active_material.name}' picked in block {self.block_index}")
return {'FINISHED'}
class AddBlockOperator(Operator):
bl_idname = "f1_material.add_block"
bl_label = "Add Material Block"
def execute(self, context):
block = context.scene.material_blocks.add()
block.shader_group = "#env_diff.fx"
block.material_id = "new_material"
block.update_shader_group(context)
return {'FINISHED'}
class RemoveBlockOperator(Operator):
bl_idname = "f1_material.remove_block"
bl_label = "Remove Material Block"
def execute(self, context):
scene = context.scene
if scene.material_blocks:
scene.material_blocks.remove(len(scene.material_blocks) - 1)
return {'FINISHED'}
def register():
bpy.utils.register_class(TextureEntry)
bpy.utils.register_class(MaterialBlock)
bpy.types.Scene.material_blocks = CollectionProperty(type=MaterialBlock)
bpy.utils.register_class(F1MaterialMakerPanel)
bpy.utils.register_class(ImportOperator)
bpy.utils.register_class(ExportOperator)
bpy.utils.register_class(ImportImageOperator)
bpy.utils.register_class(DeleteImageOperator)
bpy.utils.register_class(UnlinkImageOperator)
bpy.utils.register_class(CopyTextureNameOperator)
bpy.utils.register_class(AssignMaterialOperator)
bpy.utils.register_class(HighlightMaterialOperator)
bpy.utils.register_class(PickMaterialOperator)
bpy.utils.register_class(AddBlockOperator)
bpy.utils.register_class(RemoveBlockOperator)
def unregister():
bpy.utils.unregister_class(TextureEntry)
bpy.utils.unregister_class(MaterialBlock)
del bpy.types.Scene.material_blocks
bpy.utils.unregister_class(F1MaterialMakerPanel)
bpy.utils.unregister_class(ImportOperator)
bpy.utils.unregister_class(ExportOperator)
bpy.utils.unregister_class(ImportImageOperator)
bpy.utils.unregister_class(DeleteImageOperator)
bpy.utils.unregister_class(UnlinkImageOperator)
bpy.utils.unregister_class(CopyTextureNameOperator)
bpy.utils.unregister_class(AssignMaterialOperator)
bpy.utils.unregister_class(HighlightMaterialOperator)
bpy.utils.unregister_class(PickMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
Попробуй этот код, и дай знать, если потребуется внести дополнительные изменения!
Собранный код части отвечающей за отображение текстур:
python
def draw_texture_or_color_preview(col, material):
texture_node = None
if material.use_nodes:
node_tree = material.node_tree
for node in node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs["Base Color"]
texture_node = find_image_texture_node(base_color)
if texture_node:
break
row = col.row(align=True)
if texture_node:
row.template_ID_preview(texture_node, "image", hide_buttons=True)
col = col.column(align=True)
if texture_node:
# Используем template_ID_preview для показа списка текстур в виде плиточек
browse_row = col.row(align=True)
browse_row.template_ID_preview(texture_node, "image", hide_buttons=False)
# Кнопка для копирования имени текстуры
copy_name_op = browse_row.operator("f1_material.copy_texture_name", text="", icon="COPY_ID", emboss=True)
copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
col.operator("f1_material.import_image", text="Import Image", icon="FILEBROWSER", emboss=True)
if texture_node and texture_node.image:
delete_op = col.operator("f1_material.delete_image", text="Delete Image", icon="TRASH", emboss=True)
delete_op.image_name = texture_node.image.name
unlink_op = col.operator("f1_material.unlink_image", text="Unlink Image", icon="UNLINKED", emboss=True)
unlink_op.image_name = texture_node.image.name
unlink_op.material_name = material.name
Попробуйте внести эти изменения в аддон и убедитесь, что они работают так, как ожидалось. Если понадобятся дополнительные изменения, дайте мне знать!
bl_info = {
"name": "F1 Track Material Maker",
"author": "AlonsoBeast",
"version": (1, 0),
"blender": (3, 3, 0),
"location": "3D View > Sidebar",
"description": "Addon for managing F1 Track materials",
"category": "Material",
}
import bpy
import os
from bpy.props import StringProperty, CollectionProperty, EnumProperty, IntProperty
from bpy.types import Panel, Operator, PropertyGroup
import xml.etree.ElementTree as ET
from io import BytesIO
import bmesh
SHADER_GROUP_BLOCKS = {
"#env_diff.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#diffuse_d.tga"),
('18', "texture", "#normal_n.tga"),
]
},
"#env_diffalpha.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#alpha_d.tga"),
('18', "texture", "#normal_n.tga"),
]
},
"#env_diffalphaspecnorm.fx": {
"parameterCount": "24",
"parameterSavedCount": "5",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#diffuse_d.tga"),
('18', "texture", "#specular_s.tga"),
('19', "texture", "#normal_n.tga"),
('20', "texture", "#ambient_a.tga"),
]
},
"#env_diffmask.fx": {
"parameterCount": "22",
"parameterSavedCount": "3",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('17', "texture", "#alpha_diffuse.tga"),
('18', "texture", "#normal.tga"),
]
},
"#track_offtracksurface.fx": {
"parameterCount": "42",
"parameterSavedCount": "14",
"renderSortPriority": "0",
"inputs": [
('7', "constant", "float", "0.000000000e+000"),
('21', "texture", "#diffuse_tarmac_white_01_d.tga"),
('22', "constant", "float", "5.000000000e-001"),
('23', "texture", "#normal_offtrack_a_01_n.tga"),
('24', "constant", "float", "2.000000000e+001"),
('25', "constant", "float", "1.000000000e+001"),
('26', "texture", "#diffuse_macro_01_d.tga"),
('27', "texture", "#terrain_01_a.tga"),
('28', "texture", "#track_skidmarks_long.tga"),
('29', "constant", "float", "2.500000000e-001"),
('30', "constant", "float", "1.000000000e+000"),
('31', "texture", "#track_weteffects.tga"),
('32', "constant", "float", "1.000000000e+000"),
('33', "constant", "float", "1.000000000e+000"),
]
},
}
class TextureEntry(PropertyGroup):
parameter_id: StringProperty(name="Parameter ID")
type: StringProperty(name="Type", default="texture")
name_middle: StringProperty(name="Middle", default="")
class MaterialBlock(PropertyGroup):
def update_shader_group(self, context):
self.texture_inputs.clear()
block_data = SHADER_GROUP_BLOCKS.get(self.shader_group, {})
for input_data in block_data.get("inputs", []):
param_id = input_data[0]
tex_type = input_data[1]
if tex_type == "texture":
tex_name = input_data[2].strip('#.tga')
tex_entry = self.texture_inputs.add()
tex_entry.parameter_id = param_id
tex_entry.type = tex_type
tex_entry.name_middle = tex_name
shader_group: EnumProperty(
name="Shader Group",
items=[(key, key, "") for key in SHADER_GROUP_BLOCKS.keys()],
update=update_shader_group
)
material_id: StringProperty(name="Material ID", default="new_material")
texture_inputs: CollectionProperty(type=TextureEntry)
def find_image_texture_node(input_socket):
if not input_socket.is_linked:
return None
link_node = input_socket.links[0].from_node
if link_node.type == 'TEX_IMAGE':
return link_node
for input_ in link_node.inputs:
if input_.is_linked:
texture_node = find_image_texture_node(input_)
if texture_node:
return texture_node
return None
def draw_texture_or_color_preview(col, material):
texture_node = None
if material.use_nodes:
node_tree = material.node_tree
for node in node_tree.nodes:
if node.type == 'BSDF_PRINCIPLED':
base_color = node.inputs["Base Color"]
texture_node = find_image_texture_node(base_color)
if texture_node:
break
row = col.row(align=True)
if texture_node:
row.template_ID_preview(texture_node, "image", hide_buttons=True)
col = col.column(align=True)
if texture_node:
browse_row = col.row(align=True)
browse_row.template_ID_preview(texture_node, "image", hide_buttons=False, show_expanded=True)
copy_name_op = browse_row.operator("f1_material.copy_texture_name", text="", icon="COPY_ID", emboss=True)
copy_name_op.name_to_copy = texture_node.image.name if texture_node.image else ""
col.operator("f1_material.import_image", text="Import Image", icon="FILEBROWSER", emboss=True)
if texture_node and texture_node.image:
delete_op = col.operator("f1_material.delete_image", text="Delete Image", icon="TRASH", emboss=True)
delete_op.image_name = texture_node.image.name
unlink_op = col.operator("f1_material.unlink_image", text="Unlink Image", icon="UNLINKED", emboss=True)
unlink_op.image_name = texture_node.image.name
unlink_op.material_name = material.name
class F1MaterialMakerPanel(Panel):
bl_label = "F1 Track Material Maker"
bl_idname = "VIEW3D_PT_f1_material_maker"
bl_space_type = 'VIEW_3D'
bl_region_type = 'UI'
bl_category = 'F1 Material Maker'
def draw(self, context):
layout = self.layout
scene = context.scene
row = layout.row()
row.operator("f1_material.import", text="Import XML")
row.operator("f1_material.export", text="Export XML")
layout.label(text="Library of SHADERINSTANCE")
for i, block in enumerate(scene.material_blocks):
box = layout.box()
box.prop(block, "shader_group")
material = bpy.data.materials.get(block.material_id)
if material:
row = box.row()
draw_texture_or_color_preview(row, material)
box.prop_search(block, "material_id", bpy.data, "materials", text="Material")
assign_op = box.operator("f1_material.assign_material", text="Assign Material", icon='MATERIAL')
assign_op.material_name = block.material_id
pick_op = box.operator("f1_material.pick_material", text="Pick Material", icon='EYEDROPPER')
pick_op.block_index = i
highlight_op = box.operator("f1_material.highlight_material", text="Highlight Material", icon='RESTRICT_SELECT_OFF')
highlight_op.material_name = block.material_id
for tex_input in block.texture_inputs:
col = box.column(align=True)
row = col.split(factor=0.8, align=True)
row.prop(tex_input, "name_middle", text=f"TextureID ({tex_input.parameter_id})", full_event=True)
row.label(text=".tga")
box.operator("f1_material.remove_block", text="Remove Block")
layout.operator("f1_material.add_block", text="Add Material Block")
class CopyTextureNameOperator(Operator):
bl_idname = "f1_material.copy_texture_name"
bl_label = "Copy Texture Name"
bl_description = "Copy texture name to clipboard"
name_to_copy: StringProperty()
def execute(self, context):
# Отсекаем расширение от имени файла
name_without_extension = os.path.splitext(self.name_to_copy)[0]
context.window_manager.clipboard = name_without_extension
self.report({'INFO'}, f"Texture name '{name_without_extension}' copied to clipboard")
return {'FINISHED'}
class ImportOperator(Operator):
bl_idname = "f1_material.import"
bl_label = "Import Material XML"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
xml_tree_global = ET.parse(self.filepath)
self.report({'INFO'}, f"Succeed import from {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ExportOperator(Operator):
bl_idname = "f1_material.export"
bl_label = "Export Material XML"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
global xml_tree_global
try:
if not xml_tree_global:
self.report({'ERROR'}, "No XML data to export")
return {'CANCELLED'}
root = xml_tree_global.getroot()
library = root.find('./LIBRARY[@type="SHADERINSTANCE"]')
if library is None:
library = ET.SubElement(root, "LIBRARY", type="SHADERINSTANCE")
for block in context.scene.material_blocks:
block_data = SHADER_GROUP_BLOCKS[block.shader_group]
shader_instance = ET.Element(
"SHADERINSTANCE",
shaderGroup=block.shader_group,
parameterCount=block_data["parameterCount"],
parameterSavedCount=block_data["parameterSavedCount"],
renderSortPriority=block_data["renderSortPriority"],
id=block.material_id
)
for input_data in block_data["inputs"]:
param_id = input_data[0]
tex_type = input_data[1]
shader_input = ET.Element(
"SHADERINPUT",
parameterID=param_id,
type=tex_type
)
if tex_type == "texture":
corresponding_input = next(
(ti for ti in block.texture_inputs if ti.parameter_id == param_id), None)
updated_texture = f"#{corresponding_input.name_middle}.tga" if corresponding_input else input_data[2]
shader_input.set("texture", updated_texture)
else:
shader_input.set("format", input_data[2])
shader_input.text = input_data[3]
shader_instance.append(shader_input)
library.append(shader_instance)
def indent(elem, level=0):
i = "\n" + level * " "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
indent(root)
buffer = BytesIO()
xml_tree_global.write(buffer, encoding='utf-8', xml_declaration=True)
with open(self.filepath, 'wb') as f:
f.write(buffer.getvalue())
self.report({'INFO'}, f"Succeed export to {self.filepath}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to export XML: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ImportImageOperator(Operator):
bl_idname = "f1_material.import_image"
bl_label = "Import Image"
bl_description = "Add image to project"
filepath: StringProperty(subtype='FILE_PATH')
def execute(self, context):
try:
image = bpy.data.images.load(self.filepath, check_existing=True)
self.report({'INFO'}, f"Image '{image.name}' imported successfully")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Failed to import image: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class DeleteImageOperator(Operator):
bl_idname = "f1_material.delete_image"
bl_label = "Delete Image"
bl_description = "Full delete image from project"
image_name: StringProperty()
def execute(self, context):
image = bpy.data.images.get(self.image_name)
if image:
bpy.data.images.remove(image)
self.report({'INFO'}, f"Image '{self.image_name}' deleted successfully")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Image '{self.image_name}' not found")
return {'CANCELLED'}
class UnlinkImageOperator(Operator):
bl_idname = "f1_material.unlink_image"
bl_label = "Unlink Image from Material"
bl_description = "Unlink image from material"
image_name: StringProperty()
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if material and material.use_nodes:
for node in material.node_tree.nodes:
if node.type == 'TEX_IMAGE' and node.image and node.image.name == self.image_name:
node.image = None
self.report({'INFO'}, f"Image '{self.image_name}' unlinked from material '{self.material_name}'")
return {'FINISHED'}
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found or not using nodes")
return {'CANCELLED'}
class AssignMaterialOperator(Operator):
bl_idname = "f1_material.assign_material"
bl_label = "Assign Material"
material_name: StringProperty()
def execute(self, context):
material = bpy.data.materials.get(self.material_name)
if not material:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'CANCELLED'}
selected_objects = [obj for obj in context.selected_objects if obj.type == 'MESH']
if not selected_objects:
self.report({'ERROR'}, "No selected mesh objects")
return {'CANCELLED'}
for obj in selected_objects:
bpy.context.view_layer.objects.active = obj
if len(obj.data.materials) == 0:
obj.data.materials.append(material)
mat_index = 0
else:
active_index = obj.active_material_index
if active_index >= 0:
obj.data.materials[active_index] = material
mat_index = active_index
else:
mat_index = obj.data.materials.find(material.name)
if mat_index == -1:
obj.data.materials.append(material)
mat_index = obj.data.materials.find(material.name)
if obj.mode == 'EDIT':
bpy.ops.object.mode_set(mode='EDIT')
bm = bmesh.from_edit_mesh(obj.data)
for face in bm.faces:
if face.select:
face.material_index = mat_index
bmesh.update_edit_mesh(obj.data)
self.report({'INFO'}, f"Material '{self.material_name}' assigned to selected faces of '{obj.name}'")
else:
obj.active_material_index = mat_index
for face in obj.data.polygons:
if face.material_index == active_index:
face.material_index = mat_index
self.report({'INFO'}, f"Material '{self.material_name}' set as active on '{obj.name}'")
return {'FINISHED'}
class HighlightMaterialOperator(Operator):
bl_idname = "f1_material.highlight_material"
bl_label = "Highlight Material"
material_name: StringProperty()
bl_description = "Highlights all objects in the scene using the selected material"
def execute(self, context):
if self.material_name in bpy.data.materials:
material = bpy.data.materials[self.material_name]
bpy.ops.object.select_all(action='DESELECT')
for obj in bpy.data.objects:
if obj.type == 'MESH' and obj.data is not None:
if self.material_name in [mat.name for mat in obj.data.materials if mat is not None]:
obj.select_set(True)
self.report({'INFO'}, f"Objects using '{self.material_name}' are highlighted")
else:
self.report({'ERROR'}, f"Material '{self.material_name}' not found!")
return {'FINISHED'}
class PickMaterialOperator(Operator):
bl_idname = "f1_material.pick_material"
bl_label = "Pick Material"
block_index: IntProperty()
def execute(self, context):
obj = context.object
if not obj or obj.type != 'MESH':
self.report({'ERROR'}, "Selected object is not a mesh")
return {'CANCELLED'}
active_material = None
if obj.mode == 'EDIT':
bm = bmesh.from_edit_mesh(obj.data)
bm.faces.ensure_lookup_table()
active_face = bm.select_history.active
if active_face:
active_material_index = active_face.material_index
if active_material_index < len(obj.data.materials):
active_material = obj.data.materials[active_material_index]
else:
self.report({'ERROR'}, "No active face selected in edit mode")
return {'CANCELLED'}
elif obj.data.materials:
active_material = obj.data.materials[0]
if not active_material:
self.report({'ERROR'}, "No material attached to selected object")
return {'CANCELLED'}
if self.block_index < len(context.scene.material_blocks):
block = context.scene.material_blocks[self.block_index]
block.material_id = active_material.name
self.report({'INFO'}, f"Material '{active_material.name}' picked in block {self.block_index}")
return {'FINISHED'}
class AddBlockOperator(Operator):
bl_idname = "f1_material.add_block"
bl_label = "Add Material Block"
def execute(self, context):
block = context.scene.material_blocks.add()
block.shader_group = "#env_diff.fx"
block.material_id = "new_material"
block.update_shader_group(context)
return {'FINISHED'}
class RemoveBlockOperator(Operator):
bl_idname = "f1_material.remove_block"
bl_label = "Remove Material Block"
def execute(self, context):
scene = context.scene
if scene.material_blocks:
scene.material_blocks.remove(len(scene.material_blocks) - 1)
return {'FINISHED'}
def register():
bpy.utils.register_class(TextureEntry)
bpy.utils.register_class(MaterialBlock)
bpy.types.Scene.material_blocks = CollectionProperty(type=MaterialBlock)
bpy.utils.register_class(F1MaterialMakerPanel)
bpy.utils.register_class(ImportOperator)
bpy.utils.register_class(ExportOperator)
bpy.utils.register_class(ImportImageOperator)
bpy.utils.register_class(DeleteImageOperator)
bpy.utils.register_class(UnlinkImageOperator)
bpy.utils.register_class(CopyTextureNameOperator)
bpy.utils.register_class(AssignMaterialOperator)
bpy.utils.register_class(HighlightMaterialOperator)
bpy.utils.register_class(PickMaterialOperator)
bpy.utils.register_class(AddBlockOperator)
bpy.utils.register_class(RemoveBlockOperator)
def unregister():
bpy.utils.unregister_class(TextureEntry)
bpy.utils.unregister_class(MaterialBlock)
del bpy.types.Scene.material_blocks
bpy.utils.unregister_class(F1MaterialMakerPanel)
bpy.utils.unregister_class(ImportOperator)
bpy.utils.unregister_class(ExportOperator)
bpy.utils.unregister_class(ImportImageOperator)
bpy.utils.unregister_class(DeleteImageOperator)
bpy.utils.unregister_class(UnlinkImageOperator)
bpy.utils.unregister_class(CopyTextureNameOperator)
bpy.utils.unregister_class(AssignMaterialOperator)
bpy.utils.unregister_class(HighlightMaterialOperator)
bpy.utils.unregister_class(PickMaterialOperator)
bpy.utils.unregister_class(AddBlockOperator)
bpy.utils.unregister_class(RemoveBlockOperator)
if __name__ == "__main__":
register()
В этом коде были внесены изменения, чтобы при копировании имени текстуры отрезалась его часть с расширением, а также чтобы превью текстур отображались в виде плиточек с возможностью выбора из списка плиточных миниатюр. Если что-то не будет работать как нужно, дайте знать, и я помогу внести дополнительные изменения.